code
stringlengths
1
13.8M
NULL db_copy_to <- function(con, table, values, overwrite = FALSE, types = NULL, temporary = TRUE, unique_indexes = NULL, indexes = NULL, analyze = TRUE, ..., in_transaction = TRUE) { UseMethod("db_copy_to") } db_copy_to.DBIConnection <- function(con, table, values, overwrite = FALSE, types = NULL, temporary = TRUE, unique_indexes = NULL, indexes = NULL, analyze = TRUE, ..., in_transaction = TRUE) { new <- db_table_temporary(con, table, temporary) table <- new$table temporary <- new$temporary with_transaction(con, in_transaction, { table <- dplyr::db_write_table(con, table, types = types, values = values, temporary = temporary, overwrite = overwrite ) create_indexes(con, table, unique_indexes, unique = TRUE) create_indexes(con, table, indexes) if (analyze) dbplyr_analyze(con, table) }) table } db_compute <- function(con, table, sql, temporary = TRUE, unique_indexes = list(), indexes = list(), analyze = TRUE, ...) { UseMethod("db_compute") } db_compute.DBIConnection <- function(con, table, sql, temporary = TRUE, unique_indexes = list(), indexes = list(), analyze = TRUE, ...) { new <- db_table_temporary(con, table, temporary) table <- new$table temporary <- new$temporary table <- dbplyr_save_query(con, sql, table, temporary = temporary) create_indexes(con, table, unique_indexes, unique = TRUE) create_indexes(con, table, indexes) if (analyze) dbplyr_analyze(con, table) table } db_collect <- function(con, sql, n = -1, warn_incomplete = TRUE, ...) { UseMethod("db_collect") } db_collect.DBIConnection <- function(con, sql, n = -1, warn_incomplete = TRUE, ...) { res <- dbSendQuery(con, sql) tryCatch({ out <- dbFetch(res, n = n) if (warn_incomplete) { res_warn_incomplete(res, "n = Inf") } }, finally = { dbClearResult(res) }) out } db_write_table.DBIConnection <- function(con, table, types, values, temporary = TRUE, overwrite = FALSE, ...) { dbWriteTable( con, name = dbi_quote(table, con), value = values, field.types = types, temporary = temporary, overwrite = overwrite, row.names = FALSE ) table } dbi_quote <- function(x, con) UseMethod("dbi_quote") dbi_quote.ident <- function(x, con) DBI::dbQuoteIdentifier(con, as.character(x)) dbi_quote.character <- function(x, con) DBI::dbQuoteString(con, x) dbi_quote.sql <- function(x, con) DBI::SQL(as.character(x)) create_indexes <- function(con, table, indexes = NULL, unique = FALSE, ...) { if (is.null(indexes)) { return() } indexes <- as.list(indexes) for (index in indexes) { dbplyr_create_index(con, table, index, unique = unique, ...) } } with_transaction <- function(con, in_transaction, code) { if (in_transaction) { dbBegin(con) on.exit(dbRollback(con)) } code if (in_transaction) { on.exit() dbCommit(con) } } db_table_temporary <- function(con, table, temporary) { UseMethod("db_table_temporary") } db_table_temporary.DBIConnection <- function(con, table, temporary) { list( table = table, temporary = temporary ) }
download_idbank_list = function(dataset = NULL, label = FALSE){ insee_data_dir = tempdir() dir_creation_fail = try(create_insee_folder(), silent = TRUE) insee_local_dir = file.path(rappdirs::user_data_dir(), "R", "insee", "insee") if(("try-error" %in% class(dir_creation_fail))|(!file.exists(insee_local_dir))){ insee_local_dir = tempdir() } file_to_dwn = Sys.getenv("INSEE_idbank_dataset_path") idbank_list_file_cache = file.path(insee_data_dir, paste0(openssl::md5(file_to_dwn), ".rds")) if(!file.exists(idbank_list_file_cache)){ mapping = dwn_idbank_files() mapping = mapping[,c(1:3)] names(mapping) = c("nomflow", "idbank", "cleFlow") saveRDS(mapping, file = idbank_list_file_cache) }else{ mapping = readRDS(idbank_list_file_cache) } idbank_list_defaul_value = FALSE if(!is.null(dataset)){ dataset_list = unique(mapping[, "nomflow"]) dataset_param_in_list = which(dataset %in% dataset_list) if(length(dataset_param_in_list) > 0){ dataset_in_list = dataset[dataset_param_in_list] mapping = mapping[which(mapping[, "nomflow"] %in% dataset_in_list),] dot_vector = stringr::str_count(mapping$cleFlow, pattern = "\\.") n_col = max(dot_vector) + 1 mapping = separate_col(df = mapping, col = "cleFlow", sep = "\\.", into = paste0("dim", 1:n_col)) if(length(dataset_in_list) > 1){ pb = utils::txtProgressBar(min = 1, max = length(dataset_in_list), initial = 1, style = 3) } mapping_final = dplyr::bind_rows( lapply(1:length(dataset_in_list), function(j){ dataset_name = dataset_in_list[j] new_col_names = get_dataset_dimension(dataset = dataset_name) mapping_dataset = dplyr::filter(.data = mapping, .data$nomflow == dataset_name) if(!is.null(new_col_names)){ mapping_dataset_sep = separate_col(df = mapping_dataset, col = "cleFlow", sep = "\\.", into = new_col_names) if(label == TRUE){ for(new_col_name in new_col_names){ i_col = which(new_col_names == new_col_name) cl_col = attr(new_col_names,'cl')[i_col] dimension_labels = get_dimension_values(dimension = cl_col, col_name = new_col_name) if(!is.null(dimension_labels)){ mapping_dataset_sep = dplyr::left_join(mapping_dataset_sep, dimension_labels, by = new_col_name) } } } mapping_dataset_sep = clean_table(set_metadata_col(mapping_dataset_sep)) dataset_metadata_file_cache = file.path(insee_local_dir, paste0(openssl::md5(sprintf("%s_metadata_file", dataset_name)), ".rds")) saveRDS(mapping_dataset_sep, file = dataset_metadata_file_cache) if(length(dataset_in_list) > 1){ utils::setTxtProgressBar(pb, j) } return(mapping_dataset_sep) }else{ return(mapping_dataset) } })) }else{ idbank_list_defaul_value = TRUE warning("Dataset names do not exist, the table by default is provided") } }else{ idbank_list_defaul_value = TRUE } if(idbank_list_defaul_value == TRUE){ dot_vector = stringr::str_count(mapping$cleFlow, pattern = "\\.") n_col = max(dot_vector) + 1 mapping_final = separate_col(df = mapping, col = "cleFlow", sep = "\\.", into = paste0("dim", 1:n_col)) if(label == TRUE){ warning("Dataset names are missing, labels will not be provided") } } mapping_final = set_metadata_col(mapping_final) return(mapping_final) }
haplo.phase.known <- function(X, ploidy = 2){ X.names <- apply(X, 1, paste, collapse="") unique.X <- unique(X) unique.X.names <- apply(unique.X, 1, paste, collapse="") X.summary <- as.data.frame(table(X.names)) X.summary$prob <- X.summary$Freq / sum(X.summary$Freq) haplo <- NULL haplo$haplotype <- unique.X haplo$hap.prob <- X.summary$prob[match(unique.X.names, as.character(X.summary$X.names))] haplo$post <- rep(1, nrow(X)) if(ploidy == 1){ haplo$hap1code <- match(X.names, unique.X.names) haplo$hap2code <- haplo$hap1code haplo$indx.subj <- 1:nrow(X) } else if(ploidy == 2){ tmp <- matrix(match(X.names, unique.X.names), nrow = 2) haplo$hap1code <- tmp[1,] haplo$hap2code <- tmp[2,] haplo$indx.subj <- rep(1:(nrow(X)/2), each = 2) } else{ stop("ploidy = 1 or 2") } haplo } haplo.post.prob <- function(X, ploidy = 2, skip.haplo = 1e-7, K = NULL){ haplo <- haplo.phase.known(X, ploidy) nhap <- nrow(X) n.loci <- ncol(X) n.subj <- nrow(X) digit <- 1 H.names<-apply(haplo$haplotype, 1, paste, collapse="") Pcscn <-haplo$hap.prob; names(Pcscn)<-H.names pcscn <-rev(sort(Pcscn)) if(is.null(K)){ pos <-getcut.fun(pcscn, 2*nhap, plot=0) } else{ tl.K <- length(pcscn) if(K < 1 || K > (tl.K - 1)){ stop(paste("K should be in [", 1, ", ", tl.K - 1, "]", sep = "")) } pos <- K } reserv <-names(pcscn)[1:pos] hap1 <- haplo$hap1code hap2 <- haplo$hap2code indx <- haplo$indx.subj post <- haplo$post uhap <- sort(unique(c(hap1, hap2))) which.haplo<- haplo$hap.prob >= skip.haplo p.cscn <- Pcscn[which.haplo] h.names <- names(p.cscn) uhap <- uhap[which.haplo] BigMatB <- final.BigMatB.matC.fun(p.cscn, reserv, n.loci, digit) matB <- BigMatB$BigMatB.cscn x <- 0.5* (outer(hap1, uhap, "==") + outer(hap2, uhap, "==")); colnames(x)<-h.names x <- x[,match(rownames(matB), h.names)] xRD <- x %*% matB n.xRD <- ncol(xRD) xRD.post <- matrix(rep(NA, n.subj * n.xRD), ncol = n.xRD);for(j in 1:n.xRD){ xRD.post[,j]<-tapply(xRD[,j]*post,indx,sum)} n.x <- ncol(x) x.post <- matrix(rep(NA, n.subj * n.x), ncol = n.x);for(j in 1:n.x){ x.post[,j]<-tapply(x[,j]*post,indx,sum)}; list(haplo = haplo, FD.id = match(rownames(matB), H.names), RD.id = match(colnames(matB), H.names), FD.post = x.post, RD.post = xRD.post, g.truncate = ncol(matB)) }
library(spdep) GT <- GridTopology(c(1, 1), c(1, 1), c(10, 50)) SPix <- as(SpatialGrid(GT), "SpatialPixels") nb_rook_cont <- poly2nb(as(SPix, "SpatialPolygons"), queen=FALSE) nb_rook_dist <- dnearneigh(coordinates(SPix), 0, 1.01) expect_true(all.equal(nb_rook_cont, nb_rook_dist, check.attributes=FALSE)) t.nb <- cell2nb(GT, type='rook', legacy=TRUE) expect_false(isTRUE(all.equal(nb_rook_cont, t.nb, check.attributes=FALSE))) t.nb <- cell2nb(GT, type='rook') expect_true(isTRUE(all.equal(nb_rook_cont, t.nb, check.attributes=FALSE))) c <- 20:21 r <- 11:12 set.seed(1) for (i in c) { for (j in r) { GT <- GridTopology(c(1, 1), c(1, 1), c(i, j)) print(GT) SPix <- as(SpatialGrid(GT), "SpatialPixels") x <- rnorm(prod(slot(GT, "cells.dim"))) SPixDF <- SpatialPixelsDataFrame(SPix, data=data.frame(x=x)) SGDF <- as(SPixDF, "SpatialGridDataFrame") SPolDF <- as(SPixDF, "SpatialPolygonsDataFrame") nb_rook_cont <- poly2nb(SPolDF, queen=FALSE) M_cont <- moran.test(SPolDF$x, nb2listw(nb_rook_cont)) nb_rook_dist <- dnearneigh(coordinates(SPix), 0, 1.01) M_dist <- moran.test(SPixDF$x, nb2listw(nb_rook_dist)) print(expect_true(isTRUE(all.equal(nb_rook_cont, nb_rook_dist, check.attributes=FALSE)))) print(expect_equal(M_cont$estimate[1], M_dist$estimate[1])) nb_legacy <- cell2nb(GT, type='rook', legacy=TRUE) print(expect_false(isTRUE(all.equal(nb_rook_cont, nb_legacy, check.attributes=FALSE)))) M_cell_legacy <- moran.test(SGDF$x, nb2listw(nb_legacy)) print(expect_false(isTRUE(all.equal(M_cont$estimate[1], M_cell_legacy$estimate[1])))) nb <- cell2nb(GT, type='rook') print(expect_true(isTRUE(all.equal(nb_rook_cont, nb, check.attributes=FALSE)))) M_cell <- moran.test(SGDF$x, nb2listw(nb)) print(expect_equal(M_cont$estimate[1], M_cell$estimate[1])) } } NIN <- data.frame(row = rep(1:11, 22), col = rep(1:22, each = 11)) NIN$id <- paste(NIN$col, NIN$row, sep=":") xy.rook <- cell2nb(nrow = max(NIN$row), ncol = max(NIN$col), type="rook") GT <- GridTopology(c(1, 1), c(1, 1), c(max(NIN$col), max(NIN$row))) xy.rook1 <- cell2nb(GT, type="rook") expect_true(isTRUE(all.equal(xy.rook, xy.rook1, check.attributes=FALSE))) NIN_sf <- st_as_sf(NIN, coords=c("col", "row")) xy.dist <- dnearneigh(NIN_sf, 0, 1.01, row.names=NIN_sf$id) expect_false(isTRUE(all.equal(xy.dist, xy.rook, check.attributes=FALSE))) expect_false(isTRUE(all.equal(attr(xy.rook, "region.id"), attr(xy.dist, "region.id")))) NINa <- data.frame(row = rep(1:11, each = 22), col = rep(1:22, 11)) NINa$id <- paste(NINa$col, NINa$row, sep=":") xy.rooka <- cell2nb(nrow = max(NINa$row), ncol = max(NINa$col), type="rook") expect_true(isTRUE(all.equal(xy.rook, xy.rooka, check.attributes=FALSE))) NIN_sfa <- st_as_sf(NINa, coords=c("col", "row")) xy.dista <- dnearneigh(NIN_sfa, 0, 1.01, row.names=NIN_sfa$id) expect_true(isTRUE(all.equal(xy.dista, xy.rooka, check.attributes=FALSE))) expect_true(isTRUE(all.equal(attr(xy.rooka, "region.id"), attr(xy.dista, "region.id"))))
raSab_cbin_fc<- function (Z, Y, a, b, Sab, odmax, odobs, Sab0=NULL, eta0=NULL,SS = round(sqrt(nrow(Z)))) { if(is.null(Sab0)){ Sab0<-diag(2) } if(is.null(eta0)){ eta0<-4 } E <- Z - a %*% t(rep(1, nrow(Z))) MEL <- MEU <- -E MEL[!is.na(Y) & Y == 0] <- -Inf MEU[!is.na(Y) & Y == 1] <- Inf MEL[is.na(Y)] <- -Inf MEU[is.na(Y)] <- Inf lba <- apply(MEL, 1, max) lba[is.na(lba)] <- -Inf uba <- apply(MEU, 1, min) uba[is.na(uba)] <- Inf uba[odobs == odmax] <- Inf for (ss in 1:SS) { ea <- b * Sab[1, 2]/Sab[2, 2] sa <- sqrt(Sab[1, 1] - Sab[1, 2]^2/Sab[2, 2]) a <- ea + sa * qnorm(runif(nrow(Z), pnorm((lba - ea)/sa), pnorm((uba - ea)/sa))) Sab <- solve(rwish(solve(eta0*Sab0 + crossprod(cbind(a, b))), eta0 + nrow(Z))) } list(Z = E + a %*% t(rep(1, nrow(Z))), a = a, Sab = Sab) }
\dontrun{ library(dplyr) library(sparkline) library(formattable) mtcars %>% group_by(cyl) %>% summarise( hp = spk_chr( hp, type="box", chartRangeMin=0, chartRangeMax=max(mtcars$hp) ), mpg = spk_chr( mpg, type="box", chartRangeMin=0, chartRangeMax=max(mtcars$mpg) ) ) %>% formattable() %>% formattable::as.htmlwidget() %>% spk_add_deps() }
cor.fd <- function(evalarg1, fdobj1, evalarg2=evalarg1, fdobj2=fdobj1) { if (!(is.fd(fdobj1) || is.fdPar(fdobj1))) stop("Second argument is neither an fd object or an fdPar object") if (!(is.fd(fdobj2) || is.fdPar(fdobj2))) stop("Fourth argument is neither an fd object or an fdPar object") var1 <- var.fd(fdobj1) print(class(var1)) evalVar1 <- eval.bifd(evalarg1, evalarg1, var1) { if(missing(fdobj2)){ dimV1 <- dim(evalVar1) ndV1 <- length(dimV1) { if(ndV1<3){ s1 <- sqrt(diag(evalVar1)) return(evalVar1/outer(s1, s1)) } else{ if(dimV1[3] != 1) stop("Bug in cor.fd: Programmed only for ", "matrices or 4-d arrays with dim[3]==1. oops.") dim1 <- dim(fdobj1$coefs) nVars <- dim1[3] evalV.diag <- choose(2:(nVars+1), 2) nPts <- length(evalarg1) s1 <- array(NA, dim=c(nPts, nVars)) for(i in 1:nVars) s1[, i] <- sqrt(diag(evalVar1[,,1,evalV.diag[i]])) cor1 <- evalVar1 m <- 0 for(i in 1:nVars)for(j in 1:i){ m <- m+1 cor1[,,1,m] <- (evalVar1[,,1,m] / outer(s1[, i], s1[, j])) } return(cor1) } } } else { var2 <- var.fd(fdobj2) evalVar2 <- eval.bifd(evalarg2, evalarg2, var2) var12 <- var.fd(fdobj1, fdobj2) evalVar12 <- eval.bifd(evalarg1, evalarg2, var12) s1 <- sqrt(diag(evalVar1)) s2 <- sqrt(diag(evalVar2)) return(evalVar12 / outer(s1, s2)) } } }
train_gam <- function(X,y,pars = list(numBasisFcts = 10)) { if(!("numBasisFcts" %in% names(pars) )) { pars$numBasisFcts = 10 } p <- dim(as.matrix(X)) if(p[1]/p[2] < 3*pars$numBasisFcts) { pars$numBasisFcts <- ceiling(p[1]/(3*p[2])) cat("changed number of basis functions to ", pars$numBasisFcts, " in order to have enough samples per basis function\n") } dat <- data.frame(as.matrix(y),as.matrix(X)) coln <- rep("null",p[2]+1) for(i in 1:(p[2]+1)) { coln[i] <- paste("var",i,sep="") } colnames(dat) <- coln labs<-"var1 ~ " if(p[2] > 1) { for(i in 2:p[2]) { labs<-paste(labs,"s(var",i,",k = ",pars$numBasisFcts,") + ",sep="") } } labs<-paste(labs,"s(var",p[2]+1,",k = ",pars$numBasisFcts,")",sep="") mod_gam <- FALSE try(mod_gam <- mgcv::gam(formula=formula(labs), data=dat),silent = TRUE) if(typeof(mod_gam) == "logical") { cat("There was some error with gam. The smoothing parameter is set to zero.\n") labs<-"var1 ~ " if(p[2] > 1) { for(i in 2:p[2]) { labs<-paste(labs,"s(var",i,",k = ",pars$numBasisFcts,",sp=0) + ",sep="") } } labs<-paste(labs,"s(var",p[2]+1,",k = ",pars$numBasisFcts,",sp=0)",sep="") mod_gam <- mgcv::gam(formula=formula(labs), data=dat) } result <- list() result$Yfit <- as.matrix(mod_gam$fitted.values) result$residuals <- as.matrix(mod_gam$residuals) result$model <- mod_gam result$df <- mod_gam$df.residual result$edf <- mod_gam$edf result$edf1 <- mod_gam$edf1 return(result) }
ls_apply_script_bits <- function(data, scriptBits, setVarNames = TRUE, setLabels = TRUE, convertToCharacter = FALSE, convertToFactor = FALSE, categoricalQuestions = NULL, massConvertToNumeric = TRUE, silent=limonaid::opts$get("silent"), sticky = limonaid::opts$get("sticky")) { if (!is.data.frame(data)) { stop("`data` must be a data.frame, but has class `", class(data), "`."); } if (!("lsScriptBits" %in% class(scriptBits))) { stop("`scriptBits` must have class `scriptBits`, but has class ", vecTxt(class(scriptBits), useQuote="`"), "."); } varNamesScript <- scriptBits$varNamesScript; varLabelsScript <- scriptBits$varLabelsScript; toCharScript <- scriptBits$toCharScript; toFactorScript <- scriptBits$toFactorScript; valueLabels <- scriptBits$valueLabels; varLabels <- scriptBits$varLabels; if (setVarNames) { if (!silent) { cat0("\nSetting variable names."); } eval(parse(text=varNamesScript)); } if (convertToCharacter) { if (!silent) { cat0("\nConverting columns to character."); } eval(parse(text=toCharScript)); } if (convertToFactor || (!is.null(categoricalQuestions))) { if (!silent) { cat0("\nConverting columns to factors."); } if (massConvertToNumeric) { data <- massConvertToNumeric(data); } if (!is.null(categoricalQuestions)) { if (setVarNames) { varNames <- names(data); } else { stop("You can't set setVarNames to FALSE and also set ", "categoricalQuestions to anything else than NULL, ", "because the content of categoricalQuestions should ", "be the LimeSurvey variables names!"); } toFactorScript <- unlist(lapply(as.list(categoricalQuestions), function(x, string=toFactorScript, varNms=varNames) { return(grep(paste0("data\\[, ", which(varNms==x), "\\] <-"), string, value=TRUE)); })); } eval(parse(text=toFactorScript)); } if (sticky) { if (requireNamespace("sticky", quietly = TRUE)) { data <- sticky::sticky_all(data); } else { warning("The `sticky` package is not installed. Without this ", "package, the variable and value labels that will be ", "attached to every variable (i.e. data frame column) ", "will be lost when the data frame is subset, for example ", "when selecting specific rows or columns.\n\n", "You can install the `sticky` package (34KB) with:\n\n", " install.packages('sticky');\n\n", "You can disable this warning by setting the `sticky` ", "argument to `FALSE`."); } } if (setLabels) { if (!silent) { cat0("\nSetting variable labels."); } eval(parse(text=varLabelsScript)); varLabelsScript <- gsub("variable\\.labels", "label", varLabelsScript); eval(parse(text=varLabelsScript)); if (!silent) { cat0("\nStoring variable labels as variable attributes following `labeler` convention."); } for (i in names(varLabels)) { attr(data[, as.numeric(i)], "label") <- varLabels[[i]]; } if (!silent) { cat0("\nStoring value labels as variable attributes following `labeler` convention."); } for (i in names(valueLabels)) { attr(data[, as.numeric(i)], "labels") <- valueLabels[[i]]; } } return(data); }
lbart=function( x.train, y.train, x.test=matrix(0.0,0,0), sparse=FALSE, a=0.5, b=1, augment=FALSE, rho=NULL, xinfo=matrix(0.0,0,0), usequants=FALSE, cont=FALSE, rm.const=TRUE, tau.interval=0.95, k=2.0, power=2.0, base=.95, binaryOffset=NULL, ntree=200L, numcut=100L, ndpost=1000L, nskip=100L, keepevery=1L, nkeeptrain=ndpost, nkeeptest=ndpost, nkeeptreedraws=ndpost, printevery=100, transposed=FALSE ) { n = length(y.train) if(length(binaryOffset)==0) binaryOffset=qlogis(mean(y.train)) if(!transposed) { temp = bartModelMatrix(x.train, numcut, usequants=usequants, cont=cont, xinfo=xinfo, rm.const=rm.const) x.train = t(temp$X) numcut = temp$numcut xinfo = temp$xinfo if(length(x.test)>0) { x.test = bartModelMatrix(x.test) x.test = t(x.test[ , temp$rm.const]) } rm.const <- temp$rm.const rm(temp) } if(n!=ncol(x.train)) stop('The length of y.train and the number of rows in x.train must be identical') p = nrow(x.train) np = ncol(x.test) if(length(rho)==0) rho <- p if(length(rm.const)==0) rm.const <- 1:p if(tau.interval>0.5) tau.interval=1-tau.interval tau=qlogis(1-0.5*tau.interval)/(k*sqrt(ntree)) if((nkeeptrain!=0) & ((ndpost %% nkeeptrain) != 0)) { nkeeptrain=ndpost cat('*****nkeeptrain set to ndpost\n') } if((nkeeptest!=0) & ((ndpost %% nkeeptest) != 0)) { nkeeptest=ndpost cat('*****nkeeptest set to ndpost\n') } if((nkeeptreedraws!=0) & ((ndpost %% nkeeptreedraws) != 0)) { nkeeptreedraws=ndpost cat('*****nkeeptreedraws set to ndpost\n') } res = .Call("clbart", n, p, np, x.train, as.integer(2*y.train-1), x.test, ntree, numcut, ndpost*keepevery, nskip, power, base, binaryOffset, tau, sparse, a, b, rho, augment, nkeeptrain, nkeeptest, nkeeptreedraws, printevery, xinfo ) if(nkeeptrain>0) { res$yhat.train = res$yhat.train+binaryOffset res$prob.train = plogis(res$yhat.train) res$prob.train.mean <- apply(res$prob.train, 2, mean) } else { res$yhat.train <- NULL } if(np>0) { res$yhat.test = res$yhat.test+binaryOffset res$prob.test = plogis(res$yhat.test) res$prob.test.mean <- apply(res$prob.test, 2, mean) } else { res$yhat.test <- NULL } if(nkeeptreedraws>0) names(res$treedraws$cutpoints) = dimnames(x.train)[[1]] dimnames(res$varcount)[[2]] = as.list(dimnames(x.train)[[1]]) dimnames(res$varprob)[[2]] = as.list(dimnames(x.train)[[1]]) res$varcount.mean <- apply(res$varcount, 2, mean) res$varprob.mean <- apply(res$varprob, 2, mean) res$binaryOffset=binaryOffset res$rm.const <- rm.const attr(res, 'class') <- 'lbart' return(res) }
MockCI <- R6Class( "MockCI", inherit = CI, public = list( get_branch = function() { "mock-ci-branch" }, get_tag = function() { "mock-ci-tag" }, is_tag = function() { FALSE }, get_slug = function() { "user/repo" }, get_build_number = function() { "mock build" }, get_build_url = function() { "http://build.url" }, get_commit = function() { "00000000000000000000000000000000" }, can_push = function(name = "TIC_DEPLOY_KEY") { self$has_env(name) }, get_env = function(env) { Sys.getenv(env) }, is_env = function(env, value) { self$get_env(env) == value }, has_env = function(env) { self$get_env(env) != "" }, is_interactive = function() { TRUE } ) )
SequenomMarkers <- function(vcf1=NULL, vcf2=NULL, outdir=NULL, platform="sq"){ perl_module <- system.file("SequenomMarkers_v2", package="genotypeR") if(is.null(vcf1) & is.null(vcf2)){stop("must provide vcf files")} if(!is.null(vcf1) & is.null(vcf2)){print("using population marker designer")} if(!is.null(vcf1) & !is.null(vcf2)){print("using two sample marker designer")} files <- dir(perl_module, full.names=TRUE) if(dir.exists(outdir)==FALSE){ dir.create(outdir, showWarnings = TRUE, recursive = FALSE, mode = "0777") } if(is.null(vcf1) & is.null(vcf2)){stop("must provide vcf files")} if(!is.null(vcf1) & is.null(vcf2)){ pop_sample_path <- paste(perl_module, "pop_sample", sep="/") finding_snps <- paste(pop_sample_path, "Finding_SNPs_pop_sample.pl", sep="/") grandmaster_snps <- paste(pop_sample_path, "Grandmaster_SNPs_pop_sample.pl", sep="/") pop_or_two <- "pop" } if(!is.null(vcf1) & !is.null(vcf2)){ two_sample_path <- paste(perl_module, "two_sample", sep="/") finding_snps <- paste(two_sample_path, "Finding_SNPs_two_sample.pl", sep="/") grandmaster_snps <- paste(two_sample_path, "Grandmaster_SNPs_two_sample.pl", sep="/") sort_by_chr <- paste(two_sample_path, "sort_by_chr.sh", sep="/") pop_or_two <- "two" } setwd(outdir) if(pop_or_two=="pop"){ cmd_finding_snps <- paste(shQuote(finding_snps), shQuote(vcf1), shQuote(platform), sep=" ") cmd_grandmaster_snps <- paste(shQuote(grandmaster_snps), shQuote(vcf1), sep=" ") } if(pop_or_two=="two"){ vcf_tools_output <- paste(outdir, "Sample1_v_Sample2.out", sep="/") cmd_vcftools <- paste(shQuote("vcftools"), shQuote("--vcf"), shQuote(vcf1), shQuote("--diff"), shQuote(vcf2), shQuote("--diff-site"), shQuote("--out"), shQuote(vcf_tools_output), sep=" ") system(cmd_vcftools) awesome_vcf_name_change <- paste(outdir, "Sample1_v_Sample2.out.diff.sites_in_files", sep="/") cmd_finding_snps <- paste(shQuote(finding_snps), shQuote(awesome_vcf_name_change), shQuote(platform), sep=" ") cmd_grandmaster_snps <- paste(shQuote(grandmaster_snps), shQuote(vcf2), shQuote(vcf1), sep=" ") system(paste("cp", sort_by_chr, ".")) } system(cmd_finding_snps) system(cmd_grandmaster_snps) }
test_that("the wrapper behaves as expected", { expect_error("asdf" %>% wrap()) t0 <- trajectory() %>% seize("server", 1) %>% set_attribute("attr", 1) %>% release("server", 1) t1 <- trajectory() %>% seize("server", 1) %>% timeout(1) %>% rollback(1, times = Inf) env <- simmer(verbose = TRUE) %>% add_resource("server", 1, 0) %>% add_generator("dummy", t0, at(1:10), mon = 2) %>% add_generator("rollback", t1, at(11)) %>% run(11.5) %>% wrap() expect_output(print(env)) expect_equal(env %>% now(), 11.5) expect_equal(env %>% peek(), 12) arrivals <- env %>% get_mon_arrivals(ongoing = TRUE) arrivals_res <- env %>% get_mon_arrivals(TRUE, ongoing = TRUE) expect_equal(nrow(arrivals), 11) expect_equal(nrow(arrivals_res), 11) arrivals <- env %>% get_mon_arrivals(ongoing = FALSE) arrivals_res <- env %>% get_mon_arrivals(TRUE, ongoing = FALSE) attributes <- env %>% get_mon_attributes() resources <- env %>% get_mon_resources() expect_equal(nrow(arrivals), 10) expect_equal(nrow(arrivals_res), 10) expect_equal(nrow(attributes), 10) expect_equal(nrow(resources), 21) expect_equal(env %>% get_sources(), c("dummy", "rollback")) expect_error(env %>% get_n_generated("asdf")) expect_equal(env %>% get_n_generated("dummy"), 10) expect_equal(env %>% get_resources(), "server") expect_error(env %>% get_capacity("asdf")) expect_equal(env %>% get_capacity("server"), 1) expect_error(env %>% get_queue_size("asdf")) expect_equal(env %>% get_queue_size("server"), 0) expect_error(env %>% get_server_count("asdf")) expect_equal(env %>% get_server_count("server"), 1) expect_error(env %>% get_queue_count("asdf")) expect_equal(env %>% get_queue_count("server"), 0) })
context("test-summary-manyglm.R") test_that("gamma summary", { shape <- 1; rate <- 1; nVar <- 5; n <- 100 SEED <- 1001 FAMILY <- 'gamma' set.seed(SEED) Y2 <- mvabund(sapply(rep(1,nVar), function(rate) rgamma(n, shape, rate))) junk <- rnorm(n) mglmg <- manyglm(Y2 ~ junk, family=FAMILY) tests <- c('wald', 'score', 'LR') summaries <- lapply(tests, function(t) summary(mglmg,nBoot=1000, test=t, rep.seed = TRUE)) expect_equal_to_reference(summaries, 'gamma_summaries.rds') })
cat("\014") rm(list = ls()) setwd("~/git/of_dollars_and_data") source(file.path(paste0(getwd(),"/header.R"))) library(readxl) library(dplyr) df <- read_excel(paste0(importdir, "0063_sector_returns/sp500_sector_data.xlsx"), skip = 1) %>% filter(!(is.na(`Start Date`) | `Start Date` == 'Totals')) %>% mutate(sector = trimws(gsub("TR\\s?USD \\(USD\\)", "", gsub("S&P 500 Sec/", "", `Security Name` ) )), date = as.Date(as.numeric(`Start Date`), origin = "1899-12-31"), ret = `Total Return %`/100) %>% select(sector, date, ret) saveRDS(df, paste0(localdir, "0063_sp500_sector_returns.Rds"))
infor_design <- function(design,t,...){ UseMethod('infor_design',t) } infor_design.default <- function(design,t){ stop('Please specific your model') } infor_design.dropout <- function(design, t, ... ){ infor_point <- function(point, t, p, l ){ X <- matrix(0,nrow = p, ncol = p + t + t) X[,1:p] <- diag(rep(1, p)) for (i in 1:p) { y <- point[i] X[i, p + y] <- 1 } X[-1,p + t + 1:t] <- X[-p,p + 1:t] M <- diag(c(rep(1, l), rep(0, p - l))) out <- t(X) %*% (M - M %*% matrix(1/l, nrow = p, ncol = p) %*% M) %*% X return(out) } infor_drop <- function(point, t, ... ){ drop <- list(...)[[1]] p <- length(point) out <- matrix(0, ncol = 2*t + p,nrow = 2*t + p) for (i in 1:p) { tmp <- infor_point(point, t, p, i) out <- out + drop[i]*tmp } return(out) } d <- dim(design) p <- d[2] - 1 n <- d[1] infor1 <- matrix(0, ncol = 2*t + p, nrow = 2*t + p) weight <- design[, p + 1, drop = F] design <- design[, 1:p,drop = F] for (j in 1:n) { infor1 = infor1 + weight[j]*infor_drop(design[j,,drop = F], t,...) } return(infor1) } infor_design.interference <- function(design, t, ... ){ infor_point <- function(point, t, sigma ){ p <- length(point) if (missing(sigma)) {sigma <- diag(1,p)} X <- matrix(0,nrow = p,ncol = t + t + t) for (i in 1:p) { y <- point[i] X[i,y] <- 1 } X[2:p,t + 1:t] <- X[1:(p - 1),1:t] X[1:(p - 1),t + t + 1:t] <- X[2:p,1:t] sig_inv <- solve(sigma) out <- t(X) %*% (sig_inv - sig_inv %*% matrix(1/sum(sig_inv),ncol = p, nrow = p) %*% sig_inv) %*% X return(out) } d <- dim(design) p <- d[2] - 1 n <- d[1] paras <- list(...) sigma <- paras[[1]] infor1 <- matrix(0,ncol = 3*t,nrow = 3*t) weight <- design[, p + 1, drop = F] design <- design[, 1:p, drop = F] for (j in 1:n) { infor1 = infor1 + weight[j]*infor_point(design[j,,drop = F],t,sigma) } return(infor1) } infor_design.proportional <- function(design, t, ... ){ infor_point <- function(point, t, sigma, lambda, tau ){ p <- length(point) tau <- matrix(tau,ncol = 1) X <- matrix(0,nrow = p,ncol = p + t + 1) pr <- diag(rep(1,p)) Fd <- Rd <- matrix(0,ncol = t, nrow = p) for (i in 1:p) { y <- point[i] Fd[i,y] <- 1 } Rd[2:p,] = Fd[1:(p - 1),] X[,1:p] <- pr X[,p + 1:t] <- Fd + lambda*Rd X[,p + t + 1] <- Rd %*% tau sig_inv <- solve(sigma) out <- t(X) %*% (sig_inv %*% diag(1,p) - matrix(1/sum(sig_inv),ncol = p,nrow = p) %*% sig_inv) %*% X return(out) } d <- dim(design) p <- d[2] - 1 n <- d[1] paras <- list(...) sigma <- paras$sigma lambda <- paras$lambda tau <- paras$tau infor1 <- matrix(0,ncol = 1 + t + p,nrow = 1 + t + p) weight <- design[, p + 1, drop = F] design <- design[,1:p, drop = F] for (j in 1:n) { infor1 = infor1 + weight[j]*infor_point(design[j,,drop = F],t,sigma,lambda,tau) } return(infor1) } generate_contrast <- function(opt,t,p) { UseMethod('generate_contrast',t) } generate_contrast.interference <- function(opt, t,p){ if (opt == 0) { g_part <- matrix(0,nrow = t - 1,ncol = 3*t) g_part[,1:t] <- cbind(diag(1,t - 1),-1) } if (opt == 1) { g_part <- matrix(0,nrow = t,ncol = 3*t) g_part[,1:t] <- diag(1,t) } return(g_part) } generate_contrast.dropout <- function(opt,t,p){ if (opt == 0) { g_part <- matrix(0,nrow = t - 1 ,ncol = 2*t + p) g_part[,(t + 1):(2*t)] <- cbind(diag(1,t - 1),-1) } if (opt == 1) { g_part <- matrix(0,nrow = t,ncol = 2*t + p) g_part[,(t + 1):(2*t)] <- diag(1,t) } return(g_part) } generate_contrast.proportional <- function(opt,t,p) { if (opt == 0) { g_part <- matrix(0,nrow = t - 1, ncol = 1 + t + p) g_part[,(t + 1):(2*t)] <- cbind(diag(1,t - 1),-1) } if (opt == 1) { g_part <- matrix(0,nrow = t,ncol = 1 + t + p ) g_part[,(t + 1):(2*t)] <- diag(1,t) } return(g_part) }
A2=function(d){ A=array(F,dim=c(d,d)) for (i in 1:(d-1)) { for (j in (i+1):d) {A[i,j]=T } } return(A) } A4=function(d){ A=array(F,dim=c(d,d,d)) if(d>2){ for (i in 1:(d-2)) { for (j in (i+1):(d-1)) { for (k in (j+1):d) { A[i,j,k]=T } } }} return(A) } A5=function(d){ A=array(F,dim=c(d,d)) if (d>2){ for (i in 2:(d-1)) { for (j in (i+1):d) {A[i,j]=T } }} return(A) } A13=function(d){ A=array(F,dim=c(d,d,d)) if (d>3){ for (i in 2:(d-2)) { for (j in (i+1):(d-1)) { for (k in (j+1):d) { A[i,j,k]=T } } }} return(A) } A12=function(d){ A=array(F,dim=c(d,d,d,d)) if(d>3){ for (i in 1:(d-3)) { for (j in (i+1):(d-2)) { for (k in (j+1):(d-1)) { for (l in (k+1):d){ A[i,j,k,l]=T } } } }} return(A) } H3=function(d){ I=matrix(1,d,d) S=lower.tri(I) S=S*I diag(S)=c(0:-(d-1)) return(S)} H6=function(d){ I=matrix(1,d,d) S=lower.tri(I) S=S*I diag(S)=c(-2:-(d+1)) return(S)} H7=function(d){ I=matrix(1,d,d) S=lower.tri(I) S=S*I return(S)} H9=function(d){ I=matrix(1,d,d) S=lower.tri(I) S=S*I*3 diag(S)=c(-2:-(d+1)) return(S)} H10=function(d){ I=matrix(1,d,d) S=lower.tri(I) S=S*I diag(S)=c(-4:-(d+3)) return(S)} H15=function(d){ I=matrix(1,d,d) S=lower.tri(I) S=S*I*3 diag(S)=c(0:-(d-1)) return(S)}
cps.count = function(nsim = NULL, nsubjects = NULL, nclusters = NULL, c1 = NULL, c2 = NULL, cDiff = NULL, sigma_b_sq = NULL, sigma_b_sq2 = NULL, family = 'poisson', negBinomSize = 1, analysis = 'poisson', method = 'glmm', alpha = 0.05, quiet = FALSE, allSimData = FALSE, irgtt = FALSE, seed = NA, nofit = FALSE, poorFitOverride = FALSE, lowPowerOverride = FALSE, timelimitOverride = TRUE, optmethod = "Nelder_Mead") { if (!is.na(seed)) { set.seed(seed = seed) } est.vector <- NULL se.vector <- NULL stat.vector <- NULL pval.vector <- NULL converge.vector <- NULL simulated.datasets <- list() converge <- NULL prog.bar = progress::progress_bar$new( format = "(:spin) [:bar] :percent eta :eta", total = nsim, clear = FALSE, width = 100 ) prog.bar$tick(0) is.wholenumber = function(x, tol = .Machine$double.eps ^ 0.5) abs(x - round(x)) < tol sim.data.arg.list = list(nsim, nclusters, nsubjects, sigma_b_sq) sim.data.args = unlist(lapply(sim.data.arg.list, is.null)) if (sum(sim.data.args) > 0) { stop( "NSIM, NSUBJECTS, NCLUSTERS & sigma_b_sq must all be specified. Please review your input values." ) } min1.warning = " must be an integer greater than or equal to 1" if (!is.wholenumber(nsim) || nsim < 1) { stop(paste0("NSIM", min1.warning)) } if (!is.wholenumber(nclusters) || nclusters < 1) { stop(paste0("NCLUSTERS", min1.warning)) } if (!is.wholenumber(nsubjects) || nsubjects < 1) { stop(paste0("NSUBJECTS", min1.warning)) } if (length(nclusters) > 2) { stop( "NCLUSTERS can only be a vector of length 1 (equal ) } if (length(nclusters) == 1) { if (irgtt == TRUE) { nclusters[2] = nclusters[1] nclusters[1] = 1 } else { nclusters[2] = nclusters[1] } } if (length(nsubjects) == 1) { nsubjects[1:sum(nclusters)] = nsubjects } if (length(nsubjects) == 2) { nsubjects = c(rep(nsubjects[1], nclusters[1]), rep(nsubjects[2], nclusters[2])) } if (nclusters[1] == nclusters[2] && length(nsubjects) == nclusters[1]) { nsubjects = rep(nsubjects, 2) } if (length(nclusters) == 2 && length(nsubjects) != 1 && length(nsubjects) != sum(nclusters)) { stop( "A cluster size must be specified for each cluster. If all cluster sizes are equal, please provide a single value for NSUBJECTS" ) } if (length(sigma_b_sq) > 1 || length(sigma_b_sq2) > 1) { errorCondition("The lengths of sigma_b_sq and sigma_b_sq2 cannot be larger than 1.") } if (irgtt == FALSE) { min0.warning = " must be a numeric value greater than 0" if (!is.numeric(sigma_b_sq) || sigma_b_sq <= 0) { stop("sigma_b_sq", min0.warning) } if (!is.null(sigma_b_sq2) && sigma_b_sq2 <= 0) { stop("sigma_b_sq2", min0.warning) } } if (!is.numeric(alpha) || alpha < 0 || alpha > 1) { stop("ALPHA must be a numeric value between 0 - 1") } parm1.arg.list = list(c1, c2, cDiff) parm1.args = unlist(lapply(parm1.arg.list, is.null)) if (sum(parm1.args) > 1) { stop("At least two of the following terms must be specified: C1, C2, cDiff") } if (sum(parm1.args) == 0 && cDiff != abs(c1 - c2)) { stop("At least one of the following terms has be misspecified: C1, C2, cDiff") } if (!is.element(family, c('poisson', 'neg.binom'))) { stop( "FAMILY must be either 'poisson' (Poisson distribution) or 'neg.binom'(Negative binomial distribution)" ) } if (!is.element(analysis, c('poisson', 'neg.binom'))) { stop( "ANALYSIS must be either 'poisson' (Poisson regression) or 'neg.binom'(Negative binomial regression)" ) } if (!is.element(method, c('glmm', 'gee'))) { stop( "METHOD must be either 'glmm' (Generalized Linear Mixed Model) or 'gee'(Generalized Estimating Equation)" ) } if (!is.logical(quiet)) { stop( "QUIET must be either TRUE (No progress information shown) or FALSE (Progress information shown)" ) } if (family == 'neg.binom' && negBinomSize < 0) { stop("negBinomSize must be positive") } if (is.null(c1)) { c1 = abs(cDiff - c2) } if (is.null(c2)) { c2 = abs(c1 - cDiff) } if (is.null(cDiff)) { cDiff = c1 - c2 } if (is.null(sigma_b_sq2)) { sigma_b_sq[2] = sigma_b_sq } else{ sigma_b_sq[2] = sigma_b_sq2 } trt = c(rep(1, length.out = sum(nsubjects[1:nclusters[1]])), rep(2, length.out = sum(nsubjects[(nclusters[1] + 1):(nclusters[1] + nclusters[2])]))) clust = unlist(lapply(1:sum(nclusters), function(x) rep(x, length.out = nsubjects[x]))) est.vector <- vector(mode = "numeric", length = nsim) se.vector <- vector(mode = "numeric", length = nsim) stat.vector <- vector(mode = "numeric", length = nsim) pval.vector <- vector(mode = "numeric", length = nsim) converge.vector <- vector(mode = "logical", length = nsim) for (i in 1:nsim) { randint.0 = stats::rnorm(nclusters[1], mean = 0, sd = sqrt(sigma_b_sq[1])) randint.1 = stats::rnorm(nclusters[2], mean = 0, sd = sqrt(sigma_b_sq[2])) y0.intercept <- list() for (j in 1:length(nsubjects[1:nclusters[1]])) { y0.intercept[[j]] <- rep(randint.0[j], each = nsubjects[j]) } y0.intercept <- unlist(y0.intercept) y0.linpred = y0.intercept + log(c1) y0.prob = exp(y0.linpred) if (family == 'poisson') { y0 = stats::rpois(length(y0.prob), y0.prob) } if (family == 'neg.binom') { y0 = stats::rnbinom(length(y0.prob), size = negBinomSize, mu = y0.prob) } y1.intercept <- list() for (j in 1:length(nsubjects[(nclusters[1] + 1):length(nsubjects)])) { y1.intercept[[j]] <- rep(randint.1[j], each = nsubjects[nclusters[1] + j]) } y1.intercept <- unlist(y1.intercept) y1.linpred = y1.intercept + log(c2) y1.prob = exp(y1.linpred) if (family == 'poisson') { y1 = stats::rpois(length(y1.prob), y1.prob) } if (family == 'neg.binom') { y1 = stats::rnbinom(length(y1.prob), size = 1, mu = y1.prob) } y = c(y0, y1) sim.dat = data.frame(trt = as.factor(trt), clust = as.factor(clust), y = as.integer(y)) if (allSimData == TRUE) { simulated.datasets[[i]] = list(sim.dat) } if (nofit == TRUE) { if (!exists("nofitop")) { nofitop <- data.frame(trt = trt, clust = clust, y1 = y) } else { nofitop[, length(nofitop) + 1] <- y } if (length(nofitop) == (nsim + 2)) { temp1 <- seq(1:nsim) temp2 <- paste0("y", temp1) colnames(nofitop) <- c("arm", "cluster", temp2) } if (length(nofitop) != (nsim + 2)) { next() } return(nofitop) } options(warn = -1) start.time = Sys.time() if (method == 'glmm') { if (i == 1) { if (isTRUE(optmethod == "auto")) { if (irgtt == FALSE) { if (analysis == 'poisson') { my.mod = try(lme4::glmer( y ~ as.factor(trt) + (1 | clust), data = sim.dat, family = stats::poisson(link = 'log') )) } if (analysis == 'neg.binom') { my.mod = try(lme4::glmer.nb(y ~ as.factor(trt) + (1 | clust), data = sim.dat)) } } if (irgtt == TRUE) { if (analysis == 'poisson') { my.mod <- try(lme4::glmer( y ~ trt + (0 + as.factor(trt) | clust), data = sim.dat, family = stats::poisson(link = 'log') )) } if (analysis == 'neg.binom') { my.mod = try(lme4::glmer.nb(y ~ trt + (0 + as.factor(trt) | clust), data = sim.dat)) } } optmethod <- optimizerSearch(my.mod) } } if (irgtt == FALSE) { if (analysis == 'poisson') { my.mod = try(lme4::glmer( y ~ trt + (1 | clust), data = sim.dat, family = stats::poisson(link = 'log'), control = lme4::glmerControl( optimizer = optmethod ) )) } if (analysis == 'neg.binom') { my.mod = try(lme4::glmer.nb( y ~ trt + (1 | clust), data = sim.dat, control = lme4::glmerControl( optimizer = optmethod ) )) } glmm.values <- summary(my.mod)$coefficient est.vector[i] <- glmm.values['trt2', 'Estimate'] se.vector[i] <- glmm.values['trt2', 'Std. Error'] stat.vector[i] <- glmm.values['trt2', 'z value'] pval.vector[i] <- glmm.values['trt2', 'Pr(>|z|)'] converge.vector[i] <- ifelse(is.null(my.mod@optinfo$conv$lme4$messages), TRUE, FALSE) } if (irgtt == TRUE) { if (analysis == 'poisson') { my.mod <- try(MASS::glmmPQL( y ~ trt, random = ~ 0 + trt | clust, data = sim.dat, family = stats::poisson(link = 'log') )) if (length(my.mod)==1 & class(my.mod) == "try-error") { converge.vector[i] <- FALSE next } else{ converge.vector[i] <- TRUE } glmm.values <- summary(my.mod)$tTable est.vector[i] <- glmm.values['trt2', 'Value'] se.vector[i] <- glmm.values['trt2', 'Std.Error'] stat.vector[i] <- glmm.values['trt2', 't-value'] pval.vector[i] <- glmm.values['trt2', 'p-value'] } if (analysis == 'neg.binom') { my.mod = try(lme4::glmer.nb( y ~ trt + (0 + trt | clust), data = sim.dat, control = lme4::glmerControl( optimizer = optmethod ) )) } } } if (method == 'gee') { sim.dat = dplyr::arrange(sim.dat, clust) my.mod = geepack::geeglm( y ~ trt, data = sim.dat, family = stats::poisson(link = 'log'), id = clust, corstr = "exchangeable" ) gee.values <- summary(my.mod)$coefficients est.vector[i] <- gee.values['trt2', 'Estimate'] se.vector[i] <- gee.values['trt2', 'Std.err'] stat.vector[i] <- gee.values['trt2', 'Wald'] pval.vector[i] <- gee.values['trt2', 'Pr(>|W|)'] converge.vector[i] <- ifelse(my.mod$geese$error != 0, FALSE, TRUE) } if (lowPowerOverride == FALSE && i > 50 && (i %% 10 == 0)) { sig.val.temp <- ifelse(pval.vector < alpha, 1, 0) pval.power.temp <- sum(sig.val.temp, na.rm = TRUE) / i if (pval.power.temp < 0.5) { stop( paste( "Calculated power is < ", pval.power.temp, ". Set lowPowerOverride == TRUE to run the simulations anyway.", sep = "" ) ) } } if (poorFitOverride == FALSE && converge.vector[i] == FALSE && i > 12) { if (sum(converge.vector == FALSE, na.rm = TRUE) > (nsim * .25)) { stop("more than 25% of simulations are singular fit: check model specifications") } } options(warn = 0) if (quiet == FALSE) { if (i == 1) { avg.iter.time = as.numeric(difftime(Sys.time(), start.time, units = 'secs')) time.est = avg.iter.time * (nsim - 1) / 60 hr.est = time.est %/% 60 min.est = round(time.est %% 60, 3) if (min.est > 2 && timelimitOverride == FALSE) { stop(paste0( "Estimated completion time: ", hr.est, 'Hr:', min.est, 'Min' )) } message( paste0( 'Begin simulations :: Start Time: ', Sys.time(), ' :: Estimated completion time: ', hr.est, 'Hr:', min.est, 'Min' ) ) } prog.bar$update(i / nsim) Sys.sleep(1 / 100) if (i == nsim) { message(paste0("Simulations Complete! Time Completed: ", Sys.time())) } } } if (irgtt == FALSE) { summary.message = paste0( "Monte Carlo Power Estimation based on ", nsim, " Simulations: Simple Design, Count Outcome. Data Simulated from ", switch(family, poisson = 'Poisson', neg.binom = 'Negative Binomial'), " distribution. Analyzed using ", switch(analysis, poisson = 'Poisson', neg.binom = 'Negative Binomial'), " regression" ) } else { summary.message = paste0( "Monte Carlo Power Estimation based on ", nsim, " Simulations: IRGTT Design, Count Outcome. Data Simulated from ", switch(family, poisson = 'Poisson', neg.binom = 'Negative Binomial'), " distribution. Analyzed using glmm fit with penalized quasi-likelihood.", switch(analysis, poisson = 'Poisson', neg.binom = 'Negative Binomial'), " regression" ) } long.method = switch(method, glmm = 'Generalized Linear Mixed Model', gee = 'Generalized Estimating Equation') cps.model.est = data.frame( Estimate = as.vector(unlist(est.vector)), Std.err = as.vector(unlist(se.vector)), Test.statistic = as.vector(unlist(stat.vector)), p.value = as.vector(unlist(pval.vector)), converge = as.vector(unlist(converge.vector)) ) if (!is.na(any(cps.model.est$converge))) { cps.model.temp <- dplyr::filter(cps.model.est, converge == TRUE) } else { cps.model.temp <- cps.model.est } power.parms <- confintCalc(alpha = alpha, nsim = nsim, p.val = cps.model.temp[, 'p.value']) c1.c2.rr = round(exp(log(c1) - log(c2)), 3) c2.c1.rr = round(exp(log(c2) - log(c1)), 3) inputs = t(data.frame( 'Arm1' = c("count" = c1, "risk.ratio" = c1.c2.rr), 'Arm2' = c("count" = c2, 'risk.ratio' = c2.c1.rr), 'Difference' = c("count" = cDiff, 'risk.ratio' = c2.c1.rr - c1.c2.rr) )) cluster.sizes = list('Arm1' = nsubjects[1:nclusters[1]], 'Arm2' = nsubjects[(1 + nclusters[1]):(nclusters[1] + nclusters[2])]) n.clusters = t(data.frame( "Arm1" = c("n.clust" = nclusters[1]), "Arm2" = c("n.clust" = nclusters[2]) )) var.parms = t(data.frame( 'Arm1' = c('sigma_b_sq' = sigma_b_sq[1]), 'Arm2' = c('sigma_b_sq' = sigma_b_sq[2]) )) dist.parms = rbind( 'Family:' = paste0(switch( family, poisson = 'Poisson', neg.binom = 'Negative Binomial' ), ' distribution'), 'Analysis:' = paste0(switch( analysis, poisson = 'Poisson', neg.binom = 'Negative Binomial' ), ' distribution') ) colnames(dist.parms) = "Data Simuation & Analysis Parameters" complete.output = structure( list( "overview" = summary.message, "nsim" = nsim, "power" = power.parms, "method" = long.method, "dist.parms" = dist.parms, "alpha" = alpha, "cluster.sizes" = cluster.sizes, "n.clusters" = n.clusters, "variance.parms" = var.parms, "inputs" = inputs, "model.estimates" = cps.model.est, "sim.data" = simulated.datasets, "convergence" = converge.vector ), class = 'crtpwr' ) return(complete.output) }
pipeline_install_directory <- function( directory, dest, upgrade = TRUE, force = FALSE, ...){ directory <- normalizePath(directory, mustWork = TRUE) config_path <- file.path(directory, "DESCRIPTION") if(!file.exists(config_path)){ stop("A RAVE pipeline must contains a RAVE-CONFIG or DESCRIPTION file") } desc <- pipeline_description(config_path) if(!length(desc$Type)){ stop("Cannot find `type` in the configuration file. ") } type <- desc$Type[[1]] remotes::install_deps(directory, upgrade = upgrade, force = force, ...) if( desc$Type == "rave-pipeline-collection" ){ if(length(desc$SubPipelines)){ sub_pipes <- strsplit(desc$SubPipelines, "[,\n]+")[[1]] for(pname in sub_pipes){ pdir <- file.path(directory, pname) pipeline_install_directory(pdir, dest, upgrade = FALSE, force = force, ...) } } } else { pipeline_root <- file.path(dest, desc$Package, desc$Version) if(dir.exists(pipeline_root)){ if(!force){ stop("Pipeline ", desc$Package, " - version ", desc$Version, ' already exists. Please use `force=TRUE` to force install') } unlink(pipeline_root, recursive = TRUE, force = TRUE) } dir_create2(pipeline_root) fs <- list.files(directory, all.files = TRUE, full.names = FALSE, recursive = FALSE, include.dirs = FALSE, no.. = TRUE) file.copy(file.path(directory, fs), pipeline_root, recursive = TRUE, copy.date = TRUE) version_file <- file.path(dest, desc$Package, "versions.yaml") save_yaml(desc, version_file) } } pipeline_root <- local({ root <- NULL function(root_path){ if(!missing(root_path)){ if(is.na(root_path)){ stop("pipeline root cannot be NA") } if('.' %in% root_path){ root_path <- root_path[root_path != '.'] root <<- c(".", normalizePath(root_path)) } else { root <- normalizePath(root_path) } } else { if(is.null(root)){ root <<- c(".", file.path(R_user_dir('raveio', "data"), "pipelines")) } } root } }) pipeline_list <- function(root_path = pipeline_root()){ names <- unlist(lapply( root_path, list.dirs, full.names = FALSE, recursive = FALSE )) names <- names[!stringr::str_starts(names, "[.~_]")] names <- names[!names %in% c("R", "src", "inst", "man", "doc")] names <- names[vapply(names, function(nm){ try({ pipeline_find(nm, root_path = root_path) return(TRUE) }, silent = TRUE) return(FALSE) }, FALSE)] names } pipeline_find <- function(name, root_path = pipeline_root()){ paths <- file.path(root_path, name) paths <- paths[dir.exists(paths)] for(path in paths){ path <- tryCatch({ vpath <- file.path(path, "versions.yaml") if(file.exists(vpath)){ v <- load_yaml(file.path(path, "versions.yaml")) path <- file.path(path, v$Version) } path <- activate_pipeline(path) return(path) }, error = function(e){ NULL }) if(!is.null(path)){ return(path) } } stop("Cannot find RAVE pipeline `", name, "`. Have you installed it?") } pipeline_attach <- function(name, root_path = pipeline_root()){ path <- pipeline_find(name, root_path) Sys.setenv("RAVE_PIPELINE" = path) }
mastermix<-function() { font0 <- tkfont.create(family="times",size=35,weight="bold",slant="italic") font1<-tkfont.create(family="times",size=14,weight="bold") font2<-tkfont.create(family="times",size=16,weight="bold",slant="italic") font3<-tkfont.create(family="times",size=10,weight="bold") font4<-tkfont.create(family="times",size=10) tt <- tktoplevel() tkwm.title(tt,"forensic DNA mixtures resolution") dudioutvar <- tclVar() dudivar <- tclVar() facvar <- tclVar() nfvar <- tclVar() scannfvar <- tclVar(1) TFrame <- tkframe(tt, relief="groove") labh <- tklabel(TFrame) font0 <- tkfont.create(family="times",size=35,weight="bold",slant="italic") font1<-tkfont.create(family="times",size=14,weight="bold") font2<-tkfont.create(family="times",size=16,weight="bold",slant="italic") tkgrid(tklabel(TFrame,text="MasterMix", font=font0, foreground="red"), labh) tkgrid(tklabel(TFrame,text="Two-person DNA mixtures resolution using allele peak height/ or area information", font=font2, foreground="red"), labh) tkgrid(TFrame) RCSFrame <- tkframe(tt, relief="groove") A2.but <- tkbutton(RCSFrame, text="Two-allele model", font=font1, command=A2.simu) tkbind(A2.but, "<Button-3>", function() print(help("A2.simu"))) A3.but <- tkbutton(RCSFrame, text="Three-allele model",font=font1, command=A3.simu) tkbind(A3.but, "<Button-3>", function() print(help("A3.simu"))) A4.but <- tkbutton(RCSFrame, text="Four-allele model", font=font1,command=A4.simu) tkbind(A4.but, "<Button-3>", function() print(help("A4.simu"))) tkgrid(A2.but, A3.but,A4.but,ipadx=20) tkgrid(RCSFrame) }
logLik.SSModel <- function(object, marginal=FALSE, nsim = 0, antithetics = TRUE, theta, check.model = TRUE, transform = c("ldl", "augment"), maxiter = 50, seed, convtol = 1e-8, expected = FALSE, H_tol = 1e15, transform_tol, ...) { if (check.model) { if (!is.SSModel(object, na.check = TRUE)) { return(-.Machine$double.xmax ^ 0.75) } } if (!is.logical(expected)) stop("Argument expected should be logical. ") expected <- as.integer(expected) p <- attr(object, "p") m <- attr(object, "m") k <- attr(object, "k") n <- attr(object, "n") ymiss <- array(is.na(object$y), dim = c(n, p)) storage.mode(ymiss) <- "integer" tv <- attr(object, "tv") if (all(object$distribution == "gaussian")) { if (all(c(object$Q, object$H) < .Machine$double.eps^0.75) || all(c(object$R, object$H) < .Machine$double.eps^0.75)) return(-.Machine$double.xmax ^ 0.75) if(missing(transform_tol)) { transform_tol <- max(100, max(apply(object$H, 3, diag))) * .Machine$double.eps } if (p > 1 && any(abs(apply(object$H, 3, "[", !diag(p))) > transform_tol)) { object <- tryCatch(transformSSM(object, type = match.arg(arg = transform, choices = c("ldl", "augment")), tol = transform_tol), error = function(e) e) if (!inherits(object, "SSModel")) { warning(object$message) return(-.Machine$double.xmax ^ 0.75) } m <- attr(object, "m") k <- attr(object, "k") tv <- attr(object, "tv") } out <- .Fortran(fgloglik, NAOK = TRUE, t(object$y), t(ymiss), tv, aperm(object$Z,c(2,1,3)), object$H, object$T, object$R, object$Q, object$a1, object$P1, object$P1inf, p, m, k, n, lik = double(1), object$tol, as.integer(sum(object$P1inf))) if (marginal) { logdetxx <- .Fortran(fmarginalxx, NAOK = TRUE, object$P1inf, object$Z, object$T, m, p, n, as.integer(sum(object$P1inf)), tv, lik = double(1), info = integer(1)) if (logdetxx$info == -1) { warning("Computation of marginal likelihood failed, could not compute the additional term.") return(-.Machine$double.xmax ^ 0.75) } else { out$lik <- out$lik + logdetxx$lik } } } else { if (maxiter < 1) stop("Argument maxiter must a positive integer. ") if (all(c(object$Q, object$u) == .Machine$double.eps^0.75) || all(c(object$R, object$u) == .Machine$double.eps^0.75) || any(!is.finite(c(object$R, object$Q, object$u) == .Machine$double.eps^0.75))) return(-.Machine$double.xmax ^ 0.75) if (missing(theta) || is.null(theta)) { theta <- initTheta(object$y, object$u, object$distribution) } else theta <- array(theta, dim = c(n, p)) if (nsim == 0) { nsim <- 1 sim <- 0 simtmp <- list(epsplus = array(0, c(1, 1, 1)), etaplus = array(0, c(1, 1, 1)), aplus1 = array(0, dim = c(1, 1)), c2 = numeric(1), nonzeroP1 = which(diag(object$P1) > object$tol), nNonzeroP1 = length(which(diag(object$P1) > object$tol)), zeroP1inf = which(diag(object$P1inf) > 0), nNonzeroP1inf = as.integer(sum(object$P1inf))) } else { sim <- 1 if (missing(seed)) seed <- 123 runif(1) old_seed <- get0(".Random.seed", envir = .GlobalEnv, inherits = FALSE) on.exit(assign(".Random.seed", old_seed, envir = .GlobalEnv, inherits = FALSE)) set.seed(seed) simtmp <- simHelper(object, nsim, antithetics) } nsim2 <- as.integer(max(sim * (3 * antithetics * nsim + nsim), 1)) out <- .Fortran(fngloglik, NAOK = TRUE, object$y, ymiss, tv, object$Z, object$T, object$R, object$Q, object$a1, object$P1, object$P1inf, p, m, k, n, lik = double(1), theta = theta, object$u, pmatch(x = object$distribution, table = c("gaussian", "poisson", "binomial", "gamma", "negative binomial"), duplicates.ok = TRUE), maxiter = as.integer(maxiter), simtmp$nNonzeroP1inf, convtol, simtmp$nNonzeroP1, as.integer(nsim), simtmp$epsplus, simtmp$etaplus, simtmp$aplus1, simtmp$c2, object$tol, info = integer(1), as.integer(antithetics), as.integer(sim), nsim2, diff = double(1), marginal = as.integer(marginal), expected, H_tol = H_tol) if(out$info!=0){ warning(switch(as.character(out$info), "-5" = paste0("Gaussian approximation converged to a degenerate case with max(H) = ",out$H_tol, ".", "\nReturning ", -.Machine$double.xmax^0.75, "."), "-3" = paste0("Couldn't compute LDL decomposition of P1.", "\nReturning ", -.Machine$double.xmax^0.75, "."), "-2" = paste0("Couldn't compute LDL decomposition of Q.", "\nReturning ", -.Machine$double.xmax^0.75, "."), "1" = paste0("Gaussian approximation failed due to non-finite value in linear predictor.", "\nReturning ", -.Machine$double.xmax^0.75, "."), "2" = paste0("Gaussian approximation failed due to non-finite value of p(theta|y).", "\nReturning ", -.Machine$double.xmax^0.75, "."), "3" = "Maximum number of iterations reached, the approximation did not converge.", "5" = paste0("Computation of marginal likelihood failed, could not compute the additional term.", "\nReturning ", -.Machine$double.xmax^0.75, ".") )) if(out$info!=3) { return(-.Machine$double.xmax^0.75) } } } out$lik }
efftox_priors <- function(alpha_mean, alpha_sd, beta_mean, beta_sd, gamma_mean, gamma_sd, zeta_mean, zeta_sd, eta_mean, eta_sd, psi_mean, psi_sd) { l <- list(alpha_mean = alpha_mean, alpha_sd = alpha_sd, beta_mean = beta_mean, beta_sd = beta_sd, gamma_mean = gamma_mean, gamma_sd = gamma_sd, zeta_mean = zeta_mean, zeta_sd = zeta_sd, eta_mean = eta_mean, eta_sd = eta_sd, psi_mean = psi_mean, psi_sd = psi_sd) class(l) <- c('efftox_priors') l }
structure(list(url = "https://api.twitter.com/2/users/45648666/following?max_results=1000&user.fields=created_at%2Cdescription%2Centities%2Cid%2Clocation%2Cname%2Cpinned_tweet_id%2Cprofile_image_url%2Cprotected%2Cpublic_metrics%2Curl%2Cusername%2Cverified%2Cwithheld&pagination_token=8EOQORH82UA1CZZZ", status_code = 200L, headers = structure(list(date = "Sun, 04 Jul 2021 12:24:55 UTC", server = "tsa_o", `content-type` = "application/json; charset=utf-8", `cache-control` = "no-cache, no-store, max-age=0", `content-length` = "202323", `x-access-level` = "read", `x-frame-options` = "SAMEORIGIN", `content-encoding` = "gzip", `x-xss-protection` = "0", `x-rate-limit-limit` = "15", `x-rate-limit-reset` = "1625402278", `content-disposition` = "attachment; filename=json.json", `x-content-type-options` = "nosniff", `x-rate-limit-remaining` = "12", `strict-transport-security` = "max-age=631138519", `x-connection-hash` = "358099e7ee27d3f1daf675083a1379c26cfd5d6955da63ec8b1cae9cb6b5f130"), class = c("insensitive", "list")), all_headers = list(list(status = 200L, version = "HTTP/2", headers = structure(list(date = "Sun, 04 Jul 2021 12:24:55 UTC", server = "tsa_o", `content-type` = "application/json; charset=utf-8", `cache-control` = "no-cache, no-store, max-age=0", `content-length` = "202323", `x-access-level` = "read", `x-frame-options` = "SAMEORIGIN", `content-encoding` = "gzip", `x-xss-protection` = "0", `x-rate-limit-limit` = "15", `x-rate-limit-reset` = "1625402278", `content-disposition` = "attachment; filename=json.json", `x-content-type-options` = "nosniff", `x-rate-limit-remaining` = "12", `strict-transport-security` = "max-age=631138519", `x-connection-hash` = "358099e7ee27d3f1daf675083a1379c26cfd5d6955da63ec8b1cae9cb6b5f130"), class = c("insensitive", "list")))), cookies = structure(list(domain = c(".twitter.com", ".twitter.com"), flag = c(TRUE, TRUE), path = c("/", "/"), secure = c(TRUE, TRUE), expiration = structure(c(1688456705, 1688456705), class = c("POSIXct", "POSIXt")), name = c("personalization_id", "guest_id"), value = c("REDACTED", "REDACTED")), row.names = c(NA, -2L), class = "data.frame"), content = charToRaw("{\"data\":[{\"profile_image_url\":\"https://pbs.twimg.com/profile_images/811636493777309697/tZLcGm_w_normal.jpg\",\"url\":\"https://t.co/5Ztsx13Qdu\",\"description\":\"Mom, Flint pediatrician, public health advocate & immigrant. Author of “What the Eyes Don’t See.”\",\"verified\":true,\"location\":\"Flint, MI\",\"entities\":{\"url\":{\"urls\":[{\"start\":0,\"end\":23,\"url\":\"https://t.co/5Ztsx13Qdu\",\"expanded_url\":\"http://monahannaattisha.com\",\"display_url\":\"monahannaattisha.com\"}]}},\"pinned_tweet_id\":\"1260174318790737920\",\"created_at\":\"2012-03-30T02:30:02.000Z\",\"id\":\"540458083\",\"username\":\"MonaHannaA\",\"public_metrics\":{\"followers_count\":20092,\"following_count\":1458,\"tweet_count\":4939,\"listed_count\":303},\"protected\":false,\"name\":\"Mona Hanna-Attisha\"},{\"profile_image_url\":\"https://pbs.twimg.com/profile_images/496621759580626944/aKN4H7UN_normal.jpeg\",\"url\":\"https://t.co/2J2G4roGmX\",\"description\":\"Archaeologist & Wayne State Univ. Anthropology professor by day. Music geek & history nerd by night. Mom & wife 24/7.\",\"verified\":false,\"location\":\"Detroit \",\"entities\":{\"url\":{\"urls\":[{\"start\":0,\"end\":23,\"url\":\"https://t.co/2J2G4roGmX\",\"expanded_url\":\"http://clasweb.clas.wayne.edu/Krysta-Ryzewski\",\"display_url\":\"clasweb.clas.wayne.edu/Krysta-Ryzewski\"}]}},\"created_at\":\"2014-08-01T21:37:21.000Z\",\"id\":\"2731073285\",\"username\":\"KrystaRyzew\",\"public_metrics\":{\"followers_count\":630,\"following_count\":1343,\"tweet_count\":502,\"listed_count\":14},\"protected\":false,\"name\":\"Dr. Krysta Ryzewski\"},{\"profile_image_url\":\"https://pbs.twimg.com/profile_images/992454836435156993/xJfDC2a8_normal.jpg\",\"url\":\"http://t.co/KPF3cm6S9A\",\"description\":\"Invest Detroit finances and supports business development, commercial real estate, and entrepreneurs in Detroit and the region.\",\"verified\":false,\"location\":\"Detroit\",\"entities\":{\"url\":{\"urls\":[{\"start\":0,\"end\":22,\"url\":\"http://t.co/KPF3cm6S9A\",\"expanded_url\":\"http://www.investdetroit.com\",\"display_url\":\"investdetroit.com\"}]}},\"created_at\":\"2014-06-06T01:51:22.000Z\",\"id\":\"2549014572\",\"username\":\"InvestDet\",\"public_metrics\":{\"followers_count\":1685,\"following_count\":348,\"tweet_count\":679,\"listed_count\":55},\"protected\":false,\"name\":\"Invest Detroit\"},{\"profile_image_url\":\"https://pbs.twimg.com/profile_images/527136831607824384/KAbPxq-q_normal.png\",\"url\":\"http://t.co/fQ0aMJk78l\",\"description\":\"Research and education center dedicated to solving environmental problems at the land-water interface and bay-lake exchanges in the Great Lakes\",\"verified\":false,\"location\":\"Oregon, Ohio\",\"entities\":{\"url\":{\"urls\":[{\"start\":0,\"end\":22,\"url\":\"http://t.co/fQ0aMJk78l\",\"expanded_url\":\"http://www.utoledo.edu/nsm/lec\",\"display_url\":\"utoledo.edu/nsm/lec\"}]}},\"created_at\":\"2009-03-04T17:07:40.000Z\",\"id\":\"22800555\",\"username\":\"lakeeriecenter\",\"public_metrics\":{\"followers_count\":1843,\"following_count\":1170,\"tweet_count\":475,\"listed_count\":51},\"protected\":false,\"name\":\"UT Lake Erie Center\"},{\"profile_image_url\":\"https://pbs.twimg.com/profile_images/494886574564179968/qROYU2p1_normal.jpeg\",\"url\":\"http://t.co/Ikpz7ylbfr\",\"description\":\"Environmental writer\",\"verified\":false,\"location\":\"The (Toledo) Blade\",\"entities\":{\"url\":{\"urls\":[{\"start\":0,\"end\":22,\"url\":\"http://t.co/Ikpz7ylbfr\",\"expanded_url\":\"http://toledoblade.typepad.com/ripple-effect/\",\"display_url\":\"toledoblade.typepad.com/ripple-effect/\"}]}},\"created_at\":\"2014-07-31T15:56:23.000Z\",\"id\":\"2696042311\",\"username\":\"ecowriterohio\",\"public_metrics\":{\"followers_count\":2406,\"following_count\":3550,\"tweet_count\":6706,\"listed_count\":106},\"protected\":false,\"name\":\"Tom Henry\"},{\"profile_image_url\":\"https://pbs.twimg.com/profile_images/1295357090303746049/YgO4pY3R_normal.jpg\",\"url\":\"https://t.co/q9pcfbnIwq\",\"description\":\"Lifelong Michigander. Proud mom. Governor of Michigan. This is my personal account. For my official account, visit @GovWhitmer.\",\"verified\":true,\"location\":\"East Lansing, MI\",\"entities\":{\"url\":{\"urls\":[{\"start\":0,\"end\":23,\"url\":\"https://t.co/q9pcfbnIwq\",\"expanded_url\":\"http://gretchenwhitmer.com\",\"display_url\":\"gretchenwhitmer.com\"}]},\"description\":{\"mentions\":[{\"start\":115,\"end\":126,\"username\":\"GovWhitmer\"}]}},\"created_at\":\"2019-02-07T21:14:39.000Z\",\"id\":\"1093619068148559872\",\"username\":\"gretchenwhitmer\",\"public_metrics\":{\"followers_count\":144410,\"following_count\":56,\"tweet_count\":315,\"listed_count\":429},\"protected\":false,\"name\":\"Gretchen Whitmer\"},{\"profile_image_url\":\"https://pbs.twimg.com/profile_images/1410352589854724096/3qzSjS2P_normal.jpg\",\"url\":\"http://t.co/lOItIfcqtH\",\"description\":\"Michigan's Department of Health and Human Services\",\"verified\":true,\"location\":\"Lansing, Michigan\",\"entities\":{\"url\":{\"urls\":[{\"start\":0,\"end\":22,\"url\":\"http://t.co/lOItIfcqtH\",\"expanded_url\":\"http://www.michigan.gov/mdhhs\",\"display_url\":\"michigan.gov/mdhhs\"}]}},\"pinned_tweet_id\":\"1411008311663730694\",\"created_at\":\"2009-07-16T13:48:27.000Z\",\"id\":\"57338289\",\"username\":\"MichiganHHS\",\"public_metrics\":{\"followers_count\":32977,\"following_count\":2132,\"tweet_count\":9192,\"listed_count\":550},\"protected\":false,\"name\":\"Michigan HHS Dept\"},{\"profile_image_url\":\"https://pbs.twimg.com/profile_images/1285220097620152322/hy3KzMCL_normal.jpg\",\"url\":\"https://t.co/7nHJndtfQP\",\"description\":\"Candidate for Detroit City Council Dis. 6 | Policy & Research Director @WeThePeople_MI | MSW @UMSocialWork | Photographer | I talk a lot about change (she/her)\",\"verified\":false,\"location\":\"Detroit\",\"entities\":{\"url\":{\"urls\":[{\"start\":0,\"end\":23,\"url\":\"https://t.co/7nHJndtfQP\",\"expanded_url\":\"https://secure.actblue.com/donate/gabriela-santiago-romero\",\"display_url\":\"secure.actblue.com/donate/gabriel…\"}]},\"description\":{\"mentions\":[{\"start\":71,\"end\":86,\"username\":\"WeThePeople_MI\"},{\"start\":93,\"end\":106,\"username\":\"UMSocialWork\"}]}},\"pinned_tweet_id\":\"1384543770763534336\",\"created_at\":\"2010-12-15T13:46:17.000Z\",\"id\":\"226940716\",\"username\":\"gabysantiromero\",\"public_metrics\":{\"followers_count\":1204,\"following_count\":1980,\"tweet_count\":32390,\"listed_count\":26},\"protected\":false,\"name\":\"Gabriela Santiago-Romero\"},{\"profile_image_url\":\"https://pbs.twimg.com/profile_images/925389735216013313/AxniKLXX_normal.jpg\",\"url\":\"https://t.co/pye7tIPgOP\",\"description\":\"We're a hub of info that highlight America's common date = structure(1625401495, class = c("POSIXct", "POSIXt" ), tzone = "GMT"), times = c(redirect = 0, namelookup = 9.6e-05, connect = 1e-04, pretransfer = 0.000378, starttransfer = 0.691889, total = 0.920125)), class = "response")
library(DHARMa) library(MASS) library(lme4) library(mgcv) testData = createData(sampleSize = 200, overdispersion = 0, randomEffectVariance = 0, family = binomial(), binomialTrials = 20) fittedModelGLM <- glm(cbind(observedResponse1,observedResponse0) ~ Environment1 , family = "binomial", data = testData) fittedModelGAM <- gam(cbind(observedResponse1,observedResponse0) ~ s(Environment1) ,family = "binomial", data = testData) out = simulate(fittedModelGLM, nsim = 10) out2 = simulate(fittedModelGAM, nsim = 10) dim(out) dim(out2) out2 = data.frame(out2) x = out2 convertGam <- function(x){ nSim = ncol(x) nObs = nrow(x[[1]]) df = list() for(i in 1:nSim){ rownames(x[[i]]) <- as.character(1:200) } df= as.data.frame(df) return(df) } fitted.gam <- function(object, ...){ class(object) = "glm" out = stats::fitted(object, ...) names(out) = as.character(1:length(out)) out }
test_that("drive_rm() copes with no input", { expect_identical(drive_rm(), dribble()) }) test_that("drive_rm() copes when there are no matching files", { skip_if_no_token() skip_if_offline() expect_identical(drive_rm("non-existent-file-name"), dribble()) })
fdt_cat.data.frame <- function (x, by, sort=TRUE, decreasing=TRUE, ...) { stopifnot(is.data.frame(x)) res <- list() if (missing(by)) { logCol <- sapply(x, is.factor) for (i in 1:ncol(x)) { if (logCol[i]) { m <- as.data.frame(x[, i]) fdt <- make.fdt_cat.multiple(m, sort, decreasing) tmpres <- list(table=fdt[[1]]) res <- c(res, list(tmpres)) } } valCol <- logCol[logCol] names(res) <- names(valCol) } else { nameF <- character() nameY <- character() namesdf <- names(x) pos <- which(namesdf == by) stopifnot(is.factor((x[[pos]]))) numF <- table(x[[pos]]) for (i in 1:length(numF)) { tmpdf <- subset(x, x[[pos]] == names(numF[i])) tmpdf <- tmpdf[-pos] logCol <- sapply(tmpdf, is.factor) for (j in 1:ncol(tmpdf)) { if (logCol[j]) { m <- as.data.frame(tmpdf[, j]) fdt <- make.fdt_cat.multiple(m, sort, decreasing) newFY <- list(fdt) nameF <- names(numF[i]) nameY <- names(logCol[j]) nameFY <- paste(nameF, '.', nameY, sep="") names(newFY) <- sub(' +$', '', nameFY) res <- c(res, newFY) } } } } class(res) <- c('fdt_cat.multiple', 'fdt_cat', 'list') invisible(res) }
step_impute_roll <- function(recipe, ..., role = NA, trained = FALSE, columns = NULL, statistic = median, window = 5, skip = FALSE, id = rand_id("impute_roll")) { if (!is_tune(window) & !is_varying(window)) { if (window < 3 | window %% 2 != 1) { rlang::abort("`window` should be an odd integer >= 3") } window <- as.integer(floor(window)) } add_step( recipe, step_impute_roll_new( terms = ellipse_check(...), role = role, trained = trained, columns = columns, statistic = statistic, window = window, skip = skip, id = id ) ) } step_rollimpute <- function(recipe, ..., role = NA, trained = FALSE, columns = NULL, statistic = median, window = 5, skip = FALSE, id = rand_id("impute_roll")) { lifecycle::deprecate_warn( when = "0.1.16", what = "recipes::step_rollimpute()", with = "recipes::step_impute_roll()" ) step_impute_roll( recipe, ..., role = role, trained = trained, columns = columns, statistic = statistic, window = window, skip = skip, id = id ) } step_impute_roll_new <- function(terms, role, trained, columns, statistic, window, skip, id) { step( subclass = "impute_roll", terms = terms, role = role, trained = trained, columns = columns, statistic = statistic, window = window, skip = skip, id = id ) } prep.step_impute_roll <- function(x, training, info = NULL, ...) { col_names <- recipes_eval_select(x$terms, training, info) check_type(training[, col_names]) dbl_check <- vapply(training[, col_names], is.double, logical(1)) if (any(!dbl_check)) rlang::abort("All columns must be double precision for rolling imputation") step_impute_roll_new( terms = x$terms, role = x$role, trained = TRUE, columns = col_names, statistic = x$statistic, window = x$window, skip = x$skip, id = x$id ) } prep.step_rollimpute <- prep.step_impute_roll get_window_ind <- function(i, n, k) { sides <- (k - 1) / 2 if (i - sides >= 1 & i + sides <= n) return((i - sides):(i + sides)) if (i - sides < 1) return(1:k) if (i + sides > n) return((n - k + 1):n) } get_rolling_ind <- function(inds, n, k) map(inds, get_window_ind, n = n, k = k) window_est <- function(inds, x, statfun) { x <- x[inds] x <- x[!is.na(x)] out <- if(length(x) == 0) na_dbl else statfun(x) if(!is.double(out)) out <- as.double(out) out } impute_rolling <- function(inds, x, statfun) { map_dbl(inds, window_est, x = x, statfun = statfun) } bake.step_impute_roll <- function(object, new_data, ...) { n <- nrow(new_data) missing_ind <- lapply(new_data[, object$columns], function(x) which(is.na(x))) has_missing <- map_lgl(missing_ind, function(x) length(x) > 0) missing_ind <- missing_ind[has_missing] roll_ind <- lapply(missing_ind, get_rolling_ind, n = n, k = object$window) for(i in seq(along.with = roll_ind)) { imp_var <- names(roll_ind)[i] estimates <- impute_rolling(roll_ind[[i]], new_data[[imp_var]], object$statistic) new_data[missing_ind[[i]], imp_var] <- estimates } as_tibble(new_data) } bake.step_rollimpute <- bake.step_impute_roll print.step_impute_roll <- function(x, width = max(20, options()$width - 30), ...) { cat("Rolling Imputation for ", sep = "") printer(x$columns, x$terms, x$trained, width = width) invisible(x) } print.step_rollimpute <- print.step_impute_roll tidy.step_impute_roll <- function(x, ...) { if (is_trained(x)) { res <- tibble(terms = unname(x$columns), window = x$window) } else { term_names <- sel2char(x$terms) res <- tibble(terms = term_names, window = x$window) } res$id <- x$id res } tidy.step_rollimpute <- tidy.step_impute_roll tunable.step_impute_roll <- function(x, ...) { tibble::tibble( name = c("statistic", "window"), call_info = list( list(pkg = "dials", fun = "location_stat"), list(pkg = "dials", fun = "window") ), source = "recipe", component = "step_impute_roll", component_id = x$id ) } tunable.step_rollimpute <- tunable.step_impute_roll
\donttest{ if (bru_safe_inla(multicore = FALSE)) { input.df <- data.frame(x = cos(1:10)) input.df <- within(input.df, y <- 5 + 2 * x + rnorm(10, mean = 0, sd = 0.1)) fit <- bru(y ~ x + Intercept, family = "gaussian", data = input.df) fit$summary.fixed } if (bru_safe_inla(multicore = FALSE)) { lik <- like(family = "gaussian", formula = y ~ x + Intercept, data = input.df) fit <- bru(~ x + Intercept(1), lik) fit$summary.fixed } if (bru_safe_inla(multicore = FALSE)) { z <- 2 input.df <- within(input.df, y <- 5 + exp(z) * x + rnorm(10, mean = 0, sd = 0.1)) lik <- like( family = "gaussian", data = input.df, formula = y ~ exp(z) * x + Intercept ) fit <- bru(~ z(1) + Intercept(1), lik) fit$summary.fixed } }
acc = read.csv("path to data") View(acc) set.seed(1) index <- sample(1:nrow(acc), round(0.75*nrow(acc))) train <- acc[index,] test <- acc[-index,] fitTrn <- glm(isOneday~., data=train, family=binomial(link="logit")) fitted.results <- predict(fitTrn, newdata=test, type='response') library(ROCR) p <- predict(fitTrn, newdata=test, type="response") pr <- prediction(p, test$isOneday) prf <- performance(pr, measure="tpr", x.measure="fpr") auc <- performance(pr, measure="auc")
NULL load_task_pima = function(id = "pima") { b = as_data_backend(load_dataset("PimaIndiansDiabetes2", "mlbench")) task = TaskClassif$new(id, b, target = "diabetes", positive = "pos") b$hash = task$man = "mlr3::mlr_tasks_pima" task } mlr_tasks$add("pima", load_task_pima)
by.ppp <- function(data, INDICES=marks(data), FUN, ...) { if(missing(INDICES)) INDICES <- marks(data, dfok=FALSE) if(missing(FUN)) stop("FUN is missing") y <- split(data, INDICES) z <- list() for(i in seq_along(y)) z[[i]] <- FUN(y[[i]], ...) names(z) <- names(y) z <- as.solist(z, demote=TRUE) return(z) }
m <- matrix(1:10/10, ncol=2, byrow=TRUE) colnames(m) <- c('a', 'b') d <- as.data.frame(m) test_that('lcut on vector', { testedHedges <- c("ex", "si", "ve", "-", "ml", "ro", "qr", "vr", "ty") testedAtomic <- c("sm", "me", "bi") smHedgeNames <- c("ex", "si", "ve", "", "ml", "ro", "qr", "vr") meHedgeNames <- c("ty", "", "ml", "ro", "qr", "vr") biHedgeNames <- smHedgeNames res <- lcut(d$a, context=ctx3(0, 0.5, 1), atomic=testedAtomic, hedges=testedHedges, name='a') expectedAttrs <- c(paste(smHedgeNames, 'sm', 'a', sep='.'), paste(meHedgeNames, 'me', 'a', sep='.'), paste(biHedgeNames, 'bi', 'a', sep='.')) expectedAttrs <- sub('^\\.', '', expectedAttrs) expect_true(is.fsets(res)) expect_equal(ncol(res), 22) expect_equal(nrow(res), 5) expect_equal(colnames(res), expectedAttrs) expect_equal(vars(res), rep('a', 22)) s <- matrix(c(0,1,1,1,1,1,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,1,1,1,1,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,1,1,1,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,1,1,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,1,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,1,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,1,1,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,1,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0,0,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0), nrow=22, ncol=22, byrow=TRUE) expect_equal(specs(res), s) }) test_that('lcut on vector (some hedges disabled)', { testedHedges <- c("ex", "ve", "ml", "vr", "ty") testedAtomic <- c("me", "bi") meHedgeNames <- c("ty", "ml", "vr") biHedgeNames <- c("ex", "ve", "ml", "vr") expectedAttrs <- c(paste(meHedgeNames, 'me', 'a', sep='.'), paste(biHedgeNames, 'bi', 'a', sep='.')) res <- lcut(d$a, context=ctx3(0, 0.5, 1), atomic=testedAtomic, hedges=testedHedges, name='a') expect_true(is.fsets(res)) expect_equal(ncol(res), 7) expect_equal(nrow(res), 5) expect_equal(colnames(res), expectedAttrs) expect_equal(vars(res), rep('a', 7)) s <- matrix(c(0,1,1, 0,0,0,0, 0,0,1, 0,0,0,0, 0,0,0, 0,0,0,0, 0,0,0, 0,1,1,1, 0,0,0, 0,0,1,1, 0,0,0, 0,0,0,1, 0,0,0, 0,0,0,0), nrow=7, ncol=7, byrow=TRUE) expect_equal(specs(res), s) expect_true(is.fsets(res)) }) test_that('lcut on matrix', { testedHedges <- c("ex", "si", "ve", "-", "ml", "ro", "qr", "vr", "ty") testedAtomic <- c("sm", "me", "bi") smHedgeNames <- c("ex", "si", "ve", "", "ml", "ro", "qr", "vr") meHedgeNames <- c("ty", "", "ml", "ro", "qr", "vr") biHedgeNames <- smHedgeNames expectedAttrs <- c(paste(smHedgeNames, 'sm', 'a', sep='.'), paste(meHedgeNames, 'me', 'a', sep='.'), paste(biHedgeNames, 'bi', 'a', sep='.'), paste(smHedgeNames, 'sm', 'b', sep='.'), paste(meHedgeNames, 'me', 'b', sep='.'), paste(biHedgeNames, 'bi', 'b', sep='.')) expectedAttrs <- sub('^\\.', '', expectedAttrs) res <- lcut(as.matrix(m), context=ctx3(0, 0.5, 1), hedges=testedHedges) expect_true(is.fsets(res)) expect_equal(ncol(res), 44) expect_equal(nrow(res), 5) expect_equal(colnames(res), expectedAttrs) expect_equal(vars(res), c(rep('a', 22), rep('b', 22))) s <- matrix(c(0,1,1,1,1,1,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,1,1,1,1,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,1,1,1,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,1,1,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,1,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,1,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,1,1,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,1,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0,0,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0), byrow=TRUE, nrow=22, ncol=22) sfill <- matrix(0, nrow=22, ncol=22) s <- cbind(rbind(s, sfill), rbind(sfill, s)) expect_equal(specs(res), s) }) test_that('lcut on data frame', { testedHedges <- c("ex", "si", "ve", "-", "ml", "ro", "qr", "vr", "ty") testedAtomic <- c("sm", "me", "bi") smHedgeNames <- c("ex", "si", "ve", "", "ml", "ro", "qr", "vr") meHedgeNames <- c("ty", "", "ml", "ro", "qr", "vr") biHedgeNames <- smHedgeNames expectedAttrs <- c(paste(smHedgeNames, 'sm', 'a', sep='.'), paste(meHedgeNames, 'me', 'a', sep='.'), paste(biHedgeNames, 'bi', 'a', sep='.'), paste(smHedgeNames, 'sm', 'b', sep='.'), paste(meHedgeNames, 'me', 'b', sep='.'), paste(biHedgeNames, 'bi', 'b', sep='.')) expectedAttrs <- sub('^\\.', '', expectedAttrs) res <- lcut(as.data.frame(m), context=ctx3(0, 0.5, 1), hedges=testedHedges) expect_true(is.fsets(res)) expect_equal(ncol(res), 44) expect_equal(nrow(res), 5) expect_equal(colnames(res), expectedAttrs) expect_equal(vars(res), c(rep('a', 22), rep('b', 22))) s <- matrix(c(0,1,1,1,1,1,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,1,1,1,1,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,1,1,1,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,1,1,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,1,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,1,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,1,1,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,1,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0,0,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0), byrow=TRUE, nrow=22, ncol=22) sfill <- matrix(0, nrow=22, ncol=22) s <- cbind(rbind(s, sfill), rbind(sfill, s)) expect_equal(specs(res), s) }) test_that('lcut on single row data frame', { testedHedges <- c("ex", "si", "ve", "-", "ml", "ro", "qr", "vr", "ty") testedAtomic <- c("sm", "me", "bi") smHedgeNames <- c("ex", "si", "ve", "", "ml", "ro", "qr", "vr") meHedgeNames <- c("ty", "", "ml", "ro", "qr", "vr") biHedgeNames <- smHedgeNames expectedAttrs <- c(paste(smHedgeNames, 'sm', 'a', sep='.'), paste(meHedgeNames, 'me', 'a', sep='.'), paste(biHedgeNames, 'bi', 'a', sep='.'), paste(smHedgeNames, 'sm', 'b', sep='.'), paste(meHedgeNames, 'me', 'b', sep='.'), paste(biHedgeNames, 'bi', 'b', sep='.')) expectedAttrs <- sub('^\\.', '', expectedAttrs) res <- lcut(m[1, , drop=FALSE], context=ctx3(0, 0.5, 1), hedges=testedHedges) expect_true(is.fsets(res)) expect_equal(ncol(res), 44) expect_equal(nrow(res), 1) expect_equal(colnames(res), expectedAttrs) expect_equal(vars(res), c(rep('a', 22), rep('b', 22))) s <- matrix(c(0,1,1,1,1,1,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,1,1,1,1,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,1,1,1,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,1,1,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,1,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,1,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,1,1,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,1,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0,0,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0), byrow=TRUE, nrow=22, ncol=22) sfill <- matrix(0, nrow=22, ncol=22) s <- cbind(rbind(s, sfill), rbind(sfill, s)) expect_equal(specs(res), s) }) test_that('lcut on empty row data frame', { testedHedges <- c("ex", "si", "ve", "-", "ml", "ro", "qr", "vr", "ty") testedAtomic <- c("sm", "me", "bi") smHedgeNames <- c("ex", "si", "ve", "", "ml", "ro", "qr", "vr") meHedgeNames <- c("ty", "", "ml", "ro", "qr", "vr") biHedgeNames <- smHedgeNames expectedAttrs <- c(paste(smHedgeNames, 'sm', 'a', sep='.'), paste(meHedgeNames, 'me', 'a', sep='.'), paste(biHedgeNames, 'bi', 'a', sep='.'), paste(smHedgeNames, 'sm', 'b', sep='.'), paste(meHedgeNames, 'me', 'b', sep='.'), paste(biHedgeNames, 'bi', 'b', sep='.')) expectedAttrs <- sub('^\\.', '', expectedAttrs) res <- lcut(m[FALSE, , drop=FALSE], context=ctx3(0, 0.5, 1), hedges=testedHedges) expect_true(is.fsets(res)) expect_equal(ncol(res), 44) expect_equal(nrow(res), 0) expect_equal(colnames(res), expectedAttrs) expect_equal(vars(res), c(rep('a', 22), rep('b', 22))) s <- matrix(c(0,1,1,1,1,1,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,1,1,1,1,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,1,1,1,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,1,1,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,1,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,1,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,1, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,1,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,1,1,1,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,1,1,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,1,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,1,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,1,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0,1,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0,0,1, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0,0,0), byrow=TRUE, nrow=22, ncol=22) sfill <- matrix(0, nrow=22, ncol=22) s <- cbind(rbind(s, sfill), rbind(sfill, s)) expect_equal(specs(res), s) }) test_that('lcut empty data.frame', { testedHedges <- c("ex", "-", "ml", "ro", "qr", "vr") hedgeNames <- c("ex", "", "ml", "ro", "qr", "vr") smHedgeNames <- hedgeNames biHedgeNames <- hedgeNames attrs <- c(paste(smHedgeNames, 'sm', sep='.'), paste(biHedgeNames, 'bi', sep='.')) d <- d[FALSE, , drop=FALSE] res <- lcut(d, atomic=c('sm', 'bi'), context=ctx3(0, 0.5, 1), hedges=testedHedges) expectedAttrs <- c(paste(attrs, '.a', sep=''), paste(attrs, '.b', sep='')) expectedAttrs <- sub('^\\.', '', expectedAttrs) expect_true(is.matrix(res)) expect_equal(ncol(res), 24) expect_equal(nrow(res), 0) expect_equal(sort(colnames(res)), sort(expectedAttrs)) expect_true(inherits(res, 'fsets')) expect_equivalent(vars(res), c(rep('a', 12), rep('b', 12))) s <- matrix(c(0,1,1,1,1,1, 0,0,0,0,0,0, 0,0,1,1,1,1, 0,0,0,0,0,0, 0,0,0,1,1,1, 0,0,0,0,0,0, 0,0,0,0,1,1, 0,0,0,0,0,0, 0,0,0,0,0,1, 0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0, 0,0,0,0,0,0, 0,1,1,1,1,1, 0,0,0,0,0,0, 0,0,1,1,1,1, 0,0,0,0,0,0, 0,0,0,1,1,1, 0,0,0,0,0,0, 0,0,0,0,1,1, 0,0,0,0,0,0, 0,0,0,0,0,1, 0,0,0,0,0,0, 0,0,0,0,0,0), byrow=TRUE, nrow=12, ncol=12) sfill <- matrix(0, nrow=12, ncol=12) s <- cbind(rbind(s, sfill), rbind(sfill, s)) mapper <- seq_along(expectedAttrs) names(mapper) <- expectedAttrs s <- s[mapper[colnames(res)], mapper[colnames(res)]] expect_equal(specs(res), s) expect_true(is.fsets(res)) })
change_to_name <- function(x, column=1){ child_list <- lapply( x$children, function(y) { y <- dplyr::mutate(y, "colname" = colnames(y)[column]) dplyr::rename(y,"name" = colnames(y)[column]) } ) dplyr::mutate(x, children = child_list) } promote_na_one <- function(x){ na_child_loc <- which(is.na(x$children[[1]]$name)) if(length(na_child_loc)){ na_child <- x$children[[1]][na_child_loc,] x <- dplyr::bind_cols( x, na_child[1,setdiff(colnames(na_child),c("name","children","colname"))] ) x$children[[1]] <- x$children[[1]][-na_child_loc,] x } else { x } } promote_na <- function(x){ lapply( seq_len(nrow(x)), function(row){promote_na_one(x[row,])} ) } d3_nest <- function( data=NULL, value_cols=character(), root = "root", json = TRUE ) { stopifnot(!is.null(data), inherits(data, "data.frame")) nonnest_cols <- dplyr::setdiff(colnames(data),value_cols) data <- dplyr::as_tibble(data) data <- dplyr::mutate_if(data, is.factor, as.character) if(utils::packageVersion("tidyr") > "0.8.3") { data_nested <- dplyr::bind_rows(promote_na( change_to_name( tidyr::nest( .data=data, children = dplyr::one_of(c(nonnest_cols[length(nonnest_cols)], value_cols)) ) ) )) } else { data_nested <- dplyr::bind_rows(promote_na( change_to_name( tidyr::nest( data=data, dplyr::one_of(c(nonnest_cols[length(nonnest_cols)], value_cols)), .key="children" ) ) )) } for(x in rev( colnames(data_nested)[ -which(colnames(data_nested) %in% c("children","colname",value_cols)) ] )){ if(utils::packageVersion("tidyr") > "0.8.3") { data_nested <- dplyr::bind_rows(promote_na( change_to_name( tidyr::nest( .data = data_nested, children = dplyr::one_of(colnames(data_nested)[colnames(data_nested) %in% c(x,"children",value_cols)]) ) ) )) } else { data_nested <- dplyr::bind_rows(promote_na( change_to_name( tidyr::nest( data_nested, dplyr::one_of(colnames(data_nested)[colnames(data_nested) %in% c(x,"children",value_cols)]), .key = "children" ) ) )) } } data_nested$name = root if(json){ d3_json(data_nested,strip=TRUE) } else { data_nested } }
mapkeyIconDependency <- function() { list( htmltools::htmlDependency( "lfx-mapkeyicon", version = "1.0.0", src = system.file("htmlwidgets/lfx-mapkeyicon", package = "leaflet.extras2"), script = c("L.Icon.Mapkey.js", "lfx-mapkeyicon-bindings.js"), stylesheet = c("L.Icon.Mapkey.css"), all_files = TRUE ) ) } mapkeyIconList = function(...) { res = structure( list(...), class = "leaflet_mapkey_icon_set" ) cls = unlist(lapply(res, inherits, "leaflet_mapkey_icon")) if (any(!cls)) stop("Arguments passed to mapkeyIconList() must be icon objects returned from makeMapkeyIcon()") res } `[.leaflet_mapkey_icon_set` = function(x, i) { if (is.factor(i)) { i = as.character(i) } if (!is.character(i) && !is.numeric(i) && !is.integer(i)) { stop("Invalid subscript type '", typeof(i), "'") } structure(.subset(x, i), class = "leaflet_mapkey_icon_set") } mapkeyIconSetToMapkeyIcons = function(x) { cols = names(formals(makeMapkeyIcon)) cols = structure(as.list(cols), names = cols) leaflet::filterNULL(lapply(cols, function(col) { colVals = unname(sapply(x, `[[`, col)) if (length(unique(colVals)) == 1) { return(colVals[[1]]) } else { return(colVals) } })) } makeMapkeyIcon <- function( icon = 'mapkey', color = " iconSize = 12, background = ' borderRadius = '100%', hoverScale = 1.4, hoverEffect = TRUE, additionalCSS = NULL, hoverCSS = NULL, htmlCode = NULL, boxShadow = TRUE ) { icon = leaflet::filterNULL(list( icon = icon, color = color, size = iconSize, background = background, borderRadius = borderRadius, hoverScale = hoverScale, hoverEffect = hoverEffect, additionalCSS = additionalCSS, hoverCSS = hoverCSS, htmlCode = htmlCode, boxShadow = boxShadow )) structure(icon, class = "leaflet_mapkey_icon") } mapkeyIcons <- function( icon = 'mapkey', color = " iconSize = 12, background = ' borderRadius = '100%', hoverScale = 1.4, hoverEffect = TRUE, hoverCSS = NULL, additionalCSS = NULL, htmlCode = NULL, boxShadow = TRUE ) { leaflet::filterNULL(list( icon = icon, color = color, size = iconSize, background = background, borderRadius = borderRadius, hoverScale = hoverScale, hoverEffect = hoverEffect, hoverCSS = hoverCSS, additionalCSS = additionalCSS, htmlCode = htmlCode, boxShadow = boxShadow )) } addMapkeyMarkers = function( map, lng = NULL, lat = NULL, layerId = NULL, group = NULL, icon = NULL, popup = NULL, popupOptions = NULL, label = NULL, labelOptions = NULL, options = leaflet::markerOptions(), clusterOptions = NULL, clusterId = NULL, data = leaflet::getMapData(map) ) { map$dependencies <- c(map$dependencies, mapkeyIconDependency()) if (!is.null(icon)) { icon = leaflet::evalFormula(list(icon), data)[[1]] if (inherits(icon, "leaflet_mapkey_icon_set")) { icon = mapkeyIconSetToMapkeyIcons(icon) } icon = leaflet::filterNULL(icon) } if (!is.null(clusterOptions)) map$dependencies = c(map$dependencies, leaflet::leafletDependencies$markerCluster()) pts = leaflet::derivePoints( data, lng, lat, missing(lng), missing(lat), "addMapkeyMarkers") leaflet::invokeMethod( map, data, "addMapkeyMarkers", pts$lat, pts$lng, icon, layerId, group, options, popup, popupOptions, clusterOptions, clusterId, leaflet::safeLabel(label, data), labelOptions ) %>% expandLimits(pts$lat, pts$lng) }
nosim <- 1000 cfunc <- function(x, n) 2 * sqrt(n) * (mean(x) - 0.5) dat <- data.frame( x = c(apply(matrix(sample(0:1, nosim * 10, replace = TRUE), nosim), 1, cfunc, 10), apply(matrix(sample(0:1, nosim * 20, replace = TRUE), nosim), 1, cfunc, 20), apply(matrix(sample(0:1, nosim * 30, replace = TRUE), nosim), 1, cfunc, 30) ), size = factor(rep(c(10, 20, 30), rep(nosim, 3)))) g <- ggplot(dat, aes(x = x, fill = size)) + geom_histogram(binwidth=.3, colour = "black", aes(y = ..density..)) g <- g + stat_function(fun = dnorm, size = 2) g <- g + facet_grid(. ~ size) print(g)
draw_key_borderpath <- function(data, params, size) { if (is.null(data$linetype)) { data$linetype <- 0 } else { data$linetype[is.na(data$linetype)] <- 0 } grobTree( segmentsGrob( 0.1, 0.5, 0.9, 0.5, arrow = params$arrow, gp = gpar( col = alpha(data$bordercolour %||% data$fill %||% "white", data$alpha), fill = alpha(params$arrow.fill %||% data$colour %||% data$fill %||% "white", data$alpha), lwd = (data$size %||% 0.5 + (data$bordersize %||% 0.5) * 2) * .pt, lty = data$linetype %||% 1, lineend = "butt" ) ), segmentsGrob( 0.1, 0.5, 0.9, 0.5, arrow = params$arrow, gp = gpar( col = alpha(data$colour %||% data$fill %||% "black", data$alpha), fill = alpha(params$arrow.fill %||% data$colour %||% data$fill %||% "black", data$alpha), lwd = (data$size %||% 0.5) * .pt, lty = data$linetype %||% 1, lineend = "butt" ) ) ) } geom_borderpath <- function(mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., lineend = "butt", linejoin = "round", linemitre = 10, arrow = NULL, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) { layer( data = data, mapping = mapping, stat = stat, geom = GeomBorderpath, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list( lineend = lineend, linejoin = linejoin, linemitre = linemitre, arrow = arrow, na.rm = na.rm, ... ) ) } GeomBorderpath <- ggproto("GeomBorderpath", GeomPath, default_aes = aes( colour = "black", size = 0.5, linetype = 1, alpha = NA, bordercolour = "white", bordersize = 0.2 ), draw_panel = function(data, panel_params, coord, arrow = NULL, lineend = "butt", linejoin = "round", linemitre = 10, na.rm = FALSE) { if (!anyDuplicated(data$group)) { message_wrap("geom_path: Each group consists of only one observation. ", "Do you need to adjust the group aesthetic?") } data <- data[order(data$group), , drop = FALSE] munched <- coord_munch(coord, data, panel_params) if (!all(is.na(munched$alpha) | munched$alpha == 1)) { warning( "Use of alpha with borderlines is discouraged - use with caution!", call. = FALSE ) } rows <- stats::ave(seq_len(nrow(munched)), munched$group, FUN = length) munched <- munched[rows >= 2, ] if (nrow(munched) < 2) return(zeroGrob()) attr <- ggplot2:::dapply(munched, "group", function(df) { linetype <- unique(df$linetype) ggplot2:::new_data_frame(list( solid = identical(linetype, 1) || identical(linetype, "solid"), constant = nrow(unique(df[, c("alpha", "colour","size", "linetype")])) == 1 ), n = 1) }) solid_lines <- all(attr$solid) constant <- all(attr$constant) if (!solid_lines && !constant) { abort("geom_path: If you are using dotted or dashed lines, colour, size and linetype must be constant over the line") } n <- nrow(munched) group_diff <- munched$group[-1] != munched$group[-n] start <- c(TRUE, group_diff) end <- c(group_diff, TRUE) if (!constant) { gList( segmentsGrob( munched$x[!end], munched$y[!end], munched$x[!start], munched$y[!start], default.units = "native", arrow = arrow, gp = gpar( col = alpha(munched$bordercolour, munched$alpha)[!end], fill = alpha(munched$bordercolour, munched$alpha)[!end], lwd = (munched$size[start] + munched$bordersize[start] * 2) * .pt, lty = "solid", lineend = lineend, linejoin = linejoin, linemitre = linemitre ) ), segmentsGrob( munched$x[!end], munched$y[!end], munched$x[!start], munched$y[!start], default.units = "native", arrow = arrow, gp = gpar( col = alpha(munched$bordercolour, munched$alpha)[!end], fill = alpha(munched$bordercolour, munched$alpha)[!end], lwd = munched$size[start] * .pt, lty = munched$linetype[!end], lineend = lineend, linejoin = linejoin, linemitre = linemitre ) ) ) } else { id <- match(munched$group, unique(munched$group)) out <- lapply(unique(munched$group), function(g) { m <- subset(munched, group == g) id <- match(m$group, g) list( polylineGrob( m$x, m$y, id = id, default.units = "native", arrow = arrow, gp = gpar( col = alpha(m$bordercolour, m$alpha)[start], fill = alpha(m$bordercolour, m$alpha)[start], lwd = (m$size[start] + m$bordersize[start] * 2) * .pt, lty = "solid", lineend = lineend, linejoin = linejoin, linemitre = linemitre ) ), polylineGrob( m$x, m$y, id = id, default.units = "native", arrow = arrow, gp = gpar( col = alpha(m$colour, m$alpha)[start], fill = alpha(m$colour, m$alpha)[start], lwd = m$size[start] * .pt, lty = m$linetype[start], lineend = lineend, linejoin = linejoin, linemitre = linemitre ) ) ) }) out <- unlist(out, recursive = FALSE) do.call(gList, out) } }, draw_key = draw_key_borderpath ) geom_borderline <- function(mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., lineend = "butt", linejoin = "round", linemitre = 10, arrow = NULL, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE) { layer( data = data, mapping = mapping, stat = stat, geom = GeomBorderline, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list( lineend = lineend, linejoin = linejoin, linemitre = linemitre, arrow = arrow, na.rm = na.rm, ... ) ) } GeomBorderline <- ggproto("GeomBorderline", GeomBorderpath, setup_params = function(data, params) { params$flipped_aes <- has_flipped_aes(data, params, ambiguous = TRUE) params }, extra_params = c("na.rm", "orientation"), setup_data = function(data, params) { data$flipped_aes <- params$flipped_aes data <- flip_data(data, params$flipped_aes) data <- data[order(data$PANEL, data$group, data$x), ] flip_data(data, params$flipped_aes) } ) geom_borderstep <- function(mapping = NULL, data = NULL, stat = "identity", position = "identity", direction = "hv", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, ...) { layer( data = data, mapping = mapping, stat = stat, geom = GeomBorderstep, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = list( direction = direction, na.rm = na.rm, ... ) ) } GeomBorderstep <- ggproto("GeomBorderstep", GeomBorderpath, draw_panel = function(data, panel_params, coord, direction = "hv") { data <- ggplot2:::dapply(data, "group", ggplot2:::stairstep, direction = direction) GeomBorderpath$draw_panel(data, panel_params, coord) } ) scale_bordercolour_continuous <- function(..., aesthetics = "bordercolour") { out <- scale_colour_continuous(...) out$aesthetics <- aesthetics out } scale_bordercolour_discrete <- function(..., aesthetics = "bordercolour") { out <- scale_colour_discrete(...) out$aesthetics = aesthetics out } scale_bordersize_continuous <- function(..., aesthetics = "bordersize") { out <- scale_size_continuous(...) out$aesthetics <- aesthetics out } scale_bordersize_discrete <- function(..., aesthetics = "bordersize") { out <- scale_size_discrete(...) out$aesthetics <- aesthetics out }
clusterSamples <- function(object, k, factors = "all",...) { if (!is(object, "MOFAmodel")) stop("'object' has to be an instance of MOFAmodel") if (paste0(factors,collapse="") == "all") { factors <- factorNames(object) } else if(is.numeric(factors)) { factors <- factorNames(object)[factors] } else{ stopifnot(all(factors %in% factorNames(object))) } Z <- getFactors(object, factors=factors) N <- getDimensions(object)[["N"]] haveAllZ <- apply(Z,1, function(x) all(!is.na(x))) if(!all(haveAllZ)) warning(paste("Removing", sum(!haveAllZ), "samples with missing values on at least one factor")) Z_sub <- Z[haveAllZ,] kmeans.out <- kmeans(Z_sub, centers=k, ...) clusters <- rep(NA, length(sampleNames(object))) names(clusters) <- sampleNames(object) clusters[haveAllZ] <- kmeans.out$cluster return(clusters) }
library(micompr) context("assumptions") test_that("assumptions_manova constructs the expected objects", { if (!requireNamespace("MVN", quietly = TRUE) || !requireNamespace("biotools", quietly = TRUE) ) { expect_message(assumptions_manova(iris[, 1:4], iris[, 5]), "MANOVA assumptions require 'MVN' and 'biotools' packages.") expect_null(assumptions_manova(iris[, 1:4], iris[, 5])) } else { amnv <- assumptions_manova(iris[, 1:4], iris[, 5]) expect_is(amnv, "assumptions_manova") for (rt in amnv$mvntest) { expect_is(rt, "data.frame") } expect_is(amnv$vartest, "boxM") } }) test_that("assumptions_manova throws the expected warnings", { bogus_data <- matrix(rnorm(100), ncol = 10) factors <- c(rep("A", 3), rep("B", 3), rep("C", 4)) if (!requireNamespace("MVN", quietly = TRUE) || !requireNamespace("biotools", quietly = TRUE) ) { expect_message(assumptions_manova(bogus_data, factors), "MANOVA assumptions require 'MVN' and 'biotools' packages.") expect_null(assumptions_manova(bogus_data, factors)) } else { expect_warning(assumptions_manova(bogus_data, factors), "Royston test requires at least 4 observations", fixed = TRUE) expect_warning(assumptions_manova(bogus_data, factors), "Royston test requires more observations than (dependent)", fixed = TRUE) } }) test_that("assumptions_paruv constructs the expected objects", { auv <- assumptions_paruv(iris[, 1:4], iris[, 5]) expect_is(auv, "assumptions_paruv") for (dv in auv$uvntest) { for (swt in dv) { expect_is(swt, "htest") expect_output(print(swt), "Shapiro-Wilk normality test", fixed = TRUE) } } for (bt in auv$vartest) { expect_is(bt, "htest") expect_output(print(bt), "Bartlett test of homogeneity of variances", fixed = TRUE) } })
model.tables.lmm <- function(x, ...){ confint(x, ..., columns = c("estimate","se","df","lower","upper","p.value")) }
prodStack <- function(x, stack = "eco2mix", areas = NULL, mcYear = "average", dateRange = NULL, yMin = NULL, yMax = NULL, customTicks=NULL, main = .getLabelLanguage("Production stack", language), unit = c("MWh", "GWh", "TWh"), compare = NULL, compareOpts = list(), interactive = getInteractivity(), legend = TRUE, legendId = sample(1e9, 1), groupId = legendId, updateLegendOnMouseOver = TRUE, legendItemsPerRow = 5, width = NULL, height = NULL, xyCompare = c("union", "intersect"), h5requestFiltering = list(), stepPlot = FALSE, drawPoints = FALSE, timeSteph5 = "hourly", mcYearh5 = NULL, tablesh5 = c("areas", "links"), language = "en", hidden = NULL, refStudy = NULL, ...) { prodStackValHidden <- c("H5request", "timeSteph5", "tables", "mcYearH5", "mcYear", "main", "dateRange", "stack", "unit", "areas", "legend", "stepPlot", "drawPoints") prodStackValCompare <- c("mcYear", "main", "unit", "areas", "legend", "stack", "stepPlot", "drawPoints") listParamsCheck <- list( x = x, compare = compare, interactive = interactive, language = language, hidden = hidden, valHidden = prodStackValHidden, valCompare = prodStackValCompare, mcYear = mcYear, h5requestFiltering = h5requestFiltering, compareOptions = compareOpts ) listParamsCheck <- .check_params_A_get_cor_val(listParamsCheck) x <- listParamsCheck$x compare <- listParamsCheck$compare compareOptions <- listParamsCheck$compareOptions h5requestFiltering <- listParamsCheck$h5requestFiltering mcYear <- listParamsCheck$mcYear xyCompare <- match.arg(xyCompare) unit <- match.arg(unit) init_areas <- areas init_dateRange <- dateRange processFun <- function(x) { .check_x_antaresData(x) if (is(x, "antaresDataTable")) { if (!attr(x, "type") %in% c("areas", "districts")) stop("'x' should contain area or district data") } else if (is(x, "antaresDataList")) { if (is.null(x$areas) & is.null(x$districts)) stop("'x' should contain area or district data") if (!is.null(x$areas)) x <- x$areas else x <- x$districts } if (is.null(x$area)) x$area <- x$district timeStep <- attr(x, "timeStep") opts <- simOptions(x) if (is.null(init_areas)) { init_areas <- unique(x$area)[1] } displayMcYear <- !attr(x, "synthesis") && length(unique(x$mcYear)) > 1 dataDateRange <- as.Date(.timeIdToDate(range(x$timeId), timeStep, opts)) if (length(init_dateRange) < 2) init_dateRange <- dataDateRange plotWithLegend <- function(id, areas, main = "", unit, stack, dateRange, mcYear, legend, stepPlot, drawPoints, updateLegendOnMouseOver, yMin, yMax, customTicks) { if (length(areas) == 0) return (combineWidgets(.getLabelLanguage("Please choose an area", language))) stackOpts <- .aliasToStackOptions(stack) dt <- x[area %in% areas] if (length(mcYear) == 0){ mcYear <- "average" } if (mcYear == "average") dt <- synthesize(dt) else if ("mcYear" %in% names(dt)) { mcy <- mcYear dt <- dt[mcYear == mcy] }else{ .printWarningMcYear() } if ("annual" %in% attr(dt, "timeStep")){ dateRange <- NULL } if (!is.null(dateRange)) { dt <- dt[as.Date(.timeIdToDate(dt$timeId, timeStep, opts = opts)) %between% dateRange] } if (nrow(dt) == 0){ return (combineWidgets(.getLabelLanguage("No data for this selection", language))) } if (!is.null(stackOpts$variables)) { names(stackOpts$variables) <- sapply(names(stackOpts$variables), function(x){ .getColumnsLanguage(x, language) }) } if (!is.null(stackOpts$lines)) { names(stackOpts$lines) <- sapply(names(stackOpts$lines), function(x){ .getColumnsLanguage(x, language) }) } p <- try(.plotProdStack(dt, stackOpts$variables, stackOpts$colors, stackOpts$lines, stackOpts$lineColors, stackOpts$lineWidth, main = main, unit = unit, legendId = legendId + id - 1, groupId = groupId, updateLegendOnMouseOver = updateLegendOnMouseOver, dateRange = dateRange, yMin = yMin, yMax = yMax, customTicks=customTicks, stepPlot = stepPlot, drawPoints = drawPoints, language = language), silent = TRUE) if ("try-error" %in% class(p)){ return ( combineWidgets(paste0(.getLabelLanguage("Can't visualize stack", language), " '", stack, "'<br>", p[1])) ) } if (legend & !"ramcharts_base" %in% class(p)) { l <- prodStackLegend(stack, legendItemsPerRow, legendId = legendId + id - 1, language = language) } else { l <- NULL } combineWidgets(p, footer = l, width = width, height = height) } list( plotWithLegend = plotWithLegend, x = x, timeStep = timeStep, opts = opts, areas = init_areas, displayMcYear = displayMcYear, dataDateRange = dataDateRange, dateRange = init_dateRange ) } if (!interactive) { listParamH5NoInt <- list( timeSteph5 = timeSteph5, mcYearh5 = mcYearh5, tablesh5 = tablesh5, h5requestFiltering = h5requestFiltering ) params <- .getParamsNoInt(x = x, refStudy = refStudy, listParamH5NoInt = listParamH5NoInt, compare = compare, compareOptions = compareOptions, processFun = processFun) L_w <- lapply(seq_along(params$x), function(i){ myData <- params$x[[i]] myData$plotWithLegend(i, areas, main, unit, stack, params$x[[1]]$dateRange, mcYear, legend, stepPlot, drawPoints, updateLegendOnMouseOver, yMin, yMax, customTicks) }) return(combineWidgets(list = L_w)) } else { } table <- NULL mcYearH5 <- NULL paramsH5 <- NULL sharerequest <- NULL timeStepdataload <- NULL timeSteph5 <- NULL x_in <- NULL x_tranform <- NULL meanYearH5 <- NULL manipulateWidget( { .tryCloseH5() if(!is.null(params)){ ind <- .id %% length(params$x) if(ind == 0) ind <- length(params$x) widget <- params$x[[ind]]$plotWithLegend(.id, areas, main, unit, stack, dateRange, mcYear, legend, stepPlot, drawPoints, updateLegendOnMouseOver, yMin, yMax, customTicks) controlWidgetSize(widget, language) } else { return (combineWidgets(.getLabelLanguage("No data for this selection", language))) } }, x = mwSharedValue({x}), x_in = mwSharedValue({ .giveListFormat(x) }), h5requestFiltering = mwSharedValue({ h5requestFiltering }), paramsH5 = mwSharedValue({ tmp <- .h5ParamList(X_I = x_in, xyCompare = xyCompare, h5requestFilter = h5requestFiltering) tmp }), H5request = mwGroup( label = .getLabelLanguage("H5request", language), timeSteph5 = mwSelect( { if (length(paramsH5) > 0){ choices = paramsH5$timeStepS names(choices) <- sapply(choices, function(x) .getLabelLanguage(x, language)) choices } else { NULL } }, value = if (.initial) {paramsH5$timeStepS[1]}else{NULL}, label = .getLabelLanguage("timeStep", language), multiple = FALSE, .display = !"timeSteph5" %in% hidden ), tables = mwSelect( { if (length(paramsH5) > 0){ choices = paramsH5[["tabl"]][paramsH5[["tabl"]] %in% c("areas", "districts")] names(choices) <- sapply(choices, function(x) .getLabelLanguage(x, language)) choices } else { NULL } }, value = { if (.initial) {paramsH5[["tabl"]][paramsH5[["tabl"]] %in% c("areas", "districts")][1]}else{NULL} }, label = .getLabelLanguage("table", language), multiple = FALSE, .display = !"tables" %in% hidden ), mcYearH5 = mwSelectize( choices = { ch <- c("Average" = "", paramsH5[["mcYearS"]]) names(ch)[1] <- .getLabelLanguage("Average", language) ch }, value = { if (.initial){paramsH5[["mcYearS"]][1]}else{NULL} }, label = .getLabelLanguage("mcYears to be imported", language), multiple = TRUE, options = list(maxItems = 4), .display = (!"mcYearH5" %in% hidden & !meanYearH5) ), meanYearH5 = mwCheckbox(value = FALSE, label = .getLabelLanguage("Average mcYear", language), .display = !"meanYearH5" %in% hidden), .display = { any(unlist(lapply(x_in, .isSimOpts))) & !"H5request" %in% hidden } ), sharerequest = mwSharedValue({ tmp_tables <- tables if(is.null(tmp_tables) | (!is.null(tmp_tables) && is.function(tmp_tables))){ tmp_tables <- paramsH5[["tabl"]][paramsH5[["tabl"]] %in% c("areas", "districts")][1] } tmp_timeSteph5 <- timeSteph5 if(is.null(tmp_timeSteph5)){ tmp_timeSteph5 <- paramsH5$timeStepS[1] } if (length(meanYearH5) > 0){ if (meanYearH5){ list(timeSteph5_l = tmp_timeSteph5, mcYearh_l = NULL, tables_l = tmp_tables) } else { list(timeSteph5_l = tmp_timeSteph5, mcYearh_l = mcYearH5, tables_l = tmp_tables) } } else { list(timeSteph5_l = tmp_timeSteph5, mcYearh_l = mcYearH5, tables_l = tmp_tables) } }), x_tranform = mwSharedValue({ h5requestFilteringTp <- paramsH5$h5requestFilter if (!is.null(sharerequest)) { for (i in 1:length(h5requestFilteringTp)) { if (sharerequest$tables == "areas"){ h5requestFilteringTp[[i]]$districts = NULL } if (sharerequest$tables == "districts"){ h5requestFilteringTp[[i]]$areas = NULL } } } resXT <- .get_x_transform(x_in = x_in, sharerequest = sharerequest, refStudy = refStudy, h5requestFilter = h5requestFilteringTp ) resXT }), params = mwSharedValue({ .getDataForComp(x_tranform, NULL, compare, compareOpts = compareOptions, processFun = processFun) }), mcYear = mwSelect({ allMcY <- .compareOperation(lapply(params$x, function(vv){ unique(vv$x$mcYear) }), xyCompare) allMcY=c("average",allMcY) names(allMcY) <- allMcY if (is.null(allMcY)){ allMcY <- "average" names(allMcY) <- .getLabelLanguage("average", language) } allMcY }, value = { if (.initial) mcYear else NULL }, label = .getLabelLanguage("mcYear to be displayed", language), .display = !"mcYear" %in% hidden), main = mwText(main, label = .getLabelLanguage("title", language), .display = !"main" %in% hidden), dateRange = mwDateRange(value = { if (.initial){ res <- NULL if (!is.null(params)){ res <- c(.dateRangeJoin(params = params, xyCompare = xyCompare, "min", tabl = table), .dateRangeJoin(params = params, xyCompare = xyCompare, "max", tabl = table)) if (params$x[[1]]$timeStep == "hourly"){ if (params$x[[1]]$dateRange[2] - params$x[[1]]$dateRange[1] > 7){ res[1] <- params$x[[1]]$dateRange[2] - 7 } } } res }else{NULL} }, min = { if (!is.null(params)){ if (params$x[[1]]$timeStep != "annual"){ .dateRangeJoin(params = params, xyCompare = xyCompare, "min", tabl = table) } else { NULL } } }, max = { if (!is.null(params)){ if (params$x[[1]]$timeStep != "annual"){ .dateRangeJoin(params = params, xyCompare = xyCompare, "max", tabl = table) } else { NULL } } }, language = eval(parse(text = "language")), separator = " : ", label = .getLabelLanguage("dateRange", language), .display = timeStepdataload != "annual" & !"dateRange" %in% hidden ), stack = mwSelect(names(pkgEnv$prodStackAliases), stack, label = .getLabelLanguage("stack", language), .display = !"stack" %in% hidden), unit = mwSelect(c("MWh", "GWh", "TWh"), unit, label = .getLabelLanguage("unit", language), .display = !"unit" %in% hidden), areas = mwSelect({ as.character(.compareOperation(lapply(params$x, function(vv){ unique(vv$x$area) }), xyCompare)) }, value = { if (.initial){ if (!is.null(areas)){ areas } else { as.character(.compareOperation(lapply(params$x, function(vv){ unique(vv$x$area) }), xyCompare))[1] } } else NULL }, multiple = TRUE, label = .getLabelLanguage("areas", language), .display = !"areas" %in% hidden ), yMin= mwNumeric(value=yMin,label="yMin", .display = !"yMin" %in% hidden), yMax= mwNumeric(value=yMax,label="yMax", .display = !"yMax" %in% hidden), timeStepdataload = mwSharedValue({ attributes(x_tranform[[1]])$timeStep }), legend = mwCheckbox(legend, label = .getLabelLanguage("legend", language), .display = !"legend" %in% hidden), stepPlot = mwCheckbox(stepPlot, label = .getLabelLanguage("stepPlot", language), .display = !"stepPlot" %in% hidden), drawPoints = mwCheckbox(drawPoints, label =.getLabelLanguage("drawPoints", language), .display = !"drawPoints" %in% hidden), updateLegendOnMouseOver = mwCheckbox(updateLegendOnMouseOver, label =.getLabelLanguage("updateLegendOnMouseOver", language), .display = !"updateLegendOnMouseOver" %in% hidden), .compare = { compare }, .compareOpts = { compareOptions }, ... ) } .aliasToStackOptions <- function(variables) { if (! variables %in% names(pkgEnv$prodStackAliases)) { stop("Unknown alias '", variables, "'.") } pkgEnv$prodStackAliases[[variables]] } .plotProdStack <- function(x, variables, colors, lines, lineColors, lineWidth, main = NULL, unit = "MWh", legendId = "", groupId = legendId, updateLegendOnMouseOver = TRUE, width = NULL, height = NULL, dateRange = NULL, yMin=NULL, yMax=NULL, customTicks = NULL, stepPlot = FALSE, drawPoints = FALSE, language = "en", type = "Production") { timeStep <- attr(x, "timeStep") formulas <- append(variables, lines) variables <- names(variables) lines <- names(lines) dt <- data.table(timeId = x$timeId) for (n in names(formulas)) { dt[, c(n) := x[, eval(formulas[[n]]) / switch(unit, MWh = 1, GWh = 1e3, TWh = 1e6)]] } p <- .plotStack(dt, timeStep, simOptions(x), colors, lines, lineColors, lineWidth, legendId, groupId, updateLegendOnMouseOver = updateLegendOnMouseOver, main = main, ylab = sprintf("Production (%s)", unit), width = width, height = height, dateRange = dateRange, yMin = yMin, yMax = yMax, customTicks= customTicks, stepPlot = stepPlot, drawPoints = drawPoints, language = language, type = type) p } prodStackLegend <- function(stack = "eco2mix", legendItemsPerRow = 5, legendId = "", language = "en") { stackOpts <- .aliasToStackOptions(stack) if (!is.null(stackOpts$variables)) { names(stackOpts$variables) <- sapply(names(stackOpts$variables), function(x){ .getColumnsLanguage(x, language) }) } if (!is.null(stackOpts$lines)) { names(stackOpts$lines) <- sapply(names(stackOpts$lines), function(x){ .getColumnsLanguage(x, language) }) } tsLegend( labels = c(names(stackOpts$variables), names(stackOpts$lines)), colors = c(stackOpts$colors, stackOpts$lineColors), types = c(rep("area", length(stackOpts$variables)), rep("line", length(stackOpts$lines))), legendItemsPerRow = legendItemsPerRow, legendId = legendId ) }
test.gdi33 <- function() { dataPath <- file.path(path.package(package="clusterCrit"),"unitTests","data","testsInternal_400_4.Rdata") load(file=dataPath, envir=.GlobalEnv) idx <- intCriteria(traj_400_4, part_400_4[[4]], c("GDI33")) cat(paste("\nFound idx =",idx)) val <- 3.97505916293356 cat(paste("\nShould be =",val,"\n")) checkEqualsNumeric(idx[[1]],val) }
xPosition = function (a, scale = 1) { x <- a$cut.points[,1] - a$cut.points[1,1] pos <- x[a$what == 2] list("RingWidth" = x[length(x)] * scale, "x" = (pos[-c(1,length(pos))] - a$LD / 2) * scale) }
test_that("request_retry() logic works as advertised", { faux_response <- function(status_code = 200, h = NULL) { structure( list(status_code = status_code, headers = if (!is.null(h)) httr::insensitive(h)), class = "response" ) } faux_request_make <- function(responses = list(faux_response())) { i <- 0 force(responses) function(...) { i <<- i + 1 responses[[i]] } } fix_wait_time <- function(x) { sub( "(?<=in )[[:digit:]]+([.][[:digit:]]+)?(?= seconds)", "{WAIT_TIME}", x, perl = TRUE ) } fix_strategy <- function(x) { sub( ", clipped to (floor|ceiling) of [[:digit:]]+([.][[:digit:]]+)? seconds", "", x, perl = TRUE ) } local_gargle_verbosity("debug") out <- with_mock( request_make = faux_request_make(), { request_retry() } ) expect_equal(httr::status_code(out), 200) r <- list(faux_response(429), faux_response()) with_mock( request_make = faux_request_make(r), gargle_error_message = function(...) "oops", { msg_fail_once <- capture.output( out <- request_retry(max_total_wait_time_in_seconds = 5), type = "message" ) } ) expect_snapshot( writeLines(fix_strategy(fix_wait_time(msg_fail_once))) ) expect_equal(httr::status_code(out), 200) r <- list( faux_response(429, h = list(`Retry-After` = 1.4)), faux_response() ) with_mock( request_make = faux_request_make(r), gargle_error_message = function(...) "oops", { msg_retry_after <- capture.output( out <- request_retry(), type = "message" ) } ) expect_snapshot( writeLines(fix_strategy(fix_wait_time(msg_retry_after))) ) expect_equal(httr::status_code(out), 200) r <- list( faux_response(429), faux_response(429), faux_response(429), faux_response() ) with_mock( request_make = faux_request_make(r[1:3]), gargle_error_message = function(...) "oops", { msg_max_tries <- capture.output( out <- request_retry(max_tries_total = 3, max_total_wait_time_in_seconds = 6), type = "message" ) } ) expect_snapshot( writeLines(fix_strategy(fix_wait_time(msg_max_tries))) ) expect_equal(httr::status_code(out), 429) }) test_that("backoff() obeys obvious bounds from min_wait and max_wait", { faux_error <- function() { structure(list(status_code = 429), class = "response") } with_mock( gargle_error_message = function(...) "oops", { wait_times <- vapply( rep.int(1, 100), backoff, FUN.VALUE = numeric(1), resp = faux_error(), min_wait = 3 ) } ) %>% suppressMessages() expect_true(all(wait_times > 3)) expect_true(all(wait_times < 4)) with_mock( gargle_error_message = function(...) "oops", { wait_times <- vapply( rep.int(1, 100), backoff, FUN.VALUE = numeric(1), resp = faux_error(), base = 6, max_wait = 3 ) } ) %>% suppressMessages() expect_true(all(wait_times > 1)) expect_true(all(wait_times < 3 + 1)) }) test_that("backoff() honors Retry-After header", { faux_429 <- function(h) { structure( list(status_code = 429, headers = httr::insensitive(h)), class = "response" ) } out <- with_mock( gargle_error_message = function(...) "oops", { backoff(1, faux_429(list(`Retry-After` = "1.2"))) } ) %>% suppressMessages() expect_equal(out, 1.2) out <- with_mock( gargle_error_message = function(...) "oops", { backoff(1, faux_429(list(`retry-after` = 2.4))) } ) %>% suppressMessages() expect_equal(out, 2.4) out <- with_mock( gargle_error_message = function(...) "oops", { backoff(3, faux_429(list(`reTry-aFteR` = 3.6))) } ) %>% suppressMessages() expect_equal(out, 3.6) })
var <- function(x, ...) UseMethod("var") var.default <- function(x, y = NULL, na.rm = FALSE, use, ...) stats::var(x=x, y=y, na.rm=na.rm, use=use) var.data.frame <- function(x, ...) { sapply(x, var, ...) } var.circular <- function (x, na.rm=FALSE, ...) { if (is.matrix(x)) { apply(x, 2, var.circular, na.rm=na.rm) } else { if (na.rm) x <- x[!is.na(x)] x <- conversion.circular(x, units="radians", zero=0, rotation="counter") attr(x, "class") <- attr(x, "circularp") <- NULL VarCircularRad(x=x) } } VarCircularRad <- function(x) { rbar <- RhoCircularRad(x) circvar <- 1-rbar return(circvar) }
get_incidence_from_adjacency <- function(A) { p <- nrow(A) m <- .5 * sum(A > 0) E <- matrix(0, p, m) k <- 1 for (i in c(1:(p-1))) { for (j in c((i+1):p)) { if (A[i, j] > 0) { E[i, k] <- 1 E[j, k] <- -1 k <- k + 1 } } } return(E) } learn_laplacian_gle_mm <- function(S, A_mask = NULL, alpha = 0, maxiter = 10000, reltol = 1e-5, record_objective = FALSE, verbose = TRUE) { p <- nrow(S) Sinv <- MASS::ginv(S) if (is.null(A_mask)) A_mask <- matrix(1, p, p) - diag(p) mask <- Ainv(A_mask) > 0 w <- w_init("naive", Sinv)[mask] wk <- w m <- sum(mask) J <- matrix(1, p, p) / p H <- 2 * diag(p) - p * J K <- S + alpha * H E <- get_incidence_from_adjacency(A_mask) R <- t(E) %*% K %*% E r <- nrow(R) G <- cbind(E, rep(1, p)) if (record_objective) { z <- rep(0, .5 * p * (p - 1)) z[mask] <- wk fun <- vanilla.objective(L(z), K) } if (verbose) pb <- progress::progress_bar$new(format = "<:bar> :current/:total eta: :eta", total = maxiter, clear = FALSE, width = 80) for (k in c(1:maxiter)) { w_aug <- c(wk, 1 / p) G_aug_t <- t(G) * w_aug G_aug <- t(G_aug_t) Q <- G_aug_t %*% solve(G_aug %*% t(G), G_aug) Q <- Q[1:m, 1:m] wk <- sqrt(diag(Q) / diag(R)) if (record_objective) { z <- rep(0, .5 * p * (p - 1)) z[mask] <- wk fun <- c(fun, vanilla.objective(L(z), K)) } if (verbose) pb$tick() has_converged <- norm(w - wk, "2") / norm(w, "2") < reltol if (has_converged && k > 1) break w <- wk } z <- rep(0, .5 * p * (p - 1)) z[mask] <- wk results <- list(Laplacian = L(z), Adjacency = A(z), maxiter = k, convergence = has_converged) if (record_objective) results$obj_fun <- fun return(results) } obj_func <- function(E, K, w, J) { p <- ncol(J) EWEt <- E %*% diag(w) %*% t(E) Gamma <- EWEt + J lambda <- eigval_sym(Gamma)[2:p] return(sum(diag(E %*% diag(w) %*% t(E) %*% K)) - sum(log(lambda))) } learn_laplacian_gle_admm <- function(S, A_mask = NULL, alpha = 0, rho = 1, maxiter = 10000, reltol = 1e-5, record_objective = FALSE, verbose = TRUE) { p <- nrow(S) if (is.null(A_mask)) A_mask <- matrix(1, p, p) - diag(p) Sinv <- MASS::ginv(S) w <- w_init("naive", Sinv) Theta <- L(w) Yk <- Theta Ck <- Theta C <- Theta mu <- 2 tau <- 2 J <- matrix(1, p, p) / p H <- 2 * diag(p) - p * J K <- S + alpha * H if (verbose) pb <- progress::progress_bar$new(format = "<:bar> :current/:total eta: :eta", total = maxiter, clear = FALSE, width = 80) if (record_objective) fun <- c(vanilla.objective(Theta, K)) P <- qr.Q(qr(rep(1, p)), complete=TRUE)[, 2:p] for (k in c(1:maxiter)) { Gamma <- t(P) %*% ((K + Yk) / rho - Ck) %*% P U <- eigvec_sym(Gamma) lambda <- eigval_sym(Gamma) d <- .5 * c(sqrt(lambda ^ 2 + 4 / rho) - lambda) Xik <- crossprod(sqrt(d) * t(U)) Thetak <- P %*% Xik %*% t(P) Ck_tmp <- Yk / rho + Thetak Ck <- (diag(pmax(0, diag(Ck_tmp))) + A_mask * pmin(0, Ck_tmp)) Rk <- Thetak - Ck Yk <- Yk + rho * Rk if (record_objective) fun <- c(fun, vanilla.objective(Thetak, K)) has_converged <- norm(Theta - Thetak) / norm(Theta, "F") < reltol if (has_converged && k > 1) break s <- rho * norm(C - Ck, "F") r <- norm(Rk, "F") if (r > mu * s) rho <- rho * tau else if (s > mu * r) rho <- rho / tau Theta <- Thetak C <- Ck if (verbose) pb$tick() } results <- list(Laplacian = Thetak, Adjacency = diag(diag(Thetak)) - Thetak, convergence = has_converged) if (record_objective) results$obj_fun <- fun return(results) } aug_lag <- function(K, P, Xi, Y, C, d, rho) { PXiPt <- P %*% Xi %*% t(P) return(sum(diag(Xi %*% t(P) %*% K %*% P)) - sum(log(d)) + sum(diag(t(Y) %*% (PXiPt - C))) + .5 * rho * norm(PXiPt - C, "F") ^ 2) }
my_reg_data <- data.frame ( geo = c( "BE1", "HU102", "FR1", "FRB", "DED", "FR7", "TR", "DED2", "EL", "XK", "GB" ), values = runif(11) ) validate_nuts_regions (dat = my_reg_data) result1 <- validate_nuts_regions ( dat = data.frame (geo = c("BE1", "HU102")), nuts_year = 2003) test_that("correct typology is returned", { expect_equal(result1$typology, c("nuts_level_1", NA_character_)) }) test_that("invalid dates give error message", { expect_error(validate_nuts_regions ( dat = data.frame (geo = c("BE1", "HU102")), nuts_year = 2002)) expect_error (validate_nuts_regions (dat = "c", nut_year = 2013)) expect_error (validate_nuts_regions (dat = data.frame ( geo = c("HU102", "CZ1"), values = c(1, 2) ), geo_var = "country")) }) with_nuts_df <- data.frame ( nuts = c("DE1", "DE7", "HU1", "BE1"), values = c(1:4), typology = rep("nuts1", 4) ) tested_with_nuts <- validate_nuts_regions(dat = with_nuts_df, geo_var = "nuts") test_that("Special column names do not cause confusion", { expect_equal(all(tested_with_nuts$valid_2016), TRUE) expect_equal(ncol(tested_with_nuts), 5) })
setMethod(f="fitted", signature=c(object="bild"), function (object) { fit.i<-object@Fitted names(fit.i) <- c(1:length(fit.i)) round(fit.i ,6) } )
NULL "qshift_b" "qshift_b_bp" "near_sym_b" "near_sym_b_bp"
estimate_cbsem <- function(data, measurement_model=NULL, structural_model=NULL, item_associations=NULL, model=NULL, lavaan_model=NULL, estimator="MLR", ...) { message("Generating the seminr model for CBSEM") if (is.null(lavaan_model)) { specified_model <- extract_models(model, measurement_model, structural_model, item_associations) measurement_model <- specified_model$measurement_model structural_model <- specified_model$structural_model item_associations <- specified_model$item_associations post_interaction_object <- process_cbsem_interactions(measurement_model, data, structural_model, item_associations, estimator, ...) names(post_interaction_object$data) <- sapply(names(post_interaction_object$data), FUN=lavaanify_name, USE.NAMES = FALSE) mmMatrix <- post_interaction_object$mmMatrix data <- post_interaction_object$data structural_model[, "source"] <- sapply(structural_model[, "source"], FUN=lavaanify_name) smMatrix <- structural_model measurement_syntax <- lavaan_mm_syntax(mmMatrix) structural_syntax <- lavaan_sm_syntax(smMatrix) association_syntax <- lavaan_item_associations(item_associations) lavaan_model <- paste(measurement_syntax, structural_syntax, association_syntax, sep="\n\n") } else { structural_model <- smMatrix <- lavaan2seminr(lavaan_model)$structural_model measurement_model <- lavaan2seminr(lavaan_model)$measurement_model post_interaction_object <- process_cbsem_interactions(measurement_model, data, structural_model, item_associations, estimator, ...) mmMatrix <- post_interaction_object$mmMatrix } lavaan_output <- try_or_stop( lavaan::sem( model=lavaan_model, data=data, std.lv = TRUE, estimator=estimator, ...), "estimating CBSEM using Lavaan" ) constructs <- all_construct_names(measurement_model) lavaan_std <- lavaan::lavInspect(lavaan_output, what="std") loadings <- lavaan_std$lambda class(loadings) <- "matrix" tenB <- estimate_lavaan_ten_berge(lavaan_output) estimates <- lavaan::standardizedSolution(lavaan_output) path_df <- estimates[estimates$op == "~",] all_antecedents <- all_exogenous(smMatrix) all_outcomes <- all_endogenous(smMatrix) path_matrix <- df_xtab_matrix(est.std ~ rhs + lhs, path_df, all_antecedents, all_outcomes) rownames(path_matrix) <- gsub("_x_", "*", all_antecedents) seminr_model <- list( data = data, measurement_model = measurement_model, factor_loadings = loadings, associations = item_associations, mmMatrix = mmMatrix, smMatrix = smMatrix, constructs = constructs, construct_scores = tenB$scores, item_weights = tenB$weights, path_coef = path_matrix, lavaan_model = lavaan_model, lavaan_output = lavaan_output ) class(seminr_model) <- c("cbsem_model", "seminr_model") return(seminr_model) } estimate_cfa <- function(data, measurement_model=NULL, item_associations=NULL, model=NULL, lavaan_model=NULL, estimator="MLR", ...) { message("Generating the seminr model for CFA") mmMatrix <- NULL if (is.null(lavaan_model)) { specified_model <- extract_models( model = model, measurement_model = measurement_model, item_associations = item_associations ) measurement_model <- specified_model$measurement_model item_associations <- specified_model$item_associations mmMatrix <- mm2matrix(measurement_model) measurement_syntax <- lavaan_mm_syntax(mmMatrix) association_syntax <- lavaan_item_associations(item_associations) lavaan_model <- paste(measurement_syntax, association_syntax, sep="\n\n") } lavaan_output <- try_or_stop( lavaan::cfa(model=lavaan_model, data=data, std.lv = TRUE, estimator=estimator, ...), "run CFA in Lavaan" ) tenB <- estimate_lavaan_ten_berge(lavaan_output) seminr_model <- list( data = data, measurement_model = measurement_model, construct_scores = tenB$scores, item_weights = tenB$weights, lavaan_model = lavaan_model, lavaan_output = lavaan_output ) class(seminr_model) <- c("cfa_model", "seminr_model") return(seminr_model) }
inner.hint.for.call.chain = function(stud.expr.li, cde, ps = get.ps(), ce=NULL, assign.str="",start.char="\n", end.char="\n", env=ps$stud.env, details.of.wrong..call = TRUE, compare.vals= !(isTRUE(ps$noeval) | isTRUE(ps$hint.noeval)), call=NULL,...) { restore.point("inner.hint.for.call.chain") op = cde$name chain.na = sapply(cde$arg, name.of.call) sde.li = lapply(stud.expr.li, function(se) describe.call(call.obj=se)) if (length(sde.li)>0) { is.chain = sapply(sde.li, function(sde) sde$type=="chain") sde.li = sde.li[is.chain] stud.expr.li = stud.expr.li[is.chain] } if (length(sde.li)==0) { chain.str = paste0(chain.na, " ...", collapse = paste0(" ",op,"\n ")) chain.str = paste0(assign.str, chain.str) txt = paste0("My solution consists of a pipe chain of the form:\n\n", chain.str,"\n\nI have not seen any pipe operator ", op," in your solution, yet.") display(txt) return(invisible()) } has.place.holders = sapply(sde.li, has.call.placeholder) if (any(has.place.holders)) { txt = paste0("Here is a scrambled solution:\n\n", scramble.call.chain(cde, assign.str)) display(txt) return(invisible()) } if (compare.vals) { check.res.li = eval.chain.steps(de=cde, envir=env) } else { check.res.li = NULL } has.error = FALSE compare.li = vector("list", length(sde.li)) for (i in seq_along(sde.li)) { res = try(compare.pipe.chains( check.chain = ce, cde=cde, stud.chain = stud.expr.li[[i]], sde = sde.li[[i]], envir = env, check.res.li = check.res.li ),silent = TRUE) if (is(res, "try-error")) { txt = paste0("I could not evaluate all your code without error. Here is a scrambled solution:\n\n", scramble.call.chain(cde, assign.str)) display(txt) return(invisible()) } compare.li[[i]] = res } if (length(compare.li)>1) { fail.steps = sapply(compare.li,function(comp) { comp$fail.step }) compare.li = compare.li[[which.max(fail.steps)]] } txt = compare.li[[1]]$descr display(txt) return(invisible()) } compare.pipe.chains = function(check.chain, stud.chain, cde=describe.call(check.chain), sde=describe.call(stud.chain), compare.vals = TRUE, envir=parent.frame(), check.res.li = if (compare.vals) eval.chain.steps(de=cde, envir=envir), eval.fun = eval ) { restore.point("compare.pipe.chains") check.names = sapply(cde$arg, name.of.call) stud.names = sapply(sde$arg, name.of.call) same.until = same.until.pos(check.names, stud.names) if (same.until==0) { return(list(same=FALSE, fail.step=1, same.until=0, descr=paste0("Please start your pipe chain with ", check.names[1], ", as in the sample solution."))) } j = 1 ccall = cde$arg[[j]] scall = sde$arg[[j]] if (compare.vals) { sres = eval.fun(scall, envir) ok = identical(sres, check.res.li[[j]]) } else { res = compare.calls(stud.call = scall,check.call = ccall,compare.vals = FALSE) ok = res$same } if (!ok) { return(get.chain.failure.results(j, sde, cde,compare.vals = compare.vals, same.until=same.until)) } while (j < same.until) { j = j+1 ccall = cde$arg[[j]] scall = sde$arg[[j]] if (compare.vals) { sres = eval.next.chain.call(sres, scall, envir) ok = identical(sres, check.res.li[[j]]) } else { res = compare.calls(stud.call = scall,check.call = ccall,compare.vals = FALSE) ok = res$same } if (!ok) { return(get.chain.failure.results(j, sde, cde,compare.vals = compare.vals, same.until=same.until)) } } if (same.until < length(cde$args)) { step = same.until+1 if (length(sde$args)>=step) { return(get.chain.failure.results(step, sde, cde,compare.vals = FALSE, same.until=same.until)) } else if (length(sde$args)<step) { return(list(same=FALSE, fail.step=step, same.until=same.until, descr=paste0("You have to add another element to your pipe chain in which you call the function ", check.names[step],"."))) } } else if (length(sde$args) > same.until) { return(list(same=FALSE, fail.step=step, same.until=same.until, descr=paste0("You have too many elements in your pipe chain. Please stop after step ", same.until,", i.e. after the call ", deparse1(sde$args[[same.until]])))) } return(list(same=TRUE, fail.step=Inf, same.until=same.until, descr=paste0("Great, you entered the correct pipe chain."))) } get.chain.failure.results = function(step=1, sde, cde, compare.vals=TRUE, same.until=NULL, call.comp.descr = NULL, pipe.op = "%>%") { restore.point("get.chain.failure.results") fail = step stud.na = name.of.call(sde$arg[[step]]) check.na = name.of.call(cde$arg[[step]]) child.sde = describe.call(call.obj = sde$arg[[step]]) is.fun = child.sde$type == "fun" if (is.fun) { txt = paste0("In your following pipe chain, I detect an error in the ", to_ordinal(step)," element:\n") } else { txt = paste0("In your following pipe chain, I detect an error in the ", to_ordinal(step)," element: ", deparse1(sde$arg[[step]]),":\n") } sna = sapply(sde$arg, deparse1) err.code = rep("", length(sna)) err.code[fail] = " !! WRONG !!" op.str = rep(pipe.op,NROW(sna)) op.str[length(op.str)] = "" scall.str = paste0(sna[1]," ",op.str[1],err.code[1],paste0("\n ", sna[-1]," ", op.str[-1],err.code[-1], collapse="")) txt = paste0(txt,"\n",scall.str) if (is.null(call.comp.descr)) { is.summarize = isTRUE(stud.na %in% c("summarize","summarise") & check.na %in% c("summarize","summarise")) if ( ((stud.na == check.na) | is.summarize) & is.fun) { comp.call = compare.call.args(stud.call = sde$args[[step]], check.call = cde$args[[step]],compare.vals = FALSE, from.pipe=TRUE) call.comp.descr = paste0("It is correct to call ", check.na,". But: ", paste0(comp.call$descr,collapse="\nAlso: ")) } else if (is.fun) { call.comp.descr = paste0("You call the function ", stud.na, " but the sample solution calls the function ", check.na,".") } else { call.comp.descr = paste0("The sample solution for the ", to_ordinal(step)," element is ", deparse1(cde$arg[[step]])) } } txt = paste0(txt, "\n\n", call.comp.descr) return(list( same=FALSE, fail.step = step, same.until = same.until, descr= txt )) if (wrong.call.na=="group_by") { display("\nNote: For group_by(...) RTutor requires the groups and their order to be equal to the sample solution. You must call ", deparse1(ccall[[1]][[fail]]),".") } } same.until.pos = function(x,y) { rows = seq_len(min(length(x), length(y))) if (length(rows)==0) return(0) same = which(x[rows] != y[rows])[1] if (is.na(same)) return(length(rows)) same-1 } example.eval.next.chain.call = function() { x = data.frame(x=1:10) call = quote(mutate(y=x^2)) eval.next.chain.call(x,call) } eval.chain.steps = function(chain=NULL, de=describe.call(chain), envir = parent.frame(), eval.fun = eval) { restore.point("eval.chain.steps") if (length(de$args)==0) return(NULL) res.li = vector("list", length(de$args)) res.li[[1]] = eval.fun(de$args[[1]], envir) for (j in setdiff(seq_along(res.li),1)) { res.li[[j]] = eval.next.chain.call(res.li[[j-1]], de$args[[j]],envir=envir, eval.fun = eval.fun, pipe.fun = de$name) } res.li } eval.next.chain.call = function(x, call, envir=parent.frame(), eval.fun = eval, pipe.fun = "%>%") { new.call = substitute(._._x %>% call, list(call=call)) restore.point("eval.next.chain.call") cenv = new.env(parent=envir) cenv$._._x = x eval.fun(new.call, cenv) } scramble.call.chain = function(cde, assign.str="") { parts = sapply(cde$args, function(call) { call.str = deparse1(call) scramble.text(call.str,"?",0.5, keep.char=c(" ","\n",">","%","(",")","=", "\t")) }) str = paste0(parts, collapse = " %>%\n\t") str = paste0(assign.str, str) str }
options(width=70) library(cubing) hello.cube <- getCubieCube() hello.cube aCube <- getCubieCube("Superflip") bCube <- getCubieCube("EasyCheckerboard") cCube <- getCubieCube("HenrysSnake") plot(aCube) plot(aCube) getOption("cubing.colors") mycol <- c("yellow", "dodgerblue", "red", "ghostwhite", "limegreen", "orange") options(cubing.colors = mycol) jcol <- c("ghostwhite", "red", "limegreen", "dodgerblue", "orange", "yellow") options(cubing.colors = jcol) acol <- c("black", "darkred", "darkgreen", "yellow", "orange", "purple") options(cubing.colors = acol) ocol <- c("ghostwhite", "red", "limegreen", "yellow", "orange", "dodgerblue") options(cubing.colors = ocol) rCube <- getMovesCube(randMoves(1, nm = 22)) plot(getCubieCube(), numbers = TRUE, blank = TRUE) plot(getCubieCube(), numbers = TRUE, blank = TRUE) aCube <- getCubieCube("Wire") bCube <- cubieCube("UUUUUUUUU RLLRRRLLR BBFFFFFBB DDDDDDDDD LRRLLLRRL FFBBBBBFF") cCube <- cubieCube("UUUUUUUU RLLRRLLR BBFFFFBB DDDDDDDD LRRLLRRL FFBBBBFF") aCube <- randCube() aCube as.stickerCube(aCube) sum(sapply(randCube(100, solvable = FALSE), is.solvable)) rCube <- randCube(1, solvable = FALSE) is.solvable(rCube, split = TRUE) tcon <- textConnection("D2 F2 U F2 D R2 D B L' B R U L R U L2 F L' U'" ) aCube <- getMovesCube(scan(tcon, what = character())) close(tcon) tcon <- textConnection("x2 // inspection D' R' L2' U' F U' F' D' U' U' R' // XXcross y' R' U' R // 3rd pair y' R U' R' U' R U R' // 4th pair U' R' U' F' U F R // OLL(CP) U' // AUF") mv <- scan(tcon, what = character(), comment.char = "/") close(tcon) result <- move(aCube, mv) is.solved(result) scramble(3, state = TRUE) res.seq <- move(aCube, mv, history = TRUE) rCubes <- rotations(randCube()) aCube <- getCubieCube("EasyCheckerboard") bCube <- move(aCube, "x2") all.equal(aCube, bCube) aCube == bCube identical(aCube, bCube) identical(aCube, getMovesCube("U2D2R2L2F2B2")) identical(aCube, invCube(aCube)) aCube <- getCubieCube("BlackMamba") solver(aCube, divide = TRUE) tCube <- getCubieCube("EasyCheckerboard") solver(aCube, tCube, collapse = "-") solver(randCube(), type = "ZT") solver(randCube(), type = "TF")
get.gk.simple<- function(X.vec,Y.scaler,Ti.int,lam,beta,tau1,tau0, FUNu, rho1, N, n1, ...){ lam<- as.vector(lam) be<- as.vector(beta) uk <- FUNu(as.numeric(X.vec)) gk1<- Ti.int*rho1(crossprod(lam, uk),...)*uk - uk gk2<- (1-Ti.int)*rho1(crossprod(be, uk),...)*uk - uk gk3<- Ti.int*rho1(crossprod(lam,uk),...)*Y.scaler- tau1 gk4<- (1-Ti.int)*rho1(crossprod(be, uk),...)*Y.scaler - tau0 gk<- c(gk1,gk2,gk3,gk4) gk } get.gk.ATT<- function(X.vec,Y.scaler,Ti.int,beta,tau1,tau0, FUNu, rho1,N,n1, ...){ be<- as.vector(beta) uk <- FUNu(as.numeric(X.vec)) frac<-n1/N gk1<- (1-Ti.int)*rho1(crossprod(be, uk),...)*uk - 1/frac*Ti.int*uk gk2<- N/n1*(Ti.int*(Y.scaler- tau1)) gk3<- (1-Ti.int)*rho1(crossprod(be, uk),...)*Y.scaler - tau0 gk4<- Ti.int-frac gk<- c(gk1,gk2,gk3,gk4) gk } get.gk.MT<- function(X.vec,Y.scaler,Ti.int,lam, FUNu, rho1, big.J, taus, ...){ lam<- as.vector(lam) uk <- FUNu(as.numeric(X.vec)) K<- length(lam) gk1<- rep(-uk,big.J) gk1[(Ti.int*K + 1):((Ti.int+1)*K)]<- rho1(crossprod(lam, uk),...)*uk + gk1[(Ti.int*K + 1):((Ti.int+1)*K)] gk2<- -taus gk2[Ti.int+1]<- gk2[Ti.int+ 1] + rho1(crossprod(lam, uk),...)*Y.scaler c(gk1,gk2) } get.cov.simple<- function(X, Y, Ti, FUNu, rho, rho1, rho2, obj,...){ N<- length(Y) n1<- sum(Ti) lam<- as.vector(obj$lam.p) be<- as.vector(obj$lam.q) tau1<- obj$Y1 tau0<- obj$Y0 umat <- t(apply(X, 1, FUNu)) K<- length(lam) A<- matrix(0,ncol = 2*K, nrow = 2*K) C<- matrix(0, ncol = 2*K, nrow = 2) meat<- matrix(0, ncol = 2*K+2, nrow = 2*K+2) for(i in 1:N){ A[(1:K),(1:K)]<- A[(1:K),(1:K)] + Ti[i]*rho2(crossprod(lam, umat[i,]), ...)*tcrossprod(umat[i,]) A[((K+1):(2*K)),((K+1):(2*K))]<- A[((K+1):(2*K)),((K+1):(2*K))] + (1-Ti[i])*rho2(crossprod(be, umat[i,]),...)*tcrossprod(umat[i,]) C[1,(1:K)]<- C[1,(1:K)] + Ti[i]*rho2(crossprod(lam, umat[i,]), ...)*Y[i]*umat[i,] C[2,((K+1):(2*K))]<- C[2,((K+1):(2*K))] + (1-Ti[i])*rho2(crossprod(be, umat[i,]), ...)*Y[i]*umat[i,] meat<- meat + tcrossprod(get.gk.simple(X[i,], Y[i],Ti[i], lam,be, tau1,tau0, FUNu, rho1, N, n1,...)) } A<- A/N C<- C/N meat<- meat/N bread<- matrix(0, nrow = 2*K+2, ncol = 2*K+2) bread[1:(2*K),1:(2*K)]<- A bread[2*K+1:2, ]<- cbind(C,diag(c(-1,-1))) bread<- solve(bread) (bread%*%meat%*%t(bread))/N } get.cov.ATT<- function(X, Y, Ti, FUNu, rho, rho1, rho2, obj,...){ N<- length(Y) n1<- sum(Ti) frac<-n1/N be<- as.vector(obj$lam.q) tau1<- obj$Y1 tau0<- obj$Y0 umat <- t(apply(X, 1, FUNu)) K<- length(be) A<- matrix(0,ncol = K, nrow = K) C<- matrix(0, ncol = K, nrow = 3) q<- numeric(K) meat<- matrix(0, ncol = K+3, nrow = K+3) for(i in 1:N){ A<- A + (1-Ti[i])*rho2(crossprod(be, umat[i,]), ...)*tcrossprod(umat[i,]) C[2,(1:K)]<- C[2,(1:K)] + (1-Ti[i])*rho2(crossprod(be, umat[i,]), ...)*Y[i]*umat[i,] q <- q+1/frac^2*Ti[i]*umat[i,] meat<- meat + tcrossprod(get.gk.ATT(X[i,], Y[i], Ti[i], be, tau1, tau0, FUNu, rho1, N, n1, ...)) } A<- A/N C<- C/N meat<- meat/N bread<- matrix(0, nrow = K+3, ncol = K+3) bread[1:K,1:K]<- A bread[K+1:3, ]<- cbind(C,diag(c(-1,-1,-1))) bread[1:K,K+3]<- q/N bread<- solve(bread) (bread%*%meat%*%t(bread))/N } get.cov.MT<- function(X, Y, Ti, FUNu, rho, rho1, rho2, obj,...){ N<- length(Y) lam.mat<- obj$lam.mat umat <- t(apply(X, 1, FUNu)) K<- ncol(lam.mat) J<- length(unique(Ti)) taus<- obj$Yj.hat A<- matrix(0,ncol = J*K, nrow = J*K) C<- matrix(0, ncol = J*K, nrow = J) meat<- matrix(0, ncol = J*K+J, nrow = J*K+J) for(i in 1:N){ for(j in 0:(J-1) ){ temp.Ti<- 1*(Ti[i]==j) A[ (j*K + 1):((j + 1)*K) , (j*K + 1):((j + 1)*K) ]<- A[ (j*K + 1):((j + 1)*K) , (j*K + 1):((j + 1)*K) ] + temp.Ti*rho2(crossprod(lam.mat[j+1,], umat[i,]), ...)*tcrossprod(umat[i,]) C[j+1,(j*K + 1):((j + 1)*K)]<- C[j+1,(j*K + 1):((j + 1)*K)]+ temp.Ti*rho2(crossprod(lam.mat[j+1,], umat[i,]), ...)*Y[i]*umat[i,] } meat<- meat + tcrossprod(get.gk.MT(X[i,], Y[i], Ti[i], lam.mat[Ti[i]+1,],FUNu, rho1, J, taus,...)) } A<- A/N C<- C/N meat<- meat/N bread1<- cbind(A, matrix(0, ncol = J, nrow = J*K)) bread2<- cbind(C, diag(rep(-1, J))) bread<- rbind(bread1,bread2) bread<- solve(bread) (bread%*%meat%*%t(bread))/N }
var.asdummy <- function (x) { x_length <- length(x) x_fac <- as.factor(x) lev <- levels(x_fac) x_count <- nlevels(x_fac) dummyvarnames <- list() dummyname <- 0 for (i in 1:x_count) { dummyname[i] <- paste (lev[i],"_DUMMY", sep="") dummyvarnames <- rbind(dummyvarnames, dummyname[i]) } dummydataset <- data.frame(matrix(0, nrow=x_length, ncol=x_count)) names(dummydataset) <- dummyvarnames for (i in 1:x_count) { positionstrue <- which(x_fac == lev[i]) dummydataset[positionstrue,i] <- 1 } return(dummydataset) }
context("sf: wkt") test_that("well-known text", { gcol <- st_geometrycollection(list(st_point(1:2), st_linestring(matrix(1:4,2)))) expect_message(x <- print(gcol), "GEOMETRYCOLLECTION \\(POINT \\(1 2\\), LINESTRING \\(1 3, 2 4\\)\\)", all = TRUE) expect_equal(x, "GEOMETRYCOLLECTION (POINT (1 2), LINESTRING (1 3, 2 4))") p1 = st_point(1:3) p2 = st_point(5:7) sfc = st_sfc(p1,p2) expect_identical(st_as_text(sfc), c("POINT Z (1 2 3)", "POINT Z (5 6 7)")) expect_equal(st_sfc(gcol), st_as_sfc(list("GEOMETRYCOLLECTION (POINT (1 2), LINESTRING (1 3, 2 4))"))) }) test_that("detect ewkt", { expect_equal(is_ewkt(c("LINESTRING(1663106 -105415,1664320 -104617)", "SRID=4326;POLYGON(1.0 -2.5,3.2 -5.70000)")), c(FALSE, TRUE)) }) test_that("can parse ewkt", { expect_equal(get_crs_ewkt("SRID=4326;POINT(1.0 -2.5,3.2 -5.7)"), 4326) expect_equal(ewkt_to_wkt("SRID=4326;POINT(1.0 -2.5, 3.2 -5.7)"), "POINT(1.0 -2.5, 3.2 -5.7)") expect_equal(ewkt_to_wkt("POINT(1.0 -2.5, 3.2 -5.7)"), "POINT(1.0 -2.5, 3.2 -5.7)") }) test_that("can read ewkt", { expect_equal(st_as_sfc("SRID=3879;LINESTRING(1663106 -105415,1664320 -104617)"), st_as_sfc("LINESTRING(1663106 -105415,1664320 -104617)", 3879)) expect_equal(st_as_sfc(c("SRID=3879;LINESTRING(1663106 -105415,1664320 -104617)", "SRID=3879;LINESTRING(0 0,1 1)")), st_as_sfc(c("LINESTRING(1663106 -105415,1664320 -104617)", "LINESTRING(0 0,1 1)"), 3879) ) expect_equal(st_crs(st_as_sfc(c("SRID=3879;LINESTRING(1663106 -105415,1664320 -104617)", "SRID=3879;LINESTRING(0 0,1 1)"))), st_crs(3879)) expect_error(st_as_sfc(c("SRID=3879;LINESTRING(1663106 -105415,1664320 -104617)", "SRID=4326;LINESTRING(0 0,1 1)")), "3879, 4326") })
binspwc <- function(y, x, w=NULL,data=NULL, estmethod="reg", family=gaussian(), quantile=NULL, deriv=0, at=NULL, nolink=F, by=NULL, pwc=c(3,3), testtype="two-sided", lp=Inf, bins=c(2,2), bynbins=NULL, binspos="qs", binsmethod="dpi", nbinsrot=NULL, samebinsby=FALSE, randcut=NULL, nsims=500, simsgrid=20, simsseed=NULL, vce=NULL, cluster=NULL, asyvar=F, dfcheck=c(20,30), masspoints="on", weights=NULL, subset=NULL, numdist=NULL, numclust=NULL, ...) { qrot <- 2 xname <- deparse(substitute(x)) yname <- deparse(substitute(y)) byname <- deparse(substitute(by)) if (byname == "NULL") { print("by variable is required.") stop() } weightsname <- deparse(substitute(weights)) subsetname <- deparse(substitute(subset)) clustername <- deparse(substitute(cluster)) w.factor <- NULL if (is.null(data)) { if (is.data.frame(y)) y <- y[,1] if (is.data.frame(x)) x <- x[,1] if (!is.null(w)) { if (is.vector(w)) { w <- as.matrix(w) if (is.character(w)) { w <- model.matrix(~w)[,-1,drop=F] w.factor <- rep(T, ncol(w)) } } else if (is.formula(w)) { w.model <- binsreg.model.mat(w) w <- w.model$design w.factor <- w.model$factor.colnum } } } else { if (xname %in% names(data)) x <- data[,xname] if (yname %in% names(data)) y <- data[,yname] if (byname != "NULL") if (byname %in% names(data)) { by <- data[,byname] } if (weightsname != "NULL") if (weightsname %in% names(data)) { weights <- data[,weightsname] } if (subsetname != "NULL") if (subsetname %in% names(data)) { subset <- data[,subsetname] } if (clustername != "NULL") if (clustername %in% names(data)) { cluster <- data[,clustername] } if (deparse(substitute(w))!="NULL") { if (is.formula(w)) { if (is.data.frame(at)) { if (ncol(data)!=ncol(at)) { data[setdiff(names(at), names(data))] <- NA at[setdiff(names(data), names(at))] <- NA } data <- rbind(data, at) } w.model <- binsreg.model.mat(w, data=data) w <- w.model$design w.factor <- w.model$factor.colnum if (is.data.frame(at)) { eval.w <- w[nrow(w),] w <- w[-nrow(w),, drop=F] } } else { if (deparse(substitute(w)) %in% names(data)) w <- data[,deparse(substitute(w))] w <- as.matrix(w) if (is.character(w)) { w <- model.matrix(~w)[,-1,drop=F] w.factor <- rep(T, ncol(w)) } } } } if (!is.null(w)) nwvar <- ncol(w) else nwvar <- 0 if (!is.null(subset)) { y <- y[subset] x <- x[subset] w <- w[subset, , drop = F] by <- by[subset] if (!is.null(cluster)) cluster <- cluster[subset] if (!is.null(weights)) weights <- weights[subset] } na.ok <- complete.cases(x) & complete.cases(y) if (!is.null(w)) na.ok <- na.ok & complete.cases(w) if (!is.null(by)) na.ok <- na.ok & complete.cases(by) if (!is.null(weights)) na.ok <- na.ok & complete.cases(weights) if (!is.null(cluster)) na.ok <- na.ok & complete.cases(cluster) y <- y[na.ok] x <- x[na.ok] w <- w[na.ok, , drop = F] by <- by[na.ok] weights <- weights[na.ok] cluster <- cluster[na.ok] xmin <- min(x); xmax <- max(x) if (is.null(at)) at <- "mean" if (!is.null(family)) if (family$family!="gaussian" | family$link!="identity") { estmethod <- "glm" } if (estmethod=="glm") { familyname <- family$family linkinv <- family$linkinv linkinv.1 <- family$mu.eta if (family$link=="logit") { linkinv.2 <- function(z) linkinv.1(z)*(1-2*linkinv(z)) } else if (family$link=="probit") { linkinv.2 <- function(z) (-z)*linkinv.1(z) } else if (family$link=="identity") { linkinv.2 <- function(z) 0 } else if (family$link=="log") { linkinv.2 <- function(z) linkinv(z) } else if (family$link=="inverse") { linkinv.2 <- function(z) 2*z^(-3) } else if (family$link=="1/mu^2") { linkinv.2 <- function(z) 0.75*z^(-2.5) } else if (family$link=="sqrt") { linkinv.2 <- function(z) 2 } else { print("The specified link not allowed for computing polynomial-based CIs.") stop() } } if (estmethod=="reg") { estmethod.name <- "least squares regression" if (is.null(vce)) vce <- "HC1" vce.select <- vce } else if (estmethod=="qreg") { estmethod.name <- "quantile regression" if (is.null(vce)) vce <- "nid" if (vce=="iid") { vce.select <- "const" } else { vce.select <- "HC1" } if (is.null(quantile)) quantile <- 0.5 } else if (estmethod=="glm") { estmethod.name <- "generalized linear model" if (is.null(vce)) vce <- "HC1" vce.select <- vce } else { print("estmethod incorrectly specified.") stop() } exit <- 0 if (!is.character(binspos)) { if (min(binspos)<=xmin|max(binspos)>=xmax) { print("knots out of allowed range") exit <- 1 } } else { if (binspos!="es" & binspos!="qs") { print("binspos incorrectly specified.") exit <- 1 } } if (length(bins)==2) if (bins[1]<bins[2]) { print("p<s not allowed.") exit <- 1 } if (length(pwc)==2) if (pwc[1]<pwc[2]) { print("p<s not allowed.") exit <- 1 } if (length(pwc)>=1) if (pwc[1]<deriv) { print("p for test cannot be smaller than deriv.") exit <- 1 } if ((length(pwc)>=1)&(length(bins)>=1)) if (pwc[1]<=bins[1]) { warning("p for testing > p for bin selection is suggested.") } if (exit>0) stop() bins.p <- bins[1]; bins.s <- bins[2] tsha.p <- pwc[1]; tsha.s <- pwc[2] if (binsmethod=="dpi") { selectmethod <- "IMSE direct plug-in" } else { selectmethod <- "IMSE rule-of-thumb" } nbins_all <- NULL if (length(bynbins)==1) nbins_all <- bynbins if (!is.null(bynbins)) { selectmethod <- "User-specified" } localcheck <- massadj <- T; fewmasspoints <- F if (masspoints=="on") { localcheck <- T; massadj <- T } else if (masspoints=="off") { localcheck <- F; massadj <- F } else if (masspoints=="noadjust") { localcheck <- T; massadj <- F } else if (masspoints=="nolocalcheck") { localcheck <- F; massadj <- T } else if (masspoints=="veryfew") { print("veryfew not allowed for testing.") stop() } byvals <- sort(unique(by)) ngroup <- length(byvals) xrange <- sapply(byvals, function(byv) range(x[by == byv])) xminmat <- xrange[1,]; xmaxmat <- xrange[2,] knot <- NULL knotlistON <- F if (!is.character(binspos)) { nbins_all <- length(binspos)+1 knot <- c(xmin, sort(binspos), xmax) position <- "User-specified" es <- F selectmethod <- "User-specified" knotlistON <- T } else { if (binspos == "es") { es <- T position <- "Evenly-spaced" } else { es <- F position <- "Quantile-spaced" } } Ndist <- Nclust <- NA selectfullON <- F if (is.null(nbins_all) & samebinsby) selectfullON <- T if (selectfullON) { eN <- N <- length(x) if (massadj) { Ndist <- length(unique(x)) eN <- min(eN, Ndist) } if (!is.null(cluster)) { Nclust <- length(unique(cluster)) eN <- min(eN, Nclust) } if (is.null(nbinsrot)) { if (eN <= dfcheck[1]+bins.p+1+qrot) { warning("too small effective sample size for bin selection.") stop() } } if (is.na(Ndist)) { Ndist.sel <- NULL } else { Ndist.sel <- Ndist } if (is.na(Nclust)) { Nclust.sel <- NULL } else { Nclust.sel <- Nclust } binselect <- binsregselect(y, x, w, deriv=deriv, bins=bins, binspos=binspos, binsmethod=binsmethod, nbinsrot=nbinsrot, vce=vce.select, cluster=cluster, randcut=randcut, dfcheck=dfcheck, masspoints=masspoints, weights=weights, numdist=Ndist.sel, numclust=Nclust.sel) if (is.na(binselect$nbinsrot.regul)) { print("bin selection fails.") stop() } if (binsmethod == "rot") { nbins_all <- binselect$nbinsrot.regul } else if (binsmethod == "dpi") { nbins_all <- binselect$nbinsdpi if (is.na(nbins_all)) { warning("DPI selection fails. ROT choice used.") nbins_all <- binselect$nbinsrot.regul } } } if ((selectfullON | (!is.null(nbins_all) & samebinsby)) & is.null(knot)) { knotlistON <- T if (es) { knot <- genKnot.es(xmin, xmax, nbins_all) } else { knot <- genKnot.qs(x, nbins_all) } } knot_all <- NULL if (knotlistON) { knot_all <- knot } if (!is.null(simsseed)) set.seed(simsseed) uni_grid <- seq(max(xminmat), min(xmaxmat), length=simsgrid+2)[-c(1,simsgrid+2)] if (!is.null(w)) { if (is.character(at)) { if (at=="mean") { eval.w <- colWeightedMeans(x=w, w=weights) if (!is.null(w.factor)) eval.w[w.factor] <- 0 } else if (at=="median") { eval.w <- colWeightedMedians(x=w, w=weights) if (!is.null(w.factor)) eval.w[w.factor] <- 0 } else if (at=="zero") { eval.w <- rep(0, nwvar) } } else if (is.vector(at)) { eval.w <- at } else if (is.data.frame(at)) { eval.w <- eval.w } } else { eval.w <- NULL } N.by <- Ndist.by <- Nclust.by <- nbins.by <- cval.by <- NULL fit.sha <- se.sha <- nummat <- denom <- list() tstat <- matrix(NA, ngroup*(ngroup-1)/2, 3); pval <- matrix(NA, ngroup*(ngroup-1)/2, 1) counter <- 1 for (i in 1:ngroup) { sub <- (by == byvals[i]) y.sub <- y[sub]; x.sub <- x[sub]; w.sub <- w[sub, , drop = F] cluster.sub <- cluster[sub]; weights.sub <- weights[sub] xmin <- min(x.sub); xmax <- max(x.sub) eN <- N <- length(x.sub) N.by <- c(N.by, N) Ndist <- NA if (massadj) { Ndist <- length(unique(x.sub)) eN <- min(eN, Ndist) } Ndist.by <- c(Ndist.by, Ndist) Nclust <- NA if (!is.null(cluster.sub)) { Nclust <- length(unique(cluster.sub)) eN <- min(eN, Nclust) } Nclust.by <- c(Nclust.by, Nclust) nbins <- NULL; knot <- NULL if (!is.null(nbins_all)) nbins <- nbins_all if (length(bynbins)>1) nbins <- bynbins[i] if (is.null(nbins) & !knotlistON) { if (is.null(nbinsrot)) if (eN <= dfcheck[1]+bins.p+1+qrot) { warning("too small effective sample size for bin selection.") stop() } if (is.na(Ndist)) { Ndist.sel <- NULL } else { Ndist.sel <- Ndist } if (is.na(Nclust)) { Nclust.sel <- NULL } else { Nclust.sel <- Nclust } binselect <- binsregselect(y.sub, x.sub, w.sub, deriv=deriv, bins=bins, binspos=binspos, binsmethod=binsmethod, nbinsrot=nbinsrot, vce=vce.select, cluster=cluster.sub, randcut=randcut, dfcheck=dfcheck, masspoints=masspoints, weights=weights.sub, numdist=Ndist.sel, numclust=Nclust.sel) if (is.na(binselect$nbinsrot.regul)) { print("bin selection fails.") stop() } if (binsmethod == "rot") { nbins <- binselect$nbinsrot.regul } else if (binsmethod == "dpi") { nbins <- binselect$nbinsdpi if (is.na(nbins)) { warning("DPI selection fails. ROT choice used.") nbins <- binselect$nbinsrot.regul } } } if (knotlistON) { nbins <- length(knot_all)-1 knot <- knot_all } if ((nbins-1)*(tsha.p-tsha.s+1)+tsha.p+1+dfcheck[2]>=eN) { warning("too small effective sample size for testing shape.") } if (is.null(knot)) { if (es) knot <- genKnot.es(xmin, xmax, nbins) else knot <- genKnot.qs(x.sub, nbins) } knot <- c(knot[1], unique(knot[-1])) if (nbins!=length(knot)-1) { warning("repeated knots. Some bins dropped.") nbins <- length(knot)-1 } nbins.by <- c(nbins.by, nbins) if (localcheck) { uniqmin <- binsreg.checklocalmass(x.sub, nbins, es, knot=knot) if (uniqmin < tsha.p+1) { warning("some bins have too few distinct values of x for testing.") } } B <- binsreg.spdes(eval=x.sub, p=tsha.p, s=tsha.s, knot=knot, deriv=0) k <- ncol(B) P <- cbind(B, w.sub) if (estmethod=="reg") { model <- lm(y.sub ~ P-1, weights=weights.sub) } else if (estmethod=="qreg") { model <- rq(y.sub ~ P-1, tau=quantile, weights=weights.sub) } else if (estmethod=="glm") { model <- glm(y.sub ~ P-1, family=family, weights=weights.sub) } beta <- model$coeff[1:k] basis.sha <- binsreg.spdes(eval=uni_grid, p=tsha.p, s=tsha.s, knot=knot, deriv=deriv) if (estmethod=="glm" & (!nolink)) { pred.sha <- binsreg.pred(X=basis.sha, model=model, type="all", vce=vce, cluster=cluster.sub, deriv=deriv, wvec=eval.w, avar=asyvar) basis.0 <- binsreg.spdes(eval=uni_grid, p=tsha.p, s=tsha.s, knot=knot, deriv=0) fit.0 <- binsreg.pred(basis.0, model, type = "xb", vce=vce, cluster=cluster.sub, deriv=0, wvec=eval.w)$fit pred.sha.0 <- linkinv.1(fit.0) if (asyvar | deriv==0) { pred.sha$se <- pred.sha.0 * pred.sha$se if (deriv == 0) pred.sha$fit <- linkinv(pred.sha$fit) if (deriv == 1) pred.sha$fit <- pred.sha.0 * pred.sha$fit } else { basis.sha.1 <- basis.sha if (!is.null(eval.w)) { basis.sha.0 <- cbind(basis.0, outer(rep(1, nrow(basis.0)), eval.w)) basis.sha.1 <- cbind(basis.sha.1, outer(rep(1, nrow(basis.sha.1)), rep(0, nwvar))) } basis.all <- linkinv.2(fit.0)*pred.sha$fit*basis.sha.0 + pred.sha.0*basis.sha.1 pred.sha$fit <- pred.sha.0 * pred.sha$fit pred.sha$se <- binsreg.pred(basis.all, model=model, type="se", vce=vce, cluster=cluster.sub, avar=T)$se } } else { if (estmethod=="qreg") { pred.sha <- binsreg.pred(basis.sha, model, type = "all", vce=vce, cluster=cluster.sub, deriv=deriv, wvec=eval.w, is.qreg=TRUE, avar=asyvar, ...) } else { pred.sha <- binsreg.pred(basis.sha, model, type = "all", vce=vce, cluster=cluster.sub, deriv=deriv, wvec=eval.w, avar=asyvar) } } fit.sha[[i]] <- pred.sha$fit se.sha[[i]] <- pred.sha$se pos <- !is.na(beta) k.new <- sum(pos) if (estmethod=="qreg") vcv.sha <- binsreg.vcov(model, type=vce, cluster=cluster.sub, is.qreg=TRUE, ...)[1:k.new, 1:k.new] else vcv.sha <- binsreg.vcov(model, type=vce, cluster=cluster.sub)[1:k.new, 1:k.new] Sigma.root <- lssqrtm(vcv.sha) nummat[[i]] <- basis.sha[,pos,drop=F] %*% Sigma.root denom[[i]] <- sqrt(rowSums((basis.sha[, pos, drop=F] %*% vcv.sha) * basis.sha[, pos, drop=F])) if (i>1) { for (j in 1:(i-1)) { if (testtype=="left") { tstat[counter,] <- c(max((fit.sha[[i]]-fit.sha[[j]]) / sqrt(se.sha[[i]]^2+se.sha[[j]]^2)), i, j) } else if (testtype=="right") { tstat[counter,] <- c(min((fit.sha[[i]]-fit.sha[[j]]) / sqrt(se.sha[[i]]^2+se.sha[[j]]^2)), i, j) } else { if (is.infinite(lp)) { tstat[counter,] <- c(max(abs((fit.sha[[i]]-fit.sha[[j]]) / sqrt(se.sha[[i]]^2+se.sha[[j]]^2))), i, j) } else { tstat[counter,] <- c(mean(((fit.sha[[i]]-fit.sha[[j]]) / sqrt(se.sha[[i]]^2+se.sha[[j]]^2))^lp)^(1/lp), i, j) } } pval[counter,1] <- binspwc.pval(nummat[[i]], nummat[[j]], denom[[i]], denom[[j]], nsims, tstat=tstat[counter,1], testtype=testtype, lp=lp) counter <- counter+1 } } } out <- list(tstat=tstat, pval=pval, opt=list(bins.p=bins.p, bins.s=bins.s, deriv=deriv, pwc.p=tsha.p, pwc.s=tsha.s, byname=byname, testtype=testtype, binspos=position, binsmethod=selectmethod, N.by=N.by, Ndist.by=Ndist.by, Nclust.by=Nclust.by, nbins.by=nbins.by, byvals=byvals, lp=lp, estmethod=estmethod.name, quantile=quantile, family=family)) out$call <- match.call() class(out) <- "CCFFbinspwc" return(out) } print.CCFFbinspwc <- function(x, ...) { cat("Call: binspwc\n\n") cat("Pairwise Group Comparison\n") cat(paste("Group Variable = ", x$opt$byname, "\n", sep="")) cat(paste("Estimation Method (estmethod) = ", x$opt$estmethod, "\n", sep="")) cat(paste("degree (p) = ", x$opt$pwc.p, "\n", sep="")) cat(paste("smooth (s) = ", x$opt$pwc.s, "\n", sep="")) cat(paste("Derivative (deriv) = ", x$opt$deriv, "\n", sep="")) cat(paste("Bin selection:", "\n")) cat(paste(" Method (binsmethod) = ", x$opt$binsmethod,"\n", sep="")) cat(paste(" Placement (binspos) = ", x$opt$binspos, "\n", sep="")) cat(paste(" degree (p) = ", x$opt$bins.p, "\n", sep="")) cat(paste(" smooth (s) = ", x$opt$bins.s, "\n", sep="")) cat("\n") for (i in 1:length(x$opt$byvals)) { cat(paste("Group (by) = ", x$opt$byvals[i], "\n", sep="")) cat(paste("Sample size (n) = ", x$opt$N.by[i], "\n", sep="")) cat(paste(" cat(paste(" cat(paste(" cat("\n") } } summary.CCFFbinspwc <- function(object, ...) { x <- object args <- list(...) cat("Call: binspwc\n\n") cat("Pairwise Group Comparison\n") cat(paste("Group Variable = ", x$opt$byname, "\n", sep="")) cat(paste("Estimation Method (estmethod) = ", x$opt$estmethod, "\n", sep="")) cat(paste("degree (p) = ", x$opt$pwc.p, "\n", sep="")) cat(paste("smooth (s) = ", x$opt$pwc.s, "\n", sep="")) cat(paste("Derivative (deriv) = ", x$opt$deriv, "\n", sep="")) cat(paste("Bin selection:", "\n")) cat(paste(" Method (binsmethod) = ", x$opt$binsmethod,"\n", sep="")) cat(paste(" Placement (binspos) = ", x$opt$binspos, "\n", sep="")) cat(paste(" degree (p) = ", x$opt$bins.p, "\n", sep="")) cat(paste(" smooth (s) = ", x$opt$bins.s, "\n", sep="")) cat("\n") for (i in 1:nrow(x$tstat)) { g1 <- x$tstat[i,2]; g2 <- x$tstat[i,3] group1 <- x$opt$byvals[g1]; group2 <- x$opt$byvals[g2] cat(paste("Group", group1, " vs. Group", group2)); cat("\n") cat(paste(rep("=", 22 + 12 + 12), collapse="")); cat("\n") cat(format(paste("Group ", x$opt$byname, " =", sep=""), width = 22, justify = "left")) cat(format(group1, width = 12, justify = "right")) cat(format(group2, width = 12, justify = "right")) cat("\n") cat(paste(rep("-", 22 + 12 + 12), collapse="")); cat("\n") cat("\n") cat(format("Sample size", width=22, justify="left")) cat(format(x$opt$N.by[g1], width=12, justify="right")) cat(format(x$opt$N.by[g2], width=12, justify="right")) cat("\n") cat(format(" cat(format(x$opt$Ndist.by[g1], width=12, justify="right")) cat(format(x$opt$Ndist.by[g2], width=12, justify="right")) cat("\n") cat(format(" cat(format(x$opt$Nclust.by[g1], width=12, justify="right")) cat(format(x$opt$Nclust.by[g2], width=12, justify="right")) cat("\n") cat(format(" cat(format(x$opt$nbins.by[g1], width=12, justify="right")) cat(format(x$opt$nbins.by[g2], width=12, justify="right")) cat("\n") cat(paste(rep("-", 22 + 12 + 12), collapse="")); cat("\n") cat("\n") cat(paste("diff = Group", group1, "- Group", group2, sep=" ")); cat("\n") cat(paste(rep("=", 15 + 12 + 12), collapse="")); cat("\n") if (x$opt$testtype=="left") { cat(format("H0:", width = 15, justify = "left")) cat(format("sup T", width = 12, justify = "right")) cat(format("p value", width = 12, justify = "right")) cat("\n") cat(paste(rep("-", 15 + 12 + 12), collapse="")); cat("\n") cat(format("diff<=0", width = 15, justify = "left")) cat(format(sprintf("%3.3f", x$tstat[i,1]), width = 12, justify = "right")) cat(format(sprintf("%3.3f", x$pval[i,1]), width = 12, justify = "right")) cat("\n") cat(paste(rep("-", 15 + 12 + 12), collapse="")) cat("\n") } else if (x$opt$testtype=="right") { cat(format("H0:", width = 15, justify = "left")) cat(format("inf T", width = 12, justify = "right")) cat(format("p value", width = 12, justify = "right")) cat("\n") cat(paste(rep("-", 15 + 12 + 12), collapse="")); cat("\n") cat(format("diff>=0", width = 15, justify = "left")) cat(format(sprintf("%3.3f", x$tstat[i,1]), width = 12, justify = "right")) cat(format(sprintf("%3.3f", x$pval[i,1]), width = 12, justify = "right")) cat("\n") cat(paste(rep("-", 15 + 12 + 12), collapse="")) cat("\n") } else { if (is.infinite(x$opt$lp)) { cat(format("H0:", width = 15, justify = "left")) cat(format("sup |T|", width = 12, justify = "right")) cat(format("p value", width = 12, justify = "right")) cat("\n") cat(paste(rep("-", 15 + 12 + 12), collapse="")); cat("\n") cat(format("diff=0", width = 15, justify = "left")) cat(format(sprintf("%3.3f", x$tstat[i,1]), width = 12, justify = "right")) cat(format(sprintf("%3.3f", x$pval[i,1]), width = 12, justify = "right")) cat("\n") cat(paste(rep("-", 15 + 12 + 12), collapse="")) cat("\n") } else { cat(format("H0:", width = 15, justify = "left")) cat(format(paste("L", x$opt$lp, " of T", sep=""), width = 12, justify = "right")) cat(format("p value", width = 12, justify = "right")) cat("\n") cat(paste(rep("-", 15 + 12 + 12), collapse="")); cat("\n") cat(format("diff=0", width = 15, justify = "left")) cat(format(sprintf("%3.3f", x$tstat[i,1]), width = 12, justify = "right")) cat(format(sprintf("%3.3f", x$pval[i,1]), width = 12, justify = "right")) cat("\n") cat(paste(rep("-", 15 + 12 + 12), collapse="")) cat("\n") } } cat("\n"); cat("\n") } cat("\n") }
draw_grid_panel <- function(data, panel_params, coord, grob, debug) { if (!is.null(debug)) { coords <- coord$transform(data, panel_params) debug(data, coords) } if (is.grob(grob)) { grob } else { if (!is.function(grob)) stop("Invalid grob in GeomPanel") coords <- coord$transform(data, panel_params) grob(data, coords) } } grid_panel <- function(grob=nullGrob(), mapping = NULL, data = NULL, stat = "identity", position = "identity", inherit.aes = TRUE, show.legend = FALSE, key_glyph = NULL, debug = NULL, ...) { if (!is.grob(grob) && !is.function(grob)) stop("Invalid 'grob' argument; must be grob or function") if (!is.null(debug) && !is.function(debug)) stop("Invalid 'debug' argument: must be NULL or function") if (is.null(mapping)) { required_aes <- NULL } else { required_aes <- names(mapping) } if (packageVersion("ggplot2") <= "3.3.5") { default_aes = aes(xmin = -Inf, xmax = -Inf) } else { default_aes = aes() } GeomGridPanel <- ggproto("GeomGridPanel", Geom, required_aes = required_aes, default_aes = default_aes, draw_panel = draw_grid_panel) layer(geom = GeomGridPanel, mapping = mapping, data = data, stat = stat, position = position, inherit.aes = inherit.aes, check.aes = FALSE, show.legend = show.legend, key_glyph = key_glyph, params = list(grob = grob, debug = debug, ...)) }
.plotGeneCount <- function(curve, counts = NULL, gene = NULL, clusters = NULL, models = NULL, title = NULL){ rd <- slingshot::slingReducedDim(curve) if (!is.null(gene)) { logcounts <- log1p(counts[gene, ]) cols <- logcounts scales <- scale_color_gradient(low = "yellow", high = 'red') if (is.null(title)) title <- paste0("logged count of gene ", gene) } else { cols <- as.character(clusters) scales <- NULL if (is.null(title)) title <- "Clusters" } df <- data.frame(dim1 = rd[, 1], dim2 = rd[, 2], col = cols) p <- ggplot(df, aes(x = dim1, y = dim2, col = col)) + geom_point(size = 1) + theme_classic() + labs(col = title) + scales for (i in seq_along(slingCurves(curve))) { curve_i <- slingCurves(curve)[[i]] curve_i <- curve_i$s[curve_i$ord, seq_len(2)] colnames(curve_i) <- c("dim1", "dim2") p <- p + geom_path(data = as.data.frame(curve_i), col = "black", size = 1) } nCurves <- length(slingCurves(curve)) if (!is.null(models)) { if (is(models, "list")) { sce <- FALSE } else if(is(models, "SingleCellExperiment")){ sce <- TRUE } if(!sce){ m <- .getModelReference(models) knots <- m$smooth[[1]]$xp } else if(sce){ knots <- S4Vectors::metadata(models)$tradeSeq$knots } knots_dim <- matrix(ncol = 2, nrow = nCurves * length(knots)) for (ii in seq_along(slingCurves(curve))) { S <- project_to_curve(x = slingCurves(curve)[[ii]]$s, s = slingCurves(curve)[[ii]]$s[slingCurves(curve)[[ii]]$ord, ], stretch = 0) for (jj in seq_along(knots)) { kn <- knots[jj] times <- S$lambda knot <- which.min(abs(times - kn)) knots_dim[jj + (ii-1)*length(knots), ] <- S$s[knot, seq_len(2)] } } knots_dim <- as.data.frame(knots_dim) colnames(knots_dim) <- c("dim1", "dim2") p <- p + geom_point(data = knots_dim, col = "black", size = 2) } return(p) } setMethod(f = "plotGeneCount", signature = c(curve = "SlingshotDataSet"), definition = function(curve, counts = NULL, gene = NULL, clusters = NULL, models = NULL, title = NULL){ if (is.null(gene) & is.null(clusters)) { stop("Either gene and counts, or clusters argument must be supplied") } if (is.null(counts) & is.null(clusters)) { stop("Either gene and counts, or clusters argument must be supplied") } p <- .plotGeneCount(curve = curve, counts = counts, gene = gene, clusters = clusters, models = models, title = title) return(p) } ) setMethod(f = "plotGeneCount", signature = c(curve = "PseudotimeOrdering"), definition = function(curve, counts = NULL, gene = NULL, clusters = NULL, models = NULL, title = NULL){ if (is.null(gene) & is.null(clusters)) { stop("Either gene and counts, or clusters argument must be supplied") } if (is.null(counts) & is.null(clusters)) { stop("Either gene and counts, or clusters argument must be supplied") } p <- .plotGeneCount(curve = curve, counts = counts, gene = gene, clusters = clusters, models = models, title = title) return(p) } ) setMethod(f = "plotGeneCount", signature = c(curve = "SingleCellExperiment"), definition = function(curve, counts = NULL, gene = NULL, clusters = NULL, models = NULL, title = NULL){ if (!is.null(counts)) { message(paste0("The count argument will be ignored if the curve argument", "is a SingleCellExperiment object")) } p <- plotGeneCount(curve = slingshot::SlingshotDataSet(curve), counts = SingleCellExperiment::counts(curve), gene = gene, clusters = clusters, models = models, title = title) return(p) } )
gce_make_image_source_url <- function(image_project, image = NULL, family = NULL){ if(is.null(image)){ stopifnot(!is.null(family)) } if(is.null(image)){ img_obj <- gce_get_image_family(image_project, family) } else { img_obj <- gce_get_image(image_project, image) } gsub("https://www.googleapis.com/compute/v1/","",img_obj$selfLink) } gce_get_image <- function(image_project, image) { url <- sprintf("https://www.googleapis.com/compute/v1/projects/%s/global/images/%s", image_project, image) f <- gar_api_generator(url, "GET", data_parse_function = function(x) x) f() } gce_get_image_family <- function(image_project, family) { url <- sprintf("https://www.googleapis.com/compute/v1/projects/%s/global/images/family/%s", image_project, family) f <- gar_api_generator(url, "GET", data_parse_function = function(x) x) f() } gce_list_images <- function(image_project, filter = NULL, maxResults = NULL, pageToken = NULL) { url <- sprintf("https://www.googleapis.com/compute/v1/projects/%s/global/images", image_project) pars <- list(filter = filter, maxResults = maxResults, pageToken = pageToken) pars <- rmNullObs(pars) f <- gar_api_generator(url, "GET", pars_args = pars, data_parse_function = function(x) x) f() }
summarise <- function(.data, ..., .groups = NULL) { UseMethod("summarise") } summarize <- summarise summarise.data.frame <- function(.data, ..., .groups = NULL) { cols <- summarise_cols(.data, dplyr_quosures(...), caller_env = caller_env()) out <- summarise_build(.data, cols) if (identical(.groups, "rowwise")) { out <- rowwise_df(out, character()) } out } summarise.grouped_df <- function(.data, ..., .groups = NULL) { cols <- summarise_cols(.data, dplyr_quosures(...), caller_env = caller_env()) out <- summarise_build(.data, cols) verbose <- summarise_verbose(.groups, caller_env()) if (is.null(.groups)) { if (cols$all_one) { .groups <- "drop_last" } else { .groups <- "keep" } } group_vars <- group_vars(.data) if (identical(.groups, "drop_last")) { n <- length(group_vars) if (n > 1) { if (verbose) { new_groups <- glue_collapse(paste0("'", group_vars[-n], "'"), sep = ", ") summarise_inform("has grouped output by {new_groups}") } out <- grouped_df(out, group_vars[-n], group_by_drop_default(.data)) } } else if (identical(.groups, "keep")) { if (verbose) { new_groups <- glue_collapse(paste0("'", group_vars, "'"), sep = ", ") summarise_inform("has grouped output by {new_groups}") } out <- grouped_df(out, group_vars, group_by_drop_default(.data)) } else if (identical(.groups, "rowwise")) { out <- rowwise_df(out, group_vars) } else if(!identical(.groups, "drop")) { bullets <- c( paste0("`.groups` can't be ", as_label(.groups)), i = 'Possible values are NULL (default), "drop_last", "drop", "keep", and "rowwise"' ) abort(bullets) } out } summarise.rowwise_df <- function(.data, ..., .groups = NULL) { cols <- summarise_cols(.data, dplyr_quosures(...), caller_env = caller_env()) out <- summarise_build(.data, cols) verbose <- summarise_verbose(.groups, caller_env()) group_vars <- group_vars(.data) if (is.null(.groups) || identical(.groups, "keep")) { if (verbose && length(group_vars)) { new_groups <- glue_collapse(paste0("'", group_vars, "'"), sep = ", ") summarise_inform("has grouped output by {new_groups}") } out <- grouped_df(out, group_vars) } else if (identical(.groups, "rowwise")) { out <- rowwise_df(out, group_vars) } else if (!identical(.groups, "drop")) { bullets <- c( paste0("`.groups` can't be ", as_label(.groups)), i = 'Possible values are NULL (default), "drop", "keep", and "rowwise"' ) abort(bullets) } out } summarise_cols <- function(.data, dots, caller_env, error_call = caller_env()) { error_call <- dplyr_error_call(error_call) mask <- DataMask$new(.data, caller_env, "summarise", error_call = error_call) old_current_column <- context_peek_bare("column") on.exit(context_poke("column", old_current_column), add = TRUE) on.exit(mask$forget(), add = TRUE) cols <- list() sizes <- 1L chunks <- vector("list", length(dots)) types <- vector("list", length(dots)) chunks <- list() results <- list() types <- list() out_names <- character() withCallingHandlers({ for (i in seq_along(dots)) { context_poke("column", old_current_column) quosures <- expand_across(dots[[i]]) quosures_results <- map(quosures, summarise_eval_one, mask = mask) for (k in seq_along(quosures)) { quo <- quosures[[k]] quo_data <- attr(quo, "dplyr:::data") quo_result <- quosures_results[[k]] if (is.null(quo_result)) { next } types_k <- quo_result$types chunks_k <- quo_result$chunks results_k <- quo_result$results if (!quo_data$is_named && is.data.frame(types_k)) { chunks_extracted <- .Call(dplyr_extract_chunks, chunks_k, types_k) types_k_names <- names(types_k) for (j in seq_along(chunks_extracted)) { mask$add_one( name = types_k_names[j], chunks = chunks_extracted[[j]], result = results_k[[j]] ) } chunks <- append(chunks, chunks_extracted) types <- append(types, as.list(types_k)) results <- append(results, results_k) out_names <- c(out_names, types_k_names) } else { name <- quo_data$name_auto mask$add_one(name = name, chunks = chunks_k, result = results_k) chunks <- append(chunks, list(chunks_k)) types <- append(types, list(types_k)) results <- append(results, list(results_k)) out_names <- c(out_names, name) } } } recycle_info <- .Call(`dplyr_summarise_recycle_chunks`, chunks, mask$get_rows(), types, results) chunks <- recycle_info$chunks sizes <- recycle_info$sizes results <- recycle_info$results for (i in seq_along(chunks)) { result <- results[[i]] %||% vec_c(!!!chunks[[i]], .ptype = types[[i]]) cols[[ out_names[i] ]] <- result } }, error = function(e) { what <- "computing" index <- i if (inherits(e, "dplyr:::summarise_incompatible_size")) { index <- e$dplyr_error_data$index what <- "recycling" } local_error_context(dots = dots, .index = index, mask = mask) bullets <- c( cnd_bullet_header(what), summarise_bullets(e) ) abort(bullets, call = error_call, parent = skip_internal_condition(e) ) }) list(new = cols, size = sizes, all_one = identical(sizes, 1L)) } summarise_eval_one <- function(quo, mask) { quo_data <- attr(quo, "dplyr:::data") if (!is.null(quo_data$column)) { context_poke("column", quo_data$column) chunks_k <- withCallingHandlers( mask$eval_all_summarise(quo), error = function(cnd) { msg <- glue("Problem while computing column `{quo_data$name_auto}`.") abort(msg, call = call("across"), parent = cnd) } ) } else { chunks_k <- mask$eval_all_summarise(quo) } if (is.null(chunks_k)) { return(NULL) } types_k <- dplyr_vec_ptype_common(chunks_k, quo_data$name_auto) chunks_k <- vec_cast_common(!!!chunks_k, .to = types_k) result_k <- vec_c(!!!chunks_k, .ptype = types_k) list(chunks = chunks_k, types = types_k, results = result_k) } summarise_build <- function(.data, cols) { out <- group_keys(.data) if (!cols$all_one) { out <- vec_slice(out, rep(seq_len(nrow(out)), cols$size)) } dplyr_col_modify(out, cols$new) } summarise_bullets <- function(cnd, ..) { UseMethod("summarise_bullets") } summarise_bullets.default <- function(cnd, ...) { c(i = cnd_bullet_cur_group_label()) } `summarise_bullets.dplyr:::error_incompatible_combine` <- function(cnd, ...) { c() } `summarise_bullets.dplyr:::summarise_unsupported_type` <- function(cnd, ...) { result <- cnd$dplyr_error_data$result error_name <- peek_error_context()$error_name c( x = glue("`{error_name}` must be a vector, not {friendly_type_of(result)}."), i = cnd_bullet_rowwise_unlist(), i = cnd_bullet_cur_group_label() ) } `summarise_bullets.dplyr:::summarise_incompatible_size` <- function(cnd, ...) { expected_size <- cnd$dplyr_error_data$expected_size size <- cnd$dplyr_error_data$size group <- cnd$dplyr_error_data$group error_context <- peek_error_context() error_name <- error_context$error_name peek_mask()$set_current_group(group) c( x = glue("`{error_name}` must be size {or_1(expected_size)}, not {size}."), i = glue("An earlier column had size {expected_size}."), i = cnd_bullet_cur_group_label() ) } `summarise_bullets.dplyr:::summarise_mixed_null` <- function(cnd, ...) { error_name <- peek_error_context()$error_name c( x = glue("`{error_name}` must return compatible vectors across groups."), x = "Can't combine NULL and non NULL results." ) } summarise_verbose <- function(.groups, .env) { is.null(.groups) && is_reference(topenv(.env), global_env()) && !identical(getOption("dplyr.summarise.inform"), FALSE) } summarise_inform <- function(..., .env = parent.frame()) { inform(paste0( "`summarise()` ", glue(..., .envir = .env), '. You can override using the `.groups` argument.' )) }
compareCrimes <- function(Pairs,crimedata,varlist,binary=TRUE,longlat=FALSE, show.pb=FALSE,...){ if(class(crimedata) != 'data.frame') crimedata = as.data.frame(crimedata) if(!all(unlist(varlist) %in% colnames(crimedata))) stop("There are names in varlist that don't match column names in crimedata") valid.types = c("crimeID","spatial","temporal","categorical","numerical") if( !all(names(varlist) %in% valid.types) ) warning(paste(setdiff(names(varlist),valid.types), '(from varlist)', 'is not a valid type of crime data and will not be used to', 'make evidence variables.')) crimeID = as.character(crimedata$crimeID) i1 = match(Pairs[,1],crimeID) i2 = match(Pairs[,2],crimeID) d.spat = d.temp = d.cat = d.num = NA if(!is.null(varlist$spatial)){ spatial = crimedata[varlist$spatial] if(ncol(spatial) != 2) stop("spatial must be a data.frame of spatial coordinates with two columns") d.spat = compareSpatial(spatial[i1,1:2],spatial[i2,1:2],longlat=longlat) } if(!is.null(varlist$temporal)){ temporal = crimedata[varlist$temporal] if(ncol(temporal) == 1) temporal = cbind(temporal,temporal) d.temp = compareTemporal(temporal[i1,1:2],temporal[i2,1:2],show.pb=show.pb,...) } catNames = varlist$categorical if(!is.null(catNames)){ d.cat = data.frame(matrix(nrow=length(i1),ncol=length(catNames), dimnames=list(NULL,catNames))) for(cat in catNames){ d.cat[,cat] = compareCategorical(crimedata[i1,cat],crimedata[i2,cat], binary=binary) } } numNames = varlist$numerical if(!is.null(numNames)){ d.num = data.frame(matrix(nrow=length(i1),ncol=length(numNames), dimnames=list(NULL,numNames))) for(num in numNames){ d.num[,num] = compareNumeric(crimedata[i1,num],crimedata[i2,num]) } } Dist = data.frame(spatial=d.spat,d.temp,d.cat,d.num) Dist[sapply(Dist,function(x) all(is.na(x)))] <- list(NULL) E = cbind(Pairs,Dist,stringsAsFactors=FALSE) rownames(E) <- NULL return(E) } compareTemporal <- function(DT1,DT2,show.pb=FALSE,...){ L1 = as.numeric(abs(difftime(DT1[,2],DT1[,1],units='hours'))) L2 = as.numeric(abs(difftime(DT2[,2],DT2[,1],units='hours'))) day1 = as.numeric(julian(DT1[,1])) day2 = as.numeric(julian(DT2[,1])) tod1 = (as.numeric(DT1[,1])/3600) %% 24 tod2 = (as.numeric(DT2[,1])/3600) %% 24 dow1 = (as.numeric(DT1[,1])/(3600*24)) %% 7 dow2 = (as.numeric(DT2[,1])/(3600*24)) %% 7 n = length(L1) temporal = tod = dow = numeric(n) if(show.pb) pb = txtProgressBar(style=3,max=n) for(i in 1:n){ temporal[i] = expAbsDiff(c(day1[i],day1[i]+L1[i]/24),c(day2[i],day2[i]+L2[i]/24)) tod[i] = expAbsDiff.circ(c(tod1[i],tod1[i]+L1[i]),c(tod2[i],tod2[i]+L2[i]),mod=24,...) dow[i] = expAbsDiff.circ(c(dow1[i],dow1[i]+L1[i]/24),c(dow2[i],dow2[i]+L2[i]/24),mod=7,...) if(show.pb) setTxtProgressBar(pb,i) } if(show.pb) close(pb) return(data.frame(temporal,tod,dow) ) } expAbsDiff <- function(X,Y){ if(X[2]<X[1]) stop("X[2] < X[1]") if(Y[2]<Y[1]) stop("Y[2] < Y[1]") if(X[1]<=Y[1]){ Sx = X Sy = Y } else{ Sx = Y Sy = X } if(Sx[2] <= Sy[1]){ return(mean(Sy) - mean(Sx)) } bks = sort(c(Sx,Sy)) sz = diff(bks) mids = bks[-1] - sz/2 if(Sx[2] <= Sy[2]){ px = sz*c(1,1,0) / diff(Sx) py = sz*c(0,1,1) / diff(Sy) return( (mids[2]-mids[1])*px[1]*py[2] + (mids[3]-mids[1])*px[1]*py[3]+ (sz[2]/3)*px[2]*py[2] + (mids[3]-mids[2])*px[2]*py[3] ) } if(Sx[2] > Sy[2]){ px = sz*c(1,1,1) / diff(Sx) return( (mids[2]-mids[1])*px[1] + (sz[2]/3)*px[2] + (mids[3]-mids[2])*px[3] ) } } expAbsDiff.circ <- function(X,Y,mod=24,n=2000,method="convolution"){ if(X[1]<0 | Y[1]<0) stop("X and Y must be >0") if(diff(X)>=mod | diff(Y)>=mod) return(mod/4) if(diff(X)==0) return(getD(X[1],Y,mod=mod)) if(diff(Y)==0) return(getD(Y[1],X,mod=mod)) if(method=="convolution"){ while((n %% 2) != 0) n = nextn(n+1) theta = seq(0,mod,length=n+1) delta = diff(theta[1:2]) x = diff(punif(theta,X[1],X[2])) + diff(punif(theta+mod,X[1],X[2])) y = diff(punif(theta,Y[1],Y[2])) + diff(punif(theta+mod,Y[1],Y[2])) conv = convolve(x,y,conj=TRUE,type="circular") tt = ifelse(theta<=mod/2,theta,mod-theta)[-(n+1)] d = sum(tt*conv) } if(method=="numerical"){ if(diff(Y)<diff(X)){ tt = seq(Y[1],Y[2],length=n) d = mean(getD(tt,X,mod=mod)) } else{ tt = seq(X[1],X[2],length=n) d = mean(getD(tt,Y,mod=mod)) } } return(d) } getD <- function(y,X,mod=24){ if(X[1] > mod | X[1] < 0) stop("Minimum X[1] not within limits [0,mod)") if(X[2] < X[1]) stop("X[2] must be >= X[1]") y = (y - X[1]) %% mod B = X[2] - X[1] if(B == 0) return(mod/2-abs(mod/2-abs(y))) if(B >= mod) return(rep(mod/4,length(y))) D = numeric(length(y)) if(diff(X)>=mod/2){ K = mod - B/2 - (mod/2)^2/B u = y-mod/2 i1 = (y <= B-mod/2) D[i1] = y[i1]*(1-mod/B) + K i2 = (y > B-mod/2 & y <= mod/2) D[i2] = (y[i2]-B/2)^2/B +B/4 i3 = (y > mod/2 & y <= B) D[i3] = (B-y[i3])*(1-mod/B) + K i4 = (y > B) D[i4] = mod/2 - B/4 - ((u[i4]-B/2))^2/B } else{ u = y-B/2 i1 = (y<B) D[i1] = u[i1]^2/B + B/4 i2 = (y>=B & y<=mod/2) D[i2] = u[i2] i3 = (y>mod/2 & y<=B+mod/2) D[i3] = mod/2 - ((y[i3]-mod/2)^2 + (B-y[i3]+mod/2)^2) /(2*B) i4 = (y > B+mod/2) D[i4] = mod - u[i4] } return(D) } compareSpatial <- function(C1,C2,longlat=FALSE){ if(longlat) d = geosphere::distHaversine(C1,C2) else d = sqrt(rowSums((C1 - C2)^2)) return(d/1000) } compareNumeric <- function(C1,C2) abs(C1 - C2) compareCategorical <- function(C1,C2,levs,binary=FALSE){ if(binary){ match.na = is.na(C1) & is.na(C2) match.value = as.character(C1)==as.character(C2) B = ifelse(match.value | match.na,1,0) B[is.na(B)] = 0 return(factor(B,levels=c(0,1))) } C1 = as.factor(C1); C2 = as.factor(C2) if(missing(levs)) levs = sort(unique(levels(C1),levels(C2))) A = data.frame(C1=factor(C1,levels=levs), C2=factor(C2,levels=levs)) flip = which(is.na(A[,1]) | unclass(A[,1]) > unclass(A[,2])) A[flip,] = A[flip,2:1] B = paste(A[,1],A[,2],sep=':') B = factor(B,levels=catLevels(levs)) return(B) } catLevels <- function(levs){ levs = unique(c(levs,NA)) nlevs = length(levs) a = NULL for(i in 1:nlevs){ b = cbind(levs[i],levs[i:nlevs]) a = rbind(a,b) } levs2 = paste(a[,1],a[,2],sep=':') return(levs2) }
get_girth <- function(graph) { fcn_name <- get_calling_fcn() if (graph_object_valid(graph) == FALSE) { emit_error( fcn_name = fcn_name, reasons = "The graph object is not valid") } if (nrow(graph$nodes_df) == 0) { return(as.numeric(NA)) } ig_graph <- to_igraph(graph) igraph::girth(ig_graph, circle = FALSE)$girth }
Cuestas_Garratt_unit_root<-function(x,max_lags,lsm){ x<-as.vector(x) trend<-seq(0,length(x)-1,1) mod=lm(x~trend+trend^2+trend^3) x<-residuals(mod) AICs = NULL BICs = NULL tstats = NULL for(i in 1:max_lags){ z=diff(x) n=length(z) z.diff=embed(z, i+1)[,1] kup=x^3 z.lag.1=kup[(i+1):n] kare=x^2 z.lag.2=kare[(i+1):n] k=i+1 z.diff.lag = embed(z, i+1)[, 2:k] model<-lm(z.diff~z.lag.1+z.lag.2+0+z.diff.lag ) AICs[i+1] = AIC(model) BICs[i+1] = BIC(model) tstats[i+1] = summary(model)$coefficients[(i+2),4] } z=diff(x) n=length(z) z.diffzero=embed(z, 2)[,1] kupzero=x^3 z.lag.zero.1=kupzero[2:n] karezero=x^2 z.lag.zero.2=karezero[2:n] model0<-lm(z.diffzero~z.lag.zero.1+z.lag.zero.2+0) AICs[1] = AIC(model0) BICs[1] = BIC(model0) tstats[1] = 0.0000 if(lsm == 1){ uygun_lag=which.min(AICs)-1 } else if(lsm == 2){ uygun_lag=which.min(BICs)-1 } else { for (ti in (max_lags+1):1){ if (tstats[ti] <= 0.10){ uygun_lag = ti-1 break } } } z.diff=embed(z, uygun_lag+1)[,1] kup=x^3 z.lag.1=kup[(uygun_lag+1):n] kare=x^2 z.lag.2=kare[(uygun_lag+1):n] k=uygun_lag+1 if(uygun_lag == 0){ son <- lm(z.diff~z.lag.1+z.lag.2+0) ay <- linearHypothesis(son, c("z.lag.1=0","z.lag.2=0"), test="Chisq") } else { z.diff.lag = embed(z, uygun_lag+1)[, 2:k] son <- lm(z.diff~z.lag.1+z.lag.2+0+z.diff.lag) ay <- linearHypothesis(son, c("z.lag.1=0","z.lag.2=0"), test="Chisq") } perc <- c("1%","5%","10%") val <- c(22.44,17.27,14.97) CV = cbind(perc,val) my_list <- list("Model" = summary(son), "Selected lag"=uygun_lag, "Test Statistic"=ay$Chisq[2], "CV"=CV) return(my_list) }
HR_data <- breakDown::HR_data str(HR_data) library(randomForest) model_rf <- randomForest(average_montly_hours ~ last_evaluation + salary + satisfaction_level, data = HR_data) library(xspliner) model_xs <- xspline( average_montly_hours ~ last_evaluation + xf(salary, transition = list(value = 2)) + satisfaction_level, model = model_rf ) summary(model_xs) summary(model_xs, "salary") plot_variable_transition(model_xs, "salary") iris_data <- droplevels(iris[iris$Species != "setosa", ]) library(e1071) library(xspliner) model_svm <- svm(Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width, data = iris_data, probability = TRUE) model_xs <- xspline(Species ~ xs(Sepal.Length) + xs(Sepal.Width) + xs(Petal.Length) + xs(Petal.Width), model = model_svm) summary(model_xs) plot_variable_transition(model_xs, "Petal.Width")
print.sparsenet=function(x,digits = max(3, getOption("digits") - 3),...){ cat("\nCall: ", deparse(x$call), "\n\n") coeflist=x$coefficients rsq=x$rsq gnames=names(coeflist) for(i in seq(along=coeflist)){ x=coeflist[[i]] cat(gnames[i],": Gamma = ",signif(x$gamma,digits),"\n") print(cbind(Df=x$df,"Rsq"=signif(rsq[i,],digits),Lambda=signif(x$lambda,digits))) } }
expected <- c("bibtex", "tex") test(id=0, code={ argv <- structure(list(x = c("bibtex", "tex"), y = ".svn"), .Names = c("x", "y")) do.call('setdiff', argv); }, o = expected);
NULL NULL subsetConstraints <- function(x, i = NULL) { if (!inherits(x, "constraints")) { stop("'x' must be a 'constraints' object") } if (!validObject(x)) { stop("'x' is not a valid 'constraints' object") } if (is.null(i)) { return(x) } if (!all(i %in% 1:nrow(x@constraints))) { stop("'i' contains constraint indices not defined in @constraints") } tmp <- x@constraints[i, ] idx_to_drop <- which(toupper(names(x@constraints)) == "CONSTRAINT") tmp <- tmp[, -idx_to_drop] o <- loadConstraints( tmp, x@pool, x@item_attrib, x@st_attrib ) return(o) } combineConstraintsData <- function(raw1, raw2) { tmp <- setdiff(names(raw1), names(raw2)) raw2[tmp] <- NA tmp <- setdiff(names(raw2), names(raw1)) raw1[tmp] <- NA raw <- rbind(raw1, raw2) idx <- which(!duplicated(raw$CONSTRAINT)) raw <- raw[idx, ] return(raw) } combineConstraints <- function(x1, x2) { if (!inherits(x1, "constraints") || !inherits(x2, "constraints")) { stop("operands must be 'constraints' objects") } if (!validObject(x1)) { stop("'x1' is not a valid 'constraints' object") } if (!validObject(x2)) { stop("'x2' is not a valid 'constraints' object") } if (!identical(x1@pool, x2@pool)) { stop("@pool does not match") } if (!identical(x1@item_attrib, x2@item_attrib)) { stop("@item_attrib does not match") } if (!identical(x1@st_attrib, x2@st_attrib)) { stop("@st_attrib does not match") } raw <- combineConstraintsData(x1@constraints, x2@constraints) o <- loadConstraints(raw, x1@pool, x1@item_attrib, x1@st_attrib) id <- c(x1@constraints$CONSTRAINT, x1@constraints$CONSTRAINT) if (sum(duplicated(id)) > 0) { warning(sprintf("duplicate constraint IDs were removed: %s", paste0(id[duplicated(id)], collapse = ", "))) } return(o) } setMethod( f = "[", signature = c("constraints", "numeric"), definition = function(x, i, j, ...) { return(subsetConstraints(x, i)) } ) setMethod( f = "c", signature = "constraints", definition = function(x, ...) { arg <- list(...) o <- x for (tmp in arg) { o <- combineConstraints(o, tmp) } return(o) } ) toggleConstraints <- function(object, on = NULL, off = NULL) { nc <- nrow(object@constraints) if (length(intersect(on, off)) > 0) { stop("toggleConstraints: 'on' and 'off' must have no values in common") } if (!"ONOFF" %in% names(object@constraints)) { object@constraints[["ONOFF"]] <- "" } if (inherits(on, "character")) { on <- sapply( on, function(x) { which(object@constraints[["CONSTRAINT_ID"]] == x) } ) } if (inherits(off, "character")) { off <- sapply( off, function(x) { which(object@constraints[["CONSTRAINT_ID"]] == x) } ) } if (!is.null(on)) { if (any(!is.element(on, 1:nc))) { stop(sprintf("toggleConstraints: 'on' should be within c(1:nc), nc = %s", nc)) } for (index in on) { object@list_constraints[[index]]@suspend <- FALSE object@constraints[index, "ONOFF"] <- "" } } if (!is.null(off)) { if (any(!is.element(off, 1:nc))) { stop(sprintf("toggleConstraints: 'off' should be within c(1:nc), nc = %s", nc)) } for (index in off) { object@list_constraints[[index]]@suspend <- TRUE object@constraints[index, "ONOFF"] <- "OFF" } } index <- NULL mat <- NULL dir <- NULL rhs <- NULL for (i in 1:nc) { if (object@constraints[["TYPE"]][i] != "ORDER" && !object@list_constraints[[i]]@suspend) { object@list_constraints[[i]]@nc <- nrow(object@list_constraints[[i]]@mat) mat <- rbind(mat, object@list_constraints[[i]]@mat) dir <- c(dir, object@list_constraints[[i]]@dir) rhs <- c(rhs, object@list_constraints[[i]]@rhs) index <- c(index, rep(object@list_constraints[[i]]@constraint, object@list_constraints[[i]]@nc)) } } object@index <- index object@mat <- mat object@dir <- dir object@rhs <- rhs return(object) }
ip_op <- function(ped, name_Oe = "Oe", compute_O = FALSE, name_O = "O", Fcol = NULL, ncores = 1L, genedrop = 0, seed = NULL, complex = NULL) { check_basic(ped, "id", "dam", "sire") F_ <- check_Fcol(ped, Fcol) check_not_col(base::colnames(ped), name_O) check_not_col(base::colnames(ped), name_Oe) check_bool(compute_O) if (!base::is.null(complex)) base::warning("Argument 'complex' was deprecated in v1.3. It will be ignored.") pkm <- ip_Fij(ped, mode = "all", Fcol = Fcol, ncores = ncores, genedrop = genedrop, seed = seed) .Call(`_purgeR_op`, ped, pkm, Fcol = F_, name_O, name_Oe, "_raw", compute_O) }
library(rstanarm) library(lme4) SEED <- 12345 ITER <- 100 CHAINS <- 2 CORES <- 2 REFRESH <- 0 threshold <- 0.05 source(test_path("helpers", "expect_stanreg.R")) context("stan_nlmer") data("Orange", package = "datasets") Orange$circumference <- Orange$circumference / 100 Orange$age <- Orange$age / 100 fit <- stan_nlmer(circumference ~ SSlogis(age, Asym, xmid, scal) ~ Asym|Tree, data = Orange, prior = NULL, cores = CORES, init_r = 1, chains = CHAINS, seed = SEED, refresh = 0, QR = TRUE) startvec <- c(Asym = 200, xmid = 725, scal = 350) / 100 ml <- nlmer(circumference ~ SSlogis(age, Asym, xmid, scal) ~ Asym|Tree, data = Orange, start = startvec) test_that("stan_nlmer runs for Orange example", { expect_stanreg(fit) }) test_that("stan_nlmer is similar to nlmer on Orange example", { expect_equal(fixef(ml), fixef(fit), tol = threshold) }) test_that("stan_nlmer throws error if formula includes an unknown function", { expect_error(stan_nlmer(circumference ~ SSfoo(age, Asym, xmid, scal) ~ Asym|Tree, data = Orange), regexp = "self-starting nonlinear function") }) test_that("loo/waic for stan_nlmer works", { source(test_path("helpers", "expect_equivalent_loo.R")) }) context("posterior_predict (stan_nlmer)") test_that("compatible with stan_nlmer", { source(test_path("helpers", "check_for_error.R")) check_for_error(fit) })
gam <- 0.998 gam2 <- 0.818 y <- c(0.9510650, 0.8726557, 1.0582002) n <- length(y) params <- gam c1 <- computeFittedValues(y, c(0), params, "ar1") X <- gam ^(0:(n-1)) fit <- lm(y ~ X - 1) c2 <- fit$fitted.values test_that("correct fitted values for ar1", {expect_equal(c1, c2)}) params <- gam c1 <- computeFittedValues(y, c(0), params, "intercept") X <- cbind(gam ^ (0:(n-1)), rep(1, n)) fit <- lm(y ~ X - 1) c2 <- fit$fitted.values test_that("correct fitted values for intercept", {expect_equal(c1, c2)})
my.plot.scatter3d <- function(x, y = NULL, z = NULL, color = par("col"), pch = NULL, main = NULL, sub = NULL, xlim = NULL, ylim = NULL, zlim = NULL, xlab = NULL, ylab = NULL, zlab = NULL, scale.y = 1, angle = 40, axis = TRUE, tick.marks = TRUE, label.tick.marks = TRUE, x.ticklabs = NULL, y.ticklabs = NULL, z.ticklabs = NULL, y.margin.add = 0, grid = TRUE, box = FALSE, lab = par("lab"), lab.z = mean(lab[1:2]), type = "p", highlight.3d = FALSE, mar = c(5, 3, 4, 3) + 0.1, col.axis = par("col.axis"), col.grid = "grey", col.lab = par("col.lab"), cex.symbols = par("cex"), cex.axis = 0.8 * par("cex.axis"), cex.lab = par("cex.lab"), font.axis = par("font.axis"), font.lab = par("font.lab"), lty.axis = par("lty"), lty.grid = 2, lty.hide = 1, lty.hplot = par("lty"), log = "", ...) { mem.par <- par(mar = mar) x.scal <- y.scal <- z.scal <- 1 xlabel <- if (!missing(x)) deparse(substitute(x)) ylabel <- if (!missing(y)) deparse(substitute(y)) zlabel <- if (!missing(z)) deparse(substitute(z)) if(!is.null(d <- dim(x)) && (length(d) == 2) && (d[2] >= 4)) color <- x[,4] else if(is.list(x) && !is.null(x$color)) color <- x$color xyz <- xyz.coords(x=x, y=y, z=z, xlab=xlabel, ylab=ylabel, zlab=zlabel, log=log) if(is.null(xlab)) { xlab <- xyz$xlab; if(is.null(xlab)) xlab <- "" } if(is.null(ylab)) { ylab <- xyz$ylab; if(is.null(ylab)) ylab <- "" } if(is.null(zlab)) { zlab <- xyz$zlab; if(is.null(zlab)) zlab <- "" } if(length(color) == 1) color <- rep(color, length(xyz$x)) else if(length(color) != length(xyz$x)) stop("length(color) ", "must be equal length(x) or 1") angle <- (angle %% 360) / 90 yz.f <- scale.y * abs(if(angle < 1) angle else if(angle > 3) angle - 4 else 2 - angle) yx.f <- scale.y * (if(angle < 2) 1 - angle else angle - 3) if(angle > 2) { temp <- xyz$x; xyz$x <- xyz$y; xyz$y <- temp temp <- xlab; xlab <- ylab; ylab <- temp temp <- xlim; xlim <- ylim; ylim <- temp } angle.1 <- (1 < angle && angle < 2) || angle > 3 angle.2 <- 1 <= angle && angle <= 3 dat <- cbind(as.data.frame(xyz[c("x","y","z")]), col = color) n <- nrow(dat); y.range <- range(dat$y[is.finite(dat$y)]) if(type == "p" || type == "h") { y.ord <- rev(order(dat$y)) dat <- dat[y.ord, ] if(length(pch) > 1) if(length(pch) != length(y.ord)) stop("length(pch) ", "must be equal length(x) or 1") else pch <- pch[y.ord] daty <- dat$y daty[!is.finite(daty)] <- mean(daty[is.finite(daty)]) if(highlight.3d && !(all(diff(daty) == 0))) dat$col <- rgb(seq(0, 1, length = n) * (y.range[2] - daty) / diff(y.range), g=0, b=0) } p.lab <- par("lab") y.range <- range(dat$y[is.finite(dat$y)], ylim) y.prty <- pretty(y.range, n = lab[2], min.n = max(1, min(.5 * lab[2], p.lab[2]))) y.scal <- round(diff(y.prty[1:2]), digits = 12) y.add <- min(y.prty) dat$y <- (dat$y - y.add) / y.scal y.max <- (max(y.prty) - y.add) / y.scal x.range <- range(dat$x[is.finite(dat$x)], xlim) x.prty <- pretty(x.range, n = lab[1], min.n = max(1, min(.5 * lab[1], p.lab[1]))) x.scal <- round(diff(x.prty[1:2]), digits = 12) dat$x <- dat$x / x.scal x.range <- range(x.prty) / x.scal x.max <- ceiling(x.range[2]) x.min <- floor(x.range[1]) if(!is.null(xlim)) { x.max <- max(x.max, ceiling(xlim[2] / x.scal)) x.min <- min(x.min, floor(xlim[1] / x.scal)) } x.range <- range(x.min, x.max) z.range <- range(dat$z[is.finite(dat$z)], zlim) z.prty <- pretty(z.range, n = lab.z, min.n = max(1, min(.5 * lab.z, p.lab[2]))) z.scal <- round(diff(z.prty[1:2]), digits = 12) dat$z <- dat$z / z.scal z.range <- range(z.prty) / z.scal z.max <- ceiling(z.range[2]) z.min <- floor(z.range[1]) if(!is.null(zlim)) { z.max <- max(z.max, ceiling(zlim[2] / z.scal)) z.min <- min(z.min, floor(zlim[1] / z.scal)) } z.range <- range(z.min, z.max) plot.new() if(angle.2) {x1 <- x.min + yx.f * y.max; x2 <- x.max} else {x1 <- x.min; x2 <- x.max + yx.f * y.max} plot.window(c(x1, x2), c(z.min, z.max + yz.f * y.max)) temp <- strwidth(format(rev(y.prty))[1], cex = cex.axis/par("cex")) if(angle.2) x1 <- x1 - temp - y.margin.add else x2 <- x2 + temp + y.margin.add plot.window(c(x1, x2), c(z.min, z.max + yz.f * y.max)) if(angle > 2) par("usr" = par("usr")[c(2, 1, 3:4)]) usr <- par("usr") title(main, sub, ...) xx <- if(angle.2) c(x.min, x.max) else c(x.max, x.min) if(grid) { i <- x.min:x.max; segments(i, z.min, i + (yx.f * y.max), yz.f * y.max + z.min, col = col.grid, lty = lty.grid); i <- 0:y.max; segments(x.min + (i * yx.f), i * yz.f + z.min, x.max + (i * yx.f), i * yz.f + z.min, col = col.grid, lty = lty.grid); temp <- yx.f * y.max; temp1 <- yz.f * y.max; i <- (x.min + temp):(x.max + temp); segments(i, z.min + temp1, i, z.max + temp1, col = col.grid, lty = lty.grid); i <- (z.min + temp1):(z.max + temp1); segments(x.min + temp, i, x.max + temp, i, col = col.grid, lty = lty.grid) i <- xx[2]:x.min; mm <- z.min:z.max; segments(i, mm, i + temp, mm + temp1, col = col.grid, lty = lty.grid); i <- 0:y.max; segments(x.min + (i * yx.f), i * yz.f + z.min, xx[2] + (i * yx.f), i * yz.f + z.max, col = col.grid, lty = lty.grid) segments(x.min, z.min, x.min + (yx.f * y.max), yz.f * y.max + z.min, col = col.grid, lty = lty.hide); segments(x.max, z.min, x.max + (yx.f * y.max), yz.f * y.max + z.min, col = col.axis, lty = lty.hide); segments(x.min + (y.max * yx.f), y.max * yz.f + z.min, x.max + (y.max* yx.f), y.max * yz.f + z.min, col = col.grid, lty = lty.hide); segments(x.min + temp, z.min + temp1, x.min + temp, z.max + temp1, col = col.grid, lty = lty.hide); segments(x.max + temp, z.min + temp1, x.max + temp, z.max + temp1, col = col.axis, lty = lty.hide); segments(x.min + temp, z.max + temp1, x.max + temp, z.max + temp1, col = col.axis, lty = lty.hide); segments(xx[2], z.max, xx[2] + temp, z.max + temp1, col = col.axis, lty = lty.hide); } if(axis) { if(tick.marks) { xtl <- (z.max - z.min) * (tcl <- -par("tcl")) / 50 ztl <- (x.max - x.min) * tcl / 50 mysegs <- function(x0,y0, x1,y1) segments(x0,y0, x1,y1, col=col.axis, lty=lty.axis) i.y <- 0:y.max mysegs(yx.f * i.y - ztl + xx[1], yz.f * i.y + z.min, yx.f * i.y + ztl + xx[1], yz.f * i.y + z.min) i.x <- x.min:x.max mysegs(i.x, -xtl + z.min, i.x, xtl + z.min) i.z <- z.min:z.max mysegs(-ztl + xx[2], i.z, ztl + xx[2], i.z) if(label.tick.marks) { las <- par("las") mytext <- function(labels, side, at, ...) mtext(text = labels, side = side, at = at, line = -.5, col=col.lab, cex=cex.axis, font=font.lab, ...) if(is.null(x.ticklabs)) x.ticklabs <- format(i.x * x.scal) mytext(x.ticklabs, side = 1, at = i.x) if(is.null(z.ticklabs)) z.ticklabs <- format(i.z * z.scal) mytext(z.ticklabs, side = if(angle.1) 4 else 2, at = i.z, adj = if(0 < las && las < 3) 1 else NA) temp <- if(angle > 2) rev(i.y) else i.y if(is.null(y.ticklabs)) y.ticklabs <- format(y.prty) else if (angle > 2) y.ticklabs <- rev(y.ticklabs) text(i.y * yx.f + xx[1], i.y * yz.f + z.min, y.ticklabs, pos=if(angle.1) 2 else 4, offset=1, col=col.lab, cex=cex.axis/par("cex"), font=font.lab) } } mytext2 <- function(lab, side, line, at) mtext(lab, side = side, line = line, at = at, col = col.lab, cex = cex.lab, font = font.axis, las = 0) lines(c(x.min, x.max), c(z.min, z.min), col = col.axis, lty = lty.axis) mytext2(xlab, 1, line = 1.5, at = mean(x.range)) lines(xx[1] + c(0, y.max * yx.f), c(z.min, y.max * yz.f + z.min), col = col.axis, lty = lty.axis) mytext2(ylab, if(angle.1) 2 else 4, line= 0.5, at = z.min + y.max * yz.f) lines(xx[c(2,2)], c(z.min, z.max), col = col.axis, lty = lty.axis) mytext2(zlab, if(angle.1) 4 else 2, line= 1.5, at = mean(z.range)) } x <- dat$x + (dat$y * yx.f) z <- dat$z + (dat$y * yz.f) col <- as.character(dat$col) if(type == "h") { z2 <- dat$y * yz.f + z.min segments(x, z, x, z2, col = col, cex = cex.symbols, lty = lty.hplot, ...) points(x, z, type = "p", col = col, pch = pch, cex = cex.symbols, ...) } else points(x, z, type = type, col = col, pch = pch, cex = cex.symbols, ...) if(axis && box) { lines(c(x.min, x.max), c(z.max, z.max), col = col.axis, lty = lty.axis) lines(c(0, y.max * yx.f) + x.max, c(0, y.max * yz.f) + z.max, col = col.axis, lty = lty.axis) lines(xx[c(1,1)], c(z.min, z.max), col = col.axis, lty = lty.axis) } ob <- ls() rm(list = ob[!ob %in% c("angle", "mar", "usr", "x.scal", "y.scal", "z.scal", "yx.f", "yz.f", "y.add", "z.min", "z.max", "x.min", "x.max", "y.max", "x.prty", "y.prty", "z.prty")]) rm(ob) invisible(list( xyz.convert = function(x, y=NULL, z=NULL) { xyz <- xyz.coords(x, y, z) if(angle > 2) { temp <- xyz$x; xyz$x <- xyz$y; xyz$y <- temp } y <- (xyz$y - y.add) / y.scal return(list(x = xyz$x / x.scal + yx.f * y, y = xyz$z / z.scal + yz.f * y)) }, points3d = function(x, y = NULL, z = NULL, type = "p", ...) { xyz <- xyz.coords(x, y, z) if(angle > 2) { temp <- xyz$x; xyz$x <- xyz$y; xyz$y <- temp } y2 <- (xyz$y - y.add) / y.scal x <- xyz$x / x.scal + yx.f * y2 y <- xyz$z / z.scal + yz.f * y2 mem.par <- par(mar = mar, usr = usr) on.exit(par(mem.par)) if(type == "h") { y2 <- z.min + yz.f * y2 segments(x, y, x, y2, ...) points(x, y, type = "p", ...) } else points(x, y, type = type, ...) }, plane3d = function(Intercept, x.coef = NULL, y.coef = NULL, lty = "dashed", lty.box = NULL, ...){ if(!is.atomic(Intercept) && !is.null(coef(Intercept))) Intercept <- coef(Intercept) if(is.null(lty.box)) lty.box <- lty if(is.null(x.coef) && length(Intercept) == 3){ x.coef <- Intercept[if(angle > 2) 3 else 2] y.coef <- Intercept[if(angle > 2) 2 else 3] Intercept <- Intercept[1] } mem.par <- par(mar = mar, usr = usr) on.exit(par(mem.par)) x <- x.min:x.max ltya <- c(lty.box, rep(lty, length(x)-2), lty.box) x.coef <- x.coef * x.scal z1 <- (Intercept + x * x.coef + y.add * y.coef) / z.scal z2 <- (Intercept + x * x.coef + (y.max * y.scal + y.add) * y.coef) / z.scal segments(x, z1, x + y.max * yx.f, z2 + yz.f * y.max, lty = ltya, ...) y <- 0:y.max ltya <- c(lty.box, rep(lty, length(y)-2), lty.box) y.coef <- (y * y.scal + y.add) * y.coef z1 <- (Intercept + x.min * x.coef + y.coef) / z.scal z2 <- (Intercept + x.max * x.coef + y.coef) / z.scal segments(x.min + y * yx.f, z1 + y * yz.f, x.max + y * yx.f, z2 + y * yz.f, lty = ltya, ...) }, wall3d = function(Intercept, x.coef = NULL, y.coef = NULL, lty = "dashed", lty.box = NULL, ...){ if(!is.atomic(Intercept) && !is.null(coef(Intercept))) Intercept <- coef(Intercept) if(is.null(lty.box)) lty.box <- lty if(is.null(x.coef) && length(Intercept) == 3){ x.coef <- Intercept[if(angle > 2) 3 else 2] y.coef <- Intercept[if(angle > 2) 2 else 3] Intercept <- Intercept[1] } mem.par <- par(mar = mar, usr = usr) on.exit(par(mem.par)) x <- x.min:x.max ltya <- c(lty.box, rep(lty, length(x)-2), lty.box) x.coef <- x.coef * x.scal z1 <- (Intercept + x * x.coef + y.add * y.coef) / z.scal z2 <- (Intercept + x * x.coef + (y.max * y.scal + y.add) * y.coef) / z.scal segments(x, z1, x + y.max * yx.f, z2 + yz.f * y.max, lty = ltya, ...) y <- 0:y.max ltya <- c(lty.box, rep(lty, length(y)-2), lty.box) y.coef <- (y * y.scal + y.add) * y.coef z1 <- (Intercept + x.min * x.coef + y.coef) / z.scal z2 <- (Intercept + x.max * x.coef + y.coef) / z.scal segments(x.min + y * yx.f, z1 + y * yz.f, x.max + y * yx.f, z2 + y * yz.f, lty = ltya, ...) }, box3d = function(...){ mem.par <- par(mar = mar, usr = usr) on.exit(par(mem.par)) lines(c(x.min, x.max), c(z.max, z.max), ...) lines(c(0, y.max * yx.f) + x.max, c(0, y.max * yz.f) + z.max, ...) lines(c(0, y.max * yx.f) + x.min, c(0, y.max * yz.f) + z.max, ...) lines(c(x.max, x.max), c(z.min, z.max), ...) lines(c(x.min, x.min), c(z.min, z.max), ...) lines(c(x.min, x.max), c(z.min, z.min), ...) } )) }
updateableInput <- function(inputType) { function(...) { shinyFuncName <- as.character(as.list(match.call()[1])) shinyFunc <- get(shinyFuncName, envir = as.environment("package:shiny")) shiny::tagAppendAttributes( shinyFunc(...), `data-input-type` = inputType ) } } textInput <- updateableInput("Text") numericInput <- updateableInput("Numeric") selectInput <- updateableInput("Select") updateShinyInput <- function(session, id, value) { shinyUpdateInputId <- paste0("shiny-update-input-", id) js$getInputType(id, shinyUpdateInputId) shiny::observeEvent(session$input[[shinyUpdateInputId]], { inputType <- session$input[[shinyUpdateInputId]] updateFunc <- sprintf("update%sInput", inputType) funcParams <- list(session = session, inputId = id) if (inputType == "Select") { funcParams[['selected']] <- value } else { funcParams[['value']] <- value } do.call(updateFunc, funcParams) }) } updateShinyInputs <- function(session, updates) { lapply(names(updates), function(id) { updateShinyInput(session, id, updates[[id]]) }) }
MINTknown=function(x,y,k,ky,w=FALSE,wy=FALSE,y0){ n=dim(cbind(x,y))[1] B=dim(as.matrix(y0))[1]%/%n nullstat=rep(0,B) for(b in 1:B){ yb=as.matrix(y0)[((b-1)*n+1):(b*n),] nullstat[b]=KLentropy(yb,k=ky,weights=wy)[[2]]-KLentropy(cbind(x,yb),k=k,weights=w)[[2]] } data=cbind(x,y) stat=KLentropy(y,k=ky,weights=wy)[[2]]-KLentropy(data,k=k,weights=w)[[2]] p=(1+sum(nullstat>=stat))/(B+1) return(p) }
library(BoomSpikeSlab) library(testthat) require(MASS) set.seed(31417) cat("test-probit\n") test_that("random seed gives repeatability", { n <- 100 niter <- 1000 x <- rnorm(n) beta0 <- -3 beta1 <- 1 probits <- beta0 + beta1*x probabilities <- pnorm(probits) y <- as.numeric(runif(n) <= probabilities) model1 <- probit.spike(y ~ x, niter = niter, expected.model.size = 3, seed = 31417, ping = -1) model2 <- probit.spike(y ~ x, niter = niter, expected.model.size = 3, seed = 31417, ping = -1) expect_equal(model1$beta, model2$beta) model1 <- probit.spike(y ~ x, niter = niter, seed = 31417, ping = -1) model2 <- probit.spike(y ~ x, niter = niter, seed = 31417, ping = -1) expect_equal(model1$beta, model2$beta) }) test_that("Pima Indians", { if (requireNamespace("MASS")) { data(Pima.tr, package = "MASS") data(Pima.te, package = "MASS") pima <- rbind(Pima.tr, Pima.te) niter <- 1000 sample.size <- nrow(pima) m <- probit.spike(type == "Yes" ~ ., data = pima, niter = niter, seed = 31417, ping = -1) expect_true(!is.null(m$beta)) expect_true(is.matrix(m$beta)) expect_equal(dim(m$beta), c(1000, 8)) expect_equal(length(m$fitted.probabilities), sample.size) expect_equal(length(m$fitted.probits), sample.size) expect_equal(length(m$deviance.residuals), sample.size) expect_equal(length(m$log.likelihood), niter, ping = -1) expect_true(!is.null(m$prior)) m.summary <- summary(m) expect_true(!is.null(m.summary$coefficients)) expect_true(is.matrix(m.summary$predicted.vs.actual)) expect_equal(ncol(m.summary$predicted.vs.actual), 2) expect_equal(nrow(m.summary$predicted.vs.actual), 10) expect_equal(length(m.summary$deviance.r2.distribution), 1000) expect_equal(length(m.summary$deviance.r2), 1) expect_true(is.numeric(m.summary$deviance.r2)) expect_true(m.summary$max.log.likelihood >= m.summary$mean.log.likelihood) expect_true(m.summary$max.log.likelihood > m.summary$null.log.likelihood) m <- probit.spike(type == "Yes" ~ ., data = Pima.tr, niter = niter, seed = 31417, ping = -1) predictions <- predict(m, newdata = Pima.te) } }) test_that("probit works with small number of cases", { x <- matrix(rnorm(45), ncol = 9) x <- cbind(1, x) y <- rep(FALSE, nrow(x)) expect_warning( m <- probit.spike(y ~ x, niter = 100, seed = 31417), "Fudging around the fact that prior.success.probability is zero. Setting it to 0.14286") })
d2th_dmu2_mk <- function(fml){ switch(fml, binomial = function(mu, mi) 1 / (mi - mu)^2 - 1 / mu^2, poisson = function(mu, mi) - 1 / mu^2, Gamma = function(mu, mi) - 2 / mu^3, inverse.gaussian = function(mu, mi) - 3 / mu^4 ) }
suppressMessages(library("caret")) suppressMessages(library("mlbench")) suppressMessages(library("pROC")) library("caret") library("mlbench") library("pROC") data(Sonar) set.seed(107) inTrain <- createDataPartition(y = Sonar$Class, p = .75, list = FALSE) training <- Sonar[ inTrain,] testing <- Sonar[-inTrain,] my_control <- trainControl( method="boot", number=25, savePredictions="final", classProbs=TRUE, index=createResample(training$Class, 25), summaryFunction=twoClassSummary ) library("rpart") library("caretEnsemble") model_list <- caretList( Class~., data=training, trControl=my_control, methodList=c("glm", "rpart") ) p <- as.data.frame(predict(model_list, newdata=head(testing))) print(p) knitr::kable(p) suppressMessages(library("mlbench")) suppressMessages(library("randomForest")) suppressMessages(library("nnet")) library("mlbench") library("randomForest") library("nnet") model_list_big <- caretList( Class~., data=training, trControl=my_control, metric="ROC", methodList=c("glm", "rpart"), tuneList=list( rf1=caretModelSpec(method="rf", tuneGrid=data.frame(.mtry=2)), rf2=caretModelSpec(method="rf", tuneGrid=data.frame(.mtry=10), preProcess="pca"), nn=caretModelSpec(method="nnet", tuneLength=2, trace=FALSE) ) ) xyplot(resamples(model_list)) modelCor(resamples(model_list)) greedy_ensemble <- caretEnsemble( model_list, metric="ROC", trControl=trainControl( number=2, summaryFunction=twoClassSummary, classProbs=TRUE )) summary(greedy_ensemble) library("caTools") model_preds <- lapply(model_list, predict, newdata=testing, type="prob") model_preds <- lapply(model_preds, function(x) x[,"M"]) model_preds <- data.frame(model_preds) ens_preds <- predict(greedy_ensemble, newdata=testing, type="prob") model_preds$ensemble <- ens_preds caTools::colAUC(model_preds, testing$Class) varImp(greedy_ensemble) knitr::kable(varImp(greedy_ensemble)) glm_ensemble <- caretStack( model_list, method="glm", metric="ROC", trControl=trainControl( method="boot", number=10, savePredictions="final", classProbs=TRUE, summaryFunction=twoClassSummary ) ) model_preds2 <- model_preds model_preds2$ensemble <- predict(glm_ensemble, newdata=testing, type="prob") CF <- coef(glm_ensemble$ens_model$finalModel)[-1] colAUC(model_preds2, testing$Class) CF/sum(CF) suppressMessages(library("gbm")) suppressMessages(library("plyr")) library("gbm") gbm_ensemble <- caretStack( model_list, method="gbm", verbose=FALSE, tuneLength=10, metric="ROC", trControl=trainControl( method="boot", number=10, savePredictions="final", classProbs=TRUE, summaryFunction=twoClassSummary ) ) model_preds3 <- model_preds model_preds3$ensemble <- predict(gbm_ensemble, newdata=testing, type="prob") colAUC(model_preds3, testing$Class)
NULL decisionSupport <- function(inputFilePath, outputPath, welfareFunction, numberOfModelRuns, randomMethod="calculate", functionSyntax="data.frameNames", relativeTolerance=0.05, write_table=TRUE, plsrVipAnalysis=TRUE, individualEvpiNames=NULL, sortEvpiAlong=if(individualEvpiNames) individualEvpiNames[[1]] else NULL, oldInputStandard=FALSE, verbosity=1){ if(!oldInputStandard){ estimateObject<-estimate_read_csv(fileName=inputFilePath) }else{ estimateObject<-estimate_read_csv_old(fileName=inputFilePath) } if(verbosity > 0) cat("Estimate read from file: ",inputFilePath, "\n") if(verbosity > 1) print(estimateObject) if ( !file.exists(outputPath) ) dir.create(outputPath, recursive=TRUE) if(verbosity > 0) cat("Performing Monte Carlo Simulation for the Welfare Decision Analysis:\n") welfareDecisionResults<-welfareDecisionAnalysis(estimate=estimateObject, welfare=welfareFunction, numberOfModelRuns=numberOfModelRuns, randomMethod=randomMethod, functionSyntax=functionSyntax, relativeTolerance=relativeTolerance, verbosity=verbosity) if(verbosity > 0) cat("Monte Carlo Simulation for Welfare Decision Analysis done.\n") if(verbosity > 1){ print(summary(welfareDecisionResults$mcResult)) print(summary(welfareDecisionResults)) } if (write_table){ mcSimulationResultsFilePath<-file.path(outputPath, "mcSimulationResults.csv") write.csv(data.frame(welfareDecisionResults$mcResult$x,welfareDecisionResults$mcResult$y), mcSimulationResultsFilePath) if (verbosity > 0) cat("Monte Carlo results written into file: ", mcSimulationResultsFilePath, "\n") } for(i in names(welfareDecisionResults$mcResult$y)) { png(file.path(outputPath, paste(i, "_distribution.png",sep="")), width=1000, height=500) par(mar=c(5.1,5.1,4.1,2.1)) hist(welfareDecisionResults$mcResult, lwd=3, cex.lab=2 ,cex.axis=2, prob=FALSE, resultName=i) dev.off() } mcSummary<-summary(welfareDecisionResults$mcResult, digits=2) mcSimulationSummaryFilePath<-file.path(outputPath,"mcSummary.csv") write.csv(mcSummary$summary,mcSimulationSummaryFilePath) if (verbosity > 0) cat("Monte Carlo summary written into file: ", mcSimulationSummaryFilePath, "\n") welfareDecisionSummary<-summary(welfareDecisionResults, digits=2) welfareDecisionSummaryFilePath<-file.path(outputPath,"welfareDecisionSummary.csv") write.csv(welfareDecisionSummary$summary,welfareDecisionSummaryFilePath) if (verbosity > 0) cat("Welfare Decision Analysis summary written into file: ", welfareDecisionSummaryFilePath, "\n") if(plsrVipAnalysis){ if (!requireNamespace("chillR", quietly = TRUE)) stop("Package \"chillR\" needed. Please install it.", call. = FALSE) for(i in names(welfareDecisionResults$mcResult$y)) { plsrResult<-plsr.mcSimulation(welfareDecisionResults$mcResult, resultName=i) vipResult<-chillR::VIP(plsrResult)["Comp 1",] coef<-plsrResult$coefficients[,,1] color_bars<-chillR::color_bar_maker(vipResult, coef, threshold=0.8, col1="RED", col2="DARK GREEN", col3="DARK GREY") vipResult_select<-vipResult[order(vipResult,decreasing=TRUE)[1:50]] if(length(vipResult)<50) vipResult_select<-vipResult_select[1:length(vipResult)] col_select<-color_bars[order(vipResult,decreasing=TRUE)[1:50]] if(length(vipResult)<50) col_select<-col_select[1:length(vipResult)] png(file.path(outputPath, paste(i, "_PLS_VIP.png",sep="")),height=1400,width=1400) par(mar=c(5.1,55,4.1,2.1)) barplot(rev(vipResult_select),horiz=TRUE,las=1,col=rev(col_select),cex.names=2,cex.axis=1,main="VIP for most important variables",cex.main=2,axes=FALSE) axis(side=1,cex.axis=2,lwd=5,padj=0.7) abline(v=0.8,lwd=3) dev.off() if (write_table){ vipPlsResultTable<-cbind(vipResult,coef) colnames(vipPlsResultTable)<-c("VIP","Coefficient") write.csv(vipPlsResultTable,file.path(outputPath, paste(i,"_pls_results.csv",sep=""))) } } if (verbosity > 0) cat("VIP PLSR results written into directory: ", outputPath, "\n") } if (!is.null(individualEvpiNames)){ if( !is.character(individualEvpiNames) ) stop("\"individualEvpiNames\" must be a character vector.") else if( any(!individualEvpiNames %in% row.names(estimateObject)) ){ if( individualEvpiNames!="all") stop("\"individualEvpiNames\" must be a subset of variables defined in file \",inputFilePath\" or =\"all\".") else individualEvpiNames=row.names(estimateObject) } if(verbosity > 0) cat("Performing Monte Carlo Simulation(s) for the IndividualEVPI Calculation(s):\n") individualEvpiResults<-individualEvpiSimulation(welfare=welfareFunction, currentEstimate=estimateObject, perfectProspectiveNames=individualEvpiNames, numberOfModelRuns=numberOfModelRuns, randomMethod=randomMethod, functionSyntax=functionSyntax, relativeTolerance=relativeTolerance, verbosity=verbosity) if (verbosity > 1) print(sort(summary(individualEvpiResults))) individualEvpiSimulationSummaryFilePath<-file.path(outputPath,"individualEvpiSummary.csv") write.csv(sort(summary(individualEvpiResults), along=sortEvpiAlong)$summary$evi, individualEvpiSimulationSummaryFilePath) if (verbosity > 0) cat("IndividualEVPI simulation summary written into file: ", individualEvpiSimulationSummaryFilePath, "\n") } }
read.bif = function(file, debug = FALSE) { lines = readLines(file) read.foreign.backend(lines, format = "bif", filename = file, debug = debug) } write.bif = function(file, fitted) { check.fit(fitted) if (!is(fitted, c("bn.fit.dnet", "bn.fit.onet", "bn.fit.donet"))) stop("only discrete Bayesian networks can be exported into BIF format.") fd = file(description = file, open = "w") write.foreign.backend(fd, fitted = fitted, format = "bif") close(fd) invisible(NULL) } read.dsc = function(file, debug = FALSE) { lines = readLines(file) read.foreign.backend(lines, format = "dsc", filename = file, debug = debug) } write.dsc = function(file, fitted) { check.fit(fitted) if (!is(fitted, c("bn.fit.dnet", "bn.fit.onet", "bn.fit.donet"))) stop("only discrete Bayesian networks can be exported into DSC format.") fd = file(description = file, open = "w") write.foreign.backend(fd, fitted = fitted, format = "dsc") close(fd) invisible(NULL) } read.net = function(file, debug = FALSE) { lines = readLines(file) read.foreign.backend(lines, format = "net", filename = file, debug = debug) } write.net = function(file, fitted) { check.fit(fitted) if (!is(fitted, c("bn.fit.dnet", "bn.fit.onet", "bn.fit.donet"))) stop("only discrete Bayesian networks can be exported into DSC format.") fd = file(description = file, open = "w") write.foreign.backend(fd, fitted = fitted, format = "net") close(fd) invisible(NULL) } write.dot = function(file, graph) { check.bn.or.fit(graph) fd = file(description = file, open = "w") write.dot.backend(fd, graph = graph) close(fd) invisible(NULL) }
library(gpuR) context("Switching GPU vclMatrixBlock algebra") if(detectGPUs() >= 1){ current_context <- set_device_context("gpu") }else{ current_context <- currentContext() } set.seed(123) ORDER <- 4 Aint <- matrix(sample(seq(10), ORDER^2, replace=TRUE), nrow=ORDER, ncol=ORDER) Bint <- matrix(sample(seq(10), ORDER^2, replace=TRUE), nrow=ORDER, ncol=ORDER) A <- matrix(rnorm(ORDER^2), nrow=ORDER, ncol=ORDER) B <- matrix(rnorm(ORDER^2), nrow=ORDER, ncol=ORDER) E <- matrix(rnorm(15), nrow=5) test_that("Switching GPU vclMatrixBlock Single Precision Block Matrix multiplication", { has_multiple_gpu_skip() AS = A[2:4, 2:4] BS = B[2:4, 2:4] C <- AS %*% BS setContext(2L) fvclA <- vclMatrix(A, type="float") fvclB <- vclMatrix(B, type="float") setContext(1L) fvclAS <- block(fvclA, 2L,4L,2L,4L) fvclBS <- block(fvclB, 2L,4L,2L,4L) fvclC <- fvclAS %*% fvclBS expect_is(fvclC, "fvclMatrix") expect_equal(fvclC[,], C, tolerance=1e-07, info="float matrix elements not equivalent") expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Single Precision Matrix Subtraction", { has_multiple_gpu_skip() AS = A[2:4, 2:4] BS = B[2:4, 2:4] C <- AS - BS setContext(2L) fvclA <- vclMatrix(A, type="float") fvclB <- vclMatrix(B, type="float") setContext(1L) fvclAS <- block(fvclA, 2L,4L,2L,4L) fvclBS <- block(fvclB, 2L,4L,2L,4L) fvclE <- block(fvclA, 1L,4L,2L,4L) fvclC <- fvclAS - fvclBS expect_is(fvclC, "fvclMatrix") expect_equal(fvclC[,], C, tolerance=1e-07, info="float matrix elements not equivalent") expect_error(fvclAS - fvclE) expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Single Precision Scalar Matrix Subtraction", { has_multiple_gpu_skip() AS = A[2:4, 2:4] C <- AS - 1 C2 <- 1 - AS setContext(2L) fvclA <- vclMatrix(A, type="float") fvclAS <- block(fvclA, 2L,4L,2L,4L) setContext(1L) fvclC <- fvclAS - 1 fvclC2 <- 1 - fvclAS expect_is(fvclC, "fvclMatrix") expect_equal(fvclC[,], C, tolerance=1e-07, info="float matrix elements not equivalent") expect_is(fvclC2, "fvclMatrix") expect_equal(fvclC2[,], C2, tolerance=1e-07, info="float matrix elements not equivalent") expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Single Precision Unary Scalar Matrix Subtraction", { has_multiple_gpu_skip() AS = A[2:4, 2:4] C <- -AS setContext(2L) fvclA <- vclMatrix(A, type="float") setContext(1L) fvclAS <- block(fvclA, 2L,4L,2L,4L) fvclC <- -fvclAS expect_is(fvclC, "fvclMatrix") expect_equal(fvclC[,], C, tolerance=1e-07, info="float matrix elements not equivalent") expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Single Precision Matrix Addition", { has_multiple_gpu_skip() AS = A[2:4, 2:4] BS = B[2:4, 2:4] C <- AS + BS setContext(2L) fvclA <- vclMatrix(A, type="float") fvclB <- vclMatrix(B, type="float") setContext(1L) fvclAS <- block(fvclA, 2L,4L,2L,4L) fvclBS <- block(fvclB, 2L,4L,2L,4L) fvclE <- block(fvclA, 1L,4L,2L,4L) fvclC <- fvclAS + fvclBS expect_is(fvclC, "fvclMatrix") expect_equal(fvclC[,], C, tolerance=1e-07, info="float matrix elements not equivalent") expect_error(fvclA + fvclE) expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Single Precision Scalar Matrix Addition", { has_multiple_gpu_skip() AS = A[2:4, 2:4] C <- AS + 1 C2 <- 1 + AS setContext(2L) fvclA <- vclMatrix(A, type="float") setContext(1L) fvclAS <- block(fvclA, 2L,4L,2L,4L) fvclC <- fvclAS + 1 fvclC2 <- 1 + fvclAS expect_is(fvclC, "fvclMatrix") expect_equal(fvclC[,], C, tolerance=1e-07, info="float matrix elements not equivalent") expect_is(fvclC2, "fvclMatrix") expect_equal(fvclC2[,], C2, tolerance=1e-07, info="float matrix elements not equivalent") expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Single Precision Matrix Element-Wise Multiplication", { has_multiple_gpu_skip() AS = A[2:4, 2:4] BS = B[2:4, 2:4] C <- AS * BS setContext(2L) fvclA <- vclMatrix(A, type="float") fvclB <- vclMatrix(B, type="float") setContext(1L) fvclAS <- block(fvclA, 2L,4L,2L,4L) fvclBS <- block(fvclB, 2L,4L,2L,4L) fvclC <- fvclAS * fvclBS expect_is(fvclC, "fvclMatrix") expect_equal(fvclC[,], C, tolerance=1e-07, info="float matrix elements not equivalent") expect_error(fvclA * fvclE) expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Single Precision Scalar Matrix Multiplication", { has_multiple_gpu_skip() AS = A[2:4, 2:4] C <- AS * 2 C2 <- 2 * AS setContext(2L) fvclA <- vclMatrix(A, type="float") fvclAS <- block(fvclA, 2L,4L,2L,4L) setContext(1L) fvclC <- fvclAS * 2 fvclC2 <- 2 * fvclAS expect_is(fvclC, "fvclMatrix") expect_equal(fvclC[,], C, tolerance=1e-07, info="float matrix elements not equivalent") expect_is(fvclC2, "fvclMatrix") expect_equal(fvclC2[,], C2, tolerance=1e-07, info="float matrix elements not equivalent") expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Single Precision Matrix Element-Wise Division", { has_multiple_gpu_skip() AS = A[2:4, 2:4] BS = B[2:4, 2:4] C <- AS / BS setContext(2L) fvclA <- vclMatrix(A, type="float") fvclB <- vclMatrix(B, type="float") setContext(1L) fvclAS <- block(fvclA, 2L,4L,2L,4L) fvclBS <- block(fvclB, 2L,4L,2L,4L) fvclE <- block(fvclA, 1L,4L,2L,4L) fvclC <- fvclAS / fvclBS expect_is(fvclC, "fvclMatrix") expect_equal(fvclC[,], C, tolerance=1e-07, info="float matrix elements not equivalent") expect_error(fvclA / fvclE) expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Single Precision Scalar Matrix Division", { has_multiple_gpu_skip() AS = A[2:4, 2:4] C <- AS/2 C2 <- 2/AS setContext(2L) fvclA <- vclMatrix(A, type="float") setContext(1L) fvclAS <- block(fvclA, 2L,4L,2L,4L) fvclC <- fvclAS/2 fvclC2 <- 2/fvclAS expect_is(fvclC, "fvclMatrix") expect_equal(fvclC[,], C, tolerance=1e-07, info="float matrix elements not equivalent") expect_is(fvclC2, "fvclMatrix") expect_equal(fvclC2[,], C2, tolerance=1e-07, info="float matrix elements not equivalent") expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Single Precision Matrix Element-Wise Power", { has_multiple_gpu_skip() AS = A[2:4, 2:4] BS = B[2:4, 2:4] C <- AS ^ BS setContext(2L) fvclA <- vclMatrix(A, type="float") fvclB <- vclMatrix(B, type="float") setContext(1L) fvclAS <- block(fvclA, 2L,4L,2L,4L) fvclBS <- block(fvclB, 2L,4L,2L,4L) fvclE <- block(fvclA, 1L,4L,2L,4L) fvclC <- fvclAS ^ fvclBS expect_is(fvclC, "fvclMatrix") expect_equal(fvclC[,], C, tolerance=1e-07, info="float matrix elements not equivalent") expect_error(fvclA ^ fvclE) expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Single Precision Scalar Matrix Power", { has_multiple_gpu_skip() AS = A[2:4, 2:4] C <- AS^2 setContext(2L) fvclA <- vclMatrix(A, type="float") setContext(1L) fvclAS <- block(fvclA, 2L,4L,2L,4L) fvclC <- fvclAS^2 expect_is(fvclC, "fvclMatrix") expect_equal(fvclC[,], C, tolerance=1e-07, info="float matrix elements not equivalent") expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Single Precision crossprod", { has_multiple_gpu_skip() X <- matrix(rnorm(10), nrow=2) Y <- matrix(rnorm(10), nrow=2) Z <- matrix(rnorm(10), nrow=5) XS = X[1:2, 2:5] YS = Y[1:2, 2:5] ZS = Z[2:5, 1:2] C <- crossprod(XS,YS) Cs <- crossprod(XS) setContext(2L) fvclX <- vclMatrix(X, type="float") fvclY <- vclMatrix(Y, type="float") fvclZ <- vclMatrix(Z, type="float") setContext(1L) fvclXS <- block(fvclX, 1L,2L,2L,5L) fvclYS <- block(fvclY, 1L,2L,2L,5L) fvclZS <- block(fvclZ, 2L,5L,1L,2L) fvclC <- crossprod(fvclXS, fvclYS) fvclCs <- crossprod(fvclXS) expect_is(fvclC, "fvclMatrix") expect_equal(fvclC[,], C, tolerance=1e-07, info="float matrix elements not equivalent") expect_equal(fvclCs[,], Cs, tolerance=1e-07, info="float matrix elements not equivalent") expect_error(crossprod(fvclXS, fvclZS)) expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Single Precision tcrossprod", { has_multiple_gpu_skip() X <- matrix(rnorm(10), nrow=2) Y <- matrix(rnorm(10), nrow=2) Z <- matrix(rnorm(10), nrow=5) XS = X[1:2, 2:5] YS = Y[1:2, 2:5] ZS = Z[2:5, 1:2] C <- tcrossprod(XS,YS) Cs <- tcrossprod(XS) setContext(2L) fvclX <- vclMatrix(X, type="float") fvclY <- vclMatrix(Y, type="float") fvclZ <- vclMatrix(Z, type="float") setContext(1L) fvclXS <- block(fvclX, 1L,2L,2L,5L) fvclYS <- block(fvclY, 1L,2L,2L,5L) fvclZS <- block(fvclZ, 2L,5L,1L,2L) fvclC <- tcrossprod(fvclXS, fvclYS) fvclCs <- tcrossprod(fvclXS) expect_is(fvclC, "fvclMatrix") expect_equal(fvclC[,], C, tolerance=1e-07, info="float matrix elements not equivalent") expect_equal(fvclCs[,], Cs, tolerance=1e-06, info="float matrix elements not equivalent") expect_error(crossprod(fvclXS, fvclZS)) expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Double Precision Block Matrix multiplication", { has_multiple_gpu_skip() has_multiple_double_skip() AS = A[2:4, 2:4] BS = B[2:4, 2:4] C <- AS %*% BS setContext(2L) dvclA <- vclMatrix(A, type="double") dvclB <- vclMatrix(B, type="double") setContext(1L) dvclAS <- block(dvclA, 2L,4L,2L,4L) dvclBS <- block(dvclB, 2L,4L,2L,4L) dvclC <- dvclAS %*% dvclBS expect_is(dvclC, "dvclMatrix") expect_equal(dvclC[,], C, tolerance=.Machine$double.eps ^ 0.5, info="double matrix elements not equivalent") expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Double Precision Matrix Subtraction", { has_multiple_gpu_skip() has_multiple_double_skip() AS = A[2:4, 2:4] BS = B[2:4, 2:4] C <- AS - BS setContext(2L) dvclA <- vclMatrix(A, type="double") dvclB <- vclMatrix(B, type="double") setContext(1L) dvclAS <- block(dvclA, 2L,4L,2L,4L) dvclBS <- block(dvclB, 2L,4L,2L,4L) dvclE <- block(dvclA, 1L,4L,2L,4L) dvclC <- dvclAS - dvclBS expect_is(dvclC, "dvclMatrix") expect_equal(dvclC[,], C, tolerance=.Machine$double.eps ^ 0.5, info="double matrix elements not equivalent") expect_error(dvclAS - dvclE) expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Double Precision Scalar Matrix Subtraction", { has_multiple_gpu_skip() has_multiple_double_skip() AS = A[2:4, 2:4] C <- AS - 1 C2 <- 1 - AS setContext(2L) dvclA <- vclMatrix(A, type="double") setContext(1L) dvclAS <- block(dvclA, 2L,4L,2L,4L) dvclC <- dvclAS - 1 dvclC2 <- 1 - dvclAS expect_is(dvclC, "dvclMatrix") expect_equal(dvclC[,], C, tolerance=.Machine$double.eps ^ 0.5, info="double matrix elements not equivalent") expect_is(dvclC2, "dvclMatrix") expect_equal(dvclC2[,], C2, tolerance=.Machine$double.eps ^ 0.5, info="double matrix elements not equivalent") expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Double Precision Unary Scalar Matrix Subtraction", { has_multiple_gpu_skip() has_multiple_double_skip() AS = A[2:4, 2:4] C <- -AS setContext(2L) dvclA <- vclMatrix(A, type="double") setContext(1L) dvclAS <- block(dvclA, 2L,4L,2L,4L) dvclC <- -dvclAS expect_is(dvclC, "dvclMatrix") expect_equal(dvclC[,], C, tolerance=.Machine$double.eps ^ 0.5, info="double matrix elements not equivalent") expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Double Precision Matrix Addition", { has_multiple_gpu_skip() has_multiple_double_skip() AS = A[2:4, 2:4] BS = B[2:4, 2:4] C <- AS + BS setContext(2L) dvclA <- vclMatrix(A, type="double") dvclB <- vclMatrix(B, type="double") setContext(1L) dvclAS <- block(dvclA, 2L,4L,2L,4L) dvclBS <- block(dvclB, 2L,4L,2L,4L) dvclE <- block(dvclA, 1L,4L,2L,4L) dvclC <- dvclAS + dvclBS expect_is(dvclC, "dvclMatrix") expect_equal(dvclC[,], C, tolerance=.Machine$double.eps ^ 0.5, info="double matrix elements not equivalent") expect_error(dvclA + dvclE) expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Double Precision Scalar Matrix Addition", { has_multiple_gpu_skip() has_multiple_double_skip() AS = A[2:4, 2:4] C <- AS + 1 C2 <- 1 + AS setContext(2L) dvclA <- vclMatrix(A, type="double") setContext(1L) dvclAS <- block(dvclA, 2L,4L,2L,4L) dvclC <- dvclAS + 1 dvclC2 <- 1 + dvclAS expect_is(dvclC, "dvclMatrix") expect_equal(dvclC[,], C, tolerance=.Machine$double.eps ^ 0.5, info="double matrix elements not equivalent") expect_is(dvclC2, "dvclMatrix") expect_equal(dvclC2[,], C2, tolerance=.Machine$double.eps ^ 0.5, info="double matrix elements not equivalent") expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Double Precision Matrix Element-Wise Multiplication", { has_multiple_gpu_skip() has_multiple_double_skip() AS = A[2:4, 2:4] BS = B[2:4, 2:4] C <- AS * BS setContext(2L) dvclA <- vclMatrix(A, type="double") dvclB <- vclMatrix(B, type="double") setContext(1L) dvclAS <- block(dvclA, 2L,4L,2L,4L) dvclBS <- block(dvclB, 2L,4L,2L,4L) dvclC <- dvclAS * dvclBS expect_is(dvclC, "dvclMatrix") expect_equal(dvclC[,], C, tolerance=.Machine$double.eps ^ 0.5, info="double matrix elements not equivalent") expect_error(dvclA * dvclE) expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Double Precision Scalar Matrix Multiplication", { has_multiple_gpu_skip() has_multiple_double_skip() AS = A[2:4, 2:4] C <- AS * 2 C2 <- 2 * AS setContext(2L) dvclA <- vclMatrix(A, type="double") setContext(1L) dvclAS <- block(dvclA, 2L,4L,2L,4L) dvclC <- dvclAS * 2 dvclC2 <- 2 * dvclAS expect_is(dvclC, "dvclMatrix") expect_equal(dvclC[,], C, tolerance=.Machine$double.eps ^ 0.5, info="double matrix elements not equivalent") expect_is(dvclC2, "dvclMatrix") expect_equal(dvclC2[,], C2, tolerance=.Machine$double.eps ^ 0.5, info="double matrix elements not equivalent") expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Double Precision Matrix Element-Wise Division", { has_multiple_gpu_skip() has_multiple_double_skip() AS = A[2:4, 2:4] BS = B[2:4, 2:4] C <- AS / BS setContext(2L) dvclA <- vclMatrix(A, type="double") dvclB <- vclMatrix(B, type="double") setContext(1L) dvclAS <- block(dvclA, 2L,4L,2L,4L) dvclBS <- block(dvclB, 2L,4L,2L,4L) dvclE <- block(dvclA, 1L,4L,2L,4L) dvclC <- dvclAS / dvclBS expect_is(dvclC, "dvclMatrix") expect_equal(dvclC[,], C, tolerance=.Machine$double.eps ^ 0.5, info="double matrix elements not equivalent") expect_error(dvclA / dvclE) expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Double Precision Scalar Matrix Division", { has_multiple_gpu_skip() has_multiple_double_skip() AS = A[2:4, 2:4] C <- AS/2 C2 <- 2/AS setContext(2L) dvclA <- vclMatrix(A, type="double") setContext(1L) dvclAS <- block(dvclA, 2L,4L,2L,4L) dvclC <- dvclAS/2 dvclC2 <- 2/dvclAS expect_is(dvclC, "dvclMatrix") expect_equal(dvclC[,], C, tolerance=.Machine$double.eps ^ 0.5, info="double matrix elements not equivalent") expect_is(dvclC2, "dvclMatrix") expect_equal(dvclC2[,], C2, tolerance=.Machine$double.eps ^ 0.5, info="double matrix elements not equivalent") expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Double Precision Matrix Element-Wise Power", { has_multiple_gpu_skip() has_multiple_double_skip() AS = A[2:4, 2:4] BS = B[2:4, 2:4] C <- AS ^ BS setContext(2L) dvclA <- vclMatrix(A, type="double") dvclB <- vclMatrix(B, type="double") setContext(1L) dvclAS <- block(dvclA, 2L,4L,2L,4L) dvclBS <- block(dvclB, 2L,4L,2L,4L) dvclE <- block(dvclA, 1L,4L,2L,4L) dvclC <- dvclAS ^ dvclBS expect_is(dvclC, "dvclMatrix") expect_equal(dvclC[,], C, tolerance=.Machine$double.eps ^ 0.5, info="double matrix elements not equivalent") expect_error(dvclA ^ dvclE) expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Double Precision Scalar Matrix Power", { has_multiple_gpu_skip() has_multiple_double_skip() AS = A[2:4, 2:4] C <- AS^2 setContext(2L) dvclA <- vclMatrix(A, type="double") setContext(1L) dvclAS <- block(dvclA, 2L,4L,2L,4L) dvclC <- dvclAS^2 expect_is(dvclC, "dvclMatrix") expect_equal(dvclC[,], C, tolerance=.Machine$double.eps ^ 0.5, info="double matrix elements not equivalent") expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Double Precision crossprod", { has_multiple_gpu_skip() has_multiple_double_skip() X <- matrix(rnorm(10), nrow=2) Y <- matrix(rnorm(10), nrow=2) Z <- matrix(rnorm(10), nrow=5) XS = X[1:2, 2:5] YS = Y[1:2, 2:5] ZS = Z[2:5, 1:2] C <- crossprod(XS,YS) Cs <- crossprod(XS) setContext(2L) dvclX <- vclMatrix(X, type="double") dvclY <- vclMatrix(Y, type="double") dvclZ <- vclMatrix(Z, type="double") setContext(1L) dvclXS <- block(dvclX, 1L,2L,2L,5L) dvclYS <- block(dvclY, 1L,2L,2L,5L) dvclZS <- block(dvclZ, 2L,5L,1L,2L) dvclC <- crossprod(dvclXS, dvclYS) dvclCs <- crossprod(dvclXS) expect_is(dvclC, "dvclMatrix") expect_equal(dvclC[,], C, tolerance=.Machine$double.eps ^ 0.5, info="double matrix elements not equivalent") expect_equal(dvclCs[,], Cs, tolerance=.Machine$double.eps ^ 0.5, info="double matrix elements not equivalent") expect_error(crossprod(dvclXS, dvclZS)) expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) test_that("Switching GPU vclMatrixBlock Double Precision tcrossprod", { has_multiple_gpu_skip() has_multiple_double_skip() X <- matrix(rnorm(10), nrow=2) Y <- matrix(rnorm(10), nrow=2) Z <- matrix(rnorm(10), nrow=5) XS = X[1:2, 2:5] YS = Y[1:2, 2:5] ZS = Z[2:5, 1:2] C <- tcrossprod(XS,YS) Cs <- tcrossprod(XS) setContext(2L) dvclX <- vclMatrix(X, type="double") dvclY <- vclMatrix(Y, type="double") dvclZ <- vclMatrix(Z, type="double") setContext(1L) dvclXS <- block(dvclX, 1L,2L,2L,5L) dvclYS <- block(dvclY, 1L,2L,2L,5L) dvclZS <- block(dvclZ, 2L,5L,1L,2L) dvclC <- tcrossprod(dvclXS, dvclYS) dvclCs <- tcrossprod(dvclXS) expect_is(dvclC, "dvclMatrix") expect_equal(dvclC[,], C, tolerance=.Machine$double.eps ^ 0.5, info="double matrix elements not equivalent") expect_equal(dvclCs[,], Cs, tolerance=.Machine$double.eps ^ 0.5, info="double matrix elements not equivalent") expect_error(crossprod(dvclXS, dvclZS)) expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal([email protected]_index, 2L, info = "context index not assigned properly") expect_equal(currentContext(), 1L, info = "context index has been change unintentionally") }) setContext(current_context)
group_age <- function(x, breaks = "decades", n = 10, labels = NULL, include.lowest = TRUE, right = FALSE, dig.lab = 3, ordered_result = FALSE) { if (length(breaks) == 1 && is.character(breaks)) { if (breaks == "decades") { breaks <- seq(floor(min(na.omit(x))/10)*10, ceiling(max(na.omit(x))/10)*10, 10) } else if (breaks == "years") { breaks <- seq(floor(min(na.omit(x))), ceiling(max(na.omit(x))), 1) } else if (breaks == "even") { breaks <- quantile(na.omit(x), seq(0,1,length=n+1)) } } cut(x, breaks, labels, include.lowest, right, dig.lab, ordered_result) }
predictRestrictedMeanTime <- function(object,newdata,times,...){ UseMethod("predictRestrictedMeanTime",object) } predictRestrictedMeanTime.default <- function(object,newdata,times,...){ stop("No method for evaluating predicted probabilities from objects in class: ",class(object),call.=FALSE) } predictRestrictedMeanTime.numeric <- function(object,newdata,times,...){ if (NROW(object) != NROW(newdata) || NCOL(object) != length(times)) stop(paste("\nPrediction matrix has wrong dimensions:\nRequested newdata x times: ",NROW(newdata)," x ",length(times),"\nProvided prediction matrix: ",NROW(object)," x ",NCOL(object),"\n\n",sep="")) object } predictRestrictedMeanTime.matrix <- function(object,newdata,times,...){ if (NROW(object) != NROW(newdata) || NCOL(object) != length(times)){ stop(paste("\nPrediction matrix has wrong dimensions:\nRequested newdata x times: ",NROW(newdata)," x ",length(times),"\nProvided prediction matrix: ",NROW(object)," x ",NCOL(object),"\n\n",sep="")) } object } predictRestrictedMeanTime.aalen <- function(object,newdata,times,...){ time.coef <- data.frame(object$cum) ntime <- nrow(time.coef) objecttime <- time.coef[,1,drop=TRUE] ntimevars <- ncol(time.coef)-2 covanames <- names(time.coef)[-(1:2)] notfound <- match(covanames,names(newdata),nomatch=0)==0 if (any(notfound)) stop("\nThe following predictor variables:\n\n", paste(covanames[notfound],collapse=","), "\n\nwere not found in newdata, which only provides the following variables:\n\n", paste(names(newdata),collapse=","), "\n\n") time.vars <- cbind(1,newdata[,names(time.coef)[-(1:2)],drop=FALSE]) nobs <- nrow(newdata) hazard <- .C("survest_cox_aalen", timehazard=double(ntime*nobs), as.double(unlist(time.coef[,-1])), as.double(unlist(time.vars)), as.integer(ntimevars+1), as.integer(nobs), as.integer(ntime),PACKAGE="pec")$timehazard hazard <- matrix(hazard,ncol=ntime,nrow=nobs,dimnames=list(1:nobs,paste("TP",1:ntime,sep=""))) surv <- pmin(exp(-hazard),1) if (missing(times)) times <- sort(unique(objecttime)) p <- surv[,prodlim::sindex(jump.times=objecttime,eval.times=times)] if (NROW(p) != NROW(newdata) || NCOL(p) != length(times)) stop(paste("\nPrediction matrix has wrong dimensions:\nRequested newdata x times: ",NROW(newdata)," x ",length(times),"\nProvided prediction matrix: ",NROW(p)," x ",NCOL(p),"\n\n",sep="")) p } predictRestrictedMeanTime.cox.aalen <- function(object,newdata,times,...){ const <- c(object$gamma) names(const) <- substr(dimnames(object$gamma)[[1]],6,nchar(dimnames(object$gamma)[[1]])-1) constant.part <- t(newdata[,names(const)])*const constant.part <- exp(colSums(constant.part)) time.coef <- data.frame(object$cum) ntime <- nrow(time.coef) objecttime <- time.coef[,1,drop=TRUE] ntimevars <- ncol(time.coef)-2 time.vars <- cbind(1,newdata[,names(time.coef)[-(1:2)],drop=FALSE]) nobs <- nrow(newdata) time.part <- .C("survest_cox_aalen",timehazard=double(ntime*nobs),as.double(unlist(time.coef[,-1])),as.double(unlist(time.vars)),as.integer(ntimevars+1),as.integer(nobs),as.integer(ntime),PACKAGE="pec")$timehazard time.part <- matrix(time.part,ncol=ntime,nrow=nobs) surv <- pmin(exp(-time.part*constant.part),1) if (missing(times)) times <- sort(unique(objecttime)) p <- surv[,prodlim::sindex(objecttime,times)] if (NROW(p) != NROW(newdata) || NCOL(p) != length(times)) stop(paste("\nPrediction matrix has wrong dimensions:\nRequested newdata x times: ",NROW(newdata)," x ",length(times),"\nProvided prediction matrix: ",NROW(p)," x ",NCOL(p),"\n\n",sep="")) p } predictRestrictedMeanTime.pecRpart <- function(object,newdata,times,...){ newdata$rpartFactor <- factor(predict(object$rpart,newdata=newdata), levels=object$levels) p <- predictRestrictedMeanTime(object$survfit,newdata=newdata,times=times) p } predictRestrictedMeanTime.coxph <- function(object,newdata,times,...){ if (is.null(y <- unclass(object$y)[,1])) stop("Need 'y=TRUE' in call of 'coxph'.") eTimes <- unique(sort(y)) pos <- prodlim::sindex(jump.times=eTimes,eval.times=times) surv <- predictSurvProb(object,newdata=newdata,times=eTimes) rmt <- matrix(unlist(lapply(1:length(pos), function(j) { pos.j <- 1:(pos[j]+1) p <- cbind(1,surv)[,pos.j,drop=FALSE] time.diff <- diff(c(0, eTimes)[pos.j]) apply(p, 1, function(x) {sum(x[-length(x)] * time.diff)}) })), ncol = length(pos)) if ((miss.time <- (length(times) - NCOL(rmt)))>0) rmt <- cbind(rmt,matrix(rep(NA,miss.time*NROW(rmt)),nrow=NROW(rmt))) if (NROW(rmt) != NROW(newdata) || NCOL(rmt) != length(times)) stop(paste("\nPrediction matrix has wrong dimensions:\nRequested newdata x times: ", NROW(newdata), " x ", length(times), "\nProvided prediction matrix: ", NROW(rmt), " x ", NCOL(rmt), "\n\n", sep="")) rmt } predictRestrictedMeanTime.coxph.penal <- function(object,newdata,times,...){ frailhistory <- object$history$'frailty(cluster)'$history frailVar <- frailhistory[NROW(frailhistory),1] linearPred <- predict(object,newdata=newdata,se.fit=FALSE,conf.int=FALSE) basehaz <- basehaz(object) bhTimes <- basehaz[,2] bhValues <- basehaz[,1] survPred <- do.call("rbind",lapply(1:NROW(newdata),function(i){ (1+frailVar*bhValues*exp(linearPred[i]))^{-1/frailVar} })) where <- prodlim::sindex(jump.times=bhTimes,eval.times=times) p <- cbind(1,survPred)[,where+1] if ((miss.time <- (length(times) - NCOL(p)))>0) p <- cbind(p,matrix(rep(NA,miss.time*NROW(p)),nrow=NROW(p))) if (NROW(p) != NROW(newdata) || NCOL(p) != length(times)) stop(paste("\nPrediction matrix has wrong dimensions:\nRequested newdata x times: ",NROW(newdata)," x ",length(times),"\nProvided prediction matrix: ",NROW(p)," x ",NCOL(p),"\n\n",sep="")) p } predictRestrictedMeanTime.cph <- function(object,newdata,times,...){ if (!match("surv",names(object),nomatch=0)) stop("Argument missing: set surv=TRUE in the call to cph!") p <- rms::survest(object,times=times,newdata=newdata,se.fit=FALSE,what="survival")$surv if (is.null(dim(p))) p <- matrix(p,nrow=NROW(newdata)) if (NROW(p) != NROW(newdata) || NCOL(p) != length(times)) stop(paste("\nPrediction matrix has wrong dimensions:\nRequested newdata x times: ",NROW(newdata)," x ",length(times),"\nProvided prediction matrix: ",NROW(p)," x ",NCOL(p),"\n\n",sep="")) p } predictRestrictedMeanTime.selectCox <- function(object,newdata,times,...){ predictRestrictedMeanTime(object[[1]],newdata=newdata,times=times,...) } predictRestrictedMeanTime.prodlim <- function(object,newdata,times,...){ p <- predict(object=object, type="surv", newdata=newdata, times=times, mode="matrix", level.chaos=1) if (NROW(newdata)==1 && class(p)=="list"){ p <- unlist(p) } if (is.null(dim(p)) && NROW(newdata)>=1){ p <- as.vector(p) if (length(p)!=length(times)) stop(paste("\nPrediction matrix has wrong dimensions:\nRequested newdata x times: ",NROW(newdata)," x ",length(times),"\nProvided prediction matrix: ",NROW(p)," x ",NCOL(p),"\n\n",sep="")) } else{ if (NROW(p) != NROW(newdata) || NCOL(p) != length(times)) stop(paste("\nPrediction matrix has wrong dimensions:\nRequested newdata x times: ",NROW(newdata)," x ",length(times),"\nProvided prediction matrix: ",NROW(p)," x ",NCOL(p),"\n\n",sep="")) } rownames(p) <- NULL p } predict.survfit <- function(object,newdata,times,bytimes=TRUE,fill="last",...){ if (length(class(object))!=1 || class(object)!="survfit" || object$typ !="right") stop("Predictions only available \nfor class 'survfit', possibly stratified Kaplan-Meier fits.\n For class 'cph' Cox models see survest.cph.") if (missing(newdata)) npat <- 1 else if (is.data.frame(newdata)) npat <- nrow(newdata) else stop("If argument `newdata' is supplied it must be a dataframe." ) ntimes <- length(times) sfit <- summary(object,times=times) if (is.na(fill)) Fill <- function(x,len){x[1:len]} else if (fill=="last") Fill <- function(x,len){ y <- x[1:len] y[is.na(y)] <- x[length(x)] y} else stop("Argument fill must be the string 'last' or NA.") if (is.null(object$strata)){ pp <- Fill(sfit$surv,ntimes) p <- matrix(rep(pp,npat), ncol=ifelse(bytimes,ntimes,npat), nrow=ifelse(bytimes,npat,ntimes), byrow=bytimes) } else{ covars <- attr(terms(eval.parent(object$call$formula)),"term.labels") if (!all(match(covars,names(newdata),nomatch=FALSE))) stop("Not all strata defining variables occur in newdata.") stratdat <- newdata[,covars,drop=FALSE] names(stratdat) <- covars NewStratVerb <- survival::strata(stratdat) NewStrat <- interaction(stratdat,sep=" ") levs <- levels(sfit$strata) if (!all(choose <- match(NewStratVerb,levs,nomatch=F)) && !all(choose <- match(NewStrat,levs,nomatch=F))) stop("Not all strata levels in newdata occur in fit.") survlist <- split(sfit$surv,sfit$strata) pp <- lapply(survlist[choose],Fill,ntimes) p <- matrix(unlist(pp,use.names=FALSE), ncol=ifelse(bytimes,ntimes,npat), nrow=ifelse(bytimes,npat,ntimes), byrow=bytimes) } if (NROW(p) != NROW(newdata) || NCOL(p) != length(times)) stop(paste("\nPrediction matrix has wrong dimensions:\nRequested newdata x times: ",NROW(newdata)," x ",length(times),"\nProvided prediction matrix: ",NROW(p)," x ",NCOL(p),"\n\n",sep="")) p } predictRestrictedMeanTime.survfit <- function(object,newdata,times,...){ p <- predict.survfit(object,newdata=newdata,times=times,bytimes=TRUE,fill="last") if (NROW(p) != NROW(newdata) || NCOL(p) != length(times)) stop(paste("\nPrediction matrix has wrong dimensions:\nRequested newdata x times: ",NROW(newdata)," x ",length(times),"\nProvided prediction matrix: ",NROW(p)," x ",NCOL(p),"\n\n",sep="")) p } predictRestrictedMeanTime.psm <- function(object,newdata,times,...){ if (length(times)==1){ p <- rms::survest(object,times=c(0,times),newdata=newdata,what="survival",conf.int=FALSE)[,2] }else{ p <- rms::survest(object,times=times,newdata=newdata,what="survival",conf.int=FALSE) } if (NROW(p) != NROW(newdata) || NCOL(p) != length(times)) stop(paste("\nPrediction matrix has wrong dimensions:\nRequested newdata x times: ",NROW(newdata)," x ",length(times),"\nProvided prediction matrix: ",NROW(p)," x ",NCOL(p),"\n\n",sep="")) p } predictRestrictedMeanTime.riskRegression <- function(object,newdata,times,...){ if (missing(times))stop("Argument times is missing") temp <- predict(object,newdata=newdata) pos <- prodlim::sindex(jump.times=temp$time,eval.times=times) p <- cbind(1,1-temp$cuminc)[,pos+1,drop=FALSE] if (NROW(p) != NROW(newdata) || NCOL(p) != length(times)) stop(paste("\nPrediction matrix has wrong dimensions:\nRequested newdata x times: ",NROW(newdata)," x ",length(times),"\nProvided prediction matrix: ",NROW(p)," x ",NCOL(p),"\n\n",sep="")) p } predictRestrictedMeanTime.rfsrc <- function(object, newdata, times, ...){ ptemp <- predict(object,newdata=newdata,importance="none",...)$survival pos <- prodlim::sindex(jump.times=object$time.interest,eval.times=times) p <- cbind(1,ptemp)[,pos+1,drop=FALSE] if (NROW(p) != NROW(newdata) || NCOL(p) != length(times)) stop(paste("\nPrediction matrix has wrong dimensions:\nRequested newdata x times: ",NROW(newdata)," x ",length(times),"\nProvided prediction matrix: ",NROW(p)," x ",NCOL(p),"\n\n",sep="")) p } predictProb <- function(object,newdata,times,...){ UseMethod("predictProb",object) } predictProb.glm <- function(object,newdata,times,...){ N <- NROW(newdata) NT <- length(times) if (!(unclass(family(object))$family=="gaussian")) stop("Currently only gaussian family implemented for glm.") betax <- predict(object,newdata=newdata,se.fit=FALSE) pred.matrix <- matrix(rep(times,N),byrow=TRUE,ncol=NT,nrow=N) p <- 1-pnorm(pred.matrix - betax,mean=0,sd=sqrt(var(object$y))) if (NROW(p) != NROW(newdata) || NCOL(p) != length(times)) stop(paste("\nPrediction matrix has wrong dimensions:\nRequested newdata x times: ",NROW(newdata)," x ",length(times),"\nProvided prediction matrix: ",NROW(p)," x ",NCOL(p),"\n\n",sep="")) p } predictProb.ols <- function(object,newdata,times,...){ N <- NROW(newdata) NT <- length(times) if (!(unclass(family(object))$family=="gaussian")) stop("Currently only gaussian family implemented.") betax <- predict(object,newdata=newdata,type="lp",se.fit=FALSE) pred.matrix <- matrix(rep(times,N),byrow=TRUE,ncol=NT,nrow=N) p <- 1-pnorm(pred.matrix - betax,mean=0,sd=sqrt(var(object$y))) if (NROW(p) != NROW(newdata) || NCOL(p) != length(times)) stop(paste("\nPrediction matrix has wrong dimensions:\nRequested newdata x times: ",NROW(newdata)," x ",length(times),"\nProvided prediction matrix: ",NROW(p)," x ",NCOL(p),"\n\n",sep="")) p } predictProb.randomForest <- function(object,newdata,times,...){ N <- NROW(newdata) NT <- length(times) predMean <- predict(object,newdata=newdata,se.fit=FALSE) pred.matrix <- matrix(rep(times,N),byrow=TRUE,ncol=NT,nrow=N) p <- 1-pnorm(pred.matrix - predMean,mean=0,sd=sqrt(var(object$y))) if (NROW(p) != NROW(newdata) || NCOL(p) != length(times)) stop(paste("\nPrediction matrix has wrong dimensions:\nRequested newdata x times: ",NROW(newdata)," x ",length(times),"\nProvided prediction matrix: ",NROW(p)," x ",NCOL(p),"\n\n",sep="")) p }
twonestgen <- function(I, sec, mat, schdist, schpar, secdist, secpar, errdist, errpar, thetatrue) { matre = matrix(c(0, 0), ncol = 2) school = c(0) class = c(0) for (i in 1:I) { rsch = schdist(1, schpar) for (j in 1:sec[i]) { rsec = secdist(1, secpar) vecsec = rep(rsec, mat[i, j]) vecsch = rep(rsch, mat[i, j]) matt = cbind(vecsch, vecsec) matre = rbind(matre, matt) for (k in 1:mat[i, j]) { school = c(school, i) class = c(class, j) } } } np1 = length(matre[, 1]) n = np1 - 1 matre = matre[2:np1, ] school = school[2:np1] class = class[2:np1] xmat = cbind(rbinom(n, 1, 0.5), rnorm(n)) errs = errdist(n, errpar) ey = xmat %*% thetatrue y = ey + matre[, 1] + matre[, 2] + errs list(y = y, xmat = xmat, ey = ey, matre = matre, errs = errs, school = school, section = class) }
mapdeckHeatmapDependency <- function() { list( createHtmlDependency( name = "heatmap", version = "1.0.0", src = system.file("htmlwidgets/lib/heatmap", package = "mapdeck"), script = c("heatmap.js"), all_files = FALSE ) ) } add_heatmap <- function( map, data = get_map_data(map), lon = NULL, lat = NULL, polyline = NULL, weight = NULL, colour_range = NULL, radius_pixels = 30, intensity = 1, threshold = 0.05, layer_id = NULL, update_view = TRUE, focus_layer = FALSE, digits = 6, transitions = NULL ) { l <- list() l[["polyline"]] <- force( polyline ) l[["weight"]] <- force( weight ) l[["lon"]] <- force( lon ) l[["lat"]] <- force( lat ) l <- resolve_data( data, l, c("POINT") ) bbox <- init_bbox() update_view <- force( update_view ) focus_layer <- force( focus_layer ) if ( !is.null(l[["data"]]) ) { data <- l[["data"]] l[["data"]] <- NULL } if( !is.null(l[["bbox"]] ) ) { bbox <- l[["bbox"]] l[["bbox"]] <- NULL } layer_id <- layerId(layer_id, "heatmap") if( is.null( colour_range ) ) { colour_range <- colourvalues::colour_values(1:6, palette = "viridis") } if(length(colour_range) != 6) stop("mapdeck - colour_range must have 6 hex colours") checkHex(colour_range) map <- addDependency(map, mapdeckHeatmapDependency()) tp <- l[["data_type"]] l[["data_type"]] <- NULL jsfunc <- "add_heatmap_geo" if( tp == "sf" ) { geometry_column <- c( "geometry" ) shape <- rcpp_aggregate_geojson( data, l, geometry_column, digits, "heatmap" ) } else if ( tp == "df" ) { geometry_column <- list( geometry = c("lon", "lat") ) shape <- rcpp_aggregate_geojson_df( data, l, geometry_column, digits, "heatmap" ) } else if ( tp == "sfencoded" ) { geometry_column <- "polyline" shape <- rcpp_aggregate_polyline( data, l, geometry_column, "heatmap" ) jsfunc <- "add_heatmap_polyline" } js_transitions <- resolve_transitions( transitions, "heatmap" ) invoke_method( map, jsfunc, map_type( map ), shape[["data"]], layer_id, colour_range, radius_pixels, intensity, threshold, bbox, update_view, focus_layer, js_transitions ) } clear_heatmap <- function( map, layer_id = NULL) { layer_id <- layerId(layer_id, "heatmap") invoke_method(map, "md_layer_clear", map_type( map ), layer_id, "heatmap" ) }
"swissexper"
signal = GRanges(seqnames = "chr1", ranges = IRanges(start = c(1, 4, 7, 11, 14, 17, 21, 24, 27), end = c(2, 5, 8, 12, 15, 18, 22, 25, 28)), score = c(1, 2, 3, 1, 2, 3, 1, 2, 3)) target = GRanges(seqnames = "chr1", ranges = IRanges(start = c(10, 25), end = c(20, 30))) normalizeToMatrix(signal, target, extend = 10, w = 2) normalizeToMatrix(signal, target, extend = 10, w = 2, include_target = TRUE) normalizeToMatrix(signal, target, extend = 10, w = 2, value_column = "score") normalizeToMatrix(signal, target, extend = 10, w = 2, target_ratio = 0.5) normalizeToMatrix(signal, target, extend = 10, w = 2, target_ratio = 1) normalizeToMatrix(signal, target, w = 2, extend = c(5, 5)) normalizeToMatrix(signal, target, w = 2, extend = c(0, 5)) normalizeToMatrix(signal, target, w = 2, extend = c(5, 0)) normalizeToMatrix(signal, target, w = 2, extend = c(0, 0))
regbetawei <- function(pa, ly, sly1, x, w) { phi <- exp(pa[1]) ; b <- pa[-1] m <- exp( tcrossprod(b, x) ) m <- m / ( 1 + m ) a1 <- m * phi ; a2 <- phi - a1 - lgamma(phi) + sum( w * lgamma(a1) ) + sum( w * lgamma(a2) ) - sum(a1 * ly) - phi * sly1 }
account_albums <- function(account = 'me', ids = TRUE, ...){ if(!"token" %in% names(list(...)) && account == 'me') stop("This operation can only be performed for account 'me' using an OAuth token.") if(ids) { out <- imgurGET(paste0('account/', account, '/albums/ids'), ...) structure(out, class = 'imgur_basic') } else { out <- imgurGET(paste0('account/', account, '/albums/'), ...) lapply(out, `class<-`, 'imgur_album') } }
NuisanceData <- function(nuisPars){ if(is.null(nuisPars)) nuisPars <- nuisParsFn() else{ if(!is.null(nuisPars$mu)){ nuis.mu <- nuisPars$mu} else{ nuis.mu <- 0.01} if(!is.null(nuisPars$sd)){ nuis.sd <- nuisPars$sd} else{ nuis.sd <- 0.05} if(!is.null(nuisPars$c)){ nuis.c <- nuisPars$c} else{ nuis.c <- 0} if(!is.null(nuisPars$alpha)){ nuis.alpha <- nuisPars$alpha} else{ nuis.alpha <- 0.1} if(!is.null(nuisPars$beta)){ nuis.beta <- nuisPars$beta} else{ nuis.beta <- 0.1} nuisPars <- nuisParsFn(nuis.mu, nuis.sd, nuis.c, nuis.alpha, nuis.beta) } return(nuisPars) }
setwd(dirname(this.dir())) source("setup.R") raw_data_path <- get_inpath(this.dir()) out_data_path <- get_outpath(this.dir()) roanoke <- read_excel(paste0(raw_data_path,"roanoke_police_settlements_records.xlsx"), sheet = "amounts", col_types = "text") roanoke_po <- read_excel(paste0(raw_data_path,"roanoke_police_settlements_records.xlsx"), sheet = "police_officers") roanoke <- roanoke %>% rename(summary_allegations = `summary_allegations (;)`) %>% mutate(city = "Roanoke", state= "VA") %>% mutate(amount_awarded = as.numeric(amount_awarded), filed_date = NA, filed_year = NA, closed_date = NA, incident_date = as_date(as.numeric(incident_date),origin = '1899-12-30'), incident_year = year(incident_date), calendar_year = as.numeric(calendar_year)) roanoke_po <- roanoke_po %>% mutate(city = "Roanoke", state="VA") %>% rename(calendar_year = year) %>% mutate(closed_date = NA) merged <- full_join(roanoke_po,roanoke) roanoke <- roanoke %>% select(calendar_year, city, state, incident_date, incident_year, filed_date, filed_year, closed_date, amount_awarded, other_expenses, collection, total_incurred, case_outcome, docket_number, claim_number, court, plaintiff_name, plaintiff_attorney, matter_name, location, summary_allegations) roanoke_po <- roanoke_po %>% select(-closed_date) summary(roanoke$calendar_year) nrow(roanoke %>% group_by_all() %>% filter(n()>1)) table(roanoke$summary_allegations) print(paste("There are",nrow(roanoke %>% filter(is.na(closed_date))),"rows missing closed date")) print(paste("There are",nrow(roanoke %>% filter(is.na(calendar_year))),"rows missing calendar year")) print(paste("There are",nrow(roanoke %>% filter(is.na(amount_awarded))),"rows missing amount awarded")) print(paste("There are",nrow(roanoke %>% filter(amount_awarded==0)),"rows with amount awarded = 0")) print(paste("There are",nrow(roanoke %>% filter(is.na(docket_number))),"rows missing docket number")) print("Total number of cases") print(nrow(roanoke)) print("Total amount awarded") sum(roanoke$amount_awarded) write.csv(roanoke,paste0(out_data_path,"roanoke_edited.csv"), na = "", row.names = FALSE) write.csv(roanoke_po,paste0(out_data_path,"roanoke_police_edited.csv"), na = "",row.names = FALSE)
upper <- function(n, k = 5, x = LETTERS, prob = NULL, name = "Upper"){ stopifnot(k < length(x) || k > 0) if (!is.null(prob) && length(prob) != k) stop("length of `prob` must equa `k`") out <- sample(x = x[seq_len(k)], size = n, replace = TRUE, prob = prob) varname(out, name) } lower <- hijack(upper, x = letters, name = "Lower" ) upper_factor <- function(n, k = 5, x = LETTERS, prob = NULL, name = "Upper"){ stopifnot(k < length(x) || k > 0) stopifnot(length(prob) != k) out <- sample(x = x[seq_len(k)], size = n, replace = TRUE, prob = prob) out <- factor(out, levels = x[seq_len(k)]) varname(out, name) } lower_factor <- hijack(upper_factor, x = letters, name = "Lower" )
x <- rprobMat(10,c(2,3,4)) test_that("aperm works as expected", { expect_equal(aperm(x[1,], c(2,3,1)), aperm(x, c(2,3,1))[1,]) expect_equal(aperm(x, c(1,2,3)), x) })
micro_PERMANOVA <- function(micro_set, beta_div, method, ..., nperm = 999){ micro_set %<>% dplyr::filter(.data$Lib %in% rownames(beta_div)) %>% dplyr::distinct(.data$Lib, .keep_all = T) %>% dplyr::arrange(.data$Lib) f <- paste("beta_div ~", suppressWarnings(adonis_formula(...)) ) %>% stats::as.formula() vegan::adonis2(f, data = micro_set, method = method, permutations = nperm) }
require(geosapi, quietly = TRUE) require(testthat) context("GSDataStore") test_that("READ dataStore",{ expect_is(gsman,"GSManager") ds <- gsman$getDataStore("topp", "taz_shapes") expect_is(ds, "GSDataStore") expect_true(all(c("name", "enabled", "type", "description", "connectionParameters", "full") %in% names(ds))) expect_equal(ds$name, "taz_shapes") }) test_that("READ dataStores",{ dslist <- gsman$getDataStores("topp") expect_true(all(sapply(dslist, function(x){class(x)[1] == "GSDataStore"}))) dsnames <- gsman$getDataStoreNames("topp") expect_true(all(dsnames %in% c("states_shapefile","taz_shapes"))) }) test_that("CREATE dataStore - Shapefile",{ ds = GSShapefileDataStore$new(dataStore="topp_datastore", description = "topp_datastore description", enabled = TRUE, url = "file:data/shapefiles/states.shp") created <- gsman$createDataStore("topp", ds) expect_true(created) ds <- gsman$getDataStore("topp", "topp_datastore") expect_is(ds, "GSDataStore") expect_equal(ds$description, "topp_datastore description") expect_true(ds$enabled) }) test_that("UPDATE datastore - Shapefile",{ dataStore <- gsman$getDataStore("topp", "topp_datastore") dataStore$setDescription("topp_datastore updated description") dataStore$setEnabled(FALSE) updated <- gsman$updateDataStore("topp", dataStore) expect_true(updated) ds <- gsman$getDataStore("topp", "topp_datastore") expect_is(ds, "GSDataStore") expect_equal(ds$description, "topp_datastore updated description") expect_false(ds$enabled) }) test_that("DELETE dataStore - Shapefile",{ deleted <- gsman$deleteDataStore("topp", "topp_datastore", TRUE) expect_true(deleted) ds <- gsman$getDataStore("topp", "topp_datastore") expect_is(ds, "NULL") }) test_that("CREATE dataStore - Directory of Shapefiles",{ ds = GSShapefileDirectoryDataStore$new(dataStore="topp_datastore", description = "topp_datastore description", enabled = TRUE, url = "file:data/shapefiles") created <- gsman$createDataStore("topp", ds) expect_true(created) ds <- gsman$getDataStore("topp", "topp_datastore") expect_is(ds, "GSDataStore") expect_equal(ds$description, "topp_datastore description") expect_true(ds$enabled) }) test_that("UPDATE datastore - Directory of Shapefiles",{ dataStore <- gsman$getDataStore("topp", "topp_datastore") dataStore$setDescription("topp_datastore updated description") dataStore$setEnabled(FALSE) updated <- gsman$updateDataStore("topp", dataStore) expect_true(updated) ds <- gsman$getDataStore("topp", "topp_datastore") expect_is(ds, "GSDataStore") expect_equal(ds$description, "topp_datastore updated description") expect_false(ds$enabled) }) test_that("DELETE dataStore - Directory of Shapefiles",{ deleted <- gsman$deleteDataStore("topp", "topp_datastore", TRUE) expect_true(deleted) ds <- gsman$getDataStore("topp", "topp_datastore") expect_is(ds, "NULL") }) test_that("CREATE dataStore - GeoPackage",{ ds = GSGeoPackageDataStore$new(dataStore="topp_datastore_gpkg", description = "topp_datastore description", enabled = TRUE, database = "file:data/somefile.gpkg") created <- gsman$createDataStore("topp", ds) expect_true(created) ds <- gsman$getDataStore("topp", "topp_datastore_gpkg") expect_is(ds, "GSDataStore") expect_equal(ds$description, "topp_datastore description") expect_true(ds$enabled) }) test_that("UPDATE datastore - GeoPackage",{ dataStore <- gsman$getDataStore("topp", "topp_datastore_gpkg") dataStore$setDescription("topp_datastore updated description") dataStore$setEnabled(FALSE) updated <- gsman$updateDataStore("topp", dataStore) expect_true(updated) ds <- gsman$getDataStore("topp", "topp_datastore_gpkg") expect_is(ds, "GSDataStore") expect_equal(ds$description, "topp_datastore updated description") expect_false(ds$enabled) }) test_that("DELETE dataStore - GeoPackage",{ deleted <- gsman$deleteDataStore("topp", "topp_datastore_gpkg", TRUE) expect_true(deleted) ds <- gsman$getDataStore("topp", "topp_datastore_gpkg") expect_is(ds, "NULL") })
ComputeBest_t.example <- function(){ AlphaBetaMatrix <- matrix(c(0.7,1.5,0,0.5),ncol=2) nbts <- seq(20,50,10) ComputeBest_t(AlphaBetaMatrix=AlphaBetaMatrix, nb_ts=nbts) } ComputeBest_tau.example <- function(){ AlphaBetaMatrix <- matrix(c(0.7,1.5,0,0.5),ncol=2) nbts <- seq(20,50,10) ComputeBest_tau(AlphaBetaMatrix=AlphaBetaMatrix, nb_ts=nbts,tScheme="uniformOpt", Constrained=TRUE) }
"PreDiabetes"
draw.boxes = function( slice, start, end, maxElements = 50, maxDepth = 100, label = TRUE, labelStrand = FALSE, labelCex = 1, labelSrt = 0, labelAdj = "center", labelOverflow = TRUE, labelFamily = "sans", colorVal = " colorFun = function() NULL, border = " cex.lab = 1, spacing = 0.2, bty = "o", groupBy = NA, groupPosition = NA, groupSize = NA, groupLwd = 1, ... ) { if(is.numeric(start)) start <- as.integer(start) if(is.numeric(end)) end <- as.integer(end) if(!is.integer(start)) stop("'start' must be integer or numeric") if(!is.integer(end)) stop("'end' must be integer or numeric") if(!is.data.frame(slice)) stop("'slice' must be a data.frame") if(isTRUE(label) && !"name" %in% names(slice)) stop("'slice' needs a 'name' column when 'label'") if(isTRUE(label) && isTRUE(labelStrand) && !"strand" %in% names(slice)) stop("'slice' needs a 'strand' column when 'label' and 'labelStrand'") if(!"start" %in% names(slice)) stop("'slice' needs a 'start' column") if(!"end" %in% names(slice)) stop("'slice' needs a 'end' column") draw.bg( start = start, end = end, cex.lab = cex.lab, bty = bty, ... ) errorMessage <- NA if(nrow(slice) == 0) { errorMessage <- "No feature in the region" } else if(nrow(slice) > maxElements) { errorMessage <- sprintf("'maxElements' reached (%i)", nrow(slice)) } else { if(is.na(groupBy)) { boxes <- data.frame( start.plot = as.integer(slice$start), end.plot = as.integer(slice$end), strand = as.character(slice$strand), label = slice$name, stringsAsFactors = FALSE ) } else if(!groupBy %in% names(slice)) { stop("'groupBy' must refer to an existing column") } else if(!is.na(groupPosition) && ! groupPosition %in% names(slice)) { stop("'groupPosition' must be NA or refer to an existing column") } else if(!is.na(groupSize) && ! groupSize %in% names(slice)) { stop("'groupSize' must be NA or refer to an existing column") } else { if(is.factor(slice[[ groupBy ]])) { slice[[ groupBy ]] <- factor(as.character(slice[[ groupBy ]])) } else { slice[[ groupBy ]] <- factor(slice[[ groupBy ]]) } boxes <- data.frame( start.plot = as.integer(lapply(X=split(x=slice$start, f=slice[[ groupBy ]]), FUN=min, na.rm=TRUE)), end.plot = as.integer(lapply(X=split(x=slice$end, f=slice[[ groupBy ]]), FUN=max, na.rm=TRUE)), strand = as.character(lapply(X=split(x=as.character(slice$strand), f=slice[[ groupBy ]]), FUN="[", i=1L)), label = levels(slice[[ groupBy ]]), stringsAsFactors = FALSE ) if(!is.na(groupPosition) && !is.na(groupSize)) { start.i <- as.integer(lapply(X=split(x=slice[[ groupPosition ]], f=slice[[ groupBy ]]), FUN=min, na.rm=TRUE)) end.i <- as.integer(lapply(X=split(x=slice[[ groupPosition ]], f=slice[[ groupBy ]]), FUN=max, na.rm=TRUE)) size.i <- as.integer(lapply(X=split(x=slice[[ groupSize ]], f=slice[[ groupBy ]]), FUN="[", i=1L)) boxes[ boxes$strand == "+" & start.i > 1L , "start.plot" ] <- as.integer(graphics::par("usr")[1]) boxes[ boxes$strand == "-" & start.i > 1L , "end.plot" ] <- as.integer(graphics::par("usr")[2]) boxes[ boxes$strand == "+" & end.i < size.i , "end.plot" ] <- as.integer(graphics::par("usr")[2]) boxes[ boxes$strand == "-" & end.i < size.i , "start.plot" ] <- as.integer(graphics::par("usr")[1]) } } boxes <- yline( boxes = boxes, start = start, end = end, label = label, labelStrand = labelStrand, labelCex = labelCex, labelSrt = labelSrt, labelAdj = labelAdj, labelOverflow = labelOverflow, maxDepth = maxDepth ) if(is(boxes, "error")) { errorMessage <- conditionMessage(boxes) } else { if(is.na(groupBy)) { slice$plotLine <- boxes$yline } else { slice$plotLine <- boxes$yline[ match(slice[[ groupBy ]], boxes$label) ] } maxLine <- max(boxes$yline) + 1L if(is.na(colorVal)) { environment(colorFun) <- environment() color <- colorFun() } else { color <- colorVal } if(identical(border, "color")) border <- color if(!is.na(groupBy)) { graphics::segments( x0 = boxes$start.plot, y0 = (boxes$yline + 0.5) / maxLine, x1 = boxes$end.plot, y1 = (boxes$yline + 0.5) / maxLine, col = border, lwd = groupLwd ) } slice$start <- pmax(graphics::par("usr")[1], slice$start) slice$end <- pmin(graphics::par("usr")[2], slice$end) graphics::rect( xleft = slice$start, xright = slice$end, ytop = (slice$plotLine + (1 - spacing/2)) / maxLine, ybottom = (slice$plotLine + spacing/2) / maxLine, col = color, border = border ) if(isTRUE(label)) { if(!is.na(groupBy)) { charHeight <- graphics::yinch(graphics::par("cin")[2]) * labelCex graphics::rect( xleft = boxes$start.lab, xright = boxes$end.lab, ybottom = (boxes$yline + 0.5) / maxLine - charHeight/2, ytop = (boxes$yline + 0.5) / maxLine + charHeight/2, col = " border = border ) } if(isTRUE(labelStrand)) { boxes[ boxes$strand == "-" , "label" ] <- sprintf("< %s", boxes[ boxes$strand == "-" , "label" ]) boxes[ boxes$strand == "+" , "label" ] <- sprintf("%s >", boxes[ boxes$strand == "+" , "label" ]) } args <- with( boxes[ (isTRUE(label) && isTRUE(labelOverflow)) | !boxes$overflow ,], list( x = (start.lab + end.lab) / 2, y = (yline + 0.5) / maxLine, label = label, col = " adj = c(0.5, 0.5), cex = labelCex, srt = labelSrt ) ) if(labelFamily == "Hershey") { args$vfont <- c("sans serif", "bold") } else { args$family <- labelFamily } do.call(graphics::text, args) } } } if(!is.na(errorMessage)) { graphics::text( x = mean(graphics::par("usr")[1:2]), y = mean(graphics::par("usr")[3:4]), label = errorMessage, col = " adj = c(0.5, 0.5), cex = cex.lab ) } graphics::box( which = "plot", col = " bty = bty ) }
calc_si <- function(a, b) { calc_ed(a, b, measure = "si", prop = NULL) } calc_si_hidden <- function(a, b) { comp <- encoding2matrix(a) == encoding2matrix(b) diag(comp) <- 0 sum(comp)/(nrow(comp) * (nrow(comp) - 1)) } encoding2matrix <- function(x) { x_df <- encoding2df(x, sort = TRUE) res <- sapply(sort(levels(x_df[["element"]])), function(single_element) { x_gr <- x_df[x_df[["element"]] == single_element, "gr_id"] x_df[["gr_id"]] == x_gr }) diag(res) <- FALSE res }
logLik.dbchoice <- function(object, ...) { out <- object$loglik attr(out, "df") <- sum(!is.na(coefficients(object))) attr(out, "nobs") <- object$nobs class(out) <- "logLik" out }
report.htest <- function(x, ...) { table <- report_table(x, ...) text <- report_text(x, table = table, ...) as.report(text, table = table, ...) } report_effectsize.htest <- function(x, ...) { if (insight::model_info(x)$is_ttest) { table <- effectsize::cohens_d(x, ...) ci <- attributes(table)$ci estimate <- names(table)[1] interpretation <- effectsize::interpret_cohens_d(table[[estimate]], ...) rules <- .text_effectsize(attributes(interpretation)$rule_name) if (estimate %in% c("d", "Cohens_d")) { main <- paste0("Cohen's d = ", insight::format_value(table[[estimate]])) } else { main <- paste0(estimate, " = ", insight::format_value(table[[estimate]])) } statistics <- paste0( main, ", ", insight::format_ci(table$CI_low, table$CI_high, ci) ) table <- datawizard::data_rename( as.data.frame(table), c("CI_low", "CI_high"), paste0(estimate, c("_CI_low", "_CI_high")) ) table <- table[c(estimate, paste0(estimate, c("_CI_low", "_CI_high")))] } if (insight::model_info(x)$is_ranktest && !insight::model_info(x)$is_correlation) { table <- parameters::parameters(x, rank_biserial = TRUE, ...) ci <- attributes(table)$ci estimate <- "r_rank_biserial" interpretation <- effectsize::interpret_r(table$r_rank_biserial, ...) rules <- .text_effectsize(attributes(interpretation)$rule_name) main <- paste0("r (rank biserial) = ", insight::format_value(table$r_rank_biserial)) statistics <- paste0( main, ", ", insight::format_ci(table$rank_biserial_CI_low, table$rank_biserial_CI_high, ci) ) table <- table[c("r_rank_biserial", "rank_biserial_CI_low", "rank_biserial_CI_high")] } if (insight::model_info(x)$is_correlation) { table <- parameters::parameters(x, ...) ci <- attributes(table)$ci estimate <- names(table)[3] interpretation <- effectsize::interpret_r(table[[estimate]], ...) rules <- .text_effectsize(attributes(interpretation)$rule_name) main <- paste0(estimate, " = ", insight::format_value(table[[estimate]])) if ("CI_low" %in% names(table)) { statistics <- paste0( main, ", ", insight::format_ci(table$CI_low, table$CI_high, ci) ) table <- table[c(estimate, "CI_low", "CI_high")] } else { statistics <- main table <- table[c(estimate)] } } if (insight::model_info(x)$is_chi2test || insight::model_info(x)$is_proptest || insight::model_info(x)$is_xtab) { stop("This test is not yet supported. Please open an issue: https://github.com/easystats/report/issues") } parameters <- paste0(interpretation, " (", statistics, ")") as.report_effectsize( parameters, summary = parameters, table = table, interpretation = interpretation, statistics = statistics, rules = rules, ci = ci, main = main ) } report_table.htest <- function(x, ...) { table_full <- parameters::model_parameters(x, ...) effsize <- report_effectsize(x, ...) if (insight::model_info(x)$is_ttest) { table_full <- cbind(table_full, attributes(effsize)$table) table <- datawizard::data_remove( table_full, c("Parameter", "Group", "Mean_Group1", "Mean_Group2", "Method") ) } if (insight::model_info(x)$is_ranktest && !insight::model_info(x)$is_correlation) { table_full <- cbind(table_full, attributes(effsize)$table) } as.report_table(table_full, summary = table, effsize = effsize) } report_statistics.htest <- function(x, table = NULL, ...) { if (is.null(table) || is.null(attributes(table)$effsize)) { table <- report_table(x) } effsize <- attributes(table)$effsize candidates <- c("rho", "r", "tau", "Difference", "r_rank_biserial") estimate <- candidates[candidates %in% names(table)][1] text <- paste0(tolower(estimate), " = ", insight::format_value(table[[estimate]])) if (!is.null(attributes(x$conf.int)$conf.level)) { text <- paste0( text, ", ", insight::format_ci(table$CI_low, table$CI_high, ci = attributes(x$conf.int)$conf.level) ) } if ("t" %in% names(table)) { text <- paste0( text, ", t(", insight::format_value(table$df, protect_integers = TRUE), ") = ", insight::format_value(table$t) ) } else if ("S" %in% names(table)) { text <- paste0(text, ", S = ", insight::format_value(table$S)) } else if ("z" %in% names(table)) { text <- paste0(text, ", z = ", insight::format_value(table$z)) } else if ("W" %in% names(table)) { text <- paste0("W = ", insight::format_value(table$W)) } else if ("Chi2" %in% names(table)) { text <- paste0(text, ", Chi2 = ", insight::format_value(table$Chi2)) } text <- paste0(text, ", ", insight::format_p(table$p, stars = FALSE, digits = "apa")) if (insight::model_info(x)$is_ttest || (insight::model_info(x)$is_ranktest && !insight::model_info(x)$is_correlation)) { text_full <- paste0(text, "; ", attributes(effsize)$statistics) text <- paste0(text, ", ", attributes(effsize)$main) } else { text_full <- text } as.report_statistics(text_full, summary = text, estimate = table[[estimate]], table = table, effsize = effsize ) } report_parameters.htest <- function(x, table = NULL, ...) { stats <- report_statistics(x, table = table, ...) table <- attributes(stats)$table effsize <- attributes(stats)$effsize if (insight::model_info(x)$is_correlation) { text_full <- paste0( effectsize::interpret_direction(attributes(stats)$estimate), ", statistically ", effectsize::interpret_p(table$p, rules = "default"), ", and ", effectsize::interpret_r(attributes(stats)$estimate, ...), " (", stats, ")" ) text_short <- text_full } else { text_full <- paste0( effectsize::interpret_direction(attributes(stats)$estimate), ", statistically ", effectsize::interpret_p(table$p, rules = "default"), ", and ", attributes(effsize)$interpretation, " (", stats, ")" ) text_short <- paste0( effectsize::interpret_direction(attributes(stats)$estimate), ", statistically ", effectsize::interpret_p(table$p, rules = "default"), ", and ", attributes(effsize)$interpretation, " (", summary(stats), ")" ) } as.report_parameters( text_full, summary = text_short, table = table, effectsize = effsize, ... ) } report_model.htest <- function(x, table = NULL, ...) { if (is.null(table)) { table <- report_table(x, ...) } if (insight::model_info(x)$is_correlation) { text <- paste0(x$method, " between ", x$data.name) } if (insight::model_info(x)$is_ttest) { if (names(x$null.value) == "mean") { table$Difference <- x$estimate - x$null.value means <- paste0(" (mean = ", insight::format_value(x$estimate), ")") vars_full <- paste0(x$data.name, means, " and mu = ", x$null.value) vars <- paste0(x$data.name, " and mu = ", x$null.value) } else { table$Difference <- x$estimate[1] - x$estimate[2] means <- paste0(names(x$estimate), " = ", insight::format_value(x$estimate), collapse = ", " ) vars_full <- paste0(x$data.name, " (", means, ")") vars <- paste0(x$data.name) } text <- paste0( trimws(x$method), " testing the difference ", ifelse(grepl(" by ", x$data.name), "of ", "between "), vars_full ) } if (insight::model_info(x)$is_ranktest && !insight::model_info(x)$is_correlation) { if ("Parameter1" %in% names(table)) { vars_full <- paste0(table$Parameter1[[1]], " and ", table$Parameter2[[1]]) text <- paste0( trimws(x$method), " testing the difference in ranks between ", vars_full ) } else { vars_full <- paste0(table$Parameter[[1]]) text <- paste0( trimws(x$method), " testing the difference in rank for ", vars_full, " and true location of 0" ) } } as.report_model(text, summary = text) } report_info.htest <- function(x, effectsize = NULL, ...) { if (is.null(effectsize)) { effectsize <- report_effectsize(x, ...) } as.report_info(attributes(effectsize)$rules) } report_text.htest <- function(x, table = NULL, ...) { params <- report_parameters(x, table = table, ...) table <- attributes(params)$table model <- report_model(x, table = table, ...) info <- report_info(x, effectsize = attributes(params)$effectsize, ...) if (insight::model_info(x)$is_correlation) { text <- paste0( "The ", model, " is ", params ) text_full <- paste0( info, "\n\n", text ) } else { text_full <- paste0( info, "\n\nThe ", model, " suggests that the effect is ", params ) text <- paste0( "The ", model, " suggests that the effect is ", summary(params) ) } as.report_text(text_full, summary = text) }
.Random.seed <- c(403L, 624L, -30687743L, 2142122958L, 1257173495L, 362302924L, 1421191261L, -1218344070L, 1487659699L, -1629839272L, -275849607L, -181580826L, -301566673L, 1682848164L, -2060092331L, -545660654L, 102311275L, 1316251056L, 571432433L, 1812231934L, 815542119L, 182530172L, 1447436109L, -989136470L, 1377931043L, 138896904L, -1486676887L, 792204566L, -1106181985L, 289706580L, -508858043L, -598788798L, -1503395877L, 1374486880L, -1522796063L, 1452836398L, -1658730281L, 1410842412L, 1256542781L, -250809382L, -1550100589L, 1047173048L, -54012327L, 1749166662L, 57108495L, 1646663428L, -1632656843L, -1609132686L, -316770741L, -474904304L, -500133423L, 706568542L, -1730757049L, 166132188L, -1568521939L, 13269514L, 1684028419L, -2145438360L, 1679559753L, -1554085002L, 725658495L, -1761753164L, -1810821339L, 2123563426L, -730888005L, 1341979840L, -483646015L, 1309018254L, -774762569L, -1078337396L, -657724387L, -496595910L, 225918067L, 318783256L, 2038349369L, 2019571878L, -2137797905L, 1117168740L, -1654736875L, -1941472814L, 1883125547L, 1103780976L, 1378727345L, -695895106L, 199933223L, 867922748L, 1697731341L, -591123862L, -374908701L, -211241784L, -254874583L, 1138373078L, -1676163489L, -92558060L, -1981309691L, -831062526L, 1580302747L, 1926539296L, 1760838049L, -1265714450L, -1867004265L, -19484180L, -1428064771L, -1081715558L, -2055761581L, -2072799624L, -2052352487L, 1461679878L, -733766193L, 116908484L, 213564917L, 1797557810L, 900753419L, 1536614352L, -520173167L, -439040482L, -1617941497L, 1152818332L, -389327635L, 319818442L, 523167171L, 1073472552L, -344736759L, 675481654L, -1387376321L, 320225908L, -1398334747L, -653055390L, -136189317L, -481557632L, -477344383L, -1530225330L, -578097801L, 1673933644L, 698216413L, 1216630010L, 383014451L, 1721540056L, -1119461895L, -2112363162L, 1227808943L, -593375452L, -1271155755L, 264622738L, 2142046443L, 267326256L, -107229839L, -1734131586L, -981529881L, -1523550724L, 868763341L, -372892886L, 1580130979L, -1347370104L, 1845656553L, -1271853418L, -677622753L, -467302444L, 566724805L, -1216379198L, -239549605L, -1237643552L, -68400799L, 89239470L, 402883671L, -320838484L, 2037995965L, -914852518L, -389706989L, -111979208L, 944182745L, -1025408058L, 101553039L, 485256324L, -1755735627L, 1497581298L, 745281995L, 699070096L, 50118993L, -74913058L, 1265588679L, 1770061660L, 144713901L, 855530378L, 467619715L, -127970584L, 242428873L, -1757657866L, 1874441983L, -1660846796L, 1254155941L, -1898704094L, 938347579L, -327562688L, 1460417857L, -2000948722L, -69629129L, 1149060620L, 2062267293L, 444255674L, 1048784883L, -395330408L, -1968849479L, 789860902L, 228046447L, 1294973412L, -175345771L, 850717522L, -1239049557L, 1604487664L, 1612293425L, -417479362L, 1528371367L, 1375746236L, -439682419L, 1288752106L, -378000285L, 1004507720L, -557986903L, -855856298L, -1503751713L, -1727913324L, -989121403L, -1876373630L, 1387906331L, 1927296416L, -1780215519L, -1381931922L, -1597701609L, -1057695892L, -898826883L, -1616685542L, 2001028307L, 1271518200L, -1000712807L, 675827846L, 1048922447L, 516142916L, 1246508405L, -1825390670L, 856787851L, 1420676432L, 1877637393L, -405602L, 2050246535L, -888790500L, 96517229L, 559246410L, 1949399363L, 134840744L, 1826249609L, -1660272202L, -2008884033L, 1602189300L, 1780380261L, -124404766L, 1716776443L, 575033600L, 1433132289L, -1097201970L, 2055071991L, 1688148172L, -1066059939L, 1225395834L, 239323571L, -1489396904L, 1901911417L, 1544912614L, 1401834543L, 1862296740L, 1292954453L, 2111095826L, 1432874091L, -1750810448L, -1922614031L, -1229649410L, -1971788185L, -320160900L, 1593405005L, 648297642L, -2059192797L, 1454711048L, -1027548311L, -1694693354L, -31549537L, -1546551980L, 1332912197L, 288544834L, 854886107L, -1081861024L, 781949153L, -767698642L, 1488732119L, -573306324L, 1903976765L, -1832454438L, -1699299693L, -359198024L, -1717217959L, -1005331130L, -479543537L, 1195229700L, -246247115L, 28506226L, 1801502027L, -1554029552L, 260567249L, 1206350942L, -912329401L, 2080769244L, -1544744915L, 1591033098L, 31810307L, -1917161368L, 1718176585L, -1502806410L, -861289857L, 1162883764L, -964706779L, 790111394L, 349409211L, -76441664L, -1234484031L, -886776946L, 1731724983L, -2031375476L, -1376093411L, -2064511174L, -808049805L, 1908029976L, -1054098119L, -1512346714L, 1624416751L, -590098588L, 1720264469L, 971332818L, 1597242923L, -558516368L, 1229231281L, -1138159938L, -782339033L, -391119300L, 1125360141L, 1476423018L, -347078685L, 2129752008L, 1506519849L, -353229610L, -1801691809L, 1330878484L, 1555942405L, -1285709566L, 69798043L, 1927725856L, 2110972065L, 1474760174L, 766066071L, 1715338476L, 40338685L, -1281140838L, 2094659667L, 75174264L, -404220647L, -1828443642L, 444462287L, -1860531004L, 405581045L, 1300492594L, -1223053557L, -1669350704L, -1986713455L, -401483490L, -1754307833L, 1329637276L, 1726292973L, 742247882L, 1589316803L, 1748115240L, 450886409L, -534480074L, -760321985L, -114053772L, -609957403L, 186338658L, -1792216709L, -1363435904L, 298478721L, -216240050L, -1882725257L, 774045260L, -1220837667L, 1056100346L, -1929757389L, -693004072L, -1982702343L, 1764104294L, 992262063L, -244712924L, -1380637995L, 1873196434L, -1790324757L, 462777904L, 460434545L, 1815729022L, 1837744615L, 2014314748L, -170289715L, -2119868886L, -1788966493L, -212566392L, -1549911319L, 1234960790L, -543694049L, -1505201452L, 1219278789L, -1352062526L, -132691365L, 600320480L, -79042463L, -480443730L, -850658473L, 1022537644L, -789681987L, -755468198L, 124711443L, -2009739208L, -1629317927L, 1373189830L, -914429297L, -1223026812L, 177899701L, -546985486L, -1208196917L, -2033266288L, 1171398737L, -1254556194L, 23433415L, -680129956L, -1838614611L, -1974526326L, -462260605L, 909151720L, 1778281161L, 921745398L, -267334145L, -437655500L, -447900251L, 626996770L, -115338437L, 853828928L, -1085713343L, 994100494L, -2115141065L, -1660612340L, 267928221L, -1479782214L, 259004147L, 618641304L, -1693401927L, -1028291290L, -1471902353L, -947723036L, 1314184853L, -405221806L, 2036949419L, -184294160L, 1269728305L, -72918978L, 1555746727L, -1916091460L, -1693759091L, 72552170L, -1121004701L, -1298248376L, 1610123945L, 62561878L, 349251807L, 1936723348L, 788489093L, -32148862L, 8342555L, 686313632L, -557797343L, -648038546L, -1520142057L, 78783084L, -254735235L, -2121901798L, -466244653L, 612847352L, 1851053209L, 2102592390L, -1775394737L, 872178244L, -732158859L, -535289166L, -808922485L, 1762437200L, 1811863569L, 1142743710L, -448692601L, 1734749468L, 708348781L, 969486154L, -1395941309L, 1450556584L, -209413495L, 1469166774L, 982578111L, 909304564L, -549838491L, -693903646L, 309130491L, 1051454464L, -693634047L, 1750194638L, -1956061193L, -699276340L, -1410283939L, -1338076806L, -520638285L, 1795462744L, -2069439367L, -1890995738L, 770843439L, 970887076L, 875059797L, 725329682L, 1297265515L, -775873616L, -507831311L, 1597086974L, 1555144039L, -593475972L, 375962957L, 13205418L, 1551949091L, 2072960008L, 245013097L, 638450454L, 705179295L, 1099589716L, -344600763L, 1478654786L, -819917349L, -1727580320L, 536295393L, 1588538414L, -474827049L, 540824876L, 902787133L, 269285850L, 2095981971L, 1211076024L, -973155239L, 1378979910L, -431352305L, 1115778308L, 1093763125L, 945511282L, 541000779L, 167329552L, -472166447L, -377649314L, -524080057L, 298913756L, -233578707L, -1150550006L, -1853453821L, -406738072L, 389188169L, -1362661002L, -2014389889L, -724656716L, -2060817115L, 933840802L, 1926469307L, 1221735104L, 799433665L, -15749490L, -1174798921L, -1664518516L, 1055197725L, 151622202L, 1263602291L, 2011182360L, -1772831687L, 1805819558L, 300775663L, -482543004L, 183473685L, -2104541230L, 314950955L, -661843344L, -1520995407L, 1268294078L, -349295833L, -682587844L, 196210957L, 1472770154L, 756328163L, -857331000L, -280729047L, 2102794198L, -721619873L, 1532461844L, 433060613L, 911229954L, -709062757L, 1256513056L, 1991081889L, 1477140718L, 1979102359L, -1303296020L, 866751485L, -1890821478L, -78094509L, 569281656L, -710896615L, -852173562L, -543929393L, -580307004L, -589653003L, -1863363534L, -1960905205L, -262892080L)