code
stringlengths
1
13.8M
context("lowest_common") force_http1_1 <- list(http_version = 2L) test_that("lowest_common works with ncbi, passing in classifications and doing internally", { skip_on_cran() skip_on_travis() id <- c("9031", "9823", "9606", "9470") idc <- classification(id, db = 'ncbi', callopts = force_http1_1) aa <- lowest_common(id[2:4], db = "ncbi") bb <- lowest_common(id[2:4], db = "ncbi", low_rank = 'class') cc <- lowest_common(id[2:4], db = "ncbi", class_list = idc, low_rank = 'class') expect_is(aa, "data.frame") expect_is(bb, "data.frame") expect_is(cc, "data.frame") expect_named(aa, c('name', 'rank', 'id')) expect_named(cc, c('name', 'rank', 'id')) expect_identical(aa, bb) expect_identical(bb, cc) expect_equal(NROW(aa), 1) expect_lt( system.time(lowest_common(id[2:4], db = "ncbi", class_list = idc, low_rank = 'class'))[3], system.time(lowest_common(id[2:4], db = "ncbi", low_rank = 'class'))[3] ) }) test_that("lowest_common works with itis", { skip_on_cran() ids <- c("180722","180092","572890") idc <- classification(ids, db = 'itis') expect_identical( lowest_common(ids, db = "itis"), lowest_common(ids, db = "itis", class_list = idc) ) bb <- lowest_common(ids, db = "itis", low_rank = 'class') cc <- lowest_common(ids, db = "itis", class_list = idc, low_rank = 'class') expect_is(bb, "data.frame") expect_is(cc, "data.frame") expect_named(cc, c('name', 'rank', 'id')) expect_identical(bb, cc) expect_equal(NROW(bb), 1) })
pairwise.BMSC = function(mdl, contrast, covariate = NULL, who = "delta") { check_contrasts <- function( contr.names , contr.parts , contrast ){ M <- strsplit(contr.names , ":") out <- NULL len <- NULL i <- 1 for(m in M){ len <- c(len , length(m)) for(cp in contr.parts){ for(mm in m){ if(grepl(cp,mm)) out <- c(out , i) } } i <- i +1 } tab.out <- table( out ) return(as.numeric(names(which(len[unique(out)] == tab.out)))) } se <- function(object) { sd(object)/sqrt(length(object)) } if (mdl[[7]] == "normal") { d0 <- dnorm(0, 0, 10) } else if (mdl[[7]] == "cauchy") { d0 <- dcauchy(0, 0, sqrt(2)/2) } else if (mdl[[7]] == "student") { d0 <- LaplacesDemon::dst(0, 10, 3) } if (class(mdl)[2] != "BMSC") stop("Not a valid BMSC object.") if (!exists("contrast")) stop("Not a valid contrast") tmp.post <- tmp.data <- contr.names <- contr.column <- contr.parts <- contr.table <- tmp.marginal <- findRow <- sum_logspl <- bf_sd <- tmp.y <- NULL if(who == "delta"){ tmp.post <- rstan::extract(mdl[[2]], pars = "b_Delta") tmp.data <- mdl[[3]] contr.names <- colnames(mdl[[5]]$XF_Pts) contr.table <- mdl[[5]]$XF_Pts } else if(who == "control"){ tmp.post <- rstan::extract(mdl[[2]], pars = "b_Ctrl") tmp.data <- mdl[[4]] contr.names <- colnames(mdl[[5]]$XF_Ctrl) contr.table <- mdl[[5]]$XF_Ctrl } else if(who == "singlecase"){ delta <- rstan::extract(mdl[[2]], pars = "b_Delta") ctrl <- rstan::extract(mdl[[2]], pars = "b_Ctrl") tmp.post <- list(delta[[1]] + ctrl[[1]]) tmp.data <- mdl[[3]] contr.names <- colnames(mdl[[5]]$XF_Pts) contr.table <- mdl[[5]]$XF_Pts } else stop("Not a valid \"who\" value") if(sum(grepl(contrast,contr.names))==0) stop("Not a valid contrast") contr.parts <- unlist(strsplit(contrast,":")) contr.column <- which(grepl(contrast,contr.names)) contr.column <- c(contr.column, check_contrasts(contr.names[1:(contr.column-1)] , contr.parts , contrast)) contr.column <- c(contr.column, which(grepl("(Intercept)",contr.names))) contr.column <- contr.column[order(contr.column)] create.names <- matrix(nrow = nrow(tmp.data) , ncol = length(contr.parts)) ricontrasts <- matrix(nrow = nrow(tmp.data) , ncol = length(contr.parts)) for( i in 1:length(contr.parts) ){ cp <- contr.parts[i] create.names[ , i] <- as.character(tmp.data[,grepl(substr(cp , start = 1 , stop = (nchar(cp)-1) ), colnames(tmp.data) )]) ricontrasts[ , i] <- contr.table[,contr.column][,cp == colnames(contr.table[,contr.column])] } create.names <- as.data.frame( cbind( apply(create.names, 1, paste, collapse = " ") , ricontrasts ) ) create.names <- unique(create.names) marginal_distribution <- list() tmp.table <- unique(contr.table[,contr.column]) for(i in 1:nrow(create.names)){ findRow <- NULL for(j in 1:nrow(tmp.table)){ if(sum(tmp.table[j,colnames(tmp.table)%in%contr.parts] == create.names[i,2:(length(contr.parts)+1)])==length(contr.parts)) findRow <- j } marginal_distribution[[create.names[i,1]]] <- data.frame( y = colSums(t(tmp.post[[1]][,contr.column])*tmp.table[findRow,]), name = create.names[i,1]) } sum.unique <- list() for(marginal_name in marginal_distribution){ sum_logspl <- .suppresslogspline(marginal_name$y) bf_sd <- d0/.suppressdlogspline(0, sum_logspl) sum.unique[[marginal_name$name[1]]] <- as.data.frame(cbind(mean(marginal_name$y), se(marginal_name$y), sd(marginal_name$y), quantile(marginal_name$y, probs = 2.5/100), quantile(marginal_name$y, probs = 25/100), quantile(marginal_name$y, probs = 50/100), quantile(marginal_name$y, probs = 75/100), quantile(marginal_name$y, probs = 97.5/100), bf_sd)) colnames(sum.unique[[marginal_name$name[1]]]) <- c("mean", "se_mean", "sd", "2.5%", "25%", "50%", "75%", "97.5%","BF10 (not zero)") } sum.unique <- do.call("rbind" , sum.unique) row.names(sum.unique) <- create.names[,1] sum.contrast <- list() sum.names <- list() for(i in 1:(length(marginal_distribution)-1)){ for(j in (i+1):length(marginal_distribution)){ tmp.y <- marginal_distribution[[i]]$y - marginal_distribution[[j]]$y sum_logspl <- .suppresslogspline(tmp.y) bf_sd <- d0/.suppressdlogspline(0, sum_logspl) sum.contrast[[paste(i,j)]] <- as.data.frame(cbind(mean(tmp.y), se(tmp.y), sd(tmp.y), quantile(tmp.y, probs = 2.5/100), quantile(tmp.y, probs = 25/100), quantile(tmp.y, probs = 50/100), quantile(tmp.y, probs = 75/100), quantile(tmp.y, probs = 97.5/100), bf_sd)) colnames(sum.contrast[[paste(i,j)]]) <- c("mean", "se_mean", "sd", "2.5%", "25%", "50%", "75%", "97.5%","BF10") sum.names[[paste(i,j)]] <- paste(marginal_distribution[[i]]$name[1], marginal_distribution[[j]]$name[1], sep = " - ") } } sum.contrast <- do.call("rbind" , sum.contrast) row.names(sum.contrast) <- do.call("c" , sum.names) out <- list(sum.unique , sum.contrast , contrast , covariate , marginal_distribution , mdl[[7]]) class(out) <- append(class(out),"pairwise.BMSC") return(out) } print.pairwise.BMSC = function(x, ...) { if(is.null(x[[4]])){ cat("\nPairwise Bayesian Multilevel Single Case contrasts of coefficients divided by", x[[3]] , "\n\n") } else { cat("\nPairwise Bayesian Multilevel Single Case contrasts of", x[[4]] ,"covariate divided by", x[[3]] , "\n\n") } cat("\n\n Marginal distributions\n\n") print(x[[1]], ...) cat("\n") cat("\n\n Table of contrasts\n\n") print(x[[2]], ...) }
proj.gnm <- function (object, ...) { if (inherits(object, "gnm", TRUE) == 1) stop("proj is not implemented for gnm objects") else NextMethod }
evaluation <- function(test, measures){ method <- class(test$method) dependent <- test$dependent held_out_rows <- nrow(test$data$holdout) total_rows <- held_out_rows + nrow(test$data$train) data_transformation <- test$data_transform data_transformation <- ifelse(data_transformation=="identity", "None", data_transformation) test_attributes <- list("Method" = method, "Dependent variable" = dependent, "Rows held out" = held_out_rows, "Total rows in data" = total_rows, "Data transformation" = data_transformation) structure(class="evaluation", list(measures = measures, test_attributes = test_attributes, test = test)) } print.evaluation <- function(x, digits = max(3, getOption("digits")-4), ...){ test <- x$test measures <- x$measures test_attributes <- x$test_attributes test_class <- class(test) test_class_label <- paste0(capitalize_first(test_class), " Test Evaluation: ", test$name) cat(paste0(test_class_label, "\n\n")) cat("Test attributes:\n") held_out_percentage <- paste0(format(test_attributes$"Rows held out" / test_attributes$"Total rows in data" * 100, digits), "%") held_out <- paste(held_out_percentage, paste0("(", test_attributes$"Rows held out", " rows)")) test_attributes <- c(test_attributes[1:2], "Percentage held out" = held_out, test_attributes[4:5]) test_attribute_names <- paste(c(names(test_attributes), names(measures)), ":") test_attribute_names <- format(test_attribute_names, justify="right") test_attribute_names <- test_attribute_names[1:5] test_attribute_matrix <- cbind(test_attribute_names, format(test_attributes, digits)) print(remove_names(test_attribute_matrix), quote=FALSE) cat("\nPerformance measures & statistics:\n") measure_names <- paste(names(measures), ":") measure_names_labels <- format(measure_names, justify="right") measure_matrix <- cbind(measure_names_labels, format(measures, digits, justify="right") ) print(remove_names(measure_matrix), quote = FALSE) invisible(x) } summary.evaluation <- function(object, include_test_attributes=TRUE, ...){ out <- t( as.matrix( object$measures ) ) rownames(out) <- object$test$name if(include_test_attributes){ test_attributes <- t( as.matrix( object$test_attributes ) ) out <- cbind(test_attributes, out) } out }
treeheatr <- heat_tree
unit_trace_U_from_phi <- function(phi) { x <- unit_trace_x_from_phi(phi) L <- unit_trace_L_from_x(x) return(L %*% Adj(L)) } unit_trace_I_l <- function(l) { stopifnot(length(l)==1) if (is_quadratic(l)) { I_l <- c(0,pi/2) } else { I_l <- c(0,pi) } I_l } unit_trace_runif <- function(n, d, verbose=F) { N <- d*d-1 phi_res <- matrix(NA, nrow=N, ncol=n) U_res <- array(NA, dim=c(d,d,n)) for (j in 1:n) { if (verbose) print(j) tmp <- unit_trace_runif_single(d) phi_res[,j] <- tmp$phi U_res[,,j] <- tmp$U } list(phi=phi_res, U=U_res) } unit_trace_runif_single <- function(d) { N <- d*d-1 phi_res <- rep(NA, N) p <- unit_trace_p(d) q <- unit_trace_q(d) log_c <- unit_trace_log_c(p,q) log_d <- unit_trace_log_d(p,q) mu <- unit_trace_mu(p,q) sigma2 <- unit_trace_sigma2(p,q) log_nu <- unit_trace_nu(sigma2, log_c, log_d) for (l in 1:N) { accepted <- F while (!accepted) { sigma_l <- sqrt(sigma2[l]) phi_star <- rnorm(1, mu[l], sigma_l) alpha <- unit_trace_log_f_l(phi_star, p, q, log_c, l) - dnorm(phi_star, mu[l], sigma_l, log=T) - log_nu[l] accepted <- (log(runif(1,0,1)) < alpha) } phi_res[l] <- phi_star } U <- unit_trace_U_from_phi(phi_res) list(phi=phi_res, U=U) } unit_trace_mu <- function(p, q) { N <- length(p); stopifnot(length(q)==N); stopifnot(N>1) res <- rep(pi/2, N) i <- 1 while (i*i < N) { l <- i*i res[l] <- atan(sqrt(q[l]/p[l])) i <- i+1 } res } unit_trace_sigma2 <- function(p, q) { N <- length(p); stopifnot(length(q)==N); stopifnot(N>1) 1 / (sqrt(p) + sqrt(q))^2 } unit_trace_nu <- function(sigma2_vec, log_c_vec, log_d_vec) { log(2*pi*sigma2_vec) / 2 + log_c_vec - log_d_vec } unit_trace_log_c <- function(p, q) { N <- length(p); stopifnot(length(q)==N); stopifnot(N>1) res <- rep(NA, N) i <- 1 for (l in 1:N) { if (l == i*i) { res[l] <- log(2) + lgamma( (p[l]+1)/2 + (q[l]+1)/2 ) - lgamma( (p[l]+1)/2 ) - lgamma( (q[l]+1)/2 ) i <- i+1 } else { res[l] <- -log(pi)/2 + lgamma( (q[l]+1)/2 + 1/2 ) - lgamma( (q[l]+1)/2 ) } } res } unit_trace_log_d <- function(p, q) { N <- length(p); stopifnot(length(q)==N && N > 1) res <- rep(0,N) i <- 1 while (i*i < N) { l <- i*i res[l] <- p[l]/2 * log(1+q[l]/p[l]) + q[l]/2 * log(1+p[l]/q[l]) i <- i + 1 } res } is_quadratic <- function(l, thresh=1e-15) { sl <- sqrt(l) sl-as.integer(sl) < thresh } unit_trace_log_f_l <- function(phi, p, q, log_c, l) { N <- length(p); stopifnot(length(q) == N && length(log_c) == N && N > 1) stopifnot(l >= 1 && l <= N) I_l <- unit_trace_I_l(l) if (phi <= I_l[1] || phi >= I_l[2]) { lf_l <- -Inf } else { lf_l <- log_c[l] if (p[l] != 0) { lf_l <- lf_l + p[l] * log(cos(phi)) } if (q[l] != 0) { lf_l <- lf_l + q[l] * log(sin(phi)) } } lf_l }
zibellreg<- function(formula, data, approach = c("mle", "bayes"), hessian = TRUE, hyperpars = list(mu_psi=0, sigma_psi=10, mu_beta=0, sigma_beta=10), ...){ approach <- match.arg(approach) formula <- Formula::Formula(formula) mf <- stats::model.frame(formula=formula, data=data) Terms <- stats::terms(mf) Z <- stats::model.matrix(formula, data = mf, rhs = 1) X <- stats::model.matrix(formula, data = mf, rhs = 2) Xlabels <- colnames(X) Zlabels <- colnames(Z) y <- stats::model.response(mf) n <- nrow(X) p <- ncol(X) q <- ncol(Z) if(p>1){ if(match("(Intercept)", Xlabels)==1){ X_std <- scale(X[,-1]) x_mean <- array(c(0, attr(X_std, "scaled:center"))) x_sd <- array(c(1, attr(X_std, "scaled:scale"))) X_std <- cbind(1, X_std) Delta_x <- diag(1/x_sd) Delta_x[1,] <- Delta_x[1,] - x_mean/x_sd }else{ X_std <- scale(X) x_mean <- array(attr(X_std, "scaled:center")) x_sd <- array(attr(X_std, "scaled:scale")) Delta_x <- diag(1/x_sd) } }else{ X_std <- X x_mean <- array(0) x_sd <- array(1) } if(q>1){ if(match("(Intercept)", Zlabels)==1){ Z_std <- scale(Z[,-1]) z_mean <- array(c(0, attr(Z_std, "scaled:center"))) z_sd <- array(c(1, attr(Z_std, "scaled:scale"))) Z_std <- cbind(1, Z_std) Delta_z <- diag(1/z_sd) Delta_z[1,] <- Delta_z[1,] - z_mean/z_sd }else{ Z_std <- scale(Z) z_mean <- array(attr(Z_std, "scaled:center")) z_sd <- array(attr(Z_std, "scaled:scale")) Delta_z <- diag(1/z_sd) } }else{ Z_std <- Z z_mean <- array(0) z_sd <- array(1) } stan_data <- list(y=y, X=X_std, Z=Z_std, n=n, p=p, q=q, x_mean=x_mean, x_sd=x_sd, z_mean=z_mean, z_sd=z_sd, mu_beta = hyperpars$mu_beta, sigma_beta=hyperpars$sigma_beta, mu_psi = hyperpars$mu_psi, sigma_psi=hyperpars$sigma_psi, approach=0) if(approach=="mle"){ fit <- rstan::optimizing(stanmodels$zibellreg, hessian=hessian, data=stan_data, verbose=FALSE, ...) if(hessian==TRUE){ fit$hessian <- - fit$hessian } fit$par <- fit$theta_tilde[-(1:(p+q))] AIC <- -2*fit$value + 2*(p+q) fit <- list(fit=fit, logLik = fit$value, AIC = AIC, Delta = magic::adiag(Delta_z, Delta_x)) }else{ stan_data$approach <- 1 fit <- rstan::sampling(stanmodels$zibellreg, data=stan_data, verbose=FALSE, ...) fit <- list(fit=fit) } fit$n <- n fit$p <- p fit$q <- q fit$call <- match.call() fit$formula <- stats::formula(Terms) fit$terms <- stats::terms.formula(formula) fit$labels1 <- Zlabels fit$labels2 <- Xlabels fit$approach <- approach class(fit) <- "zibellreg" return(fit) }
miniusloglik.ce.xt.norm <- function(dat, pars) { mu=pars[1] npars=length(pars) sigma=exp(pars[npars]) beta.vec=pars[2:(npars-1)] failure.dat=dat$failure.dat aux.inf=dat$aux.inf xt.obj=dat$xt.obj wts.mat=aux.inf$wts.mat npts.vec=aux.inf$npts.vec x.val=xt.obj$x.val npts=xt.obj$npts n=xt.obj$n para.vec=kronecker(beta.vec,rep(1,npts)) para.mat=kronecker(t(para.vec),rep(1,n)) beta.xt.mat=para.mat*x.val tmp.mat=kronecker(rep(1,npars-2),diag(npts)) sum.beta.xt.mat=beta.xt.mat%*%tmp.mat sum.beta.xt.mat=exp(sum.beta.xt.mat) int.g.beta.xt=rowSums(wts.mat*sum.beta.xt.mat) g.beta.xt=as.vector(sum.beta.xt.mat)[1:n+n*(npts.vec-1)] delta=failure.dat[,"delta"] zz=(log(int.g.beta.xt)-mu)/sigma ff=dnorm(zz)/(int.g.beta.xt*sigma) FF=pnorm(zz) ll=delta*log(g.beta.xt*ff)+(1-delta)*log(1-FF) res=(-1)*sum(ll) return(res) }
library(OpenMx) library(rpf) set.seed(1) m2.data <- suppressWarnings(try(read.table("models/nightly/data/ms-data.csv"), silent=TRUE)) if (is(m2.data, "try-error")) m2.data <- read.table("data/ms-data.csv") m2.data[m2.data==-9] <- NA m2.data <- m2.data + 1 gpcm <- function(outcomes) { rpf.nrm(outcomes, T.c=lower.tri(diag(outcomes-1),TRUE) * -1) } m2.spec <- list() m2.spec[1:22] <- list(gpcm(5)) m2.spec[2] <- list(gpcm(4)) m2.spec[5] <- list(gpcm(3)) m2.spec[6] <- list(gpcm(4)) m2.spec[13:14] <- list(gpcm(4)) m2.numItems <- length(m2.spec) for (c in 1:m2.numItems) { m2.data[[c]] <- mxFactor(m2.data[[c]], levels=1:m2.spec[[c]]$outcomes) } m2.maxParam <-max(sapply(m2.spec, rpf.numParam)) ip.mat <- mxMatrix(name="item", nrow=m2.maxParam, ncol=m2.numItems, values=c(1, 1, rep(0, m2.maxParam-2)), free=FALSE) colnames(ip.mat) <- colnames(m2.data) rownames(ip.mat) <- c('f1', rep('n', nrow(ip.mat)-1)) ip.mat$labels[1,] <- 'a1' ip.mat$free[1,] <- TRUE rstart <- lapply(m2.spec, rpf.rparam, version=1) for (ix in 1:m2.numItems) { thr <- m2.spec[[ix]]$outcomes - 1 ip.mat$free[(2+thr):(1+2*thr), ix] <- TRUE ip.mat$values[ip.mat$free[,ix],ix] <- rstart[[ix]][ip.mat$free[,ix]] } ip.mat$values[!is.na(ip.mat$labels) & ip.mat$labels == 'a1'] <- sample(ip.mat$values[!is.na(ip.mat$labels) & ip.mat$labels == 'a1'], 1) fmfit <- structure(c(0.941583, 1, 0, 0, 0, -0.676556, 0.758794, -0.802595, 1.28891, 0.941583, 1, 0, 0, -0.182632, 0.897435, 1.30626, NA, NA, 0.941583, 1, 0, 0, 0, 0.177835, -1.82185, 0.005832, -0.81109, 0.941583, 1, 0, 0, 0, -1.15962, -1.229, 0.032677, 0.4922, 0.941583, 1, 0, 0.457533, 0.324595, NA, NA, NA, NA, 0.941583, 1, 0, 0, -2.69186, -1.04012, 1.61232, NA, NA, 0.941583, 1, 0, 0, 0, -1.38231, 0.034368, -1.214, -0.648291, 0.941583, 1, 0, 0, 0, -1.85655, -1.17135, -0.262079, -0.531158, 0.941583, 1, 0, 0, 0, -1.29475, -0.376539, 0.02024, 0.135187, 0.941583, 1, 0, 0, 0, -1.38279, 0.524151, -0.508742, 0.633671, 0.941583, 1, 0, 0, 0, -0.979595, -0.048528, 0.659669, 0.544857, 0.941583, 1, 0, 0, 0, -2.09039, -1.45472, -0.472137, -0.666386, 0.941583, 1, 0, 0, 0.174682, 0.645437, 0.907132, NA, NA, 0.941583, 1, 0, 0, -0.842216, 0.490717, 1.28034, NA, NA, 0.941583, 1, 0, 0, 0, -0.913355, -0.319602, -0.310164, -0.15536, 0.941583, 1, 0, 0, 0, 0.567085, -1.56762, 0.884553, 0.122113, 0.941583, 1, 0, 0, 0, -0.152985, -0.341317, -0.183837, 1.17952, 0.941583, 1, 0, 0, 0, 0.168869, -0.490354, 0.373892, 1.29714, 0.941583, 1, 0, 0, 0, -0.827385, 0.626197, -1.52994, 0.494209, 0.941583, 1, 0, 0, 0, 0.511263, -0.750358, 1.01852, 0.840026, 0.941583, 1, 0, 0, 0, 0.968905, -0.009671, 1.52297, 1.69255, 0.941583, 1, 0, 0, 0, 1.89582, 0.051828, 2.25758, 1.52469), .Dim = c(9L, 22L), .Dimnames = list(NULL, c("i1", "i2", "i3", "i4", "i5", "i6", "i7", "i8", "i9", "i10", "i11", "i12", "i13", "i14", "i15", "i16", "i17", "i18", "i19", "i20", "i21", "i22"))) if (1) { cip.mat <- ip.mat cip.mat$values <- fmfit cM <- mxModel(model="ms", cip.mat, mxData(observed=m2.data, type="raw"), mxExpectationBA81(ItemSpec=m2.spec), mxFitFunctionML(), mxComputeOnce('fitfunction', 'fit')) cM <- mxRun(cM, silent=TRUE) omxCheckCloseEnough(cM$fitfunction$result, 50661.38, .01) } plan <- mxComputeSequence(steps=list( mxComputeEM('expectation', 'scores', mxComputeNewtonRaphson(freeSet='item', verbose=0L), information="mr1991", infoArgs=list(fitfunction='fitfunction')), mxComputeStandardError(), mxComputeHessianQuality())) m2 <- mxModel(model="m2", ip.mat, mxData(observed=m2.data, type="raw"), mxExpectationBA81(ItemSpec=m2.spec), mxFitFunctionML(), plan) m2 <- mxRun(m2, silent=TRUE) omxCheckCloseEnough(m2$output$minimum, 50661.377, .01) omxCheckCloseEnough(log(m2$output$conditionNumber), 6.57, .5) semse <- c(0.022, 0.095, 0.116, 0.116, 0.108, 0.176, 0.222, 0.305, 0.382, 0.359, 0.244, 0.215, 0.105, 0.082, 0.067, 0.07, 0.185, 0.215, 0.134, 0.061, 0.071, 0.25, 0.244, 0.231, 0.155, 0.328, 0.209, 0.177, 0.16, 0.211, 0.176, 0.182, 0.185, 0.187, 0.189, 0.201, 0.194, 0.174, 0.161, 0.2, 0.234, 0.409, 0.236, 0.179, 0.154, 0.064, 0.078, 0.092, 0.084, 0.074, 0.092, 0.584, 0.493, 0.441, 0.362, 0.1, 0.097, 0.079, 0.085, 0.113, 0.115, 0.102, 0.111, 0.079, 0.082, 0.076, 0.092, 0.541, 0.607, 0.554, 0.337, 0.081, 0.083, 0.083, 0.098, 0.072, 0.084, 0.103, 0.138, 0.084, 0.103, 0.141, 0.178) omxCheckCloseEnough(c(m2$output$standardErrors), semse, .01) emstat <- m2$compute$steps[[1]]$output omxCheckCloseEnough(emstat$EMcycles, 19, 3) omxCheckCloseEnough(emstat$totalMstep, 73, 11) omxCheckCloseEnough(emstat$semProbeCount / length(semse), 3, .1) omxCheckCloseEnough(m2$output$evaluations, 1086, 23) print(m2$output$backendTime) n <- apply(!is.na(m2.data), 2, sum) i1 <- mxModel(m2, mxComputeSequence(steps=list( mxComputeOnce('fitfunction', 'information', "meat"), mxComputeStandardError(), mxComputeHessianQuality()))) i1 <- mxRun(i1, silent=TRUE) omxCheckTrue(i1$output$infoDefinite) omxCheckCloseEnough(log(i1$output$conditionNumber), 7.3, .5) se <- c(0.019, 0.1, 0.123, 0.121, 0.119, 0.237, 0.246, 0.33, 0.417, 0.386, 0.281, 0.24, 0.108, 0.086, 0.072, 0.076, 0.221, 0.265, 0.138, 0.068, 0.085, 0.275, 0.267, 0.263, 0.196, 0.359, 0.237, 0.208, 0.203, 0.227, 0.191, 0.199, 0.225, 0.21, 0.215, 0.232, 0.235, 0.184, 0.179, 0.218, 0.254, 0.437, 0.26, 0.201, 0.194, 0.07, 0.083, 0.101, 0.089, 0.079, 0.096, 0.649, 0.549, 0.507, 0.421, 0.106, 0.102, 0.084, 0.093, 0.125, 0.124, 0.112, 0.127, 0.088, 0.089, 0.087, 0.109, 0.633, 0.704, 0.61, 0.415, 0.089, 0.089, 0.09, 0.112, 0.083, 0.092, 0.115, 0.17, 0.095, 0.11, 0.16, 0.192) omxCheckCloseEnough(c(i1$output$standardErrors), se, .001) if (0) { library(mirt) rdata <- sapply(m2.data, unclass)-1 pars <- mirt(rdata, 1, itemtype="Rasch", D=1, quadpts=49, pars='values') fit <- mirt(rdata, 1, itemtype="Rasch", D=1, quadpts=49, pars=pars, SE=TRUE, SE.type="crossprod") got <- coef(fit) }
"predict.bsamdpm" <- function(object, newp, newnp, alpha = 0.05, HPD = TRUE, ...) { smcmc <- object$mcmc$smcmc nbasis <- object$nbasis nint <- object$nint + 1 nfun <- object$nfun fmodel <- object$fmodel fpm <- object$fpm xmin <- object$xmin xmax <- object$xmax if (missing(newp) && missing(newnp)) { n <- object$n newp <- object$w newnp <- object$x fxobsg <- object$fit.draws$fxobs wbg <- object$fit.draws$wbeta yhatg <- object$fit.draws$yhat } else if (missing(newp) && !missing(newnp)) { newp <- object$w if (!is.matrix(newnp)) newnp <- as.matrix(newnp) n <- object$n if (n != nrow(newnp)) stop('The number of observations for both parametric and nonparametric components must be same.') wbg <- object$fit.draws$wbeta fxobsg <- .Fortran("predictbsam", as.matrix(newnp), as.double(xmin), as.double(xmax),as.integer(n), as.integer(nfun), as.integer(nbasis), as.integer(nint), as.integer(fmodel), as.double(fpm), as.integer(smcmc), as.array(object$mcmc.draws$theta), as.matrix(object$mcmc.draws$alpha), as.matrix(object$mcmc.draws$psi), as.matrix(object$mcmc.draws$omega), fxobsg = array(0, dim = c(n, nfun, smcmc)), NAOK = TRUE, PACKAGE = "bsamGP")$fxobsg yhatg <- wbg + t(apply(fxobsg, c(1,3), sum)) } else if (!missing(newp) && missing(newnp)) { newnp <- object$x if (!is.matrix(newp)) newp <- as.matrix(newp) newp <- cbind(1, newp) n <- object$n if (n != nrow(newp)) stop('The number of observations for both parametric and nonparametric components must be same.') fxobsg <- object$fit.draws$fxobs wbg <- object$mcmc.draws$beta %*% t(newp) yhatg <- wbg + t(apply(fxobsg, c(1,3), sum)) } else if (!missing(newp) && !missing(newnp)) { if (!is.matrix(newp)) newp <- as.matrix(newp) newp <- cbind(1, newp) if (!is.matrix(newnp)) newnp <- as.matrix(newnp) if (nrow(newp) != nrow(newnp)) stop('The number of observations for both parametric and nonparametric components must be same.') n <- nrow(newp) wbg <- object$mcmc.draws$beta %*% t(newp) fxobsg <- .Fortran("predictbsam", as.matrix(newnp), as.double(xmin), as.double(xmax),as.integer(n), as.integer(nfun), as.integer(nbasis), as.integer(nint), as.integer(fmodel), as.double(fpm), as.integer(smcmc), as.array(object$mcmc.draws$theta), as.matrix(object$mcmc.draws$alpha), as.matrix(object$mcmc.draws$psi), as.matrix(object$mcmc.draws$omega), fxobsg = array(0, dim = c(n, nfun, smcmc)), NAOK = TRUE, PACKAGE = "bsamGP")$fxobsg yhatg <- wbg + t(apply(fxobsg, c(1,3), sum)) } fxobs <- list() fxobsm <- apply(fxobsg, c(1, 2), mean) fxobs$mean <- fxobsm wbeta <- list() wbm <- apply(wbg, 2, mean) wbeta$mean <- wbm yhat <- list() ym <- apply(yhatg, 2, mean) yhat$mean <- ym if (HPD) { prob <- 1 - alpha fx.l <- fx.u <- matrix(0, n, nfun) for (i in 1:nfun) { fxobsg.o <- apply(fxobsg[, i, ], 1, sort) gap <- max(1, min(smcmc - 1, round(smcmc * prob))) init <- 1:(smcmc - gap) inds <- apply(fxobsg.o[init + gap, , drop = FALSE] - fxobsg.o[init, , drop = FALSE], 2, which.min) fx.l[, i] <- fxobsg.o[cbind(inds, 1:n)] fx.u[, i] <- fxobsg.o[cbind(inds + gap, 1:n)] } fxobs$lower <- fx.l fxobs$upper <- fx.u wbg.o <- apply(wbg, 2, sort) gap <- max(1, min(smcmc - 1, round(smcmc * prob))) init <- 1:(smcmc - gap) inds <- apply(wbg.o[init + gap, , drop = FALSE] - wbg.o[init, , drop = FALSE], 2, which.min) wbeta$lower <- wbg.o[cbind(inds, 1:n)] wbeta$upper <- wbg.o[cbind(inds + gap, 1:n)] yhatg.o <- apply(yhatg, 2, sort) gap <- max(1, min(smcmc - 1, round(smcmc * prob))) init <- 1:(smcmc - gap) inds <- apply(yhatg.o[init + gap, , drop = FALSE] - yhatg.o[init, , drop = FALSE], 2, which.min) yhat$lower <- yhatg.o[cbind(inds, 1:n)] yhat$upper <- yhatg.o[cbind(inds + gap, 1:n)] } else { fxobs$lower <- apply(fxobsg, c(1, 2), function(x) quantile(x, prob = alpha/2)) fxobs$upper <- apply(fxobsg, c(1, 2), function(x) quantile(x, prob = 1 - alpha/2)) wbeta$lower <- apply(wbg, 2, function(x) quantile(x, prob = alpha/2)) wbeta$upper <- apply(wbg, 2, function(x) quantile(x, prob = 1 - alpha/2)) yhat$lower <- apply(yhatg, 2, function(x) quantile(x, prob = alpha/2)) yhat$upper <- apply(yhatg, 2, function(x) quantile(x, prob = 1 - alpha/2)) } out <- list() out$n <- n out$nbasis <- nbasis out$newp <- newp out$newnp <- newnp out$alpha <- alpha out$HPD <- HPD out$yhat <- yhat out$wbeta <- wbeta out$fxobs <- fxobs if (object$model == 'bsaqdpm') out$p <- out$p class(out) <- "predict.bsamdpm" out }
context("FAST_IMPUTE") options(bigstatsr.check.parallel.blas = FALSE) test_that("fast imputation (xgboost) works", { skip_if_not_installed("xgboost") skip_if(is_cran) suppressMessages({ library(Matrix) library(foreach) library(magrittr) library(dplyr) }) bigsnp <- snp_attachExtdata() G <- bigsnp$genotypes expect_equal(G$code256, CODE_012) corr <- snp_cor(G) ind <- which(apply(corr, 2, function(x) max(x[x < 1])) > 0.6) indNA <- foreach(j = ind, .combine = "rbind") %do% { cbind(sample(nrow(G), 100), j) } tmpfile <- tempfile() bigsnp.copy <- snp_writeBed(bigsnp, bedfile = paste0(tmpfile, ".bed")) %>% snp_readBed(backingfile = tmpfile) %>% snp_attach() GNA <- bigsnp.copy$genotypes GNA[indNA] <- as.raw(3) counts <- big_counts(GNA) expect_equal(sum(counts[4, ]), nrow(indNA)) time <- system.time( infos <- snp_fastImpute(GNA, infos.chr = bigsnp$map$chromosome, p.train = 0.6) ) counts <- big_counts(GNA) expect_equal(sum(counts[4, ]), nrow(indNA)) GNA$code256 <- CODE_IMPUTE_PRED infosNA <- tibble( col = indNA[, 2], error = (GNA[indNA] != G[indNA]) ) %>% group_by(col) %>% summarise(nb_err = sum(error)) %>% mutate(nb_err_est = (infos[1, ] * infos[2, ] * nrow(G))[col]) pval <- anova(lm(nb_err ~ nb_err_est - 1, data = infosNA))$`Pr(>F)`[[1]] expect_lt(pval, 2e-16) fake <- snp_fake(100, 200) G <- fake$genotypes G[] <- sample(as.raw(0:3), size = length(G), replace = TRUE) CHR <- fake$map$chromosome expect_error(snp_fastImpute(G, 1), "Incompatibility between dimensions.", fixed = TRUE) expect_gt(mean(snp_fastImpute(G, CHR)[2, ]), 0.5) fake <- snp_fake(100, 200) G <- fake$genotypes G[] <- sample(as.raw(0:3), size = length(G), replace = TRUE) CHR <- sort(sample(1:3, ncol(G), TRUE)) G2 <- bigsnpr:::FBM_infos(G) ind <- 1:11 + 150 G2[1, ind] <- seq(0, 1, 0.1) G2 <- snp_fastImpute(G, CHR) G3 <- G$copy(CODE_IMPUTE_PRED) nbNA <- colSums(is.na(G3[])) expect_true(all(nbNA[ind] > 0)) expect_true(all(nbNA[-ind] == 0)) bigsnp <- snp_attachExtdata() G <- bigsnp$genotypes CHR <- bigsnp$map$chromosome elemNA <- sample(length(G), size = 20) G2 <- big_copy(G); G2[elemNA] <- as.raw(3) G3 <- big_copy(G); G3[elemNA] <- as.raw(3) expect_equal(snp_fastImpute(G2, CHR, seed = 2)[], snp_fastImpute(G3, CHR, seed = 2, ncores = 2)[]) expect_equal(G2[], G3[]) }) test_that("fast imputation (simple) works", { G <- snp_attachExtdata("example-missing.bed")$genotypes expect_error(snp_fastImputeSimple(G, "mean"), "should be one of") expect_warning(G1 <- snp_fastImputeSimple(G, "zero"), "deprecated") expect_equal(G[c(18, 72), 400], rep(NA_real_, 2)) expect_equal(G1[c(18, 72), 400], rep(0, 2)) G2 <- snp_fastImputeSimple(G, "mean0") expect_equal(G[c(18, 72), 400], rep(NA_real_, 2)) expect_equal(G2[c(18, 72), 400], rep(1, 2)) G3 <- snp_fastImputeSimple(G, "mean2") expect_equal(G3[c(18, 72), 400], rep(1.01, 2)) G4 <- snp_fastImputeSimple(G, "mode") expect_equal(G4[c(4, 12), 1], rep(0, 2)) expect_equal(G4[c(18, 72), 400], rep(1, 2)) imp_val <- replicate(500, { G5 <- snp_fastImputeSimple(G, "random") G5[c(18, 72), 400] }) p <- mean(G[, 400], na.rm = TRUE) / 2 prob <- c((1 - p)^2, 2 * p * (1 - p), p^2) expect_gt(stats::chisq.test(table(imp_val), p = prob)$p.value, 1e-4) expect_equal(snp_fastImputeSimple(G, method = "mean2")[], snp_fastImputeSimple(G, method = "mean2", ncores = 2)[]) })
library(checkargs) context("isNegativeIntegerOrNaOrNanVector") test_that("isNegativeIntegerOrNaOrNanVector works for all arguments", { expect_identical(isNegativeIntegerOrNaOrNanVector(NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrNanVector(TRUE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrNanVector(FALSE, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrNanVector(NA, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNegativeIntegerOrNaOrNanVector(0, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNegativeIntegerOrNaOrNanVector(-1, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNegativeIntegerOrNaOrNanVector(-0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrNanVector(0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrNanVector(1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrNanVector(NaN, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNegativeIntegerOrNaOrNanVector(-Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrNanVector(Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrNanVector("", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrNanVector("X", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrNanVector(c(TRUE, FALSE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrNanVector(c(FALSE, TRUE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrNanVector(c(NA, NA), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNegativeIntegerOrNaOrNanVector(c(0, 0), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNegativeIntegerOrNaOrNanVector(c(-1, -2), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNegativeIntegerOrNaOrNanVector(c(-0.1, -0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrNanVector(c(0.1, 0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrNanVector(c(1, 2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrNanVector(c(NaN, NaN), stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNegativeIntegerOrNaOrNanVector(c(-Inf, -Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrNanVector(c(Inf, Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrNanVector(c("", "X"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isNegativeIntegerOrNaOrNanVector(c("X", "Y"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_error(isNegativeIntegerOrNaOrNanVector(NULL, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrNanVector(TRUE, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrNanVector(FALSE, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isNegativeIntegerOrNaOrNanVector(NA, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNegativeIntegerOrNaOrNanVector(0, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNegativeIntegerOrNaOrNanVector(-1, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNegativeIntegerOrNaOrNanVector(-0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrNanVector(0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrNanVector(1, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isNegativeIntegerOrNaOrNanVector(NaN, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNegativeIntegerOrNaOrNanVector(-Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrNanVector(Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrNanVector("", stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrNanVector("X", stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrNanVector(c(TRUE, FALSE), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrNanVector(c(FALSE, TRUE), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isNegativeIntegerOrNaOrNanVector(c(NA, NA), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNegativeIntegerOrNaOrNanVector(c(0, 0), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isNegativeIntegerOrNaOrNanVector(c(-1, -2), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNegativeIntegerOrNaOrNanVector(c(-0.1, -0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrNanVector(c(0.1, 0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrNanVector(c(1, 2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_identical(isNegativeIntegerOrNaOrNanVector(c(NaN, NaN), stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isNegativeIntegerOrNaOrNanVector(c(-Inf, -Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrNanVector(c(Inf, Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrNanVector(c("", "X"), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isNegativeIntegerOrNaOrNanVector(c("X", "Y"), stopIfNot = TRUE, message = NULL, argumentName = NULL)) })
test_that( "optimize_design works for one-sample case", { set.seed(123) cal_tbl <- calibrate_thresholds( p_null = 0.1, p_alt = 0.3, n = c(5, 25), N = 25, pp_threshold = 0.9, ppp_threshold = 0.05, direction = "greater", delta = NULL, prior = c(0.5, 0.5), S = 200, nsim = 300 ) expect_error(optimize_design.calibrate_thresholds(3)) expect_error(optimize_design(cal_tbl, minimum_power = 1:2)) expect_error(optimize_design(cal_tbl, minimum_power = "a")) expect_error(optimize_design(cal_tbl, type1_range = 3)) expect_error(optimize_design(cal_tbl, type1_range = c("a", "b"))) expect_snapshot(lapply(optimize_design(cal_tbl), as.data.frame)) } ) test_that( "optimize_design works for two-sample case", { set.seed(123) cal_tbl <- calibrate_thresholds( p_null = c(0.1, 0.1), p_alt = c(0.1, 0.5), n = cbind(c(10, 25), c(10, 25)), N = c(25, 25), pp_threshold = 0.9, ppp_threshold = 0.2, direction = "greater", delta = 0, prior = c(0.5, 0.5), S = 200, nsim = 300 ) expect_snapshot(lapply(optimize_design(cal_tbl), as.data.frame)) } )
test_that("can establish local snapshotter for testing", { snapper <- local_snapshotter() snapper$start_file("snapshot-1", "test") expect_true(snapper$is_active()) expect_equal(snapper$file, "snapshot-1") expect_equal(snapper$test, "test") }) test_that("basic workflow", { path <- withr::local_tempdir() snapper <- local_snapshotter(path) snapper$start_file("snapshot-2") expect_message(expect_snapshot_output("x"), "Can't compare") snapper$start_file("snapshot-2", "test") expect_warning(expect_snapshot_output("x"), "Adding new") snapper$end_file() expect_true(file.exists(file.path(path, "snapshot-2.md"))) expect_false(file.exists(file.path(path, "snapshot-2.new.md"))) snapper$start_file("snapshot-2", "test") expect_success(expect_snapshot_output("x")) snapper$end_file() expect_true(file.exists(file.path(path, "snapshot-2.md"))) expect_false(file.exists(file.path(path, "snapshot-2.new.md"))) snapper$start_file("snapshot-2", "test") expect_failure(expect_snapshot_output("y")) snapper$end_file() expect_true(file.exists(file.path(path, "snapshot-2.md"))) expect_true(file.exists(file.path(path, "snapshot-2.new.md"))) }) test_that("only create new files for changed variants", { snapper <- local_snapshotter() snapper$start_file("variants", "test") expect_warning(expect_snapshot_output("x"), "Adding new") expect_warning(expect_snapshot_output("x", variant = "a"), "Adding new") expect_warning(expect_snapshot_output("x", variant = "b"), "Adding new") snapper$end_file() expect_setequal( snapper$snap_files(), c("variants.md", "a/variants.md", "b/variants.md") ) snapper$start_file("variants", "test") expect_failure(expect_snapshot_output("y")) expect_success(expect_snapshot_output("x", variant = "a")) expect_success(expect_snapshot_output("x", variant = "b")) snapper$end_file() expect_setequal( snapper$snap_files(), c("variants.md", "variants.new.md", "a/variants.md", "b/variants.md") ) unlink(file.path(snapper$snap_dir, "variants.new.md")) snapper$start_file("variants", "test") expect_success(expect_snapshot_output("x")) expect_success(expect_snapshot_output("x", variant = "a")) expect_failure(expect_snapshot_output("y", variant = "b")) snapper$end_file() expect_setequal( snapper$snap_files(), c("variants.md", "a/variants.md", "b/variants.md", "b/variants.new.md") ) }) test_that("only reverting change in variant deletes .new", { snapper <- local_snapshotter() snapper$start_file("v", "test") expect_warning(expect_snapshot_output("x", variant = "a"), "Adding new") expect_warning(expect_snapshot_output("x", variant = "b"), "Adding new") snapper$end_file() expect_setequal(snapper$snap_files(), c("a/v.md", "b/v.md")) snapper$start_file("v", "test") expect_failure(expect_snapshot_output("y", variant = "a")) snapper$end_file() expect_setequal(snapper$snap_files(), c("a/v.md", "b/v.md", "a/v.new.md")) snapper$start_file("v", "test") expect_success(expect_snapshot_output("x", variant = "a")) snapper$end_file() expect_setequal(snapper$snap_files(), c("a/v.md", "b/v.md")) }) test_that("removing tests removes snap file", { path <- withr::local_tempdir() snapper <- local_snapshotter(path) snapper$start_file("snapshot-3", "test") expect_warning(expect_snapshot_output("x"), "Adding new") snapper$end_file() expect_true(file.exists(file.path(path, "snapshot-3.md"))) snapper$start_file("snapshot-3", "test") snapper$end_file() expect_false(file.exists(file.path(path, "snapshot-3.md"))) }) test_that("errors if can't roundtrip", { snapper <- local_snapshotter() snapper$start_file("snapshot-4", "test") expect_error(expect_snapshot_value(NULL), "not symmetric") }) test_that("errors in test doesn't change snapshot", { snapper <- local_snapshotter() snapper$start_file("snapshot-5", "test") expect_warning(expect_snapshot_output("x"), "Adding new") snapper$end_file() snapper$start_file("snapshot-5", "test") snapper$add_result(NULL, NULL, as.expectation(simpleError("error"))) snapper$end_file() snapper$start_file("snapshot-5", "test") expect_warning(expect_snapshot_output("x"), NA) snapper$end_file() snapper$start_file("snapshot-5", "test") expect_snapshot_output("x") expect_warning( snapper$add_result(NULL, NULL, as.expectation(simpleError("error"))), NA ) snapper$end_file() }) test_that("skips and unexpected errors reset snapshots", { regenerate <- FALSE if (regenerate) { withr::local_envvar(c(TESTTHAT_REGENERATE_SNAPS = "true")) } catch_cnd( test_file( test_path("test-snapshot", "test-snapshot.R"), reporter = NULL ) ) path <- "test-snapshot/_snaps/snapshot.md" stopifnot(file.exists(path)) snaps <- snap_from_md(brio::read_lines(path)) titles <- c("errors reset snapshots", "skips reset snapshots") expect_true(all(titles %in% names(snaps))) }) test_that("`expect_error()` can fail inside `expect_snapshot()`", { out <- test_file( test_path("test-snapshot", "test-expect-condition.R"), reporter = NULL ) err <- out[[1]]$results[[1]] expect_match(err$message, "did not throw the expected error") })
trips <- function(thedata, treat, formu = ~ ., groups=unique(treat), nstrata=5, method = 'logistic', ...) { if(length(groups) != 3) stop('Sorry, exactly three groups are required.') if(nrow(thedata) != length(treat)) stop('length(treat) does not equal nrow(thedata)') treats <- data.frame(id=1:length(treat), treat=treat, model1=rep(as.logical(NA), length(treat)), model2=rep(as.logical(NA), length(treat)), model3=rep(as.logical(NA), length(treat)), ps1=rep(as.numeric(NA), length(treat)), ps2=rep(as.numeric(NA), length(treat)), ps3=rep(as.numeric(NA), length(treat)) ) treats[which(treats$treat == groups[1]), c('model1','model2')] <- FALSE treats[which(treats$treat == groups[2]), c('model1','model3')] <- TRUE treats[which(treats$treat == groups[3]), c('model2')] <- TRUE treats[which(treats$treat == groups[3]), c('model3')] <- FALSE rows1 <- which(!is.na(treats$model1)) rows2 <- which(!is.na(treats$model2)) rows3 <- which(!is.na(treats$model3)) if(method == 'logistic') { message('Using logistic regression to estimate propensity scores...') m1 <- glm(update(formu, treat ~ .), data=cbind(thedata[rows1,], treat=treats[rows1,]$model1), family='binomial', ...) treats[rows1,]$ps1 <- fitted(m1) m2 <- glm(update(formu, treat ~ .), data=cbind(thedata[rows2,], treat=treats[rows2,]$model2), family='binomial', ...) treats[rows2,]$ps2 <- fitted(m2) m3 <- glm(update(formu, treat ~ .), data=cbind(thedata[rows3,], treat=treats[rows3,]$model3), family='binomial', ...) treats[rows3,]$ps3 <- fitted(m3) } else if(method == 'randomForest') { message('Using random forests to estimate propensity scores...') m1 <- randomForest(update(formu, treat ~ .), data=cbind(thedata[rows1,], treat=factor(treats[rows1,]$model1)), ...) treats[rows1,]$ps1 <- predict(m1, type='prob')[,2] m2 <- randomForest(update(formu, treat ~ .), data=cbind(thedata[rows2,], treat=factor(treats[rows2,]$model2)), ...) treats[rows2,]$ps2 <- predict(m2, type='prob')[,2] m3 <- randomForest(update(formu, treat ~ .), data=cbind(thedata[rows3,], treat=factor(treats[rows3,]$model3)), ...) treats[rows3,]$ps3 <- predict(m3, type='prob')[,2] } else { stop(paste0('Unsupported method: ', method)) } breaks1 <- quantile(treats$ps1, probs=seq(0,1,1/nstrata), na.rm=TRUE) breaks2 <- quantile(treats$ps2, probs=seq(0,1,1/nstrata), na.rm=TRUE) breaks3 <- quantile(treats$ps3, probs=seq(0,1,1/nstrata), na.rm=TRUE) treats$strata1 <- cut(treats$ps1, breaks=breaks1, labels=1:nstrata, include.lowest=TRUE) treats$strata2 <- cut(treats$ps2, breaks=breaks2, labels=1:nstrata, include.lowest=TRUE) treats$strata3 <- cut(treats$ps3, breaks=breaks3, labels=1:nstrata, include.lowest=TRUE) class(treats) <- c('triangle.psa', 'data.frame') attr(treats, 'data') <- thedata attr(treats, 'nstrata') <- nstrata attr(treats, 'model1') <- m1 attr(treats, 'model2') <- m2 attr(treats, 'model3') <- m3 attr(treats, 'breaks1') <- breaks1 attr(treats, 'breaks2') <- breaks2 attr(treats, 'breaks3') <- breaks3 attr(treats, 'groups') <- groups return(treats) }
test_that("Wrong parameters in the Kummer 1F1 function", { expect_warning(is.nan(chf_1F1(2.5, -1, 2))) expect_warning(is.nan(chf_1F1(2.5, 3, 2))) })
utils::globalVariables(c("snp", "study", "str")) generate_spre_forestplot <- function(beta_in, se_in, study_names_in, variant_names_in, spres_in, spre_colour_palette = c("mono_colour", "black"), set_studyNOs_as_studyIDs = FALSE, set_study_field_width = "%02.0f", set_cex = 0.66, set_xlim, set_ylim, set_at, tau2_method = "DL", adjust_labels = 1, save_plot = FALSE, verbose_output = FALSE, ...) { if (missing(set_xlim)) { set_xlim <- NULL } if (missing(set_at)) { set_at <- NULL } if (missing(set_ylim)) { set_ylim <- NULL } beta <- base::as.numeric(beta_in) se <- base::as.numeric(se_in) study_names <- base::factor(study_names_in) variant_names <- base::factor(variant_names_in) usta <- base::as.numeric(spres_in) m <- base::data.frame(beta, se, variant_names, study_names, usta) if (verbose_output) { base::writeLines("\nShowing dataset structure\u003A \n"); utils::str(m) } if (verbose_output) { base::writeLines("\nShowing first six lines of dataset\u003A \n"); base::print(utils::head(m)) } m$study <- m$study_names base::levels(m$study) <- base::seq_along(base::levels(m$study)) nstudies <- base::nlevels(m$study_names) m$snp <- m$variant_names base::levels(m$snp) <- base::seq_along(base::levels(m$snp)) nsnps <- base::nlevels(m$variant_names) if (verbose_output) { base::writeLines("\n") base::print(base::paste("Summary\u003A This analysis is based on ", nsnps, " SNP(s) and ", nstudies, " studies")) base::print("***************** end of part 1\u003A assign snp and study numbers ****************") base::writeLines("") } m_sortby_betas <- dplyr::arrange(m, snp, beta) if (verbose_output) { base::writeLines("Showing first six lines of dataset sorted by snp then by beta\u003A \n"); base::print(utils::head(m_sortby_betas)) } list_snp_minidatasets <- base::split(m_sortby_betas, as.factor(m_sortby_betas$variant_names)) if (verbose_output) { base::writeLines("\nSplitting dataset by snp to obtain mini-datasets for each snp\u003A \n"); utils::str(list_snp_minidatasets) } compute_fe <- function(dframe_current_snp) { if (set_studyNOs_as_studyIDs) { metafor_res <- metafor::rma.uni(yi = dframe_current_snp[, "beta"], sei = dframe_current_snp[, "se"], weighted = TRUE, slab = paste(formatC(dframe_current_snp[, "usta"], digits = 2, format = "f", flag = " "), sprintf(set_study_field_width, dframe_current_snp[, "study"]), sep = " "), method = "FE") } else { metafor_res <- metafor::rma.uni(yi = dframe_current_snp[, "beta"], sei = dframe_current_snp[, "se"], weighted = TRUE, slab = paste(formatC(dframe_current_snp[, "usta"], digits = 2, format = "f", flag = " "), dframe_current_snp[, "study_names"], sep = " "), method = "FE") } output <- base::list(metafor_results_outlier_present = metafor_res, current_snp_name = unique(dframe_current_snp[, "variant_names"]), current_snp_no = unique(dframe_current_snp[, "snp"])) output } metafor_results_fe <- base::lapply(list_snp_minidatasets, compute_fe) if (verbose_output) { base::writeLines("\nFixed-effect meta-analysis results\u003A \n"); base::print(metafor_results_fe) } compute_re <- function(dframe_current_snp) { if (tau2_method == "DL") { metafor_res <- metafor::rma.uni(yi = dframe_current_snp[, "beta"], sei = dframe_current_snp[, "se"], weighted = TRUE, knha = TRUE, slab = sprintf("%02.0f", dframe_current_snp[, "study"]), method = tau2_method) } else { metafor_res <- metafor::rma.uni(yi = dframe_current_snp[, "beta"], sei = dframe_current_snp[, "se"], weighted = TRUE, knha = TRUE, slab = sprintf("%02.0f", dframe_current_snp[, "study"]), method = tau2_method, control=list(stepadj=0.5, maxiter=10000)) } output <- base::list(metafor_results_outlier_present = metafor_res, current_snp_name = unique(dframe_current_snp[, "variant_names"]), current_snp_no = unique(dframe_current_snp[, "snp"])) output } metafor_results_re <- base::lapply(list_snp_minidatasets, compute_re) if (verbose_output) { base::writeLines("\nRandom-effects meta-analysis results\u003A \n"); base::print(metafor_results_re) } if (verbose_output) base::print("***************** end of part 2: Conduct fixed and random-effects meta-analyses ****************") generate_forestplot_outlier_present <- function(item_no) { if (verbose_output) { base::writeLines("\nDisplaying dataset structure for current snp\u003A \n"); utils::str(list_snp_minidatasets[[item_no]]) } basic_forestplot_params <- metafor::forest(metafor_results_fe[[item_no]]$metafor_results_outlier_present) grDevices::dev.off() if(is.null(set_xlim)) { set_xlim <- basic_forestplot_params$xlim } if(is.null(set_at)) { set_at <- basic_forestplot_params$at } set_ilab.xpos <- set_xlim[1] - (0.36 * set_xlim[1]) if(is.null(set_ylim)) { set_ylim <- basic_forestplot_params$ylim } if (verbose_output) { base::writeLines("Forestplot params\u003A \n"); base::print("set_ylim\u003A "); base::print(set_ylim) base::print("set_xlim\u003A "); base::print(set_xlim) base::print("set_at\u003A "); base::print(set_at) base::print("rows\u003A "); base::print(basic_forestplot_params$rows) } opar <- graphics::par(no.readonly =TRUE) base::on.exit(graphics::par(opar)) op <- graphics::par(cex=set_cex, mar=c(4,4,1,2)) forestplot_name_oulier_present <- base::paste0("forestplot_fixed_effect_sortedby_betas_variant_name_", (metafor_results_fe[[item_no]])$current_snp_name, "_snp_no_", (metafor_results_fe[[item_no]])$current_snp_no, ".tif") if (save_plot) { grDevices::tiff(forestplot_name_oulier_present, width = 17.35, height = 23.35, units = "cm", res = 600, compression = "lzw", pointsize = 14) } metafor::forest(metafor_results_fe[[item_no]]$metafor_results_outlier_present, xlim=set_xlim, at=set_at, cex=0.64, xlab = "log odds ratios", addfit=TRUE, mlab = "Summary effect") graphics::text(set_xlim[2], set_ylim[2] - adjust_labels, "Effect-size [95% CI]", pos=2, cex=set_cex) graphics::text(0.0, set_ylim[2] - adjust_labels, (metafor_results_fe[[item_no]])$current_snp_name, cex=set_cex) graphics::text(set_xlim[1], set_ylim[2] - adjust_labels, "SPRE Study", pos=4, cex=set_cex) plotrix::ablineclip(v = (metafor_results_fe[[item_no]]$metafor_results_outlier_present)$b[1], y1 = -1, y2 = set_ylim[2] - 2, lty="twodash", col = "grey0") wi <- 1/base::sqrt((metafor_results_fe[[item_no]]$metafor_results_outlier_present)$vi) psize <- wi/base::sum(wi) psize <- (psize - base::min(psize)) / (base::max(psize) - base::min(psize)) psize <- (psize * 1.0) + 0.5 df_usta_color <- base::data.frame("usta" = list_snp_minidatasets[[item_no]][, "usta"]) if (spre_colour_palette[1] == "mono_colour") { df_usta_color$color <- spre_colour_palette[2] } else if (spre_colour_palette[1] == "dual_colour") { df_usta_color$color <- spre_colour_palette[2] df_usta_color[, "color"][df_usta_color$usta < 0] <- spre_colour_palette[3] } else if (spre_colour_palette[1] == "multi_colour") { colorspace_hcl_hsv_palettes <- c("rainbow_hcl", "diverge_hcl", "terrain_hcl", "sequential_hcl", "diverge_hsv") gr_devices_palettes <- c("rainbow", "cm.colors", "topo.colors", "terrain.colors", "heat.colors") color_ramps_palettes <- c("matlab.like", "matlab.like2", "magenta2green", "cyan2yellow", "blue2yellow", "green2red", "blue2green", "blue2red") if (spre_colour_palette[2] == colorspace_hcl_hsv_palettes[1]) { df_usta_color$color <- colorspace::rainbow_hcl(nrow(df_usta_color)) } else if (spre_colour_palette[2] == colorspace_hcl_hsv_palettes[2]) { df_usta_color$color <- colorspace::diverge_hcl(nrow(df_usta_color)) } else if (spre_colour_palette[2] == colorspace_hcl_hsv_palettes[3]) { df_usta_color$color <- colorspace::terrain_hcl(nrow(df_usta_color)) } else if (spre_colour_palette[2] == colorspace_hcl_hsv_palettes[4]) { df_usta_color$color <- colorspace::sequential_hcl(nrow(df_usta_color)) } else if (spre_colour_palette[2] == colorspace_hcl_hsv_palettes[5]) { df_usta_color$color <- colorspace::diverge_hsv(nrow(df_usta_color)) } if (spre_colour_palette[2] == gr_devices_palettes[1]) { df_usta_color$color <- grDevices::rainbow(nrow(df_usta_color), start = 0, end = 5/6) } else if (spre_colour_palette[2] == gr_devices_palettes[2]) { df_usta_color$color <- grDevices::cm.colors(nrow(df_usta_color)) } else if (spre_colour_palette[2] == gr_devices_palettes[3]) { df_usta_color$color <- grDevices::topo.colors(nrow(df_usta_color)) } else if (spre_colour_palette[2] == gr_devices_palettes[4]) { df_usta_color$color <- grDevices::terrain.colors(nrow(df_usta_color)) } else if (spre_colour_palette[2] == gr_devices_palettes[5]) { df_usta_color$color <- grDevices::heat.colors(nrow(df_usta_color)) } if (spre_colour_palette[2] == color_ramps_palettes[1]) { df_usta_color$color <- colorRamps::matlab.like(nrow(df_usta_color)) } else if (spre_colour_palette[2] == color_ramps_palettes[2]) { df_usta_color$color <- colorRamps::matlab.like2(nrow(df_usta_color)) } else if (spre_colour_palette[2] == color_ramps_palettes[3]) { df_usta_color$color <- colorRamps::magenta2green(nrow(df_usta_color)) } else if (spre_colour_palette[2] == color_ramps_palettes[4]) { df_usta_color$color <- colorRamps::cyan2yellow(nrow(df_usta_color)) } else if (spre_colour_palette[2] == color_ramps_palettes[5]) { df_usta_color$color <- colorRamps::blue2yellow(nrow(df_usta_color)) } else if (spre_colour_palette[2] == color_ramps_palettes[6]) { df_usta_color$color <- colorRamps::green2red(nrow(df_usta_color)) } else if (spre_colour_palette[2] == color_ramps_palettes[7]) { df_usta_color$color <- colorRamps::blue2green(nrow(df_usta_color)) } else if (spre_colour_palette[2] == color_ramps_palettes[8]) { df_usta_color$color <- colorRamps::blue2red(nrow(df_usta_color)) } if (spre_colour_palette[2] == "color_brewer_palettes") { df_usta_color$color <- grDevices::colorRampPalette(RColorBrewer::brewer.pal(as.numeric(spre_colour_palette[3]),spre_colour_palette[4]))(nrow(df_usta_color)) } } graphics::points((metafor_results_fe[[item_no]]$metafor_results_outlier_present)$yi, length((metafor_results_fe[[item_no]]$metafor_results_outlier_present)$yi):1, pch=15, col=df_usta_color[, "color"], cex=psize) graphics::par(op) if (save_plot) grDevices::dev.off() } loci <- seq(unique(m$variant_names)) base::writeLines("\nGenerating forest plots\u003A \u002E\u002E\u002E \n") lapply(loci, generate_forestplot_outlier_present) base::writeLines("Done\u002E ") m_sortby_betas <- dplyr::rename(m_sortby_betas, spre = usta, study_numbers = study, variant_numbers = snp) if (verbose_output) base::print("***************** end of part 3: Generate forest plots ****************") base::list(number_variants = nsnps, number_studies = nstudies, fixed_effect_results = metafor_results_fe, random_effects_results = metafor_results_re, spre_forestplot_dataset = m_sortby_betas) }
library(analysisPipelines) knitr::opts_chunk$set( eval = FALSE )
`BOXarrows3D` <- function(x1,y1,z1,x2,y2,z2, aglyph=NULL, Rview=ROTX(0), col=grey(.5), border='black', len = .7, basethick=.05, headlen=.3,headlip=.02) { if(missing(len)) { len = .7} if(missing(basethick)) {basethick=.05 } if(missing(headlip)) { headlip=.02} if(missing(headlen)) { headlen=.3 } if(missing(col)) {col=grey(.5) } if(missing(border)) { border='black'} if(missing(Rview)) { Rview=ROTX(0)} if(missing(aglyph)) {aglyph=NULL } up = par("usr") ui = par("pin") alpha = 65 ratx = (up[2]-up[1])/ui[1] raty= (up[4]-up[3])/ui[2] if(length(col)<length(x1)) { col=rep(col,length=length(x1)) } if(is.null(aglyph)) aglyph = Z3Darrow(len = len , basethick =basethick , headlen =headlen , headlip=headlip ) myzee = matrix(c(0,0,1, 1), nrow=1, ncol=4) for(i in 1:length(x1)) { T = TRANmat(x1[i],y1[i],z1[i] ) thelen = sqrt((y2[i]-y1[i])^2+ (x2[i]-x1[i])^2+(z2[i]-z1[i] )^2) SC = diag(1,nrow = 4) SC[3,3 ] = thelen gamma = 180*atan2(y2[i]-y1[i], x2[i]-x1[i] )/pi beta = 180*atan2( sqrt( (x2[i]-x1[i])^2+(y2[i]-y1[i])^2), z2[i] - z1[i] )/pi gamma = RPMG::fmod(gamma, 360) beta = RPMG::fmod(beta, 360) R3 = ROTZ(gamma) R2 = ROTY(beta) R1 = ROTZ(alpha) M = SC %*% R1 %*% R2 %*% R3 %*% T %*% Rview M2 = R1 %*% R2 %*% R3 %*% Rview pglyph3D(aglyph$aglyph, anorms=aglyph$anorm , M=M, M2=M2, zee=myzee , col=col[i] ) } }
`print.summary.allPerms` <- function(x, ...) { dims <- dim(x) control <- attr(x, "control") observed <- attr(x, "observed") attributes(x) <- NULL dim(x) <- dims cat("\n") writeLines(strwrap("Complete enumeration of permutations\n", prefix = "\t")) print(control) cat("\nAll permutations:\n") writeLines(paste("Contains observed ordering?:", ifelse(observed, "Yes", "No"), "\n")) print(x) return(invisible(x)) }
expected <- eval(parse(text="FALSE")); test(id=0, code={ argv <- eval(parse(text="list(structure(3.14159265358979, .Tsp = c(1, 1, 1), class = \"ts\"))")); do.call(`is.call`, argv); }, o=expected);
`panel.ordi3d` <- function(x, y, z, aspect, ...) { dx <- diff(range(x)) dy <- diff(range(y)) dz <- diff(range(z)) aspect <- c(dy/dx, dz/dx) panel.cloud(x = x, y = y, z = z, aspect = aspect, ...) }
assetsSelect <- function(x, method = c("hclust", "kmeans"), control = NULL, ...) { method <- method[1] if (class(x) == "timeSeries") { x <- as.matrix(x) } fun <- paste(".", method, "Select", sep = "") FUN <- get(fun) ans <- FUN(x, control, ...) ans } .hclustSelect <- function(x, control = NULL, ...) { if (is.null(control)) control = c(measure = "euclidean", method = "complete") measure = control[1] method = control[2] ans = hclust(dist(t(x), method = measure), method = method, ...) class(ans) = c("list", "hclust") ans } .kmeansSelect <- function(x, control = NULL, ...) { if (is.null(control)) control = c(centers = 5, algorithm = "Hartigan-Wong") centers = as.integer(control[1]) algorithm = control[2] ans = kmeans(x = t(x), centers = centers, algorithm = algorithm, ...) class(ans) = c("list", "kmeans") ans }
plot.4thcorner <- function(x, stat = c("D", "D2", "G"), type = c("table", "biplot"), xax = 1, yax = 2, x.rlq = NULL, alpha = 0.05, col = c("lightgrey", "red", "deepskyblue", "purple"),...) { stat <- match.arg(stat) type <- match.arg(type) appel <- as.list(x$call) fctn <- appel[[1]] if(!inherits(x, "4thcorner") & !inherits(x, "4thcorner.rlq")) stop("x must be of class '4thcorner' or '4thcorner.rlq'") if(inherits(x, "4thcorner.rlq") & stat != "G") stop("stat should be 'G' for object of class '4thcorner.rlq' (created by the 'fourthcorner2' function)") if(type == "biplot" & stat == "G") stop("'biplot not available for the 'G' statistic") if((stat == "D2" | stat=="D")){ res <- data.frame(matrix(1, length(x$colnames.Q),length(x$colnames.R))) names(res) <- x$colnames.R row.names(res) <- x$colnames.Q if(stat == "D2") { xrand <- x$tabD2 } else { xrand <- x$tabD } for(i in 1:nrow(res)){ for(j in 1:ncol(res)){ idx.var <- ncol(res) * (i - 1) + j if(!is.na(xrand$adj.pvalue[idx.var])){ if(xrand$adj.pvalue[idx.var] < alpha){ res[i,j] <- ifelse(xrand$alter[idx.var]=="greater", 2, 3) if((x$indexR[x$assignR[j]]==1) != (x$indexQ[x$assignQ[i]]==1)){ if(stat == "D") res[i,j] <- 2 if(stat == "D2") res[i,j] <- ifelse(xrand$obs[idx.var] > 0, 2, 3) } else if((x$indexR[x$assignR[j]]==1) & (x$indexQ[x$assignQ[i]]==1)){ res[i,j] <- ifelse(xrand$obs[idx.var] > 0, 2, 3) } else if((x$indexR[x$assignR[j]]==2) & (x$indexQ[x$assignQ[i]]==2)){ res[i,j] <- ifelse(xrand$obs[idx.var] > xrand$expvar$Expectation[idx.var], 2, 3) } } } } } } else if(stat=="G"){ res <- data.frame(matrix(1, length(x$varnames.Q),length(x$varnames.R))) names(res) <- x$varnames.R row.names(res) <- x$varnames.Q xrand <- x$tabG for(i in 1:nrow(res)){ for(j in 1:ncol(res)){ idx.var <- ncol(res) * (i - 1) + j if(xrand$adj.pvalue[idx.var] < alpha){ res[i,j] <- ifelse(xrand$alter[idx.var]=="greater", 2, 3) if((x$indexR[j]==1) & (x$indexQ[i]==1)){ res[i,j] <- ifelse(xrand$obs[idx.var] > 0, 2, 3) } } } } } table4thcorner <- function (df, stat, assignR, assignQ, col) { x1 <- 1:ncol(df) y <- nrow(df):1 opar <- par(mai = par("mai"), srt = par("srt")) on.exit(par(opar)) table.prepare(x = x1, y = y, row.labels = row.names(df), col.labels = names(df), clabel.row = 1, clabel.col = 1, grid = FALSE, pos = "paint") xtot <- x1[col(as.matrix(df))] ytot <- y[row(as.matrix(df))] xdelta <- (max(x1) - min(x1))/(length(x1) - 1)/2 ydelta <- (max(y) - min(y))/(length(y) - 1)/2 z <- unlist(df) rect(xtot - xdelta, ytot - ydelta, xtot + xdelta, ytot + ydelta, col = col[1:3][z], border = "grey90") if((stat == "D") | (stat == "D2")){ idR <- which(diff(assignR)==1) idQ <- which(diff(assignQ)==1) if(length(idR) > 0) segments(sort(unique(xtot))[idR]+xdelta, max(ytot+ydelta), sort(unique(xtot))[idR]+xdelta, min(ytot-ydelta), lwd=2) if(length(idQ) > 0) segments(max(xtot+xdelta), sort(unique(ytot), decreasing = TRUE)[idQ+1]+ydelta, min(xtot-xdelta), sort(unique(ytot), decreasing = TRUE)[idQ+1]+ydelta, lwd=2) } rect(min(xtot) - xdelta, min(ytot) - ydelta, max(xtot) + xdelta, max(ytot) + ydelta, col = NULL) } biplot.rlq4thcorner <- function (res.4thcorner, obj.rlq, stat, alpha, xax, yax, clab.traits, clab.env, col) { opar <- par(mar = par("mar")) on.exit(par(opar)) coolig <- obj.rlq$li[, c(xax, yax)] coocol <- obj.rlq$c1[, c(xax, yax)] s.label(coolig, clabel = 0, cpoint = 0, xlim = 1.2 * range(coolig[,1])) born <- par("usr") k1 <- min(coocol[, 1])/born[1] k2 <- max(coocol[, 1])/born[2] k3 <- min(coocol[, 2])/born[3] k4 <- max(coocol[, 2])/born[4] k <- c(k1, k2, k3, k4) coocol <- 0.9 * coocol/max(k) idx.pos <- which(t(res.4thcorner)==2, arr.ind=TRUE) idx.neg <- which(t(res.4thcorner)==3, arr.ind=TRUE) idx.tot <- list(unique(c(idx.pos[,1],idx.neg[,1])), unique(c(idx.pos[,2],idx.neg[,2]))) par(mar = c(0.1, 0.1, 0.1, 0.1)) if(length(idx.tot[[1]]) > 0) { scatterutil.eti(coolig[-idx.tot[[1]],1], coolig[-idx.tot[[1]],2],label=row.names(coolig)[-idx.tot[[1]]], clabel = clab.env, boxes = FALSE, coul = rep(col[1], nrow(coolig) - length(idx.tot[[1]]))) scatterutil.eti(coocol[-idx.tot[[2]],1], coocol[-idx.tot[[2]],2],label=row.names(coocol)[-idx.tot[[2]]], clabel = clab.traits, boxes = FALSE, coul = rep(col[1], nrow(coocol) - length(idx.tot[[2]]))) } else { scatterutil.eti(coolig[,1], coolig[,2],label=row.names(coolig), clabel = clab.env, boxes = FALSE, coul = rep(col[1], nrow(coolig))) scatterutil.eti(coocol[,1], coocol[,2],label=row.names(coocol), clabel = clab.traits, boxes = FALSE, coul = rep(col[1], nrow(coocol))) } if(nrow(idx.pos) > 0) segments(coolig[idx.pos[,1],1],coolig[idx.pos[,1],2],coocol[idx.pos[,2],1],coocol[idx.pos[,2],2], lty = 1, lwd = 2, col = col[2]) if(nrow(idx.neg) > 0) segments(coolig[idx.neg[,1],1],coolig[idx.neg[,1],2],coocol[idx.neg[,2],1],coocol[idx.neg[,2],2], lty = 1, lwd = 2, col = col[3]) if(length(idx.tot[[1]]) > 0) { scatterutil.eti.circ(coolig[idx.tot[[1]],1], coolig[idx.tot[[1]],2], label=row.names(coolig)[idx.tot[[1]]], clabel = clab.env, boxes = FALSE) scatterutil.eti.circ(coocol[idx.tot[[2]],1], coocol[idx.tot[[2]],2],label=row.names(coocol)[idx.tot[[2]]], clabel = clab.traits, boxes = FALSE) points(coolig[idx.tot[[1]],], pch = 17) points(coocol[idx.tot[[2]],], pch = 19) } } biplot.axesrlq4thcorner <- function(res.4thcorner, coo, alpha, xax, yax, type.axes, col){ opar <- par(mar = par("mar")) on.exit(par(opar)) s.label(coo, clabel = 0, cpoint = 0) if(type.axes == "R.axes") res.4thcorner <- res.4thcorner[c(xax,yax),] if(type.axes == "Q.axes"){ res.4thcorner <- res.4thcorner[,c(xax,yax)] res.4thcorner <- t(res.4thcorner) } idx.xax <- which((res.4thcorner[1,] > 1) & (res.4thcorner[2,] == 1)) idx.yax <- which((res.4thcorner[1,] == 1) & (res.4thcorner[2,] > 1)) idx.both <- which((res.4thcorner[1,] > 1) & (res.4thcorner[2,] > 1)) idx.tot <- c(idx.xax, idx.yax, idx.both) par(mar = c(0.1, 0.1, 0.1, 0.1)) if(length(idx.tot) > 0) { scatterutil.eti(coo[-idx.tot,1], coo[-idx.tot,2],label=row.names(coo)[-idx.tot], clabel = 1, boxes = FALSE, coul = rep(col[1], nrow(coo) - length(idx.tot))) } else { scatterutil.eti(coo[,1], coo[,2],label=row.names(coo), clabel = 1, boxes = FALSE, coul = rep(col[1], nrow(coo))) } if(length(idx.xax) > 0) scatterutil.eti(coo[idx.xax,1], coo[idx.xax,2],label=row.names(coo)[idx.xax], clabel = 1, boxes = TRUE, coul = rep(col[2], length(idx.xax))) if(length(idx.yax) > 0) scatterutil.eti(coo[idx.yax,1], coo[idx.yax,2],label=row.names(coo)[idx.yax], clabel = 1, boxes = TRUE, coul = rep(col[3], length(idx.xax))) if(length(idx.both) > 0) scatterutil.eti(coo[idx.both,1], coo[idx.both,2],label=row.names(coo)[idx.both], clabel = 1, boxes = TRUE, coul = rep(col[4], length(idx.both))) } if(type=="table"){ table4thcorner(res, stat = stat, assignR = x$assignR, assignQ = x$assignQ, col = col) } else if(type=="biplot"){ if(fctn =="fourthcorner" | fctn =="fourthcorner2"){ if (!inherits(x.rlq, "rlq")) stop("'x.rlq' should be of class 'rlq'") biplot.rlq4thcorner(res.4thcorner = res, obj.rlq = x.rlq, stat = stat, alpha = alpha, xax = xax, yax = yax, clab.traits = 1, clab.env = 1, col = col) } else if(fctn=="fourthcorner.rlq"){ obj.rlq <- eval(appel$xtest, sys.frame(0)) type.axes <- eval(appel$typetest, sys.frame(0)) if(type.axes == "axes") stop("The option 'axes' is only implemented for pedagogic purposes and is not relevant to analyse data") if(type.axes == "R.axes") coo <- obj.rlq$li[, c(xax, yax)] if(type.axes == "Q.axes") coo <- obj.rlq$co[, c(xax, yax)] biplot.axesrlq4thcorner(res.4thcorner = res, coo = coo, alpha = alpha, xax = xax, yax = yax, type.axes = type.axes, col = col) } } }
geno.as.array <- function(genotypes,renumber=FALSE,miss=NULL,gtp.sep="/") { mknum<-function(genotypes, renumber=FALSE, gtp.sep="/") { alleles<- strsplit(genotypes, gtp.sep) gtp<-cbind(sapply(alleles, function(x) x[1], simplify=TRUE), sapply(alleles, function(x) x[2], simplify=TRUE)) if (renumber) { alleles<-unique(unlist(alleles)) gtp[,1]<-as.numeric(factor(gtp[,1],levels=alleles)) gtp[,2]<-as.numeric(factor(gtp[,2],levels=alleles)) } if (is.null(miss)) { gtp[is.na(genotypes),]<-NA }else{ gtp[is.na(genotypes),]<-miss } gtp } if (is.null(ncol(genotypes)) || ncol(genotypes)==1) { res<-mknum(genotypes, renumber=renumber) }else{ res<-data.frame(mknum(genotypes[,1], renumber=renumber)) for(i in 2:ncol(genotypes)) { res<-cbind(res,mknum(genotypes[,i], renumber=renumber)) } colnames(res)<-c(t(outer(names(genotypes),1:2,paste,sep="."))) } apply(res,2,as.character) } hap <- function(genotypes) { res<-geno.as.array(genotypes) nc<-ncol(res) hap1<-res[,seq(1,nc,2)] hap2<-res[,seq(2,nc,2)] loci<-colnames(genotypes) colnames(hap2)<-colnames(hap1)<-loci list(hap1=hap1, hap2=hap2, class="haplotype") } hapshuffle <- function(haplotypes, hfreq=NULL, ambiguous=NULL, verbose=FALSE, set) { if (is.null(hfreq)) hfreq<-hapfreq(haplotypes, set=set) if (is.null(ambiguous)) ambiguous<-hapambig(haplotypes) nloci<-ncol(haplotypes$hap1) nobs<-nrow(haplotypes$hap1) for(ind in ambiguous) { prop<-curr<-list(hap1=haplotypes$hap1[ind,], hap2=haplotypes$hap2[ind,]) swap<-sample(c(TRUE,FALSE),nloci,replace=TRUE) if (any(swap)) { tmp<-prop$hap1[swap] prop$hap1[swap]<-prop$hap2[swap] prop$hap2[swap]<-tmp } o1<-paste(curr$hap1,collapse=":") o2<-paste(curr$hap2,collapse=":") n1<-paste(prop$hap1,collapse=":") n2<-paste(prop$hap2,collapse=":") pos.o1<-match(o1,names(hfreq)) pos.o2<-match(o2,names(hfreq)) pos.n1<-match(n1,names(hfreq)) pos.n2<-match(n2,names(hfreq)) pn<-(hfreq[pos.n1]+0.5)*(hfreq[pos.n2]+0.5) po<-(hfreq[pos.o1]+0.5)*(hfreq[pos.o2]+0.5) qa<-pn/po if (verbose) cat("Person ",ind," ",qa," ",o1,"/",o2," -> ",n1,"/",n2,sep="") if (qa>runif(1)) { if (verbose) cat(" Accepted\n") haplotypes$hap1[ind,]<-prop$hap1 haplotypes$hap2[ind,]<-prop$hap2 hfreq[pos.n1]<-hfreq[pos.n1]+1 hfreq[pos.n2]<-hfreq[pos.n2]+1 hfreq[pos.o1]<-hfreq[pos.o1]-1 hfreq[pos.o2]<-hfreq[pos.o2]-1 }else if (verbose) { cat(" Unchanged\n") } } list(hfreq=hfreq, haplotypes=haplotypes, class="hapshuffle") } hapambig <- function(haplotypes) { which(apply(haplotypes$hap1!=haplotypes$hap2,1,sum)>1) } hapenum <- function(haplotypes) { dat<-rbind(haplotypes$hap1, haplotypes$hap2) dat<-dat[complete.cases(dat),] set<-unique(dat[,1]) for(i in 2:ncol(dat)) set<-outer(set,unique(dat[,i]),paste,sep=":") factor(set) } hapfreq <- function(haplotypes, set=NULL) { if (is.null(set)) set<-hapenum(haplotypes) hap1<-apply(haplotypes$hap1[complete.cases(haplotypes$hap1),],1,paste,collapse=":") hap2<-apply(haplotypes$hap2[complete.cases(haplotypes$hap2),],1,paste,collapse=":") dat<-c(hap1,hap2) table(factor(dat,levels=set)) } hapmcmc <- function(gtp, B=1000) { tot<-2*nrow(gtp) hap.dat<-hap(gtp) hap.set<-hapenum(hap.dat) hap.amb<-hapambig(hap.dat) hap.new<-list(hfreq=hapfreq(hap.dat, set=hap.set), haplotypes=hap.dat) res<-matrix(nrow=B, ncol=length(hap.set)) colnames(res)<-as.character(hap.set) rownames(res)<-1:B for(i in 1:B) { hap.new<-hapshuffle(hap.new$haplotypes,hfreq=hap.new$hfreq,ambiguous=hap.amb, set=hap.new$set) res[i,]<-hap.new$hfreq } apply(res,2,mean)/tot } mourant <- function(n) { tab<-matrix(c(91,32,5,147,78,17,85,75,7), nrow=3) rownames(tab)<-c("M/M","M/N","N/N") colnames(tab)<-c("S/S","S/s","s/s") dat<-as.data.frame.table(tab) p<-dat$Freq/sum(dat$Freq) dat[sample(1:nrow(dat),n,replace=TRUE,prob=p),1:2] }
NULL NULL load_esdm <- function(name, path = getwd()) { path <- paste0(path, "/", name) a <- try(read.csv(paste0(path, "/Tables/AlgoCorr.csv"), row.names = 1)) if (inherits(a, "try-error")) { cat("Algorithm correlation table empty ! \n") a <- data.frame() } b <- try(raster(paste0(path, "/Rasters/Binary.tif"))) if (inherits(b, "try-error")) { projection <- raster(paste0(path, "/Rasters/Probability.tif")) evaluation <- read.csv(paste0(path, "/Tables/ESDMeval.csv"), row.names = 1) b <- reclassify(projection, c(-Inf, evaluation$threshold, 0, evaluation$threshold, Inf, 1)) } esdm <- Ensemble.SDM(name = as.character(read.csv(paste0(path, "/Tables/Name.csv"))[1,2]), projection = raster(paste0(path, "/Rasters/Probability.tif")), binary = b, uncertainty = try(raster(paste0(path, "/Rasters/uncertainty.tif"))), evaluation = read.csv(paste0(path, "/Tables/ESDMeval.csv"), row.names = 1), algorithm.evaluation = read.csv(paste0(path, "/Tables/AlgoEval.csv"), row.names = 1), algorithm.correlation = a, data = read.csv(paste0(path, "/Tables/Data.csv"), row.names = 1), variable.importance = read.csv(paste0(path, "/Tables/VarImp.csv"), row.names = 1), parameters = read.csv(paste0(path, "/Tables/Parameters.csv"), row.names = 1, colClasses = "character")) return(esdm) } load_stack <- function(name = "Stack", path = getwd(), GUI = FALSE) { path <- paste0(path, "/", name) a <- try(read.csv(paste0(path, "/Stack/Tables/AlgoCorr.csv"), row.names = 1)) if (inherits(a, "try-error")) { cat("Algorithm correlation table empty ! \n") a <- data.frame() } stack <- Stacked.SDM(name = as.character(read.csv(paste0(path, "/Stack/Tables/Name.csv"))[1, 2]), diversity.map = raster(paste0(path, "/Stack/Rasters/Diversity.tif")), endemism.map = raster(paste0(path, "/Stack/Rasters/Endemism.tif")), uncertainty = raster(paste0(path, "/Stack/Rasters/uncertainty.tif")), evaluation = read.csv(paste0(path, "/Stack/Tables/StackEval.csv"), row.names = 1), variable.importance = read.csv(paste0(path, "/Stack/Tables/VarImp.csv"), row.names = 1), algorithm.correlation = a, algorithm.evaluation = read.csv(paste0(path, "/Stack/Tables/AlgoEval.csv"), row.names = 1), esdms = list(), parameters = read.csv(paste0(path, "/Stack/Tables/Parameters.csv"), row.names = 1, colClasses = "character")) esdms <- list.dirs(paste0(path, "/Species"), recursive = FALSE, full.names = FALSE) if (GUI) { incProgress(1/(length(esdms) + 1), detail = "stack main results") } for (i in seq_len(length(esdms))) { cat(esdms[i]) esdm <- load_esdm(esdms[i], path = paste0(path, "/Species")) stack@esdms[[esdm@name]] <- esdm if (GUI) { incProgress(1/(length(esdms) + 1), detail = esdm@name) } } return(stack) }
PsimNHPc <- function(i,lambdaiM, fixed.seed) { if (!is.null(fixed.seed)) fixed.seed<-fixed.seed+i aux<-simNHPc(lambda = lambdaiM[,i], fixed.seed = fixed.seed)$posNH return(aux) }
HampelWeightFunction <- function (x, q1, q2, q3) { i1 <- which(abs(x) <= q1) i2 <- which(abs(x) > q1 & abs(x) <= q2) i3 <- which(abs(x) > q2 & abs(x) <= q3) i4 <- which(abs(x) > q3) hampel_weights <- x hampel_weights[i1] <- 1 hampel_weights[i2] <- q1 / abs(x[i2]) hampel_weights[i3] <- (q1 * (q3 - abs(x[i3]))) / ((q3 - q2) * abs(x[i3])) hampel_weights[i4] <- 0 return(as.numeric(hampel_weights)) }
context("user_secrets") test_that("get_user_secret exists", { exists('get_user_secret') })
penalty.minfun = function(w, optvars, uservars){ m = optvars$wm pen = optvars$penalty rfun = optvars$rfun if(!is.null(dim(w)[2])){ f = apply(w, 2, FUN = function(y){ f = rfun(y, optvars, uservars) + ifelse(optvars$index[3]==1 || !is.null(optvars$ineqfun), pen * sum(pmax(parma.ineq.minfun(y, optvars, uservars), 0)^2), 0) + pen * sum(parma.eq.minfun(y, optvars, uservars)^2) if(!is.null(optvars$max.pos)) f = f + pen * pmax(0, (sum((abs(y[optvars$widx])>0.001)) - optvars$max.pos) )^2 return(f) }) } else{ f = rfun(w, optvars, uservars) + ifelse(optvars$index[3]==1 || !is.null(optvars$ineqfun), pen * sum(pmax(parma.ineq.minfun(w, optvars, uservars), 0)^2), 0) + pen * sum(parma.eq.minfun(w, optvars, uservars)^2) if(!is.null(optvars$max.pos)) f = f + pen * pmax(0, sum((abs(w[optvars$widx])>0.001)) - optvars$max.pos)^2 } return( f ) } penalty.optfun = function(w, optvars, uservars){ m = optvars$m pen = optvars$penalty rfun = optvars$rfun if(!is.null(dim(w)[2])){ f = apply(w, 2, FUN = function(y){ f = rfun(y, optvars, uservars) + pen * sum(pmax(parma.ineq.optfun(y, optvars, uservars), 0)^2) + pen * sum(parma.eq.optfun(y, optvars, uservars)^2) if(!is.null(optvars$max.pos)) f = f + pen * pmax(0, sum((abs(y[optvars$widx]/y[optvars$midx])>0.001)) - optvars$max.pos)^2 return(f) }) } else{ f = rfun(w, optvars, uservars) + pen * sum(pmax(parma.ineq.optfun(w, optvars, uservars), 0)^2) + pen * sum(parma.eq.optfun(w, optvars, uservars)^2) if(!is.null(optvars$max.pos)) f = f + pen * pmax(0, sum((abs(w[optvars$widx]/w[optvars$midx])>0.001)) - optvars$max.pos)^2 } return( f ) } func.lpmupm = function(w, optvars, uservars){ Data = optvars$Data lmoment = optvars$lmoment lthreshold = optvars$lthreshold port = Data %*% as.numeric(w[optvars$widx]) f = (mean(func.max.smooth( (w[optvars$midx]*lthreshold) - port)^lmoment))^(1/lmoment) return( f ) } func.ineq.lpmupm = function(w, optvars, uservars){ Data = optvars$Data umoment = optvars$umoment uthreshold = optvars$uthreshold N = optvars$N LB = optvars$LB UB = optvars$UB port = Data %*% as.numeric(w[optvars$widx]) A1 = 1 - (mean(func.max.smooth(port - uthreshold*w[optvars$midx])^umoment))^(1/umoment) A2 = ( c( w[optvars$midx]*LB - w[optvars$widx], w[optvars$widx] - w[optvars$midx]*UB) ) cons = c(A1, A2) if(!is.null(optvars$ineqfun)){ n = length(optvars$ineqfun) fnlist = list(w, optvars, uservars) names(fnlist) = c("w", "optvars", "uservars") for(i in 1:n){ cons = c(cons, do.call(optvars$ineqfun[[i]], args = fnlist)) } } return( cons ) } parma.eq.lpmupm = function(w, optvars, uservars){ if(optvars$index[6]==0) cons = eqfun.budget.opt(w, optvars, uservars) else cons = eqfun.leverage.opt(w, optvars, uservars) if(!is.null(optvars$eqfun)){ n = length(optvars$eqfun) fnlist = list(w, optvars, uservars) names(fnlist) = c("w", "optvars", "uservars") for(i in 1:n){ cons = c(cons, do.call(optvars$eqfun[[i]], args = fnlist)) } } return(cons) } penalty.lpmupm = function(w, optvars, uservars){ pen = optvars$penalty if(!is.null(dim(w)[2])){ f = apply(w, 2, FUN = function(y){ f = func.lpmupm(y, optvars, uservars) + pen * sum(pmax(func.ineq.lpmupm(y, optvars, uservars), 0)^2) + pen * sum(parma.eq.lpmupm(y, optvars, uservars)^2) if(!is.null(optvars$max.pos)) f = f + pen * pmax(0, sum((abs(y[optvars$widx]/y[optvars$midx])>0.001)) - optvars$max.pos)^2 return(f)}) } else{ f = func.lpmupm(w, optvars, uservars) + pen * sum(pmax(func.ineq.lpmupm(w, optvars, uservars), 0)^2) + pen * sum(parma.eq.lpmupm(w, optvars, uservars)^2) if(!is.null(optvars$max.pos)) f = f + pen * pmax(0, sum((abs(w[optvars$widx]/w[optvars$midx])>0.001)) - optvars$max.pos)^2 } return(f) } gnlpport = function(optvars, uservars, solver = "cmaes", control = list(), ...) { ctrl = .gnlp.ctrl(solver, control) risk = c("mad", "minimax", "cvar", "cdar", "ev", "lpm", "lpmupm")[optvars$index[4]] if(optvars$index[5] == 1){ func = penalty.minfun rfun = switch(risk, "cvar" = func.mincvar, "mad" = func.minmad, "lpm" = func.minlpm, "minimax" = func.minminmax, "ev" = func.minvar) optvars$rfun = rfun solution = switch(solver, "cmaes" = gnlp.mincmaes(func, optvars, uservars, ctrl), "crs" = gnlp.mincrs(func, optvars, uservars, ctrl)) } else{ if(risk == "lpmupm"){ func = penalty.lpmupm } else{ func = penalty.optfun rfun = switch(risk, "cvar" = func.optcvar, "mad" = func.optmad, "lpm" = func.optlpm, "minimax" = func.optminmax, "ev" = func.optvar) optvars$rfun = rfun } solution = switch(solver, "cmaes" = gnlp.fraccmaes(func, optvars, uservars, ctrl), "crs" = gnlp.fraccrs(func, optvars, uservars, ctrl)) } return( solution ) } .gnlp.ctrl = function(solver, control){ ans = switch(solver, "cmaes" = .cmaes.ctrl(control), "crs" = .crs.ctrl(control)) return(ans) } .cmaes.ctrl = function(control){ cmaes.control(options = control$options, CMA = control$CMA) } .crs.ctrl = function(control){ ctrl2 = list() ctrl2$algorithm = "NLOPT_GN_CRS2_LM" if( is.null(control$minf_max) ) ctrl2$minf_max = 0 else ctrl2$minf_max = control$minf_max if( is.null(control$ftol_rel) ) ctrl2$ftol_rel = NULL else ctrl2$ftol_rel = control$ftol_rel if( is.null(control$ftol_abs) ) ctrl2$ftol_abs = 1e-12 else ctrl2$ftol_abs = control$ftol_abs if( is.null(control$xtol_rel) ) ctrl2$xtol_rel = 1e-11 else ctrl2$xtol_rel = control$xtol_rel if( is.null(control$maxeval) ) ctrl2$maxeval = 100000 else ctrl2$maxeval = as.integer( control$maxeval ) if( is.null(control$maxtime) ) ctrl2$maxtime = 200 else ctrl2$maxtime = control$maxtime if( is.null(control$print_level) ) ctrl2$print_level = 0 else ctrl2$print_level = as.integer( control$print_level ) return(ctrl2) } gnlp.mincmaes = function(func, optvars, uservars, ctrl){ sol = list() ans = try(cmaes(pars = optvars$x0, fun = func, optvars = optvars, uservars = uservars, lower = optvars$LB, upper = optvars$UB, insigma = 0.1, ctrl = ctrl), silent = TRUE) if(inherits(ans, 'try-error')){ sol$status = 1 sol$weights = rep(NA, optvars$wm) sol$risk = NA sol$reward = NA if(optvars$index[4]==3) sol$VaR = NA if(optvars$index[4]==4) sol$DaR = NA } else { ansf = nlminb(start = ans$par, func, lower = optvars$LB, upper = optvars$UB, optvars = optvars, uservars = uservars, control = list(trace= ifelse(is.null(ctrl$trace), 0, ctrl$trace), eval.max = 2000, iter.max = 1000)) sol$status = ansf$convergence sol$weights = ansf$par[optvars$widx] sol$risk = ansf$objective sol$reward = sum(sol$weights * optvars$mu) if(optvars$index[4]==3) sol$VaR = ansf$par[optvars$vidx] if(optvars$index[4]==4) sol$DaR = ansf$par[optvars$vidx] } return(sol) } gnlp.mincrs = function(func, optvars, uservars, ctrl){ sol = list() ans = try(nloptr( optvars$x0, eval_f = func, lb = optvars$LB, ub = optvars$UB, opts = ctrl, optvars = optvars, uservars = uservars), silent = TRUE) if(inherits(ans, 'try-error')){ sol$status = 1 sol$weights = rep(NA, optvars$wm) sol$risk = NA sol$reward = NA if(optvars$index[4]==3) sol$VaR = NA if(optvars$index[4]==4) sol$DaR = NA } else { ansf = nlminb(start = ans$solution, func, lower = optvars$LB, upper = optvars$UB, optvars = optvars, uservars = uservars, control = list(trace= ifelse(is.null(ctrl$trace), 0, ctrl$trace), eval.max = 2000, iter.max = 1000)) sol$status = ansf$convergence sol$weights = ansf$par[optvars$widx] sol$risk = ansf$objective sol$reward = sum(sol$weights * optvars$mu) if(optvars$index[4]==3) sol$VaR = ansf$par[optvars$vidx] if(optvars$index[4]==4) sol$DaR = ansf$par[optvars$vidx] } return(sol) } gnlp.fraccmaes = function(func, optvars, uservars, ctrl){ sol = list() ans = try(cmaes(pars = optvars$x0, fun = func, optvars = optvars, uservars = uservars, lower = optvars$fLB, upper = optvars$fUB, insigma = 0.1, ctrl = ctrl), silent = TRUE) if(inherits(ans, 'try-error')){ sol$status = 1 sol$weights = rep(NA, optvars$wm) sol$risk = NA sol$reward = NA sol$multiplier = NA if(optvars$index[4]==3) sol$VaR = NA if(optvars$index[4]==4) sol$DaR = NA } else { ansf = nlminb(start = ans$par, func, lower = optvars$LB, upper = optvars$UB, optvars = optvars, uservars = uservars, control = list(trace= ifelse(is.null(ctrl$trace), 0, ctrl$trace), eval.max = 2000, iter.max = 1000)) sol$status = ansf$convergence sol$multiplier = ansf$par[optvars$midx] sol$weights = ansf$par[optvars$widx]/ansf$par[optvars$midx] sol$risk = ansf$objective/ansf$par[optvars$midx] sol$reward = sum(sol$weights * optvars$mu) if(optvars$index[4]==3) sol$VaR = ansf$par[optvars$vidx]/ansf$par[optvars$midx] if(optvars$index[4]==4) sol$DaR = ansf$par[optvars$vidx]/ansf$par[optvars$midx] } return(sol) } gnlp.fraccrs = function(func, optvars, uservars, ctrl){ ctrl2 = list() ctrl2$algorithm = "NLOPT_GN_CRS2_LM" sol = list() if( is.null(ctrl$minf_max) ) ctrl2$minf_max = 0 else ctrl2$minf_max = ctrl$minf_max if( is.null(ctrl$ftol_rel) ) ctrl2$ftol_rel = NULL else ctrl2$ftol_rel = ctrl$ftol_rel if( is.null(ctrl$ftol_abs) ) ctrl2$ftol_abs = 1e-12 else ctrl2$ftol_abs = ctrl$ftol_abs if( is.null(ctrl$xtol_rel) ) ctrl2$xtol_rel = 1e-11 else ctrl2$xtol_rel = ctrl$xtol_rel if( is.null(ctrl$maxeval) ) ctrl2$maxeval = 100000 else ctrl2$maxeval = as.integer( ctrl$maxeval ) if( is.null(ctrl$maxtime) ) ctrl2$maxtime = 200 else ctrl2$maxtime = ctrl$maxtime if( is.null(ctrl$print_level) ) ctrl2$print_level = 0 else ctrl2$print_level = as.integer( ctrl$print_level ) ans = try(nloptr( optvars$x0, eval_f = func, lb = optvars$fLB, ub = optvars$fUB, opts = ctrl, optvars = optvars, uservars = uservars), silent = TRUE) if(inherits(ans, 'try-error')){ sol$status = 1 sol$weights = rep(NA, optvars$wm) sol$risk = NA sol$reward = NA sol$multiplier = NA if(optvars$index[4]==3) sol$VaR = NA if(optvars$index[4]==4) sol$DaR = NA } else { ansf = nlminb(start = ans$solution, func, lower = optvars$LB, upper = optvars$UB, optvars = optvars, uservars = uservars, control = list(trace= ifelse(is.null(ctrl$trace), 0, ctrl$trace), eval.max = 2000, iter.max = 1000)) sol$status = ansf$convergence sol$multiplier = ansf$par[optvars$midx] sol$weights = ansf$par[optvars$widx]/ansf$par[optvars$midx] sol$risk = ansf$objective/ansf$par[optvars$midx] sol$reward = sum(sol$weights * optvars$mu) if(optvars$index[4]==3) sol$VaR = ansf$par[optvars$vidx]/ansf$par[optvars$midx] if(optvars$index[4]==4) sol$DaR = ansf$par[optvars$vidx]/ansf$par[optvars$midx] } return(sol) }
suppressPackageStartupMessages({ library(magrittr) library(mockery) library(purrr) library(fs) }) defer <- withr::defer expect_equivalent <- function(x, y) { expect_equal(x, y, ignore_attr = TRUE) } language_client <- function(working_dir = getwd(), diagnostics = FALSE, capabilities = NULL) { if (nzchar(Sys.getenv("R_LANGSVR_LOG"))) { script <- sprintf( "languageserver::run(debug = '%s')", normalizePath(Sys.getenv("R_LANGSVR_LOG"), "/", mustWork = FALSE)) } else { script <- "languageserver::run()" } client <- LanguageClient$new( file.path(R.home("bin"), "R"), c("--slave", "-e", script)) client$notification_handlers <- list( `textDocument/publishDiagnostics` = function(self, params) { uri <- params$uri diagnostics <- params$diagnostics self$diagnostics$set(uri, diagnostics) } ) client$start(working_dir = working_dir, capabilities = capabilities) client$catch_callback_error <- FALSE data <- client$fetch(blocking = TRUE) client$handle_raw(data) client %>% notify("initialized") client %>% notify( "workspace/didChangeConfiguration", list(settings = list(diagnostics = diagnostics))) withr::defer_parent({ if (Sys.getenv("R_LANGSVR_TEST_FAST", "YES") == "NO") { client %>% respond("shutdown", NULL, retry = FALSE) client$process$wait(10 * 1000) if (client$process$is_alive()) { cat("server did not shutdown peacefully\n") client$process$kill_tree() } } else { client$process$kill_tree() } }) client } notify <- function(client, method, params = NULL) { client$deliver(Notification$new(method, params)) invisible(client) } did_open <- function(client, path, uri = path_to_uri(path), text = NULL, languageId = NULL) { if (is.null(text)) { text <- stringi::stri_read_lines(path) } text <- paste0(text, collapse = "\n") if (is.null(languageId)) { languageId <- if (is_rmarkdown(uri)) "rmd" else "r" } notify( client, "textDocument/didOpen", list( textDocument = list( uri = uri, languageId = languageId, version = 1, text = text ) ) ) invisible(client) } did_save <- function(client, path, uri = path_to_uri(path), text = NULL) { includeText <- tryCatch( client$ServerCapabilities$textDocumentSync$save$includeText, error = function(e) FALSE ) if (includeText) { if (is.null(text)) { text <- stringi::stri_read_lines(path) } text <- paste0(text, collapse = "\n") params <- list(textDocument = list(uri = uri), text = text) } else { params <- list(textDocument = list(uri = uri)) } notify( client, "textDocument/didSave", params) Sys.sleep(0.5) invisible(client) } respond <- function(client, method, params, timeout, allow_error = FALSE, retry = TRUE, retry_when = function(result) length(result) == 0) { if (missing(timeout)) { if (Sys.getenv("R_COVR", "") == "true") { timeout <- 30 } else { timeout <- 10 } } storage <- new.env(parent = .GlobalEnv) cb <- function(self, result, error = NULL) { if (is.null(error)) { storage$done <- TRUE storage$result <- result } else if (allow_error) { storage$done <- TRUE storage$result <- error } } start_time <- Sys.time() remaining <- timeout client$deliver(client$request(method, params), callback = cb) if (method == "shutdown") { return(NULL) } while (!isTRUE(storage$done)) { if (remaining < 0) { fail("timeout when obtaining response") return(NULL) } data <- client$fetch(blocking = TRUE, timeout = remaining) if (!is.null(data)) client$handle_raw(data) remaining <- (start_time + timeout) - Sys.time() } result <- storage$result if (retry && retry_when(result)) { remaining <- (start_time + timeout) - Sys.time() if (remaining < 0) { fail("timeout when obtaining desired response") return(NULL) } Sys.sleep(0.2) return(Recall(client, method, params, remaining, allow_error, retry, retry_when)) } return(result) } respond_completion <- function(client, path, pos, ..., uri = path_to_uri(path)) { respond( client, "textDocument/completion", list( textDocument = list(uri = uri), position = list(line = pos[1], character = pos[2]) ), ... ) } respond_completion_item_resolve <- function(client, params, ...) { respond( client, "completionItem/resolve", params, ... ) } respond_signature <- function(client, path, pos, ..., uri = path_to_uri(path)) { respond( client, "textDocument/signatureHelp", list( textDocument = list(uri = uri), position = list(line = pos[1], character = pos[2]) ), ... ) } respond_hover <- function(client, path, pos, ..., uri = path_to_uri(path)) { respond( client, "textDocument/hover", list( textDocument = list(uri = uri), position = list(line = pos[1], character = pos[2]) ), ... ) } respond_definition <- function(client, path, pos, ..., uri = path_to_uri(path)) { respond( client, "textDocument/definition", list( textDocument = list(uri = uri), position = list(line = pos[1], character = pos[2]) ), ... ) } respond_references <- function(client, path, pos, ..., uri = path_to_uri(path)) { respond( client, "textDocument/references", list( textDocument = list(uri = uri), position = list(line = pos[1], character = pos[2]) ), ... ) } respond_rename <- function(client, path, pos, newName, ..., uri = path_to_uri(path)) { respond( client, "textDocument/rename", list( textDocument = list(uri = uri), position = list(line = pos[1], character = pos[2]), newName = newName ), ... ) } respond_prepare_rename <- function(client, path, pos, ..., uri = path_to_uri(path)) { respond( client, "textDocument/prepareRename", list( textDocument = list(uri = uri), position = list(line = pos[1], character = pos[2]) ), ... ) } respond_formatting <- function(client, path, ..., uri = path_to_uri(path)) { respond( client, "textDocument/formatting", list( textDocument = list(uri = uri), options = list(tabSize = 4, insertSpaces = TRUE) ), ... ) } respond_range_formatting <- function(client, path, start_pos, end_pos, ..., uri = path_to_uri(path)) { respond( client, "textDocument/rangeFormatting", list( textDocument = list(uri = uri), range = range( start = position(start_pos[1], start_pos[2]), end = position(end_pos[1], end_pos[2]) ), options = list(tabSize = 4, insertSpaces = TRUE) ), ... ) } respond_folding_range <- function(client, path, ..., uri = path_to_uri(path)) { respond( client, "textDocument/foldingRange", list( textDocument = list(uri = uri)), ... ) } respond_selection_range <- function(client, path, positions, ..., uri = path_to_uri(path)) { respond( client, "textDocument/selectionRange", list( textDocument = list(uri = uri), positions = positions), ... ) } respond_on_type_formatting <- function(client, path, pos, ch, ..., uri = path_to_uri(path)) { respond( client, "textDocument/onTypeFormatting", list( textDocument = list(uri = uri), position = position(pos[1], pos[2]), ch = ch, options = list(tabSize = 4, insertSpaces = TRUE) ), ... ) } respond_document_highlight <- function(client, path, pos, ..., uri = path_to_uri(path)) { respond( client, "textDocument/documentHighlight", list( textDocument = list(uri = uri), position = list(line = pos[1], character = pos[2]) ), ... ) } respond_document_symbol <- function(client, path, ..., uri = path_to_uri(path)) { respond( client, "textDocument/documentSymbol", list( textDocument = list(uri = uri) ), ... ) } respond_workspace_symbol <- function(client, query, ...) { respond( client, "workspace/symbol", list( query = query ), ... ) } respond_document_link <- function(client, path, ..., uri = path_to_uri(path)) { respond( client, "textDocument/documentLink", list( textDocument = list(uri = uri) ), ... ) } respond_document_link_resolve <- function(client, params, ...) { respond( client, "documentLink/resolve", params, ... ) } respond_document_color <- function(client, path, ..., uri = path_to_uri(path)) { respond( client, "textDocument/documentColor", list( textDocument = list(uri = uri) ), ... ) } respond_document_folding_range <- function(client, path, ..., uri = path_to_uri(path)) { respond( client, "textDocument/foldingRange", list( textDocument = list(uri = uri) ), ... ) } respond_prepare_call_hierarchy <- function(client, path, pos, ..., uri = path_to_uri(path)) { respond( client, "textDocument/prepareCallHierarchy", list( textDocument = list(uri = uri), position = list(line = pos[1], character = pos[2]) ), ... ) } respond_call_hierarchy_incoming_calls <- function(client, item, ...) { respond( client, "callHierarchy/incomingCalls", list( item = item ), ... ) } respond_call_hierarchy_outgoing_calls <- function(client, item, ...) { respond( client, "callHierarchy/outgoingCalls", list( item = item ), ... ) } respond_code_action <- function(client, path, start_pos, end_pos, ..., uri = path_to_uri(path)) { diagnostics <- client$diagnostics$get(uri) range <- range( start = position(start_pos[1], start_pos[2]), end = position(end_pos[1], end_pos[2]) ) respond( client, "textDocument/codeAction", list( textDocument = list(uri = uri), range = range, context = list( diagnostics = Filter(function(item) { range_overlap(item$range, range) }, diagnostics) ) ), ... ) } wait_for <- function(client, method, timeout = 30) { storage <- new.env(parent = .GlobalEnv) start_time <- Sys.time() remaining <- timeout original_handler <- client$notification_handlers[[method]] on.exit({ client$notification_handlers[[method]] <- original_handler }) client$notification_handlers[[method]] <- function(self, params) { storage$params <- params original_handler(self, params) } while (remaining > 0) { data <- client$fetch(blocking = TRUE, timeout = remaining) if (!is.null(data)) { client$handle_raw(data) if (hasName(storage, "params")) { return(storage$params) } } remaining <- (start_time + timeout) - Sys.time() } NULL }
mlr_tasks = R6Class("DictionaryTask", inherit = Dictionary, cloneable = FALSE )$new() as.data.table.DictionaryTask = function(x, ...) { setkeyv(map_dtr(x$keys(), function(key) { t = tryCatch(x$get(key), missingDefaultError = function(e) NULL) if (is.null(t)) { return(list(key = key)) } feats = translate_types(t$feature_types$type) insert_named(list( key = key, task_type = t$task_type, nrow = t$nrow, ncol = t$ncol, properties = list(t$properties) ), table(feats)) }, .fill = TRUE), "key")[] }
rwe_stan <- function(lst_data, stan_mdl = c("powerps", "powerpsbinary", "powerp"), chains = 4, iter = 2000, warmup = 1000, control = list(adapt_delta = 0.95), ...) { stan_mdl <- match.arg(stan_mdl) stan_rst <- rstan::sampling(stanmodels[[stan_mdl]], data = lst_data, chains = chains, iter = iter, warmup = warmup, control = control, ...) stan_rst } psrwe_powerp <- function(dta_psbor, v_outcome = "Y", outcome_type = c("continuous", "binary"), prior_type = c("fixed", "random"), ..., seed = NULL) { stopifnot(inherits(dta_psbor, what = get_rwe_class("PSDIST"))) type <- match.arg(outcome_type) prior_type <- match.arg(prior_type) stopifnot(v_outcome %in% colnames(dta_psbor$data)) old_seed <- NULL if (!is.null(seed)) { if (exists(".Random.seed", envir = .GlobalEnv)) { old_seed <- get(".Random.seed", envir = .GlobalEnv) } set.seed(seed) } rst_obs <- get_observed(dta_psbor$data, v_outcome) lst_dta <- get_stan_data(dta_psbor, v_outcome, prior_type) stan_mdl <- if_else("continuous" == type, "powerps", "powerpsbinary") ctl_post <- rwe_stan(lst_data = lst_dta$ctl, stan_mdl = stan_mdl, ...) ctl_thetas <- extract(ctl_post, "thetas")$thetas is_rct <- dta_psbor$is_rct trt_post <- NULL trt_thetas <- NULL if (is_rct) { trt_post <- rwe_stan(lst_data = lst_dta$trt, stan_mdl = stan_mdl, ...) trt_thetas <- extract(trt_post, "thetas")$thetas } rst_trt <- NULL rst_effect <- NULL if (is_rct) { rst_trt <- get_post_theta(trt_thetas, dta_psbor$Borrow$N_Cur_TRT) rst_effect <- get_post_theta(trt_thetas - ctl_thetas, dta_psbor$Borrow$N_Current) n_ctl <- dta_psbor$Borrow$N_Cur_CTL } else { n_ctl <- dta_psbor$Borrow$N_Current } rst_ctl <- get_post_theta(ctl_thetas, n_ctl) if (!is.null(seed)) { if (!is.null(old_seed)) { invisible(assign(".Random.seed", old_seed, envir = .GlobalEnv)) } else { invisible(rm(list = c(".Random.seed"), envir = .GlobalEnv)) } } rst <- list(stan_rst = list(ctl_post = ctl_post, trt_post = trt_post), Observed = rst_obs, Control = rst_ctl, Treatment = rst_trt, Effect = rst_effect, Borrow = dta_psbor$Borrow, Total_borrow = dta_psbor$Total_borrow, Method = "ps_pp", Outcome_type = type, is_rct = is_rct) class(rst) <- get_rwe_class("ANARST") rst } get_stan_data <- function(dta_psbor, v_outcome, prior_type) { f_curd <- function(i, d1, d0 = NULL) { cur_d <- c(N1 = length(d1), YBAR1 = mean(cur_d1), YSUM1 = sum(cur_d1)) if (is.null(d0)) { cur_d <- c(cur_d, N0 = 0, YBAR0 = 0, SD0 = 0) } else { cur_d <- c(cur_d, N0 = length(cur_d0), YBAR0 = mean(cur_d0), SD0 = sd(cur_d0)) } list(stan_d = cur_d, y1 = d1, inx1 = rep(i, length(d1))) } is_rct <- dta_psbor$is_rct data <- dta_psbor$data data <- data[!is.na(data[["_strata_"]]), ] strata <- levels(data[["_strata_"]]) nstrata <- length(strata) ctl_stan_d <- NULL ctl_y1 <- NULL ctl_inx1 <- NULL trt_stan_d <- NULL trt_y1 <- NULL trt_inx1 <- NULL for (i in seq_len(nstrata)) { cur_01 <- get_cur_d(data, strata[i], v_outcome) cur_d1 <- cur_01$cur_d1 cur_d0 <- cur_01$cur_d0 cur_d1t <- cur_01$cur_d1t ctl_cur <- f_curd(i, cur_d1, cur_d0) ctl_stan_d <- rbind(ctl_stan_d, ctl_cur$stan_d) ctl_y1 <- c(ctl_y1, ctl_cur$y1) ctl_inx1 <- c(ctl_inx1, ctl_cur$inx1) if (is_rct) { trt_cur <- f_curd(i, cur_d1t) trt_stan_d <- rbind(trt_stan_d, trt_cur$stan_d) trt_y1 <- c(trt_y1, trt_cur$y1) trt_inx1 <- c(trt_inx1, trt_cur$inx1) } } ctl_lst_data <- list(S = nstrata, A = dta_psbor$Total_borrow, RS = as.array(dta_psbor$Borrow$Proportion), FIXVS = as.numeric(prior_type == "fixed"), N0 = as.array(ctl_stan_d[, "N0"]), N1 = as.array(ctl_stan_d[, "N1"]), YBAR0 = as.array(ctl_stan_d[, "YBAR0"]), SD0 = as.array(ctl_stan_d[, "SD0"]), TN1 = length(ctl_y1), Y1 = ctl_y1, INX1 = ctl_inx1, YBAR1 = as.array(ctl_stan_d[, "YBAR1"]), YSUM1 = as.array(ctl_stan_d[, "YSUM1"])) trt_lst_data <- NULL if (is_rct) { trt_lst_data <- list(S = nstrata, A = 0, RS = as.array(dta_psbor$Borrow$Proportion), FIXVS = as.numeric("fixed" == "fixed"), N0 = as.array(trt_stan_d[, "N0"]), N1 = as.array(trt_stan_d[, "N1"]), YBAR0 = as.array(trt_stan_d[, "YBAR0"]), SD0 = as.array(trt_stan_d[, "SD0"]), TN1 = length(trt_y1), Y1 = trt_y1, INX1 = trt_inx1, YBAR1 = as.array(trt_stan_d[, "YBAR1"]), YSUM1 = as.array(trt_stan_d[, "YSUM1"])) } list(ctl = ctl_lst_data, trt = trt_lst_data) } get_post_theta <- function(thetas, weights) { ws <- weights / sum(weights) samples <- t(thetas) overall <- apply(samples, 2, function(x) sum(x * ws)) means <- apply(samples, 1, mean) sds <- apply(samples, 1, sd) mean_overall <- mean(overall) sd_overall <- sd(overall) list(Stratum_Samples = samples, Overall_Samples = overall, Stratum_Estimate = cbind(Mean = means, StdErr = sds), Overall_Estimate = cbind(Mean = mean_overall, StdErr = sd_overall)) } summary.PSRWE_RST <- function(object, ...) { is_rct <- object$is_rct if (is_rct) { type <- "Effect" } else { type <- "Control" } dtype <- object[[type]]$Overall_Estimate if ("ps_km" == object$Method) { dtype <- data.frame(dtype) %>% filter(object$pred_tp == T) } Overall <- data.frame(Type = type, Mean = dtype[1, "Mean"], StdErr = dtype[1, "StdErr"]) rst <- list(Overall = Overall) if (exists("CI", object)) { citype <- cbind(object$CI[[type]]$Overall_Estimate) if (is.data.frame(citype)) { if ("ps_km" == object$Method) { citype <- cbind(citype, T = object[[type]]$Overall_Estimate$T) citype <- data.frame(citype) %>% filter(object$pred_tp == T) } rst$CI <- data.frame(Lower = citype[1, "Lower"], Upper = citype[1, "Upper"], ConfLvl = object$CI$Conf_int, ConfType = object$CI$Conf_type, MethodCI = object$CI$Method_ci, Method = object$Method) } } if (exists("INFER", object)) { hitype <- object$INFER[[type]]$Overall_InferProb if ("ps_km" == object$Method) { hitype <- cbind(hitype, T = object[[type]]$Overall_Estimate$T) hitype <- data.frame(hitype) %>% filter(object$pred_tp == T) } rst$INFER <- data.frame(InferP = hitype[1, "Infer_prob"], MethodHI = object$INFER$Method_infer, Alter = object$INFER$Alternative, Mu = object$INFER$Mu) } return(rst) } print.PSRWE_RST <- function(x, ...) { rst <- summary(x, ...) rst_sum <- rst$Overall rst_ci <- rst$CI rst_infer <- rst$INFER extra_1 <- "" if ("ps_km" == x$Method) { extra_1 <- paste(" based on the survival probability at time ", x$pred_tp, ",", sep = "") } if ("Effect" == rst_sum[1, "Type"]) { extra_2 <- "treatment effect" extra_2_param <- "theta_trt-theta_ctl" } else { extra_2 <- "point estimate" extra_2_param <- "theta" } extra_ci <- "" if (exists("CI", x)) { extra_ci <- paste(" Confidence interval: ", "(", sprintf("%5.3f", rst_ci[1, "Lower"]), ", ", sprintf("%5.3f", rst_ci[1, "Upper"]), ")", " with two-sided level of ", sprintf("%5.3f", rst_ci[1, "ConfLvl"]), " by ", rst_ci[1, "MethodCI"], " method", sep = "") if (!is.na(rst_ci[1, "ConfType"])) { extra_ci <- paste(extra_ci, " and ", rst_ci[1, "ConfType"], " transformation", sep = "") } extra_ci <- paste(extra_ci, ".", sep = "") } extra_hi <- "" if (exists("INFER", x)) { extra_hi <- paste(" Hypothesis inference: ", "H0: ", extra_2_param, " ", ifelse(rst_infer[1, "Alter"] == "less", ">=", "<="), " ", sprintf("%5.3f", rst_infer[1, "Mu"]), " vs. ", "Ha: ", extra_2_param, " ", ifelse(rst_infer[1, "Alter"] == "less", "<", ">"), " ", sprintf("%5.3f", rst_infer[1, "Mu"]), " with the ", rst_infer[1, "MethodHI"], " ", sprintf("%5.5f", rst_infer[1, "InferP"]), ".", sep = "") } ss <- paste("With a total of ", x$Total_borrow, " subject borrowed from the RWD,", extra_1, " the ", extra_2, " is ", sprintf("%5.3f", rst_sum[1, "Mean"]), " with standard error ", sprintf("%5.3f", rst_sum[1, "StdErr"]), ".", extra_ci, extra_hi, sep = "") cat_paste(ss) } plot.PSRWE_RST <- function(x, ...) { rst <- switch(x$Method, ps_pp = plot_pp_rst(x, ...), ps_km = plot_km_rst(x, ...), ps_cl = { stop("This method is currently unavailable for composite likelihood analysis.") }) rst }
source("ESEUR_config.r") cli=read.csv(paste0(ESEUR_dir, "developers/remington-clilag.tsv"), as.is=TRUE, sep=" ") gui=read.csv(paste0(ESEUR_dir, "developers/remington-guilag.tsv"), as.is=TRUE, sep=" ") cli=subset(cli, Lag > 1) gui=subset(gui, Lag > 1) name_cli=subset(cli, Category == "Names") name_gui=subset(gui, Category == "Names") plot(name_cli$Lag, name_cli$Time, col=point_col, xlim=c(1, 40), ylim=c(800, 5000), xlab="Lag", ylab="Reponse time") lines(loess.smooth(name_cli$Lag, name_cli$Time, span=0.15), col=loess_col) plot(name_gui$Lag, name_gui$Time, col=point_col, xlim=c(1, 40), ylim=c(800, 5000), xlab="Lag", ylab="Reponse time") lines(loess.smooth(name_gui$Lag, name_gui$Time, span=0.15), col=loess_col)
`selAPX` <- function(APX, ista=NULL , icomp=c("V", "N", "E") ) { if(missing(icomp)) { icomp=NULL } MPX = data.frame(APX, stringsAsFactors = FALSE) if(is.null(icomp)) { atag = APX$name itag = ista w1 = which(!is.na(match(atag, itag))) m = w1 } else { M = RPMG::meshgrid(1:length(ista), 1:length(icomp) ) itag = paste(sep=".",ista[M$x], icomp[M$y]) atag = paste(sep=".", APX$name, APX$comp) m = which(!is.na(match(atag, itag))) } SWP = MPX[ m , ] SWP = as.list(SWP) return(SWP) }
get_parameters.betareg <- function(x, component = c("all", "conditional", "precision", "location", "distributional", "auxiliary"), ...) { component <- match.arg(component) cf <- stats::coef(x) params <- data.frame( Parameter = gsub("^\\(phi\\)_", "", names(cf)), Estimate = unname(cf), Component = c(rep("conditional", length(x$coefficients$mean)), rep("precision", length(x$coefficients$precision))), stringsAsFactors = FALSE, row.names = NULL ) if (component != "all") { params <- params[params$Component == component, , drop = FALSE] } .remove_backticks_from_parameter_names(params) } get_parameters.DirichletRegModel <- function(x, component = c("all", "conditional", "precision", "location", "distributional", "auxiliary"), ...) { component <- match.arg(component) cf <- stats::coef(x) if (x$parametrization == "common") { component <- "all" n_comp <- lapply(cf, length) pattern <- paste0("(", paste(x$varnames, collapse = "|"), ")\\.(.*)") p_names <- gsub(pattern, "\\2", names(unlist(cf))) params <- data.frame( Parameter = p_names, Estimate = unname(unlist(cf)), Response = rep(names(n_comp), sapply(n_comp, function(i) i)), stringsAsFactors = FALSE, row.names = NULL ) } else { out1 <- .gather(data.frame(do.call(cbind, cf$beta)), names_to = "Response", values_to = "Estimate") out2 <- .gather(data.frame(do.call(cbind, cf$gamma)), names_to = "Component", values_to = "Estimate") out1$Component <- "conditional" out2$Component <- "precision" out2$Response <- NA params <- merge(out1, out2, all = TRUE, sort = FALSE) params$Parameter <- gsub("(.*)\\.(.*)\\.(.*)", "\\3", names(unlist(cf))) params <- params[c("Parameter", "Estimate", "Component", "Response")] } if (component != "all") { params <- params[params$Component == component, , drop = FALSE] } .remove_backticks_from_parameter_names(params) } get_parameters.averaging <- function(x, component = c("conditional", "full"), ...) { component <- match.arg(component) cf <- stats::coef(x, full = component == "full") params <- data.frame( Parameter = names(cf), Estimate = unname(cf), stringsAsFactors = FALSE, row.names = NULL ) .remove_backticks_from_parameter_names(params) } get_parameters.glmx <- function(x, component = c("all", "conditional", "extra", "location", "distributional", "auxiliary"), ...) { component <- match.arg(component) cf <- stats::coef(summary(x)) params <- rbind( data.frame( Parameter = names(cf$glm[, 1]), Estimate = unname(cf$glm[, 1]), Component = "conditional", stringsAsFactors = FALSE, row.names = NULL ), data.frame( Parameter = rownames(cf$extra), Estimate = cf$extra[, 1], Component = "extra", stringsAsFactors = FALSE, row.names = NULL ) ) if (component != "all") { params <- params[params$Component == component, , drop = FALSE] } .remove_backticks_from_parameter_names(params) } get_parameters.clm2 <- function(x, component = c("all", "conditional", "scale"), ...) { component <- match.arg(component) cf <- stats::coef(summary(x)) n_intercepts <- length(x$xi) n_location <- length(x$beta) n_scale <- length(x$zeta) params <- data.frame( Parameter = rownames(cf), Estimate = unname(cf[, "Estimate"]), Component = c(rep("conditional", times = n_intercepts + n_location), rep("scale", times = n_scale)), stringsAsFactors = FALSE, row.names = NULL ) if (component != "all") { params <- params[params$Component == component, , drop = FALSE] } .remove_backticks_from_parameter_names(params) } get_parameters.clmm2 <- get_parameters.clm2 get_parameters.mvord <- function(x, component = c("all", "conditional", "thresholds", "correlation"), ...) { component <- match.arg(component) junk <- utils::capture.output(s <- summary(x)) thresholds <- as.data.frame(s$thresholds) thresholds$Parameter <- rownames(thresholds) thresholds$Response <- gsub("(.*)\\s(.*)", "\\1", thresholds$Parameter) coefficients <- as.data.frame(s$coefficients) coefficients$Parameter <- rownames(coefficients) coefficients$Response <- gsub("(.*)\\s(.*)", "\\2", coefficients$Parameter) if (!all(coefficients$Response %in% thresholds$Response)) { resp <- unique(thresholds$Response) for (i in coefficients$Response) { coefficients$Response[coefficients$Response == i] <- resp[grepl(paste0(i, "$"), resp)] } } params <- data.frame( Parameter = c(thresholds$Parameter, coefficients$Parameter), Estimate = c(unname(thresholds[, "Estimate"]), unname(coefficients[, "Estimate"])), Component = c(rep("thresholds", nrow(thresholds)), rep("conditional", nrow(coefficients))), Response = c(thresholds$Response, coefficients$Response), stringsAsFactors = FALSE, row.names = NULL ) params_error <- data.frame( Parameter = rownames(s$error.structure), Estimate = unname(s$error.structure[, "Estimate"]), Component = "correlation", Response = NA, stringsAsFactors = FALSE, row.names = NULL ) params <- rbind(params, params_error) if (.n_unique(params$Response) == 1) { params$Response <- NULL } if (component != "all") { params <- params[params$Component == component, , drop = FALSE] } .remove_backticks_from_parameter_names(params) } get_parameters.mjoint <- function(x, component = c("all", "conditional", "survival"), ...) { component <- match.arg(component) s <- summary(x) params <- rbind( data.frame( Parameter = rownames(s$coefs.long), Estimate = unname(s$coefs.long[, 1]), Component = "conditional", stringsAsFactors = FALSE, row.names = NULL ), data.frame( Parameter = rownames(s$coefs.surv), Estimate = unname(s$coefs.surv[, 1]), Component = "survival", stringsAsFactors = FALSE, row.names = NULL ) ) if (component != "all") { params <- params[params$Component == component, , drop = FALSE] } .remove_backticks_from_parameter_names(params) } get_parameters.systemfit <- function(x, ...) { cf <- stats::coef(summary(x)) f <- find_formula(x) system_names <- names(f) parameter_names <- row.names(cf) out <- lapply(system_names, function(i) { pattern <- paste0("^", i, "_(.*)") params <- grepl(pattern, parameter_names) data.frame( Parameter = gsub(pattern, "\\1", parameter_names[params]), Estimate = as.vector(cf[params, "Estimate"]), Component = i, stringsAsFactors = FALSE ) }) do.call(rbind, out) }
tabularTestSummary <- function(ph, columns=c("pvalue")) { if( !is.testMultiple(ph) ) stop(.callErrorMessage("wrongParameterError", "ph", "testMultiple")) if( sum(columns %in% c("pvalue","wtl","rank")) != length(columns) ) stop(.callErrorMessage("parameterInRangeError", "columns", "from the list [pvalue,wtl,rank]")) df <- ph$names format=data.frame(matrix("%s", nrow=nrow(df),ncol=ncol(df))) colnames(format) <- colnames(df) decreasingOrder=c(T) for ( col in columns ) { m <- do.call(.mapId2Name[[col]],list(ph)) df <- cbind(df, m$data) format <- cbind(format, m$format) decreasingOrder <- c(decreasingOrder, m$decreasingOrder) } correct_order <- .orderCascade(df, decreasing = decreasingOrder) df <- df[correct_order,,drop=FALSE] format <- format[correct_order,,drop=FALSE] methodName <- ph$experiment$method if(ncol(ph$names)>1){ colnames(df)[1:ncol(ph$names)] <- paste(methodName,1:ncol(ph$names)) } else{ colnames(df)[1] <- methodName } if ("pvalue"%in%columns) { title <- sprintf("Summary of %s post-hoc test for output \"%s\"", ph$tags$scope, ph$tags$target) tableType = "phtest" } else { title <- sprintf("Method comparison for output \"%s\"", ph$tags$target) tableType = "plain" } tab <- .exTabular(tables = list("testMultiple"=df), formats =list("testMultiple"=format), tableSplit=1, tableType=tableType, title = title, alias = "TestSummaryTable", tags = ph$tags) tab }
library(SII) OCTAVE.TST=sii( speech=c(50.00,40,40,30,20,0.0), noise=c(70,65,45,25,1.00,-15.00), threshold=c(0.00,0,0,0,0,7.10), method="octave" ) stopifnot(round(OCTAVE.TST$sii,3)==0.491) OCTAVE_1.TST=sii( speech=c(50.00,40,40,30,20,0.0), noise=c(70,65,45,25,1.00,-15.00), threshold=c(0.00,0,0,0,0,7.10), importance=c(0,0,1,0,0,0), method="octave" ) stopifnot(round(OCTAVE_1.TST$sii,3)==0.323) TO.TST=sii( speech=c(90,5,40,40,40,40,40,40,40,40,40,40,40,40,-10,-10,-10,-10), noise=c(10,-10,-10,75,-10,-10,-10,-10,-10,-10,-10,-10,-10,-10,10,10,10,10), threshold=c(90,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), method="one-third octave" ) stopifnot(round(TO.TST$sii,3)==0.445) TO_1.TST=sii( speech=c(90,5,40,40,40,40,40,40,40,40,40,40,40,40,-10,-10,-10,-10), noise=c(10,-10,-10,75,-10,-10,-10,-10,-10,-10,-10,-10,-10,-10,10,10,10,10), threshold=c(90,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), importance=c(0,0,0,0,0,0,0,0,0,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.3,0), method="one-third octave" ) stopifnot(round(TO_1.TST$sii,3)==0.438) CB.TST=sii( speech=c(-10,-10,-10,90,5,40,40,40,40,40,40,40,40,40,40,40,40,-10,-10,-10,-10), noise=c(10,10,10,10,-10,-10,70,-10,-10,-10,-10,-10,-10,-10,-10,-10,-10,10,10,10,10), threshold=c(0,0,0,90,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), ) stopifnot(round(CB.TST$sii,3)==0.273) CB_1.TST=sii( speech=c(-10,-10,-10,90,5,40,40,40,40,40,40,40,40,40,40,40,40,-10,-10,-10,-10), noise=c(10,10,10,10,-10,-10,70,-10,-10,-10,-10,-10,-10,-10,-10,-10,-10,10,10,10,10), threshold=c(0,0,0,90,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), importance=c(0,0,0,0,0,0,0,0,0,0,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.3,0,0,0) ) stopifnot(round(CB_1.TST$sii,3)==0.410) ECB.TST=sii( speech=c(-10,90,5,40,40,40,40,40,40,40,40,40,40,40,40,-10,-10), noise=c(10,10,-10,-10,70,-10,-10,-10,-10,-10,-10,-10,-10,-10,-10,10,10), threshold=c(0,90,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), method="equal-contributing" ) stopifnot(round(ECB.TST$sii,3)==0.278) ECB_1.TST=sii( speech=c(-10,90,5,40,40,40,40,40,40,40,40,40,40,40,40,-10,-10), noise=c(10,10,-10,-10,70,-10,-10,-10,-10,-10,-10,-10,-10,-10,-10,10,10), threshold=c(0,90,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0), importance=c(0,0,0,0,0,0,0,0,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.3,0), method="equal-contributing" ) stopifnot(round(ECB_1.TST$sii,3)==0.410)
library(GLMcat) data("TravelChoice") head(TravelChoice) str(TravelChoice) exp_8.4 <- discrete_cm( formula = choice ~ hinc + gc + invt, case_id = "indv", alternatives = "mode", reference = "air", data = TravelChoice, alternative_specific = c("gc", "invt"), cdf = "logistic") summary(exp_8.4) (constant_model <- discrete_cm( formula = choice ~ 1 , case_id = "indv", alternatives = "mode", reference = c("air", "train", "bus", "car"), data = TravelChoice, cdf = "logistic" )) (car_0 <- discrete_cm( formula = choice ~ hinc[air] + psize[air] + gc + ttme, case_id = "indv", alternatives = "mode", reference = c("air", "train", "bus", "car"), alternative_specific = c("gc", "ttme"), data = TravelChoice, cdf = "logistic" )) mod_1 <- discrete_cm( formula = choice ~ hinc[air] + psize[air] + gc + ttme, case_id = "indv", alternatives = "mode", reference = "air", alternative_specific = c("gc", "ttme"), data = TravelChoice, cdf = "logistic" ) logLik(mod_1) mod_2 <- discrete_cm( formula = choice ~ hinc[air] + psize[air] + gc + ttme, case_id = "indv", alternatives = "mode", reference = "bus", alternative_specific = c("gc", "ttme"), data = TravelChoice, cdf = list("student",30) ) logLik(mod_2) mod_3 <- discrete_cm( formula = choice ~ hinc[air] + psize[air] + gc + ttme, case_id = "indv", alternatives = "mode", reference = "car", alternative_specific = c("gc", "ttme"), data = TravelChoice, cdf = list("student",0.2) ) logLik(mod_3) mod_4 <- discrete_cm( formula = choice ~ hinc[air] + psize[air] + gc + ttme, case_id = "indv", alternatives = "mode", reference = "train", alternative_specific = c("gc", "ttme"), data = TravelChoice, cdf = list("student",1.35) ) logLik(mod_4)
d=2 fName="onCircle" cobra <- cobraInit(xStart=rep(5,d), fn=function(x){c(obj=sum(x^2),equ=(x[1]-1)^2+(x[2]-0)^2-4)}, fName=fName,lower=rep(-10,d), upper=rep(10,d), feval=40) cobra <- cobraPhaseII(cobra) print(getXbest(cobra)) print(getFbest(cobra)) optim = 1 plot(abs(cobra$df$Best-optim),log="y",type="l",main=fName,ylab="error",xlab="iteration")
combine.AIC <- function(AIC) { stopifnot(is.numeric(AIC)) if (length(AIC) == 1) { warning("There is only one model fit, and nothing to combine.", call. = TRUE) AIC.pool <- as.character(format(AIC, nsmall = 1)) } else { stat <- cbind(mean = mean(AIC), sd = sd(AIC)) AIC.pool <- suppressWarnings(as.character(formatMeanSd(stat, nsmall = 1))) AIC.pool <- strsplit(AIC.pool, ",")[[1]] } return(AIC.pool) }
bind_log_odds <- function(tbl, set, feature, n, uninformative = FALSE, unweighted = FALSE) { set <- enquo(set) feature <- enquo(feature) n_col <- enquo(n) grouping <- group_vars(tbl) tbl <- ungroup(tbl) pseudo <- tbl if (uninformative) { pseudo$alpha <- 1 } else { feat_counts <- count(pseudo, !!feature, wt = !!n_col, name = ".n") feat_counts <- left_join(tbl, feat_counts, by = as_name(feature)) pseudo$alpha <- feat_counts$.n } pseudo <- mutate(pseudo, y_wi = !!n_col + alpha) feat_counts <- count(pseudo, !!feature, wt = y_wi, name = "y_w") set_counts <- count(pseudo, !!set, wt = y_wi, name = "n_i") pseudo_counts <- left_join(pseudo, feat_counts, by = as_name(feature)) pseudo_counts <- left_join(pseudo_counts, set_counts, by = as_name(set)) results <- mutate( pseudo_counts, omega_wi = y_wi / (n_i - y_wi), omega_w = y_w / (sum(y_wi) - y_w), delta_wi = log(omega_wi) - log(omega_w), sigma2_wi = 1 / y_wi + 1 / y_w, zeta_wi = delta_wi / sqrt(sigma2_wi) ) clean <- rename( results, log_odds_weighted = zeta_wi, log_odds = delta_wi, ) tbl <- select( clean, -y_wi, -y_w, -n_i, -omega_wi, -omega_w, -sigma2_wi, -alpha ) if (!unweighted) { tbl$log_odds <- NULL } if (!is_empty(grouping)) { tbl <- group_by(tbl, !!sym(grouping)) } tbl }
context("Linear regression") set.seed(1, kind="Mersenne-Twister", normal.kind="Inversion") n <- 1000L df <- data.frame( x1 = rnorm(n), x2 = runif(n), x3 = rbinom(n, 1, 0.1), x4 = rgamma(n, 1, 1) ) df$y <- with(df, 1 + x1 + 2*x2 + 3*x3 + 4*x4 + rnorm(n)) test_that("linear regression works, as well as fitted, residuals and predict methods", { sampler <- create_sampler(y ~ reg(~1+x1+x2+x3+x4, name="beta"), data=df) sim <- MCMCsim(sampler, n.iter=500, burnin=100, n.chain=2, verbose=FALSE) summ <- summary(sim) expect_true(all((0.5 * c(1,1,2,3,4) < summ$beta[, "Mean"]) & (summ$beta[, "Mean"] < 2 * c(1,1,2,3,4)))) expect_true((0.5 < summ$sigma_[, "Mean"]) && (summ$sigma_[, "Mean"] < 2)) expect_equal(fitted(sim, mean.only=TRUE), as.vector(summary(fitted(sim))[, "Mean"])) expect_equal(residuals(sim, mean.only=TRUE), as.vector(summary(residuals(sim))[, "Mean"])) expect_equal(nrow(summary(predict(sim, iters=sample(1:500, 100), show.progress=FALSE))), n) expect_equal(nvars(predict(sim, X.=list(beta=model_matrix(~1+x1+x2+x3+x4, df[1:10, ])), show.progress=FALSE)), 10) expect_equal(nvars(predict(sim, newdata=df[21, ], show.progress=FALSE)), 1) }) test_that("single-site Gibbs sampler works", { sampler <- create_sampler( y ~ reg(~1, name="mu") + reg(~x1-1, name="beta1") + reg(~x2-1, name="beta2") + reg(~x3-1, name="beta3") + reg(~x4-1, name="beta4"), data=df ) sim <- MCMCsim(sampler, n.iter=500, burnin=100, n.chain=2, verbose=FALSE) summ <- summary(sim) expect_true((0.5 < summ$mu[, "Mean"]) && (summ$mu[, "Mean"] < 2)) expect_true((0.5 < summ$beta1[, "Mean"]) && (summ$beta1[, "Mean"] < 2)) expect_true((2*0.5 < summ$beta2[, "Mean"]) && (summ$beta2[, "Mean"] < 2*2)) expect_true((3*0.5 < summ$beta3[, "Mean"]) && (summ$beta3[, "Mean"] < 3*2)) expect_true((4*0.5 < summ$beta4[, "Mean"]) && (summ$beta4[, "Mean"] < 4*2)) expect_true((0.5 < summ$sigma_[, "Mean"]) && (summ$sigma_[, "Mean"] < 2)) }) test_that("full blocking works", { sampler <- create_sampler( y ~ reg(~1, name="mu") + reg(~x1-1, name="beta1") + reg(~x2-1, name="beta2") + reg(~x3-1, name="beta3") + reg(~x4-1, name="beta4"), data=df, block=TRUE ) sim <- MCMCsim(sampler, n.iter=500, burnin=100, n.chain=2, verbose=FALSE) summ <- summary(sim) expect_true((0.5 < summ$mu[, "Mean"]) && (summ$mu[, "Mean"] < 2)) expect_true((0.5 < summ$beta1[, "Mean"]) && (summ$beta1[, "Mean"] < 2)) expect_true((2*0.5 < summ$beta2[, "Mean"]) && (summ$beta2[, "Mean"] < 2*2)) expect_true((3*0.5 < summ$beta3[, "Mean"]) && (summ$beta3[, "Mean"] < 3*2)) expect_true((4*0.5 < summ$beta4[, "Mean"]) && (summ$beta4[, "Mean"] < 4*2)) expect_true((0.5 < summ$sigma_[, "Mean"]) && (summ$sigma_[, "Mean"] < 2)) }) test_that("custom blocking works", { sampler <- create_sampler( y ~ reg(~1, name="mu") + reg(~x1-1, name="beta1") + reg(~x2-1, name="beta2") + reg(~x3-1, name="beta3") + reg(~x4-1, name="beta4"), data=df, block=list(c("beta4", "beta2"), c("mu", "beta3")) ) sim <- MCMCsim(sampler, n.iter=500, burnin=100, n.chain=2, verbose=FALSE) summ <- summary(sim) expect_true((0.5 < summ$mu[, "Mean"]) && (summ$mu[, "Mean"] < 2)) expect_true((0.5 < summ$beta1[, "Mean"]) && (summ$beta1[, "Mean"] < 2)) expect_true((2*0.5 < summ$beta2[, "Mean"]) && (summ$beta2[, "Mean"] < 2*2)) expect_true((3*0.5 < summ$beta3[, "Mean"]) && (summ$beta3[, "Mean"] < 3*2)) expect_true((4*0.5 < summ$beta4[, "Mean"]) && (summ$beta4[, "Mean"] < 4*2)) expect_true((0.5 < summ$sigma_[, "Mean"]) && (summ$sigma_[, "Mean"] < 2)) }) test_that("using an offset for linear regression works", { sampler <- create_sampler( formula = y ~ reg(~ x1 + x2 + x3, name="beta") + offset(4*x4), data=df ) expect_equal(sampler$offset, 4*df$x4) sim <- MCMCsim(sampler, n.iter=500, burnin=100, n.chain=2, verbose=FALSE) summ <- summary(sim) expect_true(all((0.5 * c(1,1,2,3) < summ$beta[, "Mean"]) & (summ$beta[, "Mean"] < 2 * c(1,1,2,3)))) expect_true((0.5 < summ$sigma_[, "Mean"]) && (summ$sigma_[, "Mean"] < 2)) }) test_that("simplified formula + offset works for linear regression", { sampler <- create_sampler( formula = y ~ x1 + x2 + x3 + offset(4*x4), data=df ) expect_equal(sampler$offset, 4*df$x4) sim <- MCMCsim(sampler, n.iter=500, burnin=100, n.chain=2, verbose=FALSE) summ <- summary(sim) expect_true(all((0.5 * c(1,1,2,3) < summ$reg1[, "Mean"]) & (summ$reg1[, "Mean"] < 2 * c(1,1,2,3)))) expect_true((0.5 < summ$sigma_[, "Mean"]) && (summ$sigma_[, "Mean"] < 2)) }) test_that("model specification in two steps works", { mod <- y ~ x1 + x2 + x3 + x4 ml_mod <- y ~ reg(mod, Q0=1e-6, name="beta") sampler <- create_sampler(ml_mod, data=df, block=TRUE) sim <- MCMCsim(sampler, n.iter=500, burnin=100, n.chain=2, verbose=FALSE) summ <- summary(sim) expect_true(all((0.5 * c(1,1,2,3,4) < summ$beta[, "Mean"]) & (summ$beta[, "Mean"] < 2 * c(1,1,2,3,4)))) expect_true((0.5 < summ$sigma_[, "Mean"]) && (summ$sigma_[, "Mean"] < 2)) }) n <- 1000 sd0 <- 0.41 y <- 1 + rnorm(n, sd=sd0) test_that("different priors for residual variance work", { sampler <- create_sampler(y ~ 1, sigma.mod=pr_fixed(0.41^2)) sim <- MCMCsim(sampler, n.iter=500, burnin=100, n.chain=2, verbose=FALSE) pm_sigma <- summary(sim$sigma_)[, "Mean"] expect_true((0.75*sd0 < pm_sigma) && (pm_sigma < 1.25*sd0)) sampler <- create_sampler(y ~ 1, sigma.mod=pr_invchisq(df=1, scale="modeled")) sim <- MCMCsim(sampler, n.iter=500, burnin=100, n.chain=2, verbose=FALSE) pm_sigma <- summary(sim$sigma_)[, "Mean"] expect_true((0.75*sd0 < pm_sigma) && (pm_sigma < 1.25*sd0)) sampler <- create_sampler(y ~ 1, sigma.mod=pr_exp(scale=1)) sim <- MCMCsim(sampler, n.iter=500, burnin=100, n.chain=2, verbose=FALSE) pm_sigma <- summary(sim$sigma_)[, "Mean"] expect_true((0.75*sd0 < pm_sigma) && (pm_sigma < 1.25*sd0)) sampler <- create_sampler(y ~ 1, sigma.mod=pr_gig(a=1, b=1, p=1)) sim <- MCMCsim(sampler, n.iter=500, burnin=100, n.chain=2, verbose=FALSE) pm_sigma <- summary(sim$sigma_)[, "Mean"] expect_true((0.75*sd0 < pm_sigma) && (pm_sigma < 1.25*sd0)) })
phieta <- function(x, phi){ n <- length(x) eta <- c(phi[1], diff(phi)/diff(x)) return(eta) }
fkpsst<-function(X, ALPHA=0.05, METHOD="MC", K=default_kernel, h_power=2/5, est_ev=nrow(X), MCNsim=10000, sbb_set=NULL, M=1000, b=ceiling((2*nrow(X))^(1/3))){ if (h_power<=0 | h_power>=1) stop("The value of 'h_power' exceeds the range (0,1).") if (METHOD=="MC" & is.null(sbb_set)) stop("You must generate a simluated dataset for Monte Carlo method from the function 'generate_sbb'.") N<-nrow(X) MeanX<-apply(X,2,sum)/N StairsumX<-apply((1:N)*X,2,sum) hat_eta<-X+(((1:N-(N+1)/2)*6/(N-1)-1))%*%t(MeanX)-((1:N-(N+1)/2)*12/(N*(N^2-1)))%*%t(StairsumX) ZN<-partial_sum(hat_eta) TN<-mean(ZN^2) if (METHOD=="MC"){ lambda<-est_eigenvalue(hat_eta,K,h_power,est_ev) intV<-matrix(sample(sbb_set,MCNsim*est_ev,replace=T),ncol=est_ev) monte=(intV%*%lambda)[,1] fkpsst_result<-list(statistic=c(R_N=TN),p.value=mean(TN<monte),sample.size=N,method="Monte-Carlo-based functional KPSS test") } else { hat_xi<-apply((1:N-(N+1)/2)*X,2,sum)*(12/(N*(N^2-1))) hat_mu<-apply(X,2,sum)/N-hat_xi*(N+1)/2 if (METHOD=="SB"){ bs_teststat<-sapply(1:M,function(o){ bs_ind<-sample(1:N,N,replace=T) bs_hat_eta<-hat_eta[bs_ind,] bsX=rep(1,N)%*%t(hat_mu)+(1:N)%*%t(hat_xi)+bs_hat_eta bsTN<-FKPSS_teststat(bsX) return(bsTN) } ) fkpsst_result<-list(statistic=c(R_N=TN),p.value=mean(TN<bs_teststat),sample.size=N,method="Simple-bootstrap-based functional KPSS test") } else { bbs_teststat<-sapply(1:M,function(o){ bs<-sample(1:(N-b+1),ceiling(N/b),replace=T) bbs<-bs[1]:(bs[1]+b-1) for (i in 2:ceiling(N/b)){ bbs<-c(bbs,bs[i]:(bs[i]+b-1)) } bs_hat_eta<-hat_eta[bbs[1:N],] bsX=rep(1,N)%*%t(hat_mu)+(1:N)%*%t(hat_xi)+bs_hat_eta bsTN<-FKPSS_teststat(bsX) return(bsTN) } ) fkpsst_result<-list(statistic=c(R_N=TN),p.value=mean(TN<bbs_teststat),sample.size=N,method="Moving-block-bootstrap-based functional KPSS test") } } class(fkpsst_result)<-"htest" return(fkpsst_result) }
Internalmammpc = function(targ, data, statistic, max_k, threshold, test = NULL, ini = NULL, user_test = NULL, hash=FALSE, varsize, stat_hash, pvalue_hash, targetID, ncores) { runtime = proc.time(); D = length(targ) if ( is.null(ini) ) { cols = ncol( data[[ 1 ]] ) sta = pval = matrix(0, D, cols) univariateModels = list() if ( identical(test, testIndFisher) ) { for ( l in 1:D ) { target = targ[[ l ]] dataset = data[[ l ]] rows = length(target) a = as.vector( cor(target, dataset) ) dof = rows - 3; wa = abs( 0.5 * log( (1 + a) / (1 - a) ) * sqrt(dof) ) if ( targetID != - 1 ) wa[ targetID ] = 0 sta[l, ] = wa pval[l, ] = log(2) + pt(-wa, dof, log.p = TRUE) } univariateModels$stat = - 2 * Rfast::colsums(pval); univariateModels$pvalue = pchisq(univariateModels$stat, 2 * D, lower.tail = FALSE, log.p = TRUE) ; univariateModels$stat_hash = stat_hash; univariateModels$pvalue_hash = pvalue_hash; } else if ( identical(test, testIndSpearman) ) { for ( l in 1:D ) { target = targ[[ l ]] dataset = data[[ l ]] rows = length(target) a = as.vector( cor(target, dataset) ) dof = rows - 3; wa = abs( 0.5 * log( (1 + a) / (1 - a) ) * sqrt(dof) / 1.029563 ) if ( targetID != - 1 ) wa[ targetID ] = 0 sta[l, ] = wa pval[l, ] = log(2) + pt(-wa, dof, lower.tail = FALSE, log.p = TRUE) } univariateModels$stat = - 2 * Rfast::colsums(pval); univariateModels$pvalue = pchisq(univariateModels$stat, 2 * D, lower.tail = FALSE, log.p = TRUE) ; univariateModels$stat_hash = stat_hash; univariateModels$pvalue_hash = pvalue_hash; } else if ( identical(test, testIndMMReg) ) { univariateModels = list(); fit1 = MASS::rlm(target ~ 1, maxit = 2000, method = "MM") lik2 = numeric(cols) dof = numeric(cols) if ( ncores <= 1 | is.null(ncores) ) { for (l in 1:D) { target = targ[[ l ]] dataset = data[[ l ]] for ( i in 1:cols ) { if ( i != targetID ) { fit2 = MASS::rlm(target ~ dataset[, i], method = "MM", maxit = 2000 ) lik2[i] = as.numeric( logLik(fit2) ) dof[i] = length( coef(fit2) ) - 1 } else { lik2[i] = lik1 } } lik1 = as.numeric( logLik(fit1) ) sta[l, ] = as.vector( 2 * abs(lik1 - lik2) ) pval[l, ] = pchisq(sta[l, ], dof, lower.tail = FALSE, log.p = TRUE) } univariateModels$stat = - 2 * Rfast::colsums(pval) univariateModels$pvalue = pchisq(univariateModels$stat, 2 * D, lower.tail = FALSE, log.p = TRUE) ; univariateModels$stat_hash = stat_hash; univariateModels$pvalue_hash = pvalue_hash; } else { for ( l in 1:D ) { target = targ[[ l ]] dataset = data[[ l ]] cl <- makePSOCKcluster(ncores) registerDoParallel(cl) mod <- foreach(i = 1:cols, .combine = rbind, .packages = "MASS") %dopar% { if ( i != targetID ) { fit2 = rlm(target ~ dataset[, i] ) lik2 = as.numeric( logLik(fit2) ) return( c(lik2, length( coef(fit2) ) ) ) } else{ return( c(0, 0) ) } } stopCluster(cl) lik1 = as.numeric( logLik(fit1) ) dof = as.vector( mod[, 2] ) - 1 sta[l, ] = as.vector( 2 * abs(lik1 - mod[, 1]) ) pval[l, ] = pchisq(sta[l, ], dof, lower.tail = FALSE, log.p = TRUE) } univariateModels$stat = - 2 * Rfast::colsums(pval) univariateModels$pvalue = pchisq(univariateModels$stat, 2 * D, lower.tail = FALSE, log.p = TRUE) ; univariateModels$stat_hash = NULL univariateModels$pvalue_hash = NULL } } else if ( identical(test, testIndLogistic) & is.ordered(target) ) { lik2 = numeric(cols) dof = numeric(cols) univariateModels = list(); fit1 = ordinal::clm(target ~ 1) df1 = length( coef(fit1) ) if ( ncores <= 1 | is.null(ncores) ) { for ( l in 1:D ) { target = targ[[ l ]] dataset = data[[ l ]] for ( i in 1:cols ) { if (i != targetID){ x <- model.matrix(target ~ dataset[, i] ) fit2 <- ordinal::clm.fit(target, x) lik2[i] <- as.numeric( fit2$logLik ) dof[i] <- length( coef(fit2) ) - df1 } else { lik2[i] <- lik1 } } lik1 = as.numeric( logLik(fit1) ) sta[l, ] = as.vector( 2 * abs(lik1 - lik2) ) pval[l, ] = pchisq(sta[l, ], dof, lower.tail = FALSE, log.p = TRUE) } univariateModels$stat = - 2 * Rfast::colsums(pval) univariateModels$pvalue = pchisq(univariateModels$stat, 2 * D, lower.tail = FALSE, log.p = TRUE) ; univariateModels$stat_hash = stat_hash; univariateModels$pvalue_hash = pvalue_hash; } else { for ( l in 1:D ) { target = targ[[ l ]] dataset = data[[ l ]] cl <- makePSOCKcluster(ncores) registerDoParallel(cl) mod <- foreach(i = 1:cols, .combine = rbind, .packages = "ordinal") %dopar% { if ( i != targetID ) { x <- model.matrix(target ~ dataset[, i] ) fit2 <- ordinal::clm.fit(target, x) lik2 <- as.numeric( fit2$logLik ) return( c(lik2, length( coef(fit2) ) ) ) } else{ return( c(0, 0) ) } } stopCluster(cl) lik1 = as.numeric( logLik(fit1) ) dof = as.vector( mod[, 2] ) - df1 sta[l, ] = as.vector( 2 * abs(lik1 - mod[, 1]) ) pval[l, ] = pchisq(sta[l, ], dof, lower.tail = FALSE, log.p = TRUE) } univariateModels$stat = - 2 * Rfast::colsums(pval) univariateModels$pvalue = pchisq(univariateModels$stat, 2 * D, lower.tail = FALSE, log.p = TRUE) ; univariateModels$stat_hash = NULL univariateModels$pvalue_hash = NULL } } else { univariateModels = univariateScore.ma(targ, data, test, statistic = FALSE, hash=hash, stat_hash=stat_hash, pvalue_hash=pvalue_hash, targetID=targetID, ncores=ncores); } } else { univariateModels = ini } pvalues = univariateModels$pvalue; stats = univariateModels$stat; if ( min(pvalues , na.rm = TRUE) > threshold ) { results = NULL; results$selectedVars = c(); class(results$selectedVars) = "numeric"; results$selectedVarsOrder = c(); class(results$selectedVarsOrder) = "numeric"; results$hashObject = NULL; class(results$hashObject) = 'list'; class(results$univ) = 'list'; results$pvalues = exp(pvalues); results$stats = stats; results$univ = univariateModels results$max_k = max_k; results$threshold = threshold; runtime = proc.time() - runtime; results$runtime = runtime; return(results); } selectedVars = numeric(varsize); selectedVarsOrder = numeric(varsize) selectedVar = which( pvalues == pvalues[[which.min(pvalues)]] ); selectedVars[selectedVar] = 1; selectedVarsOrder[selectedVar] = 1; remainingVars = numeric(varsize) + 1; remainingVars[selectedVar] = 0; remainingVars[pvalues > threshold] = 0; if (targetID > 0) remainingVars[targetID] = 0; loop = any(as.logical(remainingVars)); while(loop) { max_min_results = max_min_assoc.ma(target, dataset, test, threshold, statistic, max_k, selectedVars, pvalues, stats, remainingVars, univariateModels, selectedVarsOrder, hash=hash, stat_hash=stat_hash, pvalue_hash=pvalue_hash); selectedVar = max_min_results$selected_var; selectedPvalue = max_min_results$selected_pvalue; remainingVars = max_min_results$remainingVars; pvalues = max_min_results$pvalues; stats = max_min_results$stats; stat_hash=max_min_results$stat_hash; pvalue_hash=max_min_results$pvalue_hash; if(selectedPvalue <= threshold) { selectedVars[selectedVar] = 1; selectedVarsOrder[selectedVar] = max(selectedVarsOrder) + 1; remainingVars[selectedVar] = 0; } loop = any(as.logical(remainingVars)); } selectedVarsOrder[which(!selectedVars)] = varsize; numberofSelectedVars = sum(selectedVars); selectedVarsOrder = sort(selectedVarsOrder); if(targetID > 0) { toAdjust <- which(selectedVars > targetID); selectedVars[toAdjust] = selectedVars[toAdjust] + 1; } results = NULL; results$selectedVars = which(selectedVars == 1); svorder = sort(pvalues[results$selectedVars] , index.return = TRUE); svorder = results$selectedVars[svorder$ix]; results$selectedVarsOrder = svorder; hashObject = NULL; hashObject$stat_hash = stat_hash; hashObject$pvalue_hash = pvalue_hash; results$hashObject = hashObject; class(results$hashObject) = 'list'; results$pvalues = pvalues; results$stats = stats; results$univ = univariateModels results$max_k = max_k; results$threshold = threshold; runtime = proc.time() - runtime; results$runtime = runtime; return(results); }
setCorrectDate <- function(x, type) { setCorrectDateEle <- function(x, type) { inBetween0099 <- function(range1, range2, valueX) { inBetween0009 <- function(valueXrange, valueX) { if (valueX == valueXrange) { result = paste0("0", valueX) } else { result = NA } } inBetween1099 <- function(valueXrange, valueX) { if (valueX == valueXrange) { result = as.character(valueX) } else { result = NA } } posibleDates <- c(sapply(range1, FUN = inBetween0009, valueX = valueX), sapply(range2, FUN = inBetween1099, valueX = valueX)) posibleDatesNonaInd <- which(is.na(posibleDates) == FALSE) if (length(posibleDatesNonaInd) == 1) { result <- posibleDates[posibleDatesNonaInd] } else { result = NA } result } switch(type, validYear = as.character(x), validMonth = inBetween0099(1:9,10:12, valueX = x), validDay = inBetween0099(1:9, 10:31, valueX = x), validHour = inBetween0099(0:9, 10:23, valueX = x), validMin = inBetween0099(0:9,10:59, valueX = x), validSec = inBetween0099(0:9, 10:59, valueX = x)) } result <- verifyIntEntry(x, noValid = NA) if (is.finite(result)) { result <- setCorrectDateEle(result, type = type) } result }
swirl <- function(resume.class="default", ...){ removeTaskCallback("mini") e <- new.env(globalenv()) class(e) <- c("environment", resume.class) cb <- function(expr, val, ok, vis, data=e){ e$expr <- expr e$val <- val e$ok <- ok e$vis <- vis return(resume(e, ...)) } addTaskCallback(cb, name="mini") invisible() } bye <- function(){ removeTaskCallback("mini") swirl_out(s()%N%"Leaving swirl now. Type swirl() to resume.", skip_after=TRUE) invisible() } nxt <- function(){invisible()} skip <- function(){invisible()} reset <- function(){invisible()} submit <- function(){invisible()} play <- function(){invisible()} main <- function(){invisible()} restart <- function(){invisible()} info <- function(){ swirl_out(s()%N%"When you are at the R prompt (>):") swirl_out(s()%N%"-- Typing skip() allows you to skip the current question.", skip_before=FALSE) swirl_out(s()%N%"-- Typing play() lets you experiment with R on your own; swirl will ignore what you do...", skip_before=FALSE) swirl_out(s()%N%"-- UNTIL you type nxt() which will regain swirl's attention.", skip_before=FALSE) swirl_out(s()%N%"-- Typing bye() causes swirl to exit. Your progress will be saved.", skip_before=FALSE) swirl_out(s()%N%"-- Typing main() returns you to swirl's main menu.", skip_before=FALSE) swirl_out(s()%N%"-- Typing info() displays these options again.", skip_before=FALSE, skip_after=TRUE) invisible() } resume <- function(...)UseMethod("resume") resume.default <- function(e, ...){ args_specification(e, ...) esc_flag <- TRUE on.exit(if(esc_flag)swirl_out(s()%N%"Leaving swirl now. Type swirl() to resume.", skip_after=TRUE)) if(uses_func("info")(e$expr)[[1]]){ esc_flag <- FALSE return(TRUE) } if(uses_func("nxt")(e$expr)[[1]]){ do_nxt(e) } if(uses_func("reset")(e$expr)[[1]]) { do_reset(e) } if(uses_func("submit")(e$expr)[[1]]){ do_submit(e) } if(uses_func("play")(e$expr)[[1]]){ do_play(e) } if(uses_func("skip")(e$expr)[[1]]){ if(!exists("skips", e)) e$skips <- 0 e$skips <- 1 + e$skips e$skipped <- TRUE correctAns <- e$current.row[,"CorrectAnswer"] if(is(e$current.row, "script") && is.na(correctAns)) { correct_script_path <- e$correct_script_temp_path if(file.exists(correct_script_path)) { e$script_contents <- readLines(correct_script_path, warn = FALSE) e$expr <- try(parse(text = e$script_contents), silent = TRUE) try(source(correct_script_path)) swirl_out(s()%N%"I just sourced the following script, which demonstrates one possible solution.", skip_after=TRUE) file.edit(correct_script_path) readline(s()%N%"Press Enter when you are ready to continue...") } } else { if(exists("newVarName",e)) { correctAns <- gsub("newVar", e$newVarName, correctAns) } e$expr <- parse(text=correctAns)[[1]] ce <- cleanEnv(e$snapshot) evaluation <- withVisible(eval(e$expr, ce)) e$vis <- evaluation$visible e$val <- suppressMessages(suppressWarnings(evaluation$value)) xfer(ce, globalenv()) ce <- as.list(ce) swirl_out(s()%N%"Entering the following correct answer for you...", skip_after=TRUE) message("> ", e$current.row[, "CorrectAnswer"]) if(e$vis & !is.null(e$val)) { print(e$val) } } e$playing <- FALSE } else if(exists("playing", envir=e, inherits=FALSE) && e$playing) { esc_flag <- FALSE return(TRUE) } if(uses_func("main")(e$expr)[[1]]){ do_main(e) } if(uses_func("restart")(e$expr)[[1]]){ do_restart(e) } if(uses_func("help")(e$expr)[[1]] || uses_func("`?`")(e$expr)[[1]]){ corrans <- e$current.row[, "CorrectAnswer"] corrans_parsed <- parse(text = corrans) uses_help <- uses_func("help")(corrans_parsed)[[1]] || uses_func("`?`")(corrans_parsed)[[1]] if(!uses_help) { esc_flag <- FALSE return(TRUE) } } temp <- mainMenu(e) if(is.logical(temp) && !isTRUE(temp)){ swirl_out(s()%N%"Leaving swirl now. Type swirl() to resume.", skip_after=TRUE) esc_flag <- FALSE return(FALSE) } if(!uses_func("swirl")(e$expr)[[1]] && !uses_func("swirlify")(e$expr)[[1]] && !uses_func("testit")(e$expr)[[1]] && !uses_func("demo_lesson")(e$expr)[[1]] && !uses_func("nxt")(e$expr)[[1]] && isTRUE(customTests$AUTO_DETECT_NEWVAR)) { e$delta <- mergeLists(safeEval(e$expr, e), e$delta) } while(!e$prompt){ if(e$row > min(nrow(e$les), e$test_to)) { if(is(e, "test") || is(e, "datacamp")) { post_finished(e) esc_flag <- FALSE return(FALSE) } saveProgress(e) new_path <- paste(e$progress,".done", sep="") if(file.exists(new_path))file.remove(new_path) file.rename(e$progress, new_path) courseraCheck(e) if(exists("les", e, inherits=FALSE)){ rm("les", envir=e, inherits=FALSE) } if(exists("skips", e)) e$skips <- 0 clearCustomTests() if(isTRUE(getOption("swirl_logging"))){ saveLog(e) } swirl_out(s()%N%"You've reached the end of this lesson! Returning to the main menu...") temp <- mainMenu(e) if(is.logical(temp) && !isTRUE(temp)){ swirl_out(s()%N%"Leaving swirl now. Type swirl() to resume.", skip_after=TRUE) esc_flag <- FALSE return(FALSE) } } if(e$iptr == 1){ post_progress(e) if (!is.null(e$delta)){ e$snapshot <- mergeLists(e$delta,e$snapshot) } e$delta <- list() saveProgress(e) e$current.row <- e$les[e$row,] class(e$current.row) <- c(e$current.row[,"Class"], class(e$current.row)) } e$instr[[e$iptr]](e$current.row, e) for(nm in names(e$snapshot)){ if(exists(nm, globalenv()) && !identical(e$snapshot[[nm]], get(nm, globalenv()))){ e$delta[[nm]] <- get(nm, globalenv()) } } } e$prompt <- FALSE esc_flag <- FALSE return(TRUE) }
library(polmineR) use("polmineR") testthat::context("kwic") test_that( "kwic-method for corpus", { expect_equal( nrow(kwic("REUTERS", query = "oil", pAttribute = "word")@stat), 78L ) expect_equal( nrow(kwic("REUTERS", query = '"barrel.*"', pAttribute = "word")@stat), 26L ) expect_equal( kwic("REUTERS", query = "asdfasdf", pAttribute = "word"), NULL ) expect_equal( kwic("REUTERS", query = '"asdfasdfasdfasd.*"', cqp = TRUE), NULL ) } ) test_that( "kwic-method for partition", { P <- partition("REUTERS", places = "saudi-arabia", regex = TRUE) expect_equal( nrow(kwic(P, query = "oil", pAttribute = "word")@stat), 21L ) expect_equal( nrow(kwic(P, query = '"barrel.*"', cqp = TRUE, pAttribute = "word")@stat), 7L ) expect_equal( kwic(P, query = "asdfasdf", pAttribute = "word"), NULL ) expect_equal( kwic(P, query = '"asdfasdfasdfasd.*"', cqp = TRUE, pAttribute = "word"), NULL ) } ) test_that( "as.character-method for kwic objects", { oil <- corpus("REUTERS") %>% kwic(query = "oil") str <- as.character(oil, fmt = NULL) expect_equal(length(str), 78L) expect_equal(str[1], "its contract prices for crude oil by 1.50 dlrs a barrel") expect_equal( as.character(oil)[1], "its contract prices for crude <i>oil</i> by 1.50 dlrs a barrel" ) expect_equal( as.character(corpus("REUTERS") %>% kwic(query = "oil"), fmt = "<b>%s</b>")[1], "its contract prices for crude <b>oil</b> by 1.50 dlrs a barrel" ) } ) test_that( "indexing kwic objects", { k <- corpus("REUTERS") %>% kwic(query = "oil") k2 <- k[1:5] expect_identical(unique(k2@cpos[["match_id"]]), k2@stat[["match_id"]]) } ) test_that( "subsetting kwic objects", { oil <- corpus("REUTERS") %>% kwic(query = "oil") %>% subset(grepl("prices", right)) expect_identical(unique(oil@cpos[["match_id"]]), oil@stat[["match_id"]]) int_spd <- corpus("GERMAPARLMINI") %>% kwic(query = "Integration") %>% enrich(s_attribute = "party") %>% subset(grepl("SPD", party)) expect_identical(unique(int_spd@stat[["party"]]), "SPD") } ) test_that( "as.data.frame for kwic-method", { int <- corpus("GERMAPARLMINI") %>% kwic(query = "Integration") %>% enrich(s_attributes = c("date", "speaker", "party")) %>% as.data.frame() expect_equal(int[[1]][1], "2009-10-27<br/>Heinz Riesenhuber<br/>NA") } ) test_that( "as.DocumentTermMatrix for kwic-class-object", { oil <- kwic("REUTERS", query = "oil") dtm <- as.DocumentTermMatrix(oil, p_attribute = "word") expect_equal( slam::col_sums(dtm)[["prices"]], nrow(oil@cpos[word == "prices" & direction != 0L]) ) } ) test_that( "kwic: NULL object if positivelist removes all matches", { k <- corpus("GERMAPARLMINI") %>% kwic(query = 'Integration', cqp = FALSE, positivelist = "Messer") expect_equal(is.null(k), TRUE) } ) test_that( "kwic: Apply kwic on partition_bundle", { sp <- corpus("GERMAPARLMINI") %>% subset(date == "2009-11-10") %>% split(s_attribute = "speaker") kwic_table <- kwic(sp, query = "Integration") %>% slot("stat") dt <- kwic_table[, .N, by = "subcorpus_name"] data.table::setorderv(dt, cols = "N", order = -1L) cnt <- count(sp, query = "Integration", s_attributes = "speaker", progress = FALSE) cnt <- cnt[TOTAL > 0L] setorderv(cnt, cols = "TOTAL", order = -1L) expect_equal(dt[["subcorpus_name"]], cnt[["partition"]]) expect_equal(dt[["N"]], cnt[["TOTAL"]]) } )
if (is.null(getGeneric("binOtsu"))) { setGeneric("binOtsu", function(object, ...) standardGeneric("binOtsu")) } if (is.null(getGeneric("closeImage"))) { setGeneric("closeImage", function(object, ...) standardGeneric("closeImage")) } if (is.null(getGeneric("invertImage"))) { setGeneric("invertImage", function(object, ...) standardGeneric("invertImage")) } if (is.null(getGeneric("plot"))) { setGeneric("plot", function(x, y, ...) standardGeneric("plot")) } if (is.null(getGeneric("removeSmallObjects"))) { setGeneric("removeSmallObjects", function(object, ...) standardGeneric("removeSmallObjects")) } if (is.null(getGeneric("smoothImage"))) { setGeneric("smoothImage", function(object, ...) standardGeneric("smoothImage")) } setMethod( f = "invertImage", signature = signature(object = "ms.image"), definition = function(object) { if (.isBinary(object)) { object@values <- (object@values == 0) * 1 } else { object@values <- max(object@values) - object@values } return(object) } ) setMethod("plot", signature = signature(x = "ms.image", y = "missing"), function(x, palette = "inferno") { is.bin <- .isBinary(x) df <- melt(x@values) is.rgb <- all(grepl('^ if (is.bin) { df$value <- factor(df$value) } gg <- ggplot(df, aes_string( x = "X1", y = "X2", fill = "value")) + geom_raster() + xlab("X") + ylab("Y") + { if (is.bin) { scale_fill_grey(start = 0, end = 1) } else if (is.rgb) { scale_fill_identity() } else { scale_fill_viridis(option = palette) } } + coord_fixed() + { if (length(x@name) != 0) { ggtitle(x@name) } } + guides( fill = guide_legend(title = "value"), plot.title = element_text(hjust = 0.5) ) + theme_bw() return(gg) } ) setMethod( f = "smoothImage", signature = signature(object = "ms.image"), definition = function(object, sigma = 2) { if (sigma == 0) { return(object) } if (sigma < 0) { stop("smoothImage: 'sigma' must be positive.") } object@values <- as.matrix(blur(as.im(object@values), sigma = sigma)) if (object@scaled) { object@values <- object@values / max(object@values) } return(object) } ) setMethod( f = "binOtsu", signature = signature(object = "ms.image"), definition = function(object) { if (.isBinary(object)) { bw <- msImage(object@values, "ROI") } else { km <- kmeans(c(object@values), 2) m <- which.min(km$centers) thr <- max(c(object@values)[km$cluster == m]) bw <- (object@values > thr) * 1 bw <- msImage(as.matrix(bw), "ROI") } return(bw) } ) setMethod( f = "closeImage", signature = signature(object = "ms.image"), definition = function(object, kern.size = 5) { if (!.isBinary(object)) { stop("closeImage can be applied on binary images only.") } object@values <- as.matrix(mclosing_square( im = as.cimg(object@values), size = kern.size )) return(object) } ) setMethod( f = "removeSmallObjects", signature = signature(object = "ms.image"), definition = function(object, threshold = 5, border = 3) { if (!.isBinary(object)) { stop("'removeSmallObjects' can be applied on binary images only.") } if (border < 0) { stop("'border' must be positive.") } roiMat <- object@values == 1 if (border > 0) { roiMat <- addBorderImage(roiMat, border = border) } roiMat[roiMat == 0] <- NA roiMat <- as.cimg(roiMat) CC <- label(roiMat) CC <- as.matrix(CC) if (border > 0) { CC <- remBorderImage(CC, border = border) } ux <- unique(c(CC)) ux <- ux[!is.na(ux)] numPixelsObjects <- array(NA, length(ux)) for (i in 1:length(ux)) { numPixelsObjects[i] <- sum(CC == ux[i], na.rm = T) } ux <- ux[numPixelsObjects >= threshold] if (length(ux) == 0) { warning("All objects were removed. Returning the original image.") return(object) } newRoi <- array(NA, prod(dim(object@values))) for (i in 1:length(ux)) { newRoi[CC == ux[i]] <- 1 } newRoi <- matrix(newRoi, nrow(object@values), ncol(object@values)) stopifnot(all(sort(unique(c(newRoi))) == 1)) newRoi[is.na(newRoi)] <- 0 object <- msImage(values = newRoi, name = "ROI", scale = F) return(object) } )
plot.density.lengths <- function (x, main = NULL, xlab = NULL, ylab = "Density", type = "l", zero.line = TRUE, ...) { nk <- length(x) - 2 if (is.null(main)) { main <- "Empirical densities of " if (!x$log) main <- paste(main, "stratum ", sep = "") if (x$log) main <- paste(main, "log-", sep = "") main <- paste(main, "lengths - Direction (", round(x$direction[1], 2), sep = "") if (length(x$direction) > 1) { for (i in 2:length(x$direction)) main <- paste(main, round(x$direction[i], 2), sep = ", ") } main <- paste(main, ")", sep = "") } if (!is.null(xlab)) { if(length(xlab) < nk) xlab <- rep(xlab[1], nk) } else { xlab <- c() for (i in 1:nk) xlab[i] <- paste("N =", x[[i]]$n, " Log-Bandwidth =", formatC(x[[i]]$bw)) } nomi <- names(x)[1:nk] mr <- ceiling(sqrt(nk)) mc <- floor(mr - nk / mr) ly <- matrix(c(rep(1, mr), rep(0, mr), 2:(mr^2+1)), ncol = mr, byrow = TRUE) yl <- c(rep(0, mr + 2)) ly <- cbind(yl, ly, yl)[, -(2+mr+1-mc)] widths <- c(rep(2 - 0.5 * mr, 1), rep(30/mr, mr), rep(4 - 0.5 * mr, 1)) / 4 heights <- c(0.75, 1/3.5, rep(7.5/mr, mr-mc)) ly <- layout(ly, widths = widths, heights = heights, respect = TRUE) mar <- sum(c(0, 1, 0, -0.5, -0.2, rep(0, 4), 0.2, rep(c(-0.1, rep(0, 3)), 2), 0)[1:mr]) mar <- rep(mar, 4) par(mar = mar) plot.new() text(0.5, 0.5, labels = main, cex = 2) for (i in 1:nk) { par(mar = c(5, 4, 3, 2)) plot.default(x[[i]], main = nomi[i], xlab = xlab[i], ylab = ylab, type = type, ...) if (zero.line) abline(h = 0, lwd = 0.1, col = "gray") } }
library(RcppArmadillo) Rcpp::sourceCpp("cpp/Rlapack.cpp") set.seed(123) n <- 5 n_tri <- 50 rl1 <- norm(cx_eig_pair_test(n),"2") rl2 <- norm(cx_qz_test(n),"2") rl3 <- cx_rank_test(n) rl4 <- norm(cx_solve_test(n),"2") rl5 <- norm(cx_solve_band_test(n_tri),"2") rl6 <- norm(cx_pinv_test(n),"2") rl7 <- norm(cx_schur_test(n),"2") expect_equal(rl1, 0) expect_equal(rl2, 0) expect_equal(rl3, n) expect_equal(rl4, 0) expect_equal(rl5, 0) expect_equal(rl6, 1) expect_equal(rl7, 0)
context("pred_df") test_that("perf_df works", { df1 = perf_df(mtcars$mpg, mtcars$am) expect_equal(df1$cutoff, c(Inf, sort(unique(mtcars$mpg), decreasing = TRUE))) expect_true(all(with(df1, fp+tp+tn+fn) == 32)) df2 = perf_df(mtcars$mpg, mtcars$am, quantiles = 4) expect_equal(df2$pp, c(8, 16, 24, 32)) expect_equal(df2$cutoff, sort(mtcars$mpg, decreasing = TRUE)[c(8, 16, 24, 32)]) expect_equal(df2$rpp, c(0.25, 0.5, 0.75, 1)) df3 = perf_df(mtcars$mpg, mtcars$am, quantiles = 10) expect_equal(nrow(df3), 10) df4 = perf_df(mtcars$mpg, mtcars$am, quantiles = 31) expect_equal(nrow(df4), 31) df5 = perf_df(mtcars$mpg, mtcars$am, quantiles = 33) expect_equal(nrow(df5), 32) })
expect_known_output <- function(object, file, update = TRUE, ..., info = NULL, label = NULL, print = FALSE, width = 80) { edition_deprecate(3, "expect_known_output()", "Please use `expect_snapshot_output()` instead" ) act <- list() act$quo <- enquo(object) act$lab <- label %||% quo_label(act$quo) act <- append(act, eval_with_output(object, print = print, width = width)) compare_file(file, act$out, update = update, info = info, ...) invisible(act$val) } compare_file <- function(path, lines, ..., update = TRUE, info = NULL) { if (!file.exists(path)) { warning("Creating reference output", call. = FALSE) brio::write_lines(lines, path) succeed() return() } old_lines <- brio::read_lines(path) if (update) { brio::write_lines(lines, path) if (!all_utf8(lines)) { warning("New reference output is not UTF-8 encoded", call. = FALSE) } } if (!all_utf8(old_lines)) { warning("Reference output is not UTF-8 encoded", call. = FALSE) } comp <- waldo_compare( x = old_lines, x_arg = "old", y = lines, y_arg = "new", ... ) expect( length(comp) == 0, sprintf( "Results have changed from known value recorded in %s.\n\n%s", encodeString(path, quote = "'"), paste0(comp, collapse = "\n\n") ), info = info, trace_env = caller_env() ) } expect_output_file <- function(object, file, update = TRUE, ..., info = NULL, label = NULL, print = FALSE, width = 80) { edition_deprecate(3, "expect_output_file()", "Please use `expect_snapshot_output()` instead" ) act <- list() act$quo <- enquo(object) act$lab <- label %||% quo_label(act$quo) act <- append(act, eval_with_output(object, print = print, width = width)) compare_file(file, act$out, update = update, info = info, ...) invisible(act$val) } expect_known_value <- function(object, file, update = TRUE, ..., info = NULL, label = NULL, version = 2) { edition_deprecate(3, "expect_known_value()", "Please use `expect_snapshot_value()` instead" ) act <- quasi_label(enquo(object), label, arg = "object") if (!file.exists(file)) { warning("Creating reference value", call. = FALSE) saveRDS(object, file, version = version) succeed() } else { ref_val <- readRDS(file) comp <- compare(act$val, ref_val, ...) if (update && !comp$equal) { saveRDS(act$val, file, version = version) } expect( comp$equal, sprintf( "%s has changed from known value recorded in %s.\n%s", act$lab, encodeString(file, quote = "'"), comp$message ), info = info ) } invisible(act$value) } expect_equal_to_reference <- function(..., update = FALSE) { edition_deprecate(3, "expect_equal_to_reference()", "Please use `expect_snapshot_value()` instead" ) expect_known_value(..., update = update) } expect_known_hash <- function(object, hash = NULL) { edition_deprecate(3, "expect_known_hash()", "Please use `expect_snapshot_value()` instead" ) act <- quasi_label(enquo(object), arg = "object") act_hash <- digest::digest(act$val) if (!is.null(hash)) { act_hash <- substr(act_hash, 1, nchar(hash)) } if (is.null(hash)) { warning(paste0("No recorded hash: use ", substr(act_hash, 1, 10))) succeed() } else { expect( hash == act_hash, sprintf("Value hashes to %s, not %s", act_hash, hash) ) } invisible(act$value) } all_utf8 <- function(x) { ! any(is.na(iconv(x, "UTF-8", "UTF-8"))) }
sample.saver <- function(x, rep = 1, efficiency.known = FALSE, seed = NULL) { if (!is.null(x$alpha)) { return(sample.saver.old(x, rep, efficiency.known, seed)) } ncells <- ncol(x$estimate) ngenes <- nrow(x$estimate) cell.names <- colnames(x$estimate) gene.names <- rownames(x$estimate) rep <- as.integer(rep) if (rep <= 0) { stop("rep must be a positive integer.") } if (!is.null(seed)) { set.seed(seed) } if (rep == 1) { if (efficiency.known) { samp <- t(sapply(1:ngenes, function(i) rnbinom(ncells, mu = x$estimate[i, ], size = x$estimate[i, ]^2/x$se[i, ]^2))) } else { samp <- t(sapply(1:ngenes, function(i) rgamma(ncells, x$estimate[i, ]^2/x$se[i, ]^2, x$estimate[i, ]/x$se[i, ]^2))) samp <- round(samp, 3) } rownames(samp) <- gene.names colnames(samp) <- cell.names } else { samp <- vector("list", rep) for (j in 1:rep) { if (efficiency.known) { samp[[j]] <- t(sapply(1:ngenes, function(i) rnbinom(ncells, mu = x$estimate[i, ], size = x$estimate[i, ]^2/x$se[i, ]^2))) } else { samp[[j]] <- t(sapply(1:ngenes, function(i) rgamma(ncells, x$estimate[i, ]^2/x$se[i, ]^2, x$estimate[i, ]/x$se[i, ]^2))) samp[[j]] <- round(samp[[j]], 3) } rownames(samp[[j]]) <- gene.names colnames(samp[[j]]) <- cell.names } } return(samp) }
context("Participant initiating and adding graphemes, and fetching basic information about them.") library(synr) test_that("has_graphemes() returns False if there are no graphemes", { p <- Participant$new() expect_false(p$has_graphemes()) }) test_that("add_grapheme() raises warning if passed grapheme has no associated symbol", { p <- Participant$new() g <- Grapheme$new() expect_error(p$add_grapheme(g)) }) test_that("add_graphemes() adds all passed graphemes", { p <- Participant$new() g1 <- Grapheme$new(symbol='a') g2 <- Grapheme$new(symbol='b') g3 <- Grapheme$new(symbol='monday') g_list <- list(g1, g2, g3) p$add_graphemes(g_list) expect_equal(p$graphemes[[2]], g_list[[2]]) }) test_that("has_graphemes() returns True if there are graphemes", { p <- Participant$new() g <- Grapheme$new(symbol='a') p$add_grapheme(g) expect_true(p$has_graphemes()) }) test_that("get_symbols() returns correct set of symbols", { p <- Participant$new() g1 <- Grapheme$new(symbol='a') g2 <- Grapheme$new(symbol='b') g3 <- Grapheme$new(symbol='monday') p$add_grapheme(g1) p$add_grapheme(g2) p$add_grapheme(g3) expect_equal(p$get_symbols(), c('a', 'b', 'monday')) }) test_that("get_number_all_colored_graphemes returns 3 for participant with 3 all-valid response colors graphemes", { p <- Participant$new() g1 <- Grapheme$new(symbol='a') g1$set_colors(c(" g2 <- Grapheme$new(symbol='b') g2$set_colors(c(" g3 <- Grapheme$new(symbol='monday') g3$set_colors(c(" g_list <- list(g1, g2, g3) p$add_graphemes(g_list) expect_equal(p$get_number_all_colored_graphemes(), 3) }) test_that("get_number_all_colored_graphemes returns 0 for participant with no graphemes", { p <- Participant$new() expect_equal(p$get_number_all_colored_graphemes(), 0) }) test_that("get_number_all_colored_graphemes returns 0 for participant with only graphemes without responses", { p <- Participant$new() g1 <- Grapheme$new(symbol='a') g2 <- Grapheme$new(symbol='b') g3 <- Grapheme$new(symbol='monday') g_list <- list(g1, g2, g3) p$add_graphemes(g_list) expect_equal(p$get_number_all_colored_graphemes(), 0) }) test_that("get_number_all_colored_graphemes returns 0 for participant with only graphemes with invalid responses", { p <- Participant$new() g1 <- Grapheme$new(symbol='a') g1$set_colors(c(NA, NA, NA, NA), "Luv") g2 <- Grapheme$new(symbol='b') g2$set_colors(c(NA, NA, NA, NA), "Luv") g3 <- Grapheme$new(symbol='monday') g3$set_colors(c(NA, NA, NA, NA), "Luv") g_list <- list(g1, g2, g3) p$add_graphemes(g_list) expect_equal(p$get_number_all_colored_graphemes(), 0) }) test_that(paste0( "get_nonna_color_resp_mat produces expected matrix ", "for participant with 12 valid responses" ), { p <- Participant$new() g1 <- Grapheme$new(symbol='a') g1$set_colors(c(" g2 <- Grapheme$new(symbol='b') g2$set_colors(c(" g3 <- Grapheme$new(symbol='monday') g3$set_colors(c(" g_list <- list(g1, g2, g3) p$add_graphemes(g_list) col_mat <- p$get_nonna_color_resp_mat() expect_equal(nrow(col_mat), 12) })
context("test-message") test_that("printf works", { expect_identical(capture.output(printf("My name is %s.", "Florian")), "My name is Florian.") })
jackmsatpop <- function(datafile, ndigit=3, interval=1, nrepet=100, richness=F) { input=read.delim(file=datafile, sep='\r') noext= gsub("[.].*$","",datafile) popcount=rbind(which(input == 'pop', arr.ind=T),which(input=='Pop',arr.ind=T),which(input=='POP',arr.ind=T)) popcount=popcount[,1] npops=NROW(popcount) popcount=sort(popcount) nloci=popcount[1]-1 popsizes=vector(length=npops) for (h in 1:npops) { if (h<npops) popsizes[h]=popcount[h+1]-popcount[h]-1 if (h==npops) popsizes[h]=nrow(input)-popcount[h] } n.individuals=sum(popsizes) datamatrix=matrix(NA, n.individuals, nloci*2) input2=input[-popcount,] input3=input2[-(1:nloci)] for (b in 1:n.individuals) { inddata=input3[b] inddata=as.vector(inddata) inddata=gsub( "[^[:alnum:]]", "", inddata) total=nchar(inddata) diff=total-(ndigit*2*nloci) for (x in 1:nloci) { datamatrix[b,((2*x)-1)]=substr(inddata,diff+(2*ndigit*(x-1))+(ndigit-(ndigit-1)), diff+(2*ndigit*(x-1))+ndigit) datamatrix[b,(2*x)]=substr(inddata,diff+(2*ndigit*(x-1))+ndigit+1, diff+(2*ndigit*(x-1))+(2*ndigit)) } } n.col=ncol(datamatrix) npop=NROW(popsizes) matrichness=NULL matrichnessDev=NULL for (v in 1:npop) { no=v if (v==1) first=1 if (v>1) first=sum(popsizes[1:(no-1)])+1 last=sum(popsizes[1:no]) pop=datamatrix[first:last,] compute=jackmsat(pop, interval, nrepet, richness) name=paste('pop_',no, '.txt', sep='') Means2=t(compute$Means) Stdev2=t(compute$Stdev) if (richness==F) write.table(Means2, file=name, quote=F, sep='\t', row.names=F, col.names=F) if (richness==F) write.table(Stdev2, file=name, append=T, quote=F, sep='\t', row.names=F, col.names=F) if (richness==T) matrichness=cbind(matrichness, compute$Means[-1,-1]) if (richness==T) matrichnessDev=cbind(matrichnessDev, compute$Stdev[-1,-1]) } popnames=c(1:npop) if (richness==T) { matrichness=rbind(popnames, matrichness) matrichnessDev=rbind(popnames, matrichnessDev) filename=paste('Richness for ', interval, 'ind.txt') rows2=c('',compute$row.names) matrichness2=t(matrichness) matrichness2=rbind(rows2, matrichness2) matrichnessDev2=t(matrichnessDev) matrichnessDev2=rbind(rows2, matrichnessDev2) write.table(matrichness2, file=filename, quote=F, sep='\t', row.names=F, col.names=F) write.table(matrichnessDev2, file=filename, append=T, quote=F, sep='\t', row.names=F, col.names=F) }}
boss <- function(x, y, maxstep=min(nrow(x)-intercept-1, ncol(x)), intercept=TRUE, hdf.ic.boss=TRUE, mu=NULL, sigma=NULL, ...){ n = dim(x)[1] p = dim(x)[2] if(maxstep > min(nrow(x)-intercept-1, ncol(x))){ warning('Specified maximum number of steps is larger than expected.') maxstep = min(nrow(x)-intercept-1, ncol(x)) } if(!is.null(dim(y))){ if(dim(y)[2] == 1){ y = as.numeric(y) }else{ stop('Multiple dependent variables are not supported.') } } std_result = std(x, y, intercept) x = std_result$x_std y = std_result$y_std mean_x = std_result$mean_x mean_y = std_result$mean_y sd_demanedx = std_result$sd_demeanedx if(hdf.ic.boss & maxstep < p){ guideQR_result = guideQR(x, y, maxstep, TRUE) Q = guideQR_result$Q[, 1:maxstep] R = guideQR_result$R[1:maxstep, 1:maxstep] }else{ guideQR_result = guideQR(x, y, maxstep, FALSE) Q = guideQR_result$Q R = guideQR_result$R } steps_x = as.numeric(guideQR_result$steps) z = t(Q) %*% y trans.q.to.x <- function(beta.q){ beta.x = Matrix::Matrix(0, nrow=p, ncol=maxstep, sparse = TRUE) beta.x[steps_x, ] = diag(1/sd_demanedx[steps_x]) %*% backsolve(R, beta.q) beta.x = cbind(0, beta.x) if(intercept){ beta.x = rbind(Matrix::Matrix(mean_y - mean_x %*% beta.x, sparse=TRUE), beta.x) } return(beta.x) } beta_q = matrix(rep(z, maxstep), nrow=maxstep, byrow=FALSE) beta_q = beta_q * upper.tri(beta_q, diag=TRUE) beta_fs = trans.q.to.x(beta_q) order_q = order(-z^2) steps_q = steps_x[order_q] row_i = rep(order_q, times=seq(maxstep,1)) col_j = unlist(lapply(1:maxstep, function(xx){seq(xx,maxstep)})) beta_q = Matrix::sparseMatrix(row_i, col_j, x=z[row_i], dims=c(maxstep, maxstep)) beta_boss = trans.q.to.x(beta_q) if(!hdf.ic.boss){ hdf = IC_result = NULL }else{ if(n > p){ hdf_result = calc.hdf(guideQR_result$Q, y, sigma, mu, x=NULL) }else{ hdf_result = calc.hdf(guideQR_result$Q, y, sigma, mu, x) } hdf = hdf_result$hdf[1:(maxstep+1)] sigma = hdf_result$sigma if(intercept){ hdf = hdf + 1 } IC_result = calc.ic.all(cbind(0,beta_q), Q, y, hdf, sigma) } varnames = colnames(x) if(is.null(varnames)){ varnames = paste0('X', seq(1,p)) } if(intercept){ rownames(beta_fs) = rownames(beta_boss) = c('intercept', varnames) }else{ rownames(beta_fs) = rownames(beta_boss) = varnames } names(steps_x) = varnames[steps_x] names(steps_q) = varnames[steps_q] out = list(beta_fs=beta_fs, beta_boss=beta_boss, steps_x=steps_x, steps_q=steps_q, hdf_boss=hdf, IC_boss=IC_result, sigma=sigma, call=list(intercept=intercept)) class(out) = 'boss' invisible(out) } coef.boss <- function(object, ic=c('aicc','bicc','aic','bic','gcv','cp'), select.boss=NULL, ...){ if(is.null(select.boss)){ if(is.null(object$IC_boss)){ warning("boss was called with argument 'hdf.ic.boss=FALSE', the full coef matrix is returned here") select.boss = 1:ncol(object$beta_boss) }else{ ic = match.arg(ic) select.boss = which.min(object$IC_boss[[ic]]) } }else if(select.boss == 0){ select.boss = 1:ncol(object$select.boss) } select.boss[select.boss > ncol(object$beta_boss)] = ncol(object$beta_boss) beta_boss_opt = object$beta_boss[, select.boss, drop=FALSE] return(beta_boss_opt) } predict.boss <- function(object, newx, ...){ beta_boss_opt = coef(object, ...) if(is.null(dim(newx))){ newx = matrix(newx, nrow=1) }else if(dim(newx)[2] == 1){ newx = t(newx) } if(object$call$intercept){ newx = cbind(rep(1,nrow(newx)), newx) } if(is.null(beta_boss_opt)){ mu_boss_opt = NULL }else{ if(ncol(newx) != nrow(beta_boss_opt)){ stop('Mismatch dimension of newx and coef for BOSS. Note do NOT add 1 to newx when intercept=TRUE') }else{ mu_boss_opt = newx %*% beta_boss_opt } } return(mu_boss_opt) }
NgetIntermediateResults <- function (obj, offset = NULL, convert = TRUE){ if (!(class(obj) == "NeosJob")) { stop("\nObject 'obj' is not of class 'NeosJob'.\n") } call <- match.call() jobnumber <- obj@jobnumber password <- obj@password nc <- obj@nc if(is.null(offset)){ offset <- as.integer(0) } else { offset <- as.integer(offset) } ans <- xml.rpc(url = nc@url, method = "getIntermediateResults", .args = list(jobnumber = jobnumber, password = password, offset = offset), .convert = FALSE, .opts = nc@curlopts, .curl = nc@curlhandle) tmp <- xmlToList(xmlRoot(xmlTreeParse(ans))) offset <- as.integer(tmp[2, ]) if (convert) { tmp1 <- tmp[1, ] if(!is.null(tmp1$params)){ tmp1 <- gsub("\\n", "", tmp1) class(tmp1) <- "base64" ans <- base64(tmp1) } else { ans <- "\nNothing left to return from NEOS.\n" } } res <- new("NeosOff", ans = ans, offset = offset, jobnumber = jobnumber, password = password, method = "getIntermediateResults", call = call, nc = nc) return(res) }
SuperLearner <- function(Y, X, newX = NULL, family = gaussian(), SL.library, method = 'method.NNLS', id = NULL, verbose = FALSE, control = list(), cvControl = list(), obsWeights = NULL, env = parent.frame()) { time_start = proc.time() if (is.character(method)) { if (exists(method, mode = 'list')) { method <- get(method, mode = 'list') } else if (exists(method, mode = 'function')) { method <- get(method, mode = 'function')() } } else if (is.function(method)) { method <- method() } if(!is.list(method)) { stop("method is not in the appropriate format. Check out help('method.template')") } if(!is.null(method$require)) { sapply(method$require, function(x) require(force(x), character.only = TRUE)) } control <- do.call('SuperLearner.control', control) cvControl <- do.call('SuperLearner.CV.control', cvControl) library <- .createLibrary(SL.library) .check.SL.library(library = c(unique(library$library$predAlgorithm), library$screenAlgorithm)) call <- match.call(expand.dots = TRUE) if(!inherits(X, 'data.frame')) message('X is not a data frame. Check the algorithms in SL.library to make sure they are compatible with non data.frame inputs') varNames <- colnames(X) N <- dim(X)[1L] p <- dim(X)[2L] k <- nrow(library$library) kScreen <- length(library$screenAlgorithm) Z <- matrix(NA, N, k) libraryNames <- paste(library$library$predAlgorithm, library$screenAlgorithm[library$library$rowScreen], sep="_") if(p < 2 & !identical(library$screenAlgorithm, "All")) { warning('Screening algorithms specified in combination with single-column X.') } fitLibEnv <- new.env() assign('fitLibrary', vector('list', length = k), envir = fitLibEnv) assign('libraryNames', libraryNames, envir = fitLibEnv) evalq(names(fitLibrary) <- libraryNames, envir = fitLibEnv) errorsInCVLibrary <- rep(0, k) errorsInLibrary <- rep(0, k) if(is.null(newX)) { newX <- X } if(!identical(colnames(X), colnames(newX))) { stop("The variable names and order in newX must be identical to the variable names and order in X") } if (sum(is.na(X)) > 0 | sum(is.na(newX)) > 0 | sum(is.na(Y)) > 0) { stop("missing data is currently not supported. Check Y, X, and newX for missing values") } if (!is.numeric(Y)) { stop("the outcome Y must be a numeric vector") } if(is.character(family)) family <- get(family, mode="function", envir=parent.frame()) if(is.function(family)) family <- family() if (is.null(family$family)) { print(family) stop("'family' not recognized") } if (family$family != "binomial" & isTRUE("cvAUC" %in% method$require)){ stop("'method.AUC' is designed for the 'binomial' family only") } validRows <- CVFolds(N = N, id = id, Y = Y, cvControl = cvControl) if(is.null(id)) { id <- seq(N) } if(!identical(length(id), N)) { stop("id vector must have the same dimension as Y") } if(is.null(obsWeights)) { obsWeights <- rep(1, N) } if(!identical(length(obsWeights), N)) { stop("obsWeights vector must have the same dimension as Y") } .crossValFUN <- function(valid, Y, dataX, id, obsWeights, library, kScreen, k, p, libraryNames, saveCVFitLibrary) { tempLearn <- dataX[-valid, , drop = FALSE] tempOutcome <- Y[-valid] tempValid <- dataX[valid, , drop = FALSE] tempWhichScreen <- matrix(NA, nrow = kScreen, ncol = p) tempId <- id[-valid] tempObsWeights <- obsWeights[-valid] for(s in seq(kScreen)) { screen_fn = get(library$screenAlgorithm[s], envir = env) testScreen <- try(do.call(screen_fn, list(Y = tempOutcome, X = tempLearn, family = family, id = tempId, obsWeights = tempObsWeights))) if(inherits(testScreen, "try-error")) { warning(paste("replacing failed screening algorithm,", library$screenAlgorithm[s], ", with All()", "\n ")) tempWhichScreen[s, ] <- TRUE } else { tempWhichScreen[s, ] <- testScreen } if(verbose) { message(paste("Number of covariates in ", library$screenAlgorithm[s], " is: ", sum(tempWhichScreen[s, ]), sep = "")) } } out <- matrix(NA, nrow = nrow(tempValid), ncol = k) if(saveCVFitLibrary){ model_out <- vector(mode = "list", length = k) }else{ model_out <- NULL } for(s in seq(k)) { pred_fn = get(library$library$predAlgorithm[s], envir = env) testAlg <- try(do.call(pred_fn, list(Y = tempOutcome, X = subset(tempLearn, select = tempWhichScreen[library$library$rowScreen[s], ], drop=FALSE), newX = subset(tempValid, select = tempWhichScreen[library$library$rowScreen[s], ], drop=FALSE), family = family, id = tempId, obsWeights = tempObsWeights))) if(inherits(testAlg, "try-error")) { warning(paste("Error in algorithm", library$library$predAlgorithm[s], "\n The Algorithm will be removed from the Super Learner (i.e. given weight 0) \n" )) } else { out[, s] <- testAlg$pred if(saveCVFitLibrary){ model_out[[s]] <- testAlg$fit } } if (verbose) message(paste("CV", libraryNames[s])) } if(saveCVFitLibrary){ names(model_out) <- libraryNames } invisible(list(out = out, model_out = model_out)) } time_train_start = proc.time() crossValFUN_out <- lapply(validRows, FUN = .crossValFUN, Y = Y, dataX = X, id = id, obsWeights = obsWeights, library = library, kScreen = kScreen, k = k, p = p, libraryNames = libraryNames, saveCVFitLibrary = control$saveCVFitLibrary) Z[unlist(validRows, use.names = FALSE), ] <- do.call('rbind', lapply(crossValFUN_out, "[[", "out")) if(control$saveCVFitLibrary){ cvFitLibrary <- lapply(crossValFUN_out, "[[", "model_out") }else{ cvFitLibrary <- NULL } errorsInCVLibrary <- apply(Z, 2, function(x) anyNA(x)) if (sum(errorsInCVLibrary) > 0) { Z[, as.logical(errorsInCVLibrary)] <- 0 } if (all(Z == 0)) { stop("All algorithms dropped from library") } getCoef <- method$computeCoef(Z = Z, Y = Y, libraryNames = libraryNames, obsWeights = obsWeights, control = control, verbose = verbose, errorsInLibrary = errorsInCVLibrary) coef <- getCoef$coef names(coef) <- libraryNames time_train = proc.time() - time_train_start if (!("optimizer" %in% names(getCoef))) { getCoef["optimizer"] <- NA } m <- dim(newX)[1L] predY <- matrix(NA, nrow = m, ncol = k) .screenFun <- function(fun, list) { screen_fn = get(fun, envir = env) testScreen <- try(do.call(screen_fn, list)) if (inherits(testScreen, "try-error")) { warning(paste("replacing failed screening algorithm,", fun, ", with All() in full data", "\n ")) out <- rep(TRUE, ncol(list$X)) } else { out <- testScreen } return(out) } time_predict_start = proc.time() whichScreen <- sapply(library$screenAlgorithm, FUN = .screenFun, list = list(Y = Y, X = X, family = family, id = id, obsWeights = obsWeights), simplify = FALSE) whichScreen <- do.call(rbind, whichScreen) .predFun <- function(index, lib, Y, dataX, newX, whichScreen, family, id, obsWeights, verbose, control, libraryNames) { pred_fn = get(lib$predAlgorithm[index], envir = env) testAlg <- try(do.call(pred_fn, list(Y = Y, X = subset(dataX, select = whichScreen[lib$rowScreen[index], ], drop=FALSE), newX = subset(newX, select = whichScreen[lib$rowScreen[index], ], drop=FALSE), family = family, id = id, obsWeights = obsWeights))) if (inherits(testAlg, "try-error")) { warning(paste("Error in algorithm", lib$predAlgorithm[index], " on full data", "\n The Algorithm will be removed from the Super Learner (i.e. given weight 0) \n" )) out <- rep.int(NA, times = nrow(newX)) } else { out <- testAlg$pred if (control$saveFitLibrary) { eval(bquote(fitLibrary[[.(index)]] <- .(testAlg$fit)), envir = fitLibEnv) } } if (verbose) { message(paste("full", libraryNames[index])) } invisible(out) } predY <- do.call('cbind', lapply(seq(k), FUN = .predFun, lib = library$library, Y = Y, dataX = X, newX = newX, whichScreen = whichScreen, family = family, id = id, obsWeights = obsWeights, verbose = verbose, control = control, libraryNames = libraryNames)) errorsInLibrary <- apply(predY, 2, function(algorithm) anyNA(algorithm)) if (sum(errorsInLibrary) > 0) { if (sum(coef[as.logical(errorsInLibrary)]) > 0) { warning(paste0("Re-running estimation of coefficients removing failed algorithm(s)\n", "Original coefficients are: \n", paste(coef, collapse = ", "), "\n")) Z[, as.logical(errorsInLibrary)] <- 0 if (all(Z == 0)) { stop("All algorithms dropped from library") } getCoef <- method$computeCoef(Z = Z, Y = Y, libraryNames = libraryNames, obsWeights = obsWeights, control = control, verbose = verbose, errorsInLibrary = errorsInLibrary) coef <- getCoef$coef names(coef) <- libraryNames } else { warning("Coefficients already 0 for all failed algorithm(s)") } } getPred <- method$computePred(predY = predY, coef = coef, control = control) time_predict = proc.time() - time_predict_start colnames(predY) <- libraryNames if(sum(errorsInCVLibrary) > 0) { getCoef$cvRisk[as.logical(errorsInCVLibrary)] <- NA } time_end = proc.time() times = list(everything = time_end - time_start, train = time_train, predict = time_predict) out <- list( call = call, libraryNames = libraryNames, SL.library = library, SL.predict = getPred, coef = coef, library.predict = predY, Z = Z, cvRisk = getCoef$cvRisk, family = family, fitLibrary = get('fitLibrary', envir = fitLibEnv), cvFitLibrary = cvFitLibrary, varNames = varNames, validRows = validRows, method = method, whichScreen = whichScreen, control = control, cvControl = cvControl, errorsInCVLibrary = errorsInCVLibrary, errorsInLibrary = errorsInLibrary, metaOptimizer = getCoef$optimizer, env = env, times = times ) class(out) <- c("SuperLearner") return(out) }
format_dnf <- function(dnf) { return(Reduce(function(x, y) {paste(x, y, sep = " + ")}, dnf)) } xyplot <- function(x, y, data, labels=FALSE, main.diagonal=TRUE, anti.diagonal=FALSE) { if (is.character(x)) { xname <- format_dnf(x) } else { xname <- "" } if (is.character(y)) { yname <- format_dnf(y) } else { yname <- "" } x <- evaluate_dnf(data, x) y <- evaluate_dnf(data, y) if (labels) { casenames <- rownames(data) } pl <- ggplot2::qplot(x,y) + ggplot2::scale_x_continuous(limits = c(0, 1), name = xname) + ggplot2::scale_y_continuous(limits = c(0, 1), name = yname) if (labels) { pl <- directlabels::direct.label(pl + ggplot2::geom_point(ggplot2::aes(colour=casenames))) } if (main.diagonal) { pl <- pl + ggplot2::geom_segment(ggplot2::aes(x = 0, y = 0, xend = 1, yend = 1)) } if (anti.diagonal) { pl <- pl + ggplot2::geom_segment(ggplot2::aes(x = 0, y = 1, xend = 1, yend = 0)) } return(pl) } plot.qca <- function(x, ...) { xyplot(toupper(x$tt$options$outcome), x$solution[[1]], x$tt$initial.data, ...) }
require(fitdistrplus) data("fremale") fremale.cens <- Surv2fitdistcens(fremale$AgeIn, fremale$AgeOut, fremale$Death) f1 <- fitdistcens(fremale.cens, "norm") f2 <- fitdistcens(fremale.cens, "logis") f3 <- fitdistcens(fremale.cens, "cauchy") cdfcompcens(list(f1, f2, f3)) sapply(list(f1, f2, f3), logLik)
NULL path_is_not <- function(thing, var = "x") { function(call, env) { paste0("Path '", eval(call[[var]], env), "' is not ", thing) } } NULL is.dir <- function(path) { assert_that(is.string(path), file.exists(path)) file.info(path)$isdir } on_failure(is.dir) <- path_is_not("a directory", "path") is.writeable <- function(path) { assert_that(is.string(path), file.exists(path)) file.access(path, mode = 2)[[1]] == 0 } on_failure(is.writeable) <- path_is_not("writeable", "path") is.readable <- function(path) { assert_that(is.string(path), file.exists(path)) file.access(path, mode = 4)[[1]] == 0 } on_failure(is.readable) <- path_is_not("readable", "path") has_extension <- function(path, ext) { tools::file_ext(path) == ext } on_failure(has_extension) <- function(call, env) { path <- eval(call$path, env) ext <- eval(call$ext, env) paste0("File '", basename(path), "' does not have extension ", ext) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(msaeRB)
bf.approx<-function(z,param,size,k2,oa2){ bm=0 vm2=0 sumw=0 log_ABF=0 phi2 <- oa2*k2 for (j in 1:size) { beta <- param[z,2*(j-1)+1] ds2 <- param[z,2*(j-1)+2]**2 w <- 1/(ds2+phi2) bm = bm + beta*w sumw = sumw + w vm2 = vm2 + w log_ABF<-log_ABF+0.5*log(ds2*w)+0.5*(beta^2/ds2)*(phi2*w) } bm=bm/sumw vm2<-1/vm2 log_ABF<-log_ABF+0.5*log(vm2/(oa2+vm2))+0.5*((bm^2)/vm2)*(oa2/(vm2+oa2)) return(log_ABF) }
qDiptab <- diptest:::rdRDS("extraData", "qDiptab.rds")
rAC <- function(name = c("clayton", "gumbel", "frank", "BB9", "GIG"), n, d, theta){ name <- match.arg(name) illegalpar <- switch(name, clayton = (theta < 0), gumbel = (theta < 1), frank = (theta < 0), BB9 = ((theta[1] < 1) | (theta[2] < 0)), GIG = ((theta[2] < 0) | (theta[3] < 0) | ((theta[1]>0) & (theta[3]==0)) | ((theta[1]<0) & (theta[2]==0)))) if(illegalpar) stop("Illegal parameter value") independence <- switch(name, clayton = (theta == 0), gumbel = (theta == 1), frank = (theta == 0), BB9 = (theta[1] == 1), GIG=FALSE) U <- runif(n * d) U <- matrix(U, nrow = n, ncol = d) if(independence) return(U) Y <- switch(name, clayton = rgamma(n, 1/ theta), gumbel = rstable(n, 1/ theta) * (cos(pi / (2 * theta)))^theta, frank = rFrankMix(n, theta), BB9 = rBB9Mix(n, theta), GIG = rGIG(n, theta[1], theta[2], theta[3])) Y <- matrix(Y, nrow = n, ncol = d) phi.inverse <- switch(name, clayton = function(t, theta){ (1 + t)^(-1/theta) }, gumbel = function(t, theta){ exp( - t^(1/theta)) }, frank = function(t, theta){ (-1 / theta) * log(1 - (1 - exp( - theta)) * exp( - t)) }, BB9 = function(t, theta){ exp( - (theta[2]^theta[1] + t)^(1/theta[1]) + theta[2]) }, GIG = function(t, theta){ lambda <- theta[1] chi <- theta[2] psi <- theta[3] if(chi==0){ out <- (1 + 2 * t / psi)^(-lambda) } else if(psi==0){ out <- 2^(lambda + 1) * exp(log(besselK(x = sqrt(2*chi*t), nu = lambda, expon.scaled = FALSE)) - lambda * log(2 * chi * t) / 2) / gamma(-lambda) } else { out <- exp(log(besselK(x = sqrt(chi * (psi + 2 * t)), nu = lambda, expon.scaled = FALSE)) + lambda * log(chi * psi) / 2 - log(besselK(x = sqrt(chi*psi), nu = lambda, expon.scaled = FALSE)) - lambda * log(chi * (psi + 2 * t)) / 2) } out } ) phi.inverse( - log(U) / Y, theta) } rACp <- function(name = c("clayton", "gumbel", "frank", "BB9", "GIG"), n, d, theta, A){ name <- match.arg(name) p <- length(theta) if ((dim(A)[1] != d) | (dim(A)[2] !=p)) stop("\nWeight matrix 'A' has incorrect dimensions.\n") sumcheck <- apply(A, 1, sum) - rep(1,d) if (sum(sumcheck^2) != 0) stop("\nWeights do not sum to one.\n") for (j in 1:p){ tmp <- rAC(name = name, n = n, d = d, theta = theta[j]) Amat <- matrix(A[, j], ncol = d, nrow = n, byrow = TRUE) tmp <- tmp^(1 / Amat) eval(parse(text = paste("U", j, " <- tmp", sep=""))) } args <- paste("U", 1:p, sep = "", collapse = ",") result <- parse(text = paste("pmax(", args, ")")) eval(result) } rcopula.gumbel <- function(n, theta, d){ rAC("gumbel", n, d, theta) } rcopula.clayton <- function(n, theta, d){ rAC("clayton", n, d, theta) } rcopula.frank <- function(n, theta, d){ rAC("frank", n, d, theta) } rstable <- function(n, alpha, beta = 1){ t0 <- atan(beta * tan((pi * alpha) / 2)) / alpha Theta <- pi * (runif(n) - 0.5) W <- - log(runif(n)) term1 <- sin(alpha * (t0 + Theta)) / (cos(alpha * t0) * cos(Theta))^(1 / alpha) term2 <- ((cos(alpha * t0 + (alpha - 1) * Theta)) / W)^((1 - alpha) / alpha) term1 * term2 } rFrankMix <- function(n, theta){ rfrank(n, theta) } rBB9Mix <- function(n, theta){ out <- rep(NA, n) for (i in 1:n){ X <- 0 U <- 2 while (U > exp(-X * theta[2]^theta[1])){ X <- rstable(1, 1 / theta[1]) U <- runif(1) } out[i] <- X } out } rcopula.Gumbel2Gp <- function(n = 1000, gpsizes = c(2, 2), theta =c(2, 3, 5)){ Y <- rstable(n, 1 / theta[1]) * (cos(pi / (2 * theta[1])))^theta[1] innerU1 <- rcopula.gumbel(n, theta[2] / theta[1], gpsizes[1]) innerU2 <- rcopula.gumbel(n, theta[3] / theta[1], gpsizes[2]) U <- cbind(innerU1, innerU2) Y <- matrix(Y, nrow = n, ncol = sum(gpsizes)) out <- exp( - ( - log(U) / Y)^(1 / theta[1])) out } rcopula.GumbelNested <- function(n, theta){ d <- length(theta) + 1 if (d==2) out <- rcopula.gumbel(n, theta, d) else if (d > 2){ Y <- rstable(n, 1 / theta[1]) * (cos(pi / (2 * theta[1])))^theta[1] U <- runif(n) innerU <- rcopula.GumbelNested(n, theta[-1] / theta[1]) U <- cbind(U, innerU) Y <- matrix(Y, nrow = n, ncol = d) out <- exp( - ( - log(U) / Y)^(1 / theta[1])) } out } dcopula.AC <- function(u, theta, name = c("clayton", "gumbel"), log = TRUE){ name <- match.arg(name) d <- dim(u)[2] if ((name == "gumbel") & (d > 2)) stop("\nOnly bivariate Gumbel implemented.\n") illegalpar <- switch(name, clayton = (theta <= 0), gumbel = (theta <= 1)) if(illegalpar){ out <- NA } else { phi <- switch(name, clayton = function(u, theta){(u^(-theta) - 1) / theta}, gumbel = function(u, theta){(-log(u))^theta}) lnegphidash <- switch(name, clayton = function(u, theta){(-theta - 1)*log(u)}, gumbel = function(u, theta){log(theta) + (theta - 1) * log(-log(u)) -log(u)}) loggfunc <- switch(name, clayton = function(t, d, theta){d * log(theta) + sum(log((1:d) +1 /theta - 1))-(d + 1 / theta) * log(t * theta + 1)}, gumbel = function(t, d= 2, theta){-2 * log(theta) -t^(1 / theta) + (1 / theta - 2) *log(t) + log(t^(1 / theta) + theta - 1)}) gu <- apply(phi(u, theta), 1, sum) term1 <- loggfunc(gu, d, theta) term2 <- apply(lnegphidash(u, theta), 1, sum) out <- term1 + term2 if(!(log)) out <- exp(out) } out } dcopula.clayton <- function(u, theta, log = FALSE){ d <- dim(u)[2] if(d > 2) stop("\nClayton copula density only implemented for d = 2.\n") u1 <- u[, 1] u2 <- u[, 2] out <- log(1 + theta) + (-1 - theta) * log(u1 * u2) + (-2 - 1 / theta) * log(u1^(-theta) + u2^(-theta) - 1) if (!(log)) out <- exp(out) out } dcopula.gumbel <- function(u, theta, log = FALSE){ d <- dim(u)[2] if(d > 2) stop("\nGumbel copula density only implemented for d = 2.\n") u1 <- u[, 1] u2 <- u[, 2] innerfunc <- function(x, y, theta){((-log(x))^theta + (-log(y))^theta)^(1 / theta)} out <- -innerfunc(u1, u2, theta) -log(u1 * u2) + (theta - 1) * log(log(u1) * log(u2)) + log(theta - 1 + innerfunc(u1, u2, theta)) + (1 - 2 * theta) * log(innerfunc(u1, u2, theta)) if (!(log)) out <- exp(out) out } fit.AC <- function(Udata, name = c("clayton", "gumbel"), initial = 2, ...){ negloglik <- function(x, data, name){ - sum(dcopula.AC(data, x, name, log = TRUE)) } cl <- match.call() if(!("lower" %in% names(cl))){ lower <- switch(name, gumbel = 1+1e-10, clayton = 0) fit <- nlminb(initial, negloglik, data = Udata, name = name, lower = lower, ...) } else { fit <- nlminb(initial, negloglik, data = Udata, name = name, ...) } theta <- fit$par ifelse(fit$convergence == 0, converged <- TRUE, converged <- FALSE) hessianmatrix <- hessian(negloglik, theta, data = Udata, name = name) varcov <- solve(hessianmatrix) se <- sqrt(diag(varcov)) ll.max <- - fit$objective out <- list(ll.max = ll.max, theta = theta, se = se, converged = converged, fit = fit) out }
saveout.dcm <- function(df, s, param, control, out = NULL) { if (s == 1) { out <- list() out$param <- param out$control <- control if (length(control$nsteps) == 1) { out$control$timesteps <- seq(1, control$nsteps, control$dt) } else { out$control$timesteps <- control$nsteps } out$epi <- list() for (j in 2:ncol(df)) { out$epi[[names(df)[j]]] <- data.frame(df[, j]) } } else { for (j in 2:ncol(df)) { out$epi[[names(df)[j]]][, s] <- data.frame(df[, j]) } } ns <- nrow(out$epi[[1]]) lr.na <- sapply(out$epi, function(x) is.na(x[ns, s]) & !is.na(x[ns - 1, s])) wh.lr.na <- as.numeric(which(lr.na == TRUE)) if (length(wh.lr.na) > 0) { for (jj in wh.lr.na) { out$epi[[jj]][ns, s] <- out$epi[[jj]][ns - 1, s] } } if (s == control$nruns) { for (s in as.vector(which(lapply(out$epi, class) == "data.frame"))) { colnames(out$epi[[s]]) <- paste0("run", 1:control$nruns) } } return(out) } saveout.icm <- function(dat, s, out = NULL) { if (s == 1) { out <- list() out$param <- dat$param out$control <- dat$control out$epi <- list() for (j in 1:length(dat$epi)) { out$epi[[names(dat$epi)[j]]] <- data.frame(dat$epi[j]) } } else { for (j in 1:length(dat$epi)) { out$epi[[names(dat$epi)[j]]][, s] <- data.frame(dat$epi[j]) } } if (s == dat$control$nsims) { ftodel <- grep(".FUN", names(out$control), value = TRUE) out$control[ftodel] <- NULL for (i in as.vector(which(lapply(out$epi, class) == "data.frame"))) { colnames(out$epi[[i]]) <- paste0("sim", 1:dat$control$nsims) } } return(out) } saveout.net <- function(dat, s, out = NULL) { if (get_control(dat, "tergmLite") == TRUE) { num.nw <- length(dat$el) } else { num.nw <- length(dat$nw) } if (s == 1) { out <- list() out$param <- dat$param out$control <- dat$control out$nwparam <- dat$nwparam out$control$num.nw <- num.nw out[["last_timestep"]] <- get_current_timestep(dat) out$epi <- list() for (j in seq_along(dat$epi)) { out$epi[[names(dat$epi)[j]]] <- data.frame(dat$epi[j]) } out$el.cuml <- list() out$el.cuml[[s]] <- dat$el.cuml out[["_last_unique_id"]] <- list() out[["_last_unique_id"]][[s]] <- dat[["_last_unique_id"]] out$attr.history <- list() out$attr.history[[s]] <- dat$attr.history out$raw.records <- list() out$raw.records[[s]] <- dat$raw.records out$stats <- list() if (dat$control$save.nwstats == TRUE) { out$stats$nwstats <- list(dat$stats$nwstats) } if (dat$control$save.transmat == TRUE) { if (!is.null(dat$stats$transmat)) { row.names(dat$stats$transmat) <- 1:nrow(dat$stats$transmat) out$stats$transmat <- list(dat$stats$transmat) } else { out$stats$transmat <- list(data.frame()) } class(out$stats$transmat) <- c("transmat", class(out$stats$transmat)) } if (dat$control$tergmLite == FALSE) { if (dat$control$save.network == TRUE) { if (!is.null(dat$temp$nw_list)) { out$network <- list(dat$temp$nw_list) } else { out$network <- list(dat$nw) } } } if (!is.null(dat$control$save.other)) { for (i in 1:length(dat$control$save.other)) { el.name <- dat$control$save.other[i] out[[el.name]] <- list(dat[[el.name]]) } } } if (s > 1) { if (!is.null(dat$param$random.params.values)) { for (nms in names(dat$param$random.params.values)) { if (length(dat$param$random.params.values[[nms]]) > 1) { if (!is.list(out$param$random.params.values[[nms]])) { out$param$random.params.values[[nms]] <- list( out$param$random.params.values[[nms]] ) } out$param$random.params.values[[nms]] <- c( out$param$random.params.values[[nms]], list(dat$param$random.params.values[[nms]]) ) } else { out$param$random.params.values[[nms]] <- c( out$param$random.params.values[[nms]], dat$param$random.params.values[[nms]] ) } } } for (j in seq_along(dat$epi)) { out$epi[[names(dat$epi)[j]]][, s] <- data.frame(dat$epi[j]) } out$el.cuml[[s]] <- dat$el.cuml out[["_last_unique_id"]][[s]] <- dat[["_last_unique_id"]] out$attr.history[[s]] <- dat$attr.history out$raw.records[[s]] <- dat$raw.records if (dat$control$save.nwstats == TRUE) { out$stats$nwstats[[s]] <- dat$stats$nwstats } if (dat$control$save.transmat == TRUE) { if (!is.null(dat$stats$transmat)) { row.names(dat$stats$transmat) <- 1:nrow(dat$stats$transmat) out$stats$transmat[[s]] <- dat$stats$transmat } else { out$stats$transmat[[s]] <- data.frame() } } if (dat$control$tergmLite == FALSE) { if (dat$control$save.network == TRUE) { if (!is.null(dat$temp$nw_list)) { out$network[[s]] <- dat$temp$nw_list } else { out$network[[s]] <- dat$nw } } } if (!is.null(dat$control$save.other)) { for (i in seq_along(dat$control$save.other)) { el.name <- dat$control$save.other[i] out[[el.name]][[s]] <- dat[[el.name]] } } } if (s == dat$control$nsims) { simnames <- paste0("sim", seq_len(dat$control$nsims)) for (i in as.vector(which(lapply(out$epi, class) == "data.frame"))) { colnames(out$epi[[i]]) <- simnames } if (length(out$el.cuml) > 0) names(out$el.cuml) <- simnames if (length(out[["_last_unique_id"]]) > 0) names(out[["_last_unique_id"]]) <- simnames if (length(out$attr.history) > 0) names(out$attr.history) <- simnames if (length(out$.records) > 0) names(out$raw.records) <- simnames if (dat$control$save.nwstats == TRUE) { names(out$stats$nwstats) <- simnames } if (dat$control$save.transmat == TRUE) { names(out$stats$transmat) <- simnames[seq_along(out$stats$transmat)] } if (dat$control$tergmLite == FALSE) { if (dat$control$save.network == TRUE) { names(out$network) <- simnames } } ftodel <- grep(".FUN", names(out$control), value = TRUE) out$control[ftodel] <- NULL out$control$currsim <- NULL environment(out$control$nwstats.formula) <- NULL if (!("temp" %in% dat$control$save.other)) { out$temp <- NULL } } return(out) } process_out.net <- function(dat_list) { for (s in seq_along(dat_list)) { if (s == 1) { out <- saveout.net(dat_list[[s]], s) } else { out <- saveout.net(dat_list[[s]], s, out) } } class(out) <- "netsim" return(out) }
options(width=67) library(vegclust) library(vegan) data(wetland) dim(wetland) wetlandchord = decostand(wetland,"normalize") dchord = dist(wetlandchord) wetland.km = vegclust(x = wetlandchord, mobileCenters=3, method="KM", nstart=20) names(wetland.km) t(wetland.km$memb) round(wetland.km$mobileCenters, dig=3) wetland.kmdist = vegclustdist(x = dchord, mobileMemb=3, method="KM", nstart = 20) names(wetland.kmdist) wetland.kmdist$mobileCenters t(wetland.kmdist$memb) wetland.km$mode wetland.kmdist$mode round(t(wetland.km$dist2clusters), dig=2) wetland.fcm = vegclust(x = wetlandchord, mobileCenters=3, method="FCM", m=1.2, nstart=20) round(t(wetland.fcm$memb), dig=3) groups = defuzzify(wetland.fcm)$cluster groups table(groups) groups = defuzzify(wetland.fcm, method = "cut", alpha = 0.8)$cluster groups table(groups, useNA = "always") wetland.fcm2 = vegclust(x = wetlandchord, mobileCenters=3, method="FCM", m=10, nstart=20) round(t(wetland.fcm2$memb), dig=3) groups2 = defuzzify(wetland.fcm2, method = "cut", alpha = 0.8)$cluster table(groups2, useNA = "always") wetland.nc = vegclust(x = wetlandchord, mobileCenters=3, method="NC", m=1.2, dnoise=0.8, nstart=20) round(t(wetland.nc$memb), dig=2) groups = defuzzify(wetland.nc)$cluster groups table(groups) groups = defuzzify(wetland.nc, method="cut", alpha=0.8)$cluster groups table(groups, useNA = "always") dist(wetland.km$mobileCenters) dist(wetland.fcm$mobileCenters) dist(wetland.nc$mobileCenters) wetland.kmdd = vegclust(x = wetlandchord, mobileCenters=3, method="KMdd", nstart=20) t(wetland.kmdd$memb) round(wetland.kmdd$mobileCenters, dig=3) wetland.kmdd = vegclustdist(x = dchord, mobileMemb=3, method="KMdd", nstart=20) wetland.kmdd$mobileCenters wetland.31 = wetlandchord[1:31,] wetland.31 = wetland.31[,colSums(wetland.31)>0] dim(wetland.31) wetland.10 = wetlandchord[-(1:31),] wetland.10 = wetland.10[,colSums(wetland.10)>0] dim(wetland.10) km = kmeans(wetland.31, 2) groups = km$cluster groups wetland.31.km = as.vegclust(wetland.31, groups) wetland.31.km$method wetland.10.km = vegclass(wetland.31.km, wetland.10) defuzzify(wetland.10.km)$cluster wetland.31.km.d = as.vegclust(dist(wetland.31), groups) wetland.d.10.31 = as.data.frame(as.matrix(dchord)[32:41,1:31]) wetland.d.11.km = vegclass(wetland.31.km.d,wetland.d.10.31) defuzzify(wetland.d.11.km)$cluster wetland.31.nc = as.vegclust(wetland.31, groups, method="HNC", dnoise = 0.8) wetland.10.nc = vegclass(wetland.31.nc, wetland.10) defuzzify(wetland.10.nc)$cluster cf = conformveg(wetland.31, wetland.10) wetland.31.cf<- cf$x wetland.10.cf<- cf$y dim(wetland.31.cf) dim(wetland.10.cf) fixed = clustcentroid(wetland.31.cf, groups) wetland.nc = vegclust(wetland.10.cf, mobileCenters=1, fixedCenters = fixed, method = wetland.31.nc$method, dnoise=wetland.31.nc$dnoise, nstart=10) defuzzify(wetland.nc)$cluster wetland.km = vegclust(wetland.10.cf, mobileCenters=1, fixedCenters = fixed, method = "KM", nstart=10) defuzzify(wetland.km)$cluster wetland.nc = vegclust(rbind(wetland.31.cf,wetland.10.cf), mobileCenters=1, fixedCenters = fixed, method = wetland.31.nc$method, dnoise=wetland.31.nc$dnoise, nstart=10) defuzzify(wetland.nc)$cluster fixedDist = wetland.d.11.km$dist2clusters wetland.km.d = vegclustdist(dist(wetland.10), mobileMemb = 1, fixedDistToCenters=fixedDist, method = "KM", nstart=10) defuzzify(wetland.km.d)$cluster fixedDist = rbind(wetland.31.km.d$dist2clusters, wetland.d.11.km$dist2clusters) wetland.km.d = vegclustdist(dchord, mobileMemb = 1, fixedDistToCenters=fixedDist, method = "KM", nstart=10) defuzzify(wetland.km.d)$cluster groups = c(rep(1, 17), rep(2, 14), rep(3,10)) centroids = clustcentroid(wetlandchord, groups) round(centroids, dig=3) medoids = clustmedoid(wetlandchord, groups) medoids clustvar(wetlandchord, groups) clustvar(dchord, groups) clustvar(wetlandchord) as.dist(as.matrix(dchord)[medoids,medoids]) dist(centroids) interclustdist(dchord,groups) c = clustconst(wetlandchord, memb = as.memb(groups)) d=summary(c, mode="all") summary(c, mode="cluster", name=names(c)[1])
context("test-form_resupport") test_that("form_resupport works with `method='reflect'` and 'discrete' type", { p_f <- new_p(data.frame(x = 1:4, prob = (1:4) / 10), "discrete") p_f_x_tbl <- meta_x_tbl(p_f) expect_ref_x_tbl(form_resupport(p_f, c(1, 4), "reflect"), p_f_x_tbl) expect_ref_x_tbl(form_resupport(p_f, c(0, 5), "reflect"), p_f_x_tbl) expect_ref_x_tbl( form_resupport(p_f, c(1.1, 5), "reflect"), data.frame(x = c(1.2, 2:4), prob = (1:4) / 10) ) expect_ref_x_tbl( form_resupport(p_f, c(0, 2.3), "reflect"), data.frame(x = c(0.6, 1, 1.6, 2), prob = c(0.4, 0.1, 0.3, 0.2)) ) expect_ref_x_tbl( form_resupport(p_f, c(1.1, 2.3), "reflect"), data.frame(x = c(1.2, 1.6, 2), prob = c(0.1, 0.3, 0.2) / 0.6) ) expect_ref_x_tbl( form_resupport(p_f, c(1.1, 1.3), "reflect"), data.frame(x = 1.2, prob = 1) ) expect_ref_x_tbl( form_resupport(p_f, c(2, 5), "reflect"), data.frame(x = 2:4, prob = c(0.2 + 0.2, 0.3 + 0.1, 0.4) / 1.2) ) }) test_that("form_resupport works with `method='reflect'`, 'continuous' type", { p_f <- new_p(data.frame(x = c(0, 1), y = c(1, 1)), "continuous") p_f_x_tbl <- meta_x_tbl(p_f) h <- 1e-8 tol <- 1e-9 expect_ref_x_tbl(form_resupport(p_f, c(0, 1), "reflect"), p_f_x_tbl) expect_ref_x_tbl(form_resupport(p_f, c(-1, 2), "reflect"), p_f_x_tbl) expect_ref_x_tbl( form_resupport(p_f, c(0.2, 1), "reflect"), data.frame(x = c(0.2, 0.4 - h, 0.4, 0.4 + h, 1), y = c(2, 2, 1.5, 1, 1)) ) expect_ref_x_tbl( form_resupport(p_f, c(0, 0.6), "reflect"), data.frame(x = c(0, 0.2 - h, 0.2, 0.2 + h, 0.6), y = c(1, 1, 1.5, 2, 2)) ) expect_ref_x_tbl( form_resupport(p_f, c(0.1, 0.9), "reflect"), data.frame( x = c(0.1, 0.2 - h, 0.2, 0.2 + h, 0.8 - h, 0.8, 0.8 + h, 0.9), y = c(2, 2, 1.5, 1, 1, 1.5, 2, 2) ) ) }) test_that("form_resupport works with `method = 'trim'` and 'discrete' type", { x_tbl <- data.frame( x = c(0, 1, 2, 3, 4, 5, 6, 7), prob = c(0, 0.2, 0, 0.4, 0.1, 0.1, 0.2, 0) ) p_f <- new_p(x_tbl, "discrete") expect_ref_x_tbl( form_resupport(p_f, c(1.5, 4.5), "trim"), data.frame(x = 2:4, prob = c(0, 0.8, 0.2)) ) expect_ref_x_tbl( form_resupport(p_f, c(-1, 1), "trim"), data.frame(x = 0:1, prob = c(0, 1)) ) expect_ref_x_tbl(form_resupport(p_f, c(-100, 100), "trim"), x_tbl) expect_error(form_resupport(p_f, c(0.5, 0.75), "trim"), "not.*positive.*prob") expect_error(form_resupport(p_f, c(-1, 0.5), "trim"), "not.*positive.*prob") expect_error(form_resupport(p_f, c(6.5, 7), "trim"), "not.*positive.*prob") }) test_that("form_resupport works with `method = 'trim'` and 'continuous' type", { x_tbl <- data.frame( x = c(0, 1, 2, 3, 4, 5, 6, 7, 8), y = c(0, 0, 0.4, 0, 0, 0, 0.4, 0, 0.4) ) d_f <- new_d(x_tbl, "continuous") expect_ref_x_tbl( form_resupport(d_f, c(0.5, 3.5), "trim"), data.frame(x = c(0.5, 1, 2, 3, 3.5), y = c(0, 0, 1, 0, 0)) ) expect_ref_x_tbl( form_resupport(d_f, c(-1, 1.5), "trim"), data.frame(x = c(0, 1, 1.5), y = c(0, 0, 4)) ) expect_ref_x_tbl( form_resupport(d_f, c(6.5, 7.5), "trim"), data.frame(x = c(6.5, 7, 7.5), y = c(2, 0, 2)) ) expect_ref_x_tbl(form_resupport(d_f, c(-100, 100), "trim"), x_tbl) expect_equal( meta_support(d_f), meta_support(form_resupport(d_f, c(-100, 100), "trim")) ) expect_error(form_resupport(d_f, c(2, 2), "trim"), "not.*positive.*prob") expect_error(form_resupport(d_f, c(3, 5), "trim"), "not.*positive.*prob") expect_error(form_resupport(d_f, c(0.5, 0.75), "trim"), "not.*positive.*prob") expect_error(form_resupport(d_f, c(-1, 0.5), "trim"), "not.*positive.*prob") }) test_that("form_resupport works with `method='winsor'` and 'discrete' type", { d_f <- new_d(data.frame(x = 1:4, prob = (1:4) / 10), "discrete") expect_equal_x_tbl( form_resupport(d_f, c(5, 6), "winsor"), new_d(5, "discrete") ) expect_equal_x_tbl( form_resupport(d_f, c(0, 0.5), "winsor"), new_d(0.5, "discrete") ) expect_equal_x_tbl( form_resupport(d_f, c(3.14, 3.14), "winsor"), new_d(3.14, "discrete") ) expect_ref_x_tbl( form_resupport(d_f, c(2.5, 6), "winsor"), data.frame(x = c(2.5, 3, 4), prob = c(0.3, 0.3, 0.4)) ) expect_ref_x_tbl( form_resupport(d_f, c(0, 2.5), "winsor"), data.frame(x = c(1, 2, 2.5), prob = c(0.1, 0.2, 0.7)) ) expect_ref_x_tbl( form_resupport(d_f, c(2.5, 2.75), "winsor"), data.frame(x = c(2.5, 2.75), prob = c(0.3, 0.7)) ) }) test_that("form_resupport works with `method='winsor'`, 'continuous' type", { d_f <- new_d(data.frame(x = 0:1, y = c(1, 1)), "continuous") expect_equal_x_tbl( form_resupport(d_f, c(2, 3), "winsor"), new_d(2, "continuous") ) expect_equal_x_tbl( form_resupport(d_f, c(-1, 0), "winsor"), new_d(0, "continuous") ) expect_equal_x_tbl( form_resupport(d_f, c(0.7, 0.7), "winsor"), new_d(0.7, "continuous") ) expect_ref_x_tbl( form_resupport(d_f, c(0.3, 1), "winsor"), data.frame(x = c(0.3, 0.3 + 1e-8, 1), y = c(6e7 + 1.032, 1, 1)) ) expect_ref_x_tbl( form_resupport(d_f, c(0, 0.7), "winsor"), data.frame(x = c(0, 0.7 - 1e-8, 0.7), y = c(1, 1, 6e7 + 0.696)) ) expect_ref_x_tbl( form_resupport(d_f, c(0.3, 0.7), "winsor"), data.frame( x = c(0.3, 0.3 + 1e-8, 0.7 - 1e-8, 0.7), y = c(6e7 + 1.03, 1, 1, 6e7 + 0.696) ) ) }) test_that("form_resupport works with `method = 'linear'` and 'discrete' type", { p_f <- new_p( data.frame(x = c(-1, -0.25, 2), prob = c(0, 0.1, 0.9)), "discrete" ) expect_ref_x_tbl( form_resupport(p_f, c(-0.5, 3), "linear"), data.frame(x = c(-0.5, 0.375, 3), prob = meta_x_tbl(p_f)[["prob"]]) ) expect_equal_x_tbl( form_resupport(p_f, c(15, 15), "linear"), new_p(15, "discrete") ) expect_error( form_resupport(new_p(1, "discrete"), c(0, 1), "linear"), "single.*interval" ) }) test_that("form_resupport works with `method='linear'` and 'continuous' type", { x_tbl <- data.frame( x = c(0, 1, 2, 5), y = c(0, 0, 0.5, 0) ) p_f <- new_p(x_tbl, "continuous") expect_ref_x_tbl( form_resupport(p_f, c(1, 3.5), "linear"), data.frame(x = c(1, 1.5, 2, 3.5), y = c(0, 0, 1, 0)) ) expect_equal_x_tbl( form_resupport(p_f, c(15, 15), "linear"), new_p(15, "continuous") ) }) test_that("form_resupport returns correct class of pdqr-function", { p_f_dis <- new_p(data.frame(x = 1:2, prob = c(0.3, 0.7)), "discrete") p_f_con <- new_p(data.frame(x = 1:3, y = c(0, 1, 0)), "continuous") expect_is(form_resupport(p_f_dis, c(1, 2), "trim"), "p") expect_is(form_resupport(as_d(p_f_dis), c(1, 2), "trim"), "d") expect_is(form_resupport(as_q(p_f_dis), c(1, 2), "trim"), "q") expect_is(form_resupport(as_r(p_f_dis), c(1, 2), "trim"), "r") expect_is(form_resupport(p_f_con, c(1, 2), "trim"), "p") expect_is(form_resupport(as_d(p_f_con), c(1, 2), "trim"), "d") expect_is(form_resupport(as_q(p_f_con), c(1, 2), "trim"), "q") expect_is(form_resupport(as_r(p_f_con), c(1, 2), "trim"), "r") expect_is(form_resupport(p_f_dis, c(1, 2), "linear"), "p") expect_is(form_resupport(as_d(p_f_dis), c(1, 2), "linear"), "d") expect_is(form_resupport(as_q(p_f_dis), c(1, 2), "linear"), "q") expect_is(form_resupport(as_r(p_f_dis), c(1, 2), "linear"), "r") expect_is(form_resupport(p_f_con, c(1, 2), "linear"), "p") expect_is(form_resupport(as_d(p_f_con), c(1, 2), "linear"), "d") expect_is(form_resupport(as_q(p_f_con), c(1, 2), "linear"), "q") expect_is(form_resupport(as_r(p_f_con), c(1, 2), "linear"), "r") expect_is(form_resupport(p_f_dis, c(1, 2), "reflect"), "p") expect_is(form_resupport(as_d(p_f_dis), c(1, 2), "reflect"), "d") expect_is(form_resupport(as_q(p_f_dis), c(1, 2), "reflect"), "q") expect_is(form_resupport(as_r(p_f_dis), c(1, 2), "reflect"), "r") expect_is(form_resupport(p_f_con, c(1, 2), "reflect"), "p") expect_is(form_resupport(as_d(p_f_con), c(1, 2), "reflect"), "d") expect_is(form_resupport(as_q(p_f_con), c(1, 2), "reflect"), "q") expect_is(form_resupport(as_r(p_f_con), c(1, 2), "reflect"), "r") expect_is(form_resupport(p_f_dis, c(1, 2), "winsor"), "p") expect_is(form_resupport(as_d(p_f_dis), c(1, 2), "winsor"), "d") expect_is(form_resupport(as_q(p_f_dis), c(1, 2), "winsor"), "q") expect_is(form_resupport(as_r(p_f_dis), c(1, 2), "winsor"), "r") expect_is(form_resupport(p_f_con, c(1, 2), "winsor"), "p") expect_is(form_resupport(as_d(p_f_con), c(1, 2), "winsor"), "d") expect_is(form_resupport(as_q(p_f_con), c(1, 2), "winsor"), "q") expect_is(form_resupport(as_r(p_f_con), c(1, 2), "winsor"), "r") }) test_that("form_resupport handles `NA`s in `support`", { p_f <- new_p(1:3, "discrete") expect_close_f( f_1 = form_resupport(p_f, c(1.5, NA), "trim"), f_2 = form_resupport(p_f, c(1.5, 3), "trim"), grid = 0:4 + 0.5 ) expect_close_f( f_1 = form_resupport(p_f, c(NA, 1.5), "trim"), f_2 = form_resupport(p_f, c(1, 1.5), "trim"), grid = 0:4 + 0.5 ) }) test_that("form_resupport returns self when appropriate", { output_1 <- form_resupport(p_dis, c(NA_real_, NA_real_)) expect_close_f(p_dis, output_1, x_dis_vec) for (method in methods_resupport) { output_dis <- form_resupport(p_dis, meta_support(p_dis), method) expect_close_f(p_dis, output_dis, x_dis_vec) output_con <- form_resupport(p_con, meta_support(p_con), method) expect_close_f(p_con, output_con, x_con_vec) } }) test_that("form_resupport validates input", { expect_error(form_resupport(1, c(0, 1), "trim"), "`f`.*not pdqr-function") expect_error(form_resupport(p_dis), "`support`.*missing.*vector for support") expect_error(form_resupport(p_dis, "a", "trim"), "`support`.*numeric") expect_error(form_resupport(p_dis, c(2, 1), "trim"), "`support`") expect_error(form_resupport(p_dis, c(1, 3), 1), "`method`.*string") expect_error(form_resupport(p_dis, c(1, 3), "a"), "`method`.*one of") expect_error( form_resupport(p_dis, c(x_dis_support[2] + 1, NA), "trim"), "`NA`.*support.*(10, 9).*not proper" ) })
genDoneSided <- function (func, x, sides, method = "Richardson", method.args = list(eps = 1e-04, d = 1e-04, zero.tol = sqrt(.Machine$double.eps/7e-07), r = 4, v = 2), ...) { if (method != "Richardson") stop("method not implemented.") if (length(x) != sum(abs(sides))) stop("genDoneSided: length(x) != length(sides) or bad arg passed for sides."); args <- list(eps = 1e-04, d = 1e-04, zero.tol = sqrt(.Machine$double.eps/7e-07), r = 4, v = 2) args[names(method.args)] <- method.args eps <- args$eps d <- args$d r <- args$r v <- args$v if (v != 2) stop("The current code assumes v is 2 (the default).") f0 <- func(x, ...) p <- length(x) h0 <- abs(d * x)*(abs(x) >= args$zero.tol) + eps*(abs(x) < args$zero.tol) D <- matrix(0, length(f0), (p * (p + 3))/2) Daprox <- matrix(0, length(f0), r) Hdiag <- matrix(0, length(f0), p) Haprox <- matrix(0, length(f0), r) for (i in 1:p) { h <- h0 for (k in 1:r) { f2 <- func(x + (sides*(i == (1:p))) * h, ...) f1 <- f0; f3 <- func(x + (sides* (i == (1:p))) *2* h, ...) Daprox[, k] <- (f2-f1)/(h[i]*sides[i]) Haprox[, k] <- (f1 - 2 * f2 + f3)/h[i]^2 h <- h/v NULL } for (m in 1:(r - 1)) for (k in 1:(r - m)) { Daprox[, k] <- (Daprox[, k + 1] * (2^m) - Daprox[,k])/(2^m - 1) Haprox[, k] <- (Haprox[, k + 1] * (2^m) - Haprox[,k])/(2^m - 1) NULL } D[, i] <- Daprox[, 1] Hdiag[, i] <- Haprox[, 1] NULL } u <- p for (i in 1:p) { for (j in 1:i) { u <- u + 1 if (i == j) { D[, u] <- Hdiag[, i] NULL } else { h <- h0 for (k in 1:r) { f1 <- f0; f4 <- func(x + (sides*(i == (1:p))) * h + (sides*(j == (1:p)))*h, ...) f01 <- func(x + (sides*(i == (1:p))) * h , ...) f02 <- func(x + (sides*(j == (1:p))) * h , ...) Daprox[, k] <- (f1 - f01 -f02 + f4)/(sides[i]*sides[j]*h[i]*h[j]) } for (m in 1:(r - 1)) for (k in 1:(r - m)) { Daprox[, k] <- (Daprox[, k + 1] * (2^m) - Daprox[, k])/(2^m - 1) NULL } D[, u] <- Daprox[, 1] NULL } } } D <- list(D = D, p = length(x), f0 = f0, func = func, x = x, d = d, method = method, method.args = args) class(D) <- "Darray" invisible(D) } hessianOneSided <- function (func, x, sides, method = "Richardson", method.args = list(eps = 1e-04, d = 1e-4, zero.tol = sqrt(.Machine$double.eps/7e-07), r = 4, v = 2), ...) { if (method != "Richardson") stop("method not implemented.") if (1 != length(func(x, ...))) stop("hessian.default assumes a scalar real valued function.") D <- genDoneSided(func, x,sides=sides, method = method, method.args = method.args, ...)$D if (1 != nrow(D)) stop("BUG! should not get here.") H <- diag(NA, length(x)) u <- length(x) for (i in 1:length(x)) { for (j in 1:i) { u <- u + 1 H[i, j] <- D[, u] H[j, i] <- D[, u] } } H } num.deriv = function(ftn, var, delta=0.001,...){ return((ftn(var+delta,...) - ftn(var-delta,...))/(2*delta)) } num.deriv2 <- function(ftn, var1,var2, delta=0.00001){ (ftn(c(var1+delta, var2+delta)) + ftn(c(var1-delta, var2-delta)) - ftn(c(var1+delta, var2-delta)) - ftn(c(var1-delta, var2+delta)))/(4*delta^2); } num.2deriv <- function(ftn, var, delta=0.00001,...){ num.deriv(ftn=function(x){num.deriv(ftn=ftn, var=x, delta=delta,...);}, var=var, delta=delta); }
library(ts) library(gsheet) df1 = gsheet2tbl('https://docs.google.com/spreadsheets/d/1RCj6uvsu242xDf1l5Qb720DSnOmjnTUG8ety3iYBG90') beer=df1 beer.ts <- ts(beer, frequency = 12, start = c(1956,1), end = c(1994,12)) beer.ts.qtr <- aggregate(beer.ts, nfrequency=4) beer.ts.yr <- aggregate(beer.ts, nfrequency=1) plot.ts(beer.ts[,2], main = "Monthly Beer Production in Australia", xlab = "Year", ylab = "ML") plot.ts(beer.ts.qtr[,2], main = "Quarterly Beer Production in Australia", xlab = "Year", ylab = "ML") seasonplot(beer.ts[,2], year.labels = TRUE, year.labels.left=TRUE, col=1:40, pch=19, main = "Monthly Beer Production in Australia - seasonplot", xlab = "Month", ylab = "ML")
fill_left <- function(df) { df <- as.data.frame(t(apply(df, 1, function(x) { return(c(x[!is.na(x)], x[is.na(x)])) }))) df <- Filter(function(x) ! all(is.na(x)), df) return(df) }
mp_question_multi <- function(mp_id, question_type, start_date, end_date, extra_args, verbose) { mp_id_list <- as.list(mp_id) dat <- vector("list", length(mp_id_list)) seq_list <- seq(from = 1, to = length(mp_id_list), by = 1) for (i in seq_along(seq_list)) { dat[[i]] <- hansard::mp_questions( mp_id = mp_id_list[[i]], question_type = question_type, end_date = end_date, start_date = start_date, extra_args = extra_args, verbose = verbose, tidy = FALSE, tidy_style = "snake" ) } dat <- dat[sapply(dat, function(d) is.null(d) == FALSE)] df <- dplyr::bind_rows(dat) names(df)[names(df) == "_about"] <- "about" df } mp_question_tidy <- function(df, tidy_style) { if (nrow(df) > 0) { df$dateTabled._value <- as.POSIXct(df$dateTabled._value) df$AnswerDate._value <- as.POSIXct(df$AnswerDate._value) df$AnswerDate._datatype <- "POSIXct" df$dateTabled._datatype <- "POSIXct" df$tablingMemberPrinted <- unlist(df$tablingMemberPrinted) df$AnsweringBody <- unlist(df$AnsweringBody) df$tablingMember._about <- gsub( "http://data.parliament.uk/members/", "", df$tablingMember._about ) } df <- hansard_tidy(df, tidy_style) df }
.onAttach <- function(...) { mes <- paste0("healthcareai version ", packageVersion("healthcareai"), "\nPlease visit https://docs.healthcare.ai for full documentation ", "and vignettes. Join the community at https://healthcare-ai.slack.com") packageStartupMessage(mes) }
require(SoDA) load("Examples/with_gps1.rda") pdf("Examples/gpsScatterPlot.pdf", width = 4, height=4) with(gps1, { par(mar = c(2,2,0,0)) xy = geoXY(latitude, longitude) x = xy[,1]; y = xy[,2] plot(x, y, asp = 1) }) dev.off()
library(testthat) set.seed(1) x1 <- 100 + arima.sim(model = list(ar = 0.999), n = 100) y <- 1.2 * x1 + rnorm(100) y[71:100] <- y[71:100] + 10 data <- cbind(y, x1) impact <- CausalImpact::CausalImpact(data, c(1, 70), c(71, 100)) expect_is(impact, "CausalImpact") impact <- CausalImpact::CausalImpact( data, c(1, 70), c(71, 100), model.args = list(dynamic.regression = TRUE)) expect_is(impact, "CausalImpact")
plotQuote <- function(sentences, width=30, text.cex=1, maxwidth=NULL, main=NULL, xlab="", ylab="", xlim=NULL, ylim=NULL, ...) { xaxt <- "n" yaxt <- "n" numlines <- c() out <- list() for(j in 1:length(sentences)){ sentence <- sentences[j] if(!is.null(maxwidth)) { sentence <- strwrap(sentence, width=maxwidth)[1] } out[[j]] <- stringr::str_wrap(sentence, width) numlines[j] <- length(strsplit(out[[j]], "\n")[[1]]) } if(is.null(xlim)) xlim <- c(0, 5) if(is.null(ylim)) ylim<-c(0,.5*sum(numlines)) plot(c(0,0),type="n", xlim=xlim, ylim=ylim, xaxt=xaxt, yaxt=yaxt, xlab=xlab, ylab=ylab, main=main, ...) numlines <- c(0, rev(numlines)) out <- rev(out) start <- 0 for(j in 2:(length(out)+1)){ text(2.5, start + numlines[j-1]/4 + numlines[j]/4, out[[j-1]], cex=text.cex) start <- start + numlines[j-1]/4 + numlines[j]/4 if(j!=1 & j!=(length(out)+1)) lines(c(0,5), c(sum(numlines[1:j-1])/2 + numlines[j]/2, sum(numlines[1:j-1])/2 + numlines[j]/2), lty=2) } }
NULL gamelift_accept_match <- function(TicketId, PlayerIds, AcceptanceType) { op <- new_operation( name = "AcceptMatch", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$accept_match_input(TicketId = TicketId, PlayerIds = PlayerIds, AcceptanceType = AcceptanceType) output <- .gamelift$accept_match_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$accept_match <- gamelift_accept_match gamelift_claim_game_server <- function(GameServerGroupName, GameServerId = NULL, GameServerData = NULL) { op <- new_operation( name = "ClaimGameServer", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$claim_game_server_input(GameServerGroupName = GameServerGroupName, GameServerId = GameServerId, GameServerData = GameServerData) output <- .gamelift$claim_game_server_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$claim_game_server <- gamelift_claim_game_server gamelift_create_alias <- function(Name, Description = NULL, RoutingStrategy, Tags = NULL) { op <- new_operation( name = "CreateAlias", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$create_alias_input(Name = Name, Description = Description, RoutingStrategy = RoutingStrategy, Tags = Tags) output <- .gamelift$create_alias_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$create_alias <- gamelift_create_alias gamelift_create_build <- function(Name = NULL, Version = NULL, StorageLocation = NULL, OperatingSystem = NULL, Tags = NULL) { op <- new_operation( name = "CreateBuild", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$create_build_input(Name = Name, Version = Version, StorageLocation = StorageLocation, OperatingSystem = OperatingSystem, Tags = Tags) output <- .gamelift$create_build_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$create_build <- gamelift_create_build gamelift_create_fleet <- function(Name, Description = NULL, BuildId = NULL, ScriptId = NULL, ServerLaunchPath = NULL, ServerLaunchParameters = NULL, LogPaths = NULL, EC2InstanceType, EC2InboundPermissions = NULL, NewGameSessionProtectionPolicy = NULL, RuntimeConfiguration = NULL, ResourceCreationLimitPolicy = NULL, MetricGroups = NULL, PeerVpcAwsAccountId = NULL, PeerVpcId = NULL, FleetType = NULL, InstanceRoleArn = NULL, CertificateConfiguration = NULL, Tags = NULL) { op <- new_operation( name = "CreateFleet", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$create_fleet_input(Name = Name, Description = Description, BuildId = BuildId, ScriptId = ScriptId, ServerLaunchPath = ServerLaunchPath, ServerLaunchParameters = ServerLaunchParameters, LogPaths = LogPaths, EC2InstanceType = EC2InstanceType, EC2InboundPermissions = EC2InboundPermissions, NewGameSessionProtectionPolicy = NewGameSessionProtectionPolicy, RuntimeConfiguration = RuntimeConfiguration, ResourceCreationLimitPolicy = ResourceCreationLimitPolicy, MetricGroups = MetricGroups, PeerVpcAwsAccountId = PeerVpcAwsAccountId, PeerVpcId = PeerVpcId, FleetType = FleetType, InstanceRoleArn = InstanceRoleArn, CertificateConfiguration = CertificateConfiguration, Tags = Tags) output <- .gamelift$create_fleet_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$create_fleet <- gamelift_create_fleet gamelift_create_game_server_group <- function(GameServerGroupName, RoleArn, MinSize, MaxSize, LaunchTemplate, InstanceDefinitions, AutoScalingPolicy = NULL, BalancingStrategy = NULL, GameServerProtectionPolicy = NULL, VpcSubnets = NULL, Tags = NULL) { op <- new_operation( name = "CreateGameServerGroup", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$create_game_server_group_input(GameServerGroupName = GameServerGroupName, RoleArn = RoleArn, MinSize = MinSize, MaxSize = MaxSize, LaunchTemplate = LaunchTemplate, InstanceDefinitions = InstanceDefinitions, AutoScalingPolicy = AutoScalingPolicy, BalancingStrategy = BalancingStrategy, GameServerProtectionPolicy = GameServerProtectionPolicy, VpcSubnets = VpcSubnets, Tags = Tags) output <- .gamelift$create_game_server_group_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$create_game_server_group <- gamelift_create_game_server_group gamelift_create_game_session <- function(FleetId = NULL, AliasId = NULL, MaximumPlayerSessionCount, Name = NULL, GameProperties = NULL, CreatorId = NULL, GameSessionId = NULL, IdempotencyToken = NULL, GameSessionData = NULL) { op <- new_operation( name = "CreateGameSession", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$create_game_session_input(FleetId = FleetId, AliasId = AliasId, MaximumPlayerSessionCount = MaximumPlayerSessionCount, Name = Name, GameProperties = GameProperties, CreatorId = CreatorId, GameSessionId = GameSessionId, IdempotencyToken = IdempotencyToken, GameSessionData = GameSessionData) output <- .gamelift$create_game_session_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$create_game_session <- gamelift_create_game_session gamelift_create_game_session_queue <- function(Name, TimeoutInSeconds = NULL, PlayerLatencyPolicies = NULL, Destinations = NULL, Tags = NULL) { op <- new_operation( name = "CreateGameSessionQueue", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$create_game_session_queue_input(Name = Name, TimeoutInSeconds = TimeoutInSeconds, PlayerLatencyPolicies = PlayerLatencyPolicies, Destinations = Destinations, Tags = Tags) output <- .gamelift$create_game_session_queue_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$create_game_session_queue <- gamelift_create_game_session_queue gamelift_create_matchmaking_configuration <- function(Name, Description = NULL, GameSessionQueueArns = NULL, RequestTimeoutSeconds, AcceptanceTimeoutSeconds = NULL, AcceptanceRequired, RuleSetName, NotificationTarget = NULL, AdditionalPlayerCount = NULL, CustomEventData = NULL, GameProperties = NULL, GameSessionData = NULL, BackfillMode = NULL, FlexMatchMode = NULL, Tags = NULL) { op <- new_operation( name = "CreateMatchmakingConfiguration", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$create_matchmaking_configuration_input(Name = Name, Description = Description, GameSessionQueueArns = GameSessionQueueArns, RequestTimeoutSeconds = RequestTimeoutSeconds, AcceptanceTimeoutSeconds = AcceptanceTimeoutSeconds, AcceptanceRequired = AcceptanceRequired, RuleSetName = RuleSetName, NotificationTarget = NotificationTarget, AdditionalPlayerCount = AdditionalPlayerCount, CustomEventData = CustomEventData, GameProperties = GameProperties, GameSessionData = GameSessionData, BackfillMode = BackfillMode, FlexMatchMode = FlexMatchMode, Tags = Tags) output <- .gamelift$create_matchmaking_configuration_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$create_matchmaking_configuration <- gamelift_create_matchmaking_configuration gamelift_create_matchmaking_rule_set <- function(Name, RuleSetBody, Tags = NULL) { op <- new_operation( name = "CreateMatchmakingRuleSet", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$create_matchmaking_rule_set_input(Name = Name, RuleSetBody = RuleSetBody, Tags = Tags) output <- .gamelift$create_matchmaking_rule_set_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$create_matchmaking_rule_set <- gamelift_create_matchmaking_rule_set gamelift_create_player_session <- function(GameSessionId, PlayerId, PlayerData = NULL) { op <- new_operation( name = "CreatePlayerSession", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$create_player_session_input(GameSessionId = GameSessionId, PlayerId = PlayerId, PlayerData = PlayerData) output <- .gamelift$create_player_session_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$create_player_session <- gamelift_create_player_session gamelift_create_player_sessions <- function(GameSessionId, PlayerIds, PlayerDataMap = NULL) { op <- new_operation( name = "CreatePlayerSessions", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$create_player_sessions_input(GameSessionId = GameSessionId, PlayerIds = PlayerIds, PlayerDataMap = PlayerDataMap) output <- .gamelift$create_player_sessions_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$create_player_sessions <- gamelift_create_player_sessions gamelift_create_script <- function(Name = NULL, Version = NULL, StorageLocation = NULL, ZipFile = NULL, Tags = NULL) { op <- new_operation( name = "CreateScript", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$create_script_input(Name = Name, Version = Version, StorageLocation = StorageLocation, ZipFile = ZipFile, Tags = Tags) output <- .gamelift$create_script_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$create_script <- gamelift_create_script gamelift_create_vpc_peering_authorization <- function(GameLiftAwsAccountId, PeerVpcId) { op <- new_operation( name = "CreateVpcPeeringAuthorization", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$create_vpc_peering_authorization_input(GameLiftAwsAccountId = GameLiftAwsAccountId, PeerVpcId = PeerVpcId) output <- .gamelift$create_vpc_peering_authorization_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$create_vpc_peering_authorization <- gamelift_create_vpc_peering_authorization gamelift_create_vpc_peering_connection <- function(FleetId, PeerVpcAwsAccountId, PeerVpcId) { op <- new_operation( name = "CreateVpcPeeringConnection", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$create_vpc_peering_connection_input(FleetId = FleetId, PeerVpcAwsAccountId = PeerVpcAwsAccountId, PeerVpcId = PeerVpcId) output <- .gamelift$create_vpc_peering_connection_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$create_vpc_peering_connection <- gamelift_create_vpc_peering_connection gamelift_delete_alias <- function(AliasId) { op <- new_operation( name = "DeleteAlias", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$delete_alias_input(AliasId = AliasId) output <- .gamelift$delete_alias_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$delete_alias <- gamelift_delete_alias gamelift_delete_build <- function(BuildId) { op <- new_operation( name = "DeleteBuild", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$delete_build_input(BuildId = BuildId) output <- .gamelift$delete_build_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$delete_build <- gamelift_delete_build gamelift_delete_fleet <- function(FleetId) { op <- new_operation( name = "DeleteFleet", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$delete_fleet_input(FleetId = FleetId) output <- .gamelift$delete_fleet_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$delete_fleet <- gamelift_delete_fleet gamelift_delete_game_server_group <- function(GameServerGroupName, DeleteOption = NULL) { op <- new_operation( name = "DeleteGameServerGroup", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$delete_game_server_group_input(GameServerGroupName = GameServerGroupName, DeleteOption = DeleteOption) output <- .gamelift$delete_game_server_group_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$delete_game_server_group <- gamelift_delete_game_server_group gamelift_delete_game_session_queue <- function(Name) { op <- new_operation( name = "DeleteGameSessionQueue", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$delete_game_session_queue_input(Name = Name) output <- .gamelift$delete_game_session_queue_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$delete_game_session_queue <- gamelift_delete_game_session_queue gamelift_delete_matchmaking_configuration <- function(Name) { op <- new_operation( name = "DeleteMatchmakingConfiguration", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$delete_matchmaking_configuration_input(Name = Name) output <- .gamelift$delete_matchmaking_configuration_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$delete_matchmaking_configuration <- gamelift_delete_matchmaking_configuration gamelift_delete_matchmaking_rule_set <- function(Name) { op <- new_operation( name = "DeleteMatchmakingRuleSet", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$delete_matchmaking_rule_set_input(Name = Name) output <- .gamelift$delete_matchmaking_rule_set_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$delete_matchmaking_rule_set <- gamelift_delete_matchmaking_rule_set gamelift_delete_scaling_policy <- function(Name, FleetId) { op <- new_operation( name = "DeleteScalingPolicy", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$delete_scaling_policy_input(Name = Name, FleetId = FleetId) output <- .gamelift$delete_scaling_policy_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$delete_scaling_policy <- gamelift_delete_scaling_policy gamelift_delete_script <- function(ScriptId) { op <- new_operation( name = "DeleteScript", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$delete_script_input(ScriptId = ScriptId) output <- .gamelift$delete_script_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$delete_script <- gamelift_delete_script gamelift_delete_vpc_peering_authorization <- function(GameLiftAwsAccountId, PeerVpcId) { op <- new_operation( name = "DeleteVpcPeeringAuthorization", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$delete_vpc_peering_authorization_input(GameLiftAwsAccountId = GameLiftAwsAccountId, PeerVpcId = PeerVpcId) output <- .gamelift$delete_vpc_peering_authorization_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$delete_vpc_peering_authorization <- gamelift_delete_vpc_peering_authorization gamelift_delete_vpc_peering_connection <- function(FleetId, VpcPeeringConnectionId) { op <- new_operation( name = "DeleteVpcPeeringConnection", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$delete_vpc_peering_connection_input(FleetId = FleetId, VpcPeeringConnectionId = VpcPeeringConnectionId) output <- .gamelift$delete_vpc_peering_connection_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$delete_vpc_peering_connection <- gamelift_delete_vpc_peering_connection gamelift_deregister_game_server <- function(GameServerGroupName, GameServerId) { op <- new_operation( name = "DeregisterGameServer", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$deregister_game_server_input(GameServerGroupName = GameServerGroupName, GameServerId = GameServerId) output <- .gamelift$deregister_game_server_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$deregister_game_server <- gamelift_deregister_game_server gamelift_describe_alias <- function(AliasId) { op <- new_operation( name = "DescribeAlias", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$describe_alias_input(AliasId = AliasId) output <- .gamelift$describe_alias_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$describe_alias <- gamelift_describe_alias gamelift_describe_build <- function(BuildId) { op <- new_operation( name = "DescribeBuild", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$describe_build_input(BuildId = BuildId) output <- .gamelift$describe_build_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$describe_build <- gamelift_describe_build gamelift_describe_ec2_instance_limits <- function(EC2InstanceType = NULL) { op <- new_operation( name = "DescribeEC2InstanceLimits", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$describe_ec2_instance_limits_input(EC2InstanceType = EC2InstanceType) output <- .gamelift$describe_ec2_instance_limits_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$describe_ec2_instance_limits <- gamelift_describe_ec2_instance_limits gamelift_describe_fleet_attributes <- function(FleetIds = NULL, Limit = NULL, NextToken = NULL) { op <- new_operation( name = "DescribeFleetAttributes", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$describe_fleet_attributes_input(FleetIds = FleetIds, Limit = Limit, NextToken = NextToken) output <- .gamelift$describe_fleet_attributes_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$describe_fleet_attributes <- gamelift_describe_fleet_attributes gamelift_describe_fleet_capacity <- function(FleetIds = NULL, Limit = NULL, NextToken = NULL) { op <- new_operation( name = "DescribeFleetCapacity", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$describe_fleet_capacity_input(FleetIds = FleetIds, Limit = Limit, NextToken = NextToken) output <- .gamelift$describe_fleet_capacity_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$describe_fleet_capacity <- gamelift_describe_fleet_capacity gamelift_describe_fleet_events <- function(FleetId, StartTime = NULL, EndTime = NULL, Limit = NULL, NextToken = NULL) { op <- new_operation( name = "DescribeFleetEvents", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$describe_fleet_events_input(FleetId = FleetId, StartTime = StartTime, EndTime = EndTime, Limit = Limit, NextToken = NextToken) output <- .gamelift$describe_fleet_events_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$describe_fleet_events <- gamelift_describe_fleet_events gamelift_describe_fleet_port_settings <- function(FleetId) { op <- new_operation( name = "DescribeFleetPortSettings", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$describe_fleet_port_settings_input(FleetId = FleetId) output <- .gamelift$describe_fleet_port_settings_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$describe_fleet_port_settings <- gamelift_describe_fleet_port_settings gamelift_describe_fleet_utilization <- function(FleetIds = NULL, Limit = NULL, NextToken = NULL) { op <- new_operation( name = "DescribeFleetUtilization", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$describe_fleet_utilization_input(FleetIds = FleetIds, Limit = Limit, NextToken = NextToken) output <- .gamelift$describe_fleet_utilization_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$describe_fleet_utilization <- gamelift_describe_fleet_utilization gamelift_describe_game_server <- function(GameServerGroupName, GameServerId) { op <- new_operation( name = "DescribeGameServer", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$describe_game_server_input(GameServerGroupName = GameServerGroupName, GameServerId = GameServerId) output <- .gamelift$describe_game_server_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$describe_game_server <- gamelift_describe_game_server gamelift_describe_game_server_group <- function(GameServerGroupName) { op <- new_operation( name = "DescribeGameServerGroup", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$describe_game_server_group_input(GameServerGroupName = GameServerGroupName) output <- .gamelift$describe_game_server_group_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$describe_game_server_group <- gamelift_describe_game_server_group gamelift_describe_game_server_instances <- function(GameServerGroupName, InstanceIds = NULL, Limit = NULL, NextToken = NULL) { op <- new_operation( name = "DescribeGameServerInstances", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$describe_game_server_instances_input(GameServerGroupName = GameServerGroupName, InstanceIds = InstanceIds, Limit = Limit, NextToken = NextToken) output <- .gamelift$describe_game_server_instances_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$describe_game_server_instances <- gamelift_describe_game_server_instances gamelift_describe_game_session_details <- function(FleetId = NULL, GameSessionId = NULL, AliasId = NULL, StatusFilter = NULL, Limit = NULL, NextToken = NULL) { op <- new_operation( name = "DescribeGameSessionDetails", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$describe_game_session_details_input(FleetId = FleetId, GameSessionId = GameSessionId, AliasId = AliasId, StatusFilter = StatusFilter, Limit = Limit, NextToken = NextToken) output <- .gamelift$describe_game_session_details_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$describe_game_session_details <- gamelift_describe_game_session_details gamelift_describe_game_session_placement <- function(PlacementId) { op <- new_operation( name = "DescribeGameSessionPlacement", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$describe_game_session_placement_input(PlacementId = PlacementId) output <- .gamelift$describe_game_session_placement_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$describe_game_session_placement <- gamelift_describe_game_session_placement gamelift_describe_game_session_queues <- function(Names = NULL, Limit = NULL, NextToken = NULL) { op <- new_operation( name = "DescribeGameSessionQueues", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$describe_game_session_queues_input(Names = Names, Limit = Limit, NextToken = NextToken) output <- .gamelift$describe_game_session_queues_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$describe_game_session_queues <- gamelift_describe_game_session_queues gamelift_describe_game_sessions <- function(FleetId = NULL, GameSessionId = NULL, AliasId = NULL, StatusFilter = NULL, Limit = NULL, NextToken = NULL) { op <- new_operation( name = "DescribeGameSessions", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$describe_game_sessions_input(FleetId = FleetId, GameSessionId = GameSessionId, AliasId = AliasId, StatusFilter = StatusFilter, Limit = Limit, NextToken = NextToken) output <- .gamelift$describe_game_sessions_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$describe_game_sessions <- gamelift_describe_game_sessions gamelift_describe_instances <- function(FleetId, InstanceId = NULL, Limit = NULL, NextToken = NULL) { op <- new_operation( name = "DescribeInstances", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$describe_instances_input(FleetId = FleetId, InstanceId = InstanceId, Limit = Limit, NextToken = NextToken) output <- .gamelift$describe_instances_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$describe_instances <- gamelift_describe_instances gamelift_describe_matchmaking <- function(TicketIds) { op <- new_operation( name = "DescribeMatchmaking", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$describe_matchmaking_input(TicketIds = TicketIds) output <- .gamelift$describe_matchmaking_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$describe_matchmaking <- gamelift_describe_matchmaking gamelift_describe_matchmaking_configurations <- function(Names = NULL, RuleSetName = NULL, Limit = NULL, NextToken = NULL) { op <- new_operation( name = "DescribeMatchmakingConfigurations", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$describe_matchmaking_configurations_input(Names = Names, RuleSetName = RuleSetName, Limit = Limit, NextToken = NextToken) output <- .gamelift$describe_matchmaking_configurations_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$describe_matchmaking_configurations <- gamelift_describe_matchmaking_configurations gamelift_describe_matchmaking_rule_sets <- function(Names = NULL, Limit = NULL, NextToken = NULL) { op <- new_operation( name = "DescribeMatchmakingRuleSets", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$describe_matchmaking_rule_sets_input(Names = Names, Limit = Limit, NextToken = NextToken) output <- .gamelift$describe_matchmaking_rule_sets_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$describe_matchmaking_rule_sets <- gamelift_describe_matchmaking_rule_sets gamelift_describe_player_sessions <- function(GameSessionId = NULL, PlayerId = NULL, PlayerSessionId = NULL, PlayerSessionStatusFilter = NULL, Limit = NULL, NextToken = NULL) { op <- new_operation( name = "DescribePlayerSessions", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$describe_player_sessions_input(GameSessionId = GameSessionId, PlayerId = PlayerId, PlayerSessionId = PlayerSessionId, PlayerSessionStatusFilter = PlayerSessionStatusFilter, Limit = Limit, NextToken = NextToken) output <- .gamelift$describe_player_sessions_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$describe_player_sessions <- gamelift_describe_player_sessions gamelift_describe_runtime_configuration <- function(FleetId) { op <- new_operation( name = "DescribeRuntimeConfiguration", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$describe_runtime_configuration_input(FleetId = FleetId) output <- .gamelift$describe_runtime_configuration_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$describe_runtime_configuration <- gamelift_describe_runtime_configuration gamelift_describe_scaling_policies <- function(FleetId, StatusFilter = NULL, Limit = NULL, NextToken = NULL) { op <- new_operation( name = "DescribeScalingPolicies", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$describe_scaling_policies_input(FleetId = FleetId, StatusFilter = StatusFilter, Limit = Limit, NextToken = NextToken) output <- .gamelift$describe_scaling_policies_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$describe_scaling_policies <- gamelift_describe_scaling_policies gamelift_describe_script <- function(ScriptId) { op <- new_operation( name = "DescribeScript", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$describe_script_input(ScriptId = ScriptId) output <- .gamelift$describe_script_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$describe_script <- gamelift_describe_script gamelift_describe_vpc_peering_authorizations <- function() { op <- new_operation( name = "DescribeVpcPeeringAuthorizations", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$describe_vpc_peering_authorizations_input() output <- .gamelift$describe_vpc_peering_authorizations_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$describe_vpc_peering_authorizations <- gamelift_describe_vpc_peering_authorizations gamelift_describe_vpc_peering_connections <- function(FleetId = NULL) { op <- new_operation( name = "DescribeVpcPeeringConnections", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$describe_vpc_peering_connections_input(FleetId = FleetId) output <- .gamelift$describe_vpc_peering_connections_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$describe_vpc_peering_connections <- gamelift_describe_vpc_peering_connections gamelift_get_game_session_log_url <- function(GameSessionId) { op <- new_operation( name = "GetGameSessionLogUrl", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$get_game_session_log_url_input(GameSessionId = GameSessionId) output <- .gamelift$get_game_session_log_url_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$get_game_session_log_url <- gamelift_get_game_session_log_url gamelift_get_instance_access <- function(FleetId, InstanceId) { op <- new_operation( name = "GetInstanceAccess", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$get_instance_access_input(FleetId = FleetId, InstanceId = InstanceId) output <- .gamelift$get_instance_access_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$get_instance_access <- gamelift_get_instance_access gamelift_list_aliases <- function(RoutingStrategyType = NULL, Name = NULL, Limit = NULL, NextToken = NULL) { op <- new_operation( name = "ListAliases", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$list_aliases_input(RoutingStrategyType = RoutingStrategyType, Name = Name, Limit = Limit, NextToken = NextToken) output <- .gamelift$list_aliases_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$list_aliases <- gamelift_list_aliases gamelift_list_builds <- function(Status = NULL, Limit = NULL, NextToken = NULL) { op <- new_operation( name = "ListBuilds", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$list_builds_input(Status = Status, Limit = Limit, NextToken = NextToken) output <- .gamelift$list_builds_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$list_builds <- gamelift_list_builds gamelift_list_fleets <- function(BuildId = NULL, ScriptId = NULL, Limit = NULL, NextToken = NULL) { op <- new_operation( name = "ListFleets", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$list_fleets_input(BuildId = BuildId, ScriptId = ScriptId, Limit = Limit, NextToken = NextToken) output <- .gamelift$list_fleets_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$list_fleets <- gamelift_list_fleets gamelift_list_game_server_groups <- function(Limit = NULL, NextToken = NULL) { op <- new_operation( name = "ListGameServerGroups", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$list_game_server_groups_input(Limit = Limit, NextToken = NextToken) output <- .gamelift$list_game_server_groups_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$list_game_server_groups <- gamelift_list_game_server_groups gamelift_list_game_servers <- function(GameServerGroupName, SortOrder = NULL, Limit = NULL, NextToken = NULL) { op <- new_operation( name = "ListGameServers", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$list_game_servers_input(GameServerGroupName = GameServerGroupName, SortOrder = SortOrder, Limit = Limit, NextToken = NextToken) output <- .gamelift$list_game_servers_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$list_game_servers <- gamelift_list_game_servers gamelift_list_scripts <- function(Limit = NULL, NextToken = NULL) { op <- new_operation( name = "ListScripts", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$list_scripts_input(Limit = Limit, NextToken = NextToken) output <- .gamelift$list_scripts_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$list_scripts <- gamelift_list_scripts gamelift_list_tags_for_resource <- function(ResourceARN) { op <- new_operation( name = "ListTagsForResource", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$list_tags_for_resource_input(ResourceARN = ResourceARN) output <- .gamelift$list_tags_for_resource_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$list_tags_for_resource <- gamelift_list_tags_for_resource gamelift_put_scaling_policy <- function(Name, FleetId, ScalingAdjustment = NULL, ScalingAdjustmentType = NULL, Threshold = NULL, ComparisonOperator = NULL, EvaluationPeriods = NULL, MetricName, PolicyType = NULL, TargetConfiguration = NULL) { op <- new_operation( name = "PutScalingPolicy", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$put_scaling_policy_input(Name = Name, FleetId = FleetId, ScalingAdjustment = ScalingAdjustment, ScalingAdjustmentType = ScalingAdjustmentType, Threshold = Threshold, ComparisonOperator = ComparisonOperator, EvaluationPeriods = EvaluationPeriods, MetricName = MetricName, PolicyType = PolicyType, TargetConfiguration = TargetConfiguration) output <- .gamelift$put_scaling_policy_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$put_scaling_policy <- gamelift_put_scaling_policy gamelift_register_game_server <- function(GameServerGroupName, GameServerId, InstanceId, ConnectionInfo = NULL, GameServerData = NULL) { op <- new_operation( name = "RegisterGameServer", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$register_game_server_input(GameServerGroupName = GameServerGroupName, GameServerId = GameServerId, InstanceId = InstanceId, ConnectionInfo = ConnectionInfo, GameServerData = GameServerData) output <- .gamelift$register_game_server_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$register_game_server <- gamelift_register_game_server gamelift_request_upload_credentials <- function(BuildId) { op <- new_operation( name = "RequestUploadCredentials", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$request_upload_credentials_input(BuildId = BuildId) output <- .gamelift$request_upload_credentials_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$request_upload_credentials <- gamelift_request_upload_credentials gamelift_resolve_alias <- function(AliasId) { op <- new_operation( name = "ResolveAlias", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$resolve_alias_input(AliasId = AliasId) output <- .gamelift$resolve_alias_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$resolve_alias <- gamelift_resolve_alias gamelift_resume_game_server_group <- function(GameServerGroupName, ResumeActions) { op <- new_operation( name = "ResumeGameServerGroup", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$resume_game_server_group_input(GameServerGroupName = GameServerGroupName, ResumeActions = ResumeActions) output <- .gamelift$resume_game_server_group_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$resume_game_server_group <- gamelift_resume_game_server_group gamelift_search_game_sessions <- function(FleetId = NULL, AliasId = NULL, FilterExpression = NULL, SortExpression = NULL, Limit = NULL, NextToken = NULL) { op <- new_operation( name = "SearchGameSessions", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$search_game_sessions_input(FleetId = FleetId, AliasId = AliasId, FilterExpression = FilterExpression, SortExpression = SortExpression, Limit = Limit, NextToken = NextToken) output <- .gamelift$search_game_sessions_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$search_game_sessions <- gamelift_search_game_sessions gamelift_start_fleet_actions <- function(FleetId, Actions) { op <- new_operation( name = "StartFleetActions", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$start_fleet_actions_input(FleetId = FleetId, Actions = Actions) output <- .gamelift$start_fleet_actions_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$start_fleet_actions <- gamelift_start_fleet_actions gamelift_start_game_session_placement <- function(PlacementId, GameSessionQueueName, GameProperties = NULL, MaximumPlayerSessionCount, GameSessionName = NULL, PlayerLatencies = NULL, DesiredPlayerSessions = NULL, GameSessionData = NULL) { op <- new_operation( name = "StartGameSessionPlacement", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$start_game_session_placement_input(PlacementId = PlacementId, GameSessionQueueName = GameSessionQueueName, GameProperties = GameProperties, MaximumPlayerSessionCount = MaximumPlayerSessionCount, GameSessionName = GameSessionName, PlayerLatencies = PlayerLatencies, DesiredPlayerSessions = DesiredPlayerSessions, GameSessionData = GameSessionData) output <- .gamelift$start_game_session_placement_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$start_game_session_placement <- gamelift_start_game_session_placement gamelift_start_match_backfill <- function(TicketId = NULL, ConfigurationName, GameSessionArn = NULL, Players) { op <- new_operation( name = "StartMatchBackfill", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$start_match_backfill_input(TicketId = TicketId, ConfigurationName = ConfigurationName, GameSessionArn = GameSessionArn, Players = Players) output <- .gamelift$start_match_backfill_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$start_match_backfill <- gamelift_start_match_backfill gamelift_start_matchmaking <- function(TicketId = NULL, ConfigurationName, Players) { op <- new_operation( name = "StartMatchmaking", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$start_matchmaking_input(TicketId = TicketId, ConfigurationName = ConfigurationName, Players = Players) output <- .gamelift$start_matchmaking_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$start_matchmaking <- gamelift_start_matchmaking gamelift_stop_fleet_actions <- function(FleetId, Actions) { op <- new_operation( name = "StopFleetActions", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$stop_fleet_actions_input(FleetId = FleetId, Actions = Actions) output <- .gamelift$stop_fleet_actions_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$stop_fleet_actions <- gamelift_stop_fleet_actions gamelift_stop_game_session_placement <- function(PlacementId) { op <- new_operation( name = "StopGameSessionPlacement", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$stop_game_session_placement_input(PlacementId = PlacementId) output <- .gamelift$stop_game_session_placement_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$stop_game_session_placement <- gamelift_stop_game_session_placement gamelift_stop_matchmaking <- function(TicketId) { op <- new_operation( name = "StopMatchmaking", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$stop_matchmaking_input(TicketId = TicketId) output <- .gamelift$stop_matchmaking_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$stop_matchmaking <- gamelift_stop_matchmaking gamelift_suspend_game_server_group <- function(GameServerGroupName, SuspendActions) { op <- new_operation( name = "SuspendGameServerGroup", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$suspend_game_server_group_input(GameServerGroupName = GameServerGroupName, SuspendActions = SuspendActions) output <- .gamelift$suspend_game_server_group_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$suspend_game_server_group <- gamelift_suspend_game_server_group gamelift_tag_resource <- function(ResourceARN, Tags) { op <- new_operation( name = "TagResource", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$tag_resource_input(ResourceARN = ResourceARN, Tags = Tags) output <- .gamelift$tag_resource_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$tag_resource <- gamelift_tag_resource gamelift_untag_resource <- function(ResourceARN, TagKeys) { op <- new_operation( name = "UntagResource", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$untag_resource_input(ResourceARN = ResourceARN, TagKeys = TagKeys) output <- .gamelift$untag_resource_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$untag_resource <- gamelift_untag_resource gamelift_update_alias <- function(AliasId, Name = NULL, Description = NULL, RoutingStrategy = NULL) { op <- new_operation( name = "UpdateAlias", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$update_alias_input(AliasId = AliasId, Name = Name, Description = Description, RoutingStrategy = RoutingStrategy) output <- .gamelift$update_alias_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$update_alias <- gamelift_update_alias gamelift_update_build <- function(BuildId, Name = NULL, Version = NULL) { op <- new_operation( name = "UpdateBuild", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$update_build_input(BuildId = BuildId, Name = Name, Version = Version) output <- .gamelift$update_build_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$update_build <- gamelift_update_build gamelift_update_fleet_attributes <- function(FleetId, Name = NULL, Description = NULL, NewGameSessionProtectionPolicy = NULL, ResourceCreationLimitPolicy = NULL, MetricGroups = NULL) { op <- new_operation( name = "UpdateFleetAttributes", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$update_fleet_attributes_input(FleetId = FleetId, Name = Name, Description = Description, NewGameSessionProtectionPolicy = NewGameSessionProtectionPolicy, ResourceCreationLimitPolicy = ResourceCreationLimitPolicy, MetricGroups = MetricGroups) output <- .gamelift$update_fleet_attributes_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$update_fleet_attributes <- gamelift_update_fleet_attributes gamelift_update_fleet_capacity <- function(FleetId, DesiredInstances = NULL, MinSize = NULL, MaxSize = NULL) { op <- new_operation( name = "UpdateFleetCapacity", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$update_fleet_capacity_input(FleetId = FleetId, DesiredInstances = DesiredInstances, MinSize = MinSize, MaxSize = MaxSize) output <- .gamelift$update_fleet_capacity_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$update_fleet_capacity <- gamelift_update_fleet_capacity gamelift_update_fleet_port_settings <- function(FleetId, InboundPermissionAuthorizations = NULL, InboundPermissionRevocations = NULL) { op <- new_operation( name = "UpdateFleetPortSettings", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$update_fleet_port_settings_input(FleetId = FleetId, InboundPermissionAuthorizations = InboundPermissionAuthorizations, InboundPermissionRevocations = InboundPermissionRevocations) output <- .gamelift$update_fleet_port_settings_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$update_fleet_port_settings <- gamelift_update_fleet_port_settings gamelift_update_game_server <- function(GameServerGroupName, GameServerId, GameServerData = NULL, UtilizationStatus = NULL, HealthCheck = NULL) { op <- new_operation( name = "UpdateGameServer", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$update_game_server_input(GameServerGroupName = GameServerGroupName, GameServerId = GameServerId, GameServerData = GameServerData, UtilizationStatus = UtilizationStatus, HealthCheck = HealthCheck) output <- .gamelift$update_game_server_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$update_game_server <- gamelift_update_game_server gamelift_update_game_server_group <- function(GameServerGroupName, RoleArn = NULL, InstanceDefinitions = NULL, GameServerProtectionPolicy = NULL, BalancingStrategy = NULL) { op <- new_operation( name = "UpdateGameServerGroup", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$update_game_server_group_input(GameServerGroupName = GameServerGroupName, RoleArn = RoleArn, InstanceDefinitions = InstanceDefinitions, GameServerProtectionPolicy = GameServerProtectionPolicy, BalancingStrategy = BalancingStrategy) output <- .gamelift$update_game_server_group_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$update_game_server_group <- gamelift_update_game_server_group gamelift_update_game_session <- function(GameSessionId, MaximumPlayerSessionCount = NULL, Name = NULL, PlayerSessionCreationPolicy = NULL, ProtectionPolicy = NULL) { op <- new_operation( name = "UpdateGameSession", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$update_game_session_input(GameSessionId = GameSessionId, MaximumPlayerSessionCount = MaximumPlayerSessionCount, Name = Name, PlayerSessionCreationPolicy = PlayerSessionCreationPolicy, ProtectionPolicy = ProtectionPolicy) output <- .gamelift$update_game_session_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$update_game_session <- gamelift_update_game_session gamelift_update_game_session_queue <- function(Name, TimeoutInSeconds = NULL, PlayerLatencyPolicies = NULL, Destinations = NULL) { op <- new_operation( name = "UpdateGameSessionQueue", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$update_game_session_queue_input(Name = Name, TimeoutInSeconds = TimeoutInSeconds, PlayerLatencyPolicies = PlayerLatencyPolicies, Destinations = Destinations) output <- .gamelift$update_game_session_queue_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$update_game_session_queue <- gamelift_update_game_session_queue gamelift_update_matchmaking_configuration <- function(Name, Description = NULL, GameSessionQueueArns = NULL, RequestTimeoutSeconds = NULL, AcceptanceTimeoutSeconds = NULL, AcceptanceRequired = NULL, RuleSetName = NULL, NotificationTarget = NULL, AdditionalPlayerCount = NULL, CustomEventData = NULL, GameProperties = NULL, GameSessionData = NULL, BackfillMode = NULL, FlexMatchMode = NULL) { op <- new_operation( name = "UpdateMatchmakingConfiguration", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$update_matchmaking_configuration_input(Name = Name, Description = Description, GameSessionQueueArns = GameSessionQueueArns, RequestTimeoutSeconds = RequestTimeoutSeconds, AcceptanceTimeoutSeconds = AcceptanceTimeoutSeconds, AcceptanceRequired = AcceptanceRequired, RuleSetName = RuleSetName, NotificationTarget = NotificationTarget, AdditionalPlayerCount = AdditionalPlayerCount, CustomEventData = CustomEventData, GameProperties = GameProperties, GameSessionData = GameSessionData, BackfillMode = BackfillMode, FlexMatchMode = FlexMatchMode) output <- .gamelift$update_matchmaking_configuration_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$update_matchmaking_configuration <- gamelift_update_matchmaking_configuration gamelift_update_runtime_configuration <- function(FleetId, RuntimeConfiguration) { op <- new_operation( name = "UpdateRuntimeConfiguration", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$update_runtime_configuration_input(FleetId = FleetId, RuntimeConfiguration = RuntimeConfiguration) output <- .gamelift$update_runtime_configuration_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$update_runtime_configuration <- gamelift_update_runtime_configuration gamelift_update_script <- function(ScriptId, Name = NULL, Version = NULL, StorageLocation = NULL, ZipFile = NULL) { op <- new_operation( name = "UpdateScript", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$update_script_input(ScriptId = ScriptId, Name = Name, Version = Version, StorageLocation = StorageLocation, ZipFile = ZipFile) output <- .gamelift$update_script_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$update_script <- gamelift_update_script gamelift_validate_matchmaking_rule_set <- function(RuleSetBody) { op <- new_operation( name = "ValidateMatchmakingRuleSet", http_method = "POST", http_path = "/", paginator = list() ) input <- .gamelift$validate_matchmaking_rule_set_input(RuleSetBody = RuleSetBody) output <- .gamelift$validate_matchmaking_rule_set_output() config <- get_config() svc <- .gamelift$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .gamelift$operations$validate_matchmaking_rule_set <- gamelift_validate_matchmaking_rule_set
require(geometa, quietly = TRUE) require(testthat) context("ISOMultiplicityRange") test_that("encoding",{ testthat::skip_on_cran() md <- ISOMultiplicityRange$new(lower = 1, upper = 1) expect_is(md, "ISOMultiplicityRange") xml <- md$encode() expect_is(xml, "XMLInternalNode") md2 <- ISOMultiplicityRange$new(xml = xml) xml2 <- md2$encode() expect_true(ISOAbstractObject$compare(md, md2)) })
condProbEntropy <- function(idroot, ppars, pcatlist, probs, idx) { if(is.null(ppars) || length(idx) < 1) { nodep <- probs nodep <- nodep[nodep!=0] return(log(as.numeric(length(pcatlist[[idroot]]))) + sum(nodep*log(nodep))) } idnode <- ppars[idx[1]] return(sum(sapply(seq(1, length(pcatlist[[idnode]])), function(cat) condProbEntropy(idroot, ppars, pcatlist, probs[[cat]], idx[-1])) )) } setMethod("cnKLComplexity", c("catNetwork"), function(object, node=NULL) { if(!is(object, "catNetwork")) stop("The object should be a catNetwork") if(is.null(node)) node <- 1:object@numnodes if(is.character(node)) node <- which(object@nodes == node) if(!is.numeric(node)) node <- 1:object@numnodes nodeEntropy <- sum(sapply(node, function(i) { idx <- NULL if(length(object@parents[[i]])>0) idx <- 1:length(object@parents[[i]]) return(condProbEntropy(i, object@parents[[i]], object@categories, object@probabilities[[i]], idx)) })) return(nodeEntropy) }) cnEntropy <- function(data, perturbations=NULL) { if(!is.matrix(data) && !is.data.frame(data)) stop("'data' should be a matrix or data frame of categories") if(is.data.frame(data)) { data <- as.matrix(t(data)) if(!is.null(perturbations)) { if(!is.data.frame(perturbations)) stop("Perturbations should be a data frame") perturbations <- as.matrix(t(perturbations)) } } r <- .categorizeSample(data, perturbations, object=NULL, ask=FALSE) data <- r$data perturbations <- r$perturbations numnodes <- dim(data)[1] numsamples <- dim(data)[2] nodenames <- rownames(data) mat <- .Call("ccnEntropyPairwise", data, perturbations, PACKAGE="catnet") klmat <- matrix(mat, numnodes, numnodes) rownames(klmat)<-nodenames colnames(klmat)<-nodenames return(klmat) } cnEdgeDistanceKL <- function(data, perturbations) { if(!is.matrix(data) && !is.data.frame(data)) stop("'data' should be a matrix or data frame of categories") if(is.null(perturbations)) { warning("Perturbations are essential for estimating the pairwise causality") } if(is.data.frame(data)) { data <- as.matrix(t(data)) if(!is.null(perturbations)) { if(!is.data.frame(perturbations)) stop("Perturbations should be a data frame") perturbations <- as.matrix(t(perturbations)) } } r <- .categorizeSample(data, perturbations, object=NULL, ask=FALSE) data <- r$data perturbations <- r$perturbations numnodes <- dim(data)[1] numsamples <- dim(data)[2] nodenames <- rownames(data) mat <- .Call("ccnKLPairwise", data, perturbations, PACKAGE="catnet") klmat <- matrix(mat, numnodes, numnodes) rownames(klmat)<-nodenames colnames(klmat)<-nodenames return(klmat) } cnEntropyOrder <- function(data, perturbations=NULL) { if(!is.matrix(data) && !is.data.frame(data)) stop("'data' should be a matrix or data frame of categories") if(is.data.frame(data)) { data <- as.matrix(t(data)) if(!is.null(perturbations)) { if(!is.data.frame(perturbations)) stop("Perturbations should be a data frame") perturbations <- as.matrix(t(perturbations)) } } r <- .categorizeSample(data, perturbations, object=NULL, ask=FALSE) data <- r$data perturbations <- r$perturbations numnodes <- dim(data)[1] numsamples <- dim(data)[2] nodenames <- rownames(data) norder <- .Call("ccnEntropyOrder", data, perturbations, PACKAGE="catnet") names(norder) <- nodenames return(norder) }
knitr::opts_chunk$set( collapse = TRUE, comment = " ) library(mde) na_summary(airquality) na_summary(airquality,sort_by = "percent_complete") na_summary(airquality, sort_by = "percent_missing") na_summary(airquality, sort_by="percent_missing", descending = TRUE) na_summary(airquality, exclude_cols = c("Day", "Wind")) test2 <- data.frame(ID= c("A","A","B","A","B"), Vals = c(rep(NA,4),"No"),ID2 = c("E","E","D","E","D")) na_summary(test2,grouping_cols = c("ID","ID2")) na_summary(test2, grouping_cols="ID") get_na_counts(airquality) test <- structure(list(Subject = structure(c(1L, 1L, 2L, 2L), .Label = c("A", "B"), class = "factor"), res = c(NA, 1, 2, 3), ID = structure(c(1L, 1L, 2L, 2L), .Label = c("1", "2"), class = "factor")), class = "data.frame", row.names = c(NA, -4L)) get_na_counts(test, grouping_cols = "ID") percent_missing(airquality) percent_missing(test, grouping_cols = "Subject") percent_missing(airquality,exclude_cols = c("Day","Temp")) sort_by_missingness(airquality, sort_by = "counts") sort_by_missingness(airquality, sort_by = "counts", descend = TRUE) sort_by_missingness(airquality, sort_by = "percents") dummy_test <- data.frame(ID = c("A","B","B","A"), values = c("n/a",NA,"Yes","No")) head(recode_as_na(dummy_test, value = c("n/a","No"))) another_dummy <- data.frame(ID = 1:5, Subject = 7:11, Change = c("missing","n/a",2:4 )) head(recode_as_na(another_dummy, subset_cols = "Change", value = c("n/a","missing"))) head(recode_as_na(airquality,value=190,pattern_type="starts_with",pattern="Solar")) head(recode_as_na(airquality,value=c(67,118),pattern_type="starts_with",pattern="S|O")) head(recode_as_na(airquality,value=c(67,118),pattern_type="regex",pattern="(?i)^(s|o)")) head(recode_as_na_if(airquality,sign="gt", percent_na=20)) partial_match <- data.frame(A=c("Hi","match_me","nope"), B=c(NA, "not_me","nah")) recode_as_na_str(partial_match,"ends_with","ME", case_sensitive=FALSE) head(recode_as_na_for(airquality,criteria="gt",value=25)) head(recode_as_na_for(airquality, value=40,subset_cols=c("Solar.R","Ozone"), criteria="gt")) head(recode_na_as(airquality)) head(recode_na_as(airquality, value=NaN)) head(recode_na_as(airquality, value=0, subset_cols="Ozone")) head(mde::recode_na_as(airquality, value=0, pattern_type="starts_with",pattern="Solar")) head(column_based_recode(airquality, values_from = "Wind", values_to="Wind", pattern_type = "regex", pattern = "Solar|Ozone")) head(custom_na_recode(airquality)) head(custom_na_recode(airquality,func="mean",across_columns=c("Solar.R","Ozone"))) head(custom_na_recode(airquality,func=dplyr::lead )) some_data <- data.frame(ID=c("A1","A1","A1","A2","A2", "A2"),A=c(5,NA,0,8,3,4),B=c(10,0,0,NA,5,6),C=c(1,NA,NA,25,7,8)) head(custom_na_recode(some_data,func = "mean", grouping_cols = "ID")) head(custom_na_recode(some_data,func = "mean", grouping_cols = "ID", across_columns = c("C", "A"))) some_data <- data.frame(ID=c("A1","A2","A3", "A4"), A=c(5,NA,0,8), B=c(10,0,0,1), C=c(1,NA,NA,25)) head(recode_na_if(some_data,grouping_col="ID", target_groups=c("A2","A3"), replacement= 0)) head(drop_na_if(airquality, sign="gteq",percent_na = 24)) head(drop_na_if(airquality, percent_na = 24, keep_columns = "Ozone")) head(drop_na_if(airquality, percent_na = 24)) grouped_drop <- structure(list(ID = c("A", "A", "B", "A", "B"), Vals = c(4, NA, NA, NA, NA), Values = c(5, 6, 7, 8, NA)), row.names = c(NA, -5L), class = "data.frame") drop_na_if(grouped_drop,percent_na = 67,sign="gteq", grouping_cols = "ID") head(drop_row_if(airquality, sign="gteq", type="count" , value = 2)) head(drop_row_if(airquality, type="percent", value=16, sign="gteq", as_percent=TRUE)) head(drop_na_at(airquality,pattern_type = "starts_with","O")) test2 <- data.frame(ID= c("A","A","B","A","B"), Vals = c(4,rep(NA, 4))) drop_all_na(test2, grouping_cols="ID") test2 <- data.frame(ID= c("A","A","B","A","B"), Vals = rep(NA, 5)) head(drop_all_na(test, grouping_cols = "ID"))
NULL setMethod('dbClearResult', c('PrestoResult'), function(res, ...) { if (dbHasCompleted(res)) { return(TRUE) } uri <- res@cursor$nextUri() if (uri == '') { return(TRUE) } if (res@cursor$state() == '__KILLED') { return(TRUE) } headers <- .request_headers(res@connection) delete.uri <- paste0( res@connection@host, ':', res@connection@port, '/v1/query/', [email protected] ) delete.result <- httr::DELETE(delete.uri, config=headers) s <- httr::status_code(delete.result) if (s >= 200 && s < 300) { res@cursor$state('__KILLED') rv <- TRUE } else { rv <- FALSE } return(rv) } )
.check_multicollinearity <- function(model, method = "equivalence_test", threshold = 0.7, ...) { valid_parameters <- insight::find_parameters(model, parameters = "^(?!(r_|sd_|prior_|cor_|lp__|b\\[))", flatten = TRUE) if (inherits(model, "stanfit")) { dat <- insight::get_parameters(model)[, valid_parameters, drop = FALSE] } else { dat <- as.data.frame(model, optional = FALSE)[, valid_parameters, drop = FALSE] } if (ncol(dat) > 2) { dat <- dat[, -1, drop = FALSE] if (ncol(dat) > 1) { parameter_correlation <- stats::cor(dat) parameter <- expand.grid(colnames(dat), colnames(dat), stringsAsFactors = FALSE) results <- cbind( parameter, corr = abs(as.vector(expand.grid(parameter_correlation)[[1]])), pvalue = apply(parameter, 1, function(r) stats::cor.test(dat[[r[1]]], dat[[r[2]]])$p.value) ) results <- results[results$pvalue < 0.05 & results$Var1 != results$Var2, ] if (nrow(results) > 0) { results$where <- paste0(results$Var1, " and ", results$Var2) results$where2 <- paste0(results$Var2, " and ", results$Var1) to_remove <- c() for (i in 1:nrow(results)) { if (results$where2[i] %in% results$where[1:i]) { to_remove <- c(to_remove, i) } } results <- results[-to_remove, ] threshold <- ifelse(threshold >= .9, .9, threshold) results <- results[results$corr > threshold & results$corr <= .9, ] if (nrow(results) > 0) { where <- paste0("between ", paste0(paste0(results$where, " (r = ", round(results$corr, 2), ")"), collapse = ", "), "") message("Possible multicollinearity ", where, ". This might lead to inappropriate results. See 'Details' in '?", method, "'.") } results <- results[results$corr > .9, ] if (nrow(results) > 0) { where <- paste0("between ", paste0(paste0(results$where, " (r = ", round(results$corr, 2), ")"), collapse = ", "), "") warning("Probable multicollinearity ", where, ". This might lead to inappropriate results. See 'Details' in '?", method, "'.", call. = FALSE) } } } } }
objective1TV <- function(x,T,phi,y,lambda) { X <- T %*% x OF <- norm( phi %*% X - y , c("F") ) ^ 2 + lambda * TV1 (X) return (OF) }
test_that('sample sizes must be equal', { set.seed(123) y <- rnorm(10) x <- rnorm(9) expect_error(grpsel(x, y)) }) test_that('group must have ncol(x) elements', { set.seed(123) y <- rnorm(10) x <- rnorm(10) expect_error(grpsel(x, y, group = 1:11)) }) test_that('group (as a list) must have ncol(x) elements', { set.seed(123) y <- rnorm(10) x <- rnorm(10) expect_error(grpsel(x, y, group = list(1:5, 6:11))) }) test_that('y must be in {0,1} with logistic loss', { set.seed(123) y <- rbinom(10, 1, 0.5) y[y == 0] <- - 1 x <- rnorm(10) expect_error(grpsel(x, y, loss = 'logistic')) }) test_that('y must not contain NAs', { set.seed(123) y <- rnorm(10) x <- rnorm(10) y[1] <- NA expect_error(grpsel(x, y)) }) test_that('x must not contain NAs', { set.seed(123) y <- rnorm(10) x <- rnorm(10) x[1] <- NA expect_error(grpsel(x, y)) }) test_that('lambda must contain a vector for every unique gamma', { set.seed(123) y <- rnorm(10) x <- rnorm(10) expect_error(grpsel(x, y, penalty = 'grSubset+grLasso', gamma = 1:5, lambda = 0)) }) test_that('lambda must contain ngamma vectors', { set.seed(123) y <- rnorm(10) x <- rnorm(10) expect_error(grpsel(x, y, penalty = 'grSubset+grLasso', ngamma = 5, lambda = 0)) }) test_that('nlambda must be greater than zero', { set.seed(123) y <- rnorm(10) x <- rnorm(10) expect_error(grpsel(x, y, nlambda = 0)) }) test_that('ngamma must be greater than zero', { set.seed(123) y <- rnorm(10) x <- rnorm(10) expect_error(grpsel(x, y, ngamma = 0)) }) test_that('alpha must be in (0,1)', { set.seed(123) y <- rnorm(10) x <- rnorm(10) expect_error(grpsel(x, y, alpha = 1)) }) test_that('when max.cd.iter is exceeded a warning is provided', { set.seed(123) y <- rnorm(100) x <- matrix(rnorm(100 * 10), 100, 10) expect_warning(grpsel(x, y, max.cd.iter = 5)) }) test_that('when max.ls.iter is exceeded a warning is provided', { set.seed(123) y <- rnorm(100) x <- matrix(rnorm(100 * 10), 100, 10) expect_warning(grpsel(x, y, max.ls.iter = 0)) }) test_that('gamma.min must be positive', { set.seed(123) y <- rnorm(10) x <- rnorm(10) expect_error(grpsel(x, y, gamma.min = 0)) }) test_that('gamma.max must be positive', { set.seed(123) y <- rnorm(10) x <- rnorm(10) expect_error(grpsel(x, y, gamma.max = 0)) }) test_that('subset.factor must have same length as group', { set.seed(123) y <- rnorm(10) x <- rnorm(10) expect_error(grpsel(x, y, subset.factor = rep(1, 11))) }) test_that('lasso.factor must have same length as group', { set.seed(123) y <- rnorm(10) x <- rnorm(10) expect_error(grpsel(x, y, lasso.factor = rep(1, 11))) }) test_that('ridge.factor must have same length as group', { set.seed(123) y <- rnorm(10) x <- rnorm(10) expect_error(grpsel(x, y, ridge.factor = rep(1, 11))) }) test_that('regression with square loss works', { set.seed(123) group <- rep(1:5, each = 2) x <- matrix(rnorm(100 * 10), 100, 10) y <- rnorm(100) fit <- grpsel(x, y, group, loss = 'square', eps = 1e-15) beta <- coef(fit)[, ncol(coef(fit))] beta.target <- as.numeric(glm(y ~ x, family = 'gaussian')$coef) expect_equal(beta, beta.target) }) test_that('regression with logistic loss works', { set.seed(123) group <- rep(1:5, each = 2) x <- matrix(rnorm(100 * 10), 100, 10) y <- rbinom(100, 1, 0.5) fit <- grpsel(x, y, group, loss = 'logistic', eps = 1e-15) beta <- coef(fit)[, ncol(coef(fit))] beta.target <- as.numeric(glm(y ~ x, family = 'binomial')$coef) expect_equal(beta, beta.target) }) test_that('regression with different sized groups works', { set.seed(123) group <- c(1, 1, 1, 1, 2, 2, 2, 3, 3, 4) x <- matrix(rnorm(100 * 10), 100, 10) y <- rnorm(100) fit <- grpsel(x, y, group, loss = 'square', eps = 1e-15) beta <- coef(fit)[, ncol(coef(fit))] beta.target <- as.numeric(glm(y ~ x, family = 'gaussian')$coef) expect_equal(beta, beta.target) }) test_that('regression with overlapping groups works', { set.seed(123) group <- list(1:5, 5:10) x <- matrix(rnorm(100 * 10), 100, 10) y <- rnorm(100) fit <- grpsel(x, y, group, loss = 'square', eps = 1e-15) beta <- coef(fit)[, ncol(coef(fit))] beta.target <- as.numeric(glm(y ~ x, family = 'gaussian')$coef) expect_equal(beta, beta.target) }) test_that('regression without orthogonalisation works', { set.seed(123) group <- rep(1:5, each = 2) x <- matrix(rnorm(100 * 10), 100, 10) y <- rnorm(100) fit <- grpsel(x, y, group, loss = 'square', eps = 1e-15, orthogonalise = F) beta <- coef(fit)[, ncol(coef(fit))] beta.target <- as.numeric(glm(y ~ x, family = 'gaussian')$coef) expect_equal(beta, beta.target) }) test_that('regression without sorting works', { set.seed(123) group <- rep(1:5, each = 2) x <- matrix(rnorm(100 * 10), 100, 10) y <- rnorm(100) fit <- grpsel(x, y, group, loss = 'square', eps = 1e-15, sort = F) beta <- coef(fit)[, ncol(coef(fit))] beta.target <- as.numeric(glm(y ~ x, family = 'gaussian')$coef) expect_equal(beta, beta.target) }) test_that('regression with screening works', { set.seed(123) group <- rep(1:15, each = 2) x <- matrix(rnorm(100 * 30), 100, 30) y <- rnorm(100) fit <- grpsel(x, y, group, loss = 'square', eps = 1e-15, screen = 5) beta <- coef(fit)[, ncol(coef(fit))] beta.target <- as.numeric(glm(y ~ x, family = 'gaussian')$coef) expect_equal(beta, beta.target) }) test_that('regression with screening and violations works', { set.seed(123) group <- rep(1:15, each = 2) x <- matrix(rnorm(100 * 30), 100, 30) y <- rowSums(x) + rnorm(100) fit <- grpsel(x, y, group, loss = 'square', eps = 1e-15, screen = 1) beta <- coef(fit)[, ncol(coef(fit))] beta.target <- as.numeric(glm(y ~ x, family = 'gaussian')$coef) expect_equal(beta, beta.target) }) test_that('regression with a constant response works', { set.seed(123) group <- rep(1:5, each = 2) x <- matrix(rnorm(100 * 10), 100, 10) y <- rep(1, 100) fit <- grpsel(x, y, group, loss = 'square', eps = 1e-15) beta <- coef(fit)[, ncol(coef(fit))] beta.target <- as.numeric(glm(y ~ x, family = 'gaussian')$coef) beta.target[2] <- 0 expect_equal(beta, beta.target) }) test_that('coefficients are extracted correctly', { set.seed(123) x <- matrix(rnorm(100 * 10), 100, 10) y <- rowSums(x) + rnorm(100) fit <- grpsel(x, y, eps = 1e-15) fit.target <- glm(y ~ x, family = 'gaussian') beta <- coef(fit, lambda = 0) beta.target <- as.matrix(as.numeric(coef(fit.target))) expect_equal(beta, beta.target) }) test_that('predictions are computed correctly', { set.seed(123) x <- matrix(rnorm(100 * 10), 100, 10) y <- rowSums(x) + rnorm(100) fit <- grpsel(x, y, eps = 1e-15) fit.target <- glm(y ~ x, family = 'gaussian') yhat <- predict(fit, x, lambda = 0) yhat.target <- as.matrix(as.numeric(predict(fit.target, as.data.frame(x)))) expect_equal(yhat, yhat.target) }) test_that('predictions are computed correctly when x is a data frame', { set.seed(123) x <- matrix(rnorm(100 * 10), 100, 10) y <- rowSums(x) + rnorm(100) fit <- grpsel(x, y, eps = 1e-15) fit.target <- glm(y ~ x, family = 'gaussian') yhat <- predict(fit, as.data.frame(x), lambda = 0) yhat.target <- as.matrix(as.numeric(predict(fit.target, as.data.frame(x)))) expect_equal(yhat, yhat.target) }) test_that('plot function returns a plot', { set.seed(123) x <- matrix(rnorm(100 * 10), 100, 10) y <- rowSums(x) + rnorm(100) fit <- grpsel(x, y, eps = 1e-15) p <- plot(fit) expect_s3_class(p, 'ggplot') }) test_that('number of predictors does not exceed pmax', { set.seed(123) group <- rep(1:5, each = 2) x <- matrix(rnorm(100 * 10), 100, 10) y <- rnorm(100) fit <- grpsel(x, y, group, loss = 'square', eps = 1e-15, pmax = 5) beta <- coef(fit)[, ncol(coef(fit))] sparsity <- sum(beta[- 1] != 0) expect_lte(sparsity, 5) }) test_that('number of groups does not exceed gmax', { set.seed(123) group <- rep(1:5, each = 2) x <- matrix(rnorm(100 * 10), 100, 10) y <- rnorm(100) fit <- grpsel(x, y, group, loss = 'square', eps = 1e-15, gmax = 2) beta <- coef(fit)[, ncol(coef(fit))] group.sparsity <- sum(vapply(unique(group), \(k) norm(beta[- 1][which(group == k)], '2'), numeric(1)) != 0) expect_lte(group.sparsity, 2) }) test_that('number of ridge solutions is ngamma', { set.seed(123) n <- 100 p <- 10 gamma <- 0.1 x <- matrix(rnorm(n * p), n, p) y <- rnorm(n) fit <- grpsel(x, y, penalty = 'grSubset+Ridge', ngamma = 5, lambda = rep(list(0), 5), eps = 1e-15) beta <- coef(fit) expect_equal(ncol(beta), 5) }) test_that('number of group lasso solutions is ngamma', { set.seed(123) n <- 100 p <- 10 gamma <- 0.1 x <- matrix(rnorm(n * p), n, p) y <- rnorm(n) fit <- grpsel(x, y, penalty = 'grSubset+grLasso', ngamma = 5, lambda = rep(list(0), 5), eps = 1e-15) beta <- coef(fit) expect_equal(ncol(beta), 5) }) test_that('number of group lasso solutions is ngamma for logistic loss', { set.seed(123) n <- 100 p <- 10 gamma <- 0.1 x <- matrix(rnorm(n * p), n, p) y <- rbinom(n, 1, 0.5) fit <- grpsel(x, y, penalty = 'grSubset+grLasso', loss = 'logistic', ngamma = 5, lambda = rep(list(0), 5), eps = 1e-15) beta <- coef(fit) expect_equal(ncol(beta), 5) }) test_that('number of group lasso solutions is ngamma for logistic loss', { set.seed(123) n <- 100 p <- 10 gamma <- 0.1 x <- matrix(rnorm(n * p), n, p) y <- rbinom(n, 1, 0.5) fit <- grpsel(x, y, penalty = 'grSubset+grLasso', loss = 'logistic', ngamma = 5, lambda = rep(list(0), 5), lasso.factor = c(0, rep(1, 9)), eps = 1e-15) beta <- coef(fit) expect_equal(ncol(beta), 5) }) test_that('number of group lasso solutions is ngamma', { set.seed(123) n <- 100 p <- 10 gamma <- 0.1 x <- matrix(rnorm(n * p), n, p) y <- rbinom(n, 1, 0.5) fit <- grpsel(x, y, penalty = 'grSubset+grLasso', ngamma = 5, lambda = rep(list(0), 5), lasso.factor = c(0, rep(1, 9)), eps = 1e-15) beta <- coef(fit) expect_equal(ncol(beta), 5) }) test_that('local search improves on coordinate descent for logistic loss', { set.seed(123) n <- 100 p <- 50 group <- rep(1:25, each = 2) x <- matrix(rnorm(n * p), n, p) + 2 * matrix(rnorm(n), n, p) y <- rbinom(n, 1, 1 / (1 + exp(- rowSums(x[, 1:10])))) fit.ls <- grpsel(x, y, group, loss = 'logistic', ls = T) fit.cd <- grpsel(x, y, group, loss = 'logistic', ls = F) loss.ls <- fit.ls$loss[[1]][which(fit.ls$np[[1]] %in% fit.cd$np[[1]])] loss.cd <- fit.cd$loss[[1]][which(fit.cd$np[[1]] %in% fit.ls$np[[1]])] expect_true(sum(loss.ls) < sum(loss.cd)) }) test_that('local search improves on coordinate descent for square loss', { set.seed(123) n <- 100 p <- 50 group <- rep(1:25, each = 2) x <- matrix(rnorm(n * p), n, p) + 2 * matrix(rnorm(n), n, p) y <- rnorm(n, rowSums(x[, 1:10])) fit.ls <- grpsel(x, y, group, loss = 'square', ls = T) fit.cd <- grpsel(x, y, group, loss = 'square', ls = F) loss.ls <- fit.ls$loss[[1]][which(fit.ls$np[[1]] %in% fit.cd$np[[1]])] loss.cd <- fit.cd$loss[[1]][which(fit.cd$np[[1]] %in% fit.ls$np[[1]])] expect_true(sum(loss.ls) < sum(loss.cd)) }) test_that('local search improves on coordinate descent for square loss without orthogonalisation', { set.seed(123) n <- 100 p <- 50 group <- rep(1:25, each = 2) x <- matrix(rnorm(n * p), n, p) + 2 * matrix(rnorm(n), n, p) y <- rnorm(n, rowSums(x[, 1:10])) fit.ls <- grpsel(x, y, group, loss = 'square', ls = T, orthogonalise = F) fit.cd <- grpsel(x, y, group, loss = 'square', ls = F, orthogonalise = F) loss.ls <- fit.ls$loss[[1]][which(fit.ls$np[[1]] %in% fit.cd$np[[1]])] loss.cd <- fit.cd$loss[[1]][which(fit.cd$np[[1]] %in% fit.ls$np[[1]])] expect_true(sum(loss.ls) < sum(loss.cd)) })
inside_var <- function(t,ascale_r,ascale_nr,tau,bshape,ascale_cens,p){ num = p*sapply(t,survw_integratef,ascale=ascale_r,bshape=bshape,tau=tau)+(1-p)*sapply(t,survw_integratef,ascale=ascale_nr,bshape=bshape,tau=tau) den = survmixture_f(t,ascale_r, ascale_nr, bshape, p) dervS = p*survw_derivf(t,ascale_r,bshape) + (1-p)*survw_derivf(t,ascale_nr,bshape) inside_integral <- (num/den)^2*(1/survw_f(t,ascale_cens,bshape=1))*dervS return(-inside_integral) } var_f <- function(ascale_r,ascale_nr,tau,bshape,ascale_cens,p){ requireNamespace("stats") integrate(inside_var,lower=0,upper=tau,ascale_r=ascale_r, ascale_nr= ascale_nr,tau=tau,bshape=bshape,ascale_cens=ascale_cens,p=p)$value } survw_integratef <- function(t,tau, ascale,bshape){ requireNamespace("stats") int <- integrate(survw_f,lower=t, upper=tau,ascale,bshape)$value return(int) }
open_todoist_website_profile <- function(verbose = TRUE) { if (verbose) { message("opening https://todoist.com/prefs/integrations") } browseURL("https://todoist.com/prefs/integrations") }
require(geometa, quietly = TRUE) require(testthat) context("ISOMedium") test_that("encoding",{ testthat::skip_on_cran() md <- ISOMedium$new() md$setName("satellite") md$addDensity(1.0) md$setDensityUnits("string") md$setVolumes(1L) md$addMediumFormat("tar") md$setMediumNote("description") expect_is(md, "ISOMedium") xml <- md$encode() expect_is(xml, "XMLInternalNode") md2 <- ISOMedium$new(xml = xml) xml2 <- md2$encode() expect_true(ISOAbstractObject$compare(md, md2)) }) test_that("encoding - i18n",{ testthat::skip_on_cran() md <- ISOMedium$new() md$setName("satellite") md$addDensity(1.0) md$setDensityUnits("string") md$setVolumes(1L) md$addMediumFormat("tar") md$setMediumNote( "description", locales = list( EN="description_EN", FR="description_FR", ES="description_ES", AR="description_AR", RU="description_RU", ZH="description_ZH" )) expect_is(md, "ISOMedium") xml <- md$encode() expect_is(xml, "XMLInternalNode") md2 <- ISOMedium$new(xml = xml) xml2 <- md2$encode() expect_true(ISOAbstractObject$compare(md, md2)) })
`.onLoad` <- function(libname, pkgname) { assign( "sd.default", stats::sd , asNamespace(pkgname)) assign("var.default", stats::var, asNamespace(pkgname)) }
context("test-ant") test_that("ant pulls the right number of words for cool", { expect_length(ant("cool"), 2) }) test_that("ant returns character(0) when it cannot find a word", { expect_length(ant("xxxx"), 0) expect_is(ant("xxxx"), "character") }) test_that("ant pulls the right number of words for cool with n_words", { expect_length(ant("cool", 1), 1) expect_length(ant("cool", 2), 2) expect_length(ant("cool", 100), 2) }) test_that("ant with n_words returns 0 when it cannot find a word", { expect_length(ant("xxxx", 5), 0) })
context("numericalSolution") on.exit(unlink('Rplots.pdf')) vdp.pars <- list(y0 = c(4, 2), tlim = c(0, 100)) vdp.out <- do.call(numericalSolution, c(list(deriv=phaseR::vanDerPol, parameters = 3), vdp.pars)) test_that("behavior equal to reference behavior", { expect_equal_to_reference(vdp.out[c("x","y")], "test-numericalSolution_ref-vdp.rds") }) test_that("alternative formulation equal to reference behavior", { vdp.alt <- function(t, state, parameters) { with(as.list(c(state, parameters)), { dx <- y dy <- mu*(1 - x^2)*y - x list(c(dx, dy)) }) } vdp.alt.out <- do.call(numericalSolution, c(list(deriv=vdp.alt, parameters = c(mu=3)), vdp.pars)) expect_equal(vdp.alt.out[c("x","y")], vdp.out[c("x","y")]) })
test_that("pd_stack() works", { dd <- prism_archive_subset("ppt", "daily", mon = 1, years = 1981:2011) expect_s4_class(x <- pd_stack(dd), "RasterStack") expect_equal(dim(x)[3], length(dd)) expect_setequal(names(x), dd) mm <- prism_archive_subset("tdmean", "monthly", years = 2005) expect_s4_class(x <- pd_stack(mm), "RasterStack") expect_equal(dim(x)[3], length(mm)) expect_setequal(names(x), mm) cc <- c(dd, mm) expect_s4_class(x <- pd_stack(cc), "RasterStack") expect_equal(dim(x)[3], length(cc)) expect_setequal(names(x), cc) })
context("utils-predicates") test_that("is_zipcmd_available detects zipcommand", { skip_if_not(is_zipcmd_available(), "system zip-command is available") expect_true(is_zipcmd_available()) }) test_that("is_zipcmd_available() detects missing zipcommand", { expect_false(is_zipcmd_available("sdjkghsaghaskjghsagj")) }) test_that("utils-fs can create/remove files in dry_run memory", { td <- file.path(tempdir(), "rotor") tf1 <- file.path(td, "foo") tf2 <- file.path(td, "bar") dir.create(tf1, recursive = TRUE) file.create(tf2) on.exit(unlink(c(tf2, tf1, td), recursive = TRUE)) expect_true(is_dir(tf1)) expect_false(is_dir(tf2)) }) test_that("is_pure_BackupQueue", { td <- file.path(tempdir(), "rotor") dir.create(td, recursive = TRUE) on.exit(unlink(td, recursive = TRUE)) tf <- file.path(td, "test.log") file.create(tf) expect_true(is_pure_BackupQueue(tf)) expect_true(is_pure_BackupQueueDateTime(tf)) expect_true(is_pure_BackupQueueIndex(tf)) tf_date <- file.path(td, "test.2017.log") file.create(tf_date) expect_true(is_pure_BackupQueue(tf)) expect_true(is_pure_BackupQueueDateTime(tf)) expect_false(is_pure_BackupQueueIndex(tf)) tf_idx <- file.path(td, "test.1.log") file.create(tf_idx) expect_false(is_pure_BackupQueue(tf)) expect_false(is_pure_BackupQueueDateTime(tf)) expect_false(is_pure_BackupQueueIndex(tf)) expect_error(assert_pure_BackupQueue(tf), "not possible") expect_warning(assert_pure_BackupQueue(tf, warn_only = TRUE)) file.remove(tf_date) expect_true(is_pure_BackupQueue(tf)) expect_false(is_pure_BackupQueueDateTime(tf)) expect_true(is_pure_BackupQueueIndex(tf)) unlink(tf_idx) }) test_that("is_parsable_date/time works", { expect_true(is_parsable_datetime(as.Date("2018-12-01"))) expect_true(is_parsable_datetime(as.POSIXct("2018-12-01 12:01:01"))) expect_true(is_parsable_datetime("2018-12-01")) expect_true(is_parsable_datetime("20181201")) expect_true(is_parsable_datetime("2018-02")) expect_true(is_parsable_datetime("201802")) expect_true(is_parsable_datetime("2018")) expect_true(is_parsable_datetime(20181231)) expect_false(is_parsable_datetime("1 week")) expect_false(is_parsable_datetime("2 years")) expect_true(is_parsable_datetime("2019-12-12--13-12-11")) expect_true(is_parsable_datetime("2019-12-12--13-12-")) expect_true(is_parsable_datetime("2019-12-12--13--")) expect_true(is_parsable_datetime("2019-12-12----")) expect_true(is_parsable_datetime("2019-12-----")) expect_true(is_parsable_datetime("2019------")) expect_false(is_parsable_datetime("------")) expect_true(is_parsable_datetime("2019-12-12T13-12-11")) expect_true(is_parsable_datetime("2019-12-12T13-12-")) expect_true(is_parsable_datetime("2019-12-12T13T")) expect_true(is_parsable_datetime("2019-12-12TT")) expect_true(is_parsable_datetime("2019-12TT-")) expect_true(is_parsable_datetime("2019TTT")) expect_false(is_parsable_datetime("TTT")) expect_true(is_parsable_datetime("2019-12-12 13-12-11")) expect_true(is_parsable_datetime("2019-12-12 13-12-")) expect_true(is_parsable_datetime("2019-12-12 13 ")) expect_true(is_parsable_datetime("2019-12-12 ")) expect_true(is_parsable_datetime("2019-12 -")) expect_true(is_parsable_datetime("2019 ")) expect_false(is_parsable_datetime(" ")) expect_false(is_parsable_date("2019-12-12--13-12-11")) expect_false(is_parsable_date("2019-12-12--13-12-")) expect_false(is_parsable_date("2019-12-12--13--")) expect_true(is_parsable_date("2019-12-12----")) expect_true(is_parsable_date("2019-12-----")) expect_true(is_parsable_date("2019------")) expect_false(is_parsable_date("------")) }) test_that("is_backup_older_than_interval works as expected", { now <- as.POSIXct("2019-12-11 00:12:13") expect_true(is_backup_older_than_interval(as.Date("2019-12-11"), "0 days", now)) expect_true(is_backup_older_than_interval(as.Date("2019-12-11"), "-1 days", now)) expect_true(is_backup_older_than_interval(as.Date("2019-12-11"), 0, now)) expect_true(is_backup_older_than_interval(as.Date("2019-12-11"), -1, now)) now <- "2019-12-11--00-12" expect_false(is_backup_older_than_interval(as.Date("2019-01-01"), "1 year", now)) expect_true(is_backup_older_than_interval(as.Date("2018-12-12"), "1 year", now)) expect_true(is_backup_older_than_interval(as.Date("2018-12-12"), "0 year", now)) expect_false(is_backup_older_than_interval(as.Date("2999-12-12"), Inf, now)) }) test_that("is_backup_older_than_interval works with weeks", { expect_false( is_backup_older_than_interval(interval = "1 week", as.Date("2019-04-01"), as.Date("2019-04-07")) ) expect_true( is_backup_older_than_interval(interval = "1 week", as.Date("2019-04-01"), as.Date("2019-04-08")) ) expect_false( is_backup_older_than_interval(interval = "6 week", as.Date("2019-04-01"), as.Date("2019-05-06")) ) expect_true( is_backup_older_than_interval(interval = "5 weeks", as.Date("2019-04-01"), as.Date("2019-05-06")) ) expect_false( is_backup_older_than_interval(interval = "1 month", as.Date("2019-04-01"), as.Date("2019-04-30")) ) expect_true( is_backup_older_than_interval(interval = "1 month", as.Date("2019-04-01"), as.Date("2019-05-01")) ) expect_false( is_backup_older_than_interval(interval = "6 month", as.Date("2019-04-01"), as.Date("2019-09-01")) ) expect_true( is_backup_older_than_interval(interval = "5 months", as.Date("2019-04-01"), as.Date("2019-09-06")) ) }) test_that("is_backup_older_than_datetime works as expected", { now <- as.POSIXct("2019-12-11 00:12:13") expect_true(is_backup_older_than_datetime(as.Date("2019-12-11"), now)) expect_false(is_backup_older_than_datetime(as.Date("2019-12-11"), as.Date(now))) expect_false(is_backup_older_than_datetime(as.Date("2019-12-12"), now)) })
RI.hybridFS.FRST <- function(decision.table, control = list()){ return(quickreduct.alg(decision.table, type.method = "hybrid.rule.induction", control = control)) } RI.GFRS.FRST <- function(decision.table, control = list()){ if (is.null(attr(decision.table, "decision.attr"))){ stop("A decision attribute is not indicated.") } if (attr(decision.table, "nominal.attrs")[attr(decision.table, "decision.attr")] == FALSE){ stop("The decision attribute must be nominal values") } control <- setDefaultParametersIfMissing(control, list(alpha.precision = 0.05, type.aggregation = c("t.tnorm", "lukasiewicz"), type.relation = c("tolerance", "eq.1"), t.implicator = "lukasiewicz")) objects <- decision.table desc.attrs <- attr(decision.table, "desc.attrs") nominal.att <- attr(decision.table, "nominal.attrs") num.att <- ncol(objects) indx.univ <- c(seq(1, nrow(objects))) num.object <- nrow(objects) names.attr <- t(colnames(objects)) alpha.precision <- control$alpha.precision type.aggregation <- ch.typeAggregation(control$type.aggregation) type.relation <- control$type.relation t.similarity <- type.relation[2] t.implicator <- control$t.implicator t.tnorm <- type.aggregation[[2]] res.temp <- build.discMatrix.FRST(decision.table = decision.table, type.discernibility = "alpha.red", num.red = "all", alpha.precision = alpha.precision, type.relation = type.relation, t.implicator = t.implicator, type.aggregation = type.aggregation, show.discernibilityMatrix = TRUE) disc.mat <- res.temp$disc.mat att.val.red <- c() for (i in 1 : ncol(disc.mat)){ att.val.core <- c() disc.list <- disc.mat[, i] disc.list <- unique(disc.list) disc.list <- disc.list[which(!is.na(disc.list))] att.val.core <- disc.list[which(sapply(disc.list, length) == 1)] if (length(att.val.core) != 0){ disc.list <- disc.list[which(sapply(disc.list, length) > 1)] for (ii in 1 : length(att.val.core)){ disc.list <- disc.list[which(sapply(disc.list, function(x){att.val.core[ii] %in% x}) == FALSE)] } } else { att.val.core <- disc.list[which.min(sapply(disc.list, length))] disc.list <- disc.list[which(sapply(disc.list, function(x){att.val.core %in% x}) == FALSE)] } temp.red <- c() while (length(disc.list) != 0){ new.red <- names(which.max(table(unlist(disc.list)))) temp.red <- c(temp.red, new.red) disc.list <- disc.list[which(sapply(disc.list, function(x){new.red %in% x}) == FALSE)] } temp.red <- c(temp.red, unlist(att.val.core)) att.val.red <- append(att.val.red, list(unique(temp.red))) } attributes <- c(seq(1, (num.att - 1))) control.ind <- list(type.aggregation = type.aggregation, type.relation = type.relation) IND <- BC.IND.relation.FRST(decision.table, attributes = attributes, control = control.ind) IND.decAttr <- BC.IND.relation.FRST(decision.table, attributes = c(num.att), control = control.ind) control <- list(t.implicator = t.implicator, t.tnorm = t.tnorm, alpha = alpha.precision) FRST.fvprs <- BC.LU.approximation.FRST(decision.table, IND, IND.decAttr, type.LU = "fvprs", control = control) cons.deg <- BC.positive.reg.FRST(decision.table, FRST.fvprs)$positive.freg res <- cal.var.range(objects, attributes = seq(1, (num.att - 1)), nominal.att) range.dt <- res$range.data variance.dt <- res$variance.data all.rules <- att.val.red min.rules <- c() object.rules <- list() exit <- FALSE while (exit == FALSE && length(all.rules) >= 1){ cover.rule <- c() num.rl <- matrix() indx.seq <- seq(1, length(all.rules)) indx.logical.0 <- which(sapply(all.rules, length) == 0) if (length(indx.logical.0) != 0){ indx.seq <- indx.seq[-indx.logical.0] } for (j in indx.seq){ cov.rl <- c() counter <- 0 attrs <- all.rules[[j]] rl.obj <- objects[j, sapply(attrs, function(x) which(colnames(objects) == x))] state.att <- nominal.att[sapply(attrs, function(x) which(colnames(objects) == x))] range.data.temp <- matrix(range.dt[1, sapply(attrs, function(x) which(colnames(objects) == x))], nrow = 1) variance.data.temp <- matrix(variance.dt[1, sapply(attrs, function(x) which(colnames(objects) == x))], nrow = 1) for (k in indx.seq){ if (j != k){ temp.rl.obj <- objects[k, sapply(attrs, function(x) which(colnames(objects) == x))] IND.rel <- matrix(nrow = 1, ncol = length(state.att)) for (ii in 1 : length(state.att)){ if (state.att[ii] == TRUE){ t.similarity <- "boolean" } IND.rel[1, ii] <- unlist(similarity.equation(rl.obj[ii], temp.rl.obj[ii], t.similarity, delta = 0.2, range.data = range.data.temp[1, ii], variance.data = variance.data.temp[1, ii])) } if ((1 - min(IND.rel)) < cons.deg[j]){ cov.rl <- c(cov.rl, k) counter <- counter + 1 } } } cover.rule <- append(cover.rule, list(cov.rl)) num.rl[j] <- counter } if (length(num.rl) == num.object){ list.obj <- rbind(seq(1, num.object), num.rl) } indx.max.cov <- which.max(num.rl) selected.obj <- list.obj[1, indx.max.cov] min.rules <- append(min.rules, list(all.rules[[indx.max.cov]])) object.rules <- append(object.rules, list(selected.obj)) all.rules <- all.rules[-c(cover.rule[[indx.max.cov]], indx.max.cov)] list.obj <- list.obj[, -c(cover.rule[[indx.max.cov]], indx.max.cov), drop = FALSE] if (length(all.rules) == 1){ min.rules <- append(min.rules, all.rules) object.rules <- append(object.rules, list(list.obj[1, 1])) exit <- TRUE } } indx.logical.0 <- which(sapply(min.rules, length) == 0) if (length(indx.logical.0) != 0){ min.rules <- min.rules[-indx.logical.0] object.rules <- object.rules[-indx.logical.0] } rules <- list(attributes = min.rules, objects = object.rules, threshold = cons.deg) return(std.rules(rules, type.method = "RI.GFRS.FRST", decision.table, t.similarity, t.tnorm)) } RI.indiscernibilityBasedRules.RST <- function(decision.table, feature.set) { if (!inherits(decision.table, "DecisionTable")) { stop("Provided data should inherit from the \'DecisionTable\' class.") } if (!inherits(feature.set, "FeatureSubset")) { stop("Provided feature subset should inherit from the \'FeatureSubset\' class.") } if(is.null(attr(decision.table, "decision.attr"))) { stop("A decision attribute is not indicated.") } else { decisionIdx <- attr(decision.table, "decision.attr") } if(!all(attr(decision.table, "nominal.attrs"))) { stop("Some of the attributes are numerical. Discretize attributes before calling RST-based rule induction methods.") } reduct <- feature.set$reduct if (length(reduct) >= 1) { INDrelation <- BC.IND.relation.RST(decision.table, reduct)$IND.relation } else stop("empty feature subset") clsFreqs <- table(decision.table[[decisionIdx]]) uniqueCls <- names(clsFreqs) ruleSet <- sapply(INDrelation, function(idxs, rule, dataS, clsVec, uniqueCls) laplaceEstimate(list(idx = as.integer(reduct), values = as.character(unlist(dataS[idxs[1],reduct], use.names = FALSE))), dataS, clsVec, uniqueCls, suppIdx = idxs), reduct, decision.table, decision.table[[decisionIdx]], uniqueCls, simplify = FALSE, USE.NAMES = FALSE) names(ruleSet) = NULL attr(ruleSet, "uniqueCls") <- as.character(uniqueCls) attr(ruleSet, "supportDenominator") <- nrow(decision.table) attr(ruleSet, "clsProbs") <- clsFreqs/sum(clsFreqs) attr(ruleSet, "majorityCls") <- as.character(uniqueCls[which.max(table(decision.table[[decisionIdx]]))]) attr(ruleSet, "method") <- "indiscernibilityBasedRules" attr(ruleSet, "dec.attr") <- colnames(decision.table[decisionIdx]) attr(ruleSet, "colnames") <- colnames(decision.table)[-decisionIdx] ruleSet = ObjectFactory(ruleSet, classname = "RuleSetRST") return(ruleSet) } RI.CN2Rules.RST <- function(decision.table, K = 3) { if (!inherits(decision.table, "DecisionTable")) { stop("Provided data should inherit from the \'DecisionTable\' class.") } if(is.null(attr(decision.table, "decision.attr"))) { stop("A decision attribute is not indicated.") } else { decIdx = attr(decision.table, "decision.attr") } if(!all(attr(decision.table, "nominal.attrs"))) { stop("Some of the attributes are numerical. Discretize attributes before calling RST-based rule induction methods.") } clsVec <- decision.table[,decIdx] uniqueCls <- unique(clsVec) decisionName = colnames(decision.table)[decIdx] decision.table <- decision.table[, -decIdx] clsFreqs <- table(clsVec) uncoveredObjIdx <- 1:nrow(decision.table) rules = list() while (length(uncoveredObjIdx) > 0) { rules[[length(rules)+1]] = findBestCN2Rule(decision.table[uncoveredObjIdx,], clsVec[uncoveredObjIdx], uniqueCls, K) uncoveredObjIdx = uncoveredObjIdx[setdiff(1:length(uncoveredObjIdx), rules[[length(rules)]]$support)] } attr(rules, "uniqueCls") <- as.character(sort(uniqueCls)) attr(rules, "supportDenominator") <- nrow(decision.table) attr(rules, "clsProbs") <- clsFreqs/sum(clsFreqs) attr(rules, "majorityCls") <- as.character(sort(uniqueCls)[which.max(clsFreqs)]) attr(rules, "method") <- "CN2Rules" attr(rules, "dec.attr") <- decisionName attr(rules, "colnames") <- colnames(decision.table)[-decIdx] rules = ObjectFactory(rules, classname = "RuleSetRST") return(rules); } RI.LEM2Rules.RST <- function(decision.table) { if (!inherits(decision.table, "DecisionTable")) { stop("Provided data should inherit from the \'DecisionTable\' class.") } if(is.null(attr(decision.table, "decision.attr"))) { stop("A decision attribute is not indicated.") } else decIdx = attr(decision.table, "decision.attr") if(!all(attr(decision.table, "nominal.attrs"))) { stop("Some of the attributes are numerical. Discretize attributes before calling RST-based rule induction methods.") } clsVec <- decision.table[,decIdx] uniqueCls <- unique(clsVec) decisionName = colnames(decision.table)[decIdx] clsFreqs <- table(clsVec) INDrelation = BC.IND.relation.RST(decision.table, (1:ncol(decision.table))[-decIdx]) approximations = BC.LU.approximation.RST(decision.table, INDrelation) lowerApproximations = approximations$lower.approximation rm(INDrelation, approximations) descriptorsList = attr(decision.table, "desc.attrs")[-decIdx] descriptorCandidates = list() for (i in 1:length(descriptorsList)) { descriptorCandidates = c(descriptorCandidates, lapply(descriptorsList[[i]], function(v, x) return(list(idx = x, values = v)), i)) } attributeValuePairs = lapply(descriptorCandidates, laplaceEstimate, decision.table[,-decIdx], clsVec, uniqueCls) rm(descriptorsList, descriptorCandidates) rules = list() for(i in 1:length(lowerApproximations)) { rules[[i]] = computeLEM2covering(as.integer(lowerApproximations[[i]]), attributeValuePairs, clsVec, uniqueCls) } rules = unlist(rules, recursive = FALSE) rules = lapply(rules, function(x) laplaceEstimate(list(idx = x$idx, values = x$values), decision.table, clsVec, uniqueCls, suppIdx = x$support)) attr(rules, "uniqueCls") <- as.character(sort(uniqueCls)) attr(rules, "supportDenominator") <- nrow(decision.table) attr(rules, "clsProbs") <- clsFreqs/sum(clsFreqs) attr(rules, "majorityCls") <- as.character(sort(uniqueCls)[which.max(clsFreqs)]) attr(rules, "method") <- "LEM2Rules" attr(rules, "dec.attr") <- decisionName attr(rules, "colnames") <- colnames(decision.table)[-decIdx] rules = ObjectFactory(rules, classname = "RuleSetRST") return(rules); } RI.AQRules.RST <- function(decision.table, confidence = 1.0, timesCovered = 1) { if (!inherits(decision.table, "DecisionTable")) { stop("Provided data should inherit from the \'DecisionTable\' class.") } if (is.null(attr(decision.table, "decision.attr"))) { stop("A decision attribute is not indicated.") } else decIdx = attr(decision.table, "decision.attr") if (!all(attr(decision.table, "nominal.attrs"))) { stop("Some of the attributes are numerical. Discretize attributes before calling RST-based rule induction methods.") } clsVec <- decision.table[,decIdx] uniqueCls <- unique(clsVec) decisionName = colnames(decision.table)[decIdx] clsFreqs <- table(clsVec) INDrelation = BC.IND.relation.RST(decision.table, (1:ncol(decision.table))[-decIdx]) approximations = BC.LU.approximation.RST(decision.table, INDrelation) lowerApproximations = approximations$lower.approximation rm(INDrelation, approximations) descriptorsList = attr(decision.table, "desc.attrs")[-decIdx] descriptorCandidates = list() for (i in 1:length(descriptorsList)) { tmpDescriptors = lapply(descriptorsList[[i]], function(v, x) return(list(idx = x, values = v)), i) tmpDescriptors = lapply(tmpDescriptors, laplaceEstimate, decision.table[,-decIdx], clsVec, uniqueCls) names(tmpDescriptors) = descriptorsList[[i]] descriptorCandidates[[length(descriptorCandidates) + 1]] = tmpDescriptors } rm(descriptorsList, tmpDescriptors) rules = list() set.seed(123) for(i in 1:length(lowerApproximations)) { rules[[i]] = computeAQcovering(as.integer(lowerApproximations[[i]]), descriptorCandidates, decision.table[,-decIdx], epsilon = 1 - confidence, K = timesCovered) } rules = unlist(rules, recursive = FALSE) rules = lapply(rules, function(x) laplaceEstimate(list(idx = x$idx, values = x$values), decision.table, clsVec, uniqueCls, suppIdx = x$support)) attr(rules, "uniqueCls") <- as.character(sort(uniqueCls)) attr(rules, "supportDenominator") <- nrow(decision.table) attr(rules, "clsProbs") <- clsFreqs/sum(clsFreqs) attr(rules, "majorityCls") <- as.character(sort(uniqueCls)[which.max(clsFreqs)]) attr(rules, "method") <- "AQRules" attr(rules, "dec.attr") <- decisionName attr(rules, "colnames") <- colnames(decision.table)[-decIdx] rules = ObjectFactory(rules, classname = "RuleSetRST") return(rules) } predict.RuleSetFRST <- function(object, newdata, ...) { if(!inherits(object, "RuleSetFRST")) stop("not a legitimate rules based on FRST model") if (any(object$type.method == c("RI.hybridFS.FRST", "RI.GFRS.FRST")) && object$type.model == "FRST"){ rules <- object$rules t.similarity <- object$t.similarity t.tnorm <- object$t.tnorm variance.data <- object$variance.data range.data <- object$range.data antecedent.attr <- object$antecedent.attr testData <- newdata[, c(colnames(newdata) %in% antecedent.attr), drop = FALSE] res <- data.frame(stringsAsFactors = FALSE) for (i in 1 : nrow(newdata)){ miu.Ra <- data.frame(stringsAsFactors = FALSE) for (j in 1 : length(rules$rules)){ namesAtt <- colnames(rules$rules[[j]]) test.dt <- testData[i, match(c(namesAtt[-length(namesAtt)]), names(testData)), drop = FALSE] valRules <- rules$rules[[j]] tra.dt <- valRules[-ncol(valRules)] mat.calc <- rbind(test.dt, tra.dt) P <- which(object$antecedent.attr %in% c(namesAtt[-length(namesAtt)])) temp.relation <- NA for (ii in 1 : length(P)){ if (object$nominal.att[P[ii]] == TRUE){ t.similarity <- "boolean" } temp <- unlist(similarity.equation(test.dt[1, ii], tra.dt[1, ii], t.similarity, delta = 0.2, range.data = range.data[1, P[ii]], variance.data = variance.data[1, P[ii]])) if (is.na(temp.relation)){ temp.relation <- temp } else { temp.relation <- func.tnorm(temp.relation, temp, t.tnorm = t.tnorm) } } miu.Ra[j, 1] <- valRules[1, ncol(valRules)] miu.Ra[j, 2] <- temp.relation } if (object$type.task == "classification"){ options(stringsAsFactors = FALSE) if (object$type.method == c("RI.hybridFS.FRST")){ fired.rules <- which.max(miu.Ra[, 2]) } else if (object$type.method == "RI.GFRS.FRST"){ miu.Ra[, 2] <- 1 - miu.Ra[, 2] fired.rules <- which(miu.Ra[, 2] <= rules$threshold) if (length(fired.rules) > 1){ fired.rules <- which.min(miu.Ra[fired.rules, 2]) } } res <- rbind(res, miu.Ra[fired.rules, 1, drop = FALSE]) } else { if (object$type.method == c("RI.hybridFS.FRST")){ miu.Ra <- as.matrix(miu.Ra) result <- (miu.Ra[, 2] %*% miu.Ra[, 1, drop = FALSE]) / sum(miu.Ra[, 2]) res <- rbind(res, result) } } } } rownames(res) <- NULL colnames(res) <- object$consequent.attr return(res) } predict.RuleSetRST <- function(object, newdata, ...) { if(!inherits(object, "RuleSetRST")) stop("The rule set does not an object from the \'RuleSetRST\' class") if(!inherits(newdata, "DecisionTable")) stop("Provided data should inherit from the \'DecisionTable\' class.") method = attr(object, "method") if (!(method %in% c("indiscernibilityBasedRules", "CN2Rules", "LEM2Rules", "AQRules"))) { stop("Unrecognized classification method") } majorityCls = attr(object, "majorityCls") uniqueCls = attr(object, "uniqueCls") clsProbs = attr(object, "clsProbs") predVec = switch(method, indiscernibilityBasedRules = { ruleSet = object[order(sapply(object, function(X) X$laplace), decreasing = TRUE)] INDclasses = sapply(ruleSet, function(x) paste(unlist(x$values), collapse = " ")) consequents = sapply(ruleSet, function(x) x$consequent) newdata = do.call(paste, newdata[, ruleSet[[1]]$idx, drop = FALSE]) sapply(newdata, bestFirst, INDclasses, consequents, majorityCls, uniqueCls, clsProbs) }, CN2Rules = apply(as.matrix(newdata), 1, firstWin, ruleSet = object), LEM2Rules = apply(as.matrix(newdata), 1, rulesVoting, ruleSet = object, ...), AQRules = apply(as.matrix(newdata), 1, rulesVoting, ruleSet = object, ...) ) predVec <- as.data.frame(predVec) rownames(predVec) <- NULL colnames(predVec) <- "predictions" return(predVec) } RI.laplace = function(rules, ...) { if(!inherits(rules, "RuleSetRST")) stop("not a legitimate RuleSetRST object") qualityVec = sapply(rules, function(x) x$laplace) names(qualityVec) = paste0('Rule_', 1:length(rules)) qualityVec } RI.support = function(rules, ...) { if(!inherits(rules, "RuleSetRST")) stop("not a legitimate RuleSetRST object") suppD = attr(rules, "supportDenominator") qualityVec = sapply(rules, function(x, N) length(x$support)/N, suppD) names(qualityVec) = paste0('Rule_', 1:length(rules)) qualityVec } RI.confidence = function(rules, ...) { if(!inherits(rules, "RuleSetRST")) stop("not a legitimate RuleSetRST object") nOfClasses = length(attr(rules, "uniqueCls")) qualityVec = sapply(rules, function(x, N) (x$laplace*(length(x$support) + N) - 1)/length(x$support), nOfClasses) names(qualityVec) = paste0('Rule_', 1:length(rules)) qualityVec } RI.lift = function(rules, ...) { if(!inherits(rules, "RuleSetRST")) stop("not a legitimate RuleSetRST object") suppD = attr(rules, "supportDenominator") clsProbs = attr(rules, "clsProbs") qualityVec = sapply(rules, function(x, probs, N) x$laplace/((probs[x$consequent]*N + 1)/(length(probs) + N)), clsProbs, suppD) names(qualityVec) = paste0('Rule_', 1:length(rules)) qualityVec }
comptest.cor <- function(x = NULL, y = NULL, z = NULL, group = NULL, r.xy = NULL, r.xz = NULL, r.yz = NULL, n = NULL, r.1 = NULL, r.2 = NULL, n.1 = NULL, n.2 = NULL, alternative = c("two.sided", "less", "greater"), conf.level = 0.95, digits = 3, output = TRUE) { if (((!is.null(x) | !is.null(y) | !is.null(z) | !is.null(group)) & (!is.null(r.xy) | !is.null(r.xz) | !is.null(r.yz) | !is.null(n) | !is.null(r.1) | !is.null(r.2) | !is.null(n.1) | !is.null(n.2))) | (!is.null(r.xy) | !is.null(r.xz) | !is.null(r.yz) | !is.null(r.yz)) & (!is.null(r.2) | !is.null(n.1) | !is.null(n.2))) { stop("Specifiy function parameters using arguments (x, y, z), (x, y, group), (r.xy, r.xz, r.yz, n) or (r.1, r.2, n.1, n.2)") } if (!is.null(r.xy) | !is.null(r.xz) | !is.null(r.yz) | !is.null(r.1) | !is.null(r.2)) { if (any(c(r.xy, r.xz, r.yz, r.1, r.2) > 1 | c(r.xy, r.xz, r.yz, r.1, r.2) < -1)) { stop("Specified correlation coefficient(s) out of bounds") } } if (!is.null(z) & !is.null(group)) { stop("Specify either z (dependent sample) or group (independent sample)") } type <- ifelse(is.null(group) & is.null(r.1) & is.null(r.2), "dependent", "independent") if (type == "dependent") { if (is.null(r.xy) & is.null(r.xz) & is.null(r.yz)) { dat <- data.frame(na.omit(cbind(x, y, z))) r.xy <- cor(dat$x, dat$y) r.xz <- cor(dat$x, dat$z) r.yz <- cor(dat$y, dat$z) n <- nrow(dat) } if (n < 4) { stop("Number of observations smaller than n = 4") } z.r.xy <- 0.5 * log((1 + r.xy) / (1 - r.xy)) z.r.xz <- 0.5 * log((1 + r.xz) / (1 - r.xz)) r.1 <- (r.xy + r.xz) / 2 cov.r <- 1 / ((1 - r.1^2)^2) * (r.yz * (1 - 2 * r.1^2) - 0.5 * r.1^2 * (1 - 2 * r.1^2 - r.yz^2)) se <- sqrt((2 - 2*cov.r) / (n - 3)) z.diff <- (z.r.xy - z.r.xz) / se r.xy.conf <- conf.cor(r = r.xy, n = n, conf.level = conf.level, output = FALSE)$res r.xz.conf <- conf.cor(r = r.xz, n = n, conf.level = conf.level, output = FALSE)$res cor.r <- ((r.yz - 0.5 * r.xy * r.xz) * (1 - r.xy^2 - r.xz^2 - r.yz^2) + r.yz^3) / ((1 - r.xy^2) * (1 - r.xz^2)) lower <- r.xy - r.xz - sqrt((r.xy - r.xy.conf$lower)^2 + (r.xz.conf$upper - r.xz)^2 - 2 * cor.r * (r.xy - r.xy.conf$lower) * (r.xz.conf$upper - r.xz)) upper <- r.xy - r.xz + sqrt((r.xy.conf$upper - r.xy)^2 + (r.xz - r.xz.conf$lower)^2 - 2* cor.r * (r.xy.conf$upper - r.xy) * (r.xz - r.xz.conf$lower)) } else { if (is.null(r.1) & is.null(r.2) & is.null(n.1) & is.null(n.2)) { dat <- apply(cbind(x, y), 2, function(x) split(x, group)) r.1 <- cor(dat$x[[1]], dat$y[[1]], "complete.obs") n.1 <- nrow(na.omit(cbind(dat$x[[1]], dat$y[[1]]))) r.2 <- cor(dat$x[[2]], dat$y[[2]], "complete.obs") n.2 <- nrow(na.omit(cbind(dat$x[[2]], dat$y[[2]]))) } if (any(c(n.1, n.2) < 4)) { stop("Number of observations smaller than n = 4") } z.r.1 <- 0.5 * log((1 + r.1) / (1 - r.1)) z.r.2 <- 0.5 * log((1 + r.2) / (1 - r.2)) se <- sqrt(1 / (n.1 - 3) + 1 / (n.2 - 3)) z.diff <- (z.r.1 - z.r.2) / se r.1.conf <- conf.cor(r = r.1, n = n.1, output = FALSE)$res r.2.conf <- conf.cor(r = r.2, n = n.2, output = FALSE)$res lower <- r.1 - r.2 - sqrt((r.1 - r.1.conf$lower)^2 + (r.2.conf$upper - r.2)^2) upper <- r.1 - r.2 + sqrt((r.1.conf$upper - r.1)^2 + (r.2 - r.2.conf$lower)^2) } alternative <- ifelse(all(c("two.sided", "less", "greater") %in% alternative), "two.sided", alternative) if (alternative == "two.sided") { pval <- pnorm(abs(z.diff), lower.tail = FALSE) * 2 } if (alternative == "greater") { pval <- ifelse(z.diff < 0, 1, pnorm(z.diff, lower.tail = FALSE)) } if (alternative == "less") { pval <- ifelse(z.diff > 0, 1, pnorm(z.diff, lower.tail = TRUE)) } if (type == "dependent") { object <- list(call = match.call(), dat = data.frame(x, y, z), spec = list(type = "dependent", alternative = alternative, conf.level = conf.level, digits = digits), res = list(z = z.diff, pval = pval, r.xy = r.xy, r.xz = r.xz, r.yz = r.yz, diff = r.xy - r.xz, n = n, lower = lower, upper = upper)) } else { object <- list(call = match.call(), dat = data.frame(x, y, group), spec = list(type = "independent", alternative = alternative, conf.level = conf.level, digits = digits), res = list(z = z.diff, pval = pval, r.1 = r.1, n.1 = n.1, r.2 = r.2, n.2 = n.2, diff = r.1 - r.2, lower = lower, upper = upper)) } class(object) <- "comptest.cor" if (output == TRUE) { print(object) } return(invisible(object)) }
library(ggplot2) library(patchwork) data(PlantCounts, package = "MSG") set.seed(717) gg_plant = ggplot(PlantCounts, aes(altitude, counts)) + geom_point(color = rgb(0, 0, 0, 0.3)) gg_plant1 = gg_plant for (i in seq(0.02, 1, length = 70)) { gg_plant1 = gg_plant1 + geom_smooth(se = FALSE, span = i, color = rgb(0.4, i, 0.4)) + labs(x = "高度", y = "频数") } gg_plant2 = gg_plant for (i in 1:200) { idx = sample(nrow(PlantCounts), 300, TRUE) gg_plant2 = gg_plant2 + geom_smooth(data = PlantCounts[idx, ], se = FALSE, color = rgb(0, 0, 0, 0.1)) + labs(x = "高度", y = "频数") } print(gg_plant1 | gg_plant2)
KnowBPolygon<-function(data, format="A", shape=NULL, shapenames=NULL, admAreas=FALSE, Area="World", curve= "Rational", estimator=1, cutoff=1, cutoffCompleteness= 0, cutoffSlope= 1, extent=TRUE, minLon, maxLon, minLat, maxLat, int=30, colbg=" colexc = NULL, colfexc="black", colscale=c(" legend.pos="y", breaks=9, xl=0, xr=0, yb=0, yt=0, asp, lab = NULL, xlab = "Longitude", ylab = "Latitude", main1="Records", main2="Observed richness", main3="Completeness", main4="Slope", cex.main = 1.6, cex.lab = 1.4, cex.axis = 1.2, cex.legend=0.9, family = "sans", font.main = 2, font.lab = 1, font.axis = 1, lwdP=0.6, lwdC=0.1, trans=c(1,1), ndigits=0, save="CSV", file1 = "Species per site", file2 = "Estimators", file3 = "Standard error of the estimators", na = "NA", dec = ",", row.names = FALSE, Maps=TRUE, jpg=TRUE, jpg1="Records.jpg", jpg2="Observed richness.jpg", jpg3="Completeness.jpg", jpg4="Slope.jpg",cex=1.5, pch=15, cex.labels=1.5, pchcol="red", ask=FALSE){ if(is.null(shape)){ if(Area=="World" & xl==0){ xl=182 } if(Area=="World" & xr==0){ xr=188 } } if(!missing(minLon)){ if(!missing(maxLon)){ if(minLon==-180 & maxLon==180){ xl=182 xr=188 } } } method="accumulation" SpR<-FALSE largematrix<-TRUE options(warn=-1) if(jpg==FALSE) par(ask=ask) else yuret<-1 if(exists("adworld")==FALSE){ adworld<-1 stop("It is necessary to load data(adworld)") } if(Area!="World" & exists("adworld1")==FALSE){ stop("It is necessary to use RWizard and replace data(adworld) by @_Build_AdWorld_, for using administative areas") } if(!is.null(exclude)){ stop("It is necessary to use RWizard and replace data(adworld) by @_Build_AdWorld_, for using administative areas") } if(exists("adworld1")==FALSE){ adworld1<-1 } if(exists("adworld2")==FALSE){ adworld2<-1 } if(!is.null(shape) & is.null(shapenames)){ stop("It is necessary to specify in the argment 'shapenames' the variable with the names of the polygons in the shape") } values1<-data.frame(1,2,3,4,5,6,7,8,9,10,11) values2<-data.frame(1,2,3,4,5,6,7,8) values3<-data.frame(1,2,3,4,5,6,7,8,9,10,11,12,13) sevalues1<-data.frame(1,2,3,4,5,6,7) sevalues2<-data.frame(1,2,3,4,5,6) sevalues3<-data.frame(1,2,3,4,5,6,7,8) salA<-data.frame(c(2,5,6,1,0,6,5,8,7,4,9,8), nrow=4) sal<-data.frame(c(2,5,6,1,0,6,5,8,7,4,9,8), nrow=4) cu2<-NA;cu3<-NA;cu4<-NA;cu5<-NA sp2<-NA;sp3<-NA;sp4<-NA;sp5<-NA serandom<-NA;seexact<-NA;secoleman<-NA;serarefaction<-NA if(format=="B"){ data[is.na(data)]<-0 } if(format=="A"){ ZZ<-matrix(rep("",8),nrow=4) x<-na.exclude(data) if(format=="B"){ xLo<-x[,1] xLa<-x[,2] dimg<-dim(x[,c(-1,-2)]) replicas<-rep(dimg[1], dimg[2]) x2<-matrix(as.matrix(x[,c(-1,-2)]), ncol=1) headers<-names(x[,c(-1,-2)]) sps<-rep(x=headers,times=replicas) xLo<-rep(x=xLo,times=dimg[2]) xLa<-rep(x=xLa,times=dimg[2]) x<-data.frame(sps,xLo,xLa,x2) names(x)<-c("Species","Longitude","Latitude", "Counts") x<-x[x$Counts>0,] x<-x[(x$Longitude!=0 & x$Latitude!=0),] } if(format=="A"){ if(method=="accumulation"){ b<-x[,4] x<-x[rep(1:nrow(x[,1:3]), b), ] x[,4]<-1 } } if(format=="A"){ re<-dim(x) Records<-seq(1,re[1],1) temp<-cbind(x,Records) div<-x[,2]*cos(180*3.1416/180)+x[,3]*sin(90*3.1416/180)+(x[,2]+x[,3])*x[,2]+(x[,2]-x[,3])*x[,3]+ (x[,2]+x[,3])*x[,3]+(x[,2]-x[,3])*x[,2]+(x[,2]-x[,3])*x[,2]*x[,3]+(x[,2]+x[,3])*x[,2]*x[,3] dt1<-cbind(x,div) dt1<-dt1[order(dt1[,5]), ] pp1<-subset(temp, !duplicated(temp[,1])) dimtemp<-dim(temp) dimpp1<-dim(pp1) elements<-dimtemp[1]*dimpp1[1] rm(pp1) elements[is.na(elements)]<-0 if(elements>2000000000) elements<-0 else elements<-elements if(SpR==FALSE) elements<-0 else elements<-elements if(elements==0){ datosac<-x datosf<-x } else{ datosf<-with(dt1, table(dt1[,5],dt1[,1])) datosac<-with(temp, table(temp[,5],temp[,1])) } sums<-aggregate(datosf[,4],by=list(datosf[,1],datosf[,2],datosf[,3]),sum,na.rm=TRUE) names(sums)<-c("Species","Longitude","Latitude","Records") if(save=="RData"){ file1<-paste(file1,".RData", sep="") save(sums, file=file1) } else{ file1<-paste(file1,".CSV", sep="") if(dec=="."){ write.csv(x=sums, file = file1, row.names=row.names,na=na, fileEncoding = "") } else{ write.csv2(x=sums, file = file1, row.names=row.names,na=na, fileEncoding = "") } } if(elements==0){ datosf<-x datosac<-x } else{ datosac<-cbind(temp[,2:3],datosac) datos2<-dt1[,2:3] datos2<-subset(datos2, !duplicated(datos2)) datosf<-cbind(datos2,datosf) datosf<-datosf[order(datosf[,1], datosf[,2]), ] } datosf[is.na(datosf)]<-0 species<-aggregate(x[,4],by=list(x[,1]),FUN=sum,na.rm=TRUE) species1<-aggregate(x[,4],by=list(x[,1]),FUN=mean,na.rm=TRUE) species<-cbind(species,species1[,2]) colnames(species)<-c("Species","Sum", "Mean") } else{ datosf<-x datosac<-replace(x[,-c(1,2)], x[,-c(1,2)]>1,1) datosac<-cbind(x[,c(1,2)],datosac) Sum<-colSums(x[,-c(1,2)]) Mean<-colMeans(x[,-c(1,2)]) species<-rbind(Sum,Mean) colnames(species)<-colnames(x[,-c(1,2)]) species<-cbind(c("Sum","Mean"),species) } if(format=="B") elements<-1 else elements<-elements if(elements==0){ } else{ } rm(x) } else{ tableR<-data } if(format=="A"){ tableR<-data } if(format=="B"){ tableR<-as.data.frame(data) } ppp<-1 pppp<-1 if(is.null(shape)){ out<-split(adworld,f = adworld$Area) out<-out[c(-1,-2)] if(Area!="World" & exists("adworld1")==TRUE){ out<-split(adworld1,f = adworld1$Area) } Areas<-names(out) numero<-length(Areas) out<-lapply(out, function(x) x[!(names(x) %in% c("Area"))]) out<-as.matrix(out) } else{ if(class(shape)=="list"){ data<-shape[[1]] lsh<-length(shape) if(lsh>1){ ss<-seq(2,lsh) hh<-as.character(shape[ss]) data<-eval(parse(text=paste("subset(data,",noquote(shapenames), " %in% hh)", sep=""))) } } else{ data<-shape if(class(data)=="character"){ data<-eval(parse(text=paste(".GlobalEnv$", data, sep=""))) } } numero<-length(data) Areas<-eval(parse(text=paste("data$",noquote(shapenames),sep=""))) } cut<-cutoff leng1<-numero uio<-1 pvalor<-1 suma<-1 sumas<-1 ZZ<-matrix(rep("",8),nrow=4) rm(dt1) rm(datosf) rm(temp) rm(species1) rm(species) rm(div) rm(Records) rm(datosac) rm(datos2) rm(values1) rm(values2) rm(values3) rm(pp) rm(sums) for(z in 1:numero){ end.time<-Sys.time() end.times <- format(end.time, "%b %d, %Y at %X") ZZ[1,1]<-end.times ZZ[2,1]<-paste(z,"from", numero,"polygons") ZZ[2,2]<-"" write.table(ZZ,"Inf.txt", row.names=FALSE,col.names=FALSE) if(is.null(shape)){ pp<-as.data.frame(out[z]) } else{ pp<-as.data.frame(data@polygons[[z]]@Polygons[[1]]@coords) } if(format=="B"){ log<-mgcv::in.out(as.matrix(pp),as.matrix(tableR[, c(1,2)])) } if(format=="A"){ log<-mgcv::in.out(as.matrix(pp),as.matrix(tableR[, c(2,3)])) } if(any(log==TRUE)==TRUE){ if(format=="B"){ mm<-cbind(tableR,log) dhh<-dim(mm) tableR<-subset(mm,(mm[,dhh[2]] == FALSE)) tableR<-tableR[,c(-dhh[2])] mm<-mm[mm[,dhh[2]],] mm<-mm[,c(-1,-2,-dhh[2])] mm<-mm[, apply(mm, 2, sum)!=0] if(class(mm)=="integer"){ dimtt<-length(mm) } else{ dimt<-dim(mm) dimtt<-dimt[1] } } if(format=="A"){ mm<-cbind(tableR,log) dhh<-dim(mm) tableR<-subset(mm,(mm[,dhh[2]] == FALSE)) tableR<-tableR[,c(-dhh[2])] mm<-mm[mm[,dhh[2]],] mm<-mm[,c(-dhh[2])] sp<-as.character(unique(mm[,1])) lsp<-length(sp) dco<-dim(mm) Lm<-mm[,2:3] for(as in 1:lsp){ col<-rep(0,dco[1]) r<-which(mm[,1]==sp[as]) col[r]<-1 Lm<-cbind(Lm,col) } names(Lm)<-c("Longitude","Latitude",sp) mm<-Lm[,c(-1,-2)] if(class(mm)=="integer"){ dimtt<-length(mm) } else{ dimt<-dim(mm) dimtt<-dimt[1] } } R2random<-NA R2exact<-NA if(method=="accumulation"){ if(estimator==0 | estimator==2){ if(is.null(dim(mm))){ cu2<-NA serandom<-NA } else{ cu<- vegan::specaccum(mm, method="random", permutations = 200) datosc<-data.frame(cu$richness, cu$sites) ymax<-max(datosc[,1],na.rm=T) ymin<-min(datosc[,1],na.rm=T) xmax<-max(datosc[,2],na.rm=T) xmin<-min(datosc[,2],na.rm=T) if(curve=="Clench"){ modelo<-try(nls(cu.richness ~ A*cu.sites/(1+B*cu.sites), data=datosc, start=list(A=1, B=0.01)), silent=T) } if(curve=="Exponential"){ modelo<-try(nls(cu.richness ~ (A)*(1-exp((-B*cu.sites))), data=datosc, start=list(A=ymax, B=0.01)), silent=T) } if(curve=="Saturation"){ modelo<-try(nls(cu.richness~A*(1-exp(-B*(cu.sites-C))), data=datosc, trace=T, start=list(A=ymax, B=0.01, C=0)), silent=TRUE) } if(curve=="Rational"){ modelo<-try(nls(cu.richness~(A+B*cu.sites)/(1+C*cu.sites), data=datosc, trace=T, start=list(A=1, B=1, C=0)), silent=TRUE) } res<-summary(modelo) if(res[1]=="1"){ cu2<-NA serandom<-NA } else{ cu2<-res$parameters[1,1]/res$parameters[2,1] if(curve=="Saturation" | curve=="Exponential"){ cu2<-res$parameters[1,1] } if(curve=="Rational"){ cu2<-res$parameters[2,1]/res$parameters[3,1] } if(cu2<0){ cu2<-NA sp2<-NA serandom<-NA } else{ cu2<-cu2 leng<-length(cu$sites) sp2<-cu$richness[leng]-cu$richness[leng-1] if(curve=="Clench"){res1<-datosc[,1]-(res$coefficients[1,1]*datosc[,2])/(1+res$coefficients[2,1]*datosc[,2])} if(curve=="Exponential"){res1<-datosc[,1]-(res$coefficients[1,1])*(1-exp((-res$coefficients[2,1]*datosc[,2])))} if(curve=="Saturation"){res1<-datosc[,1]-(res$coefficients[1,1]*(1-exp(-res$coefficients[2,1]*(datosc[,2]-res$coefficients[3,1]))))} if(curve=="Rational"){res1<-datosc[,1]-(res$coefficients[1,1]+res$coefficients[2,1]*datosc[,2])/(1+res$coefficients[3,1]*datosc[,2])} serandom<-sqrt(sum((res1)^2)/length(res1)) R2random<-1-var(res1, na.rm=T)/var(datosc[,1], na.rm=T) } } } } if(estimator==0 | estimator==1){ if(is.null(dim(mm))){ cu3<-NA seexact<-NA } else{ cu<- vegan::specaccum(mm, method="exact") datosc<-data.frame(cu$richness, cu$sites) ymax<-max(datosc[,1],na.rm=T) ymin<-min(datosc[,1],na.rm=T) xmax<-max(datosc[,2],na.rm=T) xmin<-min(datosc[,2],na.rm=T) if(curve=="Clench"){ modelo<-try(nls(cu.richness ~ A*cu.sites/(1+B*cu.sites), data=datosc, start=list(A=1, B=0.01)), silent=T) } if(curve=="Exponential"){ modelo<-try(nls(cu.richness ~ (A)*(1-exp((-B*cu.sites))), data=datosc, start=list(A=ymax, B=0.01)), silent=T) } if(curve=="Saturation"){ modelo<-try(nls(cu.richness~A*(1-exp(-B*(cu.sites-C))), data=datosc, trace=T, start=list(A=ymax, B=0.01, C=0)), silent=TRUE) } if(curve=="Rational"){ modelo<-try(nls(cu.richness~(A+B*cu.sites)/(1+C*cu.sites), data=datosc, trace=T, start=list(A=1, B=1, C=0)), silent=TRUE) } res<-summary(modelo) if(res[1]=="1"){ cu3<-NA seexact<-NA } else{ cu3<-res$parameters[1,1]/res$parameters[2,1] if(curve=="Saturation" | curve=="Exponential"){ cu3<-res$parameters[1,1] } if(curve=="Rational"){ cu3<-res$parameters[2,1]/res$parameters[3,1] } if(cu3<0){ cu3<-NA sp3<-NA seexact<-NA } else{ cu3<-cu3 leng<-length(cu$sites) sp3<-cu$richness[leng]-cu$richness[leng-1] if(curve=="Clench"){res1<-datosc[,1]-(res$coefficients[1,1]*datosc[,2])/(1+res$coefficients[2,1]*datosc[,2])} if(curve=="Exponential"){res1<-datosc[,1]-(res$coefficients[1,1])*(1-exp((-res$coefficients[2,1]*datosc[,2])))} if(curve=="Saturation"){res1<-datosc[,1]-(res$coefficients[1,1]*(1-exp(-res$coefficients[2,1]*(datosc[,2]-res$coefficients[3,1]))))} if(curve=="Rational"){res1<-datosc[,1]-(res$coefficients[1,1]+res$coefficients[2,1]*datosc[,2])/(1+res$coefficients[3,1]*datosc[,2])} seexact<-sqrt(sum((res1)^2)/length(res1)) R2exact<-1-var(res1, na.rm=T)/var(datosc[,1], na.rm=T) } } } } if(estimator==0){ Methods<-c(cu3,cu2) Methods[Methods < 0] <- NA seMethods<-c(seexact, serandom) seMethods[seMethods < 0] <- NA Methodssp<-c(sp3, sp2) Methodssp[Methodssp < 0] <- NA slope<-mean(Methodssp, na.rm=T) pred<-mean(Methods, na.rm=T) } if(estimator==1){ Methods<-c(cu3) Methods[Methods < 0] <- NA seMethods<-c(seexact) seMethods[seMethods < 0] <- NA Methodssp<-c(sp3) Methodssp[Methodssp < 0] <- NA slope<-Methodssp pred<-Methods } if(estimator==2){ Methods<-c(cu2) Methods[Methods < 0] <- NA seMethods<-c(serandom) seMethods[seMethods < 0] <- NA Methodssp<-c(sp2) Methodssp[Methodssp < 0] <- NA slope<-Methodssp pred<-Methods } dimy<-dim(mm) if(is.null(dimy)){ dimy[2]<-1 records<-length(mm) } else{ records<-dimy[1] } com<-(dimy[2]*100/pred) pred<-round(pred) residuals<-dimy[2]-pred if(!is.null(dimy[2]) & !is.null(records) & estimator==0 & length(mm)>1){ if((records/dimy[2])>cut){ if(!is.na(slope) & slope>cutoffSlope){ com<-NA } if(!is.na(com) & com<cutoffCompleteness){ com<-NA } if(is.na(cu3)){ sp3<-NA } if(is.na(cu2)){ sp2<-NA } if(is.na(sp3) | is.na(sp2)){ slope<-NA } ratio<-records/dimy[2] estimators<-data.frame(Areas[z],records, dimy[2], cu3,cu2,sp3,sp2,slope,com, ratio) seestimators<-data.frame(Areas[z],records, dimy[2],seexact, serandom,R2exact,R2random) } else{ ratio<-records/dimy[2] estimators<-data.frame(Areas[z],records, dimy[2], NA,NA,NA,NA,NA,NA,ratio) seestimators<-data.frame(Areas[z],records, dimy[2],NA, NA,NA,NA) } colnames(estimators)<-c("Area","Records","Observed.richness", "Richness.exact", "Richness.random","Slope.exact", "Slope.random", "Mean.slope", "Completeness", "Ratio") colnames(seestimators)<-c("Area","Records","Observed.richness","SE.exact", "SE.random","R2.exact","R2.random") if(pppp==1){ finales<-estimators finalsees<-seestimators pppp<-2 } else{ finales<-rbind(finales,estimators) finalsees<-rbind(finalsees,seestimators) } } if(!is.null(dimy[2]) & !is.null(records) & estimator==1 & length(mm)>1){ if(records/dimy[2]>cut){ if(!is.na(sp3) & sp3>cutoffSlope){ com<-NA } if(!is.na(com) & com<cutoffCompleteness){ com<-NA } if(is.na(cu3)){ sp3<-NA } ratio<-records/dimy[2] estimators<-data.frame(Areas[z],records, dimy[2], cu3,sp3,com,ratio) seestimators<-data.frame(Areas[z],records, dimy[2], seexact,R2exact) } else{ ratio<-records/dimy[2] estimators<-data.frame(Areas[z],records, dimy[2], NA,NA,NA,ratio) seestimators<-data.frame(Areas[z],records, dimy[2],NA,NA) } colnames(estimators)<-c("Area","Records","Observed.richness", "Richness","Slope", "Completeness","Ratio") colnames(seestimators)<-c("Area","Records","Observed.richness","SE","R2") if(pppp==1){ finales<-estimators finalsees<-seestimators pppp<-2 } else{ finales<-rbind(finales,estimators) finalsees<-rbind(finalsees,seestimators) } } if(!is.null(dimy[2]) & !is.null(records) & estimator==2 & length(mm)>1){ if((records/dimy[2])>cut){ if(!is.na(sp2) & sp2>cutoffSlope){ com<-NA } if(!is.na(com) & com<cutoffCompleteness){ com<-NA } if(is.na(cu2)){ sp2<-NA } ratio<-records/dimy[2] estimators<-data.frame(Areas[z],records, dimy[2], cu2,sp2,com,ratio) seestimators<-data.frame(Areas[z],records, dimy[2], serandom,R2random) } else{ ratio<-records/dimy[2] estimators<-data.frame(Areas[z],records, dimy[2], NA,NA,NA,ratio) seestimators<-data.frame(Areas[z],records, dimy[2],NA,NA) } colnames(estimators)<-c("Area","Records","Observed.richness", "Richness","Slope", "Completeness","Ratio") colnames(seestimators)<-c("Area","Records","Observed.richness","SE","R2") if(pppp==1){ finales<-estimators finalsees<-seestimators pppp<-2 } else{ finales<-rbind(finales,estimators) finalsees<-rbind(finalsees,seestimators) } } } } rm(log) rm(cu) } end.time<-Sys.time() end.times <- format(end.time, "%b %d, %Y at %X") ZZ[1,1]<-end.times ZZ[2,1]<-"Saving files...." ZZ[2,2]<-"" write.table(ZZ,"Inf.txt", row.names=FALSE,col.names=FALSE) if(exists("finales")==FALSE){ stop("There are no records in any of the shapes") } else{ estimators<-finales seestimators<-finalsees if(save=="RData"){ file2<-paste(file2,".RData", sep="") file3<-paste(file3,".RData", sep="") save(estimators, file=file2) save(seestimators, file=file3) } else{ file2<-paste(file2,".CSV", sep="") file3<-paste(file3,".CSV", sep="") if(dec=="."){ write.csv(x=estimators, file = file2, row.names=row.names,na=na, fileEncoding = "") write.csv(x=seestimators, file = file3, row.names=row.names,na=na, fileEncoding = "") } else{ write.csv2(x=estimators, file = file2, row.names=row.names,na=na, fileEncoding = "") write.csv2(x=seestimators, file = file3, row.names=row.names,na=na, fileEncoding = "") } } } if(Maps==TRUE){ temporal<-estimators datos<-data estimators<-na.exclude(estimators) AreasS<-as.character(unique(estimators[,1])) if(length(AreasS)<=1){ stop("Maps are not depicted because there are less than two polygons with information about completeness (see the file Estimators)") } if(is.null(shape)){ data<-subset(adworld, adworld[,3]==AreasS) } else{ data<-eval(parse(text=paste("subset(data,",noquote(shapenames), " %in% AreasS)", sep=""))) } if(method=="accumulation") graphics<-4 else graphics<-3 if(admAreas==TRUE | is.null(shape)){ d<-length(Area) AA<-Area[1] if (AA=="World"){ datos1<-adworld[2:5,] } else{ datos1<-rbind(adworld1,adworld2) } datos1<-na.exclude(datos1) } dimes<-dim(estimators) for(gg in 1:graphics){ if(gg==1){ filejpg<-jpg1 main<-main1 tt<-2 AreasS<-as.character(unique(temporal[,1])) if(is.null(shape)){ data<-subset(adworld, adworld[,3]==AreasS) } else{ data<-eval(parse(text=paste("subset(datos,",noquote(shapenames), " %in% AreasS)", sep=""))) } var<-temporal[,tt] ZZ[1,1]<-end.times ZZ[2,1]<-"Printing plot" ZZ[2,2]<-main1 } if(gg==2){ filejpg<-jpg2 main<-main2 tt<-3 AreasS<-as.character(unique(temporal[,1])) if(is.null(shape)){ data<-subset(adworld, adworld[,3]==AreasS) } else{ data<-eval(parse(text=paste("subset(datos,",noquote(shapenames), " %in% AreasS)", sep=""))) } var<-temporal[,tt] ZZ[1,1]<-end.times ZZ[2,1]<-"Printing plot" ZZ[2,2]<-main2 } if(gg==3){ filejpg<-jpg3 main<-main3 tt<-dimes[2]-2 AreasS<-as.character(unique(estimators[,1])) if(!is.null(shape)){ data<-eval(parse(text=paste("subset(datos,",noquote(shapenames), " %in% AreasS)", sep=""))) } var<-estimators[,"Completeness"] ZZ[1,1]<-end.times ZZ[2,1]<-"Printing plot" ZZ[2,2]<-main3 } if(gg==4){ filejpg<-jpg4 main<-main4 tt<-dimes[2]-3 AreasS<-as.character(unique(estimators[,1])) if(estimator==1 | estimator==2) var<-estimators[,"Slope"] else var<-estimators[,"Mean.slope"] ZZ[1,1]<-end.times ZZ[2,1]<-"Printing plot" ZZ[2,2]<-main4 colscale<-rev(colscale) ndigits=ndigits+2 } write.table(ZZ,"Inf.txt", row.names=FALSE,col.names=FALSE) if(!is.null(shape)){ if(class(var)=="character"){ variable<-datos@data[,var] } else{ variable<-var } if(class(variable)=="factor"){ variable<-as.numeric(levels(variable))[variable] } } else{ variable<-as.numeric(var) } if(jpg==TRUE){ jpeg(filename = filejpg, width = 8000, height = 4000, units = "px", pointsize = 14, quality = 1200, bg = "white", res = 600) } squishplot <- function(xlim,ylim,asp=1){ if(length(xlim) < 2) stop('xlim must be a vector of length 2') if(length(ylim) < 2) stop('ylim must be a vector of length 2') tmp <- par(c('plt','pin','xaxs','yaxs')) if( tmp$xaxs == 'i' ){ xlim <- range(xlim) } else { tmp.r <- diff(range(xlim)) xlim <- range(xlim) + c(-1,1)*0.04*tmp.r } if( tmp$yaxs == 'i' ){ ylim <- range(ylim) } else { tmp.r <- diff(range(ylim)) ylim <- range(ylim) + c(-1,1)*0.04*tmp.r } tmp2 <- (ylim[2]-ylim[1])/(xlim[2]-xlim[1]) tmp.y <- tmp$pin[1] * tmp2 * asp if(tmp.y < tmp$pin[2]){ par(pin=c(tmp$pin[1], tmp.y)) par(plt=c(tmp$plt[1:2], par('plt')[3:4])) } else { tmp.x <- tmp$pin[2]/tmp2/asp par(pin=c(tmp.x, tmp$pin[2])) par(plt=c(par('plt')[1:2], tmp$plt[3:4])) } return(invisible(tmp['plt'])) } if(!is.null(shape)){ colors<- colorRampPalette(colscale)(int) if(class(variable)=="factor"){ class<-cut(levels(variable)[variable], int) } else{ class<-cut(as.numeric(variable), int) } colors<-colors[class] } if (missing(inc)) inc=0.005 else inc=inc if(!is.null(shape)){ if (missing(maxLon)){ if(datos@bbox[1,2]<0) maxLon<-(datos@bbox[1,2]-datos@bbox[1,2]*inc) else maxLon<-(datos@bbox[1,2]+datos@bbox[1,2]*inc) } else { maxLon<-maxLon } if (missing(minLon)){ if(datos@bbox[1,1]<0) minLon<-(datos@bbox[1,1]+datos@bbox[1,1]*inc) else minLon<-(datos@bbox[1,1]-datos@bbox[1,1]*inc) } else { minLon<-minLon } if (missing(maxLat)){ if(datos@bbox[2,2]<0) maxLat<-(datos@bbox[2,2]-datos@bbox[2,2]*inc) else maxLat<-(datos@bbox[2,2]+datos@bbox[2,2]*inc) } else { maxLat<-maxLat } if (missing(minLat)){ if(datos@bbox[2,1]<0) minLat<-(datos@bbox[2,1]+datos@bbox[2,1]*inc) else minLat<-(datos@bbox[2,1]-datos@bbox[2,1]*inc) } else { minLat<-minLat } } else{ if (AA=="World"){ if (missing(minLat)) minLat<--90 else minLat<-minLat if (missing(maxLat)) maxLat<-90 else maxLat<-maxLat if (missing(minLon)) minLon<--180 else minLon<-minLon if (missing(maxLon)) maxLon<-180 else maxLon<-maxLon } else{ if (missing(maxLon)){ if(max(datos1$Lon)<0) maxLon<-(max(datos1$Lon)-max(datos1$Lon)*inc) else maxLon<-(max(datos1$Lon)+max(datos1$Lon)*inc) } else { maxLon<-maxLon } if (missing(minLon)){ if(min(datos1$Lon)<0) minLon<-(min(datos1$Lon)+min(datos1$Lon)*inc) else minLon<-(min(datos1$Lon)-min(datos1$Lon)*inc) } else { minLon<-minLon } if (missing(maxLat)){ if(max(datos1$Lat)<0) maxLat<-(max(datos1$Lat)-max(datos1$Lat)*inc) else maxLat<-(max(datos1$Lat)+max(datos1$Lat)*inc) } else { maxLat<-maxLat } if (missing(minLat)){ if(min(datos1$Lat)<0) minLat<-(min(datos1$Lat)+min(datos1$Lat)*inc) else minLat<-(min(datos1$Lat)-min(datos1$Lat)*inc) } else { minLat<-minLat } } } legend.max=max(variable) legend.min=min(variable) if(legend.min<0) legend.min<-legend.min+legend.min*0.1/100 else legend.min<-legend.min-legend.min*0.1/100 if(legend.max<0) legend.max<-legend.max-legend.max*0.1/100 else legend.max<-legend.max+legend.max*0.1/100 Lati<-(maxLat+minLat)/2 if (pro==TRUE) aspe=(1/cos(Lati*pi/180)) else aspe=1 if (missing(asp)) asp=aspe else asp=asp tmp<-squishplot(xlim=c(minLon,maxLon), ylim=c(minLat,maxLat), asp=aspe) if(min(variable)==0) ini<-(-0.00001) else ini<-legend.min legend.freq1=abs((legend.max-ini)/(length(colscale))) legend.freq=abs((legend.max-ini)/(breaks-1)) if(missing(legend.pos)){ if((maxLon-minLon)>260 & (maxLon-minLon)/(maxLat-minLat)>2.265) legend.pos="x" else legend.pos=legend.pos } if (legend.pos=="y") par(oma=c(0,0,0,1)) else par(oma=c(0,0,2,0)) plot(0,0,xlim=c(minLon,maxLon),ylim=c(minLat,maxLat),xlab=xlab, main="", axes=TRUE, pty="s", ylab = ylab, cex.lab=cex.lab, cex.main=cex.main, cex.axis= cex.axis,type="n",bty="o", font.lab=font.lab, font.axis=font.axis,lab=lab,yaxs="i",xaxs="i",yaxt="n",xaxt="n") mtext(text=main,side=3, line=0.3, cex=cex.main, font=font.main) axis(side=1,xlim=c(minLon,maxLon),lwd=lwdP, cex.axis=cex.axis) axis(side=2,ylim=c(minLat,maxLat),lwd=lwdP, cex.axis=cex.axis) if(colbg==" if(admAreas==TRUE){ if (AA=="World") { polygon(adworld$Lon,adworld$Lat,col=colcon, border=colf) if(!is.null(exclude)){ polygon(adworld2$Lon,adworld2$Lat,col=colexc, border=colfexc) } } else { polygon(adworld1$Lon,adworld1$Lat,col=colcon, border=colf) polygon(adworld2$Lon,adworld2$Lat,col=colexc, border=colfexc) } } if(!is.null(shape)){ sp::plot(data, col=colors, xlim=c(minLon,maxLon),ylim=c(minLat,maxLat), add=TRUE, bg="transparent") } else{ leng<-length(variable) rbPal <- colorRampPalette(colscale) colors<- rbPal(100)[as.numeric(cut(as.numeric(variable),breaks = 100))] for(kk in 1:leng){ if(Area=="World") dataP<-subset(adworld, adworld[,3]==AreasS[kk]) else dataP<-subset(adworld1, adworld1[,3]==AreasS[kk]) polygon(dataP$Lon,dataP$Lat,col=colors[kk], border=colf) } } if (legend.pos=="y"){ if (xl==0){ x1<-(maxLon-minLon)*(-0.00106495)+0.747382095+maxLon x2<-(maxLon-minLon)*(-0.003194851)+2.060146284+maxLon } else{ x1<-xl x2<-xr } if(legend.max<=10){ sequ<-(seq(ini,legend.max,by=legend.freq)) sequ<-round(sequ, digits=ndigits) } else{ if(ini==0){ legend.freq=abs((legend.max-ini)/(breaks-1)) sequ<-(seq(ini,legend.max,by=legend.freq)) sequ<-round(sequ, digits=ndigits) } else{ sequ<-(seq(ini,legend.max,by=legend.freq)) sequ<-round(sequ, digits=ndigits) } } if(legend.min<0) legend.min<-legend.min+legend.min*0.1/100 else legend.min<-legend.min-legend.min*0.1/100 if(legend.max<0) legend.max<-legend.max-legend.max*0.1/100 else legend.max<-legend.max+legend.max*0.1/100 plotrix::color.legend(xl=x1, yb=minLat, xr= x2, yt=maxLat, sequ, gradient="y", align="rb", cex=cex.legend, rect.col=colscale) } else{ if (yb==0){ if(!is.null(main)){ y1<-maxLat+(maxLat-minLat)*(0.101851852)-1.333333333 y2<-maxLat+(maxLat-minLat)*(0.157407407)-1.333333333 } else{ y1<-maxLat+(maxLat-minLat)*(0.027777778) y2<-maxLat+(maxLat-minLat)*(0.083333333) } } else{ y1<-yb y2<-yt } if(legend.max<=10){ sequ<-(seq(ini,legend.max,by=legend.freq)) sequ<-round(sequ, digits=ndigits) } else{ sequ<-(seq(ini,legend.max,by=legend.freq)) sequ<-round(sequ, digits=ndigits) } plotrix::color.legend(xl=minLon, yb=y1, xr=maxLon, yt=y2, sequ, gradient="x", align="lt", cex=cex.legend, rect.col=colscale) } par(tmp) if(jpg==TRUE){ dev.off() } } } ZZ[1,1]<-"END" ZZ[1,2]<-"" ZZ[2,1]<-"" ZZ[2,2]<-"" write.table(ZZ,"Inf.txt", row.names=FALSE,col.names=FALSE) rm(tableR) rm(out) rm(dataP) rm(datos) rm(datos1) rm(data) }
build_authorization_uri <- function(resource, tenant, app, username=NULL, ..., aad_host="https://login.microsoftonline.com/", version=1) { version <- normalize_aad_version(version) default_opts <- list( client_id=app, response_type="code", redirect_uri="http://localhost:1410/", login_hint=username, state=paste0(sample(letters, 20, TRUE), collapse="") ) default_opts <- if(version == 1) c(default_opts, resource=resource) else c(default_opts, scope=paste_v2_scopes(resource)) opts <- utils::modifyList(default_opts, list(...)) aad_uri(aad_host, normalize_tenant(tenant), version, "authorize", opts) } get_device_creds <- function(resource, tenant, app, aad_host="https://login.microsoftonline.com/", version=1) { version <- normalize_aad_version(version) uri <- aad_uri(aad_host, normalize_tenant(tenant), version, "devicecode") body <- if(version == 1) list(resource=resource) else list(scope=paste_v2_scopes(resource)) body <- c(body, client_id=app) res <- httr::POST(uri, body=body, encode="form") process_aad_response(res) }