code
stringlengths
1
13.8M
startShinyItemAnalysis <- function(background = TRUE, ...) { check_app_deps(...) run_app_script <- ' appDir <- system.file("ShinyItemAnalysis", package = "ShinyItemAnalysis") if (appDir == "") { stop("Could not find example directory. Try re-installing `ShinyItemAnalysis`.", call. = FALSE) } shiny::runApp(appDir, display.mode = "normal", launch.browser = TRUE) ' if (!isAvailable()) { message( "\n---------------------------------------------------------------\n", "ShinyItemAnalysis will run in the console as usual.\n", "To run the app in a background process, please use RStudio IDE.\n", "---------------------------------------------------------------" ) Sys.sleep(5) eval(parse(text = run_app_script)) } else if (background) { temp_script <- tempfile(fileext = ".R") writeLines(run_app_script, con = temp_script) job_id <- tryCatch( { jobRunScript(temp_script, name = "ShinyItemAnalysis") }, error = function(e) { message( "There was an error running the app as a background job.\n", "It is likely because of your username \"", Sys.info()[["user"]], "\" containing special characters.\n", "Please use `startShinyItemAnalysis(background = FALSE)`." ) return("fail") } ) if (job_id != "fail") { jobSetStatus( job_id, "The app is running in background. You can close it with the STOP button." ) executeCommand("activateConsole") message( "\n----------------------------------------------------------------\n", "ShinyItemAnalysis will start shortly as a background process.\n", "The process automatically stops as you close the browser window.\n", "----------------------------------------------------------------" ) } } else { eval(parse(text = run_app_script)) } } run_app <- function(background = TRUE, ...) { startShinyItemAnalysis(background = background, ...) } check_app_deps <- function(...) { suggests <- read.dcf(system.file("DESCRIPTION", package = "ShinyItemAnalysis"), fields = "Suggests") suggests <- trimws(strsplit(suggests, c(",", "\\("))[[1]]) suggests <- sapply(strsplit(suggests, "\\("), function(x) trimws(x[[1]])) suggests_installed <- sapply(suggests, function(x) requireNamespace(x, quietly = TRUE)) suggest_to_install <- suggests[!suggests_installed] n_pkg <- length(suggest_to_install) if (n_pkg > 0) { message( "Following ", ifelse(n_pkg > 1, "packages are", "package is"), " needed to run the app but ", ifelse(n_pkg > 1, "are", "is"), " not installed:" ) cat("", paste("-", suggest_to_install), "", sep = "\n") out <- utils::menu( choices = c("Yes", "No"), title = message("Do you want to install ", ifelse(n_pkg > 1, "them", "it"), "?") ) if (out == 1L) { utils::install.packages(pkgs = suggest_to_install, ...) } else { stop("The interactive Shiny app could not be started because of missing dependencies.", call. = FALSE) } } }
residuez <- function(b, a) { if (!is.vector(b) || !is.vector(a)) { stop("b and a must be vectors") } rpk <- residue(rev(b), rev(a)) p <- 1 / rpk$p m <- mpoles(p) r <- rpk$r * ((-p)^m) if (!is.null(rpk$k)) { k <- Conj(rev(rpk$k)) } else { k <- NULL } r <- zapIm(r) p <- zapIm(p) list(r = r, p = p, k = k) }
make_ga_4_req <- function(viewId, date_range=NULL, metrics=NULL, dimensions=NULL, dim_filters=NULL, met_filters=NULL, filtersExpression=NULL, order=NULL, segments=NULL, pivots=NULL, cohorts=NULL, pageToken=0, pageSize=1000, samplingLevel=c("DEFAULT", "SMALL","LARGE"), metricFormat=NULL, histogramBuckets=NULL) { samplingLevel <- match.arg(samplingLevel) if(!is.dim_filter_clause(dim_filters)){ assert_that_ifnn(dim_filters, is.dim_filter) } if(!is.met_filter_clause(met_filters)){ assert_that_ifnn(met_filters, is.met_filter) } assert_that_ifnn(filtersExpression, is.string) if(all(is.null(date_range), is.null(cohorts))){ stop("Must supply one of date_range or cohorts", call. = FALSE) } if(!is.null(cohorts)){ assert_that(cohort_metric_check(metrics), cohort_dimension_check(dimensions)) if(!is.null(date_range)){ stop("Don't supply date_range when using cohorts", call. = FALSE) } } if(is.null(metrics)){ stop("Must supply a metric", call. = FALSE) } if(!is.null(segments)){ if(!any("segment" %in% dimensions)){ dimensions <- c(dimensions, "segment") } } id <- sapply(viewId, checkPrefix, prefix = "ga") date_list_one <- date_ga4(date_range[1:2]) if(length(date_range) == 4){ date_list_two <- date_ga4(date_range[3:4]) } else { date_list_two <- NULL } dim_list <- dimension_ga4(dimensions, histogramBuckets) met_list <- metric_ga4(metrics, metricFormat) if(all(is.null(order), !is.null(histogramBuckets))){ bys <- intersect(dimensions, names(histogramBuckets)) order <- lapply(bys, order_type, FALSE, "HISTOGRAM_BUCKET") } request <- structure( list( viewId = id, dateRanges = list( date_list_one, date_list_two ), samplingLevel = samplingLevel, dimensions = dim_list, metrics = met_list, dimensionFilterClauses = dim_filters, metricFilterClauses = met_filters, filtersExpression = filtersExpression, orderBys = order, segments = segments, pivots = pivots, cohortGroup=cohorts, pageToken=as.character(pageToken), pageSize = pageSize, includeEmptyRows = TRUE ), class = "ga4_req") request <- rmNullObs(request) } google_analytics <- function(viewId, date_range=NULL, metrics=NULL, dimensions=NULL, dim_filters=NULL, met_filters=NULL, filtersExpression=NULL, order=NULL, segments=NULL, pivots=NULL, cohorts=NULL, max=1000, samplingLevel=c("DEFAULT", "SMALL","LARGE"), metricFormat=NULL, histogramBuckets=NULL, anti_sample = FALSE, anti_sample_batches = "auto", slow_fetch = FALSE, useResourceQuotas= NULL, rows_per_call = 10000L){ if(is_default_project()){ if(!interactive()){ default_project_message() stop("The default Google Cloud Project for googleAnalyticsR is intended \nfor evalutation only, not production scripts. \nPlease set your own client.id and client.secret via googleAuthR::gar_set_client() \nor otherwise as suggested on the website.", call. = FALSE) } } timer_start <- Sys.time() assert_that_ifnn(useResourceQuotas, is.flag) segments <- assign_list_class(segments, "segment_ga4") dim_filters <- assign_list_class(dim_filters, ".filter_clauses_ga4") met_filters <- assign_list_class(met_filters, ".filter_clauses_ga4") if(!is.null(filtersExpression)){ filtersExpression <- as(filtersExpression, "character") } assert_that(is.count(rows_per_call), rows_per_call <= 100000L) api_max_rows <- rows_per_call max <- as.integer(max) allResults <- FALSE if(max < 0){ max <- api_max_rows - 1L allResults <- TRUE } reqRowLimit <- as.integer(api_max_rows) if(!is.null(cohorts)){ anti_sample <- FALSE } if(anti_sample){ if(isTRUE(useResourceQuotas)){ stop("Can't use anti_sample=TRUE and useResourceQuoteas=TRUE in same API call (and you shouldn't need to)", call. = FALSE) } myMessage("anti_sample set to TRUE. Mitigating sampling via multiple API calls.", level = 3) return(anti_sample(viewId = viewId, date_range = date_range, metrics = metrics, dimensions = dimensions, dim_filters = dim_filters, met_filters = met_filters, filtersExpression = filtersExpression, order = order, segments = segments, pivots = pivots, cohorts = cohorts, metricFormat = metricFormat, histogramBuckets = histogramBuckets, anti_sample_batches = anti_sample_batches, slow_fetch = slow_fetch, rows_per_call = rows_per_call)) } if(max > reqRowLimit){ myMessage("Multi-call to API", level = 1) } meta_batch_start_index <- seq(from=0, to=max, by=reqRowLimit) requests <- lapply(meta_batch_start_index, function(start_index){ start_index <- as.integer(start_index) if(allResults){ remaining <- as.integer(api_max_rows) } else { remaining <- min(as.integer(max - start_index), reqRowLimit) } make_ga_4_req(viewId = viewId, date_range = date_range, metrics = metrics, dimensions = dimensions, dim_filters = dim_filters, met_filters = met_filters, filtersExpression = filtersExpression, order = order, segments = segments, pivots = pivots, cohorts = cohorts, pageToken = start_index, pageSize = remaining, samplingLevel = samplingLevel, metricFormat = metricFormat, histogramBuckets = histogramBuckets) }) if(slow_fetch){ out <- fetch_google_analytics_4_slow(requests, max_rows = max, allRows = allResults, useResourceQuotas = useResourceQuotas) allResults <- FALSE } else { out <- fetch_google_analytics_4(requests, merge = TRUE, useResourceQuotas = useResourceQuotas) } if(allResults){ all_rows <- as.integer(attr(out, "rowCount")) if(!is.null(out) && nrow(out) < all_rows){ meta_batch_start_index2 <- tryCatch(seq(from=api_max_rows, to=all_rows, by=reqRowLimit), error = function(ex){ stop("Sequence batch error: ", "\n api_max_rows: ",api_max_rows, "\n all_rows:", all_rows, "\n reqRowLimit:", reqRowLimit, call. = FALSE) }) requests2 <- lapply(meta_batch_start_index2, function(start_index){ start_index <- as.integer(start_index) remaining <- as.integer(api_max_rows) make_ga_4_req(viewId = viewId, date_range = date_range, metrics = metrics, dimensions = dimensions, dim_filters = dim_filters, met_filters = met_filters, filtersExpression = filtersExpression, order = order, segments = segments, pivots = pivots, cohorts = cohorts, pageToken = start_index, pageSize = remaining, samplingLevel = samplingLevel, metricFormat = metricFormat, histogramBuckets = histogramBuckets) }) slow <- FALSE the_rest <- tryCatch(fetch_google_analytics_4(requests2, merge = TRUE, useResourceQuotas = useResourceQuotas), error = function(ex){ myMessage("Error requesting v4 batch - retrying with slow_fetch=TRUE ...", level = 3) slow <<- TRUE Sys.sleep(5) fetch_google_analytics_4_slow(requests, max_rows = max, allRows = allResults, useResourceQuotas=useResourceQuotas) }) if(!slow){ out <- rbind(out, the_rest) } else { out <- the_rest } myMessage("All data downloaded, total of [",all_rows,"] - download time: ", format(Sys.time() - timer_start), level = 3) } else { myMessage("One batch enough to get all results", level = 1) } } sampling_message(attr(out, "samplesReadCounts"), attr(out, "samplingSpaceSizes"), hasDateComparison = any(grepl("\\.d1|\\.d2", names(out)))) out } google_analytics_4 <- function(...){ .Deprecated("google_analytics", package = "googleAnalyticsR") google_analytics(...) } fetch_google_analytics_4_slow <- function(request_list, max_rows, allRows = FALSE, useResourceQuotas=NULL){ myMessage("Calling APIv4 slowly....", level = 2) f <- get_ga4_function() do_it <- TRUE the_req <- request_list[[1]] actualRows <- max_rows response_list <- list() while(do_it){ body <- list( reportRequests = the_req, useResourceQuotas = useResourceQuotas ) body <- rmNullObs(body) myMessage("Slow fetch: [", the_req$pageToken, "] from estimated actual Rows [", actualRows, "]", level = 3) out <- tryCatch(f(the_body = body), error = function(err){ custom_error(err) }) actualRows <- attr(out[[1]], "rowCount") npt <- attr(out[[1]], "nextPageToken") if(allRows){ max_rows <- as.integer(actualRows) } if(is.null(npt) || as.integer(npt) >= max_rows){ do_it <- FALSE } the_req$pageToken <- npt response_list <- c(response_list, out) } Reduce(rbind, response_list) } fetch_google_analytics_4 <- function(request_list, merge = FALSE, useResourceQuotas = NULL){ assert_that(is.list(request_list)) ga_batch_limit <- 5 if(length(unique((lapply(request_list, function(x) x$viewId)))) != 1){ stop("request_list must all have the same viewId", call. = FALSE) } if(length(unique((lapply(request_list, function(x) x$dateRanges)))) != 1){ stop("request_list must all have the same dateRanges", call. = FALSE) } if(length(unique((lapply(request_list, function(x) x$segments)))) != 1){ stop("request_list must all have the same segments", call. = FALSE) } if(length(unique((lapply(request_list, function(x) x$samplingLevel)))) != 1){ stop("request_list must all have the same samplingLevel", call. = FALSE) } if(length(unique((lapply(request_list, function(x) x$cohortGroup)))) != 1){ stop("request_list must all have the same cohortGroup", call. = FALSE) } myMessage("Calling APIv4....", level = 2) f <- get_ga4_function() if(!is.null(request_list$viewId) || length(request_list) <= ga_batch_limit){ myMessage("Single v4 batch", level = 2) request_list <- unitToList(request_list) body <- list( reportRequests = request_list, useResourceQuotas = useResourceQuotas ) body <- rmNullObs(body) out <- tryCatch(f(the_body = body), error = function(err){ custom_error(err) }) } else { myMessage("Multiple v4 batch", level = 2) request_list_index <- seq(1, length(request_list), ga_batch_limit) batch_list <- lapply(request_list_index, function(x) request_list[x:(x+(ga_batch_limit-1))]) body_list <- lapply(batch_list, function(x){ bb <- list(reportRequests = x, useResourceQuotas = useResourceQuotas) rmNullObs(bb) }) body_list <- rmNullObs(body_list) myMessage("Looping over maximum [", length(body_list), "] batches.", level = 1) response_list <- lapply(body_list, function(b){ myMessage("Fetching v4 data batch...", level = 3) out <- tryCatch(f(the_body = b), error = function(err){ custom_error(err) }) }) out <- unlist(response_list, recursive = FALSE) } if(length(out) == 1){ out <- out[[1]] } else { if(merge){ if(all(vapply(out, is.null, logical(1)))){ out <- NULL } else { df_names <- rmNullObs(lapply(out, function(x) names(x))) if(length(unique(df_names)) != 1){ stop("List of dataframes have non-identical column names. Got ", paste(lapply(out, function(x) names(x)), collapse = " ")) } out <- Reduce(rbind, out) } } } myMessage("Downloaded [",NROW(out),"] rows from a total of [",attr(out, "rowCount"), "].", level = 3) out } get_ga4_function <- function(){ the_user <- getOption("googleAnalyticsR.quotaUser", Sys.info()[["user"]]) if(the_user != Sys.info()[["user"]]){ myMessage("Fetching API under quotaUser: ", the_user, level =3) } gar_api_generator("https://analyticsreporting.googleapis.com/v4/reports:batchGet", "POST", pars_args = list(quotaUser = the_user), data_parse_function = google_analytics_4_parse_batch, simplifyVector = FALSE) }
svds <- function(A, NSvals, which="L", tol=1e-6, u0=NULL, v0=NULL, orthou=NULL, orthov=NULL, prec=NULL, isreal=NULL, ...) { opts <- list(...); if (is.function(A)) { if (!.is.wholenumber(opts$n) || !.is.wholenumber(opts$m)) stop("matrix dimension not set (set 'm' and 'n')"); Af <- A; Aarg <- A; isreal_suggestion <- FALSE; } else if (length(dim(A)) != 2) { stop("A should be a matrix or a function") } else { opts$m <- nrow(A); opts$n <- ncol(A); if (is.matrix(A) && (is.integer(A) || is.logical(A))) { A <- as.double(A); dim(A) = c(opts$m, opts$n); } ismatrix <- (is.matrix(A) && (is.double(A) || is.complex(A))); isreal_suggestion <- if (ismatrix) is.double(A) else (inherits(A, "Matrix") && substr(class(A), 0, 1) == "d"); Af <- function(x,trans) if (trans == "n") A %*% x else crossprod(A,x); Afc <- function(x,trans) if (trans == "n") A %*% x else Conj(t(crossprod(Conj(x),A))); if ((is.null(isreal) || isreal == isreal_suggestion) && ( ismatrix || any(c("dmatrix", "dgeMatrix", "dgCMatrix", "dsCMatrix") %in% class(A)))) { Aarg <- A; } else if ("ddiMatrix" %in% class(A)) { Af <- function(x,trans) A %*% x; Aarg <- Af; } else { Aarg <- if (isreal_suggestion) Af else Afc; } } if (!.is.wholenumber(NSvals) || NSvals > min(opts$m, opts$n)) stop("NSvals should be an integer not greater than the smallest dimension of the matrix"); opts$numSvals <- NSvals targets = list(L="primme_svds_largest", S="primme_svds_smallest"); if (is.character(which) && which %in% names(targets)) { opts$target <- targets[[which]]; } else if (is.numeric(which)) { opts$targetShifts <- which; opts$target <- "primme_svds_closest_abs"; } else { stop("target should be numeric or L or S"); } if (!is.numeric(tol) || tol < 0 || tol >= 1) { stop("tol should be a positive number smaller than 1 or a function") } else { opts$eps <- tol; } check_uv <- function(u, v, u_name, v_name) { if (!is.null(u) && (!is.matrix(u) || nrow(u) != opts$m)) { stop(paste(u_name, "should be NULL or a matrix with the same number of rows as A")) } else if (!is.null(u) && is.null(v)) { v <- Af(u, "c"); } if (!is.null(v) && (!is.matrix(v) || nrow(v) != opts$n)) { stop(paste(v_name, "should be NULL or a matrix with the same number of rows as columns A has")) } else if (!is.null(v) && is.null(u)) { u <- Af(v, "n"); } if (is.null(u) && is.null(v)) list(u=matrix(nrow=0, ncol=0), v=matrix(nrow=0, ncol=0)) else list(u=u, v=v); } ortho <- check_uv(orthou, orthov, "orthou", "orthov"); init <- check_uv(u0, v0, "u0", "v0"); if (is.null(prec) || is.function(prec)) { precf <- prec } else if (!is.list(prec)) { stop("prec should be a function or a list(AHA=...,AAH=...,aug=...)") } else if (!is.null(prec$AHA) && !is.function(prec$AHA) && (!is.matrix(prec$AHA) || length(dim(prec$AHA)) != 2 || ncol(prec$AHA) != opts$n || nrow(prec$AHA) != opts$n)) { stop("prec$AHA should be a function or a square matrix of dimension ncol(A)") } else if (!is.null(prec$AAH) && !is.function(prec$AAH) && (!is.matrix(prec$AAH) || length(dim(prec$AAH)) != 2 || ncol(prec$AAH) != opts$m || nrow(prec$AAH) != opts$m)) { stop("prec$AAH should be a function or a square matrix of dimension nrow(A)") } else if (!is.null(prec$aug) && !is.function(prec$aug) && (!is.matrix(prec$aug) || length(dim(prec$aug)) != 2 || ncol(prec$aug) != opts$m+opts$n || nrow(prec$aug) != opts$m+opts$n)) { stop("prec$aug should be a function or a square matrix of dimension nrow(A)+ncol(A)") } else { tofunc <- function(x) if (is.function(x)) x else if (is.null(x)) identity else function(v) solve(x, v); precf <- function(x, mode) tofunc(prec[[mode]])(x); } methodStage1 <- opts[["methodStage1"]]; opts$methodStage1 <- NULL; methodStage2 <- opts[["methodStage2"]]; opts$methodStage2 <- NULL; method <- opts[["method"]]; opts$method <- NULL; if (!is.null(isreal) && !is.logical(isreal)) { stop("isreal should be logical"); } else if (is.null(isreal)) { isreal <- isreal_suggestion; } primme_svds <- .primme_svds_initialize(); for (x in names(opts)) { if (is.list(opts[[x]])) { primme <- .primme_svds_get_member(x, primme_svds); for (primmex in names(opts[[x]])) .primme_set_member(primmex, opts[[x]][[primmex]], primme); } else { .primme_svds_set_member(x, opts[[x]], primme_svds); } } if (!is.null(method) || !is.null(methodStage1) || !is.null(methodStage2)) { if (is.null(method)) method <- "primme_svds_default"; if (is.null(methodStage1)) methodStage1 <- "PRIMME_DEFAULT_METHOD"; if (is.null(methodStage2)) methodStage2 <- "PRIMME_DEFAULT_METHOD"; .primme_svds_set_method(method, methodStage1, methodStage2, primme_svds); } r <- if (!isreal) .zprimme_svds(ortho$u, ortho$v, init$u, init$v, Aarg, precf, primme_svds) else .dprimme_svds(ortho$u, ortho$v, init$u, init$v, Aarg, precf, primme_svds) r$stats$numMatvecs <- .primme_svds_get_member("stats_numMatvecs", primme_svds) r$stats$numPreconds <- .primme_svds_get_member("stats_numPreconds", primme_svds) r$stats$elapsedTime <- .primme_svds_get_member("stats_elapsedTime", primme_svds) r$stats$estimateANorm <- .primme_svds_get_member("aNorm", primme_svds) r$stats$timeMatvec <- .primme_svds_get_member("stats_timeMatvec", primme_svds) r$stats$timePrecond <- .primme_svds_get_member("stats_timePrecond", primme_svds) r$stats$timeOrtho <- .primme_svds_get_member("stats_timeOrtho", primme_svds) .primme_svds_free(primme_svds); if (r$ret != 0) stop(.getSvdsErrorMsg(r$ret)) else r$ret <- NULL; r } .getSvdsErrorMsg <- function(n) { l <- list( "0" = "success", "-1" = "unexpected internal error; please consider to set 'printLevel' to a value larger than 0 to see the call stack and to report these errors because they may be bugs", "-2" = "memory allocation failure", "-3" = "maximum iterations or matvecs reached", "-4" = "primme_svds is NULL", "-5" = "Wrong value for m or n or mLocal or nLocal", "-6" = "Wrong value for numProcs", "-7" = "matrixMatvec is not set", "-8" = "applyPreconditioner is not set but precondition == 1 ", "-9" = "numProcs >1 but globalSumDouble is not set", "-10" = "Wrong value for numSvals, it's larger than min(m, n)", "-11" = "Wrong value for numSvals, it's smaller than 1", "-13" = "Wrong value for target", "-14" = "Wrong value for method", "-15" = "Not supported combination of method and methodStage2", "-16" = "Wrong value for printLevel", "-17" = "svals is not set", "-18" = "svecs is not set", "-19" = "resNorms is not set", "-40" = "some LAPACK function performing a factorization returned an error code; set 'printLevel' > 0 to see the error code and the call stack", "-41" = "error happened at the matvec or applying the preconditioner", "-42" = "the matrix provided in 'lock' is not full rank", "-43" = "parallel failure", "-44" = "unavailable functionality; PRIMME was not compiled with support for the requesting precision or for GPUs"); if (n >= -100) l[[as.character(n)]] else if (n >= -200) paste("Error from PRIMME first stage:", .getEigsErrorMsg(n+100)) else if (n >= -300) paste("Error from PRIMME second stage:", .getEigsErrorMsg(n+200)) else "Unknown error code"; }
iquantile <- function (x, ...) UseMethod("iquantile")
library(uwot) context("normalized laplacian") test_that("normalized laplacian", { expected_norm_lap <- c2y( 0.7477, -0.1292, -0.03001, 0.02127, -0.563, -0.01149, 0.1402, -0.2725, -0.01241, 0.1084, -0.106, -0.5723, 0.2024, -0.3082, 0.1642, -5.549e-05, -0.04843, -0.1747, 0.1684, 0.6611 ) res <- normalized_laplacian_init(Matrix::drop0(x2d(iris[1:10, ]))) expect_equal(abs(res), abs(expected_norm_lap), tolerance = 0.2) }) test_that("laplacian eigenmap", { expected_lap_eig <- matrix( c(0.21050269, -0.07732118, 0.63486516, -0.33501476, 0.11755963, -0.40229306, -0.36728785, 0.38404235, 0.020391 , 0.20458482, -0.04123934, -0.44198941, -0.3841261 , -0.47833969, 0.17196966, 0.3883986 , -0.03743132, -0.22790212, -0.36483447, -0.32492041, 0.01860336, -0.27419176, 0.68954246, 0.34392682, 0.04537549, 0.14056785, 0.12175907, 0.39742651, -0.00077821, 0.15609656), ncol = 3, byrow = TRUE) A <- matrix( c(0, 0.0288109, 0.053397, 0.104038, 0.079341, 0.145439, 0.0946093, 0.0434563, 0.139317, 0.189191, 0.0288109, 0, 0.176753, 0.126438, 0.100761, 0.108501, 0.197306, 0.0744967, 0.0940433, 0.0614212, 0.053397, 0.176753, 0, 0.0544213, 0.0662712, 0.0462358, 0.124431, 0.0876854, 0.162838, 0.0494398, 0.104038, 0.126438, 0.0544213, 0, 0.0725848, 0.322066, 0.107206, 0.0395971, 0.164969, 0.130029, 0.079341, 0.100761, 0.0662712, 0.0725848, 0, 0.0532904, 0.255125, 0.0290714, 0.0634819, 0.0482673, 0.145439, 0.108501, 0.0462358, 0.322066, 0.0532904, 0, 0.0748701, 0.0202419, 0.187683, 0.380222, 0.0946093, 0.197306, 0.124431, 0.107206, 0.255125, 0.0748701, 0, 0.0273237, 0.142702, 0.0647643, 0.0434563, 0.0744967, 0.0876854, 0.0395971, 0.0290714, 0.0202419, 0.0273237, 0, 0.0584841, 0.0431531, 0.139317, 0.0940433, 0.162838, 0.164969, 0.0634819, 0.187683, 0.142702, 0.0584841, 0, 0.158817, 0.189191, 0.0614212, 0.0494398, 0.130029, 0.0482673, 0.380222, 0.0647643, 0.0431531, 0.158817, 0), nrow = 10) res <- laplacian_eigenmap(A, ndim = 3) expect_equal(abs(res), abs(expected_lap_eig), tolerance = 1e-4) expect_equal(abs(irlba_laplacian_eigenmap(A, ndim = 3)), abs(expected_lap_eig), tolerance = 1e-4) })
MODIStsp_get_prodlayers <- function(prodname) { stopifnot(inherits(prodname, "character")) prod_opt_list <- load_prodopts() selprod <- prod_opt_list[grep(prodname, names(prod_opt_list))] if (length(selprod) == 0){ if (prodname %in% names(prod_opt_list)) { selprod <- prod_opt_list[prodname] } else { stop("Invalid product name. Aborting! prodname should be a MODIS product code (e.g., \"M*D13Q1\"), or full MODIStsp product name (e.g., \"Vegetation Indexes_16Days_250m (M*D13Q1)\")") } } prodname <- names(selprod) selprod <- selprod[[1]][["6"]] bandnames <- selprod[["bandnames"]] band_fullnames <- selprod[["band_fullnames"]] quality_bandnames <- selprod[["quality_bandnames"]] quality_fullnames <- selprod[["quality_fullnames"]] indexes_bandnames <- selprod[["indexes_bandnames"]] indexes_fullnames <- selprod[["indexes_fullnames"]] cust_ind <- jsonlite::read_json(system.file("ExtData", "MODIStsp_indexes.json", package = "MODIStsp")) if (length(cust_ind) == 1) { cust_ind <- NULL } else { cust_ind <- cust_ind[[prodname]][["6"]] } indexes_bandnames <- c(indexes_bandnames, cust_ind$indexes_bandnames) indexes_fullnames <- c(indexes_fullnames, cust_ind$indexes_fullnames) prodnames <- list(prodname = prodname, bandnames = bandnames, bandfullnames = band_fullnames, quality_bandnames = quality_bandnames, quality_fullnames = quality_fullnames, indexes_bandnames = indexes_bandnames, indexes_fullnames = indexes_fullnames) prodnames } MODIStsp_get_prodnames <- function() { prod_opt_list <- load_prodopts() names(prod_opt_list) }
source("ESEUR_config.r") library("COMPoissonReg") library("gamlss") library("gamlss.tr") pal_col=rainbow(3) o_struct=read.csv(paste0(ESEUR_dir, "probability/bolz_data_struct_racket.csv.xz"), as.is=TRUE) struct=subset(o_struct, size < 15) pos_struct=subset(struct, size > 0) all_sizes=rep(struct$size, times=struct$fields) pos_sizes=rep(pos_struct$size, times=pos_struct$fields) nbi_mod=gamlss(all_sizes ~ 1, family=NBI) nbi_pred=sapply(0:12, function(y) length(all_sizes)* dNBI(y, mu=exp(coef(nbi_mod, what="mu")), sigma=exp(coef(nbi_mod, what="sigma")))) cmp_mod=glm.cmp(all_sizes ~ 1, formula.nu=all_sizes~1, beta.init=2.0) cmp_pred=sapply(0:12, function(y) length(all_sizes)* dcmp(y, lambda=exp(cmp_mod$beta), nu=exp(cmp_mod$gamma))) plot(struct$size, struct$fields, log="y", col=pal_col[1], xlab="Fields", ylab="Structure types\n") lines(0:12, cmp_pred, col=pal_col[2]) lines(0:12, nbi_pred, col=pal_col[3])
FDistribution <- R6Class("FDistribution", inherit = SDistribution, lock_objects = F, public = list( name = "FDistribution", short_name = "F", description = "F Probability Distribution.", packages = "stats", initialize = function(df1 = NULL, df2 = NULL, decorators = NULL) { super$initialize( decorators = decorators, support = PosReals$new(zero = FALSE), type = PosReals$new(zero = TRUE) ) }, mean = function(...) { df1 <- unlist(self$getParameterValue("df1")) df2 <- unlist(self$getParameterValue("df2")) mean <- rep(NaN, length(df1)) mean[df2 > 2] <- df2[df2 > 2] / (df2[df2 > 2] - 2) return(mean) }, mode = function(which = "all") { df1 <- unlist(self$getParameterValue("df1")) df2 <- unlist(self$getParameterValue("df2")) mode <- rep(NaN, length(df1)) mode[df1 > 2] <- ((df1[df1 > 2] - 2) * df2[df1 > 2]) / (df1[df1 > 2] * (df2[df1 > 2] + 2)) return(mode) }, variance = function(...) { df1 <- unlist(self$getParameterValue("df1")) df2 <- unlist(self$getParameterValue("df2")) var <- rep(NaN, length(df1)) var[df2 > 4] <- 2 * (df2[df2 > 4])^2 * (df1[df2 > 4] + df2[df2 > 4] - 2) / (df1[df2 > 4] * (df2[df2 > 4] - 2)^2 * (df2[df2 > 4] - 4)) return(var) }, skewness = function(...) { df1 <- unlist(self$getParameterValue("df1")) df2 <- unlist(self$getParameterValue("df2")) skew <- rep(NaN, length(df1)) skew[df2 > 6] <- ((2 * df1[df2 > 6] + df2[df2 > 6] - 2) * sqrt(8 * (df2[df2 > 6] - 4))) / (((df2[df2 > 6] - 6) * sqrt(df1[df2 > 6] * (df1[df2 > 6] + df2[df2 > 6] - 2)))) return(skew) }, kurtosis = function(excess = TRUE, ...) { df1 <- unlist(self$getParameterValue("df1")) df2 <- unlist(self$getParameterValue("df2")) exkurtosis <- rep(NaN, length(df1)) exkurtosis[df2 > 8] <- (12 * (df1[df2 > 8] * (5 * df2[df2 > 8] - 22) * (df1[df2 > 8] + df2[df2 > 8] - 2) + (df2[df2 > 8] - 4) * (df2[df2 > 8] - 2)^2)) / (df1[df2 > 8] * (df2[df2 > 8] - 6) * (df2[df2 > 8] - 8) * (df1[df2 > 8] + df2[df2 > 8] - 2)) if (excess == TRUE) { return(exkurtosis) } else { return(exkurtosis + 3) } }, entropy = function(base = 2, ...) { df1 <- unlist(self$getParameterValue("df1")) df2 <- unlist(self$getParameterValue("df2")) return(log(gamma(df1 / 2), base) + log(gamma(df2 / 2), base) - log(gamma((df1 + df2) / 2), base) + log(df1 / df2, base) + (1 - df1 / 2) * digamma(1 + df1 / 2) - (1 + df2 / 2) * digamma(1 + df2 / 2) + ((df1 + df2) / 2) * digamma((df1 + df2) / 2)) }, mgf = function(t, ...) { return(NaN) }, pgf = function(z, ...) { return(NaN) } ), active = list( properties = function() { prop <- super$properties prop$support <- if (self$getParameterValue("df1") == 1) { prop$support <- PosReals$new(zero = FALSE) } else { prop$support <- PosReals$new(zero = TRUE) } prop } ), private = list( .pdf = function(x, log = FALSE) { df1 <- self$getParameterValue("df1") df2 <- self$getParameterValue("df2") call_C_base_pdqr( fun = "df", x = x, args = list( df1 = unlist(df1), df2 = unlist(df2) ), log = log, vec = test_list(df1) ) }, .cdf = function(x, lower.tail = TRUE, log.p = FALSE) { df1 <- self$getParameterValue("df1") df2 <- self$getParameterValue("df2") call_C_base_pdqr( fun = "pf", x = x, args = list( df1 = unlist(df1), df2 = unlist(df2) ), lower.tail = lower.tail, log = log.p, vec = test_list(df1) ) }, .quantile = function(p, lower.tail = TRUE, log.p = FALSE) { df1 <- self$getParameterValue("df1") df2 <- self$getParameterValue("df2") call_C_base_pdqr( fun = "qf", x = p, args = list( df1 = unlist(df1), df2 = unlist(df2) ), lower.tail = lower.tail, log = log.p, vec = test_list(df1) ) }, .rand = function(n) { df1 <- self$getParameterValue("df1") df2 <- self$getParameterValue("df2") call_C_base_pdqr( fun = "rf", x = n, args = list( df1 = unlist(df1), df2 = unlist(df2) ), vec = test_list(df1) ) }, .traits = list(valueSupport = "continuous", variateForm = "univariate") ) ) .distr6$distributions <- rbind( .distr6$distributions, data.table::data.table( ShortName = "F", ClassName = "FDistribution", Type = "\u211D+", ValueSupport = "continuous", VariateForm = "univariate", Package = "stats", Tags = "" ) )
geometricsummary <- function (g,N,studentize,center,cbb,joint) { wr1<- g$x-g$pred.x wr2<- g$y-g$pred.y if (center==TRUE) { wr1 <- wr1 - mean(wr1) wr2 <- wr2 - mean(wr2) } n <- g$fit.statistics["n"] if (is.numeric(cbb)==TRUE){ k <- n/cbb if (abs(k-round(k)) > 0.00001 || cbb <= 0 || abs(cbb-round(cbb)) > 0.00001) stop("invalid value for cbb.")} if (studentize==TRUE) { Xmat <- cbind(rep(1,n),sin(g$period.time),cos(g$period.time)) h <- Xmat%*%solve(crossprod(Xmat))%*%t(Xmat) r.Ta <- wr1/sqrt(1-diag(h)) r.Tb <- wr2/sqrt(1-diag(h)) wr1 <- r.Ta-mean(r.Ta) wr2 <- r.Tb-mean(r.Tb) } hystenv$warningcountHysteresis <- 0 bootdat <- mapply(geometricbootwrapper, j=1:N, MoreArgs=list(wr1=wr1,wr2=wr2,x.pred=g$pred.x,y.pred=g$pred.y,n=n,cbb=cbb,joint=joint)) bootint2 <- matrix(internal.1(bootdat[4,],bootdat[5,],bootdat[3,]),nrow=N,ncol=3) bootderived <- matrix(derived.1(bootdat[4,],bootdat[5,],bootdat[3,],bootint2[,1],bootint2[,2],bootint2[,3],rep(g$fit.statistics["period"],N)),nrow=N,ncol=3) bootamps <- matrix(derived.amps(bootint2[,1],bootint2[,2],bootint2[,3]),nrow=N,ncol=5) bootfocus <- matrix(derived.focus(bootdat[4,],bootdat[5,],bootdat[3,]),nrow=N,ncol=3) bootdat <- data.frame(t(bootdat),bootderived,bootint2,bootamps,bootfocus,rep(g$fit.statistics["n"],N)) colnames(bootdat) <- names(g$values) if (diff(range(bootdat[,"rote.deg"])) > 170) warning("Bootstrapped rote.deg values on both sides of 0, 180 degrees.") if (hystenv$warningcountHysteresis > 0) warning("Failed to converge ",hystenv$warningcountHysteresis," times.") error<-apply(bootdat,2,sd,na.rm=T) themean<-apply(bootdat,2,mean,na.rm=T) ranges<-apply(bootdat,2,quantile,probs=c(0.025,0.25,0.5,0.75,0.975),na.rm=T) full <- data.frame(g$values,t(ranges),error,themean) colnames(full) <- c("Orig.Estimate","B.q0.025","B.q0.25","B.q0.5","B.q0.75","B.q0.975","Std.Error","Boot.Mean") full$Bias <- full$Boot.Mean-full$Orig.Estimate full$Boot.Estimate <- full$Orig.Estimate-full$Bias full[,c("B.q0.025","B.q0.25","B.q0.5","B.q0.75","B.q0.975")]<-full[,c("B.q0.025","B.q0.25","B.q0.5","B.q0.75","B.q0.975")]- 2*full$Bias rad<-g$period.time+full["Ta.phase","Boot.Estimate"] pred.x<-full["b.x","Boot.Estimate"]*cos(rad)+full["cx","Boot.Estimate"] pred.y<-full["b.y","Boot.Estimate"]*cos(rad)+full["retention","Boot.Estimate"]*sin(rad)+full["cy","Boot.Estimate"] full <- full[c("b.x","b.y","phase.angle", "cx","cy","retention","coercion","area", "lag","split.angle","hysteresis.x","hysteresis.y","ampx","ampy","rote.deg","rote.rad", "semi.major","semi.minor","focus.x","focus.y","eccentricity"),] bootEst<-full[,"Boot.Estimate"] names(bootEst) <- rownames(full) bootStd<-full[,"Std.Error"] names(bootStd) <- rownames(full) full2<-list("values"=full,"Boot.Estimates"=bootEst,"Boot.Std.Errors"=bootStd, "fit.statistics"=g$fit.statistics,"pred.x"=g$pred.x,"pred.y"=g$pred.y, "x"=g$x,"y"=g$y,"call"=g$call,"method"=g$method,"boot.data"=bootdat, "Delta.Std.Errors"=g$Std.Errors) invisible(full2) }
context("Statistical Helper Functions") test_that("function seVar gives correct results", { expect_equal(seVar(testData$t1), 81.6643849025553) expect_equivalent(seVar(testData[c("t1", "t2")]), c(81.6643849025553, 0.0381738341194061)) expect_equivalent(seVar(as.matrix(testData[c("t1", "t2")])), c(81.6643849025553, 0.0381738341194061)) expect_equal(seVar(testData$t3), NA_real_) expect_equal(seVar(testData$t3, na.rm = TRUE), 10.7842792902852) expect_equivalent(seVar(testData[c("t1", "t3")]), c(81.6643849025553, NA)) expect_equivalent(seVar(testData[c("t1", "t3")], na.rm = TRUE), c(81.6643849025553, 10.7842792902852)) }) test_that("function skewness gives correct results", { expect_equal(skewness(testData$t1), 0.626728847814835) expect_equivalent(skewness(testData[c("t1", "t2")]), c(0.626728847814835, -0.0584844288330201)) expect_equivalent(skewness(as.matrix(testData[c("t1", "t2")])), c(0.626728847814835, -0.0584844288330201)) expect_equal(skewness(testData$t3), NA_real_) expect_equal(skewness(testData$t3, na.rm = TRUE), -0.0683589419435095) expect_equivalent(skewness(testData[c("t1", "t3")]), c(0.626728847814835, NA)) expect_equivalent(skewness(testData[c("t1", "t3")], na.rm = TRUE), c(0.626728847814835, -0.0683589419435095)) }) test_that("function seSkewness gives correct results", { expect_equal(seSkewness(100), 0.24137977904013) expect_warning(seSkew <- seSkewness(2), "the standard error of skewness cannot be calculated") expect_equal(seSkew, NA) }) test_that("function kurtosis gives correct results", { expect_equal(kurtosis(testData$t1), -0.371370665680684) expect_equivalent(kurtosis(testData[c("t1", "t2")]), c(-0.371370665680684, -0.322837145891091)) expect_equivalent(kurtosis(as.matrix(testData[c("t1", "t2")])), c(-0.371370665680684, -0.322837145891091)) expect_equal(kurtosis(testData$t3), NA_real_) expect_equal(kurtosis(testData$t3, na.rm = TRUE), -0.4226177429994) expect_equivalent(kurtosis(testData[c("t1", "t3")]), c(-0.371370665680684, NA)) expect_equivalent(kurtosis(testData[c("t1", "t3")], na.rm = TRUE), c(-0.371370665680684, -0.4226177429994)) }) test_that("function seKurtosis gives correct results", { expect_equal(seKurtosis(100), 0.478331132994813) expect_warning(seKurt <- seKurtosis(2), "the standard error of kurtosis cannot be calculated") expect_equal(seKurt, NA) })
Outp3state <- function(data, v, ...) { return( data.frame("times1"=data[,v[1]], "delta"=as.integer(data[,v[3]] > data[,v[1]]), "times2"=data[,v[3]]-data[,v[1]], "time"=data[,v[3]], "status"=data[,v[4]], data[,-v]) ) }
"%==%"<- function(a,b){ if (length(a)==1){ (1:length(b))[a == b] }else if(length(a) > 1){ for (i in 1:length(a)) { if (i==1){location=list()} location.i=(1:length(b))[a[i] == b] location=c(location,list(location.i)) names(location)[length(location)]=a[i] } location } }
UnivarMixingDistribution <- function(..., Dlist, mixCoeff, withSimplify = getdistrOption("simplifyD")) { ldots <- list(...) if(!missing(Dlist)){ Dlist.L <- as(Dlist, "list") if(!is(try(do.call(UnivarDistrList,args=Dlist.L),silent=TRUE),"try-error")) ldots <- c(ldots, Dlist.L) } l <- length(ldots) if(l==0) stop ("No components given") if(l==1) return(ldots[[1]]) mixDistr <- do.call(UnivarDistrList,args=ldots) ep <- .Machine$double.eps if(missing(mixCoeff)) mixCoeff <- rep(1,l)/l else{ if (l!=length(mixCoeff)) stop("argument 'mixCoeff' and the mixing distributions must have the same length") if(any(mixCoeff < -ep) || sum(mixCoeff)>1+ep) stop("mixing coefficients are no probabilities") } rnew <- .rmixfun(mixDistr = mixDistr, mixCoeff = mixCoeff) pnew <- .pmixfun(mixDistr = mixDistr, mixCoeff = mixCoeff) .withArith <- any(as.logical(lapply(mixDistr, function(x) x@".withArith"))) .withSim <- any(as.logical(lapply(mixDistr, function(x) x@".withSim"))) .lowerExact<- all(as.logical(lapply(mixDistr, function(x) x@".lowerExact"))) if (all( as.logical(lapply(mixDistr, function(x) is(x,"AbscontDistribution")))) || all( as.logical(lapply(mixDistr, function(x) is(x,"DiscreteDistribution"))))) dnew <- .dmixfun(mixDistr = mixDistr, mixCoeff = mixCoeff) gaps <- NULL for(i in 1:l){ if(is.null(gaps)){ try(gaps <- gaps(mixDistr[[i]]), silent=TRUE) }else{ if(!is(try(gaps0 <- gaps(mixDistr[[i]]), silent=TRUE),"try-error")) if(!is.null(gaps0)) gaps <- .mergegaps2(gaps,gaps0) } } support <- numeric(0) for(i in 1:l){ if(!is(try(support0 <- support(mixDistr[[i]]), silent=TRUE),"try-error")) support <- unique(sort(c(support,support0))) } gaps <- .mergegaps(gaps,support) qnew <- .qmixfun(mixDistr = mixDistr, mixCoeff = mixCoeff, Cont = TRUE, pnew = pnew, gaps = gaps) obj <- new("UnivarMixingDistribution", p = pnew, r = rnew, d = NULL, q = qnew, mixCoeff = mixCoeff, mixDistr = mixDistr, .withSim = .withSim, .withArith = .withArith,.lowerExact =.lowerExact, gaps = gaps, support = support) if (all( as.logical(lapply(mixDistr, function(x) is(x@Symmetry,"SphericalSymmetry"))))){ sc <- SymmCenter(mixDistr[[1]]@Symmetry) if (all( as.logical(lapply(mixDistr, function(x) .isEqual(SymmCenter(x@Symmetry),sc))))) obj@Symmetry <- SphericalSymmetry(sc) } if (withSimplify) obj <- simplifyD(obj) return(obj) } setMethod("mixCoeff", "UnivarMixingDistribution", function(object)object@mixCoeff) setReplaceMethod("mixCoeff", "UnivarMixingDistribution", function(object,value){ object@mixCoeff<- value; object}) setMethod("mixDistr", "UnivarMixingDistribution", function(object)object@mixDistr) setReplaceMethod("mixDistr", "UnivarMixingDistribution", function(object,value){ object@mixDistr<- value; object}) setMethod("support", "UnivarMixingDistribution", function(object)object@support) setMethod("gaps", "UnivarMixingDistribution", function(object)object@gaps) setMethod("p.l", signature(object = "UnivarMixingDistribution"), function(object) .pmixfun(mixDistr = mixDistr(object), mixCoeff = mixCoeff(object), leftright = "left")) setMethod("q.r", signature(object = "UnivarMixingDistribution"), function(object){ if(!is.null(gaps(object))&&length(gaps(object))) .modifyqgaps(pfun = p(object), qfun = q.l(object), gaps = gaps(object), leftright = "right") else q.l(object) }) setMethod(".lowerExact", "UnivarMixingDistribution", function(object){ er <- is(try(slot(object, ".lowerExact"), silent = TRUE), "try-error") if(er){ object0 <- conv2NewVersion(object) objN <- paste(substitute(object)) warning(gettextf("'%s' was generated in an old version of this class.\n", objN), gettextf("'%s' has been converted to the new version",objN), gettextf(" of this class by a call to 'conv2NewVersion'.\n") ) eval.parent(substitute(object<-object0)) return([email protected])} [email protected]}) setMethod(".logExact", "UnivarMixingDistribution", function(object){ er <- is(try(slot(object, ".logExact"), silent = TRUE), "try-error") if(er){ object0 <- conv2NewVersion(object) objN <- paste(substitute(object)) warning(gettextf("'%s' was generated in an old version of this class.\n", objN), gettextf("'%s' has been converted to the new version",objN), gettextf(" of this class by a call to 'conv2NewVersion'.\n") ) eval.parent(substitute(object<-object0)) return([email protected])} [email protected]}) setMethod("Symmetry", "UnivarMixingDistribution", function(object){ er <- is(try(slot(object, "Symmetry"), silent = TRUE), "try-error") if(er){ object0 <- conv2NewVersion(object) objN <- paste(substitute(object)) warning(gettextf("'%s' was generated in an old version of this class.\n", objN), gettextf("'%s' has been converted to the new version",objN), gettextf(" of this class by a call to 'conv2NewVersion'.\n") ) eval.parent(substitute(object<-object0)) return(object0@Symmetry)} object@Symmetry})
getRefPoint = function(fn) { UseMethod("getRefPoint") } getRefPoint.smoof_single_objective_function = function(fn) { stopf("No reference point available for single-objective function.") } getRefPoint.smoof_multi_objective_function = function(fn) { return(attr(fn, "ref.point")) } getRefPoint.smoof_wrapped_function = function(fn) { return(getRefPoint(getWrappedFunction(fn))) }
context("LISTCOL functions") data <- structure( list( number = 1:3, labels = list("q", character(0), c("a:1", "b:2", "c-3")) ), row.names = c(NA, -3L), class = "data.frame", .Names = c("number", "labels")) data2 <- structure( list( number = 1:3, labels = c("a:5", "b:3", "a:1") ), row.names = c(NA, -3L), class = "data.frame", .Names = c("number", "labels")) test_that("Listcol extract funcion creates appropriate new columns", { expect_named( listcol_extract(data, "labels", "a:"), c("number", "labels", "a")) expect_named( listcol_extract(data, "labels", "b:"), c("number", "labels", "b")) expect_named( listcol_extract(data, "labels", "c:"), c("number", "labels", "c")) expect_named( listcol_extract(data, "labels", "c-"), c("number", "labels", "c")) expect_named( listcol_extract(data, "labels", "a:", new_col_name = "q"), c("number", "labels", "q")) expect_named( listcol_extract(data, "labels", ":"), c("number", "labels", "V3")) }) test_that("listcol_extract function populations columns with correct values", { expect_equal( listcol_extract(data, "labels", "a:")$a, c(NA, NA, "1")) expect_equal( listcol_extract(data, "labels", "a:", keep_regex = TRUE)$a, c(NA, NA, "a:1")) expect_equal( listcol_extract(data, "labels", "b:")$b, c(NA, NA, "2")) expect_true( all(is.na(listcol_extract(data, "labels", "c:")$c) )) expect_equal( listcol_extract(data, "labels", "c-")$c, c(NA, NA, "3")) expect_equal( listcol_extract(data, "labels", ":")$V3[[3]], c("a1", "b2")) } ) test_that("listcol_filter preserves the correct values", { expect_equal( nrow(listcol_filter(data, "labels", matches = "q")), 1) expect_equal( nrow(listcol_filter(data, "labels", matches = c("a:", "b:"), is_regex = TRUE)), 1) expect_equal( nrow(listcol_filter(data, "labels", matches = c(".*"), is_regex = TRUE)), 2) expect_equal( listcol_filter(data, "labels", matches = "q")$number, 1) expect_equal( listcol_filter(data, "labels", matches = c("a:", "b:"), is_regex = TRUE)$number, 3) expect_equal( nrow(listcol_filter(data2, "labels", matches = c("a:", "b:"), is_regex = TRUE)), 3) } ) test_that("listcol_pivot creates appropriate new columns", { expect_named(listcol_pivot(data, "labels", "^(a|b):"), c("number", "labels", "a:1", "b:2")) expect_named( listcol_pivot(data, "labels", "^(a|b):", transform_fx = function(x) gsub("^(a|b):", "", x)), c("number", "labels", "1", "2")) } )
"plotPeaks_batch" <- function(sites, file=NA, do_plot=TRUE, silent=FALSE, envir=NULL, ...) { if(! do_plot) file <- NA if(is.null(envir)) { pkenv <- new.env() } else { if(is.environment(envir)) { pkenv <- envir } else { stop("envir given but not an environment") } } numpk <- 0 for(site in sites) { if(exists(site, pkenv)) next if(! silent) message("Pulling peaks for ",site) pk <- NA pk <- dataRetrieval::readNWISpeak(site, convert=FALSE) suppressWarnings(pk <- splitPeakCodes(pk)) numpk <- numpk + length(pk$peak_va[pk$appearsSystematic == TRUE]) if(is.null(pk)) pk <- NA assign(site, pk, envir=pkenv) } if(is.null(envir) & ! silent) message("DONE (num. systematic peaks = ",numpk,")\n") numpk <- 0 empty_sites <- NULL if(! is.na(file)) pdf(file, useDingbats=FALSE) for(site in sites) { if(do_plot & ! silent) message("Plotting ", site, appendLF=FALSE) pk <- get(site, envir=pkenv) if(length(pk) == 1) { if(do_plot & ! silent) message("---empty") if(do_plot) { plot(0:2,0:2, xlab="", ylab="", xaxt="n", yaxt="n", type="n") text( 1, 1, "EMPTY PEAK FILE") mtext(site) } empty_sites <- c(empty_sites, site) } else { numpk <- numpk + length(pk$peak_va[pk$appearsSystematic == TRUE]) if(do_plot) { plotPeaks(pk, ...) mtext(site) } if(do_plot & ! silent) message("") } } if(do_plot & ! silent) message("DONE (num. systematic peaks = ",numpk,")") if(! is.na(file)) dev.off() pkenv <- as.list(pkenv) attr(pkenv, "empty_sites") <- empty_sites return(pkenv) }
J48DT <- function(data, quiet = FALSE, plot = TRUE) { msg <- NULL if (!is.data.frame(data)) { msg <- c(msg, "input data must be data.frame") } else if (nrow(data) < 2) { msg <- c(msg, "input data must have more than one row") } else if (ncol(data) < 2) { msg <- c(msg, "input data must have more than one column") } else if (sum(apply(is.na(data), 1, sum)) > 0) { msg <- c(msg, "NAs are not allowed in input data") } else if (sum(apply(data, 1, min)) < 0) { msg <- c(msg, "negative values are not allowed in input data") } if (is.null(msg)) TRUE else msg exp.df <- as.data.frame(t(data)) classVector <- factor(colnames(data)) j48.model <- J48(classVector ~ ., exp.df) if (!quiet) print(j48.model) if (plot) plot(j48.model) return(j48.model) }
plot.cca.fd <- function(x, cexval = 1, ...) { ccafd <- x if (!(inherits(ccafd, "cca.fd"))) stop("First argument not of CCA.FD class.") ccafd1 <- ccafd[[1]] ccacoef1 <- ccafd1$coefs ccabasis1 <- ccafd1$basis ccafd2 <- ccafd[[2]] ccacoef2 <- ccafd1$coefs ccabasis2 <- ccafd2$basis rangeval <- ccabasis1$rangeval argvals <- seq(rangeval[1],rangeval[2],len=201) ccamat1 <- eval.fd(argvals, ccafd1) ccamat2 <- eval.fd(argvals, ccafd2) ncan <- dim(ccacoef1)[2] par(mfrow=c(2,1), pty="s") if (ncan > 1) par(ask=TRUE) else par(ask=FALSE) for (j in (1:ncan)) { plot(argvals, ccamat1[,j], type="l", cex=cexval, ylab="First canonical weight", main=paste("Harmonic",j)) plot(argvals, ccamat2[,j], type="l", cex=cexval, ylab="Second canonical weight", main="") } par(ask=FALSE) invisible(NULL) }
predict.SeSDA <- function(object, x.test,...){ n <- nrow(x.test) p <- ncol(x.test) x.test.norm <- matrix(0,n,p) for (i in 1:p){ x.test.norm[,i] <- as.matrix(object$transform[[i]](x.test[,i])) } pred <- predict.dsda(object$objdsda, x.test.norm,...) pred }
"esrp"
low <- function(x) { set_names(x, tolower) } pad_dbl <- function(string, width, pad) { fmt <- paste0("%", pad, width, ".f") readr::parse_character( sprintf(fmt, as.double(string)) ) } commas <- function(...) { paste0(..., collapse = ", ") } pipes <- function(...) { paste0(..., collapse = "|") } anchor <- function(x) { paste0("^", x, "$") } round_any <- function(x, accuracy, f = round) { f(x / accuracy) * accuracy } has_class_df <- function(x) { any(grepl("data.frame", class(x))) } each_list_item_is_df <- function(x) { if (!is.list(x) || is.data.frame(x)) { abort("`x` must be a list of datafraems (and not itself a dataframe).") } all(vapply(x, has_class_df, logical(1))) } groups_lower <- function(x) { dplyr::grouped_df(x, tolower(dplyr::group_vars(x))) } groups_restore <- function(x, ref) { dplyr::grouped_df(x, dplyr::group_vars(ref)) } stopifnot_single_plotname <- function(.x) { if (has_name(.x, "plotname") && detect_if(.x, "plotname", is_multiple)) { stop("`.x` must have a single plotname.", call. = FALSE) } } abort_bad_class <- function(x) { .class <- glue_collapse(class(x), sep = ", ", last = ", or ") abort(glue("Can't deal with data of class: {.class}.")) }
univariateScore.glmm <- function(target, reps = NULL, group, dataset, test, wei, targetID, slopes, ncores) { univariateModels <- list(); dm <- dim(dataset) rows <- dm[1] cols <- dm[2] ind <- 1:cols la <- length( unique(target) ) if ( la > 2 & sum( round(target) - target ) != 0 & !slopes & is.null(wei) ) { group <- as.numeric(group) if ( !is.null(reps) ) reps <- as.numeric(reps) univariateModels <- MXM::rint.regs(target = target, dataset = dataset, targetID = targetID, id = group, reps = reps, tol = 1e-07) } else { if ( targetID != -1 ) { target <- dataset[, targetID] dataset[, targetID] <- rnorm(rows) } univariateModels$pvalue <- numeric(cols) univariateModels$stat <- numeric(cols) poia <- Rfast::check_data(dataset) if ( sum(poia) > 0 ) dataset[, poia] <- rnorm(rows) if ( ncores == 1 | is.null(ncores) | ncores <= 0 ) { for(i in ind) { test_results <- test(target, reps, group, dataset, i, 0, wei = wei, slopes = slopes) univariateModels$pvalue[[ i ]] <- test_results$pvalue; univariateModels$stat[[ i ]] <- test_results$stat; } } else { cl <- makePSOCKcluster(ncores) registerDoParallel(cl) test <- test mod <- foreach(i = ind, .combine = rbind, .export = c("lmer", "glmer"), .packages = "lme4") %dopar% { test_results <- test(target, reps, group, dataset, i, 0, wei = wei, slopes = slopes) return( c(test_results$pvalue, test_results$stat) ) } stopCluster(cl) univariateModels$pvalue[ind] <- as.vector( mod[, 1] ) univariateModels$stat[ind] <- as.vector( mod[, 2] ) } if ( sum(poia>0) > 0 ) { univariateModels$stat[poia] <- 0 univariateModels$pvalue[poia] <- log(1) } } if ( !is.null(univariateModels) ) { if (targetID != - 1) { univariateModels$stat[targetID] <- 0 univariateModels$pvalue[targetID] <- log(1) } } univariateModels }
make_significance_report <- function(defs, ...){ stop("Type 'significance' not yet available.") }
test_that("fit01.works", { library(RRPP) data("Pupfish") succeed(lm.rrpp(coords[,1] ~ 1, data = Pupfish, print.progress = FALSE, iter = 3)) }) test_that("fit02.works", { library(RRPP) data("Pupfish") succeed(lm.rrpp(coords ~ 1, data = Pupfish, print.progress = FALSE, iter = 3)) }) test_that("fit03.works", { library(RRPP) data("Pupfish") succeed(lm.rrpp(coords ~ CS, data = Pupfish, print.progress = FALSE, iter = 3)) }) test_that("fit04.works", { library(RRPP) data("Pupfish") succeed(lm.rrpp(coords ~ CS + Pop, data = Pupfish, print.progress = FALSE, iter = 3)) }) test_that("fit05.works", { library(RRPP) data("Pupfish") succeed(lm.rrpp(coords ~ CS + Pop, data = Pupfish, SS.type = "II", print.progress = FALSE, iter = 3)) }) test_that("fit06.works", { library(RRPP) data("Pupfish") succeed(lm.rrpp(coords ~ CS + Pop, data = Pupfish, SS.type = "III", print.progress = FALSE, iter = 3)) }) test_that("fit07.works", { library(RRPP) data("Pupfish") succeed(lm.rrpp(coords ~ CS + Pop, data = Pupfish, turbo = TRUE, print.progress = FALSE, iter = 3)) }) test_that("fit10.works", { library(RRPP) data("Pupfish") succeed(lm.rrpp(coords ~ CS * Pop * Sex, data = Pupfish, print.progress = FALSE, iter = 3)) }) test_that("fit11.works", { library(RRPP) data("Pupfish") succeed(lm.rrpp(coords ~ CS * Pop * Sex, data = Pupfish, int.first = TRUE, print.progress = FALSE, iter = 3)) }) test_that("fit12.works", { library(RRPP) data("PlethMorph") succeed(lm.rrpp(TailLength ~ SVL, data = PlethMorph, print.progress = FALSE, iter = 3)) }) test_that("fit13.works", { library(RRPP) data("PlethMorph") succeed(lm.rrpp(TailLength ~ 1, data = PlethMorph, print.progress = FALSE, Cov = PlethMorph$PhyCov, iter = 3)) }) test_that("fit14.works", { library(RRPP) data("PlethMorph") succeed(lm.rrpp(TailLength ~ SVL, data = PlethMorph, print.progress = FALSE, Cov = PlethMorph$PhyCov, iter = 3)) }) test_that("fit15.works", { library(RRPP) data("PlethMorph") succeed(lm.rrpp(cbind(TailLength, BodyWidth) ~ SVL, data = PlethMorph, print.progress = FALSE, Cov = PlethMorph$PhyCov, iter = 3)) }) test_that("coef.fit01.works", { library(RRPP) data("Pupfish") succeed(coef(lm.rrpp(coords[,1] ~ 1, data = Pupfish, print.progress = FALSE, iter = 3))) }) test_that("coef.fit02.works", { library(RRPP) data("Pupfish") succeed(coef(lm.rrpp(coords ~ 1, data = Pupfish, print.progress = FALSE, iter = 3))) }) test_that("coef.fit03.works", { library(RRPP) data("Pupfish") succeed(coef(lm.rrpp(coords ~ CS, data = Pupfish, print.progress = FALSE, iter = 3))) }) test_that("coef.fit04.works", { library(RRPP) data("Pupfish") succeed(coef(lm.rrpp(coords ~ CS + Pop, data = Pupfish, print.progress = FALSE, iter = 3))) }) test_that("coef.fit05.works", { library(RRPP) data("Pupfish") succeed(coef(lm.rrpp(coords ~ CS + Pop, data = Pupfish, SS.type = "II", print.progress = FALSE, iter = 3))) }) test_that("coef.fit06.works", { library(RRPP) data("Pupfish") succeed(coef(lm.rrpp(coords ~ CS + Pop, data = Pupfish, SS.type = "III", print.progress = FALSE, iter = 3))) }) test_that("coef.fit07.works", { library(RRPP) data("Pupfish") succeed(coef(lm.rrpp(coords ~ CS + Pop, data = Pupfish, turbo = TRUE, print.progress = FALSE, iter = 3))) }) test_that("coef.fit10.works", { library(RRPP) data("Pupfish") succeed(coef(lm.rrpp(coords ~ CS * Pop * Sex, data = Pupfish, print.progress = FALSE, iter = 3))) }) test_that("coef.fit11.works", { library(RRPP) data("Pupfish") succeed(coef(lm.rrpp(coords ~ CS * Pop * Sex, data = Pupfish, int.first = TRUE, print.progress = FALSE, iter = 3))) }) test_that("coef.fit12.works", { library(RRPP) data("PlethMorph") succeed(coef(lm.rrpp(TailLength ~ SVL, data = PlethMorph, print.progress = FALSE, iter = 3))) }) test_that("coef.fit13.works", { library(RRPP) data("PlethMorph") succeed(coef(lm.rrpp(TailLength ~ 1, data = PlethMorph, print.progress = FALSE, Cov = PlethMorph$PhyCov, iter = 3))) }) test_that("coef.fit14.works", { library(RRPP) data("PlethMorph") succeed(coef(lm.rrpp(TailLength ~ SVL, data = PlethMorph, print.progress = FALSE, Cov = PlethMorph$PhyCov, iter = 3))) }) test_that("coef.fit15.works", { library(RRPP) data("PlethMorph") succeed(coef(lm.rrpp(cbind(TailLength, BodyWidth) ~ SVL, data = PlethMorph, print.progress = FALSE, Cov = PlethMorph$PhyCov, iter = 3))) }) test_that("coef.t.fit01.works", { library(RRPP) data("Pupfish") succeed(coef(lm.rrpp(coords[,1] ~ 1, data = Pupfish, print.progress = FALSE, iter = 3), test = TRUE)) }) test_that("coef.t.fit02.works", { library(RRPP) data("Pupfish") succeed(coef(lm.rrpp(coords ~ 1, data = Pupfish, print.progress = FALSE, iter = 3), test = TRUE)) }) test_that("coef.t.fit03.works", { library(RRPP) data("Pupfish") succeed(coef(lm.rrpp(coords ~ CS, data = Pupfish, print.progress = FALSE, iter = 3), test = TRUE)) }) test_that("coef.t.fit04.works", { library(RRPP) data("Pupfish") succeed(coef(lm.rrpp(coords ~ CS + Pop, data = Pupfish, print.progress = FALSE, iter = 3), test = TRUE)) }) test_that("coef.t.fit05.works", { library(RRPP) data("Pupfish") succeed(coef(lm.rrpp(coords ~ CS + Pop, data = Pupfish, SS.type = "II", print.progress = FALSE, iter = 3), test = TRUE)) }) test_that("coef.t.fit06.works", { library(RRPP) data("Pupfish") succeed(coef(lm.rrpp(coords ~ CS + Pop, data = Pupfish, SS.type = "III", print.progress = FALSE, iter = 3), test = TRUE)) }) test_that("coef.t.fit07.works", { library(RRPP) data("Pupfish") succeed(coef(lm.rrpp(coords ~ CS + Pop, data = Pupfish, turbo = TRUE, print.progress = FALSE, iter = 3), test = TRUE)) }) test_that("coef.t.fit10.works", { library(RRPP) data("Pupfish") succeed(coef(lm.rrpp(coords ~ CS * Pop * Sex, data = Pupfish, print.progress = FALSE, iter = 3), test = TRUE)) }) test_that("coef.t.fit11.works", { library(RRPP) data("Pupfish") succeed(coef(lm.rrpp(coords ~ CS * Pop * Sex, data = Pupfish, int.first = TRUE, print.progress = FALSE, iter = 3), test = TRUE)) }) test_that("coef.t.fit12.works", { library(RRPP) data("PlethMorph") succeed(coef(lm.rrpp(TailLength ~ SVL, data = PlethMorph, print.progress = FALSE, iter = 3), test = TRUE)) }) test_that("coef.t.fit13.works", { library(RRPP) data("PlethMorph") succeed(coef(lm.rrpp(TailLength ~ 1, data = PlethMorph, print.progress = FALSE, Cov = PlethMorph$PhyCov, iter = 3), test = TRUE)) }) test_that("coef.t.fit14.works", { library(RRPP) data("PlethMorph") succeed(coef(lm.rrpp(TailLength ~ SVL, data = PlethMorph, print.progress = FALSE, Cov = PlethMorph$PhyCov, iter = 3), test = TRUE)) }) test_that("coef.t.fit15.works", { library(RRPP) data("PlethMorph") succeed(coef(lm.rrpp(cbind(TailLength, BodyWidth) ~ SVL, data = PlethMorph, print.progress = FALSE, Cov = PlethMorph$PhyCov, iter = 3), test = TRUE)) }) test_that("anova.fit01.works", { library(RRPP) data("Pupfish") succeed(anova(lm.rrpp(coords[,1] ~ 1, data = Pupfish, print.progress = FALSE, iter = 3))) }) test_that("anova.fit02.works", { library(RRPP) data("Pupfish") succeed(anova(lm.rrpp(coords ~ 1, data = Pupfish, print.progress = FALSE, iter = 3))) }) test_that("anova.fit03.works", { library(RRPP) data("Pupfish") succeed(anova(lm.rrpp(coords ~ CS, data = Pupfish, print.progress = FALSE, iter = 3))) }) test_that("anova.fit04.works", { library(RRPP) data("Pupfish") succeed(anova(lm.rrpp(coords ~ CS + Pop, data = Pupfish, print.progress = FALSE, iter = 3))) }) test_that("anova.fit05.works", { library(RRPP) data("Pupfish") succeed(anova(lm.rrpp(coords ~ CS + Pop, data = Pupfish, SS.type = "II", print.progress = FALSE, iter = 3))) }) test_that("anova.fit06.works", { library(RRPP) data("Pupfish") succeed(anova(lm.rrpp(coords ~ CS + Pop, data = Pupfish, SS.type = "III", print.progress = FALSE, iter = 3))) }) test_that("anova.fit07.works", { library(RRPP) data("Pupfish") succeed(anova(lm.rrpp(coords ~ CS + Pop, data = Pupfish, turbo = TRUE, print.progress = FALSE, iter = 3))) }) test_that("anova.fit10.works", { library(RRPP) data("Pupfish") succeed(anova(lm.rrpp(coords ~ CS * Pop * Sex, data = Pupfish, print.progress = FALSE, iter = 3))) }) test_that("anova.fit11.works", { library(RRPP) data("Pupfish") succeed(anova(lm.rrpp(coords ~ CS * Pop * Sex, data = Pupfish, int.first = TRUE, print.progress = FALSE, iter = 3))) }) test_that("anova.fit11.b.works", { library(RRPP) data("Pupfish") succeed(anova(lm.rrpp(coords ~ CS * Pop * Sex, data = Pupfish, int.first = TRUE, print.progress = FALSE, iter = 3), effect.type = "cohenf")) }) test_that("anova.fit11.c.works", { library(RRPP) data("Pupfish") succeed(anova(lm.rrpp(coords ~ CS * Pop * Sex, data = Pupfish, int.first = TRUE, print.progress = FALSE, iter = 3), effect.type = "Rsq")) }) test_that("anova.fit11.d.works", { library(RRPP) data("Pupfish") succeed(anova(lm.rrpp(coords ~ CS * Pop * Sex, data = Pupfish, int.first = TRUE, print.progress = FALSE, iter = 3), effect.type = "MS")) }) test_that("anova.fit11.e.works", { library(RRPP) data("Pupfish") succeed(anova(lm.rrpp(coords ~ Pop * Sex, data = Pupfish, int.first = TRUE, print.progress = FALSE, iter = 3), error = c("Pop:Sex", "Pop:Sex", "Residuals"))) }) test_that("anova.fit12.works", { library(RRPP) data("PlethMorph") succeed(anova(lm.rrpp(TailLength ~ SVL, data = PlethMorph, print.progress = FALSE, iter = 3))) }) test_that("predict1.works", { library(RRPP) data("PupfishHeads") fit <- lm.rrpp(log(headSize) ~ sex + locality/year, SS.type = "III", data = PupfishHeads, print.progress = FALSE, iter = 3) succeed(predict(fit)) }) test_that("manova1.works", { library(RRPP) data("Pupfish") fit <- lm.rrpp(coords ~ CS + Sex, SS.type = "I", data = Pupfish, print.progress = FALSE, iter = 3) succeed(manova.update(fit, print.progress = FALSE)) }) test_that("pairwise1.works", { library(RRPP) data("Pupfish") fit <- lm.rrpp(coords ~ CS + Sex, SS.type = "I", data = Pupfish, print.progress = FALSE, iter = 3) succeed(pairwise(fit, groups = Pupfish$Sex, print.progress = FALSE)) }) test_that("trajectory.analysis1.works", { library(RRPP) data("Pupfish") fit <- lm.rrpp(coords ~ Pop * Sex, data = Pupfish, print.progress = FALSE, iter = 3) succeed(trajectory.analysis(fit, groups = Pupfish$Pop, traj.pts = Pupfish$Sex, print.progress = FALSE)) }) test_that("trajectory.analysis2.works", { library(RRPP) data("motionpaths") fit <- lm.rrpp(trajectories ~ groups, data = motionpaths, iter = 3) succeed(trajectory.analysis(fit, groups = motionpaths$groups, traj.pts = 5)) }) test_that("ordinate1.works", { library(RRPP) data("PlethMorph") Y <- as.data.frame(PlethMorph[c("TailLength", "HeadLength", "Snout.eye", "BodyWidth", "Forelimb", "Hindlimb")]) PlethMorph$Y <- as.matrix(Y) R <- lm.rrpp(Y ~ SVL, data = PlethMorph, iter = 0, print.progress = FALSE)$LM$residuals succeed(ordinate(R, scale. = FALSE)) }) test_that("ordinate2.works", { library(RRPP) data("PlethMorph") Y <- as.data.frame(PlethMorph[c("TailLength", "HeadLength", "Snout.eye", "BodyWidth", "Forelimb", "Hindlimb")]) PlethMorph$Y <- as.matrix(Y) R <- lm.rrpp(Y ~ SVL, data = PlethMorph, iter = 0, print.progress = FALSE)$LM$residuals succeed(ordinate(R, scale. = TRUE)) }) test_that("ordinate3.works", { library(RRPP) data("PlethMorph") Y <- as.data.frame(PlethMorph[c("TailLength", "HeadLength", "Snout.eye", "BodyWidth", "Forelimb", "Hindlimb")]) PlethMorph$Y <- as.matrix(Y) R <- lm.rrpp(Y ~ SVL, data = PlethMorph, iter = 0, print.progress = FALSE)$LM$residuals succeed(ordinate(R, scale. = TRUE, transform. = FALSE, Cov = PlethMorph$PhyCov)) }) test_that("ordinate4.works", { library(RRPP) data("PlethMorph") Y <- as.data.frame(PlethMorph[c("TailLength", "HeadLength", "Snout.eye", "BodyWidth", "Forelimb", "Hindlimb")]) PlethMorph$Y <- as.matrix(Y) R <- lm.rrpp(Y ~ SVL, data = PlethMorph, iter = 0, print.progress = FALSE)$LM$residuals succeed(ordinate(R, scale. = TRUE, transform. = TRUE, Cov = PlethMorph$PhyCov)) }) test_that("ordinate5.works", { library(RRPP) data("PlethMorph") Y <- as.data.frame(PlethMorph[c("TailLength", "HeadLength", "Snout.eye", "BodyWidth", "Forelimb", "Hindlimb")]) PlethMorph$Y<- as.matrix(Y) R <- lm.rrpp(Y ~ SVL, data = PlethMorph, iter = 0, print.progress = FALSE)$LM$residuals succeed(ordinate(R, A = PlethMorph$PhyCov, scale. = TRUE)) }) test_that("ordinate6.works", { library(RRPP) data("PlethMorph") Y <- as.data.frame(PlethMorph[c("TailLength", "HeadLength", "Snout.eye", "BodyWidth", "Forelimb", "Hindlimb")]) PlethMorph$Y <- as.matrix(Y) R <- lm.rrpp(Y ~ SVL, data = PlethMorph, iter = 0, print.progress = FALSE)$LM$residuals succeed(ordinate(R, A = PlethMorph$PhyCov, scale. = TRUE, transform. = FALSE, Cov = PlethMorph$PhyCov)) })
NPMLE.Frank <- function(x.trunc,y.trunc,x.fix = median(x.trunc), y.fix = median(y.trunc),plotX = TRUE){ m=length(x.trunc) x.ox=sort(unique(x.trunc)) y.oy=sort(unique(y.trunc)) nx=length(x.ox);ny=length(y.oy) dHx1=1;Hxn=0;Ay_1=0;dAyn=1 dHx_lyn=numeric(nx);dAy_lyn=numeric(ny) for(i in 1:nx){ tx=x.ox[nx-i+1] Rx=sum( (x.trunc<=tx)&(y.trunc>=tx) ) dHx_lyn[nx-i+1]=sum(tx==x.trunc)/Rx } for(i in 1:ny){ ty=y.oy[i] Ry=sum( (x.trunc<=ty)&(y.trunc>=ty) ) dAy_lyn[i]=sum(ty==y.trunc)/Ry } dL_lyn=log(c(dHx_lyn[-1],dAy_lyn[-ny])) l.frank=function(dL){ dHx=c(dHx1,exp(dL[1:(nx-1)]));dAy=c(exp(dL[nx:(nx+ny-2)]),dAyn) Hx=c(rev(cumsum(rev(dHx)))[-1],Hxn);Ay_=c(Ay_1,cumsum(dAy)[-ny]) alpha=exp(dL[nx+ny-1]) prop=0 for(i in 1:nx){ temp_y=(y.oy>=x.ox[i]) dHxi=dHx[i];dAyi=dAy[temp_y] Fxi=exp(-Hx[i]);Sy_i=exp(-Ay_[temp_y]) B=alpha^Fxi+alpha^Sy_i C=alpha^Fxi*alpha^Sy_i prop=prop+sum((alpha-1)*log(alpha)*C/(C-B+alpha)^2*Sy_i*dAyi*Fxi*dHxi) } l=-m*log(prop) for(i in 1:m){ x_num=sum(x.ox<=x.trunc[i]);y_num=sum(y.oy<=y.trunc[i]) Hxi=Hx[x_num];Ay_i=Ay_[y_num] dHxi=dHx[x_num];dAyi=dAy[y_num] Fxi=exp(-Hxi);Sy_i=exp(-Ay_i) B=alpha^Fxi+alpha^Sy_i C=alpha^Fxi*alpha^Sy_i l=l+log((alpha-1)*log(alpha)*C/(C-B+alpha)^2)-Hxi-Ay_i+log(dHxi)+log(dAyi) } -l } res=nlm(l.frank,p=c(dL_lyn,log(0.9999)),hessian=TRUE) dL=res$estimate;conv=res$code alpha=exp(dL[nx+ny-1]) dHx=c(dHx1,exp(dL[1:(nx-1)])) dAy=c(exp(dL[nx:(nx+ny-2)]),dAyn) Hx_=rev(cumsum(rev(dHx)));Ay=cumsum(dAy) Fx=exp(-Hx_);Sy=exp(-Ay) Hx=c(Hx_[-1],Hxn) Ay_=c(Ay_1,Ay[-ny]) V_dL=solve(res$hessian) V=diag(exp(dL))%*%V_dL%*%diag(exp(dL)) SE_alpha=sqrt( V[nx+ny-1,nx+ny-1] ) Low=alpha*exp(-1.96*SE_alpha/alpha) Up=alpha*exp(1.96*SE_alpha/alpha) ML=-res$minimum iter=res$iterations Grad=res$gradient Min_eigen=min(eigen(res$hessian)$value) Hx_fix = Ay_fix = numeric(length(x.fix)) SE_Hx = SE_Ay = numeric(length(x.fix)) for (i in 1:length(x.fix)) { temp.x = c(x.ox >= x.fix[i]) Hx_fix[i] = Hx_[max(sum(x.ox <= x.fix[i]), 1)] SE_Hx[i] = sqrt((temp.x[-1]) %*% V[1:(nx - 1), 1:(nx - 1)] %*% (temp.x[-1])) } for (i in 1:length(y.fix)) { temp.y = c(y.oy <= y.fix[i]) Ay_fix[i] = Ay[max(sum(y.oy <= y.fix[i]), 1)] SE_Ay[i] = sqrt((temp.y[-ny]) %*% V[nx:(nx+ny-2),nx:(nx+ny-2)] %*% (temp.y[-ny])) } Fx_fix = exp(-Hx_fix) Sy_fix = exp(-Ay_fix) SE_Fx = Fx_fix * SE_Hx SE_Sy = Sy_fix * SE_Ay if (plotX == TRUE) { plot(x.ox, Fx, type = "s", xlab = "x", ylab = "Fx(x): Distribution function of X") } list( alpha = c(estimate=alpha, alpha_se = SE_alpha, Low95_alpha=Low, Up95_alpha=Up), Hx = c(estimate=Hx_fix, Hx_se = SE_Hx), Ay = c(estimate=Ay_fix, Ay_se = SE_Ay), Fx = c(estimate=Fx_fix, Fx_se = SE_Fx), Sy = c(estimate=Sy_fix, Sy_se = SE_Sy), ML=ML, convergence = conv,iteration=iter,Grad=sum(Grad^2),MinEigen=Min_eigen ) }
require(geometa, quietly = TRUE) require(testthat) context("ISOImageryProcessing") test_that("encoding",{ testthat::skip_on_cran() md <- ISOImageryProcessing$new() rp1 <- ISOResponsibleParty$new() rp1$setIndividualName("someone1") rp1$setOrganisationName("somewhere1") rp1$setPositionName("someposition1") rp1$setRole("pointOfContact") contact1 <- ISOContact$new() phone1 <- ISOTelephone$new() phone1$setVoice("myphonenumber1") phone1$setFacsimile("myfacsimile1") contact1$setPhone(phone1) address1 <- ISOAddress$new() address1$setDeliveryPoint("theaddress1") address1$setCity("thecity1") address1$setPostalCode("111") address1$setCountry("France") address1$setEmail("[email protected]") contact1$setAddress(address1) res <- ISOOnlineResource$new() res$setLinkage("http://www.somewhereovertheweb.org") res$setName("somename") contact1$setOnlineResource(res) rp1$setContactInfo(contact1) ct <- ISOCitation$new() ct$setTitle("sometitle") d <- ISODate$new() d$setDate(ISOdate(2015, 1, 1, 1)) d$setDateType("publication") ct$addDate(d) ct$setEdition("1.0") ct$setEditionDate(ISOdate(2015,1,1)) ct$addIdentifier(ISOMetaIdentifier$new(code = "identifier")) ct$addPresentationForm("mapDigital") ct$addCitedResponsibleParty(rp1) md$setIdentifier("identifier") md$setProcedureDescription("description") md$addSoftwareReference(ct) md$addDocumentation(ct) md$setRunTimeParameters("parameters") expect_is(md, "ISOImageryProcessing") xml <- md$encode() expect_is(xml, "XMLInternalNode") md2 <- ISOImageryProcessing$new(xml = xml) xml2 <- md2$encode() expect_true(ISOAbstractObject$compare(md, md2)) })
expected <- eval(parse(text="c(FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE)")); test(id=0, code={ argv <- eval(parse(text="list(c(1.15623864987889e-07, 2.29156215117184e-06, 2.23566813947706e-05, 0.000143191143888661, 0.000677580461489631, 0.00252801907454942, 0.00775156037133752, 0.0201095764491411, 0.0451105149252681, 0.0890234210350955, 0.15678837112652, 0.249535722442692, 0.362988194603088, 0.487807940725587, 0.611969188999548, 0.724126192770213, 0.816469100858263, 0.885981556331846, 0.933947517503216, 0.964353470219262, 0.982092072679401, 0.991629921792979))")); do.call(`is.na`, argv); }, o=expected);
knitr::opts_chunk$set(collapse = TRUE, comment = " options(tibble.print_min = 4L, tibble.print_max = 4L) library(pander) panderOptions('table.split.table', Inf) set.caption("Functions to estimate sample size using representative population sampling data.") ssrs.tab <- " Sampling | Outcome | RSurveillance | epiR Representative | Prob disease freedom | `n.pfree` | `rsu.sspfree.rs` Representative | SSe | `n.freedom` | `rsu.sssep.rs` Two stage representative | SSe | `n.2stage` | `rsu.sssep.rs2st` Representative | SSe | `n.freecalc` | `rsu.sssep.rsfreecalc` Pooled representative | SSe | `n.pooled` | `rsu.sssep.rspool`" ssrs.df <- read.delim(textConnection(ssrs.tab), header = FALSE, sep = "|", strip.white = TRUE, stringsAsFactors = FALSE) names(ssrs.df) <- unname(as.list(ssrs.df[1,])) ssrs.df <- ssrs.df[-1,] row.names(ssrs.df) <- NULL pander(ssrs.df, style = 'rmarkdown') set.caption("Functions to estimate surveillance system sensitivity (SSe) using representative population sampling data.") seprs.tab <- " Sampling | Outcome | RSurveillance | epiR Representative | SSe | `sep.binom` | `rsu.sep.rs` Representative | SSe | `sep.hypergeo` | `rsu.sep.rs` Representative | SSe | `sep` | `rsu.sep.rs` Two stage representative | SSe | `sep.sys` | `rsu.sep.rs2st` Representative | SSe | `sse.combined` | `rsu.sep.rsmult` Representative | SSe | `sep.freecalc` | `rsu.sep.rsfreecalc` Representative | SSe | `sep.binom.imperfect`| `rsu.sep.rsfreecalc` Pooled representative | SSe | `sep.pooled` | `rsu.sep.rspool` Representative | SSe | `sep.var.se` | `rsu.sep.rsvarse` Representative | SSp | `spp` | `rsu.spp.rs` Representative | SSp | `sph.hp` | `rsu.spp.rs`" seprs.df <- read.delim(textConnection(seprs.tab), header = FALSE, sep = "|", strip.white = TRUE, stringsAsFactors = FALSE) names(seprs.df) <- unname(as.list(seprs.df[1,])) seprs.df <- seprs.df[-1,] row.names(seprs.df) <- NULL pander(seprs.df, style = 'rmarkdown') set.caption("Functions to estimate the probability of disease freedom using representative population sampling data.") pfreers.tab <- " Sampling | Outcome | RSurveillance | epiR Representative | Prob disease of freedom | `pfree.1` | `rsu.pfree.rs` Representative | Prob disease of freedom | `pfree.calc` | `rsu.pfree.rs` Representative | Equilibrium prob of disease freedom | `pfree.equ` | `rsu.pfree.equ`" pfreers.df <- read.delim(textConnection(pfreers.tab), header = FALSE, sep = "|", strip.white = TRUE, stringsAsFactors = FALSE) names(pfreers.df) <- unname(as.list(pfreers.df[1,])) pfreers.df <- pfreers.df[-1,] row.names(pfreers.df) <- NULL pander(pfreers.df, style = 'rmarkdown') set.caption("Functions to estimate sample size using risk based sampling data.") ssrb.tab <- " Sampling | Outcome | RSurveillance | epiR Risk-based | SSe | `n.rb` | `rsu.sssep.rbsrg` Risk-based | SSe | `n.rb.varse` | `rsu.sssep.rbmrg` Risk-based | SSe | `n.rb.2stage.1` | `rsu.sssep.rb2st1rf` Risk-based | SSe | `n.rb.2stage.2` | `rsu.sssep.rb2st2rf`" ssrb.df <- read.delim(textConnection(ssrb.tab), header = FALSE, sep = "|", strip.white = TRUE, stringsAsFactors = FALSE) names(ssrb.df) <- unname(as.list(ssrb.df[1,])) ssrb.df <- ssrb.df[-1,] row.names(ssrb.df) <- NULL pander(ssrb.df, style = 'rmarkdown') set.caption("Functions to estimate surveillance system sensitivity (SSe) using risk based sampling data.") seprb.tab <- " Sampling | Outcome | RSurveillance | epiR Risk-based | SSe | `sep.rb.bin.varse` | `rsu.sep.rb` Risk-based | SSe | `sep.rb.bin` | `rsu.sep.rb1rf` Risk-based | SSe | `sep.rb.hypergeo` | `rsu.sep.rb1rf` Risk-based | SSe | `sep.rb2.bin` | `rsu.sep.rb2rf` Risk-based | SSe | `sep.rb2.hypergeo` | `rsu.sep.rb2rf` Risk-based | SSe | `sep.rb.hypergeo.varse` | `rsu.sep.rbvarse` Risk-based | SSe | `sse.rb2stage` | `rsu.sep.rb2stage`" seprb.df <- read.delim(textConnection(seprb.tab), header = FALSE, sep = "|", strip.white = TRUE, stringsAsFactors = FALSE) names(seprb.df) <- unname(as.list(seprb.df[1,])) seprb.df <- seprb.df[-1,] row.names(seprb.df) <- NULL pander(seprb.df, style = 'rmarkdown') set.caption("Functions to estimate surveillance system sensitivity (SSe) using census data.") sepcen.tab <- " Sampling | Outcome | RSurveillance | epiR Risk-based | SSe | `sep.exact` | `rsu.sep.cens`" sepcen.df <- read.delim(textConnection(sepcen.tab), header = FALSE, sep = "|", strip.white = TRUE, stringsAsFactors = FALSE) names(sepcen.df) <- unname(as.list(sepcen.df[1,])) sepcen.df <- sepcen.df[-1,] row.names(sepcen.df) <- NULL pander(sepcen.df, style = 'rmarkdown') set.caption("Functions to estimate surveillance system sensitivity (SSe) using passively collected surveillance data.") sepcen.tab <- " Sampling | Outcome | RSurveillance | epiR Risk-based | SSe | `sep.passive` | `rsu.sep.pass`" seppas.df <- read.delim(textConnection(sepcen.tab), header = FALSE, sep = "|", strip.white = TRUE, stringsAsFactors = FALSE) names(seppas.df) <- unname(as.list(seppas.df[1,])) seppas.df <- seppas.df[-1,] row.names(seppas.df) <- NULL pander(seppas.df, style = 'rmarkdown') set.caption("Miscellaneous functions.") misc.tab <- " Details | RSurveillance | epiR Adjusted risk | `adj.risk` | `rsu.adjrisk` Adjusted risk | `adj.risk.sim` | `rsu.adjrisk` Series test interpretation, Se | `se.series` | `rsu.dxtest` Parallel test interpretation, Se | `se.parallel` | `rsu.dxtest` Series test interpretation, Sp | `sp.series` | `rsu.dxtest` Parallel test interpretation, Sp | `sp.parallel` | `rsu.dxtest` Effective probability of infection | `epi.calc` | `rsu.epinf` Design prevalence back calculation | `pstar.calc` | `rsu.pstar` Prob disease is less than design prevalence | | `rsu.sep`" misc.df <- read.delim(textConnection(misc.tab), header = FALSE, sep = "|", strip.white = TRUE, stringsAsFactors = FALSE) names(misc.df) <- unname(as.list(misc.df[1,])) misc.df <- misc.df[-1,] row.names(misc.df) <- NULL pander(misc.df, style = 'rmarkdown')
varsquig<-function(x,y, L=locator(2) , FLIP=FALSE, filcol="blue", tracecol="red" , var=0, xpd=TRUE) { if(missing(FLIP) ) { FLIP=FALSE } if(missing(L) ) { L=locator(2) } if(missing(filcol) ) { filcol="red" } if(missing(tracecol) ) { tracecol="red" } if(missing(var) ) { var=TRUE } if(is.numeric(var)) { zee = var*(max(y, na.rm=TRUE)-mean(y, na.rm=TRUE)) } else { zee = 0 } if(FLIP==TRUE) { rx = RPMG::RESCALE(y, min(L$x), max(L$x), min(y), max(y)) ry = RPMG::RESCALE(x, max(L$y), min(L$y), min(x), max(x)) zer =RPMG::RESCALE(zee, min(L$x), max(L$x), min(y), max(y)) yup = rx>zer g = rx g[!yup] = zer g[1] = zer g[length(rx)] = zer if(var) polygon(g, ry, col=filcol, border=NA) } else { rx = RPMG::RESCALE(x, L$x[1], L$x[2], min(x), max(x)) ry = RPMG::RESCALE(y, L$y[1], L$y[2], min(y), max(y)) zer =RPMG::RESCALE(zee, L$y[1], L$y[2], min(y), max(y)) yup = ry>zer g = ry g[!yup] = zer g[1] = zer g[length(ry)] = zer if(var) polygon(rx, g , col=filcol, border=NA, xpd=xpd) } lines(rx, ry, col=tracecol, xpd=xpd) }
knitr::opts_chunk$set( echo = FALSE, collapse = TRUE, comment = " ) library(states) library(DT) data(gwstates) datatable(gwstates) data(cowstates) datatable(cowstates)
rscontract_open <- function(x) { UseMethod("rscontract_open") } rscontract_open.rscontract_ide <- function(x) { open_connection_contract(x) } rscontract_open.rscontract_spec <- function(x) { rs_contract <- as_rscontract(x) rscontract_open(rs_contract) } open_connection_contract <- function(spec) { observer <- getOption("connectionObserver") if (is.null(observer)) { return(invisible(NULL)) } connection_opened <- function(...) observer$connectionOpened(...) do.call("connection_opened", spec) }
powertrack = function (sound, timestep = 5, windowlength = 30, fs = 22050, show = TRUE, zeromax = TRUE, ...){ if (class(sound) == "ts") fs = frequency(sound) if (class(sound) == "sound") { fs = sound$fs sound = sound$sound } if (!is.numeric(sound)) stop ('Sound must be numeric.') if (timestep < 0) stop ('Timestep must be positive.') if (windowlength < timestep) stop ('Window length must be greater than or equal to timestep.') T = 1 / fs stepsize = round ((timestep / 1000) / T) half = round(ceiling (windowlength/1000 * 22050)/ 2) spots = seq (1+half, length(sound)-half, stepsize) power = rep (0, length(spots)) for (i in 1:length(spots)){ section = sound[(spots[i]-half):(spots[i]+half)] power[i] = mean ((section*windowfunc(section))^2) } use = (power != 0) spots = spots[use] power = power[use] power = log(power, 10)*10 if (zeromax) power = power - max(power) time = spots * (1000/fs) tmp = data.frame (time = time, power = power) if (show == TRUE) plot(tmp$time, tmp$power, xlab = 'Time (ms)', ylab = 'Power (dB)', type = 'l', ylim = c(min(power)-1, 2), lwd = 2, col = 4, ...) invisible (tmp) }
.sbwauxfix = function(dat, bal, wei, sol, sd_target = sd_target, ...) { if (wei$wei_sum == TRUE) { normalize = 1 } else if (wei$wei_sum == FALSE) { normalize = 0 } else {stop("The wei_sum is supposed to be TRUE or FALSE.")} if (wei$wei_pos == TRUE) { w_min = 0 } else if (wei$wei_pos == FALSE) { w_min = -Inf } else {stop("The wei_pos is supposed to be TRUE or FALSE.")} nor = "l_2" check_cov = bal$bal_cov[is.na(match(bal$bal_cov, colnames(dat)))] if (length(check_cov) > 0) stop(paste(paste(check_cov, collapse = ", "), "are not found in the dat.")) if (sum(is.na(dat[, bal$bal_cov])) > 0) { mis_value = colSums(is.na(dat[, bal$bal_cov])) stop(paste(paste(names(which(mis_value != 0)), collapse = ", "), "have missing values.")) } if (length(bal$bal_cov) != length(bal$bal_tar)) stop("bal$bal_cov and par$par_tar should have the same length as well as the same order.") if (!is.numeric(bal$bal_tol)) { stop("bal$bal_tol should be numeric.") } else if (sum(bal$bal_tol < 0) > 0) stop("bal$bal_tol should be non negative.") problemparameters.object = .problemparameters(dat = dat, nor = nor, bal = bal, normalize = normalize, w_min = w_min, sd_target = sd_target) sol$sol_nam = tolower(sol$sol_nam) if (sol$sol_nam == "cplex") { if (requireNamespace("Rcplex", quietly = TRUE)) { trace = ifelse(is.null(sol$sol_dis), 0, as.numeric(sol$sol_dis)) ptm = proc.time() sbw.object = .sbwpricplex(problemparameters.object, trace = trace) time = (proc.time()-ptm)[3] } } else if (sol$sol_nam == "pogs") { if (requireNamespace("pogs", quietly=TRUE)) { if (sum(bal$bal_tol^2) == 0) { warning("Exact balance may not be acquired. Please use the function summarize to check the balance.") } max_iter = ifelse(is.null(sol$sol_pog$sol_pog_max_iter), 100000, sol$sol_pog$sol_pog_max_iter) rel_tol = ifelse(is.null(sol$sol_pog$rel_tol), 1e-04, sol$sol_pog$rel_tol) abs_tol = ifelse(is.null(sol$sol_pog$abs_tol), 1e-04, sol$sol_pog$abs_tol) gap_stop = ifelse(is.null(sol$sol_pog$gap_stop), TRUE, sol$sol_pog$gap_stop) adaptive_rho = ifelse(is.null(sol$sol_pog$adaptive_rho), TRUE, sol$sol_pog$adaptive_rho) verbose = ifelse(is.null(sol$sol_dis), 0, as.numeric(sol$sol_dis)) params = list(rel_tol = rel_tol, abs_tol = abs_tol, max_iter = max_iter, adaptive_rho = adaptive_rho, verbose = verbose, gap_stop = gap_stop) ptm = proc.time() sbw.object = .sbwpripogs(problemparameters.object, params) time = (proc.time()-ptm)[3] } } else if (sol$sol_nam == "osqp") { verbose = as.logical(ifelse(is.null(sol$sol_dis), TRUE, FALSE)) ptm = proc.time() sbw.object = .sbwpriosqp(problemparameters.object, verbose = verbose) time = (proc.time()-ptm)[3] } else if (sol$sol_nam == "quadprog") { if (sum(bal$bal_tol^2) == 0) { stop("This problem does not have a solution from the solver quadprog. Please try other solvers.") } ptm = proc.time() sbw.object = .sbwpriquadprog(problemparameters.object) time = (proc.time()-ptm)[3] } else if (sol$sol_nam == "gurobi") { if (requireNamespace("gurobi", quietly=TRUE)) { sol_dis = ifelse(is.null(sol$sol_dis), 0, as.numeric(sol$sol_dis)) params = list(OutputFlag = sol_dis) ptm = proc.time() sbw.object = .sbwprigurobi(problemparameters.object, params = params) time = (proc.time()-ptm)[3] } } else if (sol$sol_nam == "mosek") { if (requireNamespace("Rmosek", quietly=TRUE)) { verbose = ifelse(is.null(sol$sol_dis), 0, as.numeric(paste(as.numeric(sol$sol_dis), 0, sep = ""))) ptm = proc.time() sbw.object = .sbwprimosek(problemparameters.object, verbose = verbose) time = (proc.time()-ptm)[3] } } else {stop("The assignment of solver is not found, please choose one of the available solvers.")} balance_parameters = problemparameters.object$bal_new if (length(bal$bal_cov) != length(bal$bal_tol)) { bal$bal_tol = bal$bal_tol[1] } balance_parameters$bal_tol_ori = bal$bal_tol rm(problemparameters.object) dat_weights = dat dat_weights$sbw_weights = as.numeric(as.character(sbw.object$weights)) effective_sample_size = sum(dat_weights$sbw_weights)^2/sum(dat_weights$sbw_weights^2) output = list(bal = bal, wei = wei, sol = sol, objective_value = sbw.object$objective_value, effective_sample_size = effective_sample_size, time = time, status = sbw.object$status, dat_weights = dat_weights, shadow_price = sbw.object$shadow_price, balance_parameters = balance_parameters) class(output) = "sbwaux" return(output) }
library(checkargs) context("isBooleanScalarOrNull") test_that("isBooleanScalarOrNull works for all arguments", { expect_identical(isBooleanScalarOrNull(NULL, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isBooleanScalarOrNull(TRUE, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isBooleanScalarOrNull(FALSE, stopIfNot = FALSE, message = NULL, argumentName = NULL), TRUE) expect_identical(isBooleanScalarOrNull(NA, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isBooleanScalarOrNull(0, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isBooleanScalarOrNull(-1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isBooleanScalarOrNull(-0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isBooleanScalarOrNull(0.1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isBooleanScalarOrNull(1, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isBooleanScalarOrNull(NaN, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isBooleanScalarOrNull(-Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isBooleanScalarOrNull(Inf, stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isBooleanScalarOrNull("", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isBooleanScalarOrNull("X", stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isBooleanScalarOrNull(c(TRUE, FALSE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isBooleanScalarOrNull(c(FALSE, TRUE), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isBooleanScalarOrNull(c(NA, NA), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isBooleanScalarOrNull(c(0, 0), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isBooleanScalarOrNull(c(-1, -2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isBooleanScalarOrNull(c(-0.1, -0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isBooleanScalarOrNull(c(0.1, 0.2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isBooleanScalarOrNull(c(1, 2), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isBooleanScalarOrNull(c(NaN, NaN), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isBooleanScalarOrNull(c(-Inf, -Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isBooleanScalarOrNull(c(Inf, Inf), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isBooleanScalarOrNull(c("", "X"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isBooleanScalarOrNull(c("X", "Y"), stopIfNot = FALSE, message = NULL, argumentName = NULL), FALSE) expect_identical(isBooleanScalarOrNull(NULL, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isBooleanScalarOrNull(TRUE, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_identical(isBooleanScalarOrNull(FALSE, stopIfNot = TRUE, message = NULL, argumentName = NULL), TRUE) expect_error(isBooleanScalarOrNull(NA, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isBooleanScalarOrNull(0, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isBooleanScalarOrNull(-1, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isBooleanScalarOrNull(-0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isBooleanScalarOrNull(0.1, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isBooleanScalarOrNull(1, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isBooleanScalarOrNull(NaN, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isBooleanScalarOrNull(-Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isBooleanScalarOrNull(Inf, stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isBooleanScalarOrNull("", stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isBooleanScalarOrNull("X", stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isBooleanScalarOrNull(c(TRUE, FALSE), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isBooleanScalarOrNull(c(FALSE, TRUE), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isBooleanScalarOrNull(c(NA, NA), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isBooleanScalarOrNull(c(0, 0), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isBooleanScalarOrNull(c(-1, -2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isBooleanScalarOrNull(c(-0.1, -0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isBooleanScalarOrNull(c(0.1, 0.2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isBooleanScalarOrNull(c(1, 2), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isBooleanScalarOrNull(c(NaN, NaN), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isBooleanScalarOrNull(c(-Inf, -Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isBooleanScalarOrNull(c(Inf, Inf), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isBooleanScalarOrNull(c("", "X"), stopIfNot = TRUE, message = NULL, argumentName = NULL)) expect_error(isBooleanScalarOrNull(c("X", "Y"), stopIfNot = TRUE, message = NULL, argumentName = NULL)) })
generateBlockDiagonalMatrices <- function(X, Y, groups, G, intercept=FALSE, penalty.factors=rep(1, dim(X)[2]), scaling=TRUE) { group.names = sort(unique(groups)) num.groups = length(group.names) num.pairs = num.groups*(num.groups-1)/2 if(intercept) X = cbind(X, matrix(1, dim(X)[1], 1)) new.y = Matrix(0, length(Y)+num.pairs*dim(X)[2],1, sparse=TRUE) new.x = Matrix(0, dim(X)[1], dim(X)[2]*num.groups, sparse=TRUE) new.x.f = Matrix(0, num.pairs*dim(X)[2], dim(X)[2]*num.groups, sparse=TRUE) row.start = 1 col.start = 1 for(group.i in 1:num.groups) { group.inds = groups==group.names[group.i] row.range = row.start:(row.start+sum(group.inds)-1) col.range = col.start:(col.start+dim(X)[2]-1) new.y[row.range] = Y[group.inds] new.x[row.range, col.range] = X[group.inds,] if(scaling) { new.y[row.range] = new.y[row.range]/sum(group.inds) new.x[row.range, col.range] = new.x[row.range, col.range]/sum(group.inds) } row.start = row.start + sum(group.inds) col.start = col.start + dim(X)[2] } col.start.i = 1 row.start = 1 for(group.i in 1:(num.groups-1)) { col.start.j = col.start.i + dim(X)[2] col.range.i = col.start.i:(col.start.i+dim(X)[2]-1) for(group.j in (group.i+1):num.groups) { tau = G[group.i, group.j] row.range = row.start:(row.start+dim(X)[2]-1) col.range.j = col.start.j:(col.start.j+dim(X)[2]-1) new.x.f[cbind(row.range, col.range.i)] = sqrt(tau) new.x.f[cbind(row.range, col.range.j)] = -sqrt(tau) if(intercept) { new.x.f[row.range[length(row.range)], col.range.i[length(col.range.i)]] = 0 new.x.f[row.range[length(row.range)], col.range.j[length(col.range.j)]] = 0 } row.start = row.start + dim(X)[2] col.start.j = col.start.j + dim(X)[2] } col.start.i = col.start.i + dim(X)[2] } if(intercept) { penalty = rep(c(penalty.factors, 0), num.groups) } else { penalty = rep(penalty.factors, num.groups) } return(list(X=new.x, Y=new.y, X.fused=new.x.f, penalty=penalty)) } fusedL2DescentGLMNet <- function(transformed.x, transformed.x.f, transformed.y, groups, lambda, gamma=1, ...) { transformed.x.f = transformed.x.f * sqrt(gamma * (dim(transformed.x)[1] + dim(transformed.x.f)[1])) transformed.x = rbind(transformed.x, transformed.x.f) group.names = sort(unique(groups)) num.groups = length(group.names) glmnet.result = glmnet(transformed.x, transformed.y, standardize=FALSE, ...) beta.mat = array(NA, c(dim(transformed.x)[2]/num.groups, num.groups, length(lambda))) for(lambda.i in 1:length(lambda)) { coef.temp = coef.glmnet(glmnet.result, s=lambda[lambda.i]*length(groups)/dim(transformed.x)[1]) beta.mat[,,lambda.i] = coef.temp[2:length(coef.temp)] } return(beta.mat) }
findcutpoints <- function(cox_pspline_fit,data,nquantile=100,exclude=0.05,eps=0.01, shape="U"){ x <- NULL if(missing(cox_pspline_fit)|!('coxph'%in%class(cox_pspline_fit))){ stop('"cox_pspline_fit" is missing or incorrect') } if(missing(data)|class(data)!="data.frame"){ stop('"data" is missing or incorrect') } if(shape!="U" & shape !="inverseU" ){stop('Invalid value for "shape" parameter')} f <- cox_pspline_fit$formula variablenames <- all.vars(f) variablenames <- variablenames[variablenames%in%colnames(data)] data <- data[,variablenames] if(length(variablenames)<3){ stop("There are not enough variables in dataset. At least (times, cersor, x) are required.") } else{ colnames(data) <- c('t','d','x') confounders <- NA if (length(variablenames)>3){ for (i in 4:length(variablenames)){ colnames(data)[i] <- paste("x", i-3, sep="") } confounders <- colnames(data)[4:length(variablenames)] } } adjpoint <- function(data,y){ lesslarger <- NA if (dim(data)[1]<=1){ pseudocut <- NA }else{ for ( j in c(1:(dim(data)[1]-1))){ if((data[j,'y']<y & data[j+1,'y']> y) | (data[j,'y']>y & data[j+1,'y']< y)){ lesslarger <- j } } equal <- NA for ( j in c(1:dim(data)[1])){ if(data[j,'y']== y){ equal <- j } } pseudocut <- NA if (!is.na(equal)){ pseudocut <- data[equal,'x'] }else{ if(!is.na(lesslarger)){ pseudocut <- (data[lesslarger+1,'x']-data[lesslarger,'x'])*(y-data[lesslarger,'y'])/(data[lesslarger+1,'y']-data[lesslarger,'y'])+data[lesslarger,'x'] }else{ pseudocut <- NA } } } return(pseudocut) } ptemp <- termplot(cox_pspline_fit, se=TRUE, plot=FALSE) xterm <- ptemp[[1]] PI_fit <- xterm$y turningpoint_index <- NA if (shape=="U"){ turningpoint_index <- which(PI_fit == min(PI_fit)) }else{ if(shape=="inverseU"){ turningpoint_index <- which(PI_fit == max(PI_fit)) } } ycut <- quantile(PI_fit, probs = seq((0+exclude), (1-exclude),1/nquantile)) cut_spline <- matrix(NA,length(ycut),7) colnames(cut_spline)=c('Quantile','Lindex','Rindex','Lcutpoint','Rcutpoint','AIC',' for (i in 1:length(ycut)){ y <- as.numeric(ycut[i]) cut_spline[i,"Quantile"] <- names(ycut)[i] L <- which.min((PI_fit[0:turningpoint_index]-y)^2) R <- which.min((PI_fit[turningpoint_index:length(PI_fit)]-y)^2) + turningpoint_index - 1 if(abs(PI_fit[L]-PI_fit[R])>eps){ adjust <- xterm[order(xterm$x),c('x','y')] split <- which(adjust$y == min(PI_fit)) adjust_L <- adjust[1:split,] adjust_R <- adjust[split:dim(adjust)[1],] cut_spline[i,"Lcutpoint"] <- round(adjpoint(adjust_L,y),4) cut_spline[i,"Rcutpoint"] <- round(adjpoint(adjust_R,y),4) } else { cut_spline[i,"Lindex"] <- L cut_spline[i,"Rindex"] <- R cut_spline[i,"Lcutpoint"] <- xterm$x[L] cut_spline[i,"Rcutpoint"] <- xterm$x[R] } xl <- as.numeric(cut_spline[i,"Lcutpoint"]) xr <- as.numeric(cut_spline[i,"Rcutpoint"]) if(!is.na(cut_spline[i,"Lcutpoint"]) & !is.na(cut_spline[i,"Rcutpoint"])){ datatemp <- data datatemp <- within(datatemp,{ x_c <- NA x_c[x < xl] <- 'C1' x_c[x >= xl & x <= xr] <- 'C2' x_c[x > xr] <- 'C3' } ) datatemp$x_c <- relevel(factor(datatemp$x_c),ref='C2') if(sum(is.na(confounders))){ f_cox <- Surv(t,d)~factor(x_c) }else{ f_cox <- as.formula(paste('Surv(t,d)~factor(x_c)','+', paste(confounders, collapse=" + "))) } coxHR <- survival::coxph(f_cox ,method='breslow',data=datatemp) cut_spline[i,"AIC"] <- as.numeric(extractAIC(coxHR)[2]) cut_spline[i,' } } number <- which(cut_spline[,"AIC"]==min(cut_spline[,"AIC"], na.rm = T)) multi <- length(number) if (multi>1){ if(multi%%2 ==0){ optimal <- c('Cutpoint_L'= (as.numeric(cut_spline[number[ceiling(median(multi))],"Lcutpoint"])+ as.numeric(cut_spline[number[floor(median(multi))],"Lcutpoint"]))/2, 'Cutpoint_R'= (as.numeric(cut_spline[number[ceiling(median(multi))],"Rcutpoint"])+ as.numeric(cut_spline[number[floor(median(multi))],"Rcutpoint"]))/2) } else { optimal <- c('Cutpoint_L'= as.numeric(cut_spline[number[median(multi)],"Lcutpoint"]), 'Cutpoint_R'= as.numeric(cut_spline[number[median(multi)],"Rcutpoint"])) } }else{ optimal <- c('Cutpoint_L'= as.numeric(cut_spline[number,"Lcutpoint"]),'Cutpoint_R'=as.numeric(cut_spline[number,"Rcutpoint"])) } cut_points<- list('allcuts'=cut_spline,'optimal'=optimal) return(cut_points) }
"timedep" <- function(x) { x }
num.intercepts <- function(fit, type=c('fit', 'var', 'coef')) { type <- match.arg(type) nrp <- fit$non.slopes if(!length(nrp)) { nm1 <- names(fit$coef)[1] nrp <- 1*(nm1=="Intercept" | nm1=="(Intercept)") } if(type == 'fit') return(nrp) w <- if(type == 'var') fit$var else fit$coefficients i <- attr(w, 'intercepts') li <- length(i) if(!li) return(nrp) if(li == 1 && i == 0) 0 else li }
critical_r <- function(n, alpha = .05) { df <- n - 2 critical_t <- qt(alpha / 2, df, lower.tail = FALSE) critical_r_value <- sqrt((critical_t ^ 2) / ((critical_t ^ 2) + df)) return(critical_r_value) }
rm(list=ls()) library(dplyr) library(reshape2) library(ggplot2) library(SEERaBomb) LC=c("CLL","SLL","HCL","NHL","MM","HL") system.time(load("~/Results/amlMDS/pm.RData")) system.time(load("~/Results/amlMDS/pf.RData")) brks=c(0,0.25,0.5,0.75,1,1.5,2,2.5,3,4,5,6,8,10,12) df=mkDF(pf,brks) dm=mkDF(pm,brks) d=rbind(cbind(df,Sex="Female"),cbind(dm,Sex="Male")) d=d%>%filter(cancer1%in%LC)%>%group_by(cancer2,Sex,int)%>%summarize(O=sum(O),E=sum(E),t=weighted.mean(t,py,na.rm=T)) D=d%>%mutate(RR=O/E, L=qchisq(.025,2*O)/(2*E),U=qchisq(.975,2*O+2)/(2*E)) D[D$cancer2=="MDS","t"]=D[D$cancer2=="MDS","t"]+0.05 graphics.off() quartz(width=7,height=4) theme_update(legend.position = c(.92, .825), axis.text=element_text(size=rel(1.2)), axis.title=element_text(size=rel(1.3)), axis.title.x=element_text(size=rel(1.0)), legend.title=element_text(size=rel(1)), legend.text=element_text(size=rel(1)), strip.text = element_text(size = rel(1.5))) g=qplot(x=t,y=RR,data=D,col=cancer2,geom=c("line","point"), xlab="Years Since Dx of Lymphoid First Cancer",ylab="Relative Risk") g=g+facet_grid(Sex~.,scales="free")+geom_abline(intercept=1, slope=0) g1 <- guide_legend("Second\nCancer") g=g + guides(color=g1) g=g+ geom_errorbar(aes(ymin=L,ymax=U,width=.15))+scale_y_continuous(breaks=c(0,5,10,15)) print(g) ggsave("~/Results/amlMDS/lymphoidFirst.eps") ggsave("~/Results/amlMDS/lymphoidFirst.png")
context("test idig_view_media") med_uuid = "e2d288dc-319e-4a13-b759-527021122bbc" test_that("viewing a media record returns right information", { testthat::skip_on_cran() med <- idig_view_media(med_uuid) expect_that(med, is_a("list")) expect_that(med$uuid, equals(med_uuid)) expect_that(med$data, is_a("list")) expect_that(length(med$data$coreid) > 0, is_true()) expect_that(med$indexTerms, is_a("list")) expect_that(med$indexTerms$uuid, equals(med_uuid)) expect_that(med$attribution, is_a("list")) expect_that(length(med$attribution$description) > 0, is_true()) })
context("compute_bin") comp_bin <- function(...) { suppressMessages(compute_bin(...)) } test_that("compute_bin preserves dates and times", { dates <- data.frame(val = as.Date("2013-06-01") + 0:100) NYtimes <- data.frame( val = as.POSIXct('2001-06-01 21:00', tz = 'America/New_York') + 0:10 * 100 ) UTCtimes <- data.frame( val = as.POSIXct('2001-06-01 21:00', tz = 'UTC') + seq(0, 1000, by = 10) ) res <- comp_bin(dates, ~val, width = 30) expect_true(inherits(res$x_, "Date")) expect_true(inherits(res$xmin_, "Date")) expect_true(inherits(res$xmax_, "Date")) expect_equal(sum(res$count_), length(dates$val)) res <- comp_bin(NYtimes, ~val, width = 120) expect_true(inherits(res$x_, "POSIXct")) expect_true(inherits(res$xmin_, "POSIXct")) expect_true(inherits(res$xmax_, "POSIXct")) expect_equal(sum(res$count_), length(NYtimes$val)) expect_identical(attr(NYtimes$val, "tzone"), attr(res$x_, "tzone")) res <- comp_bin(UTCtimes, ~val, width = 120) expect_equal(sum(res$count_), length(UTCtimes$val)) expect_identical(attr(UTCtimes$val, "tzone"), attr(res$x_, "tzone")) }) test_that("width in lubridate::Period", { UTCtimes <- data.frame( val = as.POSIXct('2001-06-01 21:00', tz = 'UTC') + seq(0, 1000, by = 10) ) expect_identical( comp_bin(UTCtimes, ~val, width = lubridate::ms("1 42")), comp_bin(UTCtimes, ~val, width = 102) ) }) test_that("Closed left or right", { dat <- data.frame(x = c(0, 10)) res <- comp_bin(dat, ~x, width = 10, pad = FALSE) expect_identical(res$count_, c(1, 1)) res <- comp_bin(dat, ~x, width = 10, boundary = 5, pad = FALSE) expect_identical(res$count_, c(1, 1)) res <- comp_bin(dat, ~x, width = 10, boundary = 0, pad = FALSE) expect_identical(res$count_, 2) res <- comp_bin(dat, ~x, width = 5, boundary = 0, pad = FALSE) expect_identical(res$count_, c(1, 1)) res <- comp_bin(dat, ~x, width = 10, pad = FALSE, closed = "left") expect_identical(res$count_, c(1, 1)) res <- comp_bin(dat, ~x, width = 10, boundary = 5, pad = FALSE, closed = "left") expect_identical(res$count_, c(1, 1)) res <- comp_bin(dat, ~x, width = 10, boundary = 0, pad = FALSE, closed = "left") expect_identical(res$count_, c(2)) res <- comp_bin(dat, ~x, width = 5, boundary = 0, pad = FALSE, closed = "left") expect_identical(res$count_, c(1, 1)) }) test_that("Setting boundary and center", { dat <- data.frame(x = c(0, 30)) expect_error(comp_bin(dat, ~x, width = 10, bondary = 5, center = 0, pad = FALSE)) res <- comp_bin(dat, ~x, width = 10, boundary = 0, pad = FALSE) expect_identical(res$count_, c(1, 0, 1)) expect_identical(res$xmin_[1], 0) expect_identical(res$xmax_[3], 30) res <- comp_bin(dat, ~x, width = 10, center = 0, pad = FALSE) expect_identical(res$count_, c(1, 0, 0, 1)) expect_identical(res$xmin_[1], dat$x[1] - 5) expect_identical(res$xmax_[4], dat$x[2] + 5) dat <- data.frame(x = as.Date("2013-06-01") + c(0, 30)) res <- comp_bin(dat, ~x, width = 10, boundary = as.Date("2013-06-01"), pad = FALSE) expect_identical(res$count_, c(1, 0, 1)) expect_identical(res$xmin_[1], dat$x[1]) expect_identical(res$xmax_[3], dat$x[2]) res <- comp_bin(dat, ~x, width = 10, center = as.Date("2013-06-01"), pad = FALSE) expect_identical(res$count_, c(1, 0, 0, 1)) expect_identical(res$xmin_[1], dat$x[1] - 5) expect_identical(res$xmax_[4], dat$x[2] + 5) dat <- data.frame( x = as.POSIXct('2001-06-01 21:00', tz = 'America/New_York') + c(0, 30000) ) res <- comp_bin(dat, ~x, width = 10000, boundary = dat$x[1], pad = FALSE) expect_identical(res$count_, c(1, 0, 1)) expect_identical(res$xmin_[1], dat$x[1]) expect_identical(res$xmax_[3], dat$x[2]) res <- comp_bin(dat, ~x, width = 10000, center = dat$x[1], pad = FALSE) expect_identical(res$count_, c(1, 0, 0, 1)) expect_identical(res$xmin_[1], dat$x[1] - 5000) expect_identical(res$xmax_[4], dat$x[2] + 5000) }) test_that("Automatic width", { dat <- data.frame( num = c(0, 25.0), num2 = c(0, 50.0), int = c(1L, 25L), int2 = c(1L, 50L), date = as.Date("2013-06-01") + c(0, 100), posixct = as.POSIXct('2001-06-01 21:00', tz = 'UTC') + c(0, 1000) ) res <- comp_bin(dat, ~num) expect_identical(res$width_, rep(1, length(res$width_))) res <- comp_bin(dat, ~num2) expect_identical(res$width_, rep(2, length(res$width_))) res <- comp_bin(dat, ~int) expect_true(all(res$width_ == 1L)) res <- comp_bin(dat, ~int2) expect_true(all(res$width_ == 2L)) res <- comp_bin(dat, ~date) r_version <- as.package_version(paste0(R.Version()$major, ".", R.Version()$minor)) if (r_version >= "3.3.0") expect_identical(res$width_, rep(7, length(res$width_))) else expect_identical(res$width_, rep(2, length(res$width_))) res <- comp_bin(dat, ~posixct) expect_identical(res$width_, rep(30, length(res$width_))) }) test_that("Boundaries across groups should be aligned", { dat <- data.frame(x = c(0:2, 0:2+0.7), g=c('a','a','a', 'b','b','b')) res <- dat %>% group_by(g) %>% compute_bin(~x, width = 1, pad = FALSE) expect_true(length(unique(res$x_ %% 1)) == 1) expect_identical(dplyr::groups(res), list(quote(g))) expect_identical(res$count_, rep(1, 6)) }) test_that("Zero-row inputs", { res <- mtcars[0,] %>% compute_bin(~mpg) expect_equal(nrow(res), 0) expect_true(setequal( names(res), c("count_", "x_", "xmin_", "xmax_", "width_") )) res <- mtcars[0,] %>% group_by(cyl) %>% compute_bin(~mpg) expect_equal(nrow(res), 0) expect_true(setequal( names(res), c("cyl", "count_", "x_", "xmin_", "xmax_", "width_") )) }) test_that("weights are added", { df <- data.frame(x = 1:10, y = 1:10) binned <- df %>% compute_bin(~x, ~y, width = 1, pad = FALSE) expect_equal(binned$count_, df$y) }) test_that("NAs get own bin", { x <- c(1:10, NA, NA, NA, NA) binned <- bin_vector(x, width = 100) expect_equal(binned$count_, c(10, 4)) expect_equal(binned$x_, c(50, NA)) }) test_that("only NA, one row of output", { x <- as.numeric(c(NA, NA, NA, NA)) binned <- bin_vector(x) expect_equal(binned$count_, 4) expect_equal(binned$x_, NA) })
artifNA.cv <- function(x, testNA.prop=0.1 ) { n <- nrow(x) p <- ncol(x) total <- n*p missing.matrix = is.na(x) valid.data = which(!missing.matrix) remove.indices = sample(valid.data, testNA.prop*length(valid.data)) x.train = x x.train[remove.indices] = NA return (list(remove.indices = remove.indices, x.train = x.train, x=x)) }
print.elmNN <- function(x,...) { cat("Call:\n") cat(paste(x$call, "\n")) cat("Number of hidden neurons:\n") cat(paste(x$nhid, "\n")) cat("Activation function:\n") cat(paste(x$actfun, "\n")) cat("Input arc weights:\n") cat(paste(head(x$inpweight), "...\n")) cat("Bias of hidden neurons:\n") cat(paste(head(x$biashid), "...\n")) cat("Output arc weights:\n") cat(paste(head(x$outweight), "...\n")) cat("Predictions on training set:\n") cat(paste(head(fitted(x)), "...\n")) }
library(hamcrest) test.CallReplacement <- function() { call <- quote(sin(x)) call[[1]] <- "cos" assertThat(typeof(call), equalTo("language")) } test.CallSubsetting <- function() { call <- quote(sin(x,y,z)) call <- call[c(1L,2L)] assertThat(typeof(call), equalTo("language")) } test.RemoveFunctionFromFunctionCall <- function() { call <- quote(sin(x)) call[[1]] <- NULL assertThat(typeof(call), equalTo("pairlist")) assertThat(length(call), equalTo(1)) } test.DataFrameDollar <- function() { df <- data.frame(x=1:3) df$y <- 4:6 assertThat(df$y, equalTo(c(4,5,6))) } test.RemoveLastElementInPairList <- function() { x <- pairlist(a=1,b=1) x$b <- NULL assertThat(length(x), equalTo(1)) }
path_to_file <- function(path = NULL) { if (is.null(path)) { dir(system.file("extdata", package = "palmerpenguins")) } else { system.file("extdata", path, package = "palmerpenguins", mustWork = TRUE) } }
input1 <- list(hazard_treatment = 0.01, hazard_control = 0.02, N_total = 300, lambda = c(0.3, 1), lambda_time = c(25), interim_look = c(220, 270), EndofStudy = 50) input2 <- list(hazard_treatment = c(0.01, 0.02), cutpoint = 25, EndofStudy = 50,N_impute = 10, N_total = 300, lambda = c(0.3, 1), lambda_time = c(25), interim_look = c(220, 270), alternative = "less") context("") test_that("The binomial bayesCT is ", { set.seed(200) expect_equal(do.call(survivalBACT, input1)$hazard_treatment, 0.01) expect_equal(do.call(survivalBACT, input2)$margin, 0.5) expect_equal(do.call(survivalBACT, input2)$prob_of_accepting_alternative, 0.95) input1$alternative <- "lessthan" expect_error(do.call(binomialBACT, input1)) })
bad_variance = list( list(y ~ 1 + sigma(rel(1))), list(y ~ 1, y ~ 1 + sigma(rel(x))), list(y ~ 1 + sigma(q)) ) test_bad(bad_variance) good_variance = list( list(y ~ 1 + sigma(1)), list(y ~ 1 + sigma(x + I(x^2))), list(y ~ 1 + sigma(1 + sin(x))), list(y ~ 1, ~ 0 + sigma(rel(1)), ~ x + sigma(x), ~ 0 + sigma(rel(x))), list(y ~ 1, 1 + (1|id) ~ rel(1) + I(x^2) + sigma(rel(1) + x)), list(y | weights(weights_ok) ~ 1 + sigma(1 + x), ~ 0 + sigma(1 + rel(x))) ) test_good(good_variance) bad_arma = list( list(y ~ ar(0)), list(y ~ ar(-1)), list(y ~ ar(1.5)), list(y ~ ar(1) + ar(2)), list(y ~ ar("1")), list(y ~ ar(1 + x)), list(y ~ ar(x)) ) test_bad(bad_arma) good_arma = list( list(y ~ ar(1)), list(y ~ ar(5)), list(y ~ ar(1, 1 + x + I(x^2) + exp(x))), list(y ~ ar(1), ~ ar(2, 0 + x)), list(y ~ 1, ~ 0 + ar(2)), list(y ~ 1, 1 + (1|id) ~ rel(1) + I(x^2) + ar(2, rel(1) + x)), list(y ~ ar(1) + sigma(1 + x), ~ ar(2, 1 + I(x^2)) + sigma(1)), list(y ~ ar(1), ~ ar(2, rel(1))), list(y | weights(weights_ok) ~ 1 + ar(1), ~ 0 + ar(2, 1 + x)) ) test_good(good_arma)
"APIS_sire"
som.nn.visual <- function(codes, data){ if (is.data.frame(data)){ data <- as.matrix(data) } if (is.matrix(data)){ winners <- t(apply(data, 1, som.nn.visual.one, codes=codes)) result <- data.frame(winner = winners[,1], distance = winners[,2]) } else { winners <- som.nn.visual.one(data, codes) result <- data.frame(winner = winners[1], distance = winners[2]) } return(result) } som.nn.visual.one <- function(one, codes){ taxi <- t(t(codes) - one) dist.all <- sqrt( rowSums(taxi^2)) winner <- which.min(dist.all) qerror <- dist.all[winner] result <- c(winner, qerror) names(result) <- c("winner", "qerror") return(result) }
test_that("vec_restore() returns a parameters if `x` retains parameters structure", { x <- parameters(penalty()) expect_s3_class_parameters(vec_restore(x, x)) }) test_that("vec_restore() returns bare tibble if `x` loses parameters structure", { to <- parameters(penalty()) x <- as_tibble(to) x <- x["name"] expect_s3_class_bare_tibble(vec_restore(x, to)) }) test_that("vec_restore() retains extra attributes of `to` when not falling back", { x <- parameters(penalty()) to <- x attr(to, "foo") <- "bar" x_tbl <- as_tibble(x) x_tbl <- x_tbl[1] expect_identical(attr(vec_restore(x, to), "foo"), "bar") expect_identical(attr(vec_restore(x_tbl, to), "foo"), NULL) expect_s3_class_parameters(vec_restore(x, to)) expect_s3_class_bare_tibble(vec_restore(x_tbl, to)) }) test_that("parameters proxy is a bare data frame", { x <- parameters(penalty()) expect_s3_class(vec_proxy(x), "data.frame", exact = TRUE) }) test_that("vec_ptype2() is working", { x <- parameters(penalty()) y <- parameters(mixture()) tbl <- tibble::tibble(x = 1) df <- data.frame(x = 1) expect_identical(vec_ptype2(x, x), dials_global_empty_parameters) expect_identical(vec_ptype2(x, y), dials_global_empty_parameters) expect_identical(vec_ptype2(x, tbl), vec_ptype2(tib_upcast(x), tbl)) expect_identical(vec_ptype2(tbl, x), vec_ptype2(tbl, tib_upcast(x))) expect_identical(vec_ptype2(x, df), vec_ptype2(tib_upcast(x), df)) expect_identical(vec_ptype2(df, x), vec_ptype2(df, tib_upcast(x))) }) test_that("vec_cast() is working", { x <- parameters(penalty()) tbl <- tib_upcast(x) df <- as.data.frame(tbl) expect_identical(vec_cast(x, x), x) expect_identical(vec_cast(x, tbl), tbl) expect_error(vec_cast(tbl, x), class = "vctrs_error_incompatible_type") expect_identical(vec_cast(x, df), df) expect_error(vec_cast(df, x), class = "vctrs_error_incompatible_type") }) test_that("vec_ptype() returns a parameters", { x <- parameters(penalty()) expect_identical(vec_ptype(x), dials_global_empty_parameters) expect_s3_class_parameters(vec_ptype(x)) }) test_that("vec_slice() generally returns a parameters", { params <- list(penalty(), mixture()) x <- parameters(params) expect_identical(vec_slice(x, 0), dials_global_empty_parameters) expect_identical(vec_slice(x, 1), parameters(params[1])) expect_s3_class_parameters(vec_slice(x, 0)) }) test_that("vec_slice() can return an bare tibble if `id` is duplicated", { params <- list(penalty(), mixture()) x <- parameters(params) expect_identical(vec_slice(x, c(1, 1)), vec_slice(tib_upcast(x), c(1, 1))) expect_s3_class_bare_tibble(vec_slice(x, c(1, 1))) }) test_that("vec_c() returns a parameters when all inputs are parameters unless `id` is duplicated", { params <- list(penalty(), mixture()) x <- parameters(params[1]) y <- parameters(params[2]) tbl <- tib_upcast(x) expect_identical(vec_c(x), x) expect_identical(vec_c(x, x), vec_c(tbl, tbl)) expect_identical(vec_c(x, tbl), vec_c(tbl, tbl)) expect_identical(vec_c(x, y), parameters(params)) expect_identical(vec_c(y, x), parameters(params[2:1])) }) test_that("vec_rbind() returns a parameters when all inputs are parameters unless `id` is duplicated", { params <- list(penalty(), mixture()) x <- parameters(params[1]) y <- parameters(params[2]) tbl <- tib_upcast(x) expect_identical(vec_rbind(x), x) expect_identical(vec_rbind(x, x), vec_rbind(tbl, tbl)) expect_identical(vec_rbind(x, tbl), vec_rbind(tbl, tbl)) expect_identical(vec_rbind(tbl, x), vec_rbind(tbl, tbl)) expect_identical(vec_rbind(x, y), parameters(params)) expect_identical(vec_rbind(y, x), parameters(params[2:1])) }) test_that("vec_cbind() returns a bare tibble", { params <- list(penalty(), mixture()) x <- parameters(params[1]) y <- parameters(params[2]) tbl <- tib_upcast(x) expect_identical(vec_cbind(x), vec_cbind(tbl)) expect_identical( suppressMessages(vec_cbind(x, x)), suppressMessages(vec_cbind(tbl, tbl)) ) expect_identical( suppressMessages(vec_cbind(x, tbl)), suppressMessages(vec_cbind(tbl, tbl)) ) expect_identical( suppressMessages(vec_cbind(tbl, x)), suppressMessages(vec_cbind(tbl, tbl)) ) })
test_that("Writing Python requirements works", { temp_path <- tempdir(check = TRUE) fs::dir_create(glue::glue("{temp_path}/.binder")) z <- glue::glue(" numpy==1.16.* matplotlib==3.* seaborn==0.8.1") holepunch::write_requirements(path = temp_path, requirements = z) file_path <- glue::glue("{temp_path}/.binder/requirements.txt") expect_true(fs::file_exists(file_path)) require_contents <- readLines(glue::glue("{temp_path}/.binder/requirements.txt")) expect_identical(require_contents[1], "numpy==1.16.*") expect_identical(require_contents[2], "matplotlib==3.*") expect_identical(require_contents[3], "seaborn==0.8.1") unlink(temp_path) }) teardown(unlink("tests/testthat/dir_code/.binder"))
searchSDF <- function(string, data, fileFormat = NULL, levels = FALSE) { if (inherits(data, c("edsurvey.data.frame.list"))) { call0 <- match.call() resl <- lapply(data$data, function(li) { call0$data <- li tryCatch(eval(call0), error = function(cond) { message(paste("An error occurred while working on a dataset. Excluding results from this dataset.")) message(cond) return(0) }, warning = function(w) { return(1) }) }) res <- data.frame() for(i in seq_along(resl)) { ires <- resl[[i]] covs <- data$covs covn <- colnames(covs) if(inherits(ires, "data.frame")) { if(nrow(ires) > 0) { newCol <- paste(covs[i,covn], collapse=";") ires[,newCol] <- "*" if(nrow(res) == 0) { res <- ires } else { res <- merge(res, ires, all=TRUE) } } } } res[is.na(res)] <- "" return(res) } checkDataClass(data, c("edsurvey.data.frame", "light.edsurvey.data.frame", "edsurvey.data.frame.list")) sdf <- data data <- NULL if (inherits(sdf, c("edsurvey.data.frame"))) { dataList <- sdf$dataList } else { warning(paste0("Searched for string(s) ", paste(sQuote(string), collapse=", "), " only in this light.edsurvey.data.frame. To search the full data set, change ", paste0(sQuote("data")), " argument to the edsurvey.data.frame.")) dataList <- attributes(sdf)$dataList } if(is.null(fileFormat)) { labelsFile <- do.call('rbind', lapply(dataList, function(dl){dl$fileFormat})) if (!inherits(sdf, c("edsurvey.data.frame"))) { labelsFile <- labelsFile[(toupper(labelsFile$variableName) %in% toupper(colnames(sdf))), ] } } else { if(length(fileFormat) != 1) { stop(paste0("The ", sQuote("fileFormat"), " argument must have exactly one level.")) } fileFormat <- tolower(fileFormat) if(!fileFormat %in% tolower(names(dataList))) { stop(paste0("The ", sQuote("fileFormat"), " argument must either be one of ", paste(dQuote(names(dataList)), collapse=" or "),".")) } names(dataList) <- tolower(names(dataList)) labelsFile <- (dataList[[fileFormat]])$fileFormat } for(si in string) { labelsFile <- labelsFile[grepl(si, labelsFile$variableName, ignore.case = TRUE) | grepl(si, labelsFile$Labels, ignore.case = TRUE),] } if (is.data.frame(labelsFile) & nrow(labelsFile) == 0) { strg <- ifelse(length(string) > 1, "strings", "string") warning(paste0("There are no variables containing the ", strg, " ", pasteItems(sQuote(string)), " in this edsurvey.data.frame or light.edsurvey.data.frame.")) return(NULL) } labelsFile$variableName <- tolower(labelsFile$variableName) labelsFile$Levels <- NA if (levels == TRUE) { if (length(string) == 1 && string == "") { stop(paste0("The argument ", sQuote("string"), " must be nonempty to return variable levels.")) } varsData <- labelsFile[, c("variableName", "Labels", "labelValues", "Levels")] if ("light.edsurvey.data.frame" %in% class(sdf) == TRUE) { varsData <- varsData[varsData$variableName %in% colnames(sdf), ] } varsData <- varsData[!duplicated(varsData$variableName),] for (i in 1:length(varsData$variableName)) { if (varsData$labelValues[[i]] != "") { levelsInfo <- levelsSDF(varsData$variableName[[i]], sdf)[[varsData$variableName[[i]]]] varLevels <- paste0(levelsInfo$level, ". ", levelsInfo$labels) varLevelsSplit <- c() for (ii in 1:length(varLevels)) { x <- varLevels[[ii]] varLevelsSplit <- c(varLevelsSplit, x) } varLevelsSplitPaste <- paste(varLevelsSplit, collapse = "; ") varsData$Levels[[i]] <- varLevelsSplitPaste } else { varsData$Levels[[i]] <- paste0(NA) } } varsData <- varsData[, c("variableName", "Labels", "Levels")] class(varsData) <- c("searchSDF", "data.frame") } else { labelsFile$variableName <- tolower(labelsFile$variableName) varsData <- labelsFile[, c("variableName", "Labels")] varsData <- data.frame(varsData, stringsAsFactors = FALSE, row.names = NULL) varsData <- varsData[!duplicated(varsData$variableName),] } varsData[] <- lapply(varsData, as.character) return(varsData) } print.searchSDF <- function(x, ...) { class(x) <- "data.frame" cols <- colnames(x) if ("Levels" %in% cols) { x[] <- lapply(x, as.character) for (i in 1:length(unique(x$variableName))) { cat(paste("Variable: ", tolower(x[i, "variableName"]), "\n", sep = "")) cat(paste("Label: ", x[i, "Labels"], "\n", sep = "")) if (x$Levels[i] == "NA") { cat(paste("\n", sep = "")) } else { cat(paste("Levels (Lowest level first):\n ", sep = "")) labs <- lapply(x$Levels, strsplit, split = ";") for (ii in 1:length(labs[[i]][[1]])) { cat(paste(" ", labs[[i]][[1]][ii], "\n", sep = "")) } } } } else { x[] <- lapply(x, as.character) cat(paste(x)) } }
estimateNAH <- function(RT, CR=NULL) { nt <- length(RT) if ( is.null(CR) | length(CR) != nt ) { CR <- rep(1, nt) } RTx <- sort(RT,index.return=TRUE) RT <- RTx$x CR <- as.logical(CR)[RTx$ix] Y <- rep(NA, nt) for (i in 1:nt ) { Y[i] <- sum(RT >= RT[i]) } H <- stepfun( RT[CR], c(0,cumsum(1/Y[CR] ))) H.v<-stepfun( RT[CR], c(0,cumsum(1/Y[CR]^2))) return(list(H=H, Var=H.v)) } estimateNAK <- function(RT, CR=NULL) { nt <- length(RT) if ( is.null(CR) | length(CR) != nt ) { CR <- rep(1, nt) } RTx <- sort(RT,index.return=TRUE) RT <- RTx$x CR <- as.logical(CR)[RTx$ix] G <- rep(NA, nt) for (i in 1:nt ) { G[i] <- sum(RT <= RT[i]) } K <- stepfun( RT[CR], c(rev(- cumsum( rev(1/G[CR]) )),0), right=TRUE) K.v<-stepfun( RT[CR], c(rev( cumsum( rev(1/G[CR]^2) )),0), right=TRUE) return(list(K=K, Var=K.v)) } estimateUCIPor <- function(RT, CR=NULL) { allRT <- sort(c(RT, recursive=TRUE)) ncond <- length(RT) nt <- length(allRT) if ( is.null(CR) | length(CR) != length(RT) ){ CR <- vector("list", length(RT)) } Hucip <- rep(0, nt) Hucip.v <- rep(0, nt) for ( i in 1:ncond ) { Hi <- estimateNAH(RT[[i]], CR[[i]]) Hucip <- Hucip + Hi$H(allRT) Hucip.v <- Hucip.v + Hi$Var(allRT) } Hucip <- stepfun(allRT, c(0, Hucip)) Hucip.v <- stepfun(allRT, c(0, Hucip.v)) return(list(H=Hucip, Var=Hucip.v)) } estimateUCIPand <- function(RT, CR=NULL) { allRT <- sort(c(RT, recursive=TRUE)) ncond <- length(RT) nt <- length(allRT) if ( is.null(CR) | length(CR) != length(RT) ) { CR <- vector("list", length(RT)) } Kucip <- rep(0, nt) Kucip.v <- rep(0, nt) for ( i in 1:ncond ) { Ki <- estimateNAK(RT[[i]], CR[[i]]) Kucip <- Kucip + Ki$K(allRT) Kucip.v <- Kucip.v + Ki$Var(allRT) } Kucip <- stepfun(allRT, c(Kucip,0),right=TRUE) Kucip.v <- stepfun(allRT, c(Kucip.v,0),right=TRUE) return(list(K=Kucip, Var=Kucip.v)) }
"flist.data" <- function () { return(data(package = "bio.infer")$results[,3]) }
test_that("Wide format", { expect_equal(dim(pisaW), c(500, 37)) expect_equal(names(pisaW)[c(1, 2, 14, 26)], c("ID", "y_1", "RT_1", "log_RT_1")) }) test_that("Long format", { expect_equal(dim(pisaL), c(6000, 5)) expect_equal(names(pisaL), c("ID", "item", "y", "RT", "log_RT")) }) test_that("Only positive response times", { expect_true(all(pisaL$RT > 0)) expect_true(all(unlist(pisaW[, paste0("RT_", 1:12)]) > 0)) }) test_that("Only 0 or 1 in responses", { expect_true(all(pisaL$y %in% 0:1)) expect_true(all(unlist(pisaW[, paste0("y_", 1:12)]) %in% 0:1)) }) test_that("Log response times in reasonable range", { expect_true(all(pisaL$log_RT > -1)) expect_true(all(pisaL$log_RT < 8)) expect_true(all(unlist(pisaW[, paste0("log_RT_", 1:12)]) > -1)) expect_true(all(unlist(pisaW[, paste0("log_RT_", 1:12)]) < 8)) })
subsetPointsByGrid <- function(X, Y, resolution=200, grouping=NULL) { if (length(X)!=length(Y)) { stop("'X' and 'Y' must be of the same length") } if (!is.null(grouping)) { grouping <- as.character(grouping) if (length(grouping)!=length(X)) { stop("'X' and 'grouping' must be of the same length") } ugroups <- unique(grouping) ugroups <- ugroups[!is.na(ugroups)] if (length(resolution)==1L) { resolution <- rep(resolution, length.out=length(ugroups)) names(resolution) <- ugroups } if (!all(ugroups %in% names(resolution))) { stop("a 'resolution' vector must be named with all levels in 'grouping'") } output <- logical(length(X)) for (g in ugroups) { current <- grouping==g & !is.na(grouping) output[current] <- subsetPointsByGrid(X[current], Y[current], resolution=resolution[[g]]) } return(output) } resolution <- max(resolution, 1L) resolution <- min(resolution, sqrt(.Machine$integer.max)) resolution <- as.integer(resolution) rangeX <- range(X) rangeY <- range(Y) binX <- (rangeX[2] - rangeX[1])/resolution xid <- (X - rangeX[1])/binX xid <- as.integer(xid) binY <- (rangeY[2] - rangeY[1])/resolution yid <- (Y - rangeY[1])/binY yid <- as.integer(yid) id <- DataFrame(X=xid, Y=yid) !duplicated(id, fromLast=TRUE) }
Heatmap = setClass("Heatmap", slots = list( name = "character", matrix = "matrix", matrix_param = "list", matrix_color_mapping = "ANY", matrix_legend_param = "ANY", row_title = "ANY", row_title_param = "list", column_title = "ANY", column_title_param = "list", row_dend_list = "list", row_dend_slice = "ANY", row_dend_param = "list", row_order_list = "list", row_order = "numeric", column_dend_list = "list", column_dend_slice = "ANY", column_dend_param = "list", column_order_list = "list", column_order = "numeric", row_names_param = "list", column_names_param = "list", top_annotation = "ANY", top_annotation_param = "list", bottom_annotation = "ANY", bottom_annotation_param = "list", left_annotation = "ANY", left_annotation_param = "list", right_annotation = "ANY", right_annotation_param = "list", heatmap_param = "list", layout = "list" ), contains = "AdditiveUnit" ) Heatmap = function(matrix, col, name, na_col = "grey", color_space = "LAB", rect_gp = gpar(col = NA), border = NA, border_gp = gpar(col = "black"), cell_fun = NULL, layer_fun = NULL, jitter = FALSE, row_title = character(0), row_title_side = c("left", "right"), row_title_gp = gpar(fontsize = 13.2), row_title_rot = switch(row_title_side[1], "left" = 90, "right" = 270), column_title = character(0), column_title_side = c("top", "bottom"), column_title_gp = gpar(fontsize = 13.2), column_title_rot = 0, cluster_rows = TRUE, cluster_row_slices = TRUE, clustering_distance_rows = "euclidean", clustering_method_rows = "complete", row_dend_side = c("left", "right"), row_dend_width = unit(10, "mm"), show_row_dend = TRUE, row_dend_reorder = is.logical(cluster_rows) || is.function(cluster_rows), row_dend_gp = gpar(), cluster_columns = TRUE, cluster_column_slices = TRUE, clustering_distance_columns = "euclidean", clustering_method_columns = "complete", column_dend_side = c("top", "bottom"), column_dend_height = unit(10, "mm"), show_column_dend = TRUE, column_dend_gp = gpar(), column_dend_reorder = is.logical(cluster_columns) || is.function(cluster_columns), row_order = NULL, column_order = NULL, row_labels = rownames(matrix), row_names_side = c("right", "left"), show_row_names = TRUE, row_names_max_width = unit(6, "cm"), row_names_gp = gpar(fontsize = 12), row_names_rot = 0, row_names_centered = FALSE, column_labels = colnames(matrix), column_names_side = c("bottom", "top"), show_column_names = TRUE, column_names_max_height = unit(6, "cm"), column_names_gp = gpar(fontsize = 12), column_names_rot = 90, column_names_centered = FALSE, top_annotation = NULL, bottom_annotation = NULL, left_annotation = NULL, right_annotation = NULL, km = 1, split = NULL, row_km = km, row_km_repeats = 1, row_split = split, column_km = 1, column_km_repeats = 1, column_split = NULL, gap = unit(1, "mm"), row_gap = unit(1, "mm"), column_gap = unit(1, "mm"), show_parent_dend_line = ht_opt$show_parent_dend_line, heatmap_width = unit(1, "npc"), width = NULL, heatmap_height = unit(1, "npc"), height = NULL, show_heatmap_legend = TRUE, heatmap_legend_param = list(title = name), use_raster = NULL, raster_device = c("png", "jpeg", "tiff", "CairoPNG", "CairoJPEG", "CairoTIFF", "agg_png"), raster_quality = 1, raster_device_param = list(), raster_resize_mat = FALSE, raster_by_magick = requireNamespace("magick", quietly = TRUE), raster_magick_filter = NULL, post_fun = NULL) { dev.null() on.exit(dev.off2()) verbose = ht_opt("verbose") .Object = new("Heatmap") if(missing(name)) { name = paste0("matrix_", get_heatmap_index() + 1) increase_heatmap_index() } else if(is.null(name)) { name = paste0("matrix_", get_heatmap_index() + 1) increase_heatmap_index() } if(name == "") { stop_wrap("Heatmap name cannot be empty string.") } .Object@name = name called_args = names(as.list(match.call())[-1]) for(opt_name in c("row_names_gp", "column_names_gp", "row_title_gp", "column_title_gp")) { opt_name2 = paste0("heatmap_", opt_name) if(! opt_name %in% called_args) { if(!is.null(ht_opt(opt_name2))) { if(verbose) qqcat("re-assign @{opt_name} with `ht_opt('@{opt_name2}'')`\n") assign(opt_name, ht_opt(opt_name2)) } } } if("top_annotation_height" %in% called_args) { stop_wrap("`top_annotation_height` is removed. Set the height directly in `HeatmapAnnotation()`.") } if("bottom_annotation_height" %in% called_args) { stop_wrap("`bottom_annotation_height` is removed. Set the height directly in `HeatmapAnnotation()`.") } if("combined_name_fun" %in% called_args) { stop_wrap("`combined_name_fun` is removed. Please directly set `row_names_title`. See https://jokergoo.github.io/ComplexHeatmap-reference/book/a-single-heatmap.html } if("heatmap_legend_param" %in% called_args) { for(opt_name in setdiff(c("title_gp", "title_position", "labels_gp", "grid_width", "grid_height", "border"), names(heatmap_legend_param))) { opt_name2 = paste0("legend_", opt_name) if(!is.null(ht_opt(opt_name2))) if(verbose) qqcat("re-assign heatmap_legend_param$@{opt_name} with `ht_opt('@{opt_name2}'')`\n") heatmap_legend_param[[opt_name]] = ht_opt(opt_name2) } } else { for(opt_name in c("title_gp", "title_position", "labels_gp", "grid_width", "grid_height", "border")) { opt_name2 = paste0("legend_", opt_name) if(!is.null(ht_opt(opt_name2))) if(verbose) qqcat("re-assign heatmap_legend_param$@{opt_name} with `ht_opt('@{opt_name2}'')`\n") heatmap_legend_param[[opt_name]] = ht_opt(opt_name2) } } if(is.data.frame(matrix)) { if(verbose) qqcat("convert data frame to matrix\n") warning_wrap("The input is a data frame-like object, convert it to a matrix.") if(!all(sapply(matrix, is.numeric))) { warning_wrap("Note: not all columns in the data frame are numeric. The data frame will be converted into a character matrix.") } matrix = as.matrix(matrix) } fa_level = NULL if(!is.matrix(matrix)) { if(is.atomic(matrix)) { if(is.factor(matrix)) { fa_level = levels(matrix) } rn = names(matrix) matrix = matrix(matrix, ncol = 1) if(!is.null(rn)) rownames(matrix) = rn if(!missing(name)) colnames(matrix) = name if(verbose) qqcat("convert simple vector to one-column matrix\n") } else { stop_wrap("If input is not a matrix, it should be a simple vector.") } } if(missing(row_km)) row_km = km if(is.null(row_km)) row_km = 1 if(missing(row_split)) row_split = split if(missing(row_gap)) row_gap = gap if(is.null(column_km)) column_km = 1 if(ncol(matrix) == 0 || nrow(matrix) == 0) { if(!inherits(cluster_columns, c("dendrogram", "hclust"))) { cluster_columns = FALSE show_column_dend = FALSE } if(!inherits(cluster_rows, c("dendrogram", "hclust"))) { cluster_rows = FALSE show_row_dend = FALSE } row_km = 1 column_km = 1 if(verbose) qqcat("zero row/column matrix, set cluster_columns/rows to FALSE\n") } if(ncol(matrix) == 1) { if(!inherits(cluster_columns, c("dendrogram", "hclust"))) { cluster_columns = FALSE show_column_dend = FALSE } column_km = 1 if(verbose) qqcat("one-column matrix, set cluster_columns to FALSE\n") } if(nrow(matrix) == 1) { if(!inherits(cluster_rows, c("dendrogram", "hclust"))) { cluster_rows = FALSE show_row_dend = FALSE } row_km = 1 if(verbose) qqcat("one-row matrix, set cluster_rows to FALSE\n") } if(is.character(matrix)) { called_args = names(match.call()[-1]) if("clustering_distance_rows" %in% called_args) { } else if(inherits(cluster_rows, c("dendrogram", "hclust"))) { } else { cluster_rows = FALSE show_row_dend = FALSE } row_dend_reorder = FALSE cluster_row_slices = FALSE if(inherits(cluster_rows, c("dendrogram", "hclust")) && length(row_split) == 1) { if(!"cluster_row_slices" %in% called_args) { cluster_row_slices = TRUE } } if("clustering_distance_columns" %in% called_args) { } else if(inherits(cluster_columns, c("dendrogram", "hclust"))) { } else { cluster_columns = FALSE show_column_dend = FALSE } column_dend_reorder = FALSE cluster_column_slices = FALSE if(inherits(cluster_columns, c("dendrogram", "hclust")) && length(column_split) == 1) { if(!"cluster_column_slices" %in% called_args) { cluster_column_slices = TRUE } } row_km = 1 column_km = 1 if(verbose) qqcat("matrix is character. Do not cluster unless distance method is provided.\n") } class(matrix) = "matrix" .Object@matrix = matrix .Object@matrix_param$row_km = row_km .Object@matrix_param$row_km_repeats = row_km_repeats .Object@matrix_param$row_gap = row_gap .Object@matrix_param$column_km = column_km .Object@matrix_param$column_km_repeats = column_km_repeats .Object@matrix_param$column_gap = column_gap .Object@matrix_param$jitter = jitter if(!is.null(row_split)) { if(inherits(cluster_rows, c("dendrogram", "hclust"))) { if(is.numeric(row_split) && length(row_split) == 1) { .Object@matrix_param$row_split = row_split } else { stop_wrap("When `cluster_rows` is a dendrogram, `row_split` can only be a single number.") } } else { if(identical(cluster_rows, TRUE) && is.numeric(row_split) && length(row_split) == 1) { } else { if(!is.data.frame(row_split)) row_split = data.frame(row_split) if(nrow(row_split) != nrow(matrix)) { stop_wrap("Length or nrow of `row_split` should be same as nrow of `matrix`.") } } } } .Object@matrix_param$row_split = row_split if(!is.null(column_split)) { if(inherits(cluster_columns, c("dendrogram", "hclust"))) { if(is.numeric(column_split) && length(column_split) == 1) { .Object@matrix_param$column_split = column_split } else { stop_wrap("When `cluster_columns` is a dendrogram, `column_split` can only be a single number.") } } else { if(identical(cluster_columns, TRUE) && is.numeric(column_split) && length(column_split) == 1) { } else { if(!is.data.frame(column_split)) column_split = data.frame(column_split) if(nrow(column_split) != ncol(matrix)) { stop_wrap("Length or ncol of `column_split` should be same as ncol of `matrix`.") } } } } .Object@matrix_param$column_split = column_split .Object@matrix_param$gp = check_gp(rect_gp) if(missing(border)) { if(!is.null(ht_opt$heatmap_border)) border = ht_opt$heatmap_border } if(!missing(border_gp) && missing(border)) border = TRUE .Object@matrix_param$border = border .Object@matrix_param$border_gp = border_gp .Object@matrix_param$cell_fun = cell_fun .Object@matrix_param$layer_fun = layer_fun if(nrow(matrix) > 100 || ncol(matrix) > 100) { if(!is.null(cell_fun)) { warning_wrap("You defined `cell_fun` for a heatmap with more than 100 rows or columns, which might be very slow to draw. Consider to use the vectorized version `layer_fun`.") } } if(ncol(matrix) > 0 && nrow(matrix) > 0) { if(missing(col)) { col = default_col(matrix, main_matrix = TRUE) if(!is.null(fa_level)) { col = col[fa_level] } if(verbose) qqcat("color is not specified, use randomly generated colors\n") } if(is.null(col)) { col = default_col(matrix, main_matrix = TRUE) if(!is.null(fa_level)) { col = col[fa_level] } if(verbose) qqcat("color is not specified, use randomly generated colors\n") } if(is.function(col)) { .Object@matrix_color_mapping = ColorMapping(col_fun = col, name = name, na_col = na_col) if(verbose) qqcat("input color is a color mapping function\n") } else if(inherits(col, "ColorMapping")){ .Object@matrix_color_mapping = col if(verbose) qqcat("input color is a ColorMapping object\n") } else { if(is.null(names(col))) { if(length(col) == length(unique(as.vector(matrix)))) { if(is.null(fa_level)) { if(is.numeric(matrix)) { names(col) = sort(unique(as.vector(matrix))) col = rev(col) } else { names(col) = sort(unique(as.vector(matrix))) } } else { names(col) = fa_level } .Object@matrix_color_mapping = ColorMapping(colors = col, name = name, na_col = na_col) if(verbose) qqcat("input color is a vector with no names, treat it as discrete color mapping\n") } else if(is.numeric(matrix)) { col = colorRamp2(seq(min(matrix, na.rm = TRUE), max(matrix, na.rm = TRUE), length.out = length(col)), col, space = color_space) .Object@matrix_color_mapping = ColorMapping(col_fun = col, name = name, na_col = na_col) if(verbose) qqcat("input color is a vector with no names, treat it as continuous color mapping\n") } else { stop_wrap("`col` should have names to map to values in `mat`.") } } else { full_col = col if(is.null(fa_level)) { col = col[intersect(c(names(col), "_NA_"), as.character(matrix))] } else { col = col[intersect(c(fa_level, "_NA_"), names(col))] } .Object@matrix_color_mapping = ColorMapping(colors = col, name = name, na_col = na_col, full_col = full_col) if(verbose) qqcat("input color is a named vector\n") } } .Object@matrix_legend_param = heatmap_legend_param } if(identical(row_title, NA) || identical(row_title, "")) { row_title = character(0) } .Object@row_title = row_title .Object@row_title_param$rot = row_title_rot %% 360 .Object@row_title_param$side = match.arg(row_title_side)[1] .Object@row_title_param$gp = check_gp(row_title_gp) .Object@row_title_param$just = get_text_just(rot = row_title_rot, side = .Object@row_title_param$side) if(identical(column_title, NA) || identical(column_title, "")) { column_title = character(0) } .Object@column_title = column_title .Object@column_title_param$rot = column_title_rot %% 360 .Object@column_title_param$side = match.arg(column_title_side)[1] .Object@column_title_param$gp = check_gp(column_title_gp) .Object@column_title_param$just = get_text_just(rot = column_title_rot, side = .Object@column_title_param$side) if(is.null(rownames(matrix))) { if(is.null(row_labels)) { show_row_names = FALSE } } .Object@row_names_param$labels = row_labels .Object@row_names_param$side = match.arg(row_names_side)[1] .Object@row_names_param$show = show_row_names .Object@row_names_param$gp = check_gp(row_names_gp) .Object@row_names_param$rot = row_names_rot .Object@row_names_param$centered = row_names_centered .Object@row_names_param$max_width = row_names_max_width + unit(2, "mm") if(show_row_names) { if(length(row_labels) != nrow(matrix)) { stop_wrap("Length of `row_labels` should be the same as the nrow of matrix.") } if(row_names_centered) { row_names_anno = anno_text(row_labels, which = "row", gp = row_names_gp, rot = row_names_rot, location = 0.5, just = "center") } else { row_names_anno = anno_text(row_labels, which = "row", gp = row_names_gp, rot = row_names_rot, location = ifelse(.Object@row_names_param$side == "left", 1, 0), just = ifelse(.Object@row_names_param$side == "left", "right", "left")) } .Object@row_names_param$anno = row_names_anno } if(is.null(colnames(matrix))) { if(is.null(column_labels)) { show_column_names = FALSE } } .Object@column_names_param$labels = column_labels .Object@column_names_param$side = match.arg(column_names_side)[1] .Object@column_names_param$show = show_column_names .Object@column_names_param$gp = check_gp(column_names_gp) .Object@column_names_param$rot = column_names_rot .Object@column_names_param$centered = column_names_centered .Object@column_names_param$max_height = column_names_max_height + unit(2, "mm") if(show_column_names) { if(length(column_labels) != ncol(matrix)) { stop_wrap("Length of `column_labels` should be the same as the ncol of matrix.") } if(column_names_centered) { column_names_anno = anno_text(column_labels, which = "column", gp = column_names_gp, rot = column_names_rot, location = 0.5, just = "center") } else { column_names_anno = anno_text(column_labels, which = "column", gp = column_names_gp, rot = column_names_rot, location = ifelse(.Object@column_names_param$side == "top", 0, 1), just = ifelse(.Object@column_names_param$side == "top", ifelse(.Object@column_names_param$rot >= 0, "left", "right"), ifelse(.Object@column_names_param$rot >= 0, "right", "left") )) } .Object@column_names_param$anno = column_names_anno } if(missing(cluster_rows) && !missing(row_order)) { cluster_rows = FALSE } if(is.logical(cluster_rows)) { if(!cluster_rows) { row_dend_width = unit(0, "mm") show_row_dend = FALSE } .Object@row_dend_param$cluster = cluster_rows } else if(inherits(cluster_rows, "dendrogram") || inherits(cluster_rows, "hclust")) { .Object@row_dend_param$obj = cluster_rows .Object@row_dend_param$cluster = TRUE } else if(inherits(cluster_rows, "function")) { .Object@row_dend_param$fun = cluster_rows .Object@row_dend_param$cluster = TRUE } else { oe = try(cluster_rows <- as.dendrogram(cluster_rows), silent = TRUE) if(!inherits(oe, "try-error")) { .Object@row_dend_param$obj = cluster_rows .Object@row_dend_param$cluster = TRUE } else { stop_wrap("`cluster_rows` should be a logical value, a clustering function or a clustering object.") } } if(!show_row_dend) { row_dend_width = unit(0, "mm") } .Object@row_dend_list = list() .Object@row_dend_param$distance = clustering_distance_rows .Object@row_dend_param$method = clustering_method_rows .Object@row_dend_param$side = match.arg(row_dend_side)[1] .Object@row_dend_param$width = row_dend_width + ht_opt$DENDROGRAM_PADDING .Object@row_dend_param$show = show_row_dend .Object@row_dend_param$gp = check_gp(row_dend_gp) .Object@row_dend_param$reorder = row_dend_reorder .Object@row_order_list = list() if(is.null(row_order)) { .Object@row_order = seq_len(nrow(matrix)) } else { if(is.character(row_order)) { row_order = structure(seq_len(nrow(matrix)), names = rownames(matrix))[row_order] } if(any(is.na(row_order))) { stop_wrap("`row_order` should not contain NA values.") } if(length(row_order) != nrow(matrix)) { stop_wrap("length of `row_order` should be same as the number of marix rows.") } .Object@row_order = row_order } .Object@row_dend_param$cluster_slices = cluster_row_slices if(missing(cluster_columns) && !missing(column_order)) { cluster_columns = FALSE } if(is.logical(cluster_columns)) { if(!cluster_columns) { column_dend_height = unit(0, "mm") show_column_dend = FALSE } .Object@column_dend_param$cluster = cluster_columns } else if(inherits(cluster_columns, "dendrogram") || inherits(cluster_columns, "hclust")) { .Object@column_dend_param$obj = cluster_columns .Object@column_dend_param$cluster = TRUE } else if(inherits(cluster_columns, "function")) { .Object@column_dend_param$fun = cluster_columns .Object@column_dend_param$cluster = TRUE } else { oe = try(cluster_columns <- as.dendrogram(cluster_columns), silent = TRUE) if(!inherits(oe, "try-error")) { .Object@column_dend_param$obj = cluster_columns .Object@column_dend_param$cluster = TRUE } else { stop_wrap("`cluster_columns` should be a logical value, a clustering function or a clustering object.") } } if(!show_column_dend) { column_dend_height = unit(0, "mm") } .Object@column_dend_list = list() .Object@column_dend_param$distance = clustering_distance_columns .Object@column_dend_param$method = clustering_method_columns .Object@column_dend_param$side = match.arg(column_dend_side)[1] .Object@column_dend_param$height = column_dend_height + ht_opt$DENDROGRAM_PADDING .Object@column_dend_param$show = show_column_dend .Object@column_dend_param$gp = check_gp(column_dend_gp) .Object@column_dend_param$reorder = column_dend_reorder if(is.null(column_order)) { .Object@column_order = seq_len(ncol(matrix)) } else { if(is.character(column_order)) { column_order = structure(seq_len(ncol(matrix)), names = colnames(matrix))[column_order] } if(any(is.na(column_order))) { stop_wrap("`column_order` should not contain NA values.") } if(length(column_order) != ncol(matrix)) { stop_wrap("length of `column_order` should be same as the number of marix columns") } .Object@column_order = column_order } .Object@column_dend_param$cluster_slices = cluster_column_slices .Object@top_annotation = top_annotation if(is.null(top_annotation)) { .Object@top_annotation_param$height = unit(0, "mm") } else { if(inherits(top_annotation, "AnnotationFunction")) { stop_wrap("The annotation function `anno_*()` should be put inside `HeatmapAnnotation()`.") } .Object@top_annotation_param$height = height(top_annotation) + ht_opt$COLUMN_ANNO_PADDING } if(!is.null(top_annotation)) { if(length(top_annotation) > 0) { if(!.Object@top_annotation@which == "column") { stop_wrap("`which` in `top_annotation` should only be `column`.") } } nb = nobs(top_annotation) if(!is.na(nb)) { if(nb != ncol(.Object@matrix)) { stop_wrap("number of observations in top annotation should be as same as ncol of the matrix.") } } } if(!is.null(top_annotation)) { validate_anno_names_with_matrix(matrix, top_annotation, "column") } .Object@bottom_annotation = bottom_annotation if(is.null(bottom_annotation)) { .Object@bottom_annotation_param$height = unit(0, "mm") } else { if(inherits(bottom_annotation, "AnnotationFunction")) { stop_wrap("The annotation function `anno_*()` should be put inside `HeatmapAnnotation()`.") } .Object@bottom_annotation_param$height = height(bottom_annotation) + ht_opt$COLUMN_ANNO_PADDING } if(!is.null(bottom_annotation)) { if(length(bottom_annotation) > 0) { if(!.Object@bottom_annotation@which == "column") { stop_wrap("`which` in `bottom_annotation` should only be `column`.") } } nb = nobs(bottom_annotation) if(!is.na(nb)) { if(nb != ncol(.Object@matrix)) { stop_wrap("number of observations in bottom annotation should be as same as ncol of the matrix.") } } } if(!is.null(bottom_annotation)) { validate_anno_names_with_matrix(matrix, bottom_annotation, "column") } .Object@left_annotation = left_annotation if(is.null(left_annotation)) { .Object@left_annotation_param$width = unit(0, "mm") } else { if(inherits(left_annotation, "AnnotationFunction")) { stop_wrap("The annotation function `anno_*()` should be put inside `rowAnnotation()`.") } .Object@left_annotation_param$width = width(left_annotation) + ht_opt$ROW_ANNO_PADDING } if(!is.null(left_annotation)) { if(length(left_annotation) > 0) { if(!.Object@left_annotation@which == "row") { stop_wrap("`which` in `left_annotation` should only be `row`, or consider using `rowAnnotation()`.") } } nb = nobs(left_annotation) if(!is.na(nb)) { if(nb != nrow(.Object@matrix)) { stop_wrap("number of observations in left annotation should be same as nrow of the matrix.") } } } if(!is.null(left_annotation)) { validate_anno_names_with_matrix(matrix, left_annotation, "row") } .Object@right_annotation = right_annotation if(is.null(right_annotation)) { .Object@right_annotation_param$width = unit(0, "mm") } else { if(inherits(right_annotation, "AnnotationFunction")) { stop_wrap("The annotation function `anno_*()` should be put inside `rowAnnotation()`.") } .Object@right_annotation_param$width = width(right_annotation) + ht_opt$ROW_ANNO_PADDING } if(!is.null(right_annotation)) { if(length(right_annotation) > 0) { if(!.Object@right_annotation@which == "row") { stop_wrap("`which` in `right_annotation` should only be `row`, or consider using `rowAnnotation()`.") } } nb = nobs(right_annotation) if(!is.na(nb)) { if(nb != nrow(.Object@matrix)) { stop_wrap("number of observations in right annotation should be same as nrow of the matrix.") } } } if(!is.null(right_annotation)) { validate_anno_names_with_matrix(matrix, right_annotation, "row") } .Object@layout = list( layout_size = list( column_title_top_height = unit(0, "mm"), column_dend_top_height = unit(0, "mm"), column_anno_top_height = unit(0, "mm"), column_names_top_height = unit(0, "mm"), column_title_bottom_height = unit(0, "mm"), column_dend_bottom_height = unit(0, "mm"), column_anno_bottom_height = unit(0, "mm"), column_names_bottom_height = unit(0, "mm"), row_title_left_width = unit(0, "mm"), row_dend_left_width = unit(0, "mm"), row_names_left_width = unit(0, "mm"), row_dend_right_width = unit(0, "mm"), row_names_right_width = unit(0, "mm"), row_title_right_width = unit(0, "mm"), row_anno_left_width = unit(0, "mm"), row_anno_right_width = unit(0, "mm") ), layout_index = matrix(nrow = 0, ncol = 2), graphic_fun_list = list(), initialized = FALSE ) if(is.null(width)) { width = unit(ncol(matrix), "null") } else if(is.numeric(width) && !inherits(width, "unit")) { width = unit(width, "null") } else if(!inherits(width, "unit")) { stop_wrap("`width` should be a `unit` object or a single number.") } if(is.null(height)) { height = unit(nrow(matrix), "null") } else if(is.numeric(height) && !inherits(height, "unit")) { height = unit(height, "null") } else if(!inherits(height, "unit")) { stop_wrap("`height` should be a `unit` object or a single number.") } if(!is.null(width) && !is.null(heatmap_width)) { if(is_abs_unit(width) && is_abs_unit(heatmap_width)) { stop_wrap("`heatmap_width` and `width` should not all be the absolute units.") } } if(!is.null(height) && !is.null(heatmap_height)) { if(is_abs_unit(height) && is_abs_unit(heatmap_height)) { stop_wrap("`heatmap_height` and `height` should not all be the absolute units.") } } if(is.null(use_raster)) { if(nrow(matrix) > 2000 && ncol(matrix) > 10) { use_raster = TRUE if(ht_opt$message) { message_wrap("`use_raster` is automatically set to TRUE for a matrix with more than 2000 rows. You can control `use_raster` argument by explicitly setting TRUE/FALSE to it.\n\nSet `ht_opt$message = FALSE` to turn off this message.") } } else if(ncol(matrix) > 2000 && nrow(matrix) > 10) { use_raster = TRUE if(ht_opt$message) { message_wrap("`use_raster` is automatically set to TRUE for a matrix with more than 2000 columns You can control `use_raster` argument by explicitly setting TRUE/FALSE to it.\n\nSet `ht_opt$message = FALSE` to turn off this message.") } } else { use_raster = FALSE } } if(use_raster) { if(missing(raster_by_magick)) { if(!raster_by_magick) { if(ht_opt$message) { message_wrap("'magick' package is suggested to install to give better rasterization.\n\nSet `ht_opt$message = FALSE` to turn off this message.") } } } } .Object@matrix_param$width = width .Object@matrix_param$height = height .Object@heatmap_param$width = heatmap_width .Object@heatmap_param$height = heatmap_height .Object@heatmap_param$show_heatmap_legend = show_heatmap_legend .Object@heatmap_param$use_raster = use_raster if(missing(raster_device)) { if(requireNamespace("Cairo", quietly = TRUE)) { raster_device = "CairoPNG" } else { raster_device = "png" } } else { raster_device = match.arg(raster_device)[1] } .Object@heatmap_param$raster_device = raster_device .Object@heatmap_param$raster_quality = raster_quality .Object@heatmap_param$raster_device_param = raster_device_param .Object@heatmap_param$raster_resize_mat = raster_resize_mat .Object@heatmap_param$raster_by_magick = raster_by_magick .Object@heatmap_param$raster_magick_filter = raster_magick_filter .Object@heatmap_param$verbose = verbose .Object@heatmap_param$post_fun = post_fun .Object@heatmap_param$calling_env = parent.frame() .Object@heatmap_param$show_parent_dend_line = show_parent_dend_line if(nrow(matrix) == 0) { .Object@matrix_param$height = unit(0, "mm") } if(ncol(matrix) == 0) { .Object@matrix_param$width = unit(0, "mm") } return(.Object) } setMethod(f = "make_row_cluster", signature = "Heatmap", definition = function(object) { object = make_cluster(object, "row") if(length(object@row_title) > 1) { if(length(object@row_title) != length(object@row_order_list)) { stop_wrap("If `row_title` is set with length > 1, the length should be as same as the number of row slices.") } } return(object) }) setMethod(f = "make_column_cluster", signature = "Heatmap", definition = function(object) { object = make_cluster(object, "column") if(length(object@column_title) > 1) { if(length(object@column_title) != length(object@column_order_list)) { stop_wrap("If `column_title` is set with length > 1, the length should be as same as the number of column slices.") } } return(object) }) make_cluster = function(object, which = c("row", "column")) { which = match.arg(which)[1] verbose = object@heatmap_param$verbose if(ht_opt("fast_hclust")) { hclust = fastcluster::hclust if(verbose) qqcat("apply hclust by fastcluster::hclust\n") } else { hclust = stats::hclust } mat = object@matrix jitter = object@matrix_param$jitter if(is.numeric(mat)) { if(is.logical(jitter)) { if(jitter) { mat = mat + runif(length(mat), min = 0, max = 1e-10) } } else { mat = mat + runif(length(mat), min = 0, max = jitter + 0) } } distance = slot(object, paste0(which, "_dend_param"))$distance method = slot(object, paste0(which, "_dend_param"))$method order = slot(object, paste0(which, "_order")) km = getElement(object@matrix_param, paste0(which, "_km")) km_repeats = getElement(object@matrix_param, paste0(which, "_km_repeats")) split = getElement(object@matrix_param, paste0(which, "_split")) reorder = slot(object, paste0(which, "_dend_param"))$reorder cluster = slot(object, paste0(which, "_dend_param"))$cluster cluster_slices = slot(object, paste0(which, "_dend_param"))$cluster_slices gap = getElement(object@matrix_param, paste0(which, "_gap")) dend_param = slot(object, paste0(which, "_dend_param")) dend_list = slot(object, paste0(which, "_dend_list")) dend_slice = slot(object, paste0(which, "_dend_slice")) order_list = slot(object, paste0(which, "_order_list")) order = slot(object, paste0(which, "_order")) names_param = slot(object, paste0(which, "_names_param")) dend_param$split_by_cutree = FALSE if(!is.null(dend_param$obj)) { if(inherits(dend_param$obj, "hclust")) { ncl = length(dend_param$obj$order) } else { ncl = nobs(dend_param$obj) } if(which == "row") { if(ncl != nrow(mat)) { stop_wrap("The length of the row clustering object is not the same as the number of matrix rows.") } } else { if(ncl != ncol(mat)) { stop_wrap("The length of the column clustering object is not the same as the number of matrix columns") } } } if(cluster) { if(is.numeric(split) && length(split) == 1) { if(is.null(dend_param$obj)) { if(verbose) qqcat("split @{which}s by cutree, apply hclust on the entire @{which}s\n") if(which == "row") { dend_param$obj = hclust(get_dist(mat, distance), method = method) } else { dend_param$obj = hclust(get_dist(t(mat), distance), method = method) } } } if(!is.null(dend_param$obj)) { if(km > 1) { stop_wrap("You can not perform k-means clustering since you have already specified a clustering object.") } if(inherits(dend_param$obj, "hclust")) { dend_param$obj = as.dendrogram(dend_param$obj) if(verbose) qqcat("convert hclust object to dendrogram object\n") } if(is.null(split)) { dend_list = list(dend_param$obj) order_list = list(get_dend_order(dend_param$obj)) if(verbose) qqcat("since you provided a clustering object and @{which}_split is null, the entrie clustering object is taken as an one-element list.\n") } else { if(length(split) > 1 || !is.numeric(split)) { stop_wrap(qq("Since you specified a clustering object, you can only split @{which}s by providing a number (number of @{which} slices).")) } if(split < 2) { stop_wrap(qq("`@{which}_split` should be >= 2.")) } dend_param$split_by_cutree = TRUE ct = cut_dendrogram(dend_param$obj, split) dend_list = ct$lower dend_slice = ct$upper sth = tapply(order.dendrogram(dend_param$obj), rep(seq_along(dend_list), times = sapply(dend_list, nobs)), function(x) x, simplify = FALSE) attributes(sth) = NULL order_list = sth if(verbose) qqcat("cut @{which} dendrogram into @{split} slices.\n") } if(identical(reorder, NULL)) { if(is.numeric(mat)) { reorder = TRUE } else { reorder = FALSE } } do_reorder = TRUE if(identical(reorder, NA) || identical(reorder, FALSE)) { do_reorder = FALSE } if(identical(reorder, TRUE)) { do_reorder = TRUE if(which == "row") { reorder = -rowMeans(mat, na.rm = TRUE) } else { reorder = -colMeans(mat, na.rm = TRUE) } } if(do_reorder) { if(which == "row") { if(length(reorder) != nrow(mat)) { stop_wrap("weight of reordering should have same length as number of rows.\n") } } else { if(length(reorder) != ncol(mat)) { stop_wrap("weight of reordering should have same length as number of columns\n") } } for(i in seq_along(dend_list)) { if(length(order_list[[i]]) > 1) { sub_ind = sort(order_list[[i]]) dend_list[[i]] = reorder(dend_list[[i]], reorder[sub_ind], mean) order_list[[i]] = order.dendrogram(dend_list[[i]]) } } } dend_list = lapply(dend_list, adjust_dend_by_x) slot(object, paste0(which, "_order")) = unlist(order_list) slot(object, paste0(which, "_order_list")) = order_list slot(object, paste0(which, "_dend_list")) = dend_list slot(object, paste0(which, "_dend_param")) = dend_param slot(object, paste0(which, "_dend_slice")) = dend_slice if(!is.null(split)) { if(is.null(attr(dend_list[[1]], ".class_label"))) { split = data.frame(rep(seq_along(order_list), times = sapply(order_list, length))) } else { split = data.frame(rep(sapply(dend_list, function(x) attr(x, ".class_label")), times = sapply(order_list, length))) } object@matrix_param[[ paste0(which, "_split") ]] = split for(i in seq_along(names_param$gp)) { if(length(names_param$gp[[i]]) == length(order_list)) { gp_temp = NULL for(j in seq_along(order_list)) { gp_temp[ order_list[[j]] ] = names_param$gp[[i]][j] } names_param$gp[[i]] = gp_temp } } if(!is.null(names_param$anno)) { names_param$anno@var_env$gp = names_param$gp } slot(object, paste0(which, "_names_param")) = names_param n_slice = length(order_list) if(length(gap) == 1) { gap = rep(gap, n_slice) } else if(length(gap) == n_slice - 1) { gap = unit.c(gap, unit(0, "mm")) } else if(length(gap) != n_slice) { stop_wrap(qq("Length of `gap` should be 1 or number of @{which} slices.")) } object@matrix_param[[ paste0(which, "_gap") ]] = gap title = slot(object, paste0(which, "_title")) if(!is.null(split)) { if(length(title) == 0 && !is.null(title)) { title = apply(unique(split), 1, paste, collapse = ",") } else if(length(title) == 1) { if(grepl("%s", title)) { title = apply(unique(split), 1, function(x) { lt = lapply(x, function(x) x) lt$fmt = title do.call(sprintf, lt) }) } else if(grepl("@\\{.+\\}", title)) { title = apply(unique(split), 1, function(x) { x = x envir = environment() title = get("title") op = parent.env(envir) calling_env = object@heatmap_param$calling_env parent.env(envir) = calling_env title = GetoptLong::qq(title, envir = envir) parent.env(envir) = op return(title) }) } else if(grepl("\\{.+\\}", title)) { if(!requireNamespace("glue")) { stop_wrap("You need to install glue package.") } title = apply(unique(split), 1, function(x) { x = x envir = environment() title = get("title") op = parent.env(envir) calling_env = object@heatmap_param$calling_env parent.env(envir) = calling_env title = glue::glue(title, envir = calling_env) parent.env(envir) = op return(title) }) } } } slot(object, paste0(which, "_title")) = title } return(object) } } else { if(verbose) qqcat("no clustering is applied/exists on @{which}s\n") } if(verbose) qq("clustering object is not pre-defined, clustering is applied to each @{which} slice\n") consensus_kmeans = function(mat, centers, km_repeats) { partition_list = lapply(seq_len(km_repeats), function(i) { as.cl_hard_partition(kmeans(mat, centers)) }) partition_list = cl_ensemble(list = partition_list) partition_consensus = cl_consensus(partition_list) as.vector(cl_class_ids(partition_consensus)) } if(km > 1 && is.numeric(mat)) { if(which == "row") { cl = consensus_kmeans(mat, km, km_repeats) meanmat = lapply(sort(unique(cl)), function(i) { colMeans(mat[cl == i, , drop = FALSE], na.rm = TRUE) }) } else { cl = consensus_kmeans(t(mat), km, km_repeats) meanmat = lapply(sort(unique(cl)), function(i) { rowMeans(mat[, cl == i, drop = FALSE], na.rm = TRUE) }) } meanmat = do.call("cbind", meanmat) if(length(reorder) > 1) { weight = tapply(reorder, cl, mean) } else { weight = colMeans(meanmat) } if(cluster_slices) { hc = hclust(dist(t(meanmat))) hc = as.hclust(reorder(as.dendrogram(hc), weight, mean)) } else { hc = list(order = order(weight)) } cl2 = numeric(length(cl)) for(i in seq_along(hc$order)) { cl2[cl == hc$order[i]] = i } cl2 = factor(cl2, levels = seq_along(hc$order)) if(is.null(split)) { split = data.frame(cl2) } else if(is.matrix(split)) { split = as.data.frame(split) split = cbind(cl2, split) } else if(is.null(ncol(split))) { split = data.frame(cl2, split) } else { split = cbind(cl2, split) } if(verbose) qqcat("apply k-means (@{km} groups) on @{which}s, append to the `split` data frame\n") } order_list = list() if(is.null(split)) { order_list[[1]] = order } else { if(verbose) cat("process `split` data frame\n") if(is.null(ncol(split))) split = data.frame(split) if(is.matrix(split)) split = as.data.frame(split) for(i in seq_len(ncol(split))) { if(is.numeric(split[[i]])) { split[[i]] = factor(as.character(split[[i]]), levels = as.character(sort(unique(split[[i]])))) } else if(!is.factor(split[[i]])) { split[[i]] = factor(split[[i]]) } else { split[[i]] = factor(split[[i]], levels = intersect(levels(split[[i]]), unique(split[[i]]))) } } split_name = apply(as.matrix(split), 1, paste, collapse = ",") order2 = do.call("order", split) level = unique(split_name[order2]) for(k in seq_along(level)) { l = split_name == level[k] order_list[[k]] = intersect(order, which(l)) } names(order_list) = level } slice_od = seq_along(order_list) if(cluster) { if(verbose) qqcat("apply clustering on each slice (@{length(order_list)} slices)\n") dend_list = rep(list(NULL), length(order_list)) for(i in seq_along(order_list)) { if(which == "row") { submat = mat[ order_list[[i]], , drop = FALSE] } else { submat = mat[, order_list[[i]], drop = FALSE] } nd = 0 if(which == "row") nd = nrow(submat) else nd = ncol(submat) if(nd > 1) { if(!is.null(dend_param$fun)) { if(which == "row") { obj = dend_param$fun(submat) } else { obj = dend_param$fun(t(submat)) } if(inherits(obj, "dendrogram") || inherits(obj, "hclust")) { dend_list[[i]] = obj } else { oe = try(obj <- as.dendrogram(obj), silent = TRUE) if(inherits(oe, "try-error")) { stop_wrap("the clustering function must return a `dendrogram` object or a object that can be coerced to `dendrogram` class.") } dend_list[[i]] = obj } order_list[[i]] = order_list[[i]][ get_dend_order(dend_list[[i]]) ] } else { if(which == "row") { dend_list[[i]] = hclust(get_dist(submat, distance), method = method) } else { dend_list[[i]] = hclust(get_dist(t(submat), distance), method = method) } order_list[[i]] = order_list[[i]][ get_dend_order(dend_list[[i]]) ] } } else { dend_list[[i]] = structure(1, members = 1, height = 0, leaf = TRUE, class = "dendrogram") order_list[[i]] = order_list[[i]][1] } } names(dend_list) = names(order_list) for(i in seq_along(dend_list)) { if(inherits(dend_list[[i]], "hclust")) { dend_list[[i]] = as.dendrogram(dend_list[[i]]) } } if(identical(reorder, NULL)) { if(is.numeric(mat)) { reorder = TRUE } else { reorder = FALSE } } do_reorder = TRUE if(identical(reorder, NA) || identical(reorder, FALSE)) { do_reorder = FALSE } if(identical(reorder, TRUE)) { do_reorder = TRUE if(which == "row") { reorder = -rowMeans(mat, na.rm = TRUE) } else { reorder = -colMeans(mat, na.rm = TRUE) } } if(do_reorder) { if(which == "row") { if(length(reorder) != nrow(mat)) { stop_wrap("weight of reordering should have same length as number of rows\n") } } else { if(length(reorder) != ncol(mat)) { stop_wrap("weight of reordering should have same length as number of columns\n") } } for(i in seq_along(dend_list)) { if(length(order_list[[i]]) > 1) { sub_ind = sort(order_list[[i]]) dend_list[[i]] = reorder(dend_list[[i]], reorder[sub_ind], mean) order_list[[i]] = sub_ind[ order.dendrogram(dend_list[[i]]) ] } } if(verbose) qqcat("reorder dendrograms in each @{which} slice\n") } if(length(order_list) > 1 && cluster_slices) { if(which == "row") { slice_mean = sapply(order_list, function(ind) colMeans(mat[ind, , drop = FALSE], na.rm = TRUE)) } else { slice_mean = sapply(order_list, function(ind) rowMeans(mat[, ind, drop = FALSE], na.rm = TRUE)) } if(!is.matrix(slice_mean)) { slice_mean = matrix(slice_mean, nrow = 1) } dend_slice = as.dendrogram(hclust(dist(t(slice_mean)))) dend_slice = reorder(dend_slice, slice_mean, mean) if(verbose) qqcat("perform clustering on mean of @{which} slices\n") slice_od = order.dendrogram(dend_slice) order_list = order_list[slice_od] dend_list = dend_list[slice_od] } } dend_list = lapply(dend_list, adjust_dend_by_x) slot(object, paste0(which, "_order")) = unlist(order_list) slot(object, paste0(which, "_order_list")) = order_list slot(object, paste0(which, "_dend_list")) = dend_list slot(object, paste0(which, "_dend_param")) = dend_param slot(object, paste0(which, "_dend_slice")) = dend_slice object@matrix_param[[ paste0(which, "_split") ]] = split if(which == "row") { if(nrow(mat) != length(order)) { stop_wrap(qq("Number of rows in the matrix are not the same as the length of the cluster or the @{which} orders.")) } } else { if(ncol(mat) != length(order)) { stop_wrap(qq("Number of columns in the matrix are not the same as the length of the cluster or the @{which} orders.")) } } for(i in seq_along(names_param$gp)) { if(length(names_param$gp[[i]]) == length(order_list)) { gp_temp = NULL for(j in seq_along(order_list)) { gp_temp[ order_list[[j]] ] = names_param$gp[[i]][j] } names_param$gp[[i]] = gp_temp } } if(!is.null(names_param$anno)) { names_param$anno@var_env$gp = names_param$gp } slot(object, paste0(which, "_names_param")) = names_param n_slice = length(order_list) if(length(gap) == 1) { gap = rep(gap, n_slice) } else if(length(gap) == n_slice - 1) { gap = unit.c(gap, unit(0, "mm")) } else if(length(gap) != n_slice) { stop_wrap(qq("Length of `gap` should be 1 or number of @{which} slices.")) } object@matrix_param[[ paste0(which, "_gap") ]] = gap title = slot(object, paste0(which, "_title")) if(!is.null(split)) { if(length(title) == 0 && !is.null(title)) { title = names(order_list) } else if(length(title) == 1) { if(grepl("%s", title)) { title = apply(unique(split[order2, , drop = FALSE]), 1, function(x) { lt = lapply(x, function(x) x) lt$fmt = title do.call(sprintf, lt) })[slice_od] } else if(grepl("@\\{.+\\}", title)) { title = apply(unique(split[order2, , drop = FALSE]), 1, function(x) { x = x envir = environment() title = get("title") op = parent.env(envir) calling_env = object@heatmap_param$calling_env parent.env(envir) = calling_env title = GetoptLong::qq(title, envir = envir) parent.env(envir) = op return(title) })[slice_od] } else if(grepl("\\{.+\\}", title)) { if(!requireNamespace("glue")) { stop_wrap("You need to install glue package.") } title = apply(unique(split[order2, , drop = FALSE]), 1, function(x) { x = x envir = environment() title = get("title") op = parent.env(envir) calling_env = object@heatmap_param$calling_env parent.env(envir) = calling_env title = glue::glue(title, envir = calling_env) parent.env(envir) = op return(title) })[slice_od] } } } slot(object, paste0(which, "_title")) = title return(object) } setMethod(f = "draw", signature = "Heatmap", definition = function(object, internal = FALSE, test = FALSE, ...) { if(test) { object = prepare(object) grid.newpage() if(is_abs_unit(object@heatmap_param$width)) { width = object@heatmap_param$width } else { width = 0.8 } if(is_abs_unit(object@heatmap_param$height)) { height = object@heatmap_param$height } else { height = 0.8 } pushViewport(viewport(width = width, height = height)) draw(object, internal = TRUE) upViewport() } else { if(internal) { if(nrow(object@layout$layout_index) == 0) return(invisible(NULL)) layout = grid.layout(nrow = length(HEATMAP_LAYOUT_COLUMN_COMPONENT), ncol = length(HEATMAP_LAYOUT_ROW_COMPONENT), widths = component_width(object), heights = component_height(object)) pushViewport(viewport(layout = layout)) ht_layout_index = object@layout$layout_index ht_graphic_fun_list = object@layout$graphic_fun_list for(j in seq_len(nrow(ht_layout_index))) { if(HEATMAP_LAYOUT_COLUMN_COMPONENT["heatmap_body"] %in% ht_layout_index[j, 1] && HEATMAP_LAYOUT_ROW_COMPONENT["heatmap_body"] %in% ht_layout_index[j, 2]) { pushViewport(viewport(layout.pos.row = ht_layout_index[j, 1], layout.pos.col = ht_layout_index[j, 2], name = paste(object@name, "heatmap_body_wrap", sep = "_"))) } else { pushViewport(viewport(layout.pos.row = ht_layout_index[j, 1], layout.pos.col = ht_layout_index[j, 2])) } ht_graphic_fun_list[[j]](object) upViewport() } upViewport() } else { ht_list = new("HeatmapList") ht_list = add_heatmap(ht_list, object) draw(ht_list, ...) } } }) setMethod(f = "prepare", signature = "Heatmap", definition = function(object, process_rows = TRUE, process_columns = TRUE) { if(object@layout$initialized) { return(object) } if(process_rows) { object = make_row_cluster(object) } if(process_columns) { object = make_column_cluster(object) } object = make_layout(object) return(object) })
d3ClusterDendro <- function(List, height = 2200, width = 900, heightCollapse = 0, widthCollapse = 0.5, fontsize = 10, linkColour = " nodeColour = " diameter = 980, zoom = FALSE, parentElement = "body", standAlone = TRUE, file = NULL, iframe = FALSE, d3Script = "http://d3js.org/d3.v3.min.js") { if (!isTRUE(standAlone) & isTRUE(iframe)){ stop("If iframe = TRUE then standAlone must be TRUE.") } if (is.null(file) & isTRUE(iframe)){ Random <- paste0(sample(c(0:9, letters, LETTERS), 5, replace=TRUE), collapse = "") file <- paste0("NetworkGraph", Random, ".html") } FrameHeight <- height + height * 0.07 FrameWidth <- width + width * 0.03 fontsizeBig <- fontsize * 1.9 linkOpacity <- opacity * 0.5 if (class(List) != "list"){ stop("List must be a list class object.") } RootList <- toJSON(List) RootList <- paste("var root =", RootList, "; \n") PageHead <- BasicHead() NetworkCSS <- whisker.render(TreeStyleSheet()) if (!isTRUE(zoom)){ MainScript1 <- whisker.render(MainClusterDendro1()) MainScript2 <- whisker.render(MainClusterDendro2()) } else if (isTRUE(zoom)){ MainScript1 <- whisker.render(ZoomClusterDendro1()) MainScript2 <- whisker.render(ZoomClusterDendro2()) } if (is.null(file) & !isTRUE(standAlone)){ cat(NetworkCSS, MainScript1, RootList, MainScript2) } else if (is.null(file) & isTRUE(standAlone)){ cat(PageHead, NetworkCSS, MainScript1, RootList, MainScript2, "</body>") } else if (!is.null(file) & !isTRUE(standAlone)){ cat(NetworkCSS, MainScript1, RootList, MainScript2, file = file) } else if (!is.null(file) & !isTRUE(iframe)){ cat(PageHead, NetworkCSS, MainScript1, RootList, MainScript2, "</body>", file = file) } else if (!is.null(file) & isTRUE(iframe)){ cat(PageHead, NetworkCSS, MainScript1, RootList, MainScript2, "</body>", file = file) cat("<iframe src=\'", file, "\'", " height=", FrameHeight, " width=", FrameWidth, "></iframe>", sep="") } }
generate_double_sum_function <- function(dimensions) soo_function(name="Double sum", id=sprintf("double-sum-%id", dimensions), fun=function(x, ...) .Call(do_f_double_sum, x), dimensions=dimensions, lower_bounds=rep(-65.536, dimensions), upper_bounds=rep(65.536, dimensions), best_par=rep(0, dimensions), best_value=0) class(generate_double_sum_function) <- c("soo_function_generator", "function") attr(generate_double_sum_function, "id") <- "double-sum" attr(generate_double_sum_function, "name") <- "Double sum test function"
new_ml_model_multilayer_perceptron_classification <- function(pipeline_model, formula, dataset, label_col, features_col, predicted_label_col) { new_ml_model_classification( pipeline_model, formula, dataset = dataset, label_col = label_col, features_col = features_col, predicted_label_col = predicted_label_col, class = "ml_model_multilayer_perceptron_classification" ) }
work.calgamma <- function(dmat,dvec,tmat,tvec,fout) { vfs0 <- get(paste('v',fout$smodel,sep='')) vf0t <- get(paste('v',fout$tmodel,sep='')) Gd0 <- with(fout,as.vector(vfs0(dmat,scoef[1],scoef[2],scoef[3]))) G0t <- with(fout,as.vector(vf0t(tmat,tcoef[1],tcoef[2],tcoef[3]))) tmp <- fout$k fitGamma <- Gd0 + G0t - tmp * Gd0 * G0t chk <- with(fout,(scoef[3]==0) & (tcoef[3]==0)) if(chk){ fitGamma <- fitGamma + 1e-5 } gd0 <- with(fout,as.vector(vfs0(dvec,scoef[1],scoef[2],scoef[3]))) g0t <- with(fout,as.vector(vf0t(tvec,tcoef[1],tcoef[2],tcoef[3]))) fitgamma <- gd0 + g0t - fout$k * gd0 * g0t list(Gamma = fitGamma, gamma = fitgamma) }
saveWidget <- function(widget, file, selfcontained = TRUE, libdir = NULL, background = "white", title = class(widget)[[1]], knitrOptions = list()) { if (grepl("^ bgcol <- grDevices::col2rgb(background, alpha = TRUE) background <- sprintf("rgba(%d,%d,%d,%f)", bgcol[1,1], bgcol[2,1], bgcol[3,1], bgcol[4,1]/255) } html <- toHTML(widget, standalone = TRUE, knitrOptions = knitrOptions) if (is.null(libdir)){ libdir <- paste(tools::file_path_sans_ext(basename(file)), "_files", sep = "") } if (selfcontained) { pandoc_save_markdown(html, file = file, libdir = libdir, background = background, title = title) if (!pandoc_available()) { stop("Saving a widget with selfcontained = TRUE requires pandoc. For details see:\n", "https://github.com/rstudio/rmarkdown/blob/master/PANDOC.md") } pandoc_self_contained_html(file, file) unlink(libdir, recursive = TRUE) } else { html <- tagList(tags$head(tags$title(title)), html) htmltools::save_html(html, file = file, libdir = libdir, background = background) } invisible(NULL) }
DistAlleleShare <- function(e) { N <- nrow(e) P <- mat.or.vec(N,2*N+1) P[1,1] <- e[1,1] P[1,2] <- e[1,2] P[1,3] <- e[1,3] for (r in 2:N) { P[r,1] <- P[r-1,1]*e[r,1] P[r,2] <- P[r-1,1]*e[r,2]+P[r-1,2]*e[r,1] m <- 2*r-1 for (k in 3:m) { P[r,k] <- P[r-1,k-2]*e[r,3]+P[r-1,k-1]*e[r,2]+P[r-1,k]*e[r,1] } P[r,2*r] <-P[r-1,2*r-2]*e[r,3]+P[r-1,2*r-1]*e[r,2] P[r,2*r+1] <- P[r-1,2*r-1]*e[r,3] } colnames(P)<-0:(ncol(P)-1) return(data.frame("X"=c(0:(2*N)),"Density"=P[N,])) }
fertilizers <- function() { f <- system.file("extdata/fertilizers.csv", package="Rquefts") utils::read.csv(f) } nutrientRates <- function(supply, treatment) { NPK <- supply[, c("N", "P", "K")] * treatment / 100 apply(NPK, 2, sum) } fertApp <- function(nutrients, fertilizers, price, exact=TRUE, retCost=FALSE){ stopifnot(length(price) == nrow(fertilizers)) name <- fertilizers$name supply <- t(as.matrix(fertilizers[,-1,drop=FALSE])) treatment <- as.matrix(nutrients) result <- matrix(nrow=ncol(supply), ncol=nrow(treatment)) colnames(result) <- rownames(nutrients) if (!any(is.na(price))) { treatment <- treatment * 100 for (i in 1:nrow(treatment)) { if (exact) { solution <- limSolve::linp(E=supply, F=treatment[i,], Cost=price) } else { solution <- limSolve::linp(G=supply, H=treatment[i,], Cost=price) } if (solution$IsError) { result[,i] <- NA } else { result[,i] <- solution$X } } } if (retCost) { r <- colSums(result * price) } else { r <- data.frame(name, result) } r }
orthodrom.dist<-function(x1, y1, x2, y2){ dist <- distMeeus(cbind(x1, y1), cbind(x2, y2))/1000 return(dist) }
geom_textsmooth <- function(mapping = NULL, data = NULL, stat = "smooth", position = "identity", ..., method = NULL, formula = NULL, na.rm = FALSE, method.args = list(), orientation = NA, show.legend = NA, inherit.aes = TRUE) { params <- set_params( na.rm = na.rm, orientation = orientation, method.args = method.args, ... ) if (identical(stat, "smooth")) { params$method <- method params$formula <- formula } layer( data = data, mapping = mapping, stat = stat, geom = GeomTextpath, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = params ) } geom_labelsmooth <- function(mapping = NULL, data = NULL, stat = "smooth", position = "identity", method = NULL, formula = NULL, na.rm = FALSE, method.args = list(), orientation = NA, show.legend = NA, inherit.aes = TRUE, ...) { params <- set_params( na.rm = na.rm, orientation = orientation, method.args = method.args, ... ) if (identical(stat, "smooth")) { params$method <- method params$formula <- formula } layer( geom = GeomLabelpath, mapping = mapping, data = data, stat = stat, position = position, show.legend = show.legend, inherit.aes = inherit.aes, params = params ) }
cat_plot <- function(model, pred, modx = NULL, mod2 = NULL, data = NULL, geom = c("point", "line", "bar"), pred.values = NULL, modx.values = NULL, mod2.values = NULL, interval = TRUE, plot.points = FALSE, point.shape = FALSE, vary.lty = FALSE, centered = "all", int.type = c("confidence", "prediction"), int.width = .95, line.thickness = 1.1, point.size = 1.5, pred.point.size = 3.5, jitter = 0.1, geom.alpha = NULL, dodge.width = NULL, errorbar.width = NULL, interval.geom = c("errorbar", "linerange"), outcome.scale = "response", robust = FALSE, cluster = NULL, vcov = NULL, pred.labels = NULL, modx.labels = NULL, mod2.labels = NULL, set.offset = 1, x.label = NULL, y.label = NULL, main.title = NULL, legend.main = NULL, colors = "CUD Bright", partial.residuals = FALSE, point.alpha = 0.6, color.class = NULL, at = NULL, ...) { dots <- list(...) if (length(dots) > 0) { if ("predvals" %in% names(dots)) { pred.values <- dots$predvals } if ("modxvals" %in% names(dots)) { modx.values <- dots$modxvals } if ("mod2vals" %in% names(dots)) { mod2.values <- dots$mod2vals } } if (!is.null(color.class)) { colors <- color.class msg_wrap("The color.class argument is deprecated. Please use 'colors' instead.") } pred <- quo_name(enexpr(pred)) modx <- quo_name(enexpr(modx)) if (modx == "NULL") {modx <- NULL} mod2 <- quo_name(enexpr(mod2)) if (mod2 == "NULL") {mod2 <- NULL} if (any(c(pred, modx, mod2) %in% centered)) { warn_wrap("You cannot mean-center the focal predictor or moderators with this function.") centered <- centered %not% c(pred, modx, mod2) if (length(centered) == 0) {centered <- "none"} } geom <- geom[1] if (geom == "dot") {geom <- "point"} modxvals2 <- mod2vals2 <- resp <- NULL if (is.null(data)) { d <- get_data(model, warn = TRUE) } else { d <- data } weights <- get_weights(model, d)$weights_name if (is.null(modx.labels) & !is.null(names(modx.values))) { modx.labels <- names(modx.values) } if (is.null(mod2.labels) & !is.null(names(mod2.values))) { mod2.labels <- names(mod2.values) } pred_out <- prep_data(model = model, pred = pred, modx = modx, pred.values = pred.values, modx.values = modx.values, mod2 = mod2, mod2.values = mod2.values, centered = centered, interval = interval, int.type = int.type, int.width = int.width, outcome.scale = outcome.scale, linearity.check = FALSE, robust = robust, cluster = cluster, vcov = vcov, set.offset = set.offset, pred.labels = pred.labels, modx.labels = modx.labels, mod2.labels = mod2.labels, facet.modx = FALSE, d = d, survey = "svyglm" %in% class(model), weights = weights, preds.per.level = 100, partial.residuals = partial.residuals, at = at, ...) meta <- attributes(pred_out) lapply(names(meta), function(x, env) {env[[x]] <- meta[[x]]}, env = environment()) pm <- pred_out$predicted d <- pred_out$original plot_cat(predictions = pm, pred = pred, modx = modx, mod2 = mod2, data = d, geom = geom, pred.values = pred.values, modx.values = modx.values, mod2.values = mod2.values, interval = interval, plot.points = plot.points | partial.residuals, point.shape = point.shape, vary.lty = vary.lty, pred.labels = pred.labels, modx.labels = modx.labels, mod2.labels = mod2.labels, x.label = x.label, y.label = y.label, main.title = main.title, legend.main = legend.main, colors = colors, weights = weights, resp = resp, geom.alpha = geom.alpha, dodge.width = dodge.width, errorbar.width = errorbar.width, interval.geom = interval.geom, point.size = point.size, line.thickness = line.thickness, pred.point.size = pred.point.size, jitter = jitter, point.alpha = point.alpha) } plot_cat <- function(predictions, pred, modx = NULL, mod2 = NULL, data = NULL, geom = c("point", "line", "bar", "boxplot"), pred.values = NULL, modx.values = NULL, mod2.values = NULL, interval = TRUE, plot.points = FALSE, point.shape = FALSE, vary.lty = FALSE, pred.labels = NULL, modx.labels = NULL, mod2.labels = NULL, x.label = NULL, y.label = NULL, main.title = NULL, legend.main = NULL, colors = "CUD Bright", weights = NULL, resp = NULL, jitter = 0.1, geom.alpha = NULL, dodge.width = NULL, errorbar.width = NULL, interval.geom = c("errorbar", "linerange"), line.thickness = 1.1, point.size = 1, pred.point.size = 3.5, point.alpha = 0.6) { pm <- predictions d <- data geom <- geom[1] if (geom == "dot") {geom <- "point"} if (geom %in% c("boxplot", "box")) { stop_wrap("The boxplot geom is no longer supported.") } if (length(jitter) == 1) {jitter <- rep(jitter, 2)} if (is.null(legend.main)) { legend.main <- modx } if (is.null(x.label)) { x.label <- pred } if (is.null(y.label)) { y.label <- resp } if (is.numeric(pm[[pred]])) { pred.levels <- if (!is.null(pred.values)) {pred.values} else { unique(pm[[pred]]) } pred.labels <- if (!is.null(pred.labels)) {pred.labels} else { unique(pm[[pred]]) } pm[[pred]] <- factor(pm[[pred]], levels = pred.levels, labels = pred.labels) d <- d[d[[pred]] %in% pred.levels,] d[[pred]] <- factor(d[[pred]], levels = pred.levels, labels = pred.labels) } if (!is.null(modx)) { gradient <- is.numeric(d[[modx]]) & !vary.lty } else {gradient <- FALSE} pred <- sym(pred) resp <- sym(resp) if (!is.null(modx)) {modx <- sym(modx)} if (!is.null(mod2)) {mod2 <- sym(mod2)} if (!is.null(weights)) {weights <- sym(weights)} colors <- suppressWarnings(get_colors(colors, length(modx.labels), gradient = gradient)) types <- c("solid", "4242", "2222", "dotdash", "dotted", "twodash", "12223242", "F282", "F4448444", "224282F2", "F1") ltypes <- types[seq_along(modx.labels)] names(ltypes) <- modx.labels names(colors) <- modx.labels if (is.null(geom.alpha)) { a_level <- 1 if (plot.points == TRUE) { if (!is.null(modx)) { a_level <- 0 } else { a_level <- 0.5 } } else if (interval == TRUE) { a_level <- 0.5 } } else {a_level <- geom.alpha} if (is.null(dodge.width)) { dodge.width <- if (geom %in% c("bar", "point")) {0.9} else {0} } if (is.null(errorbar.width)) { errorbar.width <- if (geom == "point") { 0.9 } else if (geom == "bar") { 0.75 } else {0.5} } shape <- if (point.shape == TRUE) {modx} else {NULL} lty <- if (vary.lty == TRUE) {modx} else {NULL} grp <- if (!is.null(modx)) modx else 1 p <- ggplot(pm, aes(x = !! pred, y = !! resp, group = !! grp, colour = !! modx, fill = !! modx, shape = !! shape, linetype = !! lty)) if (geom == "bar") { p <- p + geom_bar(stat = "identity", position = "dodge", alpha = a_level) } else if (geom %in% c("point", "line")) { p <- p + geom_point(size = pred.point.size, position = position_dodge(dodge.width)) } if (geom == "line") { p <- p + geom_path(position = position_dodge(dodge.width), size = line.thickness) } if (interval == TRUE & interval.geom[1] == "errorbar") { p <- p + geom_errorbar(aes(ymin = !! sym("ymin"), ymax = !! sym("ymax")), alpha = 1, show.legend = FALSE, position = position_dodge(dodge.width), width = errorbar.width, size = line.thickness) } else if (interval == TRUE & interval.geom[1] %in% c("line", "linerange")) { p <- p + geom_linerange(aes(ymin = !! sym("ymin"), ymax = !! sym("ymax")), alpha = 0.8, show.legend = FALSE, position = position_dodge(dodge.width), size = line.thickness) } if (!is.null(mod2)) { facets <- facet_grid(paste(". ~", as_string(mod2))) p <- p + facets } if (plot.points == TRUE) { constants <- list(alpha = point.alpha) if (is.null(weights)) { constants$size <- point.size } p <- p + layer(geom = "point", data = d, stat = "identity", inherit.aes = TRUE, show.legend = FALSE, mapping = aes(x = !! pred, y = !! resp, size = !! weights, group = !! grp, colour = !! modx, shape = !! shape), position = if (!is.null(modx)) { position_jitterdodge(dodge.width = dodge.width, jitter.width = jitter[1], jitter.height = jitter[2]) } else { position_jitter(width = jitter[1], height = jitter[2]) }, params = constants) + scale_size(range = c(1 * point.size, 5 * point.size), guide = "none") } if (is.null(mod2)) { p <- p + theme_nice(legend.pos = "right") } else { p <- p + theme_nice(legend.pos = "bottom") } p <- p + labs(x = x.label, y = y.label) p <- p + scale_colour_manual(name = legend.main, values = colors, breaks = names(colors)) + scale_fill_manual(name = legend.main, values = colors, breaks = names(colors)) + scale_shape(name = legend.main) + scale_x_discrete(limits = pred.values, labels = pred.labels) if (vary.lty == TRUE) { p <- p + scale_linetype_manual(name = legend.main, values = ltypes, breaks = names(ltypes), na.value = "blank") p <- p + theme(legend.key.width = grid::unit(3, "lines")) } if (!is.null(main.title)) { p <- p + ggtitle(main.title) } return(p) }
test_that("make_operation", { operation <- list( name = "Operation", http = list( method = "POST", requestUri = "/abc" ), input = list( shape = "InputShape" ), output = list( shape = "OutputShape" ), documentation = "Foo." ) api <- list( metadata = list( serviceAbbreviation = "api" ), shapes = list( InputShape = list( required = list(), members = list( Input1 = list(shape = "Input1"), Input2 = list(shape = "Input2"), Input3 = list(shape = "Input3") ), type = "structure" ), Input1 = list(type = "string"), Input2 = list(type = "string"), Input3 = list(type = "integer"), OutputShape = list( required = list(), members = list( Output1 = list(shape = "Output1"), Output2 = list(shape = "Output2"), Output3 = list(shape = "Output3") ), type = "structure" ), Output1 = list(type = "string"), Output2 = list(type = "string"), Output3 = list(type = "integer") ) ) a <- make_operation(operation, api) a <- gsub(" +\n", "\n", a) e <- gsub("\n {4}", "\n", " api_operation <- function(Input1 = NULL, Input2 = NULL, Input3 = NULL) { op <- new_operation( name = \"Operation\", http_method = \"POST\", http_path = \"/abc\", paginator = list() ) input <- .api$operation_input(Input1 = Input1, Input2 = Input2, Input3 = Input3) output <- .api$operation_output() config <- get_config() svc <- .api$service(config) request <- new_request(svc, op, input, output) response <- send_request(request) return(response) } .api$operations$operation <- api_operation") actual <- formatR::tidy_source(text = a, output = FALSE) expected <- formatR::tidy_source(text = e, output = FALSE) expect_equal(actual, expected) })
Rsymphony_solve_LP <- function(obj, mat, dir, rhs, bounds = NULL, types = NULL, max = FALSE, verbosity = -2, time_limit = -1, node_limit = -1, gap_limit = -1, first_feasible = FALSE, write_lp = FALSE, write_mps = FALSE) { if(!identical(max, TRUE) && !identical(max, FALSE)) stop("'Argument 'max' must be either TRUE or FALSE.") if(missing(mat) || is.null(mat)) mat <- matrix(0, 0L, length(obj)) if(missing(dir) || is.null(dir)) dir <- character() if(missing(rhs) || is.null(rhs)) rhs <- numeric() if((length(dim(mat)) != 2L) && is.numeric(mat)) mat <- matrix(c(mat), nrow = 1L) nr <- nrow(mat) nc <- ncol(mat) if(length(obj) != nc) stop("Arguments 'obj' and 'mat' are not conformable.") if(length(dir) != nr) stop("Arguments 'mat' and 'dir' are not conformable.") if(length(rhs) != nr) stop("Arguments 'mat' and 'rhs' are not conformable.") TABLE <- c("L", "E", "G") names(TABLE) <- c("<=", "==", ">=") row_sense <- TABLE[dir] if(any(is.na(row_sense))) stop("Argument 'dir' must be one of '<=', '==' or '>='.") bounds <- glp_bounds(as.list(bounds), nc) col_lb <- replace(bounds[, 2L], bounds[, 2L] == -Inf, -.Machine$double.xmax) col_ub <- replace(bounds[, 3L], bounds[, 3L] == Inf, .Machine$double.xmax) int <- if(is.null(types)) logical(nc) else { if(!is.character(types) || !all(types %in% c("C", "I", "B"))) stop("Invalid 'types' argument.") types <- rep(types, length.out = nc) col_ub[types == "B" & (col_ub > 1)] <- 1 types != "C" } mat <- make_csc_matrix(mat) need_dummy <- (length(mat$values) == 0L) if(need_dummy) { obj <- c(obj, 0) mat <- make_csc_matrix(rbind(c(double(nc), 1))) row_sense <- "E" rhs <- 0 types <- c(types, "C") int <- c(int, FALSE) col_lb <- c(col_lb, 0) col_ub <- c(col_ub, 0) nr <- 1L nc <- length(obj) } out <- .C(R_symphony_solve, as.integer(nc), as.integer(nr), as.integer(mat$matbeg), as.integer(mat$matind), as.double(mat$values), as.double(col_lb), as.double(col_ub), as.integer(int), if(max) as.double(-obj) else as.double(obj), obj2 = double(nc), as.character(paste(row_sense, collapse = "")), as.double(rhs), double(nr), objval = double(1L), solution = double(nc), status = integer(1L), verbosity = as.integer(verbosity), time_limit = as.integer(time_limit), node_limit = as.integer(node_limit), gap_limit = as.double(gap_limit), first_feasible = as.integer(first_feasible), write_lp = as.integer(write_lp), write_mps = as.integer(write_mps)) solution <- out$solution solution[int] <- round(solution[int]) if(need_dummy) { solution <- solution[-nc] obj <- obj[-nc] } status_db <- c("TM_NO_PROBLEM" = 225L, "TM_NO_SOLUTION" = 226L, "TM_OPTIMAL_SOLUTION_FOUND" = 227L, "TM_TIME_LIMIT_EXCEEDED" = 228L, "TM_NODE_LIMIT_EXCEEDED" = 229L, "TM_ITERATION_LIMIT_EXCEEDED" = 230L, "TM_TARGET_GAP_ACHIEVED" = 231L, "TM_FOUND_FIRST_FEASIBLE" = 232L, "TM_FINISHED" = 233L, "TM_UNFINISHED" = 234L, "TM_FEASIBLE_SOLUTION_FOUND" = 235L, "TM_SIGNAL_CAUGHT" = 236L, "TM_UNBOUNDED" = 237L, "PREP_OPTIMAL_SOLUTION_FOUND" = 238L, "PREP_NO_SOLUTION" = 239L, "TM_ERROR__NO_BRANCHING_CANDIDATE" = -250L, "TM_ERROR__ILLEGAL_RETURN_CODE" = -251L, "TM_ERROR__NUMERICAL_INSTABILITY" = -252L, "TM_ERROR__COMM_ERROR" = -253L, "TM_ERROR__USER" = -275L, "PREP_ERROR" = -276L) status <- if(out$status == 227L) c("TM_OPTIMAL_SOLUTION_FOUND" = 0L) else status_db[match(out$status, status_db)] list(solution = solution, objval = sum(obj * solution), status = status) }
library(cometr) library(tidyr) library(ggplot2) library(keras) library(reticulate) exp <- create_experiment( keep_active = TRUE, log_output = TRUE, log_error = FALSE, log_code = TRUE, log_system_details = TRUE, log_git_info = TRUE ) exp$add_tags(c("made with keras")) fashion_mnist <- dataset_fashion_mnist() c(train_images, train_labels) %<-% fashion_mnist$train c(test_images, test_labels) %<-% fashion_mnist$test train_images <- train_images / 255 test_images <- test_images / 255 model <- keras_model_sequential() model %>% layer_flatten(input_shape = c(28, 28)) %>% layer_dense(units = 128, activation = 'relu') %>% layer_dense(units = 10, activation = 'softmax') model %>% compile( optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = c('accuracy') ) epochs <- 5 exp$log_parameter("epochs", epochs) LogMetrics <- R6::R6Class("LogMetrics", inherit = KerasCallback, public = list( losses = NULL, on_epoch_end = function(epoch, logs = list()) { self$losses <- c(self$losses, c(epoch, logs[["loss"]])) } ) ) callback <- LogMetrics$new() model %>% fit(train_images, train_labels, epochs = epochs, verbose = 2, callbacks = list(callback)) losses <- matrix(callback$losses, nrow = 2) for (i in 1:ncol(losses)) { exp$log_metric("loss", losses[2, i], step=losses[1, i]) } score <- model %>% evaluate(test_images, test_labels, verbose = 0) cat('Test loss:', score$loss, "\n") cat('Test accuracy:', score$acc, "\n") exp$log_metric("test_loss", score$loss) exp$log_metric("test_accuracy", score$acc) predictions <- model %>% predict(test_images) class_names = c('T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot') png(file = "FashionMNISTResults.png") par(mfcol=c(5,5)) par(mar=c(0, 0, 1.5, 0), xaxs='i', yaxs='i') for (i in 1:25) { img <- test_images[i, , ] img <- t(apply(img, 2, rev)) predicted_label <- which.max(predictions[i, ]) - 1 true_label <- test_labels[i] if (predicted_label == true_label) { color <- ' } else { color <- ' } image(1:28, 1:28, img, col = gray((0:255)/255), xaxt = 'n', yaxt = 'n', main = paste0(class_names[predicted_label + 1], " (", class_names[true_label + 1], ")"), col.main = color) } dev.off() exp$upload_asset("FashionMNISTResults.png") exp$log_other(key = "Created by", value = "cometr") exp$print() exp$stop()
TransformIni <- function(X, InitTransform="None", transform = "Standardize columns") { n = nrow(X) p = ncol(X) RowNames = rownames(X) ColNames = colnames(X) InitTransforms=c("None", "Log", "Logit") if (is.numeric(InitTransform)) InitTransform = InitTransforms[InitTransform] ContinuousDataTransform = c("Raw Data", "Substract the global mean", "Double centering", "Column centering", "Standardize columns", "Row centering", "Standardize rows", "Divide by the column means and center", "Normalized residuals from independence") if (is.numeric(transform)) transform = ContinuousDataTransform[transform] switch(InitTransform, `Log` = { if (sum(which(X<=0)) >0) stop("Initial log transformation is not compatible with negative or zero values") X = log(X) },`Logit` = { if (sum(which(X<=0)) >0) stop("Initial logit transformation is not compatible with negative values") X= X + 0.01 * (X==0) - 0.01 * (X==1) x=log(X/(1-X)) }) switch(transform, `Substract the global mean` = { gmean = mean(X) X = X - gmean }, `Double centering` = { X = (diag(n) - matrix(1, n, n)/n) %*% X %*% (diag(p) - matrix(1, p, p)/p) }, `Column centering` = { means = apply(X, 2, mean) X=X- matrix(1,n,1) %*% matrix(means,1,p) }, `Standardize columns` = { means = apply(X, 2, mean) stdDevs = apply(X, 2, sd) X=(X- matrix(1,n,1) %*% matrix(means,1,p))/(matrix(1,n,1) %*% matrix(stdDevs,1,p)) }, `Row centering` = { means = apply(X, 1, mean) X = X %*% (diag(p) - matrix(1, p, p)/p) }, `Standardize rows` = { means = apply(X, 1, mean) stdDevs = apply(X, 1, sd) X = solve(diag(stdDevs)) %*% X %*% (diag(p) - matrix(1, p, p)/p) }, `Divide by the column means and center` = { means = apply(X, 2, mean) for (i in (1:p)) X[, i] = X[, i]/means[i] X = (diag(n) - matrix(1, n, n)/n) %*% X }, `Normalized residuals from independence` = { nt = sum(sum(X)) dr = apply(X,1,sum) dc = apply(X,2,sum) esp = (t(t(dr)) %*% dc)/nt var = t(t(1 - dr/nt)) %*% (1 - dc/nt) X = ((X - esp)/sqrt(esp))/sqrt(var) },`Divide by the range`={ Rangos=apply(X,2,max)-apply(X,2,min) X=X%*%diag(1/Rangos) }) rownames(X) = RowNames colnames(X) = ColNames return(X) }
Glue <- function(...) abind(..., rev.along=0) collectSummaries <- function(listOfSummaries){ summaries <- list() summaries[['coefC']] <- do.call(rbind, lapply(listOfSummaries, '[[', 'coefC')) rownames(summaries[['coefC']]) <- names(listOfSummaries) summaries[['vcovC']] <- do.call(Glue, lapply(listOfSummaries, '[[', 'vcovC')) summaries[['df.resid']] <- do.call(rbind, lapply(listOfSummaries, '[[', 'df.resid')) summaries[['df.null']] <- do.call(rbind, lapply(listOfSummaries, '[[', 'df.null')) summaries[['deviance']] <- do.call(rbind, lapply(listOfSummaries, '[[', 'deviance')) summaries[['dispersion']] <- do.call(rbind, lapply(listOfSummaries, '[[', 'dispersion')) summaries[['dispersionNoshrink']] <- do.call(rbind, lapply(listOfSummaries, '[[', 'dispersionNoshrink')) summaries[['converged']] <- do.call(rbind, lapply(listOfSummaries, '[[', 'converged')) summaries[['loglik']] <- do.call(rbind, lapply(listOfSummaries, '[[', 'loglik')) summaries[['coefD']] <- do.call(rbind, lapply(listOfSummaries, '[[', 'coefD')) summaries[['vcovD']] <- do.call(Glue, lapply(listOfSummaries, '[[', 'vcovD')) rownames(summaries[['coefD']]) <- names(listOfSummaries) summaries } .lrtZlmFit <- function(zlmfit, newMM, hString, ...){ o1 <- zlmfit LMlike <- o1@LMlike model.matrix(LMlike) <- newMM message('Refitting on reduced model...') if('exprs_values' %in% slotNames(zlmfit)) { o0 <- zlm(sca=o1@sca, LMlike=LMlike, exprs_values = o1@exprs_values, ...) } else{ o0 <- zlm(sca=o1@sca, LMlike=LMlike, ...) } lambda <- -2*(o0@loglik-o1@loglik) testable <- o0@converged & o1@converged testable[,'C'] <- testable[,'C'] & ([email protected] > 1 & [email protected] > 1)[,'C'] lambda <- ifelse(testable, lambda, 0) df <- [email protected]@df.resid df <- ifelse(testable, df, 0) cst <- makeChiSqTable(as.data.frame(lambda), as.data.frame(df), hString) dimnames(cst) <- list(primerid=mcols(zlmfit@sca)$primerid, test.type=dimnames(cst)[[2]], metric=dimnames(cst)[[3]]) cst } setMethod('lrTest', signature=c(object='ZlmFit', hypothesis='character'), function(object, hypothesis, ...){ o1 <- object LMlike <- o1@LMlike oldMM <- model.matrix(LMlike) newF <- update.formula(LMlike@formula, formula(sprintf(' ~. - %s', hypothesis))) LMlike <- update(LMlike, newF) newMM <- model.matrix(LMlike) newq <- qr.Q(qr(newMM)) diff <- any(abs(newq %*% crossprod(newq, oldMM) - oldMM)>1e-6) if(!diff) stop('Removing term ', sQuote(hypothesis), " doesn't actually alter the model, maybe due to marginality? Try specifying individual coefficents as a `CoefficientHypothesis`.") .lrtZlmFit(o1, LMlike@modelMatrix, hypothesis, ...) }) setMethod('lrTest', signature=c(object='ZlmFit', hypothesis='CoefficientHypothesis'), function(object, hypothesis, ...){ h <- generateHypothesis(hypothesis, colnames(object@coefD)) testIdx <- h@index newMM <- model.matrix(object@LMlike)[,-testIdx, drop=FALSE] .lrtZlmFit(object, newMM, [email protected], ...) }) setMethod('lrTest', signature=c(object='ZlmFit', hypothesis='Hypothesis'), function(object, hypothesis, ...){ h <- generateHypothesis(hypothesis, colnames(object@coefD)) lrTest(object, h@contrastMatrix, ...) }) setMethod('lrTest', signature=c(object='ZlmFit', hypothesis='matrix'), function(object, hypothesis, ...){ LMlike <- object@LMlike MM <- .rotateMM(LMlike, hypothesis) testIdx <- attr(MM, 'testIdx') .lrtZlmFit(object, MM[,-testIdx, drop=FALSE], 'Contrast Matrix', ...) }) setMethod('waldTest', signature=c(object='ZlmFit', hypothesis='matrix'), function(object, hypothesis){ coefC <- coef(object, 'C') coefD <- coef(object, 'D') vcovC <- vcov(object, 'C') vcovD <- vcov(object, 'D') converged <- object@converged genes <- rownames(coefC) tests <- aaply(seq_along(genes), 1, function(i){ .waldTest(coefC[i,], coefD[i,], vcovC[,,i], vcovD[,,i], hypothesis, converged[i,]) }, .drop=FALSE) dimnames(tests)[[1]] <- genes names(dimnames(tests)) <- c('primerid', 'test.type', 'metric') tests }) setMethod('waldTest', signature=c(object='ZlmFit', hypothesis='CoefficientHypothesis'), function(object, hypothesis){ h <- generateHypothesis(hypothesis, colnames(object@coefD)) waldTest(object, h@contrastMatrix) }) setMethod('waldTest', signature=c(object='ZlmFit', hypothesis='Hypothesis'), function(object, hypothesis){ h <- generateHypothesis(hypothesis, colnames(object@coefD)) waldTest(object, h@contrastMatrix) }) setMethod('show', signature=c(object='ZlmFit'), function(object){ cat('Fitted zlm on', nrow(object@sca), 'genes and', ncol(object@sca), 'cells.\n Using', class(object@LMlike), as.character(object@LMlike@formula), '\n') }) setMethod('coef', signature=c(object='ZlmFit'), function(object, which, ...){ which <- match.arg(which, c('C', 'D')) if(which=='C') object@coefC else object@coefD }) setMethod('vcov', signature=c(object='ZlmFit'), function(object, which, ...){ which <- match.arg(which, c('C', 'D')) if(which=='C') object@vcovC else object@vcovD }) setMethod('se.coef', signature=c(object='ZlmFit'), function(object, which, ...){ which <- match.arg(which, c('C', 'D')) vc <- if(which=='C') object@vcovC else object@vcovD se <- sqrt(aaply(vc, 3, diag)) rownames(se) <- mcols(object@sca)$primerid se }) normalci <- function(center, se, level){ zstar <- qnorm(1-(1-level)/2) list(coef=center, ci.lo=center-se*zstar, ci.hi=center+se*zstar) } setMethod('summary', signature=c(object='ZlmFit'), function(object, logFC=TRUE, doLRT=FALSE, level=.95, parallel = FALSE, ...){ message('Combining coefficients and standard errors') coefAndCI <- aaply( c(C='C', D='D'), 1, function(component){ coefs <- coef(object, which=component) se <- se.coef(object, which=component) names(dimnames(se)) <- names(dimnames(coefs)) <- c('primerid', 'Coefficient') ci <- normalci(coefs, se, level) z <- coefs/se abind(coef=coefs, z=z, ci.lo=ci[['ci.lo']], ci.hi=ci[['ci.hi']], rev.along=0, hier.names=TRUE) }) names(dimnames(coefAndCI)) <- c('component', 'primerid', 'contrast', 'metric') dt <- dcast.data.table(data.table(reshape2::melt(coefAndCI, as.is=TRUE)), primerid + component + contrast ~ metric) setkey(dt, primerid, contrast) stouffer <- dt[,list(z=sum(z)/sqrt(sum(!is.na(z))), component='S'), keyby=list(primerid, contrast)] dt <- rbind(dt, stouffer, fill=TRUE) if(is.logical(logFC) && logFC){ message("Calculating log-fold changes") logFC <- getLogFC(zlmfit=object) } if(!is.logical(logFC)){ lfc <- logFC ci <- normalci(lfc$logFC, sqrt(lfc$varLogFC), level=level) setnames(lfc, 'logFC', 'coef') lfc <- lfc[,c('component', 'ci.lo', 'ci.hi', 'varLogFC'):=list('logFC', ci$ci.lo, ci$ci.hi, NULL)] dt <- rbind(dt, lfc, fill=TRUE) } setkey(dt, contrast, z) if(is.logical(doLRT) && doLRT){ doLRT <- setdiff(colnames(coef(object, 'D')), '(Intercept)') } if(!is.logical(doLRT)){ message('Calculating likelihood ratio tests') llrt <- lapply(doLRT, function(x) lrTest(object, CoefficientHypothesis(x), parallel = parallel)[,,'Pr(>Chisq)']) names(llrt) <- doLRT llrt <- data.table(reshape2::melt(llrt)) setnames(llrt, c('test.type', 'L1', 'value'), c('component', 'contrast', 'Pr(>Chisq)')) llrt[,':='(component=c(cont='C', disc='D', hurdle='H')[component], primerid=as.character(primerid))] setkey(llrt, primerid, component, contrast) setkey(dt, primerid, component, contrast) dt <- merge(llrt, dt, all.x=TRUE, all.y=TRUE) dt[is.na(component), component :='H'] } out <- list(datatable=dt) class(out) <- c('summaryZlmFit', 'list') out }) if(getRversion() >= "2.15.1") globalVariables(c( 'contrast', 'metric', '.', 'value')) print.summaryZlmFit <- function(x, n=2, by='logFC', ...){ x <- x$datatable ns <- seq_len(n) dt <- x[contrast!='(Intercept)',] by <- match.arg(by, c('logFC', 'D', 'C')) if(length(intersect(dt$component, 'logFC'))==0 & by=='logFC'){ warning('Log fold change not calculated, selecting discrete', call.=FALSE) by <- 'D' } dt[,metric:=ifelse(is.na(z), 0, -abs(z))] describe <- switch(by, logFC='log fold change Z-score', D='Wald Z-scores on discrete', C='Wald Z-scores tests on continuous') dt <- dt[component==by,] setkey(dt, contrast, metric) pid <- dt[,list(primerid=primerid[ns]),by=contrast] setkey(dt, primerid) setkey(pid, primerid, contrast) dts <- dt[unique(pid[,list(primerid)]), list(contrast=contrast, primerid=primerid, z=z)] setkey(dts, primerid, contrast) dts[pid,value:=sprintf('%6.1f*', z)] dts[!pid,value:=sprintf('%6.1f ', z)] cdts <- as.data.frame(dcast.data.table(dts, primerid ~ contrast)) cat('Fitted zlm with top', n, 'genes per contrast:\n') cat('(', describe, ')\n') print(cdts, right=FALSE, row.names=FALSE) invisible(cdts) }
NULL plot_cont_indices <- function(indices_list = NULL, select = FALSE, ci_width = 0.95, min_year = NULL, max_year = NULL, species = "", title_size = 20, axis_title_size = 18, axis_text_size = 16, add_observed_means = FALSE) { .Deprecated(new = "plot_indices", msg = "plot_cont_indices() is deprecated in favour of plot_indices()") Year <- NULL; rm(Year) Index <- NULL; rm(Index) obs_mean <- NULL; rm(obs_mean) lci <- NULL; rm(lci) uci <- NULL; rm(uci) indices = indices_list$data_summary if(select){ indices = indices[which(indices$Region_Type == "continental"),] } lq = (1-ci_width)/2 uq = ci_width+lq lqc = paste0("Index_q_",lq) uqc = paste0("Index_q_",uq) indices$lci = indices[,lqc] indices$uci = indices[,uqc] if (!is.null(min_year)) { indices <- indices[which(indices$Year >= min_year), ] } if(!is.null(max_year)) { indices <- indices[which(indices$Year <= max_year), ] } mny = min(indices$Year) mxy = max(indices$Year) yys = pretty(seq(mny, mxy)) yys = c(yys[-length(yys)],mxy) if(add_observed_means){ p <- ggplot2::ggplot() + ggplot2::theme(panel.grid.major = ggplot2::element_blank(), panel.grid.minor = ggplot2::element_blank(), panel.background = ggplot2::element_blank(), axis.line = ggplot2::element_line(colour = "black"), plot.title = ggplot2::element_text(size = title_size), axis.title = ggplot2::element_text(size = axis_title_size), axis.text = ggplot2::element_text(size = axis_text_size)) + ggplot2::labs(title = paste(species, " Continental Trajectory and raw mean counts", sep = ""), x = "Year", y = "Annual index of abundance (mean count)") + ggplot2::geom_point(data = indices,ggplot2::aes(x = Year,y = obs_mean),colour = grDevices::grey(0.6))+ ggplot2::geom_line(data = indices, ggplot2::aes(x = Year, y = Index)) + ggplot2::geom_ribbon(data = indices, ggplot2::aes(x = Year, ymin = lci, ymax = uci), alpha = 0.12)+ ggplot2::scale_x_continuous(breaks = yys)+ ggplot2::scale_y_continuous(limits = c(0,NA)) }else{ p <- ggplot2::ggplot() + ggplot2::theme(panel.grid.major = ggplot2::element_blank(), panel.grid.minor = ggplot2::element_blank(), panel.background = ggplot2::element_blank(), axis.line = ggplot2::element_line(colour = "black"), plot.title = ggplot2::element_text(size = title_size), axis.title = ggplot2::element_text(size = axis_title_size), axis.text = ggplot2::element_text(size = axis_text_size)) + ggplot2::labs(title = paste(species, " Continental Trajectory", sep = ""), x = "Year", y = "Annual index of abundance (mean count)") + ggplot2::geom_line(data = indices, ggplot2::aes(x = Year, y = Index)) + ggplot2::geom_ribbon(data = indices, ggplot2::aes(x = Year, ymin = lci, ymax = uci), alpha = 0.12)+ ggplot2::scale_x_continuous(breaks = yys)+ ggplot2::scale_y_continuous(limits = c(0,NA)) } return(p) }
hyperParStringNN <- function(hyperpar, topL){ paste(paste("size", hyperpar$size), paste("decay", hyperpar$decay), paste("maxit", hyperpar$maxit), paste0("L", topL), sep = " - ") } generateNnet <- function(trainId, loadFromExternalHD, predictors, topL, hyperpar){ saveDir <- file.path(getwd(), "nnet", "Models") savePath <- file.path(saveDir, paste0("nnet - ", paste("train", trainId), " - ", hyperParStringNN(hyperpar, topL), ".rds")) if(!file.exists(savePath)){ if(loadFromExternalHD){ featuresDir <- "H:/Facebook features" } else{ featuresDir <- paste0("../../Feature engineering/", "23-05-2016", "/", "train") } featuresPath <- file.path(featuresDir, paste0("train features - Random batch - ", trainId, ".rds")) targetVar <- "placeMatch" features <- readRDS(featuresPath) features <- features[,names(features) %in% c(predictors, targetVar, "topMRank"), with=FALSE] if(!"topMRank" %in% names(features)){ suppressWarnings(features[, topMRank := 1:100, by=row_id]) } features <- features[topMRank <= topL] predictorMeans <- sapply(features[, predictors, with=FALSE], mean) predictorSds <- sapply(features[, predictors, with=FALSE], sd) targetCol <- which(names(features) == targetVar) featuresS <- data.table(scale(features)) modelData <- cbind(features[, targetVar, with=FALSE], featuresS[, predictors, with=FALSE]) form <- paste(targetVar, paste(predictors, collapse=" + "), sep=" ~ ") model <- nnet(as.formula(form), size = hyperpar$size, maxit = hyperpar$maxit, decay = hyperpar$decay, data = modelData, linout = TRUE, trace = TRUE, MaxNWts = 1e4) rm(list=setdiff(ls(), c("model", "predictors", "hyperpar", "predictorMeans", "predictorSds", "savePath"))) saveRDS(list(model=model, predictors=predictors, hyperpar=hyperpar, predictorMeans=predictorMeans, predictorSds=predictorSds), savePath) } }
concatenate_soundfiles <- function(path, result_file_name = "concatenated", annotation = "textgrid") { match.arg(annotation, c("textgrid", "eaf", "exb")) files <- list.files( path = normalizePath(path), pattern = "(\\.WAVE?$)|(\\.wave?$)|(\\.MP3?$)|(\\.mp3?$)" ) if (length(files) == 0) { stop("There is no any .wav or .mp3 files") } list <- lapply(paste0(normalizePath(path), "/", files), function(file_name) { ext <- tolower(tools::file_ext(file_name)) if (ext == "wave" | ext == "wav") { s <- tuneR::readWave(file_name) } else if (ext == "mp3") { s <- tuneR::readMP3(file_name) } }) sound_attributes <- lapply(seq_along(list), function(x) { data.frame( file = files[x], stereo = list[[x]]@stereo, samp.rate = list[[x]]@samp.rate, bit = list[[x]]@bit ) }) sound_attributes <- do.call(rbind, sound_attributes) problems <- lapply(sound_attributes, function(i) { length(unique(i)) != 1 }) if (TRUE %in% problems[-1]) { pos_probs <- c("channel representation", "sampling rate", "bit rate") problem_text <- paste(pos_probs[unlist(problems)[-1]], collapse = ", and ") message(sound_attributes[, unlist(problems)]) stop(paste0( "You have a problem with ", problem_text, ". Sampling rate, resolution (bit), and number of channels should be the same across all recordings." )) } sound <- do.call(tuneR::bind, list) tuneR::writeWave(sound, paste0(path, "/", result_file_name, ".wav")) if (!is.null(annotation)) { if (annotation[1] == "textgrid") { duration <- unlist(lapply(list, function(i) { length(i@left) / [email protected] })) start_time <- c(0, cumsum(duration[-length(duration)])) end_time <- cumsum(duration) my_textgrid <- data.frame( TierNumber = 1, TierName = "annotation", TierType = "IntervalTier", Index = seq_along(files), StartTime = start_time, EndTime = end_time, Label = sort(files), stringsAsFactors = FALSE ) writeLines( c( 'File type = "ooTextFile"', 'Object class = "TextGrid"', "", "xmin = 0 ", paste0("xmax = ", end_time[length(end_time)]), "tiers? <exists> ", "size = 1 ", "item []: ", " item [1]:", ' class = "IntervalTier"', ' name = "labels"', " xmin = 0", paste0(" xmax = ", end_time[length(end_time)]), paste0(" intervals: size = ", length(duration)), paste0(paste0(" intervals [", my_textgrid$Index, "]:"), "\n", paste0(" xmin = ", my_textgrid$StartTime), "\n", paste0(" xmax = ", my_textgrid$EndTime), "\n", paste0(' text = "', my_textgrid$Label, '"'), "\n", collapse = "" ) ), paste0(path, "/", result_file_name, ".TextGrid") ) } else if (annotation[1] == "eaf") { warning("Will be done in the future") } else if (annotation[1] == "exb") { warning("Will be done in the future") } } }
create_img_db <- function(path, ext = "dcm", all = TRUE, keywords = c("StudyDate", "StudyTime", "SeriesDate", "SeriesTime", "AcquisitionDate", "AcquisitionTime", "ConversionType", "Manufacturer", "InstitutionName", "InstitutionalDepartmentName", "ReferringPhysicianName", "Modality", "ManufacturerModelName", "StudyDescription", "SeriesDescription", "StudyComments", "ProtocolName", "RequestedProcedureID", "ViewPosition", "StudyInstanceUID", "SeriesInstanceUID", "SOPInstanceUID", "AccessionNumber", "PatientName", "PatientID", "IssuerOfPatientID", "PatientBirthDate", "PatientSex", "PatientAge", "PatientSize", "PatientWeight", "StudyID", "SeriesNumber", "AcquisitionNumber", "InstanceNumber", "BodyPartExamined", "SliceThickness", "SpacingBetweenSlices", "PixelSpacing", "PixelAspectRatio", "Rows", "Columns", "FieldOfViewDimensions", "RescaleIntercept", "RescaleSlope", "WindowCenter", "WindowWidth", "BitsAllocated", "BitsStored", "PhotometricInterpretation", "KVP", "ExposureTime", "XRayTubeCurrent", "ExposureInuAs", "ImageAndFluoroscopyAreaDoseProduct", "FilterType", "ConvolutionKernel", "CTDIvol", "ReconstructionFieldOfView"), nThread = 4, na = TRUE, identical = TRUE) { pydicom <- reticulate::import("pydicom") img_db <- dcm_db(path = path, ext = ext, all = all, keywords = keywords, nThread = nThread, pydicom = pydicom) img_db$time_study <- as.POSIXct(paste0(img_db$StudyDate, img_db$StudyTime), format = "%Y%m%d %H%M%S", tz = "EST") img_db$time_series <- as.POSIXct(paste0(img_db$SeriesDate, img_db$SeriesTime), format = "%Y%m%d %H%M%S", tz = "EST") img_db$time_acquisition <- as.POSIXct(paste0(img_db$AcquisitionDate, img_db$AcquisitionTime), format = "%Y%m%d %H%M%S", tz = "EST") img_db$name_img <- trimws(gsub("[[:punct:]]", " ", img_db$PatientName)) img_db$time_date_of_birth_img <- as.POSIXct(img_db$PatientBirthDate, format = "%Y%m%d", tz = "EST") img_db$img_pixel_spacing <- as.numeric(gsub("\\[(.+),.*", "\\1", img_db$PixelSpacing)) img_db <- remove_column(dt = img_db, na = na, identical = identical) img_db }
facet_sample <- function(n_per_facet = 3, n_facets = 12, nrow = NULL, ncol = NULL, scales = "fixed", shrink = TRUE, strip.position = "top") { facet <- facet_wrap(~.strata, nrow = nrow, ncol = ncol, scales = scales, shrink = shrink, strip.position = strip.position) facet$params$n <- n_facets facet$params$n_per_facet <- n_per_facet ggproto(NULL, FacetSample, shrink = shrink, params = facet$params ) } FacetSample <- ggproto( "FacetSample", FacetWrap, compute_layout = function(data, params) { id <- seq_len(params$n) dims <- wrap_dims(n = params$n, nrow = params$nrow, ncol = params$ncol) layout <- data.frame(PANEL = factor(id)) if (params$as.table) { layout$ROW <- as.integer((id - 1L) %/% dims[2] + 1L) } else { layout$ROW <- as.integer(dims[1] - (id - 1L) %/% dims[2]) } layout$COL <- as.integer((id - 1L) %% dims[2] + 1L) layout <- layout[order(layout$PANEL), , drop = FALSE] rownames(layout) <- NULL layout$SCALE_X <- if (params$free$x) id else 1L layout$SCALE_Y <- if (params$free$y) id else 1L cbind(layout, .strata = id) }, map_data = function(data, layout, params) { if (is.null(data) || nrow(data) == 0) { return(cbind(data, PANEL = integer(0))) } new_data <- data %>% sample_n_keys(size = params$n * params$n_per_facet) %>% stratify_keys(n_strata = params$n) new_data$PANEL = new_data$.strata return(new_data) } )
CRB <- function(sdf, supp=NULL, A=NULL, eps=1e-04,...) { p <- length(sdf) dsdf <- function(x,j){ (sdf[[j]](x+eps)-sdf[[j]](x-eps))/(2*eps)} if(is.null(supp)) supp <- matrix(c(rep(-8,p),rep(8,p)),ncol=2) if(is.null(A)) A <- diag(p) kap <- NULL lambda <- NULL for(j in 1:p){ kap[j] <- integrate(Vectorize(function(x){dsdf(x,j)^2/sdf[[j]](x)}),supp[j,1],supp[j,2],...)$value lambda[j] <- integrate(Vectorize(function(x){dsdf(x,j)^2*x^2/sdf[[j]](x)}),supp[j,1],supp[j,2],...)$value-1 } crlb <- matrix(0,p,p) for(i in 1:p){ for(j in 1:p){ if(i!=j){ crlb[i,j] <- kap[j]/(kap[i]*kap[j]-1) }else{ crlb[i,i] <- 1/(lambda[i]) } } } FIM <- matrix(0,p^2,p^2) FIM1 <- matrix(0,p,p) for(i in 1:p){ for(j in 1:p){ if(i==j){ FIM1 <- tcrossprod(A[,j],A[,i])*lambda[i] for(l in 1:p){ if(l!=i){ FIM1 <- FIM1+tcrossprod(A[,l],A[,l])*kap[i] } } FIM[((i-1)*p+1):(i*p),((j-1)*p+1):(j*p)]<-FIM1 }else{ FIM[((i-1)*p+1):(i*p),((j-1)*p+1):(j*p)]<-tcrossprod(A[,j],A[,i]) } } } EMD <- sum(crlb-diag(crlb)*as.vector(diag(p))) list(CRLB=crlb, FIM=FIM, EMD=EMD) }
expected <- eval(parse(text="structure(list(ctrl = c(4.17, 5.58, 5.18, 6.11, 4.5, 4.61, 5.17, 4.53, 5.33, 5.14), trt1 = c(4.81, 4.17, 4.41, 3.59, 5.87, 3.83, 6.03, 4.89, 4.32, 4.69), trt2 = c(6.31, 5.12, 5.54, 5.5, 5.37, 5.29, 4.92, 6.15, 5.8, 5.26)), .Names = c(\"ctrl\", \"trt1\", \"trt2\"))")); test(id=0, code={ argv <- eval(parse(text="list(structure(list(ctrl = c(4.17, 5.58, 5.18, 6.11, 4.5, 4.61, 5.17, 4.53, 5.33, 5.14), trt1 = c(4.81, 4.17, 4.41, 3.59, 5.87, 3.83, 6.03, 4.89, 4.32, 4.69), trt2 = c(6.31, 5.12, 5.54, 5.5, 5.37, 5.29, 4.92, 6.15, 5.8, 5.26)), .Dim = 3L, .Dimnames = list(c(\"ctrl\", \"trt1\", \"trt2\"))))")); do.call(`c`, argv); }, o=expected);
test_that("confl_post_page() works", { skip_on_cran() res <- structure(list(status_code = 200), class = "response") m <- mockery::mock(res) with_mock( "conflr::confl_verb" = m, "httr::content" = function(res) NULL, { confl_post_page("page", "space1", "title", "<p>foo</p>") } ) args <- mockery::mock_args(m)[[1]] expect_equal(args$body, list( type = "page", title = "title", space = list( key = "space1" ), body = list( storage = list( value = "<p>foo</p>", representation = "storage" ) ) )) }) test_that("confl_update_page() works", { skip_on_cran() res <- structure(list(status_code = 200), class = "response") m <- mockery::mock(res) info <- list(version = list(number = 11L), type = "page") m2 <- mockery::mock(info) with_mock( "conflr::confl_verb" = m, "conflr::confl_get_page" = m2, "httr::content" = function(res) NULL, { confl_update_page("1234", "title", "<p>foo</p>") } ) args <- mockery::mock_args(m)[[1]] expect_equal(args$body, list( type = "page", title = "title", body = list( storage = list( value = "<p>foo</p>", representation = "storage" ) ), version = list( number = 12L ) )) })
library(gridGraphics) box1 <- function() { set.seed(1) plot(1:7, abs(stats::rnorm(7)), type = "h", axes = FALSE) axis(1, at = 1:7, labels = letters[1:7]) box(lty = '1373', col = 'red') } plotdiff(expression(box1()), "box-1") plotdiffResult()
which_first <- function(expr, verbose = FALSE, reverse = FALSE, sexpr, eval_parent_n = 1L, suppressWarning = getOption("hutilscpp_suppressWarning", FALSE), use.which.max = FALSE) { if (use.which.max) { return(.which_first(expr, verbose = verbose, reverse = reverse)) } rhs <- NULL if (missing(sexpr)) { sexpr <- substitute(expr) } if (!is.call(sexpr) || length(sexpr) != 3L || isFALSE(op <- op2M(operator <- as.character(sexpr[[1L]])))) { o <- .which_first(expr, verbose = verbose, reverse = reverse) return(o) } lhs <- sexpr[[2L]] if (!is.name(lhs)) { o <- .which_first(expr, verbose = verbose, reverse = reverse) return(o) } rhs <- sexpr[[3L]] isValidExpr <- is.numeric(rhs) || AND(is.call(rhs) && is.numeric(rhs[[2L]]), as.character(rhs[[1L]]) == "-") || is.logical(rhs_eval <- eval.parent(rhs, n = eval_parent_n)) || AND(op >= 7 && op <= 10, is.numeric(rhs_eval)) || AND(is.symbol(rhs), AND(is.numeric(lhs_eval <- eval.parent(lhs, n = eval_parent_n)), is.numeric(rhs_eval))) || AND(is.character(rhs_eval), all(is.character(lhs_eval <- eval.parent(lhs, n = eval_parent_n)), OR(length(lhs_eval) == length(rhs_eval), length(rhs_eval) == 1L), OR(operator == "!=", operator == "=="), na.rm = TRUE)) if (!isValidExpr) { o <- .which_first(expr, verbose = verbose, reverse = reverse) return(o) } lhs_eval <- eval.parent(lhs, n = eval_parent_n) if (length(lhs_eval) <= 1L) { if (isTRUE(expr)) { return(1L) } else { return(0L) } } rhs_eval <- eval.parent(rhs, n = eval_parent_n) if (is.logical(lhs_eval)) { if (operator == "%in%") { if (reverse) { o <- do_which_last_in_lgl(lhs_eval, anyNA_ = anyNA(rhs_eval), any_ = any(rhs_eval, na.rm = TRUE), nall_ = !all(rhs_eval, na.rm = TRUE)) } else { o <- do_which_first_in_lgl(lhs_eval, anyNA_ = anyNA(rhs_eval), any_ = any(rhs_eval, na.rm = TRUE), nall_ = !all(rhs_eval, na.rm = TRUE)) } return(R_xlen_t(o)) } if (length(rhs_eval) == length(lhs_eval) || operator == "%between%" || operator == "%(between)%") { if (is.logical(rhs_eval)) { if (identical(as.logical(lhs_eval), as.logical(rhs_eval))) { if (operator == "==" || operator == "<=" || operator == ">=" || operator == "%in%") { return(1L) } else { return(0L) } } else { return(do_which_first_lgl_lgl_op(lhs_eval, rhs_eval, op, reverse = reverse)) } } } if (anyNA(rhs_eval)) { warn_msg <- "`rhs` appears to be logical NA. Treating as\n\twhich_first(is.na(.))" if (operator == "!=") { warn_msg <- "`rhs` appears to be logical NA. Treating as\n\twhich_first(!is.na(.))" } suppressThisWarn <- isTRUE(suppressWarning) || AND(is.character(suppressWarning), any(vapply(suppressWarning, grepl, x = warn_msg, perl = TRUE, FUN.VALUE = FALSE), na.rm = TRUE)) switch(operator, "==" = { if (!suppressThisWarn) { warning(warn_msg) } o <- .which_first(is.na(lhs_eval), verbose = verbose, reverse = reverse) }, "!=" = { if (!suppressThisWarn) { warning(warn_msg) } o <- .which_first(!is.na(lhs_eval), verbose = verbose, reverse = reverse) }, stop("`rhs` appears to be logical NA. This is not supported for operator '", operator, "'.")) } else { o <- .which_first_logical(lhs_eval, as.logical(rhs_eval), operator = operator, rev = reverse) } return(R_xlen_t(o)) } if (is.numeric(lhs_eval) && is.numeric(rhs_eval)) { if (op == 7L) { o <- if (reverse) { fmatchp(lhs_eval, rhs_eval, whichFirst = -1L) } else { fmatchp(lhs_eval, rhs_eval, whichFirst = 1L) } return(R_xlen_t(o)) } nx <- length(lhs_eval) ny <- length(rhs_eval) if (op > 7L && op <= 10L && ny != 2) { stop("Expression in `which_first` was of the form:\n\t which_first(x %between% rhs)\n", "yet `length(rhs) = ", ny, "`. Ensure the object passed to RHS is an atomic vector ", "of length two.") } if (op < 7L) { if (nx == 0L || ny == 0L) { return(0L) } if (nx != ny && ny != 1L) { stop("In `expr ~ <lhs> <op> <rhs>`, length of lhs = ", nx, " but length of rhs = ", ny, ". ", "With operator '", operator, "' the only permitted lengths of the RHS are 1 and length(lhs).") } if (ny == 2L) { ny <- 3L } } if (is.integer(rhs_eval)) { y1d <- y1i <- rhs_eval[1L] y2d <- y2i <- rhs_eval[2L] } else { y1d <- y1i <- rhs_eval[1L] y2d <- y2i <- rhs_eval[2L] } if (!is.double(y1d)) { y1d <- as.double(y1d) } if (!is.double(y2d)) { y2d <- as.double(y2d) } if (reverse) { o <- do_which_last__(lhs_eval, op, rhs_eval, ny = qd2i(ny), y1i = qd2i(y1i), y2i = qd2i(y2i), y1d = y1d, y2d = y2d) } else { o <- do_which_first__(lhs_eval, op, rhs_eval, ny = qd2i(ny), y1i = qd2i(y1i), y2i = qd2i(y2i), y1d = y1d, y2d = y2d) } return(R_xlen_t(o)) } if (is.character(lhs_eval)) { oc <- switch(operator, "==" = AnyCharMatch(lhs_eval, as.character(rhs_eval)), "!=" = AnyCharMatch(lhs_eval, as.character(rhs_eval), opposite = TRUE), { o <- .which_first(expr, verbose = verbose, reverse = reverse) }) if (oc <= .Machine$integer.max) { oc <- as.integer(oc) } return(oc) } o <- .which_first(expr, reverse = reverse) R_xlen_t(o) } .which_first <- function(expr, verbose = FALSE, reverse = FALSE) { if (verbose) { message("Falling back to `which.max(expr)`.") } if (reverse) { return(do_which_last(expr)) } o <- which.max(expr) if (length(o) == 0L) { return(0L) } if (o == 1L && !expr[1L]) { o <- 0L } o } .which_first_logical <- function(lhs, rhs, operator = "==", verbose = FALSE, rev = FALSE) { stopifnot(length(lhs) >= 1L, is.logical(rhs), length(rhs) == 1L, is.logical(verbose)) if (is.na(rhs)) { return(.Call("C_which_first_lgl1", lhs, rhs, op2M(operator), isTRUE(rev), PACKAGE = packageName)) } switch({ operator }, "!=" = { if (rhs) { if (rev) { return(do_which_last_false(lhs)) } else { return(do_which_first_false(lhs)) } } else { if (rev) { return(do_which_last(lhs)) } else { return(do_which_first(lhs)) } } }, "==" = { if (rhs) { if (rev) { return(do_which_last(lhs)) } else { return(do_which_first(lhs)) } } else { if (rev) { return(do_which_last_false(lhs)) } else { return(do_which_first_false(lhs)) } } }, "<" = { if (rhs) { if (rev) { return(do_which_last_false(lhs)) } else { return(do_which_first_false(lhs)) } } else { return(0L) } }, "<=" = { if (rhs) { if (rev) { return(length(lhs)) } else { return(1L) } } else { if (rev) { return(do_which_last_false(lhs)) } else { return(do_which_first_false(lhs)) } } }, ">" = { if (rhs) { return(0L) } else { if (rev) { return(do_which_last(lhs)) } else { return(do_which_first(lhs)) } } }, ">=" = { if (rhs) { if (rev) { return(do_which_last(lhs)) } else { return(do_which_first(lhs)) } } else { if (rev) { return(length(lhs)) } else { return(1L) } } }) print(ls.str()) stop("Internal error: 559:2019:11:18. ") } which_last <- function(expr, verbose = FALSE, reverse = FALSE, suppressWarning = getOption("hutilscpp_suppressWarning", FALSE)) { force(reverse) which_first(expr, verbose = verbose, reverse = isFALSE(reverse), sexpr = substitute(expr), eval_parent_n = 2L, suppressWarning = suppressWarning) } do_which_first__ <- function(x, op, y, ny, y1i, y2i, y1d, y2d) { Nx <- length(x) Ny <- length(y) if (ny > 2L && Nx != Ny) { stop("Lengths differ.") } stopifnot(is.numeric(x), is.integer(op), length(op) == 1L, is.numeric(y), is.integer(y1i), is.integer(y2i), length(y1i) == 1L, length(y2i) == 1L, is.double(y1d), is.double(y2d), length(y1d) == 1L, length(y2d) == 1L) .Call("Cwhich_first__", x, op, y, ny, y1i, y2i, y1d, y2d, PACKAGE = packageName) } do_which_first <- function(x) { .Call("Cwhich_first", x, PACKAGE = packageName) } do_which_last <- function(x) { .Call("Cwhich_last", x, PACKAGE = packageName) } do_which_first_false <- function(x) { .Call("Cwhich_first_false", x, PACKAGE = packageName) } do_which_last_false <- function(x) { .Call("Cwhich_last_false", x, PACKAGE = packageName) } do_which_first_in_lgl <- function(x, anyNA_, any_, nall_) { .Call("Cwhich_first_in_lgl", x, anyNA_, any_, nall_, PACKAGE = packageName) } do_which_last_in_lgl <- function(x, anyNA_, any_, nall_) { .Call("Cwhich_last_in_lgl", x, anyNA_, any_, nall_, PACKAGE = packageName) } do_which_firstNA <- function(x) { .Call("Cwhich_firstNA", x, PACKAGE = packageName) } do_which_lastNA <- function(x) { .Call("Cwhich_lastNA", x, PACKAGE = packageName) } do_which_last_notTRUE <- function(x) { .Call("Cwhich_last_notTRUE", x, PACKAGE = packageName) } do_which_last_notFALSE <- function(x) { .Call("Cwhich_last_notFALSE", x, PACKAGE = packageName) } do_which_first_lgl_lgl_op <- function(x, y, op, reverse = FALSE) { .Call("Cwhich_first_lgl_lgl_op", x, y, op, reverse, PACKAGE = packageName) } do_which_last__ <- function(x, op, y, ny, y1i, y2i, y1d, y2d) { Nx <- length(x) Ny <- length(y) if (ny > 2L && Nx != Ny) { stop("Lengths differ.") } stopifnot(is.numeric(x), is.integer(op), length(op) == 1L, is.numeric(y), is.integer(y1i), is.integer(y2i), length(y1i) == 1L, length(y2i) == 1L, is.double(y1d), is.double(y2d), length(y1d) == 1L, length(y2d) == 1L) .Call("Cwhich_last__", x, op, y, ny, y1i, y2i, y1d, y2d, PACKAGE = packageName) }
tippecanoe <- function(input, output, layer_name = NULL, min_zoom = NULL, max_zoom = NULL, drop_rate = NULL, overwrite = TRUE, other_options = NULL, keep_geojson = FALSE) { check_install <- system("tippecanoe -v") == 0 if (!check_install) { stop("tippecanoe is not installed. Please visit https://github.com/mapbox/tippecanoe for installation instructions.", call. = FALSE) } opts <- c() if (!is.null(min_zoom)) { opts <- c(opts, sprintf("-Z%s", min_zoom)) } if (!is.null(max_zoom)) { opts <- c(opts, sprintf("-z%s", max_zoom)) } if (is.null(min_zoom) && is.null(max_zoom)) { opts <- c(opts, "-zg") } if (!is.null(drop_rate)) { opts <- c(opts, sprintf("-r%s", drop_rate)) } else { opts <- c(opts, "-as") } if (overwrite) { opts <- c(opts, "-f") } collapsed_opts <- paste0(opts, collapse = " ") if (!is.null(other_options)) { extra_opts <- paste0(other_options, collapse = " ") collapsed_opts <- paste(collapsed_opts, extra_opts) } dir <- getwd() if (any(grepl("^sf", class(input)))) { input <- sf::st_transform(input, 4326) if (is.null(layer_name)) { layer_name <- stringi::stri_rand_strings(1, 6) } if (keep_geojson) { outfile <- paste0(layer_name, ".geojson") path <- file.path(dir, outfile) sf::st_write(input, path, quiet = TRUE, delete_dsn = TRUE, delete_layer = TRUE) } else { tmp <- tempdir() tempfile <- paste0(layer_name, ".geojson") path <- file.path(tmp, tempfile) sf::st_write(input, path, quiet = TRUE, delete_dsn = TRUE, delete_layer = TRUE) } call <- sprintf("tippecanoe -o %s/%s %s %s", dir, output, collapsed_opts, path) system(call) } else if (class(input) == "character") { if (!is.null(layer_name)) { collapsed_opts <- paste0(collapsed_opts, " -l ", layer_name) } call <- sprintf("tippecanoe -o %s/%s %s %s", dir, output, collapsed_opts, input) system(call) } }
expected <- eval(parse(text="structure(list(x = 2.28125, y = 1.70580465116279, xlab = NULL, ylab = NULL), .Names = c(\"x\", \"y\", \"xlab\", \"ylab\"))")); test(id=0, code={ argv <- eval(parse(text="list(x = 2.28125, y = 1.70580465116279, xlab = NULL, ylab = NULL)")); do.call(`list`, argv); }, o=expected);
XMLParseErrors <- structure(c(0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 35L, 36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 46L, 47L, 48L, 49L, 50L, 51L, 52L, 53L, 54L, 55L, 56L, 57L, 58L, 59L, 60L, 61L, 62L, 63L, 64L, 65L, 66L, 67L, 68L, 69L, 70L, 71L, 72L, 73L, 74L, 75L, 76L, 77L, 78L, 79L, 80L, 81L, 82L, 83L, 84L, 85L, 86L, 87L, 88L, 89L, 90L, 91L, 92L, 93L, 94L, 95L, 96L, 97L, 98L, 99L, 100L, 101L, 102L, 103L, 104L, 105L, 106L, 107L, 108L, 109L, 200L, 201L, 202L, 203L, 204L, 205L, 500L, 501L, 502L, 503L, 504L, 505L, 506L, 507L, 508L, 509L, 510L, 511L, 512L, 513L, 514L, 515L, 516L, 517L, 518L, 519L, 520L, 521L, 522L, 523L, 524L, 525L, 526L, 527L, 528L, 529L, 530L, 531L, 532L, 533L, 534L, 535L, 536L, 537L, 538L, 539L, 540L, 541L, 800L, 801L, 1000L, 1001L, 1002L, 1003L, 1004L, 1005L, 1006L, 1007L, 1008L, 1009L, 1010L, 1011L, 1012L, 1013L, 1014L, 1015L, 1016L, 1017L, 1018L, 1019L, 1020L, 1021L, 1022L, 1023L, 1024L, 1025L, 1026L, 1027L, 1028L, 1029L, 1030L, 1031L, 1032L, 1033L, 1034L, 1035L, 1036L, 1037L, 1038L, 1039L, 1040L, 1041L, 1042L, 1043L, 1044L, 1045L, 1046L, 1047L, 1048L, 1049L, 1050L, 1051L, 1052L, 1053L, 1054L, 1055L, 1056L, 1057L, 1058L, 1059L, 1060L, 1061L, 1062L, 1063L, 1064L, 1065L, 1066L, 1067L, 1068L, 1069L, 1070L, 1071L, 1072L, 1073L, 1074L, 1075L, 1076L, 1077L, 1078L, 1079L, 1080L, 1081L, 1082L, 1083L, 1084L, 1085L, 1086L, 1087L, 1088L, 1089L, 1090L, 1091L, 1092L, 1093L, 1094L, 1095L, 1096L, 1097L, 1098L, 1099L, 1100L, 1101L, 1102L, 1103L, 1104L, 1105L, 1106L, 1107L, 1108L, 1109L, 1110L, 1111L, 1112L, 1113L, 1114L, 1115L, 1116L, 1117L, 1118L, 1119L, 1120L, 1121L, 1122L, 1200L, 1201L, 1202L, 1203L, 1204L, 1205L, 1206L, 1207L, 1208L, 1209L, 1210L, 1211L, 1212L, 1213L, 1214L, 1215L, 1216L, 1217L, 1218L, 1219L, 1220L, 1221L, 1300L, 1301L, 1302L, 1303L, 1400L, 1401L, 1402L, 1403L, 1450L, 1500L, 1501L, 1502L, 1503L, 1504L, 1505L, 1506L, 1507L, 1508L, 1509L, 1510L, 1511L, 1512L, 1513L, 1514L, 1515L, 1516L, 1517L, 1518L, 1519L, 1520L, 1521L, 1522L, 1523L, 1524L, 1525L, 1526L, 1527L, 1528L, 1529L, 1530L, 1531L, 1532L, 1533L, 1534L, 1535L, 1536L, 1537L, 1538L, 1539L, 1540L, 1541L, 1542L, 1543L, 1544L, 1545L, 1546L, 1547L, 1548L, 1549L, 1550L, 1551L, 1552L, 1553L, 1554L, 1555L, 1556L, 1600L, 1601L, 1602L, 1603L, 1604L, 1605L, 1606L, 1607L, 1608L, 1609L, 1610L, 1611L, 1612L, 1613L, 1614L, 1615L, 1616L, 1617L, 1618L, 1650L, 1651L, 1652L, 1653L, 1654L, 1700L, 1701L, 1702L, 1703L, 1704L, 1705L, 1706L, 1707L, 1708L, 1709L, 1710L, 1711L, 1712L, 1713L, 1714L, 1715L, 1716L, 1717L, 1718L, 1719L, 1720L, 1721L, 1722L, 1723L, 1724L, 1725L, 1726L, 1727L, 1728L, 1729L, 1730L, 1731L, 1732L, 1733L, 1734L, 1735L, 1736L, 1737L, 1738L, 1739L, 1740L, 1741L, 1742L, 1743L, 1744L, 1745L, 1746L, 1747L, 1748L, 1749L, 1750L, 1751L, 1752L, 1753L, 1754L, 1755L, 1756L, 1757L, 1758L, 1759L, 1760L, 1761L, 1762L, 1763L, 1764L, 1765L, 1766L, 1767L, 1768L, 1769L, 1770L, 1771L, 1772L, 1773L, 1774L, 1775L, 1776L, 1777L, 1778L, 1779L, 1780L, 1781L, 1782L, 1783L, 1784L, 1785L, 1786L, 1787L, 1788L, 1789L, 1790L, 1791L, 1792L, 1793L, 1794L, 1795L, 1796L, 1797L, 1798L, 1799L, 1800L, 1801L, 1802L, 1803L, 1804L, 1805L, 1806L, 1807L, 1808L, 1809L, 1810L, 1811L, 1812L, 1813L, 1814L, 1815L, 1816L, 1817L, 1818L, 1819L, 1820L, 1821L, 1822L, 1823L, 1824L, 1825L, 1826L, 1827L, 1828L, 1829L, 1830L, 1831L, 1832L, 1833L, 1834L, 1835L, 1836L, 1837L, 1838L, 1839L, 1840L, 1841L, 1842L, 1843L, 1844L, 1845L, 1846L, 1847L, 1848L, 1849L, 1850L, 1851L, 1852L, 1853L, 1854L, 1855L, 1856L, 1857L, 1858L, 1859L, 1860L, 1861L, 1862L, 1863L, 1864L, 1865L, 1866L, 1867L, 1868L, 1869L, 1870L, 1871L, 1872L, 1873L, 1874L, 1875L, 1876L, 1877L, 1878L, 1879L, 1900L, 1901L, 1902L, 1903L, 1950L, 1951L, 1952L, 1953L, 1954L, 1955L, 2000L, 2001L, 2002L, 2003L, 2020L, 2021L, 2022L, 3000L, 3001L, 3002L, 3003L, 3004L, 3005L, 3006L, 3007L, 3008L, 3009L, 3010L, 3011L, 3012L, 3013L, 3014L, 3015L, 3016L, 3017L, 3018L, 3019L, 3020L, 3021L, 3022L, 3023L, 3024L, 3025L, 3026L, 3027L, 3028L, 3029L, 3030L, 3031L, 3032L, 3033L, 3034L, 3035L, 3036L, 3037L, 3038L, 3039L, 3040L, 3041L, 3042L, 3043L, 3044L, 3045L, 3046L, 3047L, 3048L, 3049L, 3050L, 3051L, 3052L, 3053L, 3054L, 3055L, 3056L, 3057L, 3058L, 3059L, 3060L, 3061L, 3062L, 3063L, 3064L, 3065L, 3066L, 3067L, 3068L, 3069L, 3070L, 3071L, 3072L, 3073L, 3074L, 3075L, 3076L, 3077L, 3078L, 3079L, 3080L, 3081L, 3082L, 3083L, 3084L, 3085L, 3086L, 3087L, 3088L, 3089L, 3090L, 3091L, 4000L, 4001L, 4900L, 4901L, 5000L, 5001L, 5002L, 5003L, 5004L, 5005L, 5006L, 5007L, 5008L, 5009L, 5010L, 5011L, 5012L, 5013L, 5014L, 5015L, 5016L, 5017L, 5018L, 5019L, 5020L, 5021L, 5022L, 5023L, 5024L, 5025L, 5026L, 5027L, 5028L, 5029L, 5030L, 5031L, 5032L, 5033L, 5034L, 5035L, 5036L, 5037L, 6000L, 6001L, 6002L, 6003L, 6004L), .Names = c("XML_ERR_OK", "XML_ERR_INTERNAL_ERROR", "XML_ERR_NO_MEMORY", "XML_ERR_DOCUMENT_START", "XML_ERR_DOCUMENT_EMPTY", "XML_ERR_DOCUMENT_END", "XML_ERR_INVALID_HEX_CHARREF", "XML_ERR_INVALID_DEC_CHARREF", "XML_ERR_INVALID_CHARREF", "XML_ERR_INVALID_CHAR", "XML_ERR_CHARREF_AT_EOF", "XML_ERR_CHARREF_IN_PROLOG", "XML_ERR_CHARREF_IN_EPILOG", "XML_ERR_CHARREF_IN_DTD", "XML_ERR_ENTITYREF_AT_EOF", "XML_ERR_ENTITYREF_IN_PROLOG", "XML_ERR_ENTITYREF_IN_EPILOG", "XML_ERR_ENTITYREF_IN_DTD", "XML_ERR_PEREF_AT_EOF", "XML_ERR_PEREF_IN_PROLOG", "XML_ERR_PEREF_IN_EPILOG", "XML_ERR_PEREF_IN_INT_SUBSET", "XML_ERR_ENTITYREF_NO_NAME", "XML_ERR_ENTITYREF_SEMICOL_MISSING", "XML_ERR_PEREF_NO_NAME", "XML_ERR_PEREF_SEMICOL_MISSING", "XML_ERR_UNDECLARED_ENTITY", "XML_WAR_UNDECLARED_ENTITY", "XML_ERR_UNPARSED_ENTITY", "XML_ERR_ENTITY_IS_EXTERNAL", "XML_ERR_ENTITY_IS_PARAMETER", "XML_ERR_UNKNOWN_ENCODING", "XML_ERR_UNSUPPORTED_ENCODING", "XML_ERR_STRING_NOT_STARTED", "XML_ERR_STRING_NOT_CLOSED", "XML_ERR_NS_DECL_ERROR", "XML_ERR_ENTITY_NOT_STARTED", "XML_ERR_ENTITY_NOT_FINISHED", "XML_ERR_LT_IN_ATTRIBUTE", "XML_ERR_ATTRIBUTE_NOT_STARTED", "XML_ERR_ATTRIBUTE_NOT_FINISHED", "XML_ERR_ATTRIBUTE_WITHOUT_VALUE", "XML_ERR_ATTRIBUTE_REDEFINED", "XML_ERR_LITERAL_NOT_STARTED", "XML_ERR_LITERAL_NOT_FINISHED", "XML_ERR_COMMENT_NOT_FINISHED", "XML_ERR_PI_NOT_STARTED", "XML_ERR_PI_NOT_FINISHED", "XML_ERR_NOTATION_NOT_STARTED", "XML_ERR_NOTATION_NOT_FINISHED", "XML_ERR_ATTLIST_NOT_STARTED", "XML_ERR_ATTLIST_NOT_FINISHED", "XML_ERR_MIXED_NOT_STARTED", "XML_ERR_MIXED_NOT_FINISHED", "XML_ERR_ELEMCONTENT_NOT_STARTED", "XML_ERR_ELEMCONTENT_NOT_FINISHED", "XML_ERR_XMLDECL_NOT_STARTED", "XML_ERR_XMLDECL_NOT_FINISHED", "XML_ERR_CONDSEC_NOT_STARTED", "XML_ERR_CONDSEC_NOT_FINISHED", "XML_ERR_EXT_SUBSET_NOT_FINISHED", "XML_ERR_DOCTYPE_NOT_FINISHED", "XML_ERR_MISPLACED_CDATA_END", "XML_ERR_CDATA_NOT_FINISHED", "XML_ERR_RESERVED_XML_NAME", "XML_ERR_SPACE_REQUIRED", "XML_ERR_SEPARATOR_REQUIRED", "XML_ERR_NMTOKEN_REQUIRED", "XML_ERR_NAME_REQUIRED", "XML_ERR_PCDATA_REQUIRED", "XML_ERR_URI_REQUIRED", "XML_ERR_PUBID_REQUIRED", "XML_ERR_LT_REQUIRED", "XML_ERR_GT_REQUIRED", "XML_ERR_LTSLASH_REQUIRED", "XML_ERR_EQUAL_REQUIRED", "XML_ERR_TAG_NAME_MISMATCH", "XML_ERR_TAG_NOT_FINISHED", "XML_ERR_STANDALONE_VALUE", "XML_ERR_ENCODING_NAME", "XML_ERR_HYPHEN_IN_COMMENT", "XML_ERR_INVALID_ENCODING", "XML_ERR_EXT_ENTITY_STANDALONE", "XML_ERR_CONDSEC_INVALID", "XML_ERR_VALUE_REQUIRED", "XML_ERR_NOT_WELL_BALANCED", "XML_ERR_EXTRA_CONTENT", "XML_ERR_ENTITY_CHAR_ERROR", "XML_ERR_ENTITY_PE_INTERNAL", "XML_ERR_ENTITY_LOOP", "XML_ERR_ENTITY_BOUNDARY", "XML_ERR_INVALID_URI", "XML_ERR_URI_FRAGMENT", "XML_WAR_CATALOG_PI", "XML_ERR_NO_DTD", "XML_ERR_CONDSEC_INVALID_KEYWORD", "XML_ERR_VERSION_MISSING", "XML_WAR_UNKNOWN_VERSION", "XML_WAR_LANG_VALUE", "XML_WAR_NS_URI", "XML_WAR_NS_URI_RELATIVE", "XML_ERR_MISSING_ENCODING", "XML_WAR_SPACE_VALUE", "XML_ERR_NOT_STANDALONE", "XML_ERR_ENTITY_PROCESSING", "XML_ERR_NOTATION_PROCESSING", "XML_WAR_NS_COLUMN", "XML_WAR_ENTITY_REDEFINED", "XML_ERR_UNKNOWN_VERSION", "XML_ERR_VERSION_MISMATCH", "XML_NS_ERR_XML_NAMESPACE", "XML_NS_ERR_UNDEFINED_NAMESPACE", "XML_NS_ERR_QNAME", "XML_NS_ERR_ATTRIBUTE_REDEFINED", "XML_NS_ERR_EMPTY", "XML_NS_ERR_COLON", "XML_DTD_ATTRIBUTE_DEFAULT", "XML_DTD_ATTRIBUTE_REDEFINED", "XML_DTD_ATTRIBUTE_VALUE", "XML_DTD_CONTENT_ERROR", "XML_DTD_CONTENT_MODEL", "XML_DTD_CONTENT_NOT_DETERMINIST", "XML_DTD_DIFFERENT_PREFIX", "XML_DTD_ELEM_DEFAULT_NAMESPACE", "XML_DTD_ELEM_NAMESPACE", "XML_DTD_ELEM_REDEFINED", "XML_DTD_EMPTY_NOTATION", "XML_DTD_ENTITY_TYPE", "XML_DTD_ID_FIXED", "XML_DTD_ID_REDEFINED", "XML_DTD_ID_SUBSET", "XML_DTD_INVALID_CHILD", "XML_DTD_INVALID_DEFAULT", "XML_DTD_LOAD_ERROR", "XML_DTD_MISSING_ATTRIBUTE", "XML_DTD_MIXED_CORRUPT", "XML_DTD_MULTIPLE_ID", "XML_DTD_NO_DOC", "XML_DTD_NO_DTD", "XML_DTD_NO_ELEM_NAME", "XML_DTD_NO_PREFIX", "XML_DTD_NO_ROOT", "XML_DTD_NOTATION_REDEFINED", "XML_DTD_NOTATION_VALUE", "XML_DTD_NOT_EMPTY", "XML_DTD_NOT_PCDATA", "XML_DTD_NOT_STANDALONE", "XML_DTD_ROOT_NAME", "XML_DTD_STANDALONE_WHITE_SPACE", "XML_DTD_UNKNOWN_ATTRIBUTE", "XML_DTD_UNKNOWN_ELEM", "XML_DTD_UNKNOWN_ENTITY", "XML_DTD_UNKNOWN_ID", "XML_DTD_UNKNOWN_NOTATION", "XML_DTD_STANDALONE_DEFAULTED", "XML_DTD_XMLID_VALUE", "XML_DTD_XMLID_TYPE", "XML_DTD_DUP_TOKEN", "XML_HTML_STRUCURE_ERROR", "XML_HTML_UNKNOWN_TAG", "XML_RNGP_ANYNAME_ATTR_ANCESTOR", "XML_RNGP_ATTR_CONFLICT", "XML_RNGP_ATTRIBUTE_CHILDREN", "XML_RNGP_ATTRIBUTE_CONTENT", "XML_RNGP_ATTRIBUTE_EMPTY", "XML_RNGP_ATTRIBUTE_NOOP", "XML_RNGP_CHOICE_CONTENT", "XML_RNGP_CHOICE_EMPTY", "XML_RNGP_CREATE_FAILURE", "XML_RNGP_DATA_CONTENT", "XML_RNGP_DEF_CHOICE_AND_INTERLEAVE", "XML_RNGP_DEFINE_CREATE_FAILED", "XML_RNGP_DEFINE_EMPTY", "XML_RNGP_DEFINE_MISSING", "XML_RNGP_DEFINE_NAME_MISSING", "XML_RNGP_ELEM_CONTENT_EMPTY", "XML_RNGP_ELEM_CONTENT_ERROR", "XML_RNGP_ELEMENT_EMPTY", "XML_RNGP_ELEMENT_CONTENT", "XML_RNGP_ELEMENT_NAME", "XML_RNGP_ELEMENT_NO_CONTENT", "XML_RNGP_ELEM_TEXT_CONFLICT", "XML_RNGP_EMPTY", "XML_RNGP_EMPTY_CONSTRUCT", "XML_RNGP_EMPTY_CONTENT", "XML_RNGP_EMPTY_NOT_EMPTY", "XML_RNGP_ERROR_TYPE_LIB", "XML_RNGP_EXCEPT_EMPTY", "XML_RNGP_EXCEPT_MISSING", "XML_RNGP_EXCEPT_MULTIPLE", "XML_RNGP_EXCEPT_NO_CONTENT", "XML_RNGP_EXTERNALREF_EMTPY", "XML_RNGP_EXTERNAL_REF_FAILURE", "XML_RNGP_EXTERNALREF_RECURSE", "XML_RNGP_FORBIDDEN_ATTRIBUTE", "XML_RNGP_FOREIGN_ELEMENT", "XML_RNGP_GRAMMAR_CONTENT", "XML_RNGP_GRAMMAR_EMPTY", "XML_RNGP_GRAMMAR_MISSING", "XML_RNGP_GRAMMAR_NO_START", "XML_RNGP_GROUP_ATTR_CONFLICT", "XML_RNGP_HREF_ERROR", "XML_RNGP_INCLUDE_EMPTY", "XML_RNGP_INCLUDE_FAILURE", "XML_RNGP_INCLUDE_RECURSE", "XML_RNGP_INTERLEAVE_ADD", "XML_RNGP_INTERLEAVE_CREATE_FAILED", "XML_RNGP_INTERLEAVE_EMPTY", "XML_RNGP_INTERLEAVE_NO_CONTENT", "XML_RNGP_INVALID_DEFINE_NAME", "XML_RNGP_INVALID_URI", "XML_RNGP_INVALID_VALUE", "XML_RNGP_MISSING_HREF", "XML_RNGP_NAME_MISSING", "XML_RNGP_NEED_COMBINE", "XML_RNGP_NOTALLOWED_NOT_EMPTY", "XML_RNGP_NSNAME_ATTR_ANCESTOR", "XML_RNGP_NSNAME_NO_NS", "XML_RNGP_PARAM_FORBIDDEN", "XML_RNGP_PARAM_NAME_MISSING", "XML_RNGP_PARENTREF_CREATE_FAILED", "XML_RNGP_PARENTREF_NAME_INVALID", "XML_RNGP_PARENTREF_NO_NAME", "XML_RNGP_PARENTREF_NO_PARENT", "XML_RNGP_PARENTREF_NOT_EMPTY", "XML_RNGP_PARSE_ERROR", "XML_RNGP_PAT_ANYNAME_EXCEPT_ANYNAME", "XML_RNGP_PAT_ATTR_ATTR", "XML_RNGP_PAT_ATTR_ELEM", "XML_RNGP_PAT_DATA_EXCEPT_ATTR", "XML_RNGP_PAT_DATA_EXCEPT_ELEM", "XML_RNGP_PAT_DATA_EXCEPT_EMPTY", "XML_RNGP_PAT_DATA_EXCEPT_GROUP", "XML_RNGP_PAT_DATA_EXCEPT_INTERLEAVE", "XML_RNGP_PAT_DATA_EXCEPT_LIST", "XML_RNGP_PAT_DATA_EXCEPT_ONEMORE", "XML_RNGP_PAT_DATA_EXCEPT_REF", "XML_RNGP_PAT_DATA_EXCEPT_TEXT", "XML_RNGP_PAT_LIST_ATTR", "XML_RNGP_PAT_LIST_ELEM", "XML_RNGP_PAT_LIST_INTERLEAVE", "XML_RNGP_PAT_LIST_LIST", "XML_RNGP_PAT_LIST_REF", "XML_RNGP_PAT_LIST_TEXT", "XML_RNGP_PAT_NSNAME_EXCEPT_ANYNAME", "XML_RNGP_PAT_NSNAME_EXCEPT_NSNAME", "XML_RNGP_PAT_ONEMORE_GROUP_ATTR", "XML_RNGP_PAT_ONEMORE_INTERLEAVE_ATTR", "XML_RNGP_PAT_START_ATTR", "XML_RNGP_PAT_START_DATA", "XML_RNGP_PAT_START_EMPTY", "XML_RNGP_PAT_START_GROUP", "XML_RNGP_PAT_START_INTERLEAVE", "XML_RNGP_PAT_START_LIST", "XML_RNGP_PAT_START_ONEMORE", "XML_RNGP_PAT_START_TEXT", "XML_RNGP_PAT_START_VALUE", "XML_RNGP_PREFIX_UNDEFINED", "XML_RNGP_REF_CREATE_FAILED", "XML_RNGP_REF_CYCLE", "XML_RNGP_REF_NAME_INVALID", "XML_RNGP_REF_NO_DEF", "XML_RNGP_REF_NO_NAME", "XML_RNGP_REF_NOT_EMPTY", "XML_RNGP_START_CHOICE_AND_INTERLEAVE", "XML_RNGP_START_CONTENT", "XML_RNGP_START_EMPTY", "XML_RNGP_START_MISSING", "XML_RNGP_TEXT_EXPECTED", "XML_RNGP_TEXT_HAS_CHILD", "XML_RNGP_TYPE_MISSING", "XML_RNGP_TYPE_NOT_FOUND", "XML_RNGP_TYPE_VALUE", "XML_RNGP_UNKNOWN_ATTRIBUTE", "XML_RNGP_UNKNOWN_COMBINE", "XML_RNGP_UNKNOWN_CONSTRUCT", "XML_RNGP_UNKNOWN_TYPE_LIB", "XML_RNGP_URI_FRAGMENT", "XML_RNGP_URI_NOT_ABSOLUTE", "XML_RNGP_VALUE_EMPTY", "XML_RNGP_VALUE_NO_CONTENT", "XML_RNGP_XMLNS_NAME", "XML_RNGP_XML_NS", "XML_XPATH_EXPRESSION_OK", "XML_XPATH_NUMBER_ERROR", "XML_XPATH_UNFINISHED_LITERAL_ERROR", "XML_XPATH_START_LITERAL_ERROR", "XML_XPATH_VARIABLE_REF_ERROR", "XML_XPATH_UNDEF_VARIABLE_ERROR", "XML_XPATH_INVALID_PREDICATE_ERROR", "XML_XPATH_EXPR_ERROR", "XML_XPATH_UNCLOSED_ERROR", "XML_XPATH_UNKNOWN_FUNC_ERROR", "XML_XPATH_INVALID_OPERAND", "XML_XPATH_INVALID_TYPE", "XML_XPATH_INVALID_ARITY", "XML_XPATH_INVALID_CTXT_SIZE", "XML_XPATH_INVALID_CTXT_POSITION", "XML_XPATH_MEMORY_ERROR", "XML_XPTR_SYNTAX_ERROR", "XML_XPTR_RESOURCE_ERROR", "XML_XPTR_SUB_RESOURCE_ERROR", "XML_XPATH_UNDEF_PREFIX_ERROR", "XML_XPATH_ENCODING_ERROR", "XML_XPATH_INVALID_CHAR_ERROR", "XML_TREE_INVALID_HEX", "XML_TREE_INVALID_DEC", "XML_TREE_UNTERMINATED_ENTITY", "XML_TREE_NOT_UTF8", "XML_SAVE_NOT_UTF8", "XML_SAVE_CHAR_INVALID", "XML_SAVE_NO_DOCTYPE", "XML_SAVE_UNKNOWN_ENCODING", "XML_REGEXP_COMPILE_ERROR", "XML_IO_UNKNOWN", "XML_IO_EACCES", "XML_IO_EAGAIN", "XML_IO_EBADF", "XML_IO_EBADMSG", "XML_IO_EBUSY", "XML_IO_ECANCELED", "XML_IO_ECHILD", "XML_IO_EDEADLK", "XML_IO_EDOM", "XML_IO_EEXIST", "XML_IO_EFAULT", "XML_IO_EFBIG", "XML_IO_EINPROGRESS", "XML_IO_EINTR", "XML_IO_EINVAL", "XML_IO_EIO", "XML_IO_EISDIR", "XML_IO_EMFILE", "XML_IO_EMLINK", "XML_IO_EMSGSIZE", "XML_IO_ENAMETOOLONG", "XML_IO_ENFILE", "XML_IO_ENODEV", "XML_IO_ENOENT", "XML_IO_ENOEXEC", "XML_IO_ENOLCK", "XML_IO_ENOMEM", "XML_IO_ENOSPC", "XML_IO_ENOSYS", "XML_IO_ENOTDIR", "XML_IO_ENOTEMPTY", "XML_IO_ENOTSUP", "XML_IO_ENOTTY", "XML_IO_ENXIO", "XML_IO_EPERM", "XML_IO_EPIPE", "XML_IO_ERANGE", "XML_IO_EROFS", "XML_IO_ESPIPE", "XML_IO_ESRCH", "XML_IO_ETIMEDOUT", "XML_IO_EXDEV", "XML_IO_NETWORK_ATTEMPT", "XML_IO_ENCODER", "XML_IO_FLUSH", "XML_IO_WRITE", "XML_IO_NO_INPUT", "XML_IO_BUFFER_FULL", "XML_IO_LOAD_ERROR", "XML_IO_ENOTSOCK", "XML_IO_EISCONN", "XML_IO_ECONNREFUSED", "XML_IO_ENETUNREACH", "XML_IO_EADDRINUSE", "XML_IO_EALREADY", "XML_IO_EAFNOSUPPORT", "XML_XINCLUDE_RECURSION", "XML_XINCLUDE_PARSE_VALUE", "XML_XINCLUDE_ENTITY_DEF_MISMATCH", "XML_XINCLUDE_NO_HREF", "XML_XINCLUDE_NO_FALLBACK", "XML_XINCLUDE_HREF_URI", "XML_XINCLUDE_TEXT_FRAGMENT", "XML_XINCLUDE_TEXT_DOCUMENT", "XML_XINCLUDE_INVALID_CHAR", "XML_XINCLUDE_BUILD_FAILED", "XML_XINCLUDE_UNKNOWN_ENCODING", "XML_XINCLUDE_MULTIPLE_ROOT", "XML_XINCLUDE_XPTR_FAILED", "XML_XINCLUDE_XPTR_RESULT", "XML_XINCLUDE_INCLUDE_IN_INCLUDE", "XML_XINCLUDE_FALLBACKS_IN_INCLUDE", "XML_XINCLUDE_FALLBACK_NOT_IN_INCLUDE", "XML_XINCLUDE_DEPRECATED_NS", "XML_XINCLUDE_FRAGMENT_ID", "XML_CATALOG_MISSING_ATTR", "XML_CATALOG_ENTRY_BROKEN", "XML_CATALOG_PREFER_VALUE", "XML_CATALOG_NOT_CATALOG", "XML_CATALOG_RECURSION", "XML_SCHEMAP_PREFIX_UNDEFINED", "XML_SCHEMAP_ATTRFORMDEFAULT_VALUE", "XML_SCHEMAP_ATTRGRP_NONAME_NOREF", "XML_SCHEMAP_ATTR_NONAME_NOREF", "XML_SCHEMAP_COMPLEXTYPE_NONAME_NOREF", "XML_SCHEMAP_ELEMFORMDEFAULT_VALUE", "XML_SCHEMAP_ELEM_NONAME_NOREF", "XML_SCHEMAP_EXTENSION_NO_BASE", "XML_SCHEMAP_FACET_NO_VALUE", "XML_SCHEMAP_FAILED_BUILD_IMPORT", "XML_SCHEMAP_GROUP_NONAME_NOREF", "XML_SCHEMAP_IMPORT_NAMESPACE_NOT_URI", "XML_SCHEMAP_IMPORT_REDEFINE_NSNAME", "XML_SCHEMAP_IMPORT_SCHEMA_NOT_URI", "XML_SCHEMAP_INVALID_BOOLEAN", "XML_SCHEMAP_INVALID_ENUM", "XML_SCHEMAP_INVALID_FACET", "XML_SCHEMAP_INVALID_FACET_VALUE", "XML_SCHEMAP_INVALID_MAXOCCURS", "XML_SCHEMAP_INVALID_MINOCCURS", "XML_SCHEMAP_INVALID_REF_AND_SUBTYPE", "XML_SCHEMAP_INVALID_WHITE_SPACE", "XML_SCHEMAP_NOATTR_NOREF", "XML_SCHEMAP_NOTATION_NO_NAME", "XML_SCHEMAP_NOTYPE_NOREF", "XML_SCHEMAP_REF_AND_SUBTYPE", "XML_SCHEMAP_RESTRICTION_NONAME_NOREF", "XML_SCHEMAP_SIMPLETYPE_NONAME", "XML_SCHEMAP_TYPE_AND_SUBTYPE", "XML_SCHEMAP_UNKNOWN_ALL_CHILD", "XML_SCHEMAP_UNKNOWN_ANYATTRIBUTE_CHILD", "XML_SCHEMAP_UNKNOWN_ATTR_CHILD", "XML_SCHEMAP_UNKNOWN_ATTRGRP_CHILD", "XML_SCHEMAP_UNKNOWN_ATTRIBUTE_GROUP", "XML_SCHEMAP_UNKNOWN_BASE_TYPE", "XML_SCHEMAP_UNKNOWN_CHOICE_CHILD", "XML_SCHEMAP_UNKNOWN_COMPLEXCONTENT_CHILD", "XML_SCHEMAP_UNKNOWN_COMPLEXTYPE_CHILD", "XML_SCHEMAP_UNKNOWN_ELEM_CHILD", "XML_SCHEMAP_UNKNOWN_EXTENSION_CHILD", "XML_SCHEMAP_UNKNOWN_FACET_CHILD", "XML_SCHEMAP_UNKNOWN_FACET_TYPE", "XML_SCHEMAP_UNKNOWN_GROUP_CHILD", "XML_SCHEMAP_UNKNOWN_IMPORT_CHILD", "XML_SCHEMAP_UNKNOWN_LIST_CHILD", "XML_SCHEMAP_UNKNOWN_NOTATION_CHILD", "XML_SCHEMAP_UNKNOWN_PROCESSCONTENT_CHILD", "XML_SCHEMAP_UNKNOWN_REF", "XML_SCHEMAP_UNKNOWN_RESTRICTION_CHILD", "XML_SCHEMAP_UNKNOWN_SCHEMAS_CHILD", "XML_SCHEMAP_UNKNOWN_SEQUENCE_CHILD", "XML_SCHEMAP_UNKNOWN_SIMPLECONTENT_CHILD", "XML_SCHEMAP_UNKNOWN_SIMPLETYPE_CHILD", "XML_SCHEMAP_UNKNOWN_TYPE", "XML_SCHEMAP_UNKNOWN_UNION_CHILD", "XML_SCHEMAP_ELEM_DEFAULT_FIXED", "XML_SCHEMAP_REGEXP_INVALID", "XML_SCHEMAP_FAILED_LOAD", "XML_SCHEMAP_NOTHING_TO_PARSE", "XML_SCHEMAP_NOROOT", "XML_SCHEMAP_REDEFINED_GROUP", "XML_SCHEMAP_REDEFINED_TYPE", "XML_SCHEMAP_REDEFINED_ELEMENT", "XML_SCHEMAP_REDEFINED_ATTRGROUP", "XML_SCHEMAP_REDEFINED_ATTR", "XML_SCHEMAP_REDEFINED_NOTATION", "XML_SCHEMAP_FAILED_PARSE", "XML_SCHEMAP_UNKNOWN_PREFIX", "XML_SCHEMAP_DEF_AND_PREFIX", "XML_SCHEMAP_UNKNOWN_INCLUDE_CHILD", "XML_SCHEMAP_INCLUDE_SCHEMA_NOT_URI", "XML_SCHEMAP_INCLUDE_SCHEMA_NO_URI", "XML_SCHEMAP_NOT_SCHEMA", "XML_SCHEMAP_UNKNOWN_MEMBER_TYPE", "XML_SCHEMAP_INVALID_ATTR_USE", "XML_SCHEMAP_RECURSIVE", "XML_SCHEMAP_SUPERNUMEROUS_LIST_ITEM_TYPE", "XML_SCHEMAP_INVALID_ATTR_COMBINATION", "XML_SCHEMAP_INVALID_ATTR_INLINE_COMBINATION", "XML_SCHEMAP_MISSING_SIMPLETYPE_CHILD", "XML_SCHEMAP_INVALID_ATTR_NAME", "XML_SCHEMAP_REF_AND_CONTENT", "XML_SCHEMAP_CT_PROPS_CORRECT_1", "XML_SCHEMAP_CT_PROPS_CORRECT_2", "XML_SCHEMAP_CT_PROPS_CORRECT_3", "XML_SCHEMAP_CT_PROPS_CORRECT_4", "XML_SCHEMAP_CT_PROPS_CORRECT_5", "XML_SCHEMAP_DERIVATION_OK_RESTRICTION_1", "XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_1", "XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_2", "XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_2", "XML_SCHEMAP_DERIVATION_OK_RESTRICTION_3", "XML_SCHEMAP_WILDCARD_INVALID_NS_MEMBER", "XML_SCHEMAP_INTERSECTION_NOT_EXPRESSIBLE", "XML_SCHEMAP_UNION_NOT_EXPRESSIBLE", "XML_SCHEMAP_SRC_IMPORT_3_1", "XML_SCHEMAP_SRC_IMPORT_3_2", "XML_SCHEMAP_DERIVATION_OK_RESTRICTION_4_1", "XML_SCHEMAP_DERIVATION_OK_RESTRICTION_4_2", "XML_SCHEMAP_DERIVATION_OK_RESTRICTION_4_3", "XML_SCHEMAP_COS_CT_EXTENDS_1_3", "XML_SCHEMAV_NOROOT", "XML_SCHEMAV_UNDECLAREDELEM", "XML_SCHEMAV_NOTTOPLEVEL", "XML_SCHEMAV_MISSING", "XML_SCHEMAV_WRONGELEM", "XML_SCHEMAV_NOTYPE", "XML_SCHEMAV_NOROLLBACK", "XML_SCHEMAV_ISABSTRACT", "XML_SCHEMAV_NOTEMPTY", "XML_SCHEMAV_ELEMCONT", "XML_SCHEMAV_HAVEDEFAULT", "XML_SCHEMAV_NOTNILLABLE", "XML_SCHEMAV_EXTRACONTENT", "XML_SCHEMAV_INVALIDATTR", "XML_SCHEMAV_INVALIDELEM", "XML_SCHEMAV_NOTDETERMINIST", "XML_SCHEMAV_CONSTRUCT", "XML_SCHEMAV_INTERNAL", "XML_SCHEMAV_NOTSIMPLE", "XML_SCHEMAV_ATTRUNKNOWN", "XML_SCHEMAV_ATTRINVALID", "XML_SCHEMAV_VALUE", "XML_SCHEMAV_FACET", "XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_1", "XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_2", "XML_SCHEMAV_CVC_DATATYPE_VALID_1_2_3", "XML_SCHEMAV_CVC_TYPE_3_1_1", "XML_SCHEMAV_CVC_TYPE_3_1_2", "XML_SCHEMAV_CVC_FACET_VALID", "XML_SCHEMAV_CVC_LENGTH_VALID", "XML_SCHEMAV_CVC_MINLENGTH_VALID", "XML_SCHEMAV_CVC_MAXLENGTH_VALID", "XML_SCHEMAV_CVC_MININCLUSIVE_VALID", "XML_SCHEMAV_CVC_MAXINCLUSIVE_VALID", "XML_SCHEMAV_CVC_MINEXCLUSIVE_VALID", "XML_SCHEMAV_CVC_MAXEXCLUSIVE_VALID", "XML_SCHEMAV_CVC_TOTALDIGITS_VALID", "XML_SCHEMAV_CVC_FRACTIONDIGITS_VALID", "XML_SCHEMAV_CVC_PATTERN_VALID", "XML_SCHEMAV_CVC_ENUMERATION_VALID", "XML_SCHEMAV_CVC_COMPLEX_TYPE_2_1", "XML_SCHEMAV_CVC_COMPLEX_TYPE_2_2", "XML_SCHEMAV_CVC_COMPLEX_TYPE_2_3", "XML_SCHEMAV_CVC_COMPLEX_TYPE_2_4", "XML_SCHEMAV_CVC_ELT_1", "XML_SCHEMAV_CVC_ELT_2", "XML_SCHEMAV_CVC_ELT_3_1", "XML_SCHEMAV_CVC_ELT_3_2_1", "XML_SCHEMAV_CVC_ELT_3_2_2", "XML_SCHEMAV_CVC_ELT_4_1", "XML_SCHEMAV_CVC_ELT_4_2", "XML_SCHEMAV_CVC_ELT_4_3", "XML_SCHEMAV_CVC_ELT_5_1_1", "XML_SCHEMAV_CVC_ELT_5_1_2", "XML_SCHEMAV_CVC_ELT_5_2_1", "XML_SCHEMAV_CVC_ELT_5_2_2_1", "XML_SCHEMAV_CVC_ELT_5_2_2_2_1", "XML_SCHEMAV_CVC_ELT_5_2_2_2_2", "XML_SCHEMAV_CVC_ELT_6", "XML_SCHEMAV_CVC_ELT_7", "XML_SCHEMAV_CVC_ATTRIBUTE_1", "XML_SCHEMAV_CVC_ATTRIBUTE_2", "XML_SCHEMAV_CVC_ATTRIBUTE_3", "XML_SCHEMAV_CVC_ATTRIBUTE_4", "XML_SCHEMAV_CVC_COMPLEX_TYPE_3_1", "XML_SCHEMAV_CVC_COMPLEX_TYPE_3_2_1", "XML_SCHEMAV_CVC_COMPLEX_TYPE_3_2_2", "XML_SCHEMAV_CVC_COMPLEX_TYPE_4", "XML_SCHEMAV_CVC_COMPLEX_TYPE_5_1", "XML_SCHEMAV_CVC_COMPLEX_TYPE_5_2", "XML_SCHEMAV_ELEMENT_CONTENT", "XML_SCHEMAV_DOCUMENT_ELEMENT_MISSING", "XML_SCHEMAV_CVC_COMPLEX_TYPE_1", "XML_SCHEMAV_CVC_AU", "XML_SCHEMAV_CVC_TYPE_1", "XML_SCHEMAV_CVC_TYPE_2", "XML_SCHEMAV_CVC_IDC", "XML_SCHEMAV_CVC_WILDCARD", "XML_SCHEMAV_MISC", "XML_XPTR_UNKNOWN_SCHEME", "XML_XPTR_CHILDSEQ_START", "XML_XPTR_EVAL_FAILED", "XML_XPTR_EXTRA_OBJECTS", "XML_C14N_CREATE_CTXT", "XML_C14N_REQUIRES_UTF8", "XML_C14N_CREATE_STACK", "XML_C14N_INVALID_NODE", "XML_C14N_UNKNOW_NODE", "XML_C14N_RELATIVE_NAMESPACE", "XML_FTP_PASV_ANSWER", "XML_FTP_EPSV_ANSWER", "XML_FTP_ACCNT", "XML_FTP_URL_SYNTAX", "XML_HTTP_URL_SYNTAX", "XML_HTTP_USE_IP", "XML_HTTP_UNKNOWN_HOST", "XML_SCHEMAP_SRC_SIMPLE_TYPE_1", "XML_SCHEMAP_SRC_SIMPLE_TYPE_2", "XML_SCHEMAP_SRC_SIMPLE_TYPE_3", "XML_SCHEMAP_SRC_SIMPLE_TYPE_4", "XML_SCHEMAP_SRC_RESOLVE", "XML_SCHEMAP_SRC_RESTRICTION_BASE_OR_SIMPLETYPE", "XML_SCHEMAP_SRC_LIST_ITEMTYPE_OR_SIMPLETYPE", "XML_SCHEMAP_SRC_UNION_MEMBERTYPES_OR_SIMPLETYPES", "XML_SCHEMAP_ST_PROPS_CORRECT_1", "XML_SCHEMAP_ST_PROPS_CORRECT_2", "XML_SCHEMAP_ST_PROPS_CORRECT_3", "XML_SCHEMAP_COS_ST_RESTRICTS_1_1", "XML_SCHEMAP_COS_ST_RESTRICTS_1_2", "XML_SCHEMAP_COS_ST_RESTRICTS_1_3_1", "XML_SCHEMAP_COS_ST_RESTRICTS_1_3_2", "XML_SCHEMAP_COS_ST_RESTRICTS_2_1", "XML_SCHEMAP_COS_ST_RESTRICTS_2_3_1_1", "XML_SCHEMAP_COS_ST_RESTRICTS_2_3_1_2", "XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_1", "XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_2", "XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_3", "XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_4", "XML_SCHEMAP_COS_ST_RESTRICTS_2_3_2_5", "XML_SCHEMAP_COS_ST_RESTRICTS_3_1", "XML_SCHEMAP_COS_ST_RESTRICTS_3_3_1", "XML_SCHEMAP_COS_ST_RESTRICTS_3_3_1_2", "XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_2", "XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_1", "XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_3", "XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_4", "XML_SCHEMAP_COS_ST_RESTRICTS_3_3_2_5", "XML_SCHEMAP_COS_ST_DERIVED_OK_2_1", "XML_SCHEMAP_COS_ST_DERIVED_OK_2_2", "XML_SCHEMAP_S4S_ELEM_NOT_ALLOWED", "XML_SCHEMAP_S4S_ELEM_MISSING", "XML_SCHEMAP_S4S_ATTR_NOT_ALLOWED", "XML_SCHEMAP_S4S_ATTR_MISSING", "XML_SCHEMAP_S4S_ATTR_INVALID_VALUE", "XML_SCHEMAP_SRC_ELEMENT_1", "XML_SCHEMAP_SRC_ELEMENT_2_1", "XML_SCHEMAP_SRC_ELEMENT_2_2", "XML_SCHEMAP_SRC_ELEMENT_3", "XML_SCHEMAP_P_PROPS_CORRECT_1", "XML_SCHEMAP_P_PROPS_CORRECT_2_1", "XML_SCHEMAP_P_PROPS_CORRECT_2_2", "XML_SCHEMAP_E_PROPS_CORRECT_2", "XML_SCHEMAP_E_PROPS_CORRECT_3", "XML_SCHEMAP_E_PROPS_CORRECT_4", "XML_SCHEMAP_E_PROPS_CORRECT_5", "XML_SCHEMAP_E_PROPS_CORRECT_6", "XML_SCHEMAP_SRC_INCLUDE", "XML_SCHEMAP_SRC_ATTRIBUTE_1", "XML_SCHEMAP_SRC_ATTRIBUTE_2", "XML_SCHEMAP_SRC_ATTRIBUTE_3_1", "XML_SCHEMAP_SRC_ATTRIBUTE_3_2", "XML_SCHEMAP_SRC_ATTRIBUTE_4", "XML_SCHEMAP_NO_XMLNS", "XML_SCHEMAP_NO_XSI", "XML_SCHEMAP_COS_VALID_DEFAULT_1", "XML_SCHEMAP_COS_VALID_DEFAULT_2_1", "XML_SCHEMAP_COS_VALID_DEFAULT_2_2_1", "XML_SCHEMAP_COS_VALID_DEFAULT_2_2_2", "XML_SCHEMAP_CVC_SIMPLE_TYPE", "XML_SCHEMAP_COS_CT_EXTENDS_1_1", "XML_SCHEMAP_SRC_IMPORT_1_1", "XML_SCHEMAP_SRC_IMPORT_1_2", "XML_SCHEMAP_SRC_IMPORT_2", "XML_SCHEMAP_SRC_IMPORT_2_1", "XML_SCHEMAP_SRC_IMPORT_2_2", "XML_SCHEMAP_INTERNAL", "XML_SCHEMAP_NOT_DETERMINISTIC", "XML_SCHEMAP_SRC_ATTRIBUTE_GROUP_1", "XML_SCHEMAP_SRC_ATTRIBUTE_GROUP_2", "XML_SCHEMAP_SRC_ATTRIBUTE_GROUP_3", "XML_SCHEMAP_MG_PROPS_CORRECT_1", "XML_SCHEMAP_MG_PROPS_CORRECT_2", "XML_SCHEMAP_SRC_CT_1", "XML_SCHEMAP_DERIVATION_OK_RESTRICTION_2_1_3", "XML_SCHEMAP_AU_PROPS_CORRECT_2", "XML_SCHEMAP_A_PROPS_CORRECT_2", "XML_SCHEMAP_C_PROPS_CORRECT", "XML_SCHEMAP_SRC_REDEFINE", "XML_SCHEMAP_SRC_IMPORT", "XML_SCHEMAP_WARN_SKIP_SCHEMA", "XML_SCHEMAP_WARN_UNLOCATED_SCHEMA", "XML_SCHEMAP_WARN_ATTR_REDECL_PROH", "XML_SCHEMAP_WARN_ATTR_POINTLESS_PROH", "XML_SCHEMAP_AG_PROPS_CORRECT", "XML_SCHEMAP_COS_CT_EXTENDS_1_2", "XML_SCHEMAP_AU_PROPS_CORRECT", "XML_SCHEMAP_A_PROPS_CORRECT_3", "XML_SCHEMAP_COS_ALL_LIMITED", "XML_SCHEMATRONV_ASSERT", "XML_SCHEMATRONV_REPORT", "XML_MODULE_OPEN", "XML_MODULE_CLOSE", "XML_CHECK_FOUND_ELEMENT", "XML_CHECK_FOUND_ATTRIBUTE", "XML_CHECK_FOUND_TEXT", "XML_CHECK_FOUND_CDATA", "XML_CHECK_FOUND_ENTITYREF", "XML_CHECK_FOUND_ENTITY", "XML_CHECK_FOUND_PI", "XML_CHECK_FOUND_COMMENT", "XML_CHECK_FOUND_DOCTYPE", "XML_CHECK_FOUND_FRAGMENT", "XML_CHECK_FOUND_NOTATION", "XML_CHECK_UNKNOWN_NODE", "XML_CHECK_ENTITY_TYPE", "XML_CHECK_NO_PARENT", "XML_CHECK_NO_DOC", "XML_CHECK_NO_NAME", "XML_CHECK_NO_ELEM", "XML_CHECK_WRONG_DOC", "XML_CHECK_NO_PREV", "XML_CHECK_WRONG_PREV", "XML_CHECK_NO_NEXT", "XML_CHECK_WRONG_NEXT", "XML_CHECK_NOT_DTD", "XML_CHECK_NOT_ATTR", "XML_CHECK_NOT_ATTR_DECL", "XML_CHECK_NOT_ELEM_DECL", "XML_CHECK_NOT_ENTITY_DECL", "XML_CHECK_NOT_NS_DECL", "XML_CHECK_NO_HREF", "XML_CHECK_WRONG_PARENT", "XML_CHECK_NS_SCOPE", "XML_CHECK_NS_ANCESTOR", "XML_CHECK_NOT_UTF8", "XML_CHECK_NO_DICT", "XML_CHECK_NOT_NCNAME", "XML_CHECK_OUTSIDE_DICT", "XML_CHECK_WRONG_NAME", "XML_CHECK_NAME_NOT_NULL", "XML_I18N_NO_NAME", "XML_I18N_NO_HANDLER", "XML_I18N_EXCESS_HANDLER", "XML_I18N_CONV_FAILED", "XML_I18N_NO_OUTPUT" )) XMLDomainErrors <- structure(0:28, .Names = c("NONE", "PARSER", "TREE", "NAMESPACE", "DTD", "HTML", "MEMORY", "OUTPUT", "IO", "FTP", "HTTP", "XINCLUDE", "XPATH", "XPOINTER", "REGEXP", "DATATYPE", "SCHEMASP", "SCHEMASV", "RELAXNGP", "RELAXNGV", "CATALOG", "C14N", "XSLT", "VALID", "CHECK", "WRITER", "MODULE", "I18N", "SCHEMATRONV"))
library(forecast) ?nhtemp par(mfrow=c(1,1)) plot(nhtemp) (fitse = ets(nhtemp, model='ANN')) (fitse2 = ses(nhtemp)) forecast(fitse,3) plot(forecast(fitse,c(3))) accuracy(fitse) TS = level + slope * t + irregular plot(AirPassengers) plot(log(AirPassengers)) (fithe = ets(log(AirPassengers), model='AAA')) (pred = forecast(fithe, 5)) plot(pred, main='Forecast for Air Travel', ylab='Log (Air Passengers)', xlab='Time') pred$mean (pred$mean = exp(pred$mean)) (pred$lower = exp(pred$lower)) (pred$upper = exp(pred$upper)) (p = cbind(pred$mean, pred$lower, pred$upper)) (pred$mean = exp(pred$mean)) TS = level + slope * t + s(t) + irregular fit <- HoltWinters(nhtemp, beta=FALSE, gamma=FALSE) fit forecast(fit, 1) plot(forecast(fit, 1), xlab="Year", ylab=expression(paste("Temperature (", degree*F,")",)), main="New Haven Annual Mean Temperature") accuracy(fit) fit <- HoltWinters(log(AirPassengers)) fit accuracy(fit) pred <- forecast(fit, 5) pred plot(pred, main="Forecast for Air Travel", ylab="Log(AirPassengers)", xlab="Time") pred$mean <- exp(pred$mean) pred$lower <- exp(pred$lower) pred$upper <- exp(pred$upper) p <- cbind(pred$mean, pred$lower, pred$upper) dimnames(p)[[2]] <- c("mean", "Lo 80", "Lo 95", "Hi 80", "Hi 95") p library(forecast) fit <- ets(JohnsonJohnson) fit plot(forecast(fit), main="Johnson and Johnson Forecasts", ylab="Quarterly Earnings (Dollars)", xlab="Time") library(forecast) library(tseries) plot(Nile) ndiffs(Nile) dNile <- diff(Nile) plot(dNile) adf.test(dNile) library(forecast) ?auto.arima ?arima
"plot.sucra" <- function(x, legend.position = "none", ...) { nT <- length(x$SUCRA) cumeffectiveness <- apply(x$rankprob, 2, cumsum) names <- x$names gglist <- vector(mode = "list", nT) for (TRT in 1:nT) { Area=round(x$SUCRA[TRT], 3) ddd <- data.frame(trt = names, CDF = cumeffectiveness[,TRT], PDF = x$rankprob[,TRT], stringAsFactors = FALSE) ddd$trt <- factor(ddd$trt, levels = ddd$trt) bb <- ggplot(ddd, aes(x = trt, group = 1)) + geom_line(aes(y = CDF), color = " geom_line(aes(y = PDF), color = rgb(0, 157, 114, maxColorValue = 255), linetype = "twodash", size = 1) + theme_gray() + theme(legend.position = legend.position) + ylab("Probability") + labs(title = paste0("Trt (", names[TRT], "): ", Area)) gglist[[TRT]] <- bb } do.call(grid.arrange, gglist) invisible(gglist) }
test_that("best_tau works", { skip_on_cran() skip_if(getRversion() < "3.6.0") img <- ijtiff::read_tif(system.file("extdata", "bleached.tif", package = "detrendr" ), msg = FALSE) expect_error( best_tau(img), paste0( "You must choose \\*either\\* 'FCS' \\*or\\* 'FFS' for\\s?", "`purpose`." ) ) set.seed(1) expect_equal(round(best_tau(img, purpose = "ffs", parallel = 2)), 34, tolerance = 2 ) img_2ch <- abind::abind(img, img, along = 3) set.seed(1) t1 <- best_tau(img_2ch, purpose = "fcs") expect_equal(length(t1), 2) set.seed(1) t2 <- best_tau(img_2ch, purpose = "fcs") expect_equal(t1, t2, tolerance = 1) img <- array(rpois(99^3, 99), dim = rep(99, 3)) bt <- best_tau(img, purpose = "ffs") if (!is.na(bt)) { expect_gt(bt, 150) } img[] <- 0 expect_error( best_tau(img, purpose = "fcs"), "all pixel values are equal to 0" ) }) test_that("best_l works", { skip_on_cran() img <- ijtiff::read_tif(system.file("extdata", "bleached.tif", package = "detrendr" ), msg = FALSE) expect_error( best_l(img), paste0( "You must choose \\*either\\* 'FCS' \\*or\\* 'FFS' for\\s?", "`purpose`." ) ) set.seed(1) expect_equal(round(best_l(img, parallel = 2, purpose = "ffs")), 17, tolerance = 2 ) img_2ch <- abind::abind(img, img, along = 3) set.seed(1) l1 <- best_l(img_2ch, purpose = "fcs") expect_equal(length(l1), 2) expect_equal(mean(l1), 17, tolerance = 2) set.seed(4) img <- array(rpois(99^3, 99), dim = rep(99, 3)) bt <- round(best_tau(img, purpose = "ffs")) if (!is.na(bt)) { expect_equal(bt, 28372, tolerance = 28200) } img[] <- 0 expect_error(best_l(img, purpose = "ffs"), "all pixel values are equal to 0") img <- array(round(seq(0, .Machine$integer.max, length.out = 2^3)), dim = rep(2, 3) ) expect_error( best_l(img, purpose = "ffs"), "Even with.*the most severe detrend" ) skip_if_not_installed("abind") }) test_that("best_degree works", { skip_on_cran() img <- ijtiff::read_tif(system.file("extdata", "bleached.tif", package = "detrendr" ), msg = FALSE) expect_error( best_degree(img), paste0( "You must choose \\*either\\* 'FCS' \\*or\\* 'FFS' for\\s?", "`purpose`." ) ) set.seed(1) best_degree <- suppressWarnings(round(best_degree(img, purpose = "ffs"))) expect_equal(best_degree, 17, tolerance = 2) img_2ch <- abind::abind(img, img, along = 3) d1 <- suppressWarnings(best_degree(img_2ch, purpose = "fcs")) expect_equal(length(d1), 2) expect_equal(mean(d1), 17, tolerance = 2) set.seed(7) img <- array(rpois(99^3, 99), dim = rep(99, 3)) best_degree <- suppressWarnings(round(best_degree(img, purpose = "ffs"))) expect_equal(best_degree, NA_real_) img[] <- 0 expect_error( best_degree(img, purpose = "ffs"), "all pixel values are equal to 0" ) }) test_that("best_swaps() works", { img <- ijtiff::read_tif(system.file("extdata", "bleached.tif", package = "detrendr" )) set.seed(1) expect_equal(best_swaps(img, quick = TRUE), 1588366, tolerance = 4000) expect_error( best_swaps(array(7, dim = rep(1, 4))), paste( "Your image is constant: all pixel values are equal to 7.+", "This type of image is not detrendable." ) ) for (i in seq_len(77)) { set.seed(i) sim_img <- array(rpois(6^4, 8), dim = rep(6, 4)) expect_lt( sum(best_swaps(sim_img, quick = TRUE)), sum(sim_img) * dim(sim_img)[3] ) } })
library(odr) myod1 <- od.2(icc = 0.2, r12 = 0.5, r22 = 0.5, c1 = 1, c2 = 5, c1t = 1, c2t = 50, varlim = c(0.01, 0.02)) myod2 <- od.2(icc = 0.2, r12 = 0.5, r22 = 0.5, c1 = 1, c2 = 5, c1t = 1, c2t = 50, plot.by = list(p = "p"), n = 20, varlim = c(0.005, 0.030)) myod3 <- od.2(icc = 0.2, r12 = 0.5, r22 = 0.5, c1 = 1, c2 = 5, c1t = 1, c2t = 50, p = 0.5, varlim = c(0.005, 0.020)) myod4 <- od.2(icc = 0.2, r12 = 0.5, r22 = 0.5, c1 = 1, c2 = 5, c1t = 1, c2t = 50, plots = FALSE, n = 20, p = 0.5, varlim = c(0.005, 0.025)) mym <- power.2(expr = myod1, d = 0.3, q = 1, power = 0.8) figure <- par(mfrow = c(1, 2)) budget <- NULL nrange <- c(2:50) for (n in nrange) budget <- c(budget, power.2(expr = myod1, constraint = list (n = n), d = 0.3, q = 1, power = 0.8)$out$m) plot(nrange, budget, type = "l", lty = 1, xlim = c(0, 50), ylim = c(1500, 3500), xlab = "Level-1 sample size: n", ylab = "Budget", main = "", col = "black") abline(v = 9, lty = 2, col = "Blue") budget <- NULL prange <- seq(0.05, 0.95, by = 0.005) for (p in prange) budget <- c(budget, power.2(expr = myod1, constraint = list (p = p), d = 0.3, q = 1, power = 0.8)$out$m) plot(prange, budget, type = "l", lty = 1, xlim = c(0, 1), ylim = c(1500, 7000), xlab = "Porportion groups in treatment: p", ylab = "Budget", main = "", col = "black") abline(v = 0.33, lty = 2, col = "Blue") par(figure) mypower <- power.2(expr = myod1, q = 1, d = 0.3, m = 1702) figure <- par(mfrow = c (1, 2)) pwr <- NULL nrange <- c(2:50) for (n in nrange) pwr <- c(pwr, power.2(expr = myod1, constraint = list (n = n), d = 0.3, q = 1, m = 1702)$out) plot(nrange, pwr, type = "l", lty = 1, xlim = c(0, 50), ylim = c(0.4, 0.9), xlab = "Level-1 sample size: n", ylab = "Power", main = "", col = "black") abline(v = 9, lty = 2, col = "Blue") pwr <- NULL prange <- seq(0.05, 0.95, by = 0.005) for (p in prange) pwr <- c(pwr, power.2(expr = myod1, constraint = list (p = p), d = 0.3, q = 1, m = 1702)$out) plot(prange, pwr, type = "l", lty = 1, xlim = c(0, 1), ylim = c(0.1, 0.9), xlab = "Porportion groups in treatment: p", ylab = "Power", main = "", col = "black") abline(v = 0.33, lty = 2, col = "Blue") par(figure) mymdes <- power.2(expr = myod1, q = 1, power = 0.80, m = 1702) figure <- par(mfrow = c (1, 2)) MDES <- NULL nrange <- c(2:50) for (n in nrange) MDES <- c(MDES, power.2(expr = myod1, constraint = list (n = n), power = 0.8, q = 1, m = 1702)$out) plot(nrange, MDES, type = "l", lty = 1, xlim = c(0, 50), ylim = c(0.3, 0.8), xlab = "Level-1 sample size: n", ylab = "MDES", main = "", col = "black") abline(v = 9, lty = 2, col = "Blue") MDES <- NULL prange <- seq(0.05, 0.95, by = 0.005) for (p in prange) MDES <- c(MDES, power.2(expr = myod1, constraint = list (p = p), power = 0.8, q = 1, m = 1702)$out) plot(prange, MDES, type = "l", lty = 1, xlim = c(0, 1), ylim = c(0.3, 0.8), xlab = "Porportion groups in treatment: p", ylab = "MDES", main = "", col = "black") abline(v = 0.33, lty = 2, col = "Blue") par(figure) myJ <- power.2(cost.model = FALSE, expr = myod1, d = 0.3, q = 1, power = 0.8) myJ$out mypower1 <- power.2(cost.model = FALSE, expr = myod1, J = 59, d = 0.3, q = 1) mypower1$out mymdes1 <- power.2(cost.model = FALSE, expr = myod1, J = 59, power = 0.8, q = 1) mymdes1$out figure <- par(mfrow = c (1, 2)) pwr <- NULL mrange <- c(300:3000) for (m in mrange) pwr <- c(pwr, power.2(expr = myod1, d = 0.3, q = 1, m = m)$out) plot(mrange, pwr, type = "l", lty = 1, xlim = c(300, 3000), ylim = c(0, 1), xlab = "Budget", ylab = "Power", main = "", col = "black") abline(v = 1702, lty = 2, col = "Blue") pwr <- NULL Jrange <- c(4:100) for (J in Jrange) pwr <- c(pwr, power.2(expr = myod1, cost.model = FALSE, d = 0.3, q = 1, J = J)$out) plot(Jrange, pwr, type = "l", lty = 1, xlim = c(4, 100), ylim = c(0, 1), xlab = "Level-2 sample size: J", ylab = "Power", main = "", col = "black") abline(v = 59, lty = 2, col = "Blue") par(figure) myre <- re(od = myod1, subod= myod2) myre$re myre <- re(od = myod1, subod= myod3) myre <- re(od = myod1, subod= myod4)
context("ml fpm prefixspan") test_that("ml_prefixspan() works as expected", { test_requires_version("2.4.0", "prefixspan requires spark 2.4.0+") skip_on_arrow() sc <- testthat_spark_connection() df <- tibble::tibble( seq = list( list(list(1, 2), list(3)), list(list(1), list(3, 2), list(1, 2)), list(list(1, 2), list(5)), list(list(6)) ) ) sdf <- copy_to(sc, df, overwrite = TRUE) prefix_span_model <- ml_prefixspan( sc, seq_col = "seq", min_support = 0.5, max_pattern_length = 5, max_local_proj_db_size = 32000000 ) res <- prefix_span_model$frequent_sequential_patterns(sdf) %>% collect() expect_equal(nrow(res), 5) expect_setequal( lapply(seq(nrow(res)), function(i) as.list(res[i,])), list( list(sequence = list(list(list(3))), freq = 2), list(sequence = list(list(list(2))), freq = 3), list(sequence = list(list(list(1))), freq = 3), list(sequence = list(list(list(1, 2))), freq = 3), list(sequence = list(list(list(1), list(3))), freq = 2) ) ) })
context("packages") test_that("packages", { reg = makeTestRegistry(packages = "MASS") expect_true(is.list(reg$packages) && setequal(names(reg$packages), c("BatchJobs", "MASS"))) reg = addRegistryPackages(reg, "testthat") expect_true(is.list(reg$packages) && setequal(names(reg$packages), c("BatchJobs", "MASS", "testthat"))) reg = addRegistryPackages(reg, "checkmate") expect_true(is.list(reg$packages) && setequal(names(reg$packages), c("BatchJobs", "MASS", "testthat", "checkmate"))) reg = removeRegistryPackages(reg, "testthat") expect_true(is.list(reg$packages) && setequal(names(reg$packages), c("BatchJobs", "MASS", "checkmate"))) reg = removeRegistryPackages(reg, "MASS") expect_true(is.list(reg$packages) && setequal(names(reg$packages), c("BatchJobs", "checkmate"))) reg = setRegistryPackages(reg, c("MASS", "checkmate")) expect_true(is.list(reg$packages) && setequal(names(reg$packages), c("BatchJobs", "MASS", "checkmate"))) reg = addRegistryPackages(reg, "BatchJobs") expect_true(is.list(reg$packages) && setequal(names(reg$packages), c("BatchJobs", "MASS", "checkmate"))) })
`func.mode` <- function(functions, h = 0.20) { depth.mode(functions) }
library(RJcluster) high_balanced = simulate_HD_data() low_balanced = simulate_HD_data(signal_variance = 2) high_unbalanced = simulate_HD_data(size_vector = c(20, 20, 80, 80)) print(dim(high_balanced$X)) print(dim(low_balanced$X)) print(dim(high_unbalanced$X)) res_high_balanced = RJclust(data = high_balanced$X) res_low_balanced = RJclust(data = low_balanced$X) res_high_unbalanced = RJclust(data = high_unbalanced$X) results = list(res_high_balanced, res_low_balanced, res_high_unbalanced) data = list(high_balanced, low_balanced, high_unbalanced, high_balanced, low_balanced, high_unbalanced) for (i in 1:length(results)) { temp_results = results[[i]] mi = Mutual_Information(temp_results$class, data[[i]]$Y) print(paste("Number of classes found:", temp_results$K, "NMI:", round(mi$nmi,2), "AMI", round(mi$ami,2))) }
ldl <- function(x, tol) { if(length(x) == 1) { if(x >= 0) return(matrix(x)) if(x < 0) stop("Matrix x is not positive semidefinite.") } if (missing(tol)) { tol <- max(100, max(abs(diag(as.matrix(x))))) * .Machine$double.eps } if (!isSymmetric(x, tol = tol)) stop("Matrix is not symmetric!") out <- .Fortran(fldl, x = x, as.integer(dim(x)[1]), tol = tol, info = integer(1)) if (out$info != 0) stop("Matrix x is not positive semidefinite.") out$x }
library(plumber) cars_lm <- lm(mpg ~ cyl + disp, data = mtcars) v <- vetiver_model(cars_lm, "cars1") test_that("default endpoint", { p <- pr() %>% vetiver_pr_predict(v) expect_equal(names(p$routes), c("ping", "predict")) expect_equal(map_chr(p$routes, "verbs"), c(ping = "GET", predict = "POST")) }) test_that("default endpoint via modular functions", { p1 <- pr() %>% vetiver_pr_predict(v) p2 <- pr() %>% vetiver_pr_post(v) %>% vetiver_pr_docs(v) expect_equal(p1$endpoints, p2$endpoints) expect_equal(p1$routes, p2$routes) }) test_that("pin URL endpoint", { v$metadata <- list(url = "potato") p <- pr() %>% vetiver_pr_predict(v) expect_equal(names(p$routes), c("pin-url", "ping", "predict")) expect_equal(map_chr(p$routes, "verbs"), c(`pin-url` = "GET", ping = "GET", predict = "POST")) }) test_that("default OpenAPI spec", { v$metadata <- list(url = "potatoes") p <- pr() %>% vetiver_pr_predict(v) car_spec <- p$getApiSpec() post_spec <- car_spec$paths$`/predict`$post expect_equal(names(post_spec), c("summary", "requestBody", "responses")) expect_equal(as.character(post_spec$summary), "Return predictions from model using 2 features") expect_equal(post_spec$requestBody$content$`application/json`$schema$items, list(type = "object", properties = list(cyl = list(type = "number"), disp = list(type = "number")))) get_spec <- car_spec$paths$`/pin-url`$get expect_equal(as.character(get_spec$summary), "Get URL of pinned vetiver model") }) test_that("OpenAPI spec is the same for modular functions", { v$metadata <- list(url = "potatoes") p1 <- pr() %>% vetiver_pr_predict(v) p2 <- pr() %>% vetiver_pr_post(v) %>% vetiver_pr_docs(v) spec1 <- p1$getApiSpec() spec2 <- p2$getApiSpec() expect_equal(spec1, spec2) }) test_that("OpenAPI spec for save_ptype = FALSE", { v1 <- vetiver_model(cars_lm, "cars1", save_ptype = FALSE) p <- pr() %>% vetiver_pr_predict(v1) expect_equal(names(p$routes), c("ping", "predict")) expect_equal(map_chr(p$routes, "verbs"), c(ping = "GET", predict = "POST")) car_spec <- p$getApiSpec() post_spec <- car_spec$paths$`/predict`$post expect_equal(names(post_spec), c("summary", "requestBody", "responses")) expect_equal(as.character(post_spec$summary), "Return predictions from model") expect_equal(names(post_spec$requestBody$content$`application/json`$schema$items), c("type", "properties")) }) test_that("OpenAPI spec with custom ptype", { car_ptype <- mtcars[15:16, 2:3] v <- vetiver_model(cars_lm, "cars1", b, save_ptype = car_ptype) p <- pr() %>% vetiver_pr_predict(v) car_spec <- p$getApiSpec() post_spec <- car_spec$paths$`/predict`$post expect_equal(names(post_spec), c("summary", "requestBody", "responses")) expect_equal(as.character(post_spec$summary), "Return predictions from model using 2 features") expect_equal(post_spec$requestBody$content$`application/json`$schema$items, list(type = "object", properties = list(cyl = list(type = "number"), disp = list(type = "number")))) expect_equal(post_spec$requestBody$content$`application/json`$schema$example, purrr::transpose(car_ptype)) }) test_that("OpenAPI spec with additional endpoint", { v$metadata <- list(url = "potatoes") another_handler <- function(req) { newdata <- req$body sum(newdata[names(v$ptype)]) } p <- pr() %>% vetiver_pr_post(v) %>% pr_post(path = "/sum", handler = another_handler) %>% vetiver_pr_docs(v) car_spec <- p$getApiSpec() expect_equal(sort(names(car_spec$paths)), sort(paste0("/", names(p$routes)))) post_spec <- car_spec$paths$`/predict`$post sum_spec <- car_spec$paths$`/sum`$post expect_equal(names(post_spec), c("summary", "requestBody", "responses")) expect_equal(names(sum_spec), c("summary", "requestBody", "responses")) expect_equal(as.character(post_spec$summary), "Return predictions from model using 2 features") expect_equal(as.character(sum_spec$summary), "Return /sum from model using 2 features") items <- list(type = "object", properties = list(cyl = list(type = "number"), disp = list(type = "number"))) expect_equal(post_spec$requestBody$content$`application/json`$schema$items, items) expect_equal(sum_spec$requestBody$content$`application/json`$schema$items, items) }) test_that("debug listens to `is_interactive()`", { rlang::with_interactive(value = FALSE, { p <- pr() %>% vetiver_pr_predict(v) expect_equal(p$getDebug(), FALSE) }) rlang::with_interactive(value = TRUE, { p <- pr() %>% vetiver_pr_predict(v) expect_equal(p$getDebug(), TRUE) }) })
catColorPal <- function(x, levels = NULL, colors = NULL, naCol = " if (is.null(levels)) { if (is.factor(x)) levels <- levels(x) else levels <- unique(x) } if (is.null(colors)) colors <- DEFAULT_CAT_COLORS colors <- rep(colors, length.out = length(levels)) names(colors) <- levels res <- unname(colors[as.character(x)]) res[is.na(res)] <- naCol attr(res, "levels") <- levels attr(res, "pal") <- colors res }
maskFile <- function(shp_poligon, nam="RSIP_", dimname=c(17,26)) { cuenca<-readOGR('.',shp_poligon) cuenca<- spTransform(cuenca, CRS('+proj=longlat +datum=WGS84')) files<- list.files(pattern='.tif') imageraster <- raster(files[1]) imageraster <- crop(imageraster, cuenca) imageraster <- mask(imageraster, cuenca) names(imageraster) <- substr(files[1], dimname[1], dimname[2]) names(imageraster) <- paste0(nam,names(imageraster)) cat(sprintf('\n RSIP: Processing raster %s \n',names(imageraster))) writeRaster(imageraster,names(imageraster), format = "GTiff",overwrite = T) if(length(files)>=2){ for (i in 2:length(files)) { imageraster <- raster(files[i]) imageraster <- crop(imageraster, cuenca) imageraster <- mask(imageraster, cuenca) names(imageraster) <- substr(files[i], dimname[1], dimname[2]) names(imageraster) <- paste0(nam,names(imageraster)) writeRaster(imageraster, names(imageraster), format = "GTiff",overwrite = T) cat(sprintf('RSIP: Processing raster %s \n',names(imageraster))) } } } exportValueGrid <- function() { files<- list.files(pattern='.tif') imageraster <- raster(files[1]) cat(sprintf('\n RSIP: Processing raster %s \n',names(imageraster))) val<-rasterToPoints(imageraster) combine<-cbind(val[,1],val[,2],val[,3]) if(length(files)>=2){ for (i in 2:length(files)) { imageraster <- raster(files[i]) val<-rasterToPoints(imageraster) combine<-cbind(combine,val[,3]) cat(sprintf('RSIP: Processing raster %s \n',names(imageraster))) } } write.table(combine,paste0('RSIP_ValueGrid','.txt')) cat('\nRSIP: Successful Analysis! - The Values were printed correctly \n') } exportValuePoligon <- function(shp_poligon) { cuenca <- readOGR('.',shp_poligon) files<- list.files(pattern='.tif') imageraster <- raster(files[1]) cat(sprintf('RSIP: Processing raster %s \n',names(imageraster))) rbrick <- imageraster if(length(files)>=2){ for (i in 2:length(files)) { imageraster <- raster(files[i]) rbrick <- addLayer(rbrick,imageraster) cat(sprintf('RSIP: Processing raster %s \n',names(imageraster))) } } cat('\n RSIP: Extracting basin values...\n') Pm_c <-extract(rbrick, cuenca[1:1, ]) write.table(Pm_c, file = paste0('RSIP_ValuePoligono','.csv'),row.names=T, na="",col.names=T, sep="\t") cat('\nRSIP: Successful Analysis! - The Values were printed correctly \n') } exportValuePointShp <- function(shp_station) { estaciones <- readOGR('.',shp_station) estaciones.ll <- spTransform(estaciones, CRS("+proj=longlat")) files<- list.files(pattern='.tif') imageraster <- raster(files[1]) cat(sprintf('RSIP: Processing raster %s \n',names(imageraster))) rbrick <- imageraster if(length(files)>=2){ for (i in 2:length(files)) { imageraster <- raster(files[i]) rbrick <- addLayer(rbrick,imageraster) cat(sprintf('RSIP: Processing raster %s \n',names(imageraster))) } } cat('\n RSIP: Extracting Values from Stations...\n') Pm_e <-extract(rbrick,estaciones) name_station<-estaciones@data[[1]] row.names(Pm_e)<- name_station write.table(Pm_e,paste0('RSIP_ValuePointShp','.txt')) cat('\nRSIP: Successful Analysis! - The Values were printed correctly \n') } exportValuePointsTxt<- function(txt_xy) { xy<-cbind(txt_xy[,1],txt_xy[,2]) files<- list.files(pattern='.tif') imageraster <- raster(files[1]) cat(sprintf('RSIP: Processing raster %s \n',names(imageraster))) rbrick <- imageraster if(length(files)>=2){ for (i in 2:length(files)) { imageraster <- raster(files[i]) rbrick <- addLayer(rbrick,imageraster) cat(sprintf('Processing raster %s \n',names(imageraster))) } } cat('\n RSIP: Extracting Values from File...\n') Pm_e <-extract(rbrick,xy) df1 <- data.frame(Pe = Pm_e) rownames(df1) <- txt_xy[,3] write.table(df1,paste0('RSIP_ValuePointsTxt','.txt')) print(df1) cat('\nRSIP: Successful Analysis! - The Values were printed correctly \n') } plotAll <- function(dimplot = c(3,4), color = c("red", "yellow",'green3',"cyan", "blue"), zlim=c(-10,2000), dimname=c(17,23)) { files<- list.files(pattern='.tif') imageraster <- raster(files[1]) names(imageraster) <- substr(files[1], dimname[1], dimname[2]) cat(sprintf('RSIP: Processing raster %s \n',names(imageraster))) rbrick <- imageraster if(length(files)>=2){ for (i in 2:length(files)) { imageraster <- raster(files[i]) names(imageraster) <- substr(files[i], dimname[1], dimname[2]) rbrick <- addLayer(rbrick,imageraster) cat(sprintf('RSIP: Processing raster %s \n',names(imageraster))) } } spplot(rbrick,layout=dimplot, zlim = zlim, col.regions=colorRampPalette(color)(255)) cat('\nRSIP: Successful Analysis! - The imagen were printed correctly \n') } trmmToTiff <- function() { files<- list.files(pattern='.nc4') for (i in 1:length(files)) { dat.ncdf4 <- nc_open(files[i]) lon <- ncvar_get(dat.ncdf4, 'lon') lat <- ncvar_get(dat.ncdf4, 'lat') Pdiario <- ncvar_get(dat.ncdf4, 'precipitation') d1 <- expand.grid(x = lon, y = lat) p<-as.vector(t(Pdiario)) df <- data.frame( x = d1$x, y = d1$y, P_daily = p) dfr<-rasterFromXYZ(df) projection(dfr) <- CRS("+proj=longlat +datum=WGS84") writeRaster(dfr, filename = dat.ncdf4$filename, format = 'GTiff', overwrite = T) cat(sprintf('RSIP: Processesing raster %s \n',dat.ncdf4$filename)) } }
vuniroot2 <- function( y, f, interval = stop('must provide a length-2 `interval`'), tol = .Machine$double.eps^.25, maxiter = 1000 ) { if (any(is.infinite(y))) stop('infinite return from function `f` cannot be handled') out <- rep(NA_real_, times = length(y)) if (!any(yok <- !is.na(y))) return(out) out[yok] <- Inf yok_ <- y[yok] f.intv <- f(interval) if (anyNA(f.intv)) { stop('function evaluated at either end of the `interval` must not be NA') } f.lower <- f.intv[1L] - yok_ f.upper <- f.intv[2L] - yok_ if (any(fl0 <- (abs(f.lower) < tol))) { out[yok][fl0] <- interval[1L] f.lower <- f.lower[!fl0] f.upper <- f.upper[!fl0] yok[yok][fl0] <- FALSE if (!any(yok)) return(out) } if (any(fu0 <- (abs(f.upper) < tol))) { out[yok][fu0] <- interval[2L] f.lower <- f.lower[!fu0] f.upper <- f.upper[!fu0] yok[yok][fu0] <- FALSE if (!any(yok)) return(out) } yok_ <- y[yok] if (any(sign_same <- (f.lower * f.upper > 0))) { out[yok][sign_same & (abs(f.lower) < abs(f.upper))] <- -Inf sign_change <- which(!sign_same) } else sign_change <- seq_along(yok_) if (nn <- length(sign_change)) { out[yok][sign_change] <- vuniroot( f = function(x) f(x) - yok_[sign_change], lower = rep(interval[1L], times = nn), upper = rep(interval[2L], times = nn), f.lower = f.lower[sign_change], f.upper = f.upper[sign_change], extendInt = 'no', check.conv = TRUE, tol = tol, maxiter = maxiter, trace = 0L)[[1L]] } return(out) }