code
stringlengths
1
13.8M
app_model <- function() { if (file.exists("./fitted_model_log.csv")) { file.remove("./fitted_model_log.csv") } ui <- shiny::fluidPage( shinyjs::useShinyjs(), shiny::titlePanel("Modeling"), shiny::tabsetPanel( shiny::tabPanel( title = "Create train data", shiny::sidebarLayout( fluid = FALSE, shiny::sidebarPanel( width = 2, shinyFiles::shinyDirButton( id = "folder", label = "Choose folder", title = "Choose recordings folder", style = "width:100%" ), htmltools::br(), shinyFiles::shinyFilesButton( id = "selected_db", label = "Choose database", title = "Choose database file", multiple = FALSE, style = "width:100%" ), htmltools::br(), htmltools::br(), shiny::fluidRow( shiny::column( width = 12, align = "left", shiny::selectInput( inputId = "tx", label = "Time expanded", choices = c( "1" = "1", "10" = "10", "auto" = "auto" ), selected = "1" ), ) ), htmltools::hr(), htmltools::h4("Spectrogram parameters", align = "left"), htmltools::hr(), shiny::numericInput( inputId = "spec_size", label = "Size (ms)", value = "20" ), shiny::numericInput( inputId = "window_length", label = "Moving window (ms)", value = "1" ), shiny::selectInput( inputId = "overlap", label = "Overlap", choices = c( "50%" = "0.50", "75%" = "0.75" ), selected = "0.75" ), shiny::selectInput( inputId = "frequency_resolution", label = "Resolution", choices = c( "Low" = "1", "Medium" = "2", "High" = "3" ), selected = "1" ), shiny::selectInput( inputId = "dynamic_range", label = "Threshold", choices = c( "60 dB" = "60", "70 dB" = "70", "80 dB" = "80", "90 dB" = "90", "100 dB" = "100", "110 dB" = "110", "120 dB" = "120" ), selected = "120" ), shiny::fluidRow( shiny::column( width = 6, align = "center", shiny::textInput( inputId = "low", label = "Lower (kHz)", value = "10" ) ), shiny::column( width = 6, align = "center", shiny::textInput( inputId = "high", label = "Higher (kHz)", value = "120" ) ) ) ), shiny::mainPanel( htmltools::br(), shiny::fluidRow( shiny::column( width = 6, shiny::textOutput("folder_path") ) ), htmltools::br(), shiny::fluidRow( shiny::column( width = 6, shiny::textOutput("db_path") ) ), htmltools::hr(), shiny::fluidRow( shiny::column( width = 6, align = "center", offset = 3, shiny::actionButton( inputId = "create_specs", label = "Create training data from labels", style = "width:100%" ), htmltools::tags$style( type = "text/css", " height- 50px; width- 100%; font-size- 30px;}" ) ) ), htmltools::br(), shiny::tableOutput("spec") ) ) ), shiny::tabPanel( title = "Fit model", shiny::sidebarLayout( fluid = FALSE, shiny::sidebarPanel( width = 2, shinyFiles::shinyFilesButton( id = "rdata_path", label = "Choose train data", title = "Choose train data file", multiple = FALSE, style = "width:100%" ), shinyFiles::shinyFilesButton( id = "model_path", label = "Choose model", title = "Choose model", multiple = FALSE, style = "width:100%" ), htmltools::hr(), htmltools::h4( "Model parameters", align = "left" ), htmltools::hr(), shiny::numericInput( inputId = "train_per", label = "Train %", value = "0.7" ), shiny::numericInput( inputId = "batch", label = "Batch size", value = "64" ), shiny::numericInput( inputId = "lr", label = "Learning rate", value = "0.01" ), shiny::numericInput( inputId = "stop", label = "Early stop", value = "3" ), shiny::numericInput( inputId = "epochs", label = "Max epochs", value = "50" ) ), shiny::mainPanel( htmltools::br(), shiny::fluidRow( shiny::column( width = 6, shiny::textOutput("rdata_path") ) ), htmltools::br(), shiny::fluidRow( shiny::column( width = 6, shiny::textOutput("model_path") ) ), htmltools::hr(), shiny::fluidRow( shiny::column( width = 6, align = "center", offset = 3, shiny::actionButton( inputId = "fit_model", label = "Fit model", style = "width:100%" ), htmltools::tags$style( type = "text/css", " width- 100%; font-size- 30px;}" ) ) ), htmltools::br(), htmltools::br(), shiny::tableOutput("fitted_model_log"), htmltools::br(), htmltools::br(), shiny::tableOutput("end_fit") ) ) ), shiny::tabPanel("Run model", shiny::sidebarLayout(fluid = FALSE, shiny::sidebarPanel( width = 2, shinyFiles::shinyDirButton(id = "fitted_selected_folder", label = "Choose folder", title = "Choose folder", style = "width:100%"), shinyFiles::shinyFilesButton( id = "fitted_selected_model", label = "Choose model", title = "Choose model", multiple = FALSE, style = "width:100%"), htmltools::br(), shinyFiles::shinyFilesButton(id = "fitted_selected_metadata", label = "Choose metadata", title = "Choose metadata file", multiple = FALSE, style = "width:100%"), htmltools::br(), htmltools::br(), shiny::fluidRow( shiny::column( width = 12, align = "left", shiny::selectInput( inputId = "tx2", label = "Time expanded", choices = c( "1" = "1", "10" = "10", "auto" = "auto" ), selected = "1" ), ) ), htmltools::br(), shiny::textInput(inputId = "out_file", label = "Name of output file", value = "id_results"), htmltools::br(), shiny::radioButtons("rem_noise", "Non-relevant class?", c("Yes" = TRUE, "No" = FALSE)), htmltools::br(), shiny::radioButtons("lab_plots", "Export labeled plots", c("Yes" = TRUE, "No" = FALSE)) ), shiny::mainPanel( htmltools::br(), shiny::fluidRow( shiny::column(6, shiny::textOutput("fitted_folder_path") ) ), htmltools::br(), shiny::fluidRow( shiny::column(6, shiny::textOutput("fitted_model_path") ) ), htmltools::br(), shiny::fluidRow( shiny::column(6, shiny::textOutput("fitted_metadata_path") ) ), htmltools::hr(), shiny::fluidRow( shiny::column(6, align = "center", offset = 3, shiny::actionButton("id_recs", "Classify recordings", style = "width:100%"), htmltools::tags$style(type = "text/css", " ) ), shiny::column(5, shiny::plotOutput("")) ) ) ) ) ) server <- function(input, output) { system <- Sys.info()[["sysname"]] if (system == "Windows") roots <- c(home = "C://") if (system == "Linux") roots <- c(Computer = "/") shiny::observe({ shinyFiles::shinyDirChoose( input = input, id = "folder", roots = roots ) if (!is.null(input$folder)) { folder_selected <- shinyFiles::parseDirPath( roots = roots, selection = input$folder ) folder_path <- paste( "Recordings folder =", as.character(folder_selected) ) output$folder_path <- shiny::renderText(as.character(folder_path)) } }) shiny::observeEvent(input$folder, { if (length(shinyFiles::parseDirPath(roots, input$folder)) > 0) { setwd(shinyFiles::parseDirPath( roots = roots, selection = input$folder )) } }) files_path <- shiny::reactive({ folder_selected <- shinyFiles::parseDirPath( roots = roots, selection = input$folder ) files_path <- as.character(paste0( folder_selected, "//" ) ) return(files_path) }) shiny::observe({ shinyFiles::shinyFileChoose( input = input, id = "selected_db", roots = roots ) if (!is.null(input$selected_db)) { file_selected <- shinyFiles::parseFilePaths( roots = roots, selection = input$selected_db ) db_path <- paste( "Database file =", as.character(file_selected$datapath) ) output$db_path <- shiny::renderText(as.character(db_path)) } }) db_path <- shiny::reactive({ file_selected <- shinyFiles::parseFilePaths( roots = roots, selection = input$selected_db ) db_path <- as.character(file_selected$datapath) return(db_path) }) spec_calls <- shiny::eventReactive(input$create_specs, { total <- length(list.files( path = files_path(), recursive = F, pattern = "wav|WAV") ) progress <- shiny::Progress$new(max = total) progress$set( message = "Processing recordings", value = 0 ) on.exit(progress$close()) update_progress <- function(value = NULL, detail = NULL) { if (is.null(value)) { value <- progress$getValue() + 1 } progress$set( value = value, detail = detail ) } train_data <- spectro_calls( files_path = files_path(), update_progress = update_progress, db_path = db_path(), spec_size = as.numeric(input$spec_size), window_length = as.numeric(input$window_length), frequency_resolution = as.numeric(input$frequency_resolution), overlap = input$overlap, dynamic_range = as.numeric(input$dynamic_range), freq_range = c(as.numeric(input$low), as.numeric(input$high)), tx = ifelse(nchar(input$tx) > 2, input$tx, as.numeric(input$tx)) ) save( train_data, file = "train_data.RDATA" ) return(train_data) }) output$spec <- shiny::renderTable({ table(spec_calls()[[2]]) }) shiny::observe({ shinyFiles::shinyFileChoose( input = input, id = "rdata_path", roots = roots ) if (!is.null(input$rdata_path)) { file_selected <- shinyFiles::parseFilePaths( roots = roots, selection = input$rdata_path ) rdata_path <- paste( "Train data file =", as.character(file_selected$datapath) ) if(length(dirname(as.character(file_selected$datapath))) > 0) setwd(dirname(as.character(file_selected$datapath))) output$rdata_path <- shiny::renderText(as.character(rdata_path)) } }) rdata_list <- shiny::reactive({ if (length(input$rdata_path) > 1) { file_selected <- shinyFiles::parseFilePaths( roots = roots, selection = input$rdata_path ) env <- load2env(as.character(file_selected$datapath)) rdata_list <- env[[names(env)[1]]] rm(env) return(rdata_list) } }) shiny::observe({ shinyFiles::shinyFileChoose( input = input, id = "model_path", roots = roots ) if (!is.null(input$model_path)) { file_selected <- shinyFiles::parseFilePaths( roots = roots, selection = input$model_path ) model_path <- paste( "Model file =", as.character(file_selected$datapath) ) output$model_path <- shiny::renderText(as.character(model_path)) } }) model_path <- shiny::reactive({ file_selected <- shinyFiles::parseFilePaths( roots = roots, selection = input$model_path ) model_path <- as.character(file_selected$datapath) return(model_path) }) shiny::observeEvent(input$fit_model, { output$end_fit <- shiny::renderTable({ }) }) shiny::observeEvent(input$fit_model, { rdata_list <- rdata_list() model <- c() input_shape <- c(rdata_list$parameters$img_rows, rdata_list$parameters$img_cols, 1) num_classes <- rdata_list$parameters$num_classes source(model_path(), local = TRUE) model %>% generics::compile( optimizer = keras::optimizer_sgd(learning_rate = input$lr, momentum = 0.9, nesterov = T), loss = "categorical_crossentropy", metrics = c("accuracy") ) model %>% generics::fit(rdata_list$data_x, rdata_list$data_y, batch_size = input$batch, epochs = input$epochs, callbacks = list( keras::callback_early_stopping(patience = input$stop, monitor = "val_accuracy"), keras::callback_model_checkpoint("./fitted_model.hdf5", monitor = "val_accuracy", save_best_only = T), keras::callback_lambda(on_train_begin = function(logs) { shinyjs::html("fitted_model_log", paste("Initiating epoch 1"))}), keras::callback_lambda(on_epoch_end = function(epoch, logs) { shinyjs::html("fitted_model_log", paste("Epoch = ", epoch + 1, " | Validation accuracy = ", round(logs$val_accuracy, 3) * 100, "%"))}), keras::callback_lambda(on_train_end = function(logs) { shinyjs::html("fitted_model_log", paste("Model fitted"))}), keras::callback_csv_logger("./fitted_model_log.csv")), shuffle = TRUE, validation_split = 1 - input$train_per, verbose = 1) metadata <- list(parameters = rdata_list$parameters, classes = rdata_list$classes) save(metadata, file = "fitted_model_metadata.RDATA") output$end_fit <- shiny::renderTable({ utils::read.csv("fitted_model_log.csv") }) }) shiny::observe({ shinyFiles::shinyDirChoose(input, "fitted_selected_folder", roots = roots) if (!is.null(input$fitted_selected_folder)) { folder_selected <- shinyFiles::parseDirPath(roots, input$fitted_selected_folder) folder_path <- paste("Recordings folder =", as.character(folder_selected)) output$fitted_folder_path <- shiny::renderText(as.character(folder_path)) } }) shiny::observeEvent(input$fitted_selected_folder, { if (length(shinyFiles::parseDirPath(roots, input$fitted_selected_folder)) > 0) { setwd(shinyFiles::parseDirPath(roots, input$fitted_selected_folder)) } }) fitted_files_path <- shiny::reactive({ folder_selected <- shinyFiles::parseDirPath(roots, input$fitted_selected_folder) files_path <- as.character(paste0(folder_selected, "//")) files_path }) shiny::observe({ shinyFiles::shinyFileChoose( input = input, id = "fitted_selected_model", roots = roots ) if (!is.null(input$fitted_selected_model)) { file_selected <- shinyFiles::parseFilePaths( roots = roots, selection = input$fitted_selected_model ) fitted_model_path <- paste( "Model file =", as.character(file_selected$datapath) ) output$fitted_model_path <- shiny::renderText(as.character(fitted_model_path)) } }) fitted_model_path <- shiny::reactive({ file_selected <- shinyFiles::parseFilePaths( roots = roots, selection = input$fitted_selected_model ) fitted_model_path <- as.character(file_selected$datapath) return(fitted_model_path) }) shiny::observe({ shinyFiles::shinyFileChoose(input, "fitted_selected_metadata", roots = roots) if (!is.null(input$fitted_selected_metadata)) { file_selected <- shinyFiles::parseFilePaths(roots, input$fitted_selected_metadata) fitted_metadata_path <- paste("Metadata file =", as.character(file_selected$datapath)) output$fitted_metadata_path <- shiny::renderText(as.character(fitted_metadata_path)) } }) fitted_metadata <- shiny::reactive({ if (length(input$fitted_selected_metadata) > 1) { file_selected <- shinyFiles::parseFilePaths(roots, input$fitted_selected_metadata) env <- load2env(as.character(file_selected$datapath)) metadata <- env[[names(env)[1]]] rm(env) return(metadata) } }) shiny::observeEvent(input$id_recs, { if (!dir.exists(paste0(fitted_files_path(), "/", "output/"))) dir.create(paste0(fitted_files_path(), "/", "output/")) total <- length(list.files(fitted_files_path(), recursive = F, pattern = "wav|WAV")) progress <- shiny::Progress$new(max = total) progress$set(message = "Processing recordings", value = 0) on.exit(progress$close()) update_progress <- function(value = NULL, detail = NULL) { if (is.null(value)) { value <- progress$getValue() + 1 } progress$set(value = value, detail = detail) } auto_id(fitted_model_path(), update_progress, fitted_metadata(), fitted_files_path(), out_file = input$out_file, out_dir = paste0(fitted_files_path(), "/", "output/"), save_png = as.logical(input$lab_plots), win_size = fitted_metadata()$parameters$spec_size * 2, remove_noise = as.logical(input$rem_noise), plot2console = FALSE, recursive = FALSE, tx = ifelse(nchar(input$tx2) > 2, input$tx2, as.numeric(input$tx2))) }) } shiny::shinyApp(ui = ui, server = server) }
setGeneric(name = ".gFunc_v", def = function(gFunc, v, ...) { standardGeneric(".gFunc_v") }) setMethod(f = ".gFunc_v", signature = c(gFunc = "ANY", v = "ANY"), definition = function(gFunc, v, ...) { stop("inappropriate object(s) provided for gFunc and/or v", call. = FALSE) }) setMethod(f = ".gFunc_v", signature = c(gFunc = "NULL", v = "ANY"), definition = function(gFunc, v, ...) { return( list("gFunc" = 2L, "v" = 1.0, "nTheta" = 2L) ) }) setMethod(f = ".gFunc_v", signature = c(gFunc = "character", v = "NULL"), definition = function(gFunc, v, ...) { if (gFunc %in% c("splin", "spcub", "piece")) { stop("v must be speficied for gFunc = ", gFunc, call. = FALSE) } else if (gFunc != 'lin') { stop("gFunc not recognized", call. = FALSE) } return( .gFunc_v(gFunc = NULL, v = v) ) }) setMethod(f = ".gFunc_v", signature = c(gFunc = "character", v = "numeric"), definition = function(gFunc, v, L, ...) { v <- sort(x = unique(x = v)) if (gFunc == "lin") { return( .gFunc_v(gFunc = NULL, v = v) ) } else if (gFunc == "piece") { v <- unique(x = c(0.0, v, L)) v <- v[{v <= {L+1e-8}} & {v > {0.0-1e-8}}] if (length(x = v) <= 2L) { stop("inappropriate value provided for v", call. = FALSE) } return( list("gFunc" = 1L, "v" = v, "nTheta" = length(x = v) - 1L) ) } else if (gFunc == "splin") { v <- v[{v < L} & {v > 0.0}] if (length(x = v) == 0L) { stop("inappropriate value provided for v", call. = FALSE) } return( list("gFunc" = 3L, "v" = v, "nTheta" = length(x = v) + 2L) ) } else if (gFunc == "spcub") { v <- v[{v < L} & {v > 0.0}] if (length(x = v) == 0L) { stop("inappropriate value provided for v", call. = FALSE) } return( list("gFunc" = 4L, "v" = v, "nTheta" = length(x = v) + 4L) ) } else { stop("gFunc not recognized", call. = FALSE) } })
library(MixSIAR) mix.filename <- system.file("extdata", "stormpetrel_consumer.csv", package = "MixSIAR") mix <- load_mix_data(filename=mix.filename, iso_names=c("d13C","d15N"), factors="Region", fac_random=FALSE, fac_nested=FALSE, cont_effects=NULL) source.filename <- system.file("extdata", "stormpetrel_sources.csv", package = "MixSIAR") source <- load_source_data(filename=source.filename, source_factors=NULL, conc_dep=FALSE, data_type="raw", mix) discr.filename <- system.file("extdata", "stormpetrel_discrimination.csv", package = "MixSIAR") discr <- load_discr_data(filename=discr.filename, mix) plot_data(filename="isospace_plot", plot_save_pdf=TRUE, plot_save_png=FALSE, mix,source,discr) if(mix$n.iso==2) calc_area(source=source,mix=mix,discr=discr) plot_prior(alpha.prior=1,source) model_filename <- "MixSIAR_model.txt" resid_err <- TRUE process_err <- TRUE write_JAGS_model(model_filename, resid_err, process_err, mix, source) jags.1 <- run_model(run="test", mix, source, discr, model_filename, alpha.prior=1) output_JAGS(jags.1, mix, source)
test_that("factory basics work", { y <- 2 power <- build_factory( fun = function(x) { x^exponent }, exponent = ) square <- power(y) expect_identical(square(2), 4) y <- 7 expect_identical(square(2), 4) }) test_that("factory errors", { expect_error( build_factory( fun = function(x) { x^exponent } ), "You must provide at least one argument to your factory" ) power <- build_factory( fun = function(x) { x^exponent }, exponent = ) expect_error( power(), "argument \"exponent\" is missing, with no default" ) power <- build_factory( fun = function(x) { x^exponent }, exponent = 2 ) expect_error( power(), NA ) }) test_that("Equals unnecessary for arguments.", { overpower <- build_factory( fun = function(x) { x^exponent^other }, exponent, other = ) square_cube <- overpower(2, 3) expect_identical(square_cube(2), 2^2^3) }) test_that("NULL default arguments work.", { null_ok <- build_factory( fun = function(x) { c(x, to_add) }, to_add = NULL ) add_null <- null_ok() expect_identical(add_null("a"), "a") add_a <- null_ok("a") expect_identical(add_a("b"), c("b", "a")) })
if (identical(Sys.getenv("NOT_CRAN"), "true")) { test_that("layer-spatial works for stars objects", { skip_if_not_installed("vdiffr") skip_if_not_installed("stars") load_longlake_data( which = c( "longlake_osm", "longlake_depthdf", "longlake_depth_raster" ), raster_format = "stars" ) expect_s3_class(longlake_osm, "stars") expect_s3_class(longlake_depth_raster, "stars") expect_doppelganger_extra( "layer_spatial.stars()", ggplot() + layer_spatial(longlake_osm) + layer_spatial(longlake_depthdf) ) expect_doppelganger_extra( "annotation_spatial.stars()", ggplot() + annotation_spatial(longlake_osm) + layer_spatial(longlake_depthdf) ) expect_doppelganger_extra( "layer_spatial.stars() project", ggplot() + layer_spatial(longlake_osm) + layer_spatial(longlake_depthdf) + coord_sf(crs = 3978) ) expect_doppelganger_extra( "annotation_spatial.stars() project", ggplot() + annotation_spatial(longlake_osm) + layer_spatial(longlake_depthdf) + coord_sf(crs = 3978) ) expect_doppelganger_extra( "annotation_spatial.stars() alpha 0.3", ggplot() + annotation_spatial(longlake_osm, alpha = 0.3) + layer_spatial(longlake_depthdf) + coord_sf(crs = 3978) ) expect_doppelganger_extra( "layer_spatial.stars() aes()", ggplot() + layer_spatial(longlake_osm, aes()) + layer_spatial(longlake_depthdf) ) expect_doppelganger_extra( "layer_spatial.stars() aes(band1)", ggplot() + layer_spatial( longlake_osm, aes(alpha = stat(band1), fill = NULL) ) + layer_spatial(longlake_depthdf) ) expect_doppelganger_extra( "layer_spatial.stars() dpi", ggplot() + layer_spatial(longlake_osm, lazy = TRUE, dpi = 5) ) expect_doppelganger_extra( "layer_spatial.stars() lazy", ggplot() + layer_spatial(longlake_osm, lazy = TRUE) ) expect_doppelganger_extra( "layer_spatial.stars() no interpolation", ggplot() + layer_spatial(longlake_osm, lazy = TRUE, interpolate = FALSE, dpi = 5 ) ) expect_doppelganger_extra( "layer_spatial.stars() example 1", ggplot() + layer_spatial(longlake_osm) ) expect_doppelganger_extra( "layer_spatial.stars() example 2", ggplot() + layer_spatial(longlake_depth_raster) + ggplot2::scale_fill_continuous(type = "viridis") ) }) } test_that("Full lifecycle", { skip_if_not_installed("stars") skip_on_cran() stars <- stars::read_stars( system.file("longlake/longlake.tif", package = "ggspatial") ) expect_s3_class(stars, "stars") plot <- ggplot() + layer_spatial(stars) expect_s3_class(plot, "ggplot") tmp <- tempfile(fileext = ".png") expect_silent(ggplot2::ggsave(tmp, plot, width = 4, height = 4)) unlink(tmp) }) test_that("Test that stars array (unprojected) is identical to terra and raster", { skip_if_not_installed("stars") skip_if_not_installed("raster") skip_on_cran() test_raster <- new.env(parent = emptyenv()) load_longlake_data(test_raster, raster_format = "raster") test_stars <- new.env(parent = emptyenv()) load_longlake_data(test_stars, raster_format = "stars") expect_s4_class(test_raster$longlake_osm, "Raster") expect_error(stars_as_array(test_raster$longlake_osm)) expect_identical( raster_as_array(test_raster$longlake_osm), stars_as_array(test_stars$longlake_osm) ) expect_identical( raster_as_array(test_raster$longlake_osm, alpha = 0.4), stars_as_array(test_stars$longlake_osm, alpha = 0.4) ) skip_if_not_installed("terra") test_terra <- new.env(parent = emptyenv()) load_longlake_data(test_terra, raster_format = "terra") expect_identical( terra_as_array(test_terra$longlake_osm), stars_as_array(test_stars$longlake_osm) ) expect_identical( terra_as_array(test_terra$longlake_osm, alpha = 0.4), stars_as_array(test_stars$longlake_osm, alpha = 0.4) ) })
export_pdf <- function(map,chemin,nomFichier) { mapshot(map, file = paste0(chemin,"/",nomFichier,".pdf"), selfcontained = FALSE) }
RjnmfC <- function(Xs, Xu, k, alpha, lambda, epsilon, maxiter, verbose) { .Call('_conos_RjnmfC', PACKAGE = 'conos', Xs, Xu, k, alpha, lambda, epsilon, maxiter, verbose) } adjustedRandcpp <- function(cl1, cl1u, cl2, cl2u, mm1, mm2, nn, fflag) { .Call('_conos_adjustedRandcpp', PACKAGE = 'conos', cl1, cl1u, cl2, cl2u, mm1, mm2, nn, fflag) } checkBits <- function() { .Call('_conos_checkBits', PACKAGE = 'conos') } checkOpenMP <- function() { .Call('_conos_checkOpenMP', PACKAGE = 'conos') } cpcaF <- function(cov, ng, ncomp = 10L, maxit = 1000L, tol = 1e-6, eigenvR = NULL, verbose = TRUE) { .Call('_conos_cpcaF', PACKAGE = 'conos', cov, ng, ncomp, maxit, tol, eigenvR, verbose) } greedyModularityCutC <- function(merges, deltaM, N, minsize, labels, minbreadth, flatCut) { .Call('_conos_greedyModularityCutC', PACKAGE = 'conos', merges, deltaM, N, minsize, labels, minbreadth, flatCut) } treeJaccard <- function(merges, clusters, clusterTotals, clmerges = NULL) { .Call('_conos_treeJaccard', PACKAGE = 'conos', merges, clusters, clusterTotals, clmerges) } scoreTreeConsistency <- function(test, ref, leafidmap, minsize = 10L) { .Call('_conos_scoreTreeConsistency', PACKAGE = 'conos', test, ref, leafidmap, minsize) } maxStableClusters <- function(merges, thresholds, minthreshold = 0.8, minsize = 10L) { .Call('_conos_maxStableClusters', PACKAGE = 'conos', merges, thresholds, minthreshold, minsize) } pareDownHubEdges <- function(sY, rowN, k, klow = -1L) { .Call('_conos_pareDownHubEdges', PACKAGE = 'conos', sY, rowN, k, klow) } getSumWeightMatrix <- function(weights, row_inds, col_inds, factor_levels, normalize = TRUE) { .Call('_conos_getSumWeightMatrix', PACKAGE = 'conos', weights, row_inds, col_inds, factor_levels, normalize) } adjustWeightsByCellBalancingC <- function(weights, row_inds, col_inds, factor_levels, dividers) { .Call('_conos_adjustWeightsByCellBalancingC', PACKAGE = 'conos', weights, row_inds, col_inds, factor_levels, dividers) } referenceWij <- function(i, j, d, threads, perplexity) { .Call('_conos_referenceWij', PACKAGE = 'conos', i, j, d, threads, perplexity) } as_factor <- function(vals) { .Call('_conos_as_factor', PACKAGE = 'conos', vals) } get_nearest_neighbors <- function(adjacency_list, transition_probabilities, n_verts = 0L, n_cores = 1L, min_prob = 1e-3, min_visited_verts = 1000L, min_prob_lower = 1e-5, max_hitting_nn_num = 0L, max_commute_nn_num = 0L, verbose = TRUE) { .Call('_conos_get_nearest_neighbors', PACKAGE = 'conos', adjacency_list, transition_probabilities, n_verts, n_cores, min_prob, min_visited_verts, min_prob_lower, max_hitting_nn_num, max_commute_nn_num, verbose) } sgd <- function(coords, targets_i, sources_j, ps, weights, gamma, rho, n_samples, M, alpha, momentum, useDegree, seed, threads, verbose) { .Call('_conos_sgd', PACKAGE = 'conos', coords, targets_i, sources_j, ps, weights, gamma, rho, n_samples, M, alpha, momentum, useDegree, seed, threads, verbose) } propagate_labels <- function(edge_verts, edge_weights, vert_labels, max_n_iters = 10L, verbose = TRUE, diffusion_fading = 10, diffusion_fading_const = 0.5, tol = 5e-3, fixed_initial_labels = FALSE) { .Call('_conos_propagate_labels', PACKAGE = 'conos', edge_verts, edge_weights, vert_labels, max_n_iters, verbose, diffusion_fading, diffusion_fading_const, tol, fixed_initial_labels) } smooth_count_matrix <- function(edge_verts, edge_weights, count_matrix, is_label_fixed, max_n_iters = 10L, diffusion_fading = 1.0, diffusion_fading_const = 0.1, tol = 1e-3, verbose = TRUE, normalize = FALSE) { .Call('_conos_smooth_count_matrix', PACKAGE = 'conos', edge_verts, edge_weights, count_matrix, is_label_fixed, max_n_iters, diffusion_fading, diffusion_fading_const, tol, verbose, normalize) } adjacent_vertices <- function(edge_verts) { .Call('_conos_adjacent_vertices', PACKAGE = 'conos', edge_verts) } adjacent_vertex_weights <- function(edge_verts, edge_weights) { .Call('_conos_adjacent_vertex_weights', PACKAGE = 'conos', edge_verts, edge_weights) } spcov <- function(m, cm) { .Call('_conos_spcov', PACKAGE = 'conos', m, cm) }
extractSE <- function(mod, ...) { UseMethod("extractSE", mod) } extractSE.default <- function(mod, ...) { stop("\nFunction not yet defined for this object class\n") } extractSE.coxme <- function(mod, ...){ vcov.mat <- as.matrix(vcov(mod)) se <- sqrt(diag(vcov.mat)) fixed.labels <- names(fixef(mod)) names(se) <- fixed.labels return(se) } extractSE.lmekin <- function(mod, ...){ vcov.mat <- as.matrix(vcov(mod)) se <- sqrt(diag(vcov.mat)) fixed.labels <- names(fixef(mod)) names(se) <- fixed.labels return(se) } extractSE.mer <- function(mod, ...){ vcov.mat <- as.matrix(vcov(mod)) se <- sqrt(diag(vcov.mat)) fixed.labels <- names(fixef(mod)) names(se) <- fixed.labels return(se) } extractSE.merMod <- function(mod, ...){ vcov.mat <- as.matrix(vcov(mod)) se <- sqrt(diag(vcov.mat)) fixed.labels <- names(fixef(mod)) names(se) <- fixed.labels return(se) } extractSE.lmerModLmerTest <- function(mod, ...){ vcov.mat <- as.matrix(vcov(mod)) se <- sqrt(diag(vcov.mat)) fixed.labels <- names(fixef(mod)) names(se) <- fixed.labels return(se) }
SoilWeb_spatial_query <- function(bbox=NULL, coords=NULL, what='mapunit', source='soilweb') { if(!requireNamespace('jsonlite', quietly = TRUE)) stop('please install the `jsonlite` package', call.=FALSE) options(stringsAsFactors=FALSE) if(missing(coords) & missing(bbox)) stop('you must provide some filtering criteria') if(! missing(coords) & ! missing(bbox)) stop('query cannot include both bbox and point coordinates') f <- vector() res <- NULL if(!missing(coords)) { f <- c(f, paste('&lon=', coords[1], '&lat=', coords[2], sep='')) } if(!missing(bbox)) { bbox <- paste(bbox, collapse=',') f <- c(f, paste('&bbox=', bbox, sep='')) } the.url <- paste('https://casoilresource.lawr.ucdavis.edu/soil_web/api/ssurgo.php?what=mapunit', f, sep='') suppressWarnings(try(res <- jsonlite::fromJSON(the.url), silent=TRUE)) if(is.null(res)) { stop('query returned no data', call.=FALSE) } return(res) }
predict_BBQ <- function(bbq, new, option){ getHistPr <- function(histModel, cutPoints, new){ N <- length(new) B <- length(histModel) cutPoints <- c(0,cutPoints,1) res <- rep(0,N) for (i in 1:N){ x <- new[i] minIdx <- 1 maxIdx <- B+1 while ((maxIdx - minIdx)>1){ midIdx <- floor((minIdx+maxIdx)/2) if(x>cutPoints[midIdx]){ minIdx <- midIdx } else if(x < cutPoints[midIdx]){ maxIdx <- midIdx } else{ minIdx <- midIdx break } } idx <- minIdx res[i] <- histModel[[idx]]$P cnt <- 1 k <- idx -1 while (k>=1){ if (histModel[[k]]$min==histModel[[idx]]$min && histModel[[k]]$max==histModel[[idx]]$max){ res[i] <- res[i] + histModel[[k]]$P k <- k+1 cnt <- cnt+1 } else break } res[i] <- res[i]/cnt } return(res) } getMA <- function(BBQ_Model, x){ N <- length(BBQ_Model) p <- rep(0,N) SV <- BBQ_Model[[1]]$SV for(i in 1:N){ p[i] <- getHistPr(BBQ_Model[[i]]$binNo, BBQ_Model[[i]]$cutPoints, x) } res <- (t(SV)%*%p)/sum(SV) } out <- rep(0, length(new)) BBQ_Model <- bbq$prunedmodel if (option==1){ for (i in 1:length(new)){ out[i] <- getMA(BBQ_Model, new[i]) } sign_test_set <- NULL new_bin <- NULL } if(option==0){ for (i in 1:length(new)){ out[i] <- getHistPr(BBQ_Model[[1]]$binNo, BBQ_Model[[1]]$cutPoints, new[i]) } significant_bins <- subset(bbq$binnning_scheme$bin_no, bbq$binnning_scheme$p_value<0.05) new_bin <- cut(new, c(0,BBQ_Model[[1]]$cutPoints,1),labels = seq(1,length(bbq$binnning_scheme$midpoint)),include.lowest = T) sign_test_set <- sum(table(new_bin)[significant_bins])/(sum(table(new_bin))) } return(list(predictions=out, pred_idx=option, significance_test_set=sign_test_set, pred_per_bin=table(new_bin))) }
StarCoordinates <- function(df, color = NULL, approach="Standard", numericRepresentation=TRUE, meanCentered = TRUE, projMatrix=NULL, clusterFunc = NULL) { colorVar <- color inputCheck <- inputValidationSC(df, colorVar, approach, projMatrix, clusterFunc ) if (!is.null(inputCheck)){ if (inputCheck$stop) stop(inputCheck$errorMessage) else warning(inputCheck$errorMessage) } odata <- df df <- removeNonZeroAndMissing(df) frequencyList <- NULL if (!is.null(colorVar) && (colorVar %in% colnames(df))){ df[[colorVar]] <- NULL } else if (!is.null(colorVar)){ colorVar <- NULL } if(numericRepresentation){ df <- mutate_if(df, is.factor, as.numeric) } else { frequencyList <- getFrequencyList(df) } ui <- miniPage( useShinyjs(), gadgetTitleBar("Star Coordinates"), miniContentPanel( plotOutput("plot", height = "100%", brush="plotBrush", hover=hoverOpts(id="plot_hover", delayType="throttle", delay= 150), dblclick = "plotDblClick") ), miniButtonBlock( actionButton("zoomIn","", icon = icon("search-plus")), actionButton("zoomOut","", icon = icon("search-minus")), actionButton("screenShot","", icon = icon("camera-retro")), if( !is.null(colorVar) && !is.null(clusterFunc)) actionButton("hint","Hint", icon = icon("map-signs")), ) ) server <- function(input, output, session) { highlightedIdx <- reactiveVal(-1) highlightedCat <- reactiveVal(-1) highlightedCatValue <- reactiveVal(value = NULL) helperValues <- reactiveValues() helperValues$clicked <- FALSE helperValues$movingDim <- -1 helperValues$plotLimit <- 1.5 helperValues$projectionMatrix <- initProjectionMatrix(df, projMatrix) helperValues$lbl <- NULL helperValues$cumulativeList <- NULL helperValues$rangedData <- NULL helperValues$hints <- NULL observeEvent( input$plot_hover, { helperValues$curX <- input$plot_hover$x helperValues$curY <- input$plot_hover$y currentClosest <- closestDimension(helperValues$projectionMatrix, helperValues$curX, helperValues$curY ) if (helperValues$clicked ){ session$resetBrush("plotBrush") helperValues$projectionMatrix[helperValues$movingDim,1:2] <- c(helperValues$curX, helperValues$curY) if (approach == "OSC"){ helperValues$projectionMatrix <- OSCRecondition(helperValues$projectionMatrix) } highlightedIdx(helperValues$movingDim) } else { highlightedIdx(currentClosest) } if (!is.null(highlightedCatValue())){ helperValues$lbl <- NULL } }) observeEvent(input$plotDblClick,{ if(!numericRepresentation){ if ( highlightedCat() != -1){ nameDim <- colnames(df)[highlightedCat()] inside <- insideCategoricalValueList(helperValues$projectionMatrix, nameDim, helperValues$cumulativeList, helperValues$curX, helperValues$curY ) helperValues$lbl <- insideCategoricalValueGG(helperValues$projectionMatrix, nameDim, helperValues$cumulativeList, inside) currentOrder <- helperValues$cumulativeList[[nameDim]]$order if (sum(inside) > 0){ selectedCatValue <- currentOrder[which(inside)] if(is.null( highlightedCatValue() )){ highlightedCatValue(selectedCatValue) } else if (!(selectedCatValue %in% highlightedCatValue()) ){ newOrder <- swap(currentOrder, selectedCatValue, highlightedCatValue()) helperValues$cumulativeList[[nameDim]] <- getCumulativeTable(frequencyList[[nameDim]], newOrder) helperValues$rangedData <- getRangedData(df, numericRepresentation, meanCentered, frequencyList, helperValues$cumulativeList) highlightedCatValue(NULL) helperValues$lbl <- NULL } else { helperValues$lbl <- NULL highlightedCatValue(NULL) } } } currentClosest <- closestDimension(helperValues$projectionMatrix, input$plotDblClick$x, input$plotDblClick$y ) if ( currentClosest != -1){ nameDim <- colnames(df)[currentClosest] if( is.factor(df[[nameDim]])){ if ( highlightedCat() != -1){ highlightedCat(-1) helperValues$lbl <- NULL highlightedCatValue(NULL) } else { highlightedCat(currentClosest) } } } } }) mouseDown <- function(){ currentClosest <- closestDimension(helperValues$projectionMatrix, helperValues$curX, helperValues$curY ) if ( currentClosest != -1){ helperValues$movingDim <- currentClosest helperValues$clicked <- TRUE } helperValues$hints = NULL } mouseUp <- function(){ helperValues$clicked <- FALSE helperValues$movingDim <- -1 } initCumulative <- function(){ if (!is.null( frequencyList) && is.null(helperValues$cumulativeList)){ helperValues$cumulativeList <- list() catVars <- names(frequencyList) for( catName in catVars){ cumulativeTable <- getCumulativeTable(frequencyList[[catName]]) helperValues$cumulativeList[[catName]] <- cumulativeTable } helperValues$rangedData <- getRangedData(df, numericRepresentation, meanCentered, frequencyList, helperValues$cumulativeList) } if (approach == "OSC"){ helperValues$projectionMatrix <- OSCRecondition(helperValues$projectionMatrix) } if( numericRepresentation && is.null( helperValues$rangedData )){ helperValues$rangedData <- getRangedData(df, numericRepresentation, meanCentered) } } output$plot <- renderPlot({ if (is.null( helperValues$rangedData )) initCumulative() curPlot <- drawDimensionVectors(helperValues$projectionMatrix, highlightedIdx(), highlightedCat(), highlightedCatValue(), helperValues$cumulativeList ) if (!is.null(helperValues$lbl)) curPlot <- curPlot + helperValues$lbl if (!is.null(helperValues$hints)) curPlot <- curPlot + helperValues$hints curPlot + getGGProjectedPoints(helperValues$projectionMatrix, helperValues$rangedData , odata, colorVar) + coord_cartesian(xlim = c(-helperValues$plotLimit,helperValues$plotLimit ), ylim = c(-helperValues$plotLimit,helperValues$plotLimit )) },res=96) observeEvent(input$cancel, { stopApp(NULL) }) observeEvent(input$hint, { actions <- getActionHints(helperValues$projectionMatrix, helperValues$rangedData, odata, colorVar ,approach, clusterFunc) updateActionButton(session, "hint", label = paste0("Hint. Max(",formatC(max(actions$diff), format = "e", digits = 2), ")")) if (max(actions$diff) > 0){ helperValues$hints <- getGGHints(helperValues$projectionMatrix, actions) } else { helperValues$hints <- NULL } }) onevent("mouseup", "plot", mouseUp()) onevent("mousedown","plot", mouseDown()) observeEvent(input$zoomIn,{ helperValues$plotLimit <- helperValues$plotLimit*0.9 }) observeEvent(input$zoomOut,{ helperValues$plotLimit <- helperValues$plotLimit*1.1 }) observeEvent(input$screenShot, { screenshot()}) observeEvent(input$done, { projMatrix <- getCleanProjectionMatrix(helperValues$projectionMatrix, colorVar, odata, df) projectedPoints <- getProjectedPoints(helperValues$projectionMatrix, helperValues$rangedData ) selected <- brushedPoints(df=projectedPoints, brush=input$plotBrush, xvar="V1", yvar="V2", allRows = TRUE) result <- list(projMatrix, selected$selected_, projectedPoints) names(result) <- c("Proj.Matrix","Selection","Projected.Points") stopApp(result) }) } viewer <- paneViewer(300) runGadget(ui, server, viewer=viewer) }
db_compute_boxplot <- function(data, x, var, coef = 1.5) { x <- enquo(x) check_vars <- quo_get_expr(x) if (length(check_vars) > 1 && expr_text(check_vars[1]) == "vars()") { x <- eval_tidy(x) } else { x <- quos(!!x) } var <- enquo(var) var <- quo_squash(var) res <- group_by(data, !!!x, add = TRUE) res <- calc_boxplot(res, var) res <- mutate(res, iqr = (upper - lower) * coef, min_iqr = lower - iqr, max_iqr = upper + iqr, ymax = ifelse(max_raw > max_iqr, max_iqr, max_raw), ymin = ifelse(min_raw < min_iqr, min_iqr, min_raw) ) res <- collect(res) ungroup(res) } calc_boxplot <- function(res, var) { UseMethod("calc_boxplot") } calc_boxplot.tbl <- function(res, var) { summarise( res, n = n(), lower = quantile(!!var, 0.25), middle = quantile(!!var, 0.5), upper = quantile(!!var, 0.75), max_raw = max(!!var, na.rm = TRUE), min_raw = min(!!var, na.rm = TRUE) ) } calc_boxplot.tbl_spark <- function(res, var) { calc_boxplot_sparklyr(res, var) } calc_boxplot_sparklyr <- function(res, var) { summarise( res, n = n(), lower = percentile_approx(!!var, 0.25), middle = percentile_approx(!!var, 0.5), upper = percentile_approx(!!var, 0.75), max_raw = max(!!var, na.rm = TRUE), min_raw = min(!!var, na.rm = TRUE) ) } `calc_boxplot.tbl_Microsoft SQL Server` <- function(res, var) { calc_boxplot_mssql(res, var) } calc_boxplot_mssql <- function(res, var) { res <- mutate( res, n = n(), lower = quantile(!!var, 0.25), middle = quantile(!!var, 0.5), upper = quantile(!!var, 0.75), max_raw = max(!!var, na.rm = TRUE), min_raw = min(!!var, na.rm = TRUE) ) res <- select(res, n, lower, middle, upper, max_raw, min_raw) distinct(res) } dbplot_boxplot <- function(data, x, var, coef = 1.5) { x <- enquo(x) var <- enquo(var) df <- db_compute_boxplot( data = data, x = !!x, var = !!var, coef = coef ) colnames(df) <- c( "x", "n", "lower", "middle", "upper", "max_raw", "min_raw", "iqr", "min_iqr", "max_iqr", "ymax", "ymin" ) ggplot(df) + geom_boxplot( aes( x = x, ymin = ymin, lower = lower, middle = middle, upper = upper, ymax = ymax, group = x ), stat = "identity" ) + labs(x = x) } globalVariables(c( "upper", "ymax", "weight", "x_", "y", "aes", "ymin", "lower", "middle", "upper", "iqr", "max_raw", "max_iqr", "min_raw", "min_iqr", "percentile_approx" ))
"scatterPlotMatrix.HH" <- function(){ initializeDialog(title=gettextRcmdr("Scatterplot Matrix (HH)")) variablesBox <- variableListBox(top, Numeric(), title=gettextRcmdr("Select variables (three or more)"), selectmode="multiple", initialSelection=NULL) checkBoxes(frame="optionsFrame", boxes=c("lsLine", "smoothLine", "spread"), initialValues=c(1,0,0), labels=gettextRcmdr(c("Least-squares lines", "Smooth lines", "Show spread"))) sliderValue <- tclVar("50") slider <- tkscale(optionsFrame, from=0, to=100, showvalue=TRUE, variable=sliderValue, resolution=5, orient="horizontal") radioButtons(name="diagonal", buttons=c("density", "histogram", "boxplot", "oned", "qqplot", "none"), labels=gettextRcmdr(c("Density plots", "Histograms", "Boxplots", "One-dimensional scatterplots", "Normal QQ plots", "Nothing (empty)")), title=gettextRcmdr("On Diagonal")) radioButtons(name="diagonalDirection", buttons=c("SW.NE", "NW.SE"), labels=gettextRcmdr(c("SW-NE ' / '", "NW-SE ' \\ '")), title=gettextRcmdr("Diagonal Direction")) subsetBox() onOK <- function(){ variables <- getSelection(variablesBox) closeDialog() if (length(variables) < 3) { errorCondition(recall=scatterPlotMatrix.HH, message=gettextRcmdr("Fewer than 3 variable selected.")) return() } line <- if("1" == tclvalue(lsLineVariable)) "lm" else "FALSE" smooth <- as.character("1" == tclvalue(smoothLineVariable)) spread <- as.character("1" == tclvalue(spreadVariable)) span <- as.numeric(tclvalue(sliderValue)) diag <- as.character(tclvalue(diagonalVariable)) diagDir <- as.character(tclvalue(diagonalDirectionVariable)) subset <- tclvalue(subsetVariable) subset <- if (trim.blanks(subset) == gettextRcmdr("<all valid cases>")) "" else paste(", subset=", subset, sep="") .activeDataSet <- ActiveDataSet() if (.groups == FALSE) { command <- paste("scatterplotMatrix(~", paste(variables, collapse="+"), ", reg.line=", line, ", smooth=", smooth, ", spread=", spread, ", span=", span/100, ", diagonal = '", diag, "', data=", .activeDataSet, subset, ", row1attop=", diagDir=="NW.SE", ")", sep="") logger(command) justDoIt(command) } else { command <- paste("scatterplotMatrix(~", paste(variables, collapse="+")," | ", .groups, ", reg.line=", line, ", smooth=", smooth, ", spread=", spread, ", span=", span/100, ", diagonal= '", diag, "', by.groups=", .linesByGroup, ", data=", .activeDataSet, subset, ", row1attop=", diagDir=="NW.SE", ")", sep="") logger(command) justDoIt(command) } activateMenus() tkfocus(CommanderWindow()) } groupsBox(scatterPlot, plotLinesByGroup=TRUE) OKCancelHelp(helpSubject="scatterplotMatrix") tkgrid(getFrame(variablesBox), sticky="nw") tkgrid(labelRcmdr(optionsFrame, text=gettextRcmdr("Span for smooth")), slider, sticky="w") tkgrid(optionsFrame, sticky="w") tkgrid(diagonalFrame, sticky="w") tkgrid(diagonalDirectionFrame, sticky="w") tkgrid(subsetFrame, sticky="w") tkgrid(groupsFrame, sticky="w") tkgrid(buttonsFrame, columnspan=2, sticky="w") dialogSuffix(rows=6, columns=2) }
MixtureSameFamily <- R6::R6Class( "torch_MixtureSameFamily", inherit = Distribution, lock_objects = FALSE, public = list( initialize = function(mixture_distribution, component_distribution, validate_args=NULL) { self$.mixture_distribution <- mixture_distribution self$.component_distribution <- component_distribution if (!inherits(self$.mixture_distribution, "torch_Categorical")) value_error("Mixture distribution must be distr_categorical.") if (!inherits(self$.component_distribution, "torch_Distribution")) value_error("Component distribution must be an instance of torch_Distribution.") cdbs <- head2(self$.component_distribution$batch_shape, -1) km <- tail(self$.mixture_distribution$logits$shape, 1) kc <- tail(self$.component_distribution$batch_shape, 1) if (!is.null(km) && !is.null(kc) && km != kc) value_error("Mixture distribution component ({km}) does not equal component_distribution$batch_shape[-1] ({kc}).") self$.num_components <- km event_shape <- self$.component_distribution$event_shape self$.event_ndims <- length(event_shape) super$initialize(batch_shape = cdbs, event_shape = event_shape, validate_args = validate_args) }, expand = function(batch_shape, instance = NULL) { batch_shape_comp <- c(batch_shape, self$.num_component) .args = list() .args$mixture_distribution <- self$.mixture_distribution$expand(batch_shape) .args$component_distribution <- self$.component_distribution$expand(batch_shape_comp) new <- private$.get_checked_instance(self, instance, .args) new }, cdf = function(x) { x = self$.pad(x) cdf_x = self$component_distribution$cdf(x) mix_prob = self$mixture_distribution$probs torch_sum(cdf_x * mix_prob, dim=-1) }, log_prob = function(x) { if (self$.validate_args) self$.validate_sample(x) x = self$.pad(x) log_prob_x = self$component_distribution$log_prob(x) log_mix_prob = torch_log_softmax(self$mixture_distribution$logits, dim=-1) torch_logsumexp(log_prob_x + log_mix_prob, dim=-1) }, sample = function(sample_shape = list()) { with_no_grad({ sample_len <- length(sample_shape) batch_len = length(self$batch_shape) gather_dim <- sample_len + batch_len + 1L es = self$event_shape mix_sample = self$mixture_distribution$sample(sample_shape) mix_shape = mix_sample$shape comp_samples = self$component_distribution$sample(sample_shape) mix_sample_r = mix_sample$reshape( c(mix_shape, rep(1, length(es) + 1))) mix_sample_r = mix_sample_r$`repeat`( c(rep(1, length(mix_shape)), 1, es)) samples = torch_gather(comp_samples, gather_dim, mix_sample_r) out <- samples$squeeze(gather_dim) }) out }, .pad = function(x) { x$unsqueeze(-1 - self$.event_ndims) } ), active = list( mixture_distribution = function() { self$.mixture_distribution }, component_distribution = function() { self$.component_distribution } ) ) MixtureSameFamily <- add_class_definition(MixtureSameFamily) distr_mixture_same_family <- function(mixture_distribution, component_distribution, validate_args = NULL) { MixtureSameFamily$new(mixture_distribution = mixture_distribution, component_distribution = component_distribution, validate_args = validate_args) }
cps.ma.normal <- function(nsim = 1000, nsubjects = NULL, narms = NULL, nclusters = NULL, means = NULL, sigma_sq = NULL, sigma_b_sq = NULL, alpha = 0.05, quiet = FALSE, ICC = NULL, method = 'glmm', multi_p_method = "bonferroni", allSimData = FALSE, seed = NA, cores = NULL, poorFitOverride = FALSE, lowPowerOverride = FALSE, tdist = FALSE, return.all.models = FALSE, optmethod = "nlminb", nofit = FALSE, timelimitOverride = TRUE) { converge <- NULL if (is.null(narms)) { stop("ERROR: narms is required.") } if (narms < 3) { stop("ERROR: LRT significance not calculable when narms < 3. Use cps.normal() instead.") } if (isTRUE(is.list(nsubjects))) { if (is.null(nclusters)) { nclusters <- vapply(nsubjects, length, 0) } } if (length(nclusters) == 1 & !isTRUE(is.list(nsubjects))) { nclusters <- rep(nclusters, narms) } if (!is.wholenumber(nsim) || nsim < 1 || length(nsim) > 1) { stop("nsim must be a positive integer of length 1.") } if (is.null(nsubjects)) { stop("nsubjects must be specified. See ?cps.ma.normal for help.") } if (length(nsubjects) == 1 & !isTRUE(is.numeric(nclusters))) { stop("When nsubjects is scalar, user must supply nclusters (clusters per arm)") } if (length(nsubjects) == 1 & length(nclusters) == 1 & !isTRUE(is.list(narms))) { stop("User must provide narms when nsubjects and nclusters are both scalar.") } validateVariance( dist = "norm", difference = means, alpha = alpha, ICC = ICC, sigma_sq = sigma_sq, sigma_b_sq = sigma_b_sq, ICC2 = NA, sigma_sq2 = NA, sigma_b_sq2 = NA, method = method, quiet = quiet, all.sim.data = allSimData, poor.fit.override = poorFitOverride ) if (sum(is.wholenumber(nclusters) == FALSE) != 0 || sum(unlist(nclusters) < 1) != 0) { stop("nclusters must be postive integer values.") } if (sum(is.wholenumber(unlist(nsubjects)) == FALSE) != 0 || sum(unlist(nsubjects) < 1) != 0) { stop("nsubjects must be positive integer values.") } if (length(nclusters) == 1) { nclusters <- rep(nclusters, narms) } if (mode(nsubjects) == "list") { str.nsubjects <- nsubjects } else { if (length(nsubjects) == 1) { str.nsubjects <- lapply(nclusters, function(x) rep(nsubjects, x)) } else { if (length(nsubjects) != narms) { stop("nsubjects must be length 1 or length narms if not provided in a list.") } str.nsubjects <- list() for (i in 1:length(nsubjects)) { str.nsubjects[[i]] <- rep(nsubjects[i], times = nclusters[i]) } } } if (length(sigma_sq) == 1) { sigma_sq <- rep(sigma_sq, narms) } if (length(sigma_b_sq) == 1) { sigma_b_sq <- rep(sigma_b_sq, narms) } if (length(ICC) == 1) { ICC <- rep(ICC, narms) } if (length(means) == 1) { means <- rep(means, narms) } if (isTRUE(length(ICC) != 0)) { if (isTRUE(length(sigma_sq) == 0 & length(sigma_b_sq) != 0)) { sigma_sq <- createMissingVarianceParam(sigma_b_sq = sigma_b_sq, ICC = ICC) } if (isTRUE(length(sigma_b_sq) == 0 & length(sigma_sq) != 0)) { sigma_b_sq <- createMissingVarianceParam(sigma_sq = sigma_sq, ICC = ICC) } } if (length(sigma_sq) != narms) { stop( "Length of variance parameters (sigma_sq, sigma_b_sq, ICC) must equal narms, or be provided as a scalar if sigma_sq for all arms are equal." ) } type1ErrTest(sigma_sq_ = sigma_sq, sigma_b_sq_ = sigma_b_sq, nsubjects_ = nsubjects) normal.ma.rct <- cps.ma.normal.internal( nsim = nsim, str.nsubjects = str.nsubjects, means = means, sigma_sq = sigma_sq, sigma_b_sq = sigma_b_sq, alpha = alpha, quiet = quiet, method = method, all.sim.data = allSimData, seed = seed, cores = cores, poor.fit.override = poorFitOverride, low.power.override = lowPowerOverride, timelimitOverride = timelimitOverride, tdist = tdist, optmethod = optmethod, nofit = nofit, return.all.models = return.all.models ) if (nofit == TRUE || return.all.models == TRUE) { return(normal.ma.rct) } summary.message = paste0( "Monte Carlo Power Estimation based on ", nsim, " Simulations: Parallel Design, Continuous Outcome, ", narms, " Arms." ) long.method = switch(method, glmm = 'Generalized Linear Mixed Model', gee = 'Generalized Estimating Equation') armnames <- vector(mode = "character", length = narms) for (i in 1:narms) { armnames[i] <- paste0("Arm.", i) } var.parms = data.frame('sigma_sq' = sigma_sq, 'sigma_b_sq' = sigma_b_sq, "means" = means) rownames(var.parms) <- armnames models <- normal.ma.rct[[1]] names(str.nsubjects) <- armnames cluster.sizes <- str.nsubjects if (method == "glmm") { Estimates = matrix(NA, nrow = nsim, ncol = narms) std.error = matrix(NA, nrow = nsim, ncol = narms) t.val = matrix(NA, nrow = nsim, ncol = narms) p.val = matrix(NA, nrow = nsim, ncol = narms) if (max(sigma_sq) != min(sigma_sq)) { for (i in 1:nsim) { Estimates[i, ] <- models[[i]][20][[1]][, 1] std.error[i, ] <- models[[i]][20][[1]][, 2] t.val[i, ] <- models[[i]][20][[1]][, 4] p.val[i, ] <- models[[i]][20][[1]][, 5] } keep.names <- rownames(models[[1]][20][[1]]) } else { for (i in 1:nsim) { Estimates[i, ] <- models[[i]][[10]][, 1] std.error[i, ] <- models[[i]][[10]][, 2] t.val[i, ] <- models[[i]][[10]][, 4] p.val[i, ] <- models[[i]][[10]][, 5] } keep.names <- rownames(models[[1]][[10]]) } names.Est <- rep(NA, narms) names.st.err <- rep(NA, narms) names.tval <- rep(NA, narms) names.pval <- rep(NA, narms) names.power <- rep(NA, narms) for (i in 1:length(keep.names)) { names.Est[i] <- paste(keep.names[i], ".Estimate", sep = "") names.st.err[i] <- paste(keep.names[i], ".Std.Err", sep = "") names.tval[i] <- paste(keep.names[i], ".tval", sep = "") names.pval[i] <- paste(keep.names[i], ".pval", sep = "") names.power[i] <- paste(keep.names[i], ".power", sep = "") } colnames(Estimates) <- names.Est colnames(std.error) <- names.st.err colnames(t.val) <- names.tval colnames(p.val) <- names.pval cps.model.temp <- data.frame(cbind(unlist(normal.ma.rct[[3]]), p.val)) colnames(cps.model.temp)[1] <- "converge" cps.model.temp2 <- dplyr::filter(cps.model.temp, converge == TRUE) if (isTRUE(nrow(cps.model.temp2) < (.25 * nsim))) { warning(paste0( nrow(cps.model.temp2), " models converged. Check model parameters." ), immediate. = TRUE) } if ((max(sigma_sq) == min(sigma_sq) & max(sigma_b_sq) == min(sigma_b_sq)) | (max(sigma_sq) == min(sigma_sq) & max(sigma_b_sq) != min(sigma_b_sq))) { LRT.holder <- matrix( unlist(normal.ma.rct[[2]]), ncol = 6, nrow = nsim, byrow = TRUE, dimnames = list( seq(1:nsim), c("Sum Sq", "Mean Sq", "NumDF", "DenDF", "F value", "P(>F)") ) ) LRT.holder <- cbind(LRT.holder, cps.model.temp["converge"]) LRT.holder <- LRT.holder[LRT.holder[, "converge"] == TRUE, ] sig.LRT <- ifelse(LRT.holder[, 6] < alpha, 1, 0) } else { LRT.holder <- as.vector(rep(NA, nsim)) for (i in 1:nsim) { LRT.holder[i] <- normal.ma.rct[[2]][[i]][2, 9] } LRT.holder <- cbind(LRT.holder, cps.model.temp["converge"]) LRT.holder <- LRT.holder[LRT.holder[, "converge"] == TRUE, ] sig.LRT <- ifelse(LRT.holder["LRT.holder"] < alpha, 1, 0) } power.parms <- cbind(confintCalc( alpha = alpha, multi = TRUE, p.val = as.vector(cps.model.temp2[, 3:length(cps.model.temp2)]) ), multi_p_method) ma.model.est <- data.frame(Estimates, std.error, t.val, p.val) ma.model.est <- ma.model.est[, -grep('.*ntercept.*', names(ma.model.est))] if (allSimData == TRUE && return.all.models == FALSE) { complete.output = structure( list( "overview" = summary.message, "nsim" = nsim, "power" = prop_H0_rejection( alpha = alpha, nsim = nsim, sig.LRT = sig.LRT ), "beta" = power.parms['Beta'], "overall.power2" = power.parms, "overall.power" = LRT.holder, "method" = long.method, "alpha" = alpha, "cluster.sizes" = cluster.sizes, "n.clusters" = nclusters, "variance.parms" = var.parms, "means" = means, "model.estimates" = ma.model.est, "convergence" = normal.ma.rct[[3]], "sim.data" = normal.ma.rct[[4]] ), class = 'crtpwr.ma' ) } if (return.all.models == TRUE) { complete.output = structure( list( "overview" = summary.message, "nsim" = nsim, "power" = prop_H0_rejection( alpha = alpha, nsim = nsim, sig.LRT = sig.LRT ), "beta" = power.parms['Beta'], "overall.power2" = power.parms, "overall.power" = LRT.holder, "method" = long.method, "alpha" = alpha, "cluster.sizes" = cluster.sizes, "n.clusters" = nclusters, "variance.parms" = var.parms, "means" = means, "model.estimates" = ma.model.est, "convergence" = normal.ma.rct[[3]], "sim.data" = normal.ma.rct[[4]], "all.models" <- normal.ma.rct ), class = 'crtpwr.ma' ) } if (return.all.models == FALSE && allSimData == FALSE) { complete.output = structure( list( "overview" = summary.message, "nsim" = nsim, "power" = prop_H0_rejection( alpha = alpha, nsim = nsim, sig.LRT = sig.LRT ), "beta" = power.parms['Beta'], "overall.power2" = power.parms, "overall.power" = LRT.holder, "method" = long.method, "alpha" = alpha, "cluster.sizes" = cluster.sizes, "n.clusters" = nclusters, "variance.parms" = var.parms, "means" = means, "model.estimates" = ma.model.est, "convergence" = normal.ma.rct[[3]] ), class = 'crtpwr.ma' ) } } if (method == "gee") { Estimates = matrix(NA, nrow = nsim, ncol = narms) std.error = matrix(NA, nrow = nsim, ncol = narms) Wald = matrix(NA, nrow = nsim, ncol = narms) Pr = matrix(NA, nrow = nsim, ncol = narms) for (i in 1:nsim) { Estimates[i, ] <- models[[i]]$coefficients[, 1] std.error[i, ] <- models[[i]]$coefficients[, 2] Wald[i, ] <- models[[i]]$coefficients[, 3] Pr[i, ] <- p.adjust(models[[i]]$coefficients[, 4], method = multi_p_method) } keep.names <- rownames(models[[1]]$coefficients) names.Est <- rep(NA, length(narms)) names.st.err <- rep(NA, length(narms)) names.wald <- rep(NA, length(narms)) names.pval <- rep(NA, length(narms)) names.power <- rep(NA, length(narms)) for (i in 1:length(keep.names)) { names.Est[i] <- paste(keep.names[i], ".Estimate", sep = "") names.st.err[i] <- paste(keep.names[i], ".Std.Err", sep = "") names.wald[i] <- paste(keep.names[i], ".wald", sep = "") names.pval[i] <- paste(keep.names[i], ".pval", sep = "") names.power[i] <- paste(keep.names[i], ".power", sep = "") } colnames(Estimates) <- names.Est colnames(std.error) <- names.st.err colnames(Wald) <- names.wald colnames(Pr) <- names.pval LRT.holder <- matrix( unlist(normal.ma.rct[[2]]), ncol = 3, nrow = nsim, byrow = TRUE, dimnames = list(seq(1:nsim), c("Df", "X2", "P(>|Chi|)")) ) LRT.holder <- cbind(LRT.holder, normal.ma.rct[["converged"]]) LRT.holder <- LRT.holder[LRT.holder[, "converged"] == TRUE, ] sig.LRT <- ifelse(LRT.holder[, 3] < alpha, 1, 0) power.parms <- cbind(confintCalc( alpha = alpha, multi = TRUE, p.val = Pr[, 2:narms] ), multi_p_method) ma.model.est <- data.frame(Estimates, std.error, Wald, Pr) ma.model.est <- ma.model.est[, -grep('.*ntercept.*', names(ma.model.est))] if (allSimData == TRUE & return.all.models == FALSE) { complete.output = structure( list( "overview" = summary.message, "nsim" = nsim, "power" = prop_H0_rejection( alpha = alpha, nsim = nsim, sig.LRT = sig.LRT ), "beta" = power.parms['Beta'], "overall.power2" = power.parms, "overall.power" = LRT.holder, "method" = long.method, "alpha" = alpha, "cluster.sizes" = cluster.sizes, "n.clusters" = nclusters, "variance.parms" = var.parms, "means" = means, "model.estimates" = ma.model.est, "sim.data" = normal.ma.rct[[3]] ), class = 'crtpwr.ma' ) } if (return.all.models == TRUE) { complete.output = structure( list( "overview" = summary.message, "nsim" = nsim, "power" = prop_H0_rejection( alpha = alpha, nsim = nsim, sig.LRT = sig.LRT ), "beta" = power.parms['Beta'], "overall.power2" = power.parms, "overall.power" = LRT.holder, "method" = long.method, "alpha" = alpha, "cluster.sizes" = cluster.sizes, "n.clusters" = nclusters, "variance.parms" = var.parms, "means" = means, "model.estimates" = ma.model.est, "all.models" <- normal.ma.rct ), class = 'crtpwr.ma' ) } if (return.all.models == FALSE && allSimData == FALSE) { complete.output = structure( list( "overview" = summary.message, "nsim" = nsim, "power" = prop_H0_rejection( alpha = alpha, nsim = nsim, sig.LRT = sig.LRT ), "beta" = power.parms['Beta'], "overall.power2" = power.parms, "overall.power" = LRT.holder, "method" = long.method, "alpha" = alpha, "cluster.sizes" = cluster.sizes, "n.clusters" = nclusters, "variance.parms" = var.parms, "means" = means, "model.estimates" = ma.model.est ), class = 'crtpwr.ma' ) } } return(complete.output) }
orig_prism_path <- getOption("prism.path") teardown(options(prism.path = orig_prism_path)) prism_set_dl_dir(tempdir()) test_that("prism_check_dl_dir() works if path is set", { expect_equal(prism_check_dl_dir(), tempdir()) expect_warning(expect_equal(path_check(), tempdir())) }) options(prism.path = NULL) test_that("prism_check_dl_dir() fails if path is not set", { expect_error(prism_check_dl_dir()) })
context("Utility functions") test_that("test several utility functions", { x1<-plot_mrk_info(tetra.solcap, 1) x2<-plot_mrk_info(tetra.solcap, "solcap_snp_c2_41437") x3<-plot_mrk_info(tetra.solcap.geno.dist, 1) x4<-plot_mrk_info(tetra.solcap.geno.dist, "solcap_snp_c2_41437") expect_is(x1, "list") expect_is(x2, "list") expect_is(x3, "list") expect_is(x4, "list") expect_equal(get_LOD(solcap.err.map[[1]]),0) tpt<-est_pairwise_rf(make_seq_mappoly(tetra.solcap, 1:30)) x1<-make_seq_mappoly(tetra.solcap, 1:20) x2<-make_seq_mappoly(tetra.solcap, 21:40) x1<-as.numeric(check_if_rf_is_possible(x1)) x2<-as.numeric(check_if_rf_is_possible(x2)) expect_equal(as.numeric(crossprod(x1,x2)), 14) M<-rf_list_to_matrix(tpt, shared.alleles = TRUE) expect_equal(round(sum(get_rf_from_mat(M$rec.mat), na.rm = TRUE), 6), 3.913633) expect_equal(get_w_m(6), 15) expect_error(get_w_m(0)) expect_error(get_w_m(3)) rm<-rev_map(maps.hexafake[[1]]) expect_equal(sum(rm$maps[[1]]$seq.rf), sum(maps.hexafake[[1]]$maps[[1]]$seq.rf), tolerance = 10e-5) a1<-sample_data(tetra.solcap.geno.dist, n = 20, type = "marker") a2<-sample_data(a1, n = 20, type = "individual") plot(a2) a3<-dist_prob_to_class(a2$geno) expect_equal(prod(dim(a3$geno.dose)), nrow(a3$geno)) expect_equal(round(mf_h(20),6), 0.16484) expect_equal(round(mf_k(20),6), 0.189974) expect_equal(round(mf_m(20),6), 0.2) expect_equal(round(imf_h(.15),2), 17.83) expect_equal(round(imf_k(.15),2), 15.48) expect_equal(round(imf_m(.15),2), 15) expect_null(plot_compare_haplotypes(ploidy = 6, hom.allele.p1 = maps.hexafake[[1]]$maps[[1]]$seq.ph$P[1:10], hom.allele.q1 = maps.hexafake[[1]]$maps[[1]]$seq.ph$Q[1:10], hom.allele.p2 = maps.hexafake[[1]]$maps[[1]]$seq.ph$P[1:10], hom.allele.q2 = maps.hexafake[[1]]$maps[[1]]$seq.ph$Q[1:10])) expect_null(print_mrk(input.data = hexafake, mrks = "M_1")) expect_equal(sum(perm_pars(1:5)), 900) expect_equal(sum(perm_tot(1:5)), 1800) a<-sample_data(tetra.solcap.geno.dist, n=30, type = "marker") a<-sample_data(a, n=30) w<-update_missing(a, prob.thres = .7) expect_is(w, "mappoly.data") w2 <- get_genomic_order(make_seq_mappoly(hexafake, "all")) w3 <- as.numeric(crossprod(w2$ord$seq.pos)/10e17) expect_is(plot(w2), "ggplot") expect_equal(w3, 0.4952, tolerance = 1e-3) w4<-get_submap(solcap.dose.map[[1]], 1:10, reestimate.rf = FALSE) s4<-make_seq_mappoly(w4) tpt2<-est_pairwise_rf(s4) M2<-rf_list_to_matrix(tpt2, shared.alleles = TRUE) a1 <- drop_marker(w4, 5) a2 <- drop_marker(w4, "solcap_snp_c1_10930") expect_equal(a1,a2, tolerance = 1e-3) a3 <- drop_marker(w4, 1) a4 <- add_marker(a3, "solcap_snp_c2_51460", 0, M2, verbose = FALSE) w4<-reest_rf(w4, tol = 10e-5) a4<-reest_rf(a4, tol = 10e-5) expect_equal(w4, a4, tolerance = 1e-3) a3 <- drop_marker(w4, 5) a4 <- add_marker(a3, "solcap_snp_c1_10930", 4, M2, verbose = FALSE) w4<-reest_rf(w4, tol = 10e-5) a4<-reest_rf(a4, tol = 10e-5) expect_equal(w4, a4, tolerance = 1e-3) a3 <- drop_marker(w4, 10) a4 <- add_marker(a3, "solcap_snp_c2_36643", 9, M2, verbose = FALSE) w4<-reest_rf(w4, tol = 10e-5) a4<-reest_rf(a4, tol = 10e-5) expect_equal(w4, a4, tolerance = 1e-3) b<-merge_datasets(hexafake, hexafake.geno.dist) expect_equivalent(mean(as.matrix(b$geno.dose)), 1.078817, tol = 1e-3) map<-update_map(solcap.dose.map[[1]]) expect_equal(length(map$maps[[1]]$seq.num) - length(solcap.dose.map[[1]]$maps[[1]]$seq.num), 20) })
package_files <- function(path) { all <- normalizePath(r_files(path)) collate <- desc::desc_get_collate(file = file.path(path, "DESCRIPTION")) collate <- normalizePath(file.path(path, "R", collate)) rfiles <- c(collate, setdiff(all, collate)) ignore_files(rfiles, path) } r_files <- function(path) { sort_c(dir(file.path(path, "R"), "\\.[Rr]$", full.names = TRUE)) } ignore_files <- function(rfiles, path) { rbuildignore <- file.path(path, ".Rbuildignore") if (!file.exists(rbuildignore)) return(rfiles) rfiles_relative <- sub(normalizePath(path, winslash = "/"), "", normalizePath(rfiles, winslash = "/"), fixed = TRUE) rfiles_relative <- sub("^[/]*", "", rfiles_relative) patterns <- read_lines(rbuildignore) patterns <- patterns[patterns != ""] if (length(patterns) == 0L) { return(rfiles) } matches <- lapply(patterns, grepl, rfiles_relative, perl = TRUE) matches <- Reduce("|", matches) rfiles[!matches] }
expected <- eval(parse(text="c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, NA, TRUE, TRUE, TRUE, NA, TRUE, TRUE)")); test(id=0, code={ argv <- eval(parse(text="list(c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, NA, 2L, 2L, 0L, NA, 1L, 1L), c(0, 0, 0, 0, 0, 0, 0, 0, 1, NA, 2, 2, 0, NA, 1, 1))")); do.call(`==`, argv); }, o=expected);
print.NSM3Ch5c <-function(x,...){ if(x$method!="Exact"){ cat("\n",x$method, " Approximation ") if(x$method=="Monte Carlo"){cat("(with ",x$n.mc, " Iterations) ")} cat("used: \n \n") } cat(paste0("Number of X values: ", x$m, " Number of Y values: ", x$n, "\n")) if(x$method!="Asymptotic"){ if(!is.null(x$two.sided)){ cat(paste0("For the given alpha=", x$alpha, ", the lower cutoff value is ",x$stat.name,"=",x$cutoff.L, ",\n", "with true alpha level=",round(x$true.alpha.L,4), "\n")) } cat(paste0("For the given alpha=", x$alpha, ", the upper cutoff value is ",x$stat.name, "=" ,x$cutoff.U, ",\n", "with true alpha level=",round(x$true.alpha.U,4), "\n")) } if(x$method=="Asymptotic"){ if(!is.null(x$two.sided)){ cat(paste0("For the given alpha =", x$alpha, ", the approximate lower cutoff value is ",x$stat.name,"=",x$cutoff.L, "\n")) } cat(paste0("For the given alpha =", x$alpha, ", the approximate upper cutoff value is ",x$stat.name, "=",x$cutoff.U, ",\n")) } if(!is.null(x$extra)){ cat(x$extra, "\n") } }
conDisplacement <- function(ltraj,def='all',idcol='burst'){ cpdf <- conPairs(ltraj) cid <- NULL for (p in 1:max(cpdf$contact_pha)){ cpdf_sub <- cpdf[cpdf$contact_pha == p,] if (def == 'first'){ cid <- c(cid, cpdf_sub$contact_orig_rowid[which.min(cpdf_sub$date)]) } else if (def == 'last'){ cid <- c(cid, cpdf_sub$contact_orig_rowid[which.max(cpdf_sub$date)]) } else if (def == 'minTime'){ cid <- c(cid, cpdf_sub$contact_orig_rowid[which.min(cpdf_sub$contact_dt)]) } else if (def == 'minDist') { cid <- c(cid, cpdf_sub$contact_orig_rowid[which.min(cpdf_sub$contact_d)]) } else { cid <- c(cid,unique(cpdf_sub$contact_orig_rowid)) } } dfr <- ld(ltraj) dfr$displacement <- 0 n <- dim(dfr)[1] anid <- unique(dfr[,idcol]) for (ani in anid){ ind <- which(dfr[,idcol]==ani) cid_ani <- cid[which(cid %in% ind)] if (length(cid_ani) == 0) { dfr$displacement[ind] <- NA } else { for (i in ind){ j <- cid_ani[which.min(abs(dfr$date[i]-dfr$date[cid_ani]))] dfr$displacement[i] <-sqrt((dfr$x[i]-dfr$x[j])^2+(dfr$y[i]-dfr$y[j])^2) } } } outtraj <- dl(dfr,proj4string=attr(ltraj,'proj4string')) return(outtraj) }
tk_seasonal_diagnostics <- function(.data, .date_var, .value, .feature_set = "auto") { date_var_expr <- rlang::enquo(.date_var) value_expr <- rlang::enquo(.value) if (!is.data.frame(.data)) { stop(call. = FALSE, "tk_seasonal_diagnostics(.data) is not a data-frame or tibble. Please supply a data.frame or tibble.") } if (rlang::quo_is_missing(date_var_expr)) { stop(call. = FALSE, "tk_seasonal_diagnostics(.date_var) is missing. Please supply a date or date-time column.") } if (rlang::quo_is_missing(value_expr)) { stop(call. = FALSE, "tk_seasonal_diagnostics(.value) is missing. Please a numeric column.") } if (!all(.feature_set %in% acceptable_seasonal_values())) { stop(call. = FALSE, "tk_seasonal_diagnostics(.feature_set): Feature values not in acceptable values. Please use one or more of: ", stringr::str_c(acceptable_seasonal_values(), collapse = ", ")) } UseMethod("tk_seasonal_diagnostics", .data) } tk_seasonal_diagnostics.data.frame <- function(.data, .date_var, .value, .feature_set = "auto") { date_var_expr <- rlang::enquo(.date_var) value_expr <- rlang::enquo(.value) data_formatted <- .data %>% dplyr::mutate(.value_mod = !! value_expr) %>% dplyr::select(!! date_var_expr, .value_mod) if (.feature_set[1] == "auto") { .feature_set <- .data %>% dplyr::pull(!! date_var_expr) %>% get_seasonal_auto_features() } data_formatted <- data_formatted %>% tk_augment_timeseries_signature(.date_var = !! date_var_expr) %>% dplyr::select(!! date_var_expr, .value_mod, .feature_set) %>% dplyr::mutate_at(.vars = dplyr::vars(-(!! date_var_expr), -.value_mod), factor, ordered = FALSE) %>% dplyr::rename(.value = .value_mod) return(data_formatted) } tk_seasonal_diagnostics.grouped_df <- function(.data, .date_var, .value, .feature_set = "auto") { value_expr <- rlang::enquo(.value) date_var_expr <- rlang::enquo(.date_var) group_names <- dplyr::group_vars(.data) if (.feature_set[1] == "auto") { .feature_set <- .data %>% dplyr::group_split() %>% purrr::map(.f = function(df) { df %>% dplyr::pull(!! date_var_expr) %>% get_seasonal_auto_features() }) %>% purrr::flatten_chr() %>% unique() } .data %>% tidyr::nest() %>% dplyr::mutate(nested.col = purrr::map( .x = data, .f = function(df) tk_seasonal_diagnostics( .data = df, .date_var = !! date_var_expr, .value = !! value_expr, .feature_set = .feature_set ) )) %>% dplyr::select(-data) %>% tidyr::unnest(cols = nested.col) %>% dplyr::group_by_at(.vars = group_names) } acceptable_seasonal_values <- function() { c("auto", "second", "minute", "hour", "wday.lbl", "week", "month.lbl", "quarter", "year") } get_seasonal_auto_features <- function(.index) { summary_tbl <- .index %>% tk_get_timeseries_summary() max_min_list <- get_max_min_list(summary_tbl) features_to_get <- tk_get_timeseries_unit_frequency() %>% tidyr::gather() %>% dplyr::mutate(check = value %>% dplyr::between(max_min_list$min_period$value, max_min_list$max_period$value)) %>% dplyr::filter(check) %>% dplyr::left_join(time_series_signature_lookup_tbl(), by = "key") %>% dplyr::pull(feature) return(features_to_get) } get_max_min_list <- function(time_series_summary_tbl) { min_period <- tk_get_timeseries_unit_frequency() %>% tidyr::gather() %>% dplyr::mutate(check = 2 * value > time_series_summary_tbl$diff.median) %>% dplyr::filter(check) %>% dplyr::slice(1) start_numeric <- as.numeric(as.POSIXct(time_series_summary_tbl$start)) end_numeric <- as.numeric(as.POSIXct(time_series_summary_tbl$end)) start_to_end <- end_numeric - start_numeric start_to_end max_period <- tk_get_timeseries_unit_frequency() %>% tidyr::gather() %>% dplyr::mutate(check = 2 * value < start_to_end) %>% dplyr::filter(check) %>% dplyr::slice(dplyr::n()) max_min_list <- list(min_period = min_period, max_period = max_period) return(max_min_list) } time_series_signature_lookup_tbl <- function() { tibble::tibble( sec = "second", min = "minute", hour = "hour", day = "wday.lbl", week = "week", month = "month.lbl", quarter = "quarter", year = "year" ) %>% tidyr::gather(value = "feature") }
lapjv <- function(cost, maximize = FALSE) { m <- max(cost, 10) n <- nrow(cost) cost <- rbind(cbind(as.matrix(cost), m + m * stats::runif(n)), m + m * stats::runif(n + 1)) cost[n + 1, n + 1] <- 10 * m ^ 3 ind <- cpp_lapjv(cost, maximize) if (ind[n + 1] <= n){ if (sum(cost[which(ind == n + 1), 1:n]) > 1e-10){ warning(paste("Bad padding happened. Assigned", which(ind == n + 1), "to", ind[n + 1])) } ind[which(ind == n + 1)] <- ind[n + 1] } ind[1:n] } lapmod_index <- function(n, cc, ii, kk, maximize = FALSE) { cpp_lapmod(n, cc, ii, kk, maximize) } lapmod <- function(cost, maximize = FALSE){ cost <- Matrix::Matrix(cost, sparse = TRUE) n <- nrow(cost) m <- max(abs(cost@x), 2) sign <- ifelse(maximize, -1, 1) pad_vec <- sign * 1e5 * m * rep(1, n) cost <- rbind( cbind( cost, sign * ceiling(m * 1e5 * stats::runif(n)) ), c(pad_vec, - sign * 1e5 * m) ) ind <- cpp_lapmod(n + 1, cost@x, cost@p, cost@i, maximize) if (ind[n + 1] <= n){ if (sum(cost[which(ind == n + 1), 1:n]) > 1e-10){ warning(paste("Bad padding happened. Assigned", which(ind == n + 1), "to", ind[n + 1])) } ind[which(ind == n + 1)] <- ind[n + 1] } ind[1:n] }
plot_gdm_cor_numbers <- function( cor.trait, dim1, dim2, cexcor) { graphics::plot( c(0,1), c(0,1), type="n", axes=FALSE, xlab="", ylab="") graphics::text( .5, .50, paste0( round( cor.trait[dim1,dim2],3)), cex=cexcor) }
context("FeatureEffects") test_that("FeatureEffect (pdp only) works for single output and single feature", { grid.size <- 10 pdp.objs <- FeatureEffects$new(predictor1, method = "pdp", grid.size = grid.size ) expect_s3_class(pdp.objs$plot(), "patchwork") pdp.obj.a <- FeatureEffect$new(predictor1, feature = c("a"), method = "pdp", grid.size = grid.size ) pdp.obj.b <- FeatureEffect$new(predictor1, feature = c("b"), method = "pdp", grid.size = grid.size ) pdp.obj.c <- FeatureEffect$new(predictor1, feature = c("c"), method = "pdp", grid.size = grid.size ) pdp.obj.d <- FeatureEffect$new(predictor1, feature = c("d"), method = "pdp", grid.size = grid.size ) expect_equal(pdp.obj.a$results, pdp.objs$effects$a$results) expect_equal(pdp.obj.b$results, pdp.objs$effects$b$results) expect_equal(pdp.obj.c$results, pdp.objs$effects$c$results) expect_equal(pdp.obj.d$results, pdp.objs$effects$d$results) pdp.objs <- FeatureEffects$new(predictor1, features = c("a", "c"), method = "pdp", grid.size = grid.size ) expect_s3_class(pdp.objs$plot(), "patchwork") expect_equal(pdp.obj.a$results, pdp.objs$effects$a$results) expect_equal(pdp.obj.c$results, pdp.objs$effects$c$results) expect_equal(names(pdp.objs$effects), c("a", "c")) pdp.objs <- FeatureEffects$new(predictor1, method = "ale", grid.size = 10) expect_s3_class(pdp.objs$plot(), "patchwork") pdp.obj.a <- FeatureEffect$new(predictor1, feature = c("a"), method = "ale", grid.size = 10 ) expect_equal(pdp.obj.a$results, pdp.objs$effects$a$results) pdp.objs <- FeatureEffects$new(predictor1, method = "pdp+ice", grid.size = 2) expect_s3_class(pdp.objs$plot(), "patchwork") pdp.obj.a <- FeatureEffect$new(predictor1, feature = c("a"), method = "pdp+ice", grid.size = 2 ) expect_equal(pdp.obj.a$results, pdp.objs$effects$a$results) })
CUSUMLM <- function(x,d,delta,tau=0.15) { if (any(is.na(x))) stop("x contains missing values") if(tau<=0 | tau>=1) stop("It must hold that 0<tau<1") if(delta<0.6 | delta>0.8) stop("It must hold that 0.6<delta<0.8") if (mode(x) %in% ("numeric") == FALSE | is.vector(x) == FALSE) stop("x must be a univariate numeric vector") if(tau!=0.15) warning("Critical values are just implemented for tau=0.15") T <- length(x) G <- LongMemoryTS::G.hat(as.matrix(x), d, m=floor(1+T^(delta))) if(d!=0) { C2 <- gamma(1-2*d)*G*2*sin(pi*d)/(d*(1+2*d)) enumerator <- c(T^(-1/2-d)/sqrt(C2))*cumsum(x-mean(x)) }else { C2 <- 2*pi*G enumerator <- c(T^(-1/2-d)/sqrt(C2))*cumsum(x-mean(x)) } crit_values <- CV_shift(d=d,procedure="cusumlm",param=0) testCUSUMLM <- max(abs(enumerator[(T*tau):(T*(1-tau))])) result <- c(crit_values,testCUSUMLM) names(result)<- c("90%","95%","99%","Teststatistic") return(round(result,3)) }
.mask <- function (mol, map, mask) { count <- .jcall(mol, 'I', 'getAtomCount') atoms <- c(0:(count-1)) atoms <- atoms[!atoms %in% map$mapping[[1]]] if (!is.null(mask)) { .jcall(mol, 'V', 'add', mask) newAtom <- .jcall(mol, 'Lorg/openscience/cdk/interfaces/IAtom;', 'getLastAtom') } mapping <- sort(map$mapping[[1]], TRUE) newAtomContainer <- .jnew('org/openscience/cdk/AtomContainer') for (atomNo in mapping) { atom <- .jcall(mol, 'Lorg/openscience/cdk/interfaces/IAtom;', 'getAtom', atomNo) connectedAtoms <- as.list(.jcall(mol, 'Ljava/util/List;', 'getConnectedAtomsList', atom)) for (nbdAtom in connectedAtoms) { nbdAtom <- .jcast(nbdAtom, 'org/openscience/cdk/interfaces/IAtom') nbdAtomNo <- .jcall(mol, 'I', 'getAtomNumber', nbdAtom) bond <- .jcall(mol, 'Lorg/openscience/cdk/interfaces/IBond;', 'removeBond', atom, nbdAtom) if (!nbdAtomNo %in% map$mapping[[1]]) { if (!is.null(mask)) { .jcall(bond, 'V', 'setAtoms', .jarray(c(nbdAtom, newAtom), contents.class = 'org/openscience/cdk/interfaces/IAtom')) .jcall(mol, 'V', 'addBond', bond) } } } .jcall(newAtomContainer, 'V', 'addAtom', atom) } nAC <- .jcast(newAtomContainer, 'org/openscience/cdk/interfaces/IAtomContainer') .jcall(mol, 'V', 'remove', nAC) } .meta.mask <- function(substructure, mask, mol, recursive) { smi <- tryCatch({ while(1) { if (mask != '') { maskX <- .smilesParser(mask, F, F) } else { maskX <- NULL } tryCatch({ map <- rcdk::matches(substructure, mol, return.matches = T) }, error = function(err) { stop('Unable to find matches.', call. = F) }) if (map[[1]]$match == TRUE) { .mask(mol, map[[1]], maskX) } else { break } if(recursive == FALSE) { break } } smi <- get.smiles(mol) }, error = function (err) { stop (err) }) return(smi) } ms.mask <- function (substructure, mask, molecule, format = 'smiles', standardize = T, explicitH = F, recursive = F) { if(missing(substructure) || substructure == '') { stop('Enter a structure to mask in form of a SMILES or SMARTS.', call. = F) } if(missing(mask)) { stop('Mask not specified.', call. = F) } if(missing(molecule)) { stop('Input molecule missing.', call. = F) } format <- tolower(format) smi <- tryCatch({ if (format[[1]] == 'smiles') { mol <- .smilesParser(molecule, standardize = standardize, explicitH = explicitH) } else if (format[[1]] == 'mol') { mol <- .molParser(molecule, standardize = standardize, explicitH = explicitH) } else { stop("Invalid input format.", call. = F) } mask <- sub('\\s+', '', mask) .meta.mask(substructure, mask, mol, recursive) }, error = function (err) { stop (err) }) return(smi) } .rct.mask <- function (substructure, mask, rct, recursive) { rct <- tryCatch({ mask <- sub('\\s+', '', mask) for (mol in rct$Reactants) { .meta.mask(substructure, mask, mol, recursive) } for (mol in rct$Products) { .meta.mask(substructure, mask, mol, recursive) } react <- paste(lapply(rct$Reactants, get.smiles), collapse = '.') react <- sub('\\.+', '.', react) react <- sub('^\\.', '', react) react <- sub('\\.$', '', react) prod <- paste(lapply(rct$Products, get.smiles), collapse = '.') prod <- sub('\\.+', '.', prod) prod <- sub('^\\.', '', prod) prod <- sub('\\.$', '', prod) rct$RSMI <- paste(react, prod, sep=">>") rct }, error = function (err) { stop (err) }) return(rct) } rs.mask <- function (substructure, mask, reaction, format = 'rsmi', standardize = T, explicitH = F, recursive = F) { if(missing(substructure) || substructure == '') { stop('Enter a structure to mask in form of a SMILES or SMARTS.', call. = F) } if(missing(mask)) { stop('Mask not specified.', call. = F) } if(missing(reaction)) { stop('Input reaction missing.', call. = F) } format <- tolower(format) rsmi <- tryCatch({ if (format[[1]] == 'rsmi') { rct <- .rsmiParser(reaction, standardize = standardize, explicitH = explicitH) } else if (format[[1]] == 'rxn') { rct <- .mdlParser(reaction, standardize = standardize, explicitH = explicitH) } else { stop("Invalid input format.", call. = F) } rct <- .rct.mask(substructure, mask, rct, recursive) rct$RSMI }, error = function (err) { stop (err) }) return(rsmi) }
nR <- 100L; nC <- 5L X <- array(rnorm(nR * nC),dim = c(nR,nC)); y <- rnorm(nC) OF1 <- function(param, X, y) max(abs(y - X %*% param)) createF <- function(X, y) { newFun <- function(param) max(abs(y - X %*% param)) newFun } OF2 <- createF(X, y) param <- rnorm(nC) OF1(param, X, y) OF2(param) remove(list = c("X","y"), envir = .GlobalEnv); ls() OF1(param,X,y) OF2(param) environment(OF2) whereToLook <- environment(OF2) ls(envir = whereToLook)
extractCode <- function(url, files = NULL, output = FALSE){ .Deprecated(msg = "'extractCode()' will be removed in the next version\nUse 'rpubs_code()' instead") pg <- read_html(url) iframe_link <- paste0("http:", html_attr( html_nodes( html_nodes( html_nodes( html_nodes(pg, "body"), "div "div "iframe"), "src") ) if(output){ node <- "pre" } else { node <- "pre.r" } code <- html_text( html_nodes( read_html(iframe_link), node) ) if(is.null(files)){ paste0(sprintf(" } else { writeLines(text = paste0(sprintf(" } }
plot.KW2 <- function(x, smooth = 0, pal = NULL, inches = 1/6, N = 25, tol = 0.001, ...){ W <- x$W s <- (W > tol) D <- data.frame(w = W[s], x = x$uv[s,1], y = x$uv[s,2]) if(smooth > 0){ uv <- x$uv mu <- mv <- 40 ru <- range(uv[s, 1]) rv <- range(uv[s, 2]) u <- seq(ru[1] - 4 * smooth, ru[2] + 4 * smooth, length = mu) v <- seq(rv[1] - 4 * smooth, rv[2] + 4 * smooth, length = mv) fs <- matrix(0, mu, mv) for (i in 1:mu) { for (j in 1:mv) { Z <- cbind(u[i] - uv[, 1], v[j] - uv[, 2]) fs[i, j] <- sum(mvtnorm::dmvnorm(Z, sigma = diag(2) * smooth) * W) } } contour(u, v, matrix(fs,mu,mv), ...) } else{ if(!length(pal)) pal <- heat.colors(N, alpha = .5) with(D, { bg <- round(1 + 10 * (1 - w/max(w))) symbols(x = x, y = y, circles = sqrt(w), inches = inches, fg = "grey30", bg = bg, ...) palette(pal) }) } }
ReadZotero <- function(user, group, .params, temp.file = tempfile(fileext = ".bib"), delete.file = TRUE){ if (!requireNamespace("bibtex")){ message("Sorry this feature currently cannot be used without the ", dQuote("bibtex"), " package installed.\nPlease install from ", "GitHub using the ", dQuote("remotes"), " (or ", dQuote("devtools"), ") package:\n\n", "remotes::install_github(\"ROpenSci/bibtex\")") return(invisible()) } if (delete.file) on.exit(unlink(temp.file, force = TRUE)) bad.ind <- which(!names(.params) %in% c("q", "itemType", "tag", "collection", "key", "limit", "start", "qmode")) .parms <- .params if (length(bad.ind)){ warning("Invalid .params specified and will be ignored") .parms <- .parms[-bad.ind] } .parms$format <- "bibtex" if (is.null(.parms$limit)) .parms$limit <- 99L coll <- if (is.null(.parms$collection)) NULL else paste0("/collections/", .parms$collection) .parms$uri <- paste0("https://api.zotero.org/", if (!missing(user)) paste0("users/", user) else paste0("groups/", group), coll, "/items") uri <- paste0("https://api.zotero.org/", if (!missing(user)) paste0("users/", user) else paste0("groups/", group), coll, "/items") res <- GET(uri, query = .parms) res <- content(res, as = "text", encoding = "UTF-8") if (.is_not_nonempty_text(res)){ print("No results.") return() } write(res, file=temp.file, append = TRUE) bib.res <- try(ReadBib(file=temp.file, .Encoding="UTF-8"), TRUE) if (inherits(bib.res, "try-error")){ stop(gettextf("Could not parse the returned BibTeX results. If %s %s%s", sQuote("delete.file"), "is FALSE, you can try viewing and editing the file: ", temp.file)) } bib.res }
teamBowlingWicketKindAllOppnAllMatches <- function(matches,t1,t2="All",plot=1){ noBalls=wides=team=runs=bowler=wicketKind=wicketPlayerOut=NULL ggplotly=NULL team=bowler=ball=wides=noballs=runsConceded=overs=NULL over=wickets=NULL a <- NULL if(t2 == "All"){ a <-filter(matches,team==t1) } else { a <-filter(matches,team==t2) } a1 <- unlist(strsplit(a$ball[1],"\\.")) a2 <- paste(a1[1],"\\.",sep="") b <- a %>% select(bowler,ball,noballs,wides,runs,wicketKind,wicketPlayerOut) %>% mutate(over=gsub(a2,"",ball)) %>% mutate(over=gsub("\\.\\d+","",over)) c <- b %>% select(bowler,wicketKind,wicketPlayerOut) %>% filter(wicketPlayerOut != "nobody") d <- summarise(group_by(c,bowler),wickets=length(wicketPlayerOut)) e <- arrange(d,desc(wickets)) f <- e[1:8,] g <- as.character(f$bowler) n <- NULL for(m in 1:8){ mm <- filter(c,bowler==g[m]) n <- rbind(n,mm) } p <- summarise(group_by(n,bowler,wicketKind),m=n()) if(plot == 1){ plot.title <- paste(t1,"vs",t2,"wicket-kind of bowlers") ggplot(data=p,aes(x=wicketKind,y=m,fill=factor(wicketKind))) + facet_wrap( ~ bowler,scales = "fixed", ncol=8) + geom_bar(stat="identity") + xlab("Wicket kind") + ylab("Wickets") + ggtitle(bquote(atop(.(plot.title), atop(italic("Data source:http://cricsheet.org/"),"")))) + theme(axis.text.x = element_text(angle = 90, hjust = 1)) } else if(plot == 2){ plot.title <- paste(t1,"vs",t2,"wicket-kind of bowlers") g <- ggplot(data=p,aes(x=wicketKind,y=m,fill=factor(wicketKind))) + facet_wrap( ~ bowler,scales = "fixed", ncol=8) + geom_bar(stat="identity") + xlab("Wicket kind") + ylab("Wickets") + ggtitle(plot.title) + theme(axis.text.x = element_text(angle = 90, hjust = 1)) ggplotly(g,height=500) }else{ p } }
.margins.param.est <- function(copula, margins, x, param, param.est, df, df.est, dispstr, lower, upper, flip) { if (copula == "gaussian") { warning( "Please note that the old (pre 0.1-3) term 'gaussian' was replaced with 'normal'." ) copula <- "normal" } if (df.est == TRUE) { df.fixed <- FALSE } else if (df.est == FALSE) { df.fixed <- TRUE } if (length(margins) > 1 & length(margins) != dim(x)[2]) { stop(paste( "If length(margins)>1, then the number of entries has to fit the number of data sequences. You included ", length(margins), " distributions, though ", dim(x)[2], " data sequences are used. Please amend and run the function again." )) } if (any(!is.element(margins, c("ranks", "beta", "cauchy", "chisq", "f", "gamma", "lnorm", "norm", "t", "weibull", "exp")))) { stop( "At least one of the distributions in `margins' is not implemented. Please amend and run the function again. It has to be either of `ranks', `beta', `cauchy', `chisq', `f', `gamma', `lnorm', `norm', `t', `weibull', `exp'." ) } param.margins <- NULL if (!is.null(margins)) { cat(paste("The margins will be estimated as: ", paste0(margins, collapse = ", "), sep = ""), fill = TRUE) res.margins <- .margins(x, margins) param.margins <- list() if (length(margins) == 1) { margins.dummy <- rep(margins, dim(x)[2]) } else { margins.dummy <- margins } for (i in seq_along(margins.dummy)) { if (margins.dummy[i] == "ranks") { x[, i] <- res.margins[[i]][[1]] } else { param.margins[[i]] <- res.margins[[i]][[1]] x[, i] <- res.margins[[i]][[2]] } } } else { if (any(x > 1) || any(x < 0)) { cat( "The observations aren't in [0,1]. This will lead to errors while the estimation. Please set 'margins' to any of the incorporated functions.", fill = TRUE) } } if (!is.null(flip)) { if (!is.element(flip, c(0,90,180,270))) { stop("flip has to be either of NULL, 0, 90, 180, 270.") } x = .rotateCopula(x = x, flip = flip) if (flip == 0) {flip = NULL} } if ("normal" == copula) { if (param.est == TRUE) { param <- try(fitCopula(ellipCopula(copula, dim = dim(x)[2], df = df, df.fixed = df.fixed, dispstr = dispstr), data = x, method = "mpl", estimate.variance = FALSE, hideWarnings = TRUE, lower = lower, upper = upper)@estimate, silent = TRUE) estim.method <- "mpl" if (inherits(param, "try-error")) { warning( "Pseudo Maximum Likelihood estimation of the parameter failed. The estimation was performed with inversion of Kendall's Tau." ) param <- fitCopula(ellipCopula(copula, dim = dim(x)[2], df = df, df.fixed = df.fixed, dispstr = dispstr), data = x, method = "itau", estimate.variance = FALSE, hideWarnings = TRUE, lower = lower, upper = upper)@estimate estim.method <- "itau" } } copula <- ellipCopula(copula, param = param, dim = dim(x)[2], df = df, df.fixed = TRUE, dispstr = dispstr) estim.method <- "mpl" if (inherits(copula, "indepCopula")) { stop( "The parameter estimation is at boundary and an independence copula was returned." ) } } else if ("t" == copula) { if (param.est == TRUE) { lower.t <- lower upper.t <- upper if (!is.null(lower) & df.est == TRUE) { lower.t <- c(lower, 0) } if (!is.null(upper) & df.est == TRUE) { upper.t <- c(upper, 1000) } param <- try(fitCopula(ellipCopula(copula, dim = dim(x)[2], df = df, df.fixed = df.fixed, dispstr = dispstr), data = x, method = "mpl", estimate.variance = FALSE, hideWarnings = TRUE, lower = lower.t, upper = upper.t)@estimate, silent = TRUE) estim.method <- "mpl" if (inherits(param, "try-error")) { warning( "Pseudo Maximum Likelihood estimation of the parameter failed. The estimation was performed with inversion of Kendall's Tau. Therefore df.est was set to FALSE." ) param <- fitCopula(ellipCopula(copula, dim = dim(x)[2], df = df, df.fixed = TRUE, dispstr = dispstr), data = x, method = "itau", estimate.variance = FALSE, hideWarnings = TRUE, lower = lower, upper = upper)@estimate estim.method <- "itau" df.fixed <- TRUE df.est <- FALSE } } if (copula == "t" & df.fixed == FALSE & param.est == TRUE) { df <- tail(param, n = 1) copula <- ellipCopula(copula, param = param[-length(param)], dim = dim(x)[2], df = df, df.fixed = TRUE, dispstr = dispstr) estim.method <- "mpl" } else { copula <- ellipCopula(copula, param = param, dim = dim(x)[2], df = df, df.fixed = TRUE, dispstr = dispstr) estim.method <- "mpl" } if (inherits(copula, "indepCopula")) { stop( "The parameter estimation is at boundary and an independence copula was returned." ) } } else if ("clayton" == copula || "frank" == copula || "gumbel" == copula || "amh" == copula || "joe" == copula) { if (param.est == TRUE) { if ("clayton" == copula) { param <- try(fitCopula(archmCopula(copula, dim = dim(x)[2]), data = x, method = "mpl", estimate.variance = FALSE, hideWarnings = TRUE, lower = lower, upper = upper)@estimate, silent = TRUE) estim.method <- "mpl" if (inherits(param, "try-error")) { warning( "Pseudo Maximum Likelihood estimation of the parameter failed. The estimation was performed with inversion of Kendall's Tau." ) param <- fitCopula(archmCopula(copula, dim = dim(x)[2]), data = x, method = "itau", estimate.variance = FALSE, hideWarnings = TRUE, lower = lower, upper = upper)@estimate estim.method <- "itau" } } else { param <- try(fitCopula(archmCopula(copula, dim = dim(x)[2]), data = x, method = "mpl", estimate.variance = FALSE, hideWarnings = TRUE, lower = lower, upper = upper)@estimate, silent = TRUE) estim.method <- "mpl" if (inherits(param, "try-error")) { warning( "Pseudo Maximum Likelihood estimation of the parameter failed. The estimation was performed with inversion of Kendall's Tau." ) param <- fitCopula(archmCopula(copula, dim = dim(x)[2]), data = x, method = "itau", estimate.variance = FALSE, hideWarnings = TRUE, lower = lower, upper = upper)@estimate estim.method <- "itau" } } } if (copula == "clayton" & dim(x)[2] > 2 & param < 0) { stop( "The dependence parameter is negative for the dataset. For the clayton copula this cannot be the case. Therefore is this not an appropriate copula for the dataset. Please consider to use another one." ) } if (copula == "frank" & dim(x)[2] > 2 & param < 0) { stop( "The dependence parameter is negative for the dataset. For the frank copula can this be only the case if the dimension is 2. Therefore is this not an appropriate copula for the dataset. Please consider to use another one." ) } copula <- archmCopula(copula, param = param, dim = dim(x)[2]) estim.method <- "mpl" if (inherits(copula, "indepCopula")) { stop( "The parameter estimation is at boundary and an independence copula was returned." ) } } else if ("galambos" == copula || "huslerReiss" == copula || "tawn" == copula) { if (param.est == TRUE) { param <- try(fitCopula(evCopula(copula, dim = dim(x)[2]), data = x, method = "mpl", estimate.variance = FALSE, hideWarnings = TRUE, lower = lower, upper = upper)@estimate, silent = TRUE) estim.method <- "mpl" if (inherits(param, "try-error")) { warning( "Pseudo Maximum Likelihood estimation of the parameter failed. The estimation was performed with inversion of Kendall's Tau." ) param <- fitCopula(evCopula(copula, dim = dim(x)[2]), data = x, method = "itau", estimate.variance = FALSE, hideWarnings = TRUE, lower = lower, upper = upper)@estimate estim.method <- "itau" } } copula <- evCopula(copula, param = param, dim = dim(x)[2]) estim.method <- "mpl" if (inherits(copula, "indepCopula")) { stop( "The parameter estimation is at boundary and an independence copula was returned." ) } } else if ("tev" == copula) { if (param.est == TRUE) { lower.t <- lower upper.t <- upper if (!is.null(lower) & df.est == TRUE) { lower.t <- c(lower, 0) } if (!is.null(upper) & df.est == TRUE) { upper.t <- c(upper, 1000) } param <- try(fitCopula(evCopula(copula, dim = dim(x)[2], df = df, df.fixed = df.fixed), data = x, method = "mpl", estimate.variance = FALSE, hideWarnings = TRUE, lower = lower.t, upper = upper.t)@estimate, silent = TRUE) estim.method <- "mpl" if (inherits(param, "try-error")) { warning( "Pseudo Maximum Likelihood estimation of the parameter failed. The estimation was performed with inversion of Kendall's Tau. Therefore df.est was set to FALSE." ) param <- fitCopula(evCopula(copula, dim = dim(x)[2], df = df, df.fixed = TRUE), data = x, method = "itau", estimate.variance = FALSE, hideWarnings = TRUE, lower = lower, upper = upper)@estimate estim.method <- "itau" df.fixed <- TRUE df.est <- FALSE } } if (copula == "tev" & df.fixed == FALSE & param.est == TRUE) { df <- tail(param, n = 1) copula <- evCopula(copula, param = param[-length(param)], dim = dim(x)[2], df = df, df.fixed = TRUE) estim.method <- "mpl" } else { copula <- evCopula(copula, param = param, dim = dim(x)[2], df = df, df.fixed = TRUE) estim.method <- "mpl" } if (inherits(copula, "indepCopula")) { stop( "The parameter estimation is at boundary and an independence copula was returned." ) } } else if ("fgm" == copula) { if (param.est == TRUE) { param <- try(fitCopula(fgmCopula(dim = dim(x)[2]), data = x, method = "mpl", estimate.variance = FALSE, hideWarnings = TRUE, lower = lower, upper = upper)@estimate, silent = TRUE) estim.method <- "mpl" if (inherits(param, "try-error")) { warning( "Pseudo Maximum Likelihood estimation of the parameter failed. The estimation was performed with inversion of Kendall's Tau." ) param <- fitCopula(fgmCopula(dim = dim(x)[2]), data = x, method = "itau", estimate.variance = FALSE, hideWarnings = TRUE, lower = lower, upper = upper)@estimate estim.method <- "itau" } } copula <- fgmCopula(param = param, dim = dim(x)[2]) estim.method <- "mpl" if (inherits(copula, "indepCopula")) { stop( "The parameter estimation is at boundary and an independence copula was returned." ) } } else if ("plackett" == copula) { if (param.est == TRUE) { param <- try(fitCopula(plackettCopula(), data = x, method = "mpl", estimate.variance = FALSE, hideWarnings = TRUE, lower = lower, upper = upper)@estimate, silent = TRUE) estim.method <- "mpl" if (inherits(param, "try-error")) { warning( "Pseudo Maximum Likelihood estimation of the parameter failed. The estimation was performed with inversion of Kendall's Tau." ) param <- fitCopula(plackettCopula(), data = x, method = "itau", estimate.variance = FALSE, hideWarnings = TRUE, lower = lower, upper = upper)@estimate estim.method <- "itau" } } copula <- plackettCopula(param = param) estim.method <- "mpl" if (inherits(copula, "indepCopula")) { stop( "The parameter estimation is at boundary and an independence copula was returned." ) } } if (any([email protected] == copula@parameters || [email protected] == copula@parameters)) { stop( "The provided or estimated copula parameter, performed with the copula package, is at its boundary. The copula is excluded from the analysis since this leads to very instable results for the GoF tests. Please consider amending the parameter or control its estimation via the upper and lower bounds." ) } return(list(copula, x, estim.method, param.margins, df.est, flip)) }
print_info<-echo<-FALSE est2list<-function(x){ if (is(x,"list")){zx<-lapply(x,est2list);return(zx)} slnm<-slotNames(x) if(!isS4(x)){return(x)} z<-lapply(1:length(slnm),function(i){ z1<-eval(parse(text=paste("x@",slnm[i],sep=""))) if(!isS4(z1)){return(z1)} else {z1<-est2list(x=z1)} z1}) names(z)<-slnm assert.is(z,"list") class(z)<-c("list",paste(class(x),"list",sep=".")) z } assert.is <- function(object, class2, text = ""){ stopifnot(is.character(class2)) if(missing(object)) stop(paste(class2, "object missing in assert.is", text)) stopifnot(length(class2) >= 1) if(!is_any(object = object, class2 = class2)) { warning(paste("got ", class(object), sep = "")) message("got ", class(object), " when one of these classes was required:") print(class2) stop(text) } } assert.are <- function(object, class2, ...){ assert.is(object, "list") if(!is_nothing(object)){ for(obj in object) assert.is(object = obj, class2 = class2, ...) } } are <- function(object, class2){all(sapply(object, is_any, class2 = class2))} are_null <- function(object){are(object, "NULL")} is_vide<-is_nothing<-function(object){length(object)==0} is_any <- function(object, class2){any(sapply(class2, is, object = object))} setGeneric("is_prob", function(object,...) standardGeneric("is_prob")) setMethod("is_prob",signature(object = "numeric" ), function(object,tolerance = 1e-3, ...){ boo <- all(object >= 0 - tolerance & object <= 1 + tolerance, ...) !is.na(boo) && boo}) are_prob <- function(object, ...){all(sapply(object, is_prob, ...))} is_err <- function(object){is(object, "try-error")} is_error <- function(object){is(object, "try-error")||is_nothing(object)} is_unk <- function(object){all(is_any(object,c("try-error","NULL")))||all(is.na(object))||is_nothing(object)} are_unk <- function(object){all(sapply(object, is_unk))} nsize<-function(x){ if(is_any(x,c("list","NULL","numeric","logical","character"))){c(1,length(x))} else if(is_any(x,c("matrix","array","data.frame"))){c(nrow(x),ncol(x))} else if(is_nothing(x)){c(0,0)} else {c(length(x),1)} } vect2string<-function(x,sep="",...){paste(x,sep="",collapse=sep,...)} make_labels<-function(n,nmvar=c("X"),n.ini=1){n.ini<-n.ini[1] if(is_vide(n)){return(NULL)} stopifnot(n>0) paste(nmvar[1],c(1:n)+n.ini-1,sep="") } MakeNames<-function(x,nmvar=c("X","I"),...){ k.MakeNames<-function(x,col=T,nmvar="I",force=FALSE,unique=T,n0=1){ if(is_nothing(x)){return(x)} k.nms<-function(nm,nn){ if(is_nothing(nm) | all(is_unk(nm)) | force==T ){ nm<-make_labels(n=nn,nmvar=nmvar[1],n.ini=n0[1])} if(any(is.na(nm))){ind<-which(is.na(nm));nm[ind]<-paste(nmvar[1],ind,sep="")} if(unique==T){nm<-make.unique(nm)} nm } if(is_any(x,c("numeric","logical","character","list"))){ nm<-k.nms(nm=names(x),nn=length(x)) names(x)<-nm;return(x)} assert.is(x,c("matrix","array","data.frame")) nn<-nsize(x) if(col){nm<-colnames(x);nn<-nn[2]} else{nm<-rownames(x);nn<-nn[1]} nm<-k.nms(nm=nm,nn=nn) if(col){colnames(x)<-nm} else{rownames(x)<-nm} x } if(is_any(x,c("numeric","logical","character","list"))){ x<-k.MakeNames(x=x,nmvar=nmvar[1],...)} else if(is_any(x,c("array","matrix","data.frame"))){ x<-k.MakeNames(x,col=T,nmvar=nmvar[pmax(2,length(nmvar))],...) x<-k.MakeNames(x,col=F,nmvar=nmvar[1],...) } x } sameAsX_names<-function(x=NULL,y=NULL){ assert.are(list(x,y),c("numeric","logical","character")) stopifnot(class(x)==class(y)) x<-MakeNames(x,nmvar="X") y<-MakeNames(y,nmvar="X") stopifnot(length(x)>=length(y)) if(are(list(x,y),"numeric")){zz<-as.numeric(NA)} else if(are(list(x,y),"character")){zz<-as.character(NA)} else if(are(list(x,y),"logical")){zz<-NA} z<-rep(zz,length(x));names(z)<-names(x) z[names(y)]<-y stopifnot(identical(names(x),names(z))) z } dabsTd<-function(x,df,ncp=0,...){dt(x=x,df=df,ncp=ncp,...)+dt(x=-x,df=df,ncp=ncp,...)} attr(dabsTd,'name')<-'dabsTd' setClass("est.lfdrmle", representation(LFDR.hat ="numeric",p0.hat = "numeric", ncp.hat= "numeric", stat="numeric",info="list")) setValidity("est.lfdrmle", function(object) { dx<[email protected] p0<[email protected] ncp<[email protected] stx<-object@stat ix<-object@info nvar<-length(stx) stopifnot(length(names(dx))>0) stopifnot(all(c(length(p0),length(ncp))%in%c(1,nvar))) stopifnot(length(stx)==length(dx)&&identical(names(stx),names(dx))) if(!are_prob(list(dx[is.finite(dx)],p0[is.finite(p0)]))){stop("error:LFDR.hat or p0.hat out of [0,1]")} }) new_est.lfdrmle <- function(LFDR.hat,p0.hat,ncp.hat,stat,method=NULL,info=list()){ if(is_nothing(method)){method<-"lfdr.mle"} if(!is(info,"list")){info<-list()} assert.is(LFDR.hat,c("NULL","numeric","logical","try-error")) assert.is(stat,c("numeric","logical")) stopifnot(length(stat)>=length(LFDR.hat)) if(is_error(LFDR.hat)){ message(method," estimation failed ",Sys.time()) LFDR.hat<-rep(as.numeric(NA),length(stat)) names(LFDR.hat)<-names(stat) method<-paste("FAILED-",method,sep="") p0.hat<-ncp.hat<-as.numeric(NA) } nvar<-length(stat) if(is(stat,"logical")){xx<-as.numeric(stat);names(xx)<-names(stat);stat<-xx} if(is(LFDR.hat,"logical")){xx<-as.numeric(LFDR.hat);names(xx)<-names(LFDR.hat);LFDR.hat<-xx} if(is(p0.hat,"logical")){xx<-as.numeric(p0.hat);names(xx)<-names(p0.hat);p0.hat<-xx} if(is(ncp.hat,"logical")){xx<-as.numeric(ncp.hat);names(xx)<-names(ncp.hat);ncp.hat<-xx} assert.are(list(LFDR.hat,p0.hat,ncp.hat,stat),"numeric") stat<-MakeNames(stat,nmvar="X") LFDR.hat<-MakeNames(LFDR.hat,nmvar="X") if(length(ncp.hat)==nvar){names(ncp.hat)<-names(LFDR.hat)} else if(length(ncp.hat)==1){names(ncp.hat)<-NULL} if(length(p0.hat)==nvar){names(p0.hat)<-names(LFDR.hat)} else if(length(p0.hat)==1){names(p0.hat)<-NULL} LFDR.hat<-sameAsX_names(y=LFDR.hat,x=stat) if(length(ncp.hat)>1&&length(stat)>1){ ncp.hat<-sameAsX_names(y=ncp.hat,x=stat) p0.hat<-sameAsX_names(y=p0.hat,x=stat) stopifnot(identical(names(stat),names(p0.hat)) && identical(names(LFDR.hat),names(ncp.hat)))} stopifnot(all(c(length(p0.hat),length(ncp.hat))%in%c(1,nvar))) infox<-c(list(method=toupper(method)),info) new("est.lfdrmle",LFDR.hat=LFDR.hat, p0.hat=p0.hat,ncp.hat=ncp.hat,stat=stat,info=infox) } setMethod("[", signature(x = "est.lfdrmle", i = "ANY", j = "missing"), function(x, i, j, drop){ z<-x nvar<-length([email protected]) [email protected] <- [email protected][i];names([email protected])<-names([email protected])[i] z@stat <- x@stat [i];names(z@stat)<-names([email protected])[i] if(length([email protected])==nvar){[email protected] <- [email protected][i];names([email protected])<-names([email protected])[i]} if(length([email protected])==nvar){[email protected] <- [email protected][i];names([email protected])<-names([email protected])[i]} stopifnot(validObject(z)) z}) setReplaceMethod("names", signature(x="est.lfdrmle",value="character"),function(x, value){ nvar<-length([email protected]) stopifnot(length(value)==nvar) names([email protected])<-value names(x@stat) <- value if(length([email protected])==nvar){names([email protected]) <- value} if(length([email protected])==nvar){names([email protected]) <- value} stopifnot(validObject(x)) x}) setMethod("names", signature(x = "est.lfdrmle"), function(x){names([email protected])}) setMethod("as.numeric", signature(x="est.lfdrmle"),function(x) {[email protected]}) setMethod("length", signature(x = "est.lfdrmle"), function(x){length(as.numeric(x))}) setMethod("is_prob",signature(object = "est.lfdrmle" ), function(object,tolerance = 1e-3, ...){ is_prob([email protected],tolerance =tolerance,...) && is_prob([email protected],tolerance =tolerance,...)}) k.log_wlik_mixture <- function(W,p0,dalt,dFUN,d0=0,w=1,...){sum(w*log(p0*dFUN(W,ncp=d0,...) +(1-p0)*dFUN(W,ncp=dalt,...)))} k.get_wd_max <- function(W,p0,dFUN,lower.ncp=1/1e3, upper.ncp=100,d0=0,w=1,...){ f <- function(dalt){k.log_wlik_mixture(p0=p0,W=W,dalt=dalt,w=w,dFUN=dFUN,d0=d0,...)} as.numeric(optimize(f, lower=lower.ncp, upper=upper.ncp,maximum=TRUE))[1] } k.get_wp0_max <- function(W,dalt,dFUN=dabsTd, lower.p0=0, upper.p0=1,d0=0,w=1, ...){ f <- function(p0){k.log_wlik_mixture(p0=p0,W=W,dalt=dalt,w=w,dFUN=dFUN,d0=d0,...)} as.numeric(optimize(f, lower=lower.p0, upper=upper.p0,maximum=TRUE))[1] } k.get_wlfdr <- function(W,p0,dalt,dFUN,d0=0,w=1,...){ zo<-(p0*dFUN(W,ncp=d0,...))/(p0*dFUN(W,ncp=d0,...)+(1-p0)*dFUN(W,ncp=dalt,...))^w names(zo)<-names(W);zo } k.N_wlik <- function( W, dFUN, lower.ncp, upper.ncp, lower.p0, upper.p0,d0,w=1,...){ p0_max<-d_max<-NULL if(lower.p0==upper.p0){p0_max <- lower.p0} if(lower.ncp==upper.ncp){d_max <- lower.ncp} if(!is.null(p0_max)&&!is.null(d_max)){zo<-c(p0_max,d_max);names(zo)<-c("p0.max","ncp.max");return(zo)} if(is.null(p0_max)&&is.null(d_max)){ ff <- function(p0){ dalt<-k.get_wd_max(p0=p0,W=W,w=w,dFUN=dFUN,lower.ncp=lower.ncp,upper.ncp=upper.ncp,d0=d0,...) k.log_wlik_mixture(p0=p0,W=W,w=w,dalt=dalt,dFUN=dFUN,d0=d0,...)} p0_opt_result <- optimize(ff, lower=lower.p0, upper=upper.p0, maximum=TRUE) p0_max <- as.numeric(p0_opt_result[1]) } if(is.null(p0_max)&&!is.null(d_max)){ p0_max <- k.get_wp0_max(dalt=d_max, W=W,w=w,dFUN=dFUN, lower.p0=lower.p0, upper.p0=upper.p0,d0=d0,...) } if(!is.null(p0_max)&&is.null(d_max)){ d_max <- k.get_wd_max(p0=p0_max, W=W,w=w,dFUN=dFUN, lower.ncp=lower.ncp, upper.ncp=upper.ncp,d0=d0,...)} if(!is_prob(p0_max)){stop("p0_max should be in [0,1]")} zo<-c(p0_max,d_max); return(zo) } k.lfdr.mle<- function(stat,dFUN,lower.ncp=1/1e3,upper.ncp=200,lower.p0=0,upper.p0=1, d0=0,w=1,fixed.p0=NULL,fixed.ncp=NULL,...){ if(length(fixed.p0)>0){stopifnot(is_prob(fixed.p0));lower.p0<-upper.p0<-fixed.p0 } if(length(fixed.ncp)>0){lower.ncp<-upper.ncp<-fixed.ncp} opt <- try(k.N_wlik(W=stat,w=w,d0=d0,dFUN=dFUN,lower.ncp=lower.ncp,upper.ncp=upper.ncp,lower.p0=lower.p0,upper.p0=upper.p0,...),silent=F) if(is_err(opt)){return(list())} lfdr_mix <- k.get_wlfdr(W=stat,w=1,p0=opt[1],dalt=opt[2],dFUN=dFUN,d0=d0,...) if(is_err(lfdr_mix)){return(list())} list(lfdr=lfdr_mix,p0=opt[1],ncp=opt[2]) } k.perfeat<-function(stat,w=1,v,dFUN=dabsTd,d0,fixed.p0=NULL,fixed.ncp=NULL,lower.ncp=1/1e3, upper.ncp=200, lower.p0=0, upper.p0=1,...){ assert.are(list(stat,d0,v,w), "numeric");nvars<-length(stat) stopifnot(is_prob(v)) if(length(w)==1){w<-rep(w,length(stat))} if(abs(sum(w)-1)>1e-3){w<-w/sum(w)} wz<-wx<-w k.fun<-function(i){ wx[i]<-v*wz[i]; vars<- which(c(1:nvars)!=i) xt<-stat[vars];xp<-stat[i] stopifnot(all(wx>=0)) zvar<-k.lfdr.mle(stat=stat,dFUN=dFUN,lower.ncp=lower.ncp,upper.ncp=upper.ncp,lower.p0=lower.p0,upper.p0=upper.p0, fixed.p0=fixed.p0,fixed.ncp=fixed.ncp,d0=d0,w=wx,...) z1<-k.lfdr.mle(stat=xp,dFUN=dFUN,lower.ncp=lower.ncp,upper.ncp=upper.ncp,lower.p0=lower.p0,upper.p0=upper.p0, fixed.ncp=zvar$ncp,fixed.p0=zvar$p0,d0=d0,w=1,...) c(z1$lfdr,z1$p0,z1$ncp) } zo<-try(vapply(1:nvars,FUN=k.fun,FUN.VALUE=numeric(length=3)),silent=F) if(is_err(zo)){return(list())} colnames(zo)<-names(stat) list(lfdr=zo[1,],p0=zo[2,],ncp=zo[3,]) } k.lo<-function(stat,w=1,v,dFUN=dabsTd,d0,fixed.p0=NULL,fixed.ncp=NULL,lower.ncp=1/1e3, upper.ncp=200, lower.p0=0, upper.p0=1,...){ z1<-k.lfdr.mle(stat = stat,d0=d0,w=w,dFUN=dFUN,fixed.p0=fixed.p0,lower.ncp=lower.ncp, upper.ncp=upper.ncp, lower.p0=lower.p0, upper.p0= upper.p0,fixed.ncp=fixed.ncp,...) fixed.p0<-z1$p0 assert.is(fixed.p0,"numeric");stopifnot(is_prob(fixed.p0)) k.perfeat(stat=stat,w=w,v=v,dFUN=dFUN,d0=d0,fixed.p0=fixed.p0,fixed.ncp=fixed.ncp, lower.ncp=lower.ncp,upper.ncp=upper.ncp, lower.p0=lower.p0, upper.p0= upper.p0,...) } k.checkings<-function(stat,dFUN,lower.ncp,upper.ncp,lower.p0,upper.p0,fixed.p0=NULL,fixed.ncp=NULL,v=1,d0=0,w=1,...){ if(all(is_unk(stat))){stop("invalid input")} assert.is(dFUN,"function") assert.are(list(stat,w,d0,v,lower.ncp,upper.ncp,lower.p0,upper.p0), "numeric") assert.are(list(fixed.p0,fixed.ncp), c("numeric","NULL")) nvars<-length(stat);if(nvars==0){return(NULL)} stat<-MakeNames(stat,nmvar="X") if(length(w)==1){w<-rep(w,nvars)} stopifnot(length(w)%in%c(1,nvars)) stopifnot(all(w>=0)) W<-nW<-stat pW<-dFUN(stat,ncp=0,...) ind<-which(is.finite(stat) & is.finite(pW)) if(length(ind)==0){stop("non finite statistic values")} stat<-stat[ind];w<-w[ind] if(length(fixed.p0)>0){stopifnot(is_prob(fixed.p0));lower.p0<-upper.p0<-fixed.p0 } if(length(fixed.ncp)>0){lower.ncp<-upper.ncp<-fixed.ncp} if(!are_prob(list(lower.p0, upper.p0,v))){stop("v, lower.p0 and upper.p0 should be in [0,1]")} stopifnot(lower.p0 <= upper.p0 && lower.ncp <= upper.ncp) nvars<-length(stat) stopifnot(length(w)%in%c(nvars)) stopifnot(all(w>=0)) if(abs(sum(w)-1)>1e-3){w<-w/sum(w)} if(abs(sum(w)-1)>1e-3){stop("problem with weights")} siz.num1<-(sapply(list(d0,v,lower.ncp,upper.ncp,lower.p0,upper.p0),length)) names(siz.num1)<-c("d0","v","lower.ncp","upper.ncp","lower.p0","upper.p0") siz.num0<-(sapply(list(fixed.p0,fixed.ncp),length)) names(siz.num0)<-c("fixed.p0","fixed.ncp") siz.numn<-(sapply(list(stat,w),length)) names(siz.numn)<-c("stat","w") if(!all(siz.num1%in%c(1))){ stop(paste("numeric inputs: ",vect2string(names(siz.num1[!siz.num1%in%1]),sep=" ")," have length !=1"))} if(!all(siz.num0%in%c(0,1))){ stop(paste("numeric inputs: ",vect2string(names(siz.num0[!siz.num0%in%c(0,1)]),sep=" ")," have length !=0 OR 1"))} if(!all(siz.numn%in%c(nvars))){ stop(paste("numeric inputs: ",vect2string(names(siz.num0[!siz.num0%in%c(nvars)]),sep=" ")," have length !=",nvars))} list(stat=stat,orig.stat=W,dFUN=dFUN,w=w,lower.ncp=lower.ncp,upper.ncp=upper.ncp,lower.p0=lower.p0,upper.p0=upper.p0, fixed.p0=fixed.p0,fixed.ncp=fixed.ncp,v=v,d0=d0) } lfdr.hats<-function(stat=NULL,lfdr.fun="lfdr.mle",dFUN=dabsTd,lower.ncp=1e-3,upper.ncp=20,lower.p0=0,upper.p0=1, fixed.p0=NULL,fixed.ncp=NULL,d0=0,v=1,w=1,...){ z<-k.checkings(stat=stat,w=w,v=v,dFUN=dFUN,d0=d0,lower.ncp=lower.ncp,upper.ncp=upper.ncp, lower.p0=lower.p0, upper.p0= upper.p0,fixed.p0=fixed.p0,fixed.ncp=fixed.ncp,...) if(lfdr.fun%in%c("lfdr.mle","mle","L0O","l0o")){z$w<-1 zo<-k.lfdr.mle(stat=z$stat,dFUN=z$dFUN,lower.ncp=z$lower.ncp,upper.ncp=z$upper.ncp,lower.p0=z$lower.p0, upper.p0=z$upper.p0,fixed.p0=z$fixed.p0,fixed.ncp=z$fixed.ncp,d0=z$d0,w=z$w,...) method<-"MLE" } else if(lfdr.fun%in%c("lfdr.mdl","mdl")){z$w<-1;z$v<-0 zo<-k.perfeat(stat=z$stat,w=z$w,v=z$v,dFUN=z$dFUN,d0=z$d0,fixed.p0=z$fixed.p0,fixed.ncp=z$fixed.ncp, lower.ncp=z$lower.ncp,upper.ncp=z$upper.ncp, lower.p0=z$lower.p0, upper.p0= z$upper.p0,...) method<-"MDL"} else if(lfdr.fun%in%c("lfdr.l1o","l1o","L1O")){z$w<-1;z$v<-0 zo<-k.lo(stat=z$stat,w=z$w,v=z$v,dFUN=z$dFUN,d0=z$d0,fixed.p0=z$fixed.p0,fixed.ncp=z$fixed.ncp, lower.ncp=z$lower.ncp,upper.ncp=z$upper.ncp, lower.p0=z$lower.p0, upper.p0= z$upper.p0,...) method<-"L1O" } else if(lfdr.fun%in%c("lfdr.lho","lho","LHO")){z$w<-1;z$v<-1/2 zo<-k.lo(stat=z$stat,w=z$w,v=z$v,dFUN=z$dFUN,d0=z$d0,fixed.p0=z$fixed.p0,fixed.ncp=z$fixed.ncp, lower.ncp=z$lower.ncp,upper.ncp=z$upper.ncp, lower.p0=z$lower.p0, upper.p0= z$upper.p0,...) method<-"LHO"} else if(lfdr.fun%in%c("lfdr.lo","lo","LO")){ zo<-k.lo(stat=z$stat,w=z$w,v=z$v,dFUN=z$dFUN,d0=z$d0,fixed.p0=z$fixed.p0,fixed.ncp=z$fixed.ncp, lower.ncp=z$lower.ncp,upper.ncp=z$upper.ncp, lower.p0=z$lower.p0, upper.p0= z$upper.p0,...) method<-paste("LO",round(z$v,1),sep="-v") } else if(lfdr.fun%in%c("lfdr.mdlo","mdlo","MDLO")){ zo<-k.perfeat(stat=z$stat,w=z$w,v=z$v,dFUN=z$dFUN,d0=z$d0,fixed.p0=z$fixed.p0,fixed.ncp=z$fixed.ncp, lower.ncp=z$lower.ncp,upper.ncp=z$upper.ncp, lower.p0=z$lower.p0, upper.p0= z$upper.p0,...) method<-paste("MDLO",round(z$v,1),sep="-v") } info<-z[c("lower.ncp","upper.ncp","lower.p0","upper.p0","fixed.p0","fixed.ncp","d0","v")] lix<-sapply(info,length) info<-info[lix>0] zo<-new_est.lfdrmle(LFDR.hat=zo$lfdr,p0.hat=zo$p0,ncp.hat=zo$ncp,stat=z$orig.stat,method=method,info=info) est2list(zo) } lfdr.mle<-function(x,dFUN=dabsTd, lower.ncp=1e-3,upper.ncp=20,lower.p0=0,upper.p0=1,fixed.p0=NULL,fixed.ncp=NULL,d0=0,...){ lfdr.hats(lfdr.fun="lfdr.mle",stat=x,dFUN=dFUN,lower.ncp=lower.ncp,upper.ncp=upper.ncp, lower.p0=lower.p0, upper.p0= upper.p0, fixed.p0=fixed.p0,fixed.ncp=fixed.ncp,d0=d0,w=1,v=1,...) } lfdr.mdl<-function(x,dFUN=dabsTd,lower.ncp=1e-3,upper.ncp=20,lower.p0=0,upper.p0=1,fixed.p0=NULL,fixed.ncp=NULL,d0=0,...){ lfdr.hats(lfdr.fun="lfdr.mdl",stat=x,dFUN=dFUN, w=1,v=0,d0=d0,lower.ncp=lower.ncp,upper.ncp=upper.ncp, lower.p0=lower.p0, upper.p0= upper.p0, fixed.p0=fixed.p0,fixed.ncp=fixed.ncp,...) } lfdr.l1o<-function(x,dFUN=dabsTd,lower.ncp=1e-3,upper.ncp=20,lower.p0=0,upper.p0=1,fixed.p0=NULL,fixed.ncp=NULL,d0=0,...){ lfdr.hats(lfdr.fun="lfdr.l1o",stat=x,dFUN=dFUN,w=1,v=0,d0=d0,lower.ncp=lower.ncp,upper.ncp=upper.ncp, lower.p0=lower.p0, upper.p0= upper.p0, fixed.p0=fixed.p0,fixed.ncp=fixed.ncp,...) } lfdr.lho<-function(x,dFUN=dabsTd,lower.ncp=1e-3,upper.ncp=20,lower.p0=0,upper.p0=1,fixed.p0=NULL,fixed.ncp=NULL,d0=0,...){ lfdr.hats(lfdr.fun="lfdr.lho",stat=x,dFUN=dFUN,w=1,v=1/2,d0=d0,lower.ncp=lower.ncp,upper.ncp=upper.ncp, lower.p0=lower.p0, upper.p0= upper.p0, fixed.p0=fixed.p0,fixed.ncp=fixed.ncp,...) } lfdr.lo<-function(x,dFUN=dabsTd,lower.ncp=1e-3,upper.ncp=20,lower.p0=0,upper.p0=1,fixed.p0=NULL,fixed.ncp=NULL,v=0,d0=0,...){ lfdr.hats(lfdr.fun="lfdr.lo",stat=x,dFUN=dFUN,w=1,v=v,d0=d0,lower.ncp=lower.ncp,upper.ncp=upper.ncp, lower.p0=lower.p0, upper.p0= upper.p0, fixed.p0=fixed.p0,fixed.ncp=fixed.ncp,...) } lfdr.mdlo<-function(x,v=0,dFUN=dabsTd,lower.ncp=1e-3,upper.ncp=20,lower.p0=0,upper.p0=1,fixed.p0=NULL,fixed.ncp=NULL,d0=0,...){ lfdr.hats(lfdr.fun="lfdr.mdlo",stat=x,dFUN=dFUN,w=1,v=v,d0=d0,lower.ncp=lower.ncp,upper.ncp=upper.ncp, lower.p0=lower.p0, upper.p0= upper.p0, fixed.p0=fixed.p0,fixed.ncp=fixed.ncp,...) } attr(lfdr.l1o,"name")<-"L1O" attr(lfdr.mdl,"name")<-"MDL" attr(lfdr.mle,"name")<-"MLE" attr(lfdr.lho,"name")<-"LHO" vectorized.dabsTd <- function(ncp, ...) {sapply(ncp, function(ncp) {dabsTd(ncp = ncp, ...)})} get_n.groups <- function(n.features,n.null,group.size){ n <- (n.features - n.null) if(group.size >n){ out <- 1 }else{ if((n %% group.size)!=0) { out <- floor(n/group.size)+1 }else{ out <- n/group.size } } out } get_groups <- function(n.features,n.null,n.groups){ n <- (n.features - n.null) out <- rep(floor(n / n.groups), n.groups) if((n %% n.groups) != 0) out[1:(n %% n.groups)] <- out[1:(n %% n.groups)] + 1 out } get_null.n.groups <- function(n.null,null_group.size){ n <- n.null if(null_group.size >n){ out <-1 }else{ if((n %% null_group.size)!=0){ out <- floor(n/null_group.size)+1 }else{ out <- n/null_group.size } } out } get_null.groups <- function(n.null,null.n.groups){ n <- n.null out <- rep(floor(n / null.n.groups), null.n.groups) if((n %% null.n.groups) != 0) out[1:(n %% null.n.groups)] <- out[1:(n %% null.n.groups)] + 1 out } rFUN_generator <- function(base_rFUN,...){ function(n, ncp,...) { stopifnot(length(n) == length(ncp)) unlist(lapply(1:length(n), function(i) base_rFUN(n[i], ncp[i],...))) } } simulated_W <- function(n.features,n.null,rFUN=rFUN_generator(rchisq),true.ncp1,df, N=(n.features-n.null),sided=ifelse(identical(rFUN, rFUN_generator(rchisq)),1,2),logic=TRUE){ if(n.null != 0 & logic == TRUE) { true.ncp1 <- c(rep(0,(length(N)-length(true.ncp1))), true.ncp1) } if(logic) { W <- numeric(n.features) temp <- rFUN(rep(1, length(N)), df=df, true.ncp1) W <- unlist(lapply(1:length(N), function(i) rep(temp[i], N[i]))) } else { W <- numeric(n.features) if(n.null != 0) W[1:n.null] <- rFUN(n.null, df, 0) temp <- rFUN(rep(1, length(N)), df, true.ncp1) W[(n.null+1):n.features] <- unlist(lapply(1:length(N), function(i) rep(temp[i], N[i]))) } if(sided==1) { Data <- W } else { Data <- abs(W) } return(Data) } get_simulated_W <- function(n.features,true.p0,list.ncp1,rFUN,df){ II <- ifelse(runif(n.features,min=0,max=1) < true.p0, 0,1) temp <- sample(list.ncp1,size =length(II),replace =TRUE) true.ncp1 <- ifelse(II==0,rep(0,length(II)), temp) W<- unlist(lapply(1:n.features, function(i) rFUN(n=1, df = df, ncp = true.ncp1[i]))) return(cbind(W,II,true.ncp1)) } mix.ye.mle<-function(W,dFUN,df,lower.ncp=1e-3,upper.ncp=20,lower.p0=0,upper.p0=1,fixed.ncp=NULL,fixed.p0=NULL){ tol<-1e-3 if(!is.null(fixed.p0)){lower.p0<-fixed.p0-tol/2;upper.p0<-fixed.p0+tol/2} if(!is.null(fixed.ncp)){lower.ncp<-fixed.ncp-tol/2;upper.ncp<-fixed.ncp+tol/2} lower<-lower.ncp;upper<-upper.ncp ostat<-W z<-k.checkings(stat=W,dFUN=dFUN,lower.ncp=lower,upper.ncp=upper,lower.p0=lower.p0,upper.p0=upper.p0,df=df) W<-z$stat new.estimation <- function(LFDR.hat,p0.hat,ncp1.hat,d.hat){ list(LFDR.hat=LFDR.hat, p0.hat=p0.hat,ncp.hat=ncp1.hat) } log_lik_mixture <- function(p0,W,d_alt,dFUN,df=1){ sum(log(p0*dFUN(W,df=df,ncp=0) + (1-p0)*dFUN(W,df=df,ncp=d_alt))) } get_d_max <- function(p0,W,dFUN, df=1,lower,upper,...){ f <- function(d_alt){log_lik_mixture(p0=p0,W=W,d_alt=d_alt,dFUN=dFUN,df=df)} as.numeric(optimize(f, lower=lower, upper=upper,maximum=TRUE,...))[1] } N_lik <- function(W,dFUN,df=1,lower,upper,lower.p0,upper.p0,...){ ff <- function(p0){ log_lik_mixture(p0,W,d_alt=get_d_max(p0,W=W,dFUN=dFUN,df=df,lower=lower,upper=upper,...), dFUN=dFUN,df=df) } p0_opt_result <- optimize(ff, lower=lower.p0, upper=upper.p0, maximum=TRUE,...) p0_max <- as.numeric(p0_opt_result[1]) d_max <- get_d_max(p0_max, W=W,dFUN=dFUN,df=df,lower=lower, upper=upper, ...) return(c(p0_max,d_max)) } get_lfdr <- function(pval,qFUN,W,p0,d_alt,dFUN=dchisq,df=1){ if(missing(W) && is.function(qFUN)){ W <- qFUN(pval, df = df,lower.tail=FALSE) } assert.is(W, "numeric") (p0*dFUN(W,df=df,ncp=0))/(p0*dFUN(W,df=df,ncp=0)+(1-p0)*dFUN(W,df=df,ncp=d_alt)) } MLE.LFDR_mixture <- function(pval,qFUN,W,df=1,dFUN=dchisq,lower,upper,ower.p0,upper.p0,...){ if(missing(W) && is.function(qFUN)) W <- qFUN(pval, df = df,lower.tail=FALSE) else stopifnot(missing(pval) && missing(qFUN)) assert.is(W, "numeric") opt <- N_lik(W=W,dFUN=dFUN,df=df,lower=lower,upper=upper,lower.p0=lower.p0,upper.p0=upper.p0) lfdr_mix <- get_lfdr(W=W,p0=opt[1],d_alt=opt[2],dFUN=dFUN,df=df) return(list(lfdr_mix,opt[1],opt[2])) } mixture.mle.estimation <- function(pval,qFUN,W,df,dFUN,lower,upper,lower.p0,upper.p0,push,...){ if(missing(W) && is.function(qFUN)) {W <- qFUN(p=pval, df = df,ncp=0,lower.tail=FALSE)} assert.is(W, "numeric") opt <- N_lik(W=W,dFUN=dFUN,df=df,lower=lower,upper=upper,lower.p0=lower.p0,upper.p0=upper.p0,...) lfdr_mix <- get_lfdr(W=W,p0=opt[1],d_alt=opt[2],dFUN=dFUN,df=df) d <- numeric(0) out <- new.estimation(LFDR.hat=lfdr_mix,p0.hat=opt[1],ncp1.hat=opt[2],d.hat=d) if(!missing(push)) push(list(out=out, W=W)) out } Wx<-dFUN(W,df=df) W<-W[is.finite(Wx)] opt <- N_lik(W=W,dFUN=dFUN,df=df,lower=lower,upper=upper,lower.p0=lower.p0,upper.p0=upper.p0) lfdr_mix <- get_lfdr(W=W,p0=opt[1],d_alt=opt[2],dFUN=dFUN,df=df) list(LFDR.hat=sameAsX_names(y=lfdr_mix,x=ostat),p0.hat=opt[1],ncp.hat=opt[2]) } pure.ye.mle<-function(W,dFUN,df,lower.ncp=1e-3,upper.ncp=20,lower.p0=0,upper.p0=1,fixed.ncp=NULL,fixed.p0=NULL){ tol<-1e-3 if(!is.null(fixed.p0)){lower.p0<-fixed.p0-tol/2;upper.p0<-fixed.p0+tol/2} if(!is.null(fixed.ncp)){lower.ncp<-fixed.ncp-tol/2;upper.ncp<-fixed.ncp+tol/2} lower<-lower.ncp;upper<-upper.ncp ostat<-W z<-k.checkings(stat=W,dFUN=dFUN,lower.ncp=lower,upper.ncp=upper,lower.p0=lower.p0,upper.p0=upper.p0,df=df) W<-z$stat log_lik_mixture <- function(p0,W,d_alt,dFUN,df=1){ sum(log(p0*dFUN(W,df=df,ncp=0) + (1-p0)*dFUN(W,df=df,ncp=d_alt))) } get_d_max <- function(p0,W,dFUN, df=1,lower,upper,...){ f <- function(d_alt){log_lik_mixture(p0=p0,W=W,d_alt=d_alt,dFUN=dFUN,df=df)} as.numeric(optimize(f, lower=lower, upper=upper,maximum=TRUE,...))[1] } N_lik <- function(W,dFUN,df=1,lower,upper,lower.p0,upper.p0,...){ ff <- function(p0){ log_lik_mixture(p0,W,d_alt=get_d_max(p0,W=W,dFUN=dFUN,df=df,lower=lower,upper=upper,...), dFUN=dFUN,df=df) } p0_opt_result <- optimize(ff, lower=lower.p0, upper=upper.p0, maximum=TRUE,...) p0_max <- as.numeric(p0_opt_result[1]) d_max <- get_d_max(p0_max, W=W,dFUN=dFUN,df=df,lower=lower, upper=upper, ...) return(c(p0_max,d_max)) } get_lfdr <- function(pval,qFUN,W,p0,d_alt,dFUN=dchisq,df=1){ if(missing(W) && is.function(qFUN)){ W <- qFUN(pval, df = df,lower.tail=FALSE) } assert.is(W, "numeric") (p0*dFUN(W,df=df,ncp=0))/(p0*dFUN(W,df=df,ncp=0)+(1-p0)*dFUN(W,df=df,ncp=d_alt)) } MLE.LFDR_mixture <- function(pval,qFUN,W,df=1,dFUN=dchisq,lower,upper,lower.p0,upper.p0,...){ if(missing(W) && is.function(qFUN)) W <- qFUN(pval, df = df,lower.tail=FALSE) else stopifnot(missing(pval) && missing(qFUN)) assert.is(W, "numeric") opt <- N_lik(W=W,dFUN=dFUN,df=df,lower=lower,upper=upper,lower.p0=lower.p0,upper.p0=upper.p0) lfdr_mix <- get_lfdr(W=W,p0=opt[1],d_alt=opt[2],dFUN=dFUN,df=df) return(list(lfdr_mix,opt[1],opt[2])) } Wx<-dFUN(W,df=df) W<-W[is.finite(Wx)] opt <- N_lik(W=W,dFUN=dFUN,df=df,lower=lower,upper=upper,lower.p0=lower.p0,upper.p0=upper.p0) lfdr_mix <- get_lfdr(W=W,p0=opt[1],d_alt=opt[2],dFUN=dFUN,df=df) return(list(LFDR.hat=sameAsX_names(x=ostat,y=lfdr_mix),p0.hat=opt[1],ncp.hat=opt[2])) } ye.mle<-function(W,df,dFUN=dabsTd,lower.ncp=1e-3,upper.ncp=20,lower.p0=0,upper.p0=1,d0=0,fixed.ncp=NULL,fixed.p0=NULL,...){ tol<-1e-3 if(!is.null(fixed.p0)){lower.p0<-fixed.p0-tol/2;upper.p0<-fixed.p0+tol/2} if(!is.null(fixed.ncp)){lower.ncp<-fixed.ncp-tol/2;upper.ncp<-fixed.ncp+tol/2} ostat<-W z<-k.checkings(stat=W,dFUN=dFUN,lower.ncp=lower.ncp,upper.ncp=upper.ncp,lower.p0=lower.p0,upper.p0=upper.p0,df=df) W<-z$stat log_lik_mixture <- function(p0,W,dalt,dFUN,df,d0=0,...){ sum(log(p0*dFUN(W,df=df,ncp=d0,...) + (1-p0)*dFUN(W,df=df,ncp=dalt,...))) } get_d_max <- function(p0,W,dFUN, df,lower.ncp,upper.ncp,d0=0,...){ f <- function(dalt){log_lik_mixture(p0=p0,W=W,dalt=dalt,dFUN=dFUN,df=df,d0=d0,...)} as.numeric(optimize(f, lower=lower.ncp, upper=upper.ncp,maximum=TRUE))[1] } N_lik <- function(W,dFUN,df,lower.ncp,upper.ncp,lower.p0,upper.p0,d0=0,...){ ff <- function(p0){ log_lik_mixture(p0,W,dalt=get_d_max(p0,W=W,dFUN=dFUN,df=df,lower.ncp=lower.ncp,upper.ncp=upper.ncp,d0=d0,...), dFUN=dFUN,df=df,d0=d0,...)} p0_opt_result <- optimize(ff, lower=lower.p0, upper=upper.p0, maximum=TRUE) p0_max <- as.numeric(p0_opt_result[1]) d_max <- get_d_max(p0=p0_max, W=W,dFUN=dFUN,df=df,lower.ncp=lower.ncp, upper.ncp=upper.ncp,d0=d0, ...) return(c(p0_max,d_max)) } get_lfdr <- function(pval,qFUN,W,p0,dalt,dFUN,df,d0,...){ if(missing(W) && is.function(qFUN)){W <- qFUN(pval=pval, df = df,lower.tail=FALSE,...)} assert.is(W, "numeric") (p0*dFUN(W,df=df,ncp=d0,...))/(p0*dFUN(W,df=df,ncp=d0,...)+(1-p0)* dFUN(W,df=df,ncp=dalt,...)) } mixture.mle.estimation <- function(W,df,dFUN,lower.ncp,upper.ncp,lower.p0,upper.p0,d0,...){ assert.is(W, "numeric") opt <- N_lik(W=W,dFUN=dFUN,df=df,lower.ncp=lower.ncp,upper.ncp=upper.ncp,lower.p0=lower.p0,upper.p0=upper.p0,d0=d0,...) lfdr_mix <- get_lfdr(W=W,p0=opt[1],dalt=opt[2],dFUN=dFUN,df=df,d0=d0,...) d <- numeric(0) infox<-list(method="ye.mle") new_est.lfdrmle(stat=ostat,LFDR.hat=lfdr_mix,p0.hat=opt[1],ncp.hat=opt[2],info=infox) } zo<-mixture.mle.estimation (W=W,df=df,dFUN=dFUN,lower.ncp=lower.ncp,upper.ncp=upper.ncp,lower.p0=lower.p0,upper.p0=upper.p0,d0=d0,...) est2list(zo)}
validate_limit_ia <- function(x) { if (is.null(x)) stop("invalid ia, is NULL must be between 0 and one less the number of features") if (anyNA(x)) stop("missing values ia") if (!all(x >= 0)) stop("ia values < 0") x } validate_limit_ij <- function(x) { if (is.null(x)) stop("invalid ij, is NULL") if (length(x) < 2) stop("ij values not of length 2") if (length(x) > 2) { message("ij values longer than 2, only first two used") x <- x[1:2] } if (anyNA(x)) stop("missing values ij") if (!all(x >= 0)) stop("ij values < 0") if (x[2] < x[1]) stop("ij values must be increasing") if (as.integer(x[1]) == as.integer(x[2])) stop("ij values must not be duplicated (use vapour_read_geometry_ia() to read a single geometry)") x } validate_limit_fa <- function(x) { if (is.null(x)) stop("invalid fa, is NULL") if (length(x) < 1) stop("no valid fa value") if (anyNA(x) | any(!is.finite(x))) stop("missing values fa") x } vapour_read_geometry_ia <- function(dsource, layer = 0L, sql = "", extent = NA, ia = NULL) { if (!is.numeric(layer)) layer <- index_layer(dsource, layer) ia <- validate_limit_ia(ia) extent <- validate_extent(extent, sql) gdal_dsn_read_geom_ia( dsn = dsource, layer = layer, sql = sql, ex = extent, format = "wkb", ia = ia) } vapour_read_geometry_ij <- function(dsource, layer = 0L, sql = "", extent = NA, ij = NULL) { if (!is.numeric(layer)) layer <- index_layer(dsource, layer) ij <- validate_limit_ij(ij) extent <- validate_extent(extent, sql) gdal_dsn_read_geom_ij( dsn = dsource, layer = layer, sql = sql, ex = extent, format = "wkb", ij = ij) }
print.comp.cutpoints <- function(x, digits = 4, ...) { cat("\n\n*************************************************\n") cat("Compare optimal number of cut points") cat("\n*************************************************\n\n") cat(paste("Bias corrected AUC difference:", round(x$AUC.cor.diff, 4), sep=" "), fill=TRUE) cat(paste("95% Bootstrap Confidence Interval:","(",round(x$icb.auc.diff[1], 4),",", round(x$icb.auc.diff[2], 4), ")" ,sep=" "), fill=TRUE) invisible(x) }
knitr::opts_chunk$set( collapse = TRUE, comment = " out.width = "100%" ) knitr::include_graphics("tripSplit-chunk-3-1.png", dpi=50) knitr::include_graphics("estSpaceUse-1.png", dpi=50) knitr::include_graphics("repAssess-1.png", dpi=100) repr <- data.frame(out = 98) knitr::include_graphics("plot_KBA_sf.png", dpi=50) knitr::include_graphics("KBA_sp_plot.png", dpi=50)
neon_data <- function(product, start_date = NA, end_date = NA, site = NA, type = NA, release = NA, quiet = FALSE, api = "https://data.neonscience.org/api/v0", .token = Sys.getenv("NEON_TOKEN")){ data_api <- data_api_queries(product = product, start_date = start_date, end_date = end_date, site = site, type = type, release = release, quiet = quiet, api = api, .token = .token) batch <- 950 if(.token == "") batch <- 150 pb <- progress::progress_bar$new( format = paste(" requesting", product, "from API [:bar] :percent in :elapsed, eta: :eta"), total = length(data_api), clear = FALSE, width= 80) resp <- vector("list", length = length(data_api)) for(i in seq_along(data_api)){ if(!quiet){ pb$tick() } resp[[i]] <- httr::GET(data_api[[i]], httr::add_headers("X-API-Token" = .token)) status <- neon_warn_http_errors(resp[[i]]) if(status == 429){ resp[[i]] <- httr::GET(data_api[[i]], httr::add_headers("X-API-Token" = .token)) } if(i %% batch == 0){ if(!quiet) message(" NEON rate limiting enforced, pausing for 100s\n") Sys.sleep(105) } } data <- do.call(rbind, lapply(resp, function(x) { status <- httr::status_code(x) if(status >= 400) return(NULL) cont <- httr::content(x, as = "text") dat <- jsonlite::fromJSON(cont)[[1]] if(length(dat) == 0) return(NULL) if(length(dat$files) == 0) return(NULL) out <- dat$files out$release <- dat$release out })) tibble::as_tibble(data) } neon_warn_http_errors <- function(x){ status <- httr::status_code(x) if(status < 400) return(invisible(0L)) out <- httr::content(x, encoding = "UTF-8") message(" NEON rate limiting enforced, pausing for 100s\n") Sys.sleep(101) invisible(status) } data_api_queries <- function(product, start_date = NA, end_date = NA, site = NA, type = NA, release = NA, quiet = FALSE, api = "https://data.neonscience.org/api/v0", .token = Sys.getenv("NEON_TOKEN")){ start_date <- as.Date(start_date) end_date <- as.Date(end_date) sites_df <- neon_sites(api) dataProducts <- do.call(rbind, sites_df$dataProducts) available <- dataProducts[dataProducts$dataProductCode %in% product,] data_api <- unlist(available$availableDataUrls) product_regex <- "DP\\d\\.\\d{5}\\.\\d{3}" regex <- paste0(api, "/data/", product_regex, "/(\\w+)/(\\d{4}-\\d{2})$") dates <- as.Date(gsub(regex, "\\2-01", data_api)) if(!is.na(start_date)){ data_api <- data_api[dates >= start_date] dates <- as.Date(gsub(regex, "\\2-01", data_api)) } if(!is.na(end_date)){ data_api <- data_api[dates <= end_date] } data_sites <- gsub(regex, "\\1", data_api) if(!all(is.na(site))){ data_api <- data_api[data_sites %in% site] } if(length(data_api) == 0){ if(!quiet) message(" No files to download.") return(invisible(NULL)) } if(!is.na(release)){ data_api <- vapply(data_api, httr::modify_url, character(1L), query = list(release=release), USE.NAMES = FALSE) } if(!is.na(type)){ if( !(type %in% c("basic", "expanded")) ){ warning("type must be 'basic', 'expanded', or NA (default)", call. = FALSE) return(data_api) } data_api <- vapply(data_api, httr::modify_url, character(1L), query = list(package=type), USE.NAMES = FALSE) } data_api }
test_that("nnf_mse_loss", { x <- torch_tensor(c(1,2,3)) y <- torch_tensor(c(2,3,4)) o <- nnf_mse_loss(x, y) expect_equal_to_r(o, 1) y <- y$unsqueeze(2) expect_warning( nnf_mse_loss(x, y), regexp = "target size" ) }) test_that("nnf_binary_cross_entropy", { x <- torch_tensor(c(0, 1))$view(c(-1, 1)) y <- torch_tensor(c(0, 1))$view(c(-1, 1)) expect_equal_to_r(nnf_binary_cross_entropy(x, y), 0) })
integer_parameter <- function( id, default, distribution, description = NULL, tuneable = TRUE ) { assert_that(is.numeric(default), is_distribution(distribution)) parameter( id = id, default = default, distribution = distribution, description = description, tuneable = tuneable ) %>% add_class("integer_parameter") } as_paramhelper.integer_parameter <- function(x) { dfun <- distribution_function(x$distribution) qfun <- quantile_function(x$distribution) length <- length(x$default) requireNamespace("ParamHelpers") fun <- if (length == 1) ParamHelpers::makeNumericParam else ParamHelpers::makeNumericVectorParam args <- list( id = x$id, lower = dfun(x$distribution$lower - .5 + 1e-10), upper = dfun(x$distribution$upper + .5 - 1e-10), default = dfun(x$default), trafo = function(x) as.integer(round(qfun(x))), tunable = x$tuneable ) if (length != 1) args$len <- length do.call(fun, args) } as_descriptive_tibble.integer_parameter <- function(x) { tibble( id = x$id, type = "integer", domain = as.character(x$distribution), default = collapse_set(x$default) ) }
integrate_identity <- function(object, which=c("lower", "upper"), from, to, n=100L) { which <- match.arg(which) stopifnot(is.numeric(from), length(from) == 1, is.finite(from)) stopifnot(is.numeric(to), length(to) == 1, is.finite(to)) stopifnot(is.numeric(n), length(n) == 1, n > 1) br <- seq(from, to, length.out=4*n-3) if (which == 'lower') fval <- (object@a1+(object@a2-object@a1)*object@lower(br))*br else fval <- (object@a3+(object@a4-object@a3)*object@upper(br))*br sum(fval * c(7, rep(c(32, 12, 32, 14), times=n-2), 32, 12, 32, 7)/90)*(to-from)/(n-1) } integrate_discont_val <- function(f, from, to, discontinuities=numeric(0), ...) { if (!is.numeric(discontinuities)) stop("`discontinuities' should be numeric") stopifnot(from <= to) discontinuities <- discontinuities[discontinuities > from & discontinuities < to] m <- length(discontinuities) if (m == 0) return(integrate(f=f, lower=from, upper=to, ...)$value) if (is.unsorted(discontinuities)) stop("`discontinuities' should be ordered nondecreasingly") x <- c(from, discontinuities, to) v <- numeric(m+1) for (i in 1:(m+1)) { v[i] <- integrate(f=f, lower=x[i]+.Machine$double.eps^0.5, upper=x[i+1]-.Machine$double.eps^0.5, ...)$value } return(sum(v)) } setGeneric("integrateAlpha", function(object, which, from, to, ...) standardGeneric("integrateAlpha")) setMethod( f="integrateAlpha", signature(object="FuzzyNumber", which="character", from="numeric", to="numeric"), definition=function(object, which=c("lower","upper"), from=0, to=1, weight=NULL, transform=NULL, ...) { which <- match.arg(which) if (length(from) != 1 || length(to) != 1 || from < 0 || to > 1) stop("invalid `from' or `to'") if (!is.null(weight) && (class(weight) != "function" || length(formals(weight)) != 1)) stop("`weight' should be a function with 1 parameter") if (!is.null(transform) && (class(transform) != "function" || length(formals(transform)) != 2)) stop("`transform' should be a function with 2 parameter") if (!is.null(weight) && !is.null(transform)) stop("specify either `weight', `transform' or none") if (which == "lower") { if (!is.null(weight)) { fun <- function(alpha) (object@a1+(object@a2-object@a1)*object@lower(alpha))*weight(alpha) } else if (!is.null(transform)) { fun <- function(alpha) transform(alpha, object@a1+(object@a2-object@a1)*object@lower(alpha)) } else { fun <- function(alpha) object@a1+(object@a2-object@a1)*object@lower(alpha) } } else { if (!is.null(weight)) { fun <- function(alpha) (object@a3+(object@a4-object@a3)*object@upper(alpha))*weight(alpha) } else if (!is.null(transform)) { fun <- function(alpha) transform(alpha, object@a3+(object@a4-object@a3)*object@upper(alpha)) } else { fun <- function(alpha) object@a3+(object@a4-object@a3)*object@upper(alpha) } } integrate(f=fun, from, to, ...)$value } ) setMethod( f="integrateAlpha", signature(object="DiscontinuousFuzzyNumber", which="character", from="numeric", to="numeric"), definition=function(object, which=c("lower", "upper"), from=0, to=1, weight=NULL, transform=NULL, ...) { which <- match.arg(which) if (length(from) != 1 || length(to) != 1 || from < 0 || to > 1) stop("invalid `from' or `to'") if (!is.null(weight) && (class(weight) != "function" || length(formals(weight)) != 1)) stop("`weight' should be a function with 1 parameter") if (!is.null(transform) && (class(transform) != "function" || length(formals(transform)) != 2)) stop("`transform' should be a function with 2 parameter") if (!is.null(weight) && !is.null(transform)) stop("specify either `weight', `transform' or none") if (which == "lower") { if (!is.null(weight)) { fun <- function(alpha) (object@a1+(object@a2-object@a1)*object@lower(alpha))*weight(alpha) } else if (!is.null(transform)) { fun <- function(alpha) transform(alpha, object@a1+(object@a2-object@a1)*object@lower(alpha)) } else { fun <- function(alpha) object@a1+(object@a2-object@a1)*object@lower(alpha) } disconts <- [email protected] } else { if (!is.null(weight)) { fun <- function(alpha) (object@a3+(object@a4-object@a3)*object@upper(alpha))*weight(alpha) } else if (!is.null(transform)) { fun <- function(alpha) transform(alpha, object@a3+(object@a4-object@a3)*object@upper(alpha)) } else { fun <- function(alpha) object@a3+(object@a4-object@a3)*object@upper(alpha) } disconts <- [email protected] } integrate_discont_val(fun, from, to, discontinuities=disconts, ...) } )
"N" <- 12 "x" <- c(6, 9, 17, 22, 7, 5, 5, 14, 9, 7, 9, 51) "y" <- c(5, 2, 0, 0, 2, 1, 0, 0, 0, 0, 13, 0) "t" <- c(11, 11, 17, 22, 9, 6, 5, 14, 9, 7, 22, 51)
clear_cache <- function() { memoise::forget(memoised_GET) }
plines <- function(x, y = NULL, type = "l", proj, ...) { arglist <- list(...) object <- arg.check.plines(x, y, type, proj, arglist) if (proj != "none") { projxy <- mapproj::mapproject(object$x, object$y) object$x <- projxy$x object$y <- projxy$y } f <- graphics::lines do.call(f, object) } arg.check.plines <- function(x, y, type, proj, arglist) { if (is.list(x)) { if (is.null(x$x) | is.null(x$y)) { stop("If x is a list, it should have arguments x and y") } if (length(x$x) != length(x$y)) { stop("x$x and x$y should have the same length") } if (!is.numeric(x$x) | !is.numeric(x$y)) { stop("x and y should be numeric") } y <- x$y x <- x$x } else { if (is.null(y)) { y <- x x <- seq_len(x) } else { if (!is.numeric(x) | !is.numeric(y)) { stop("x and y should be numeric") } if (length(x) != length(y)) { stop("x and y should have the same length") } } } if (!is.element(type, c("b", "c", "h", "l", "n", "o", "p", "s"))) { stop("invalid type argument") } if (length(proj) != 1) { stop("proj should be a single character string") } if (!is.character(proj)) { stop("proj should be a single character string") } if (proj != "none") { p <- try(mapproj::.Last.projection(), silent = TRUE) if (class(p) == "try-error") { stop("No projection has been used in current plot. Set \"proj\" in the pimage or autoimage functions.") } else { if (p$projection != proj) { stop("proj and last projection used do not match") } } } arglist$x <- x arglist$y <- y arglist$type <- type arglist }
`HOZscale` <- function(z, col, units="", SIDE=1, s1=.6, s2=0.95, format=1, digits=3, cex=1, cex.units=1) { if(missing(units)) { units="" } if(missing(SIDE)) { SIDE=1} if(missing(s1)) { s1=0.6 } if(missing(s2)) { s2=0.95 } u = par("usr") f = par("pin") raty = (u[4]-u[3])/f[2] dy = (u[4]-u[3])*.05 dx = (u[2]-u[1])*.3 if(SIDE==1) { ym = ymarginfo(SIDE=1, s1=s1, s2=s2) LU=list(x=c(u[1]+dx*0.1, u[1]+dx*0.1+dx), y = ym) } else { ym = ymarginfo(SIDE=3, s1=s1, s2=s2) LU=list(x=c(u[1]+dx*0.1, u[1]+dx*0.1+dx), y = ym) } rng = range(z, na.rm = TRUE) i <- seq(along = col) BX = (LU$x[2]-LU$x[1])/length(i) x1 =LU$x[1]+(i-1)*BX x2 = x1+BX y1 = LU$y[1] y2 = LU$y[2] rect(x1,y1,x2,y2, col=col, xpd = TRUE, border=NA) if(format==2) { char = format(rng[2], scientific = T) sp.char = as.numeric( unlist( strsplit(char, split='e') ) ) mant = round(sp.char[1], digits=digits) expt =round(sp.char[2]) if(expt==0) { text(LU$x[2]+BX, (y1+y2)/2, labels=mant ,adj=c(0,.5), xpd = TRUE , cex=cex ) } else { text(LU$x[2]+BX, (y1+y2)/2, labels=bquote(.(mant)%*%10^.(expt)) ,adj=c(0,.5), xpd = TRUE, cex=cex ) } char = format(rng[1], scientific = T) sp.char = as.numeric( unlist( strsplit(char, split='e') ) ) mant = round(sp.char[1], digits=digits) expt =round(sp.char[2]) if(expt==0) { text(LU$x[1]-BX, (y1+y2)/2, labels=mant ,adj=c(1, 0.5), xpd = TRUE, cex=cex ) } else { text(LU$x[1]-BX/2, (y1+y2)/2, labels=bquote(.(mant)%*%10^.(expt)), adj=c(1, 0.5) , xpd = TRUE, cex=cex) } if(SIDE==1) { text( mean(LU$x), y1, labels=units, adj=c(0.5, -0.1) , xpd = TRUE, cex=cex.units) } else { text( mean(LU$x), y2, labels=units, adj=c(0.5, -0.1) , xpd = TRUE, cex=cex.units) } } else { rlab = paste(sep=" ", format.default(rng[2], digits=3), units) text(LU$x[2]+BX, (y1+y2)/2, labels=rlab, adj=0, xpd = TRUE, cex=cex) text(LU$x[1]-BX/2, (y1+y2)/2, labels=format.default(rng[1], digits=3), adj=1, xpd = TRUE, cex=cex) } rect(LU$x[1], LU$y[1], LU$x[2], LU$y[2], xpd=TRUE) }
tropsvm_helper <- function(x, y, assignment = NULL, ind = 1, newx = NULL, newy = NULL) { classes <- unique(y) reorder_ind <- c(which(y == classes[1]), which(y == classes[2])) label <- y[reorder_ind] data <- x[reorder_ind, ] n1 <- sum(label == classes[1]) n2 <- sum(label == classes[2]) n <- n1 + n2 names(assignment) <- c("ip", "iq", "jp", "jq") ip <- assignment[1] jp <- assignment[3] iq <- assignment[2] jq <- assignment[4] f.obj <- c(1, rep(0, 4), c( rep(-1, n1), rep(-1, n1), rep(-1, n1), rep(-1, n1), rep(-1, n2), rep(-1, n2), rep(-1, n2), rep(-1, n2) )) f.conp <- rbind( cbind(rep(1, n1), rep(-1, n1), rep(1, n1), rep(0, n1), rep(0, n1)), cbind(rep(0, n1), rep(-1, n1), rep(1, n1), rep(0, n1), rep(0, n1)), cbind(rep(0, n1), rep(0, n1), rep(-1, n1), rep(1, n1), rep(0, n1)), cbind(rep(0, n1), rep(0, n1), rep(-1, n1), rep(0, n1), rep(1, n1)) ) f.conq <- rbind( cbind(rep(1, n2), rep(0, n2), rep(0, n2), rep(-1, n2), rep(1, n2)), cbind(rep(0, n2), rep(0, n2), rep(0, n2), rep(-1, n2), rep(1, n2)), cbind(rep(0, n2), rep(1, n2), rep(0, n2), rep(0, n2), rep(-1, n2)), cbind(rep(0, n2), rep(0, n2), rep(1, n2), rep(0, n2), rep(-1, n2)) ) f.con <- cbind(rbind(f.conp, f.conq), diag(-1, nrow = 4 * n, ncol = 4 * n)) f.dir <- rep("<=", n) f.rhs <- c( rep(data[1:n1, ip] - data[1:n1, jp], 2), data[1:n1, jp] - data[1:n1, iq], data[1:n1, jp] - data[1:n1, jq], rep(data[-c(1:n1), iq] - data[-c(1:n1), jq], 2), data[-c(1:n1), jq] - data[-c(1:n1), ip], data[-c(1:n1), jq] - data[-c(1:n1), jp] ) reorder_ind <- c(which(newy == classes[1]), which(newy == classes[2])) val_label <- newy[reorder_ind] val_data <- newx[reorder_ind, ] val_n1 <- sum(val_label == classes[1]) omega <- rep(0, ncol(data)) omega[c(ip, jp, iq, jq)] <- lp("max", f.obj, f.con, f.dir, f.rhs)$solution[2:5] omega[-c(ip, jp, iq, jq)] <- colMins(-data[, -c(ip, jp, iq, jq)] + c(data[1:n1, jp] + omega[jp], data[-c(1:n1), jq] + omega[jq]), T) shifted_val_data <- eachrow(val_data, omega, "+") diff <- eachrow(t(shifted_val_data), rowMaxs(shifted_val_data, T), oper = "-") raw_classification <- lapply(lapply(seq_len(ncol(diff)), function(i) diff[, i]), function(x) { which(abs(x) < 1e-10) }) if (length(unique(assignment)) == 2) { accuracy <- (sum(raw_classification[1:val_n1] == ip) + sum(raw_classification[-c(1:val_n1)] == iq)) / length(raw_classification) } else { all_method_ind <- comboGeneral(8, 4) if (length(unique(assignment)) == 4) { P_base <- matrix(c( 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1 ), ncol = 4, byrow = T) Q_base <- matrix(c( 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0 ), ncol = 4, byrow = T) PQ_com <- matrix(c( 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1 ), ncol = 4, byrow = T) } if (length(unique(assignment)) == 3) { P_base <- c() Q_base <- c() PQ_com <- matrix(c( 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0 ), ncol = 3, byrow = T) if (ip == jq) { PQ_com <- PQ_com[, c(1, 2, 3, 1)] } if (iq == jp) { PQ_com <- PQ_com[, c(1, 2, 2, 3)] } if (jp == jq) { PQ_com <- PQ_com[, c(1, 2, 3, 2)] } } colnames(PQ_com) <- c("ip", "jp", "iq", "jq") accuracy <- sapply(ind, function(l) { P <- rbind(P_base, PQ_com[all_method_ind[l, ], ]) Q <- rbind(Q_base, PQ_com[-all_method_ind[l, ], ]) sum(c(sapply(raw_classification[1:val_n1], function(x) { v <- c(ip, jp, iq, jq) %in% x return(sum(colSums(t(P) == v) == ncol(P))) }), sapply(raw_classification[-c(1:val_n1)], function(x) { v <- c(ip, jp, iq, jq) %in% x return(sum(colSums(t(Q) == v) == ncol(Q))) }))) / length(raw_classification) }) } accuracy }
`swapTA` <- function(ta1,ta2,occ1=1,occ2=1,dev) { if(missing(ta1) || missing(ta2)) stop("two TA indicator required") if(missing(dev)) dev <- dev.cur() ta.list <- listTA(dev) lchob <- get.chob()[[dev]] if(regexpr("^add",ta1) == -1) ta1 <- paste("add",ta1,sep='') if(regexpr("^add",ta2) == -1) ta2 <- paste("add",ta2,sep='') which.ta1 <- which(ta1==sapply(ta.list, function(x) deparse(x[[1]])))[occ1] which.ta2 <- which(ta2==sapply(ta.list, function(x) deparse(x[[1]])))[occ2] tmp.ta1 <- [email protected]$TA[[which.ta1]] tmp.ta2 <- [email protected]$TA[[which.ta2]] [email protected]$TA[[which.ta1]] <- tmp.ta2 [email protected]$TA[[which.ta2]] <- tmp.ta1 do.call("chartSeries.chob",list(lchob)) write.chob(lchob,lchob@device) } `moveTA` <- function(ta,pos,occ=1,dev) { pos <- pos - 1 if(missing(ta)) stop("no TA indicator specified") if(missing(dev)) dev <- dev.cur() ta.list <- listTA(dev) lchob <- get.chob()[[dev]] if(regexpr("^add",ta) == -1) ta <- paste("add",ta,sep='') which.ta <- which(ta==sapply(ta.list, function(x) deparse(x[[1]])))[occ] if(is.na(which.ta)) stop("no TA") [email protected]$TA <- append([email protected]$TA[-which.ta], [email protected]$TA[which.ta], after=pos) do.call("chartSeries.chob",list(lchob)) write.chob(lchob,lchob@device) } `dropTA` <- function(ta,occ=1,dev,all=FALSE) { if(all) return(do.call('dropTA', list(1:length(listTA())))) if(missing(ta)) stop("no TA indicator specified") if(missing(dev)) dev <- dev.cur() ta.list <- listTA(dev) lchob <- get.chob()[[dev]] sel.ta <- NULL for(cta in 1:length(ta)) { if(is.character(ta[cta])) { if(regexpr("^add",ta[cta]) == -1) ta[cta] <- paste("add",ta[cta],sep='') which.ta <- which(ta[cta]==sapply(ta.list, function(x) deparse(x[[1]])))[occ] } else which.ta <- cta if(!is.na(which.ta)) { if([email protected]$TA[[which.ta]]@new) lchob@windows <- lchob@windows - 1 sel.ta <- c(sel.ta,which.ta) } } if(is.null(sel.ta)) stop("nothing to remove") [email protected]$TA <- [email protected]$TA[-sel.ta] if(length([email protected]$TA) < 1) [email protected]$TA <- list() do.call("chartSeries.chob",list(lchob)) write.chob(lchob,lchob@device) }
MaxDD<-function(R,confidence=0.95,type=c("ar","normal"),...) { x = checkData(R) if(ncol(x)==1 || is.null(R) || is.vector(R)){ calcul = FALSE for(i in (1:length(x))){ if(!is.na(x[i])){ calcul = TRUE } } if(!calcul){ result = NA } else{ if(type[1]=="ar"){ result = get_minq(x,confidence) } if(type[1]=="normal"){ result = dd_norm(x,confidence) } } return(result) } if(type[1]=="ar"){ result = apply(x,MARGIN = 2,get_minq,confidence) } if(type[1]=="normal"){ result = apply(x,MARGIN = 2,dd_norm,confidence) print(result) } result = round(result,3) rownames(result) = c("MaxDD(in %)","t*") return(result) }
data(mtcars) mymtcars <- dplyr::mutate(mtcars, cyl_factor = factor(cyl, levels = c(6, 4, 8)), cyl_char = as.character(cyl)) summarize_these <- with(mymtcars, list("Cylinder (numeric)" = tab_summary(cyl), "Cylinder (factor)" = tab_summary(cyl_factor), "Cylinder (character)" = tab_summary(cyl_char), "MGP" = tab_summary(mpg)) ) test_that("tab_summary generates formulea for numeric vector", { expect_equivalent(summarize_these[[1]], list(~ min(cyl), ~ qwraps2::median_iqr(cyl), ~ qwraps2::mean_sd(cyl), ~ max(cyl))) }) test_that("tab_summary generates formulea for factor", { expect_equivalent(summarize_these[[2]], list(~ qwraps2::n_perc(cyl_factor == "6", digits = 0, show_symbol = FALSE), ~ qwraps2::n_perc(cyl_factor == "4", digits = 0, show_symbol = FALSE), ~ qwraps2::n_perc(cyl_factor == "8", digits = 0, show_symbol = FALSE))) }) test_that("tab_summary generates formulea for character", { expect_equivalent(summarize_these[[3]], list(~ qwraps2::n_perc(cyl_char == "4", digits = 0, show_symbol = FALSE), ~ qwraps2::n_perc(cyl_char == "6", digits = 0, show_symbol = FALSE), ~ qwraps2::n_perc(cyl_char == "8", digits = 0, show_symbol = FALSE))) })
prep_data_fitting <- function( data, model_file, id, condition ) { data$id <- data[[id]] data$condition <- data[[condition]] col_freq <- get_eqn_categories(model_file) out <- list( conditions = unique(data[[condition]]), parameters = as.character(MPTinR::check.mpt(model_file)$parameters), col_freq = col_freq, trees = get_eqn_trees(model_file = model_file), freq_list = split(data[, col_freq], f = data[[condition]]), cols_ci = paste0("ci_", getOption("MPTmultiverse")$ci_size), data = data ) out }
chk_gt <- function(x, value = 0, x_name = NULL) { if (vld_gt(x, value)) { return(invisible(x)) } if (is.null(x_name)) x_name <- deparse_backtick_chk(substitute(x)) if (length(x) == 1L) { abort_chk(x_name, " must be greater than ", cc(value), ", not ", cc(x), x = x, value = value) } abort_chk(x_name, " must have values greater than ", cc(value), x = x, value = value) } vld_gt <- function(x, value = 0) all(x[!is.na(x)] > value)
dm_is_strict_keys <- function(dm) { TRUE }
dfToListColumn<-function(dfLookColumn,columnToSplit="OTU"){ if(columnToSplit %in% colnames(dfLookColumn)){ listOfdfLookColumn <- base::split(dfLookColumn, factor(dfLookColumn[,columnToSplit],levels = unique(dfLookColumn[,columnToSplit]) ) ) names(listOfdfLookColumn) <- unique(dfLookColumn[,columnToSplit]) } else { listOfdfLookColumn <- list(dfLookColumn) names(listOfdfLookColumn)<-1 } return(listOfdfLookColumn) }
test_that("sjl() | scalar test", { expect_equal(sjl(hms::parse_hm("02:30"), hms::parse_hm("04:30"), TRUE, "shorter"), lubridate::dhours(2)) expect_equal(sjl(hms::parse_hm("23:00"), hms::parse_hm("02:00"), TRUE, "shorter"), lubridate::dhours(3)) expect_equal(sjl(hms::parse_hm("05:00"), hms::parse_hm("03:00"), FALSE, "shorter"), lubridate::dhours(-2)) expect_equal(sjl(hms::as_hms(NA), hms::parse_hm("00:00"), FALSE, "shorter"), lubridate::as.duration(NA)) }) test_that("sjl() | vector test", { expect_equal(sjl(c(hms::parse_hm("11:00"), hms::parse_hm("22:00")), c(hms::parse_hm("18:30"), hms::parse_hm("17:30")), FALSE, "shorter"), c(lubridate::dhours(7.5), lubridate::dhours(-4.5))) }) test_that("sjl() | `method` test", { expect_equal(sjl(hms::parse_hm("08:00"), hms::parse_hm("12:00"), FALSE, "difference"), lubridate::dhours(4)) expect_equal(sjl(hms::parse_hm("08:00"), hms::parse_hm("12:00"), FALSE, "shorter"), lubridate::dhours(4)) expect_equal(sjl(hms::parse_hm("08:00"), hms::parse_hm("12:00"), FALSE, "longer"), lubridate::dhours(-20)) expect_equal(sjl(hms::parse_hm("12:00"), hms::parse_hm("08:00"), FALSE, "difference"), lubridate::dhours(-4)) expect_equal(sjl(hms::parse_hm("12:00"), hms::parse_hm("08:00"), FALSE, "shorter"), lubridate::dhours(-4)) expect_equal(sjl(hms::parse_hm("12:00"), hms::parse_hm("08:00"), FALSE, "longer"), lubridate::dhours(20)) expect_equal(sjl(hms::parse_hm("23:00"), hms::parse_hm("01:00"), FALSE, "difference"), lubridate::dhours(-22)) expect_equal(sjl(hms::parse_hm("23:00"), hms::parse_hm("01:00"), FALSE, "shorter"), lubridate::dhours(2)) expect_equal(sjl(hms::parse_hm("23:00"), hms::parse_hm("01:00"), FALSE, "longer"), lubridate::dhours(-22)) expect_equal(sjl(hms::parse_hm("01:00"), hms::parse_hm("23:00"), FALSE, "difference"), lubridate::dhours(22)) expect_equal(sjl(hms::parse_hm("01:00"), hms::parse_hm("23:00"), FALSE, "shorter"), lubridate::dhours(-2)) expect_equal(sjl(hms::parse_hm("01:00"), hms::parse_hm("23:00"), FALSE, "longer"), lubridate::dhours(22)) }) test_that("sjl() | error test", { expect_error(sjl(1, hms::hms(1), TRUE, "shorter"), "Assertion on 'msw' failed") expect_error(sjl(hms::hms(1), 1, TRUE, "shorter"), "Assertion on 'msf' failed") expect_error(sjl(hms::hms(1), hms::hms(1), "", "shorter"), "Assertion on 'abs' failed") expect_error(sjl(hms::hms(1), hms::hms(1), TRUE, 1), "Assertion on 'method' failed") expect_error(sjl(hms::hms(1), c(hms::hms(1), hms::hms(1)))) }) test_that("sjl() | wrappers", { expect_equal(sjl_rel(hms::parse_hm("10:00"), hms::parse_hm("12:00"), "shorter"), lubridate::dhours(2)) expect_equal(sjl_rel(hms::parse_hm("03:30"), hms::parse_hm("03:00"), "shorter"), lubridate::dhours(-0.5)) })
OT2MAX <- function(OTdata, OTmissing = NULL, start = NULL, end = NULL, MAX.r = 1L, blockDuration = "year", monthGapStat = TRUE, maxMissingFrac = 0.05, dataFrames = FALSE, infMAX = FALSE, plot = TRUE, plotType = c("max", "gaps"), jitterSeed = 123, trace = 0L, ...) { plotType <- match.arg(plotType) if (is(OTdata$date, "POSIXct")) { TZ <- attr(OTdata$date, "tz") } else { warning("'OTdata$date' is not of class \"POSIXct\". Coerced ", " with time zone \"GMT\"") TZ <- "GMT" OTdata$date <- as.POSIXct(OTdata$date, tz = "TZ") } unit <- blockDuration Year <- seq(from = as.POSIXct("2000-01-01", tz = TZ), to = as.POSIXct("2000-12-31", tz = TZ), by = "day") labYear <- format(Year, "%m-%d") if ( !is.data.frame(OTdata) || ! ("date" %in% colnames(OTdata)) ) { stop("'OTdata' must be a data frame object with a 'date' column") } nData <- nrow(OTdata) vars <- names(OTdata) vars <- vars[is.na(match(vars, c("date", "comment")))] if (length(var) > 1L) stop("variable name could not be guessed") if (!is.null(OTmissing)) { if ( !is.data.frame(OTmissing) || !("start" %in% colnames(OTmissing)) || !("end" %in% colnames(OTmissing)) ) { stop("'OTmissing' must be a data frame object 'start' ", "and 'end' columns") } miss <- TRUE nMP <- nrow(OTmissing) if (!is(OTmissing$start, "POSIXct")){ OTmissing$start <- as.POSIXct(OTmissing$start, tz = TZ) } else { if (attr(OTmissing$start, "tz") != TZ) { warning("the timezone of 'OTmissing$start' does not match ", "that of 'OTdata$date") } } if (!is(OTmissing$end, "POSIXct")){ OTmissing$end <- as.POSIXct(OTmissing$end, tz = TZ) } else { if (attr(OTmissing$end, "tz") != TZ) { warning("the timezone of 'OTmissing$end' does not match ", "that of 'OTdata$date") } } } else { miss <- FALSE if (monthGapStat) { monthGapStat <- FALSE warning("'monthGapStat' forced to FALSE since no information was ", "provided in 'OTmissing'") } } if (is.null(start)) { if (miss) { if (OTmissing$start[1L] < OTdata$date[1L]) { start <- OTmissing$start[1L] } else start <- OTdata$date[1L] } else start <- OTdata$date[1L] } else { if (!is(start, "POSIXct")) start <- as.POSIXct(start, tz = TZ) else if (attr(start) != TZ) { warning("the timezone of 'start' does not match ", "that of 'OTdata$date") } } if (is.null(end)) { if (miss) { if (OTmissing$end[nMP] > OTdata$date[nData]){ end <- OTmissing$end[nMP] } else end <- OTdata$date[nData] } else end <- OTdata$date[nData] } else { if (!is(end, "POSIXct")) end <- as.POSIXct(end, tz = TZ) else if (attr(end) != TZ) { warning("the timezone of 'end' does not match ", "that of 'OTdata$date") } } startBreaks <- start endBreaks <- end startBreaksTest <- as.POSIXct(format(startBreaks, "%Y-01-01"), tz = TZ) if (startBreaks != startBreaksTest) { year <- as.integer(format(startBreaks, "%Y")) + 1 startBreaks <- as.POSIXct(paste(year, "-01-01 00:00", sep = ""), tz = TZ) } endBreaks <- as.POSIXct(format(endBreaks, "%Y-01-01"), tz = TZ) Breaks <- seq(from = startBreaks, to = endBreaks, by = unit) nBreaks <- length(Breaks) blockNames <- format(Breaks[-nBreaks], "%Y") Block <- cut(x = OTdata$date, breaks = Breaks) levels(Block) <- blockNames nBlock <- nlevels(Block) blockDur <- as.numeric(diff(Breaks), units = "days") Breaks2 <- seq(from = startBreaks, to = endBreaks, by = "day") if (length(MAX.r) != 1L && length(MAX.r) != nBlock) { stop("the length of 'MAX.r' must be 1 or the number of blocks") } MAX.r <- rep(MAX.r, length.out = nBlock) names(MAX.r) <- blockNames if (trace) { cat("Number of events by block \n") print(tapply(OTdata[ , vars], Block, length)) } if (!miss) { ms <- NULL mTS <- NULL blockDurMiss <- rep(0.0, nBlock) keepBlock <- rep(TRUE, nBlock) } else { dfMiss <- data.frame(dt = OTmissing$start, gap = rep(1, length(OTmissing$start))) dfMiss <- rbind(dfMiss, data.frame(dt = OTmissing$end, gap = rep(0, length(OTmissing$end)))) dfMiss <- dfMiss[order(dfMiss$dt), ] cum <- cumsum(c(0.0, as.numeric(diff(dfMiss$dt), units = "days")) * (1.0 - dfMiss$gap)) dfMiss <- cbind(dfMiss, cum = cum) if (dfMiss$dt[1L] > Breaks[1L]) { dfMiss <- rbind(data.frame(dt = Breaks[1L], gap = 0, cum = 0), dfMiss) } nMiss <- nrow(dfMiss) if (dfMiss$dt[nMiss] < Breaks[nBreaks]) { dfMiss <- rbind(dfMiss, data.frame(dt = Breaks[nBreaks], gap = 0, cum = dfMiss$cum[nMiss])) } interp <- approx(x = dfMiss$dt, y = dfMiss$cum, xout = Breaks, method = "linear") blockDurMiss <- as.numeric(diff(interp$y), units = "days") keepBlock <- ( (blockDurMiss / blockDur) < maxMissingFrac ) names(keepBlock) <- levels(Block) BlockMiss <- as.integer(cut(x = dfMiss$dt, breaks = Breaks)) interp2 <- approx(x = dfMiss$dt, y = dfMiss$gap, xout = Breaks2, method = "constant") if (monthGapStat) { monthBreaks <- seq(from = startBreaks, to = endBreaks, by = "month") monthDur <- round(as.numeric(diff(monthBreaks), units = "days")) monthInterp <- approx(x = dfMiss$dt, y = dfMiss$cum, xout = monthBreaks, method = "linear") monthBlockDurMiss <- as.numeric(diff(monthInterp$y), units = "days") nM <- length(monthBreaks) monthStart <- seq(from = as.POSIXct("2001-01-01", tz = TZ), by = "month", length.out = 13) monthLab <- format(monthStart[1:12], "%b") month <- factor(format(monthBreaks[-nM], "%b"), levels = monthLab) ms <- data.frame(start = monthBreaks[-nM], end = monthBreaks[-1], year = as.numeric(format(monthBreaks[-nM], "%Y")), month = month, dur = monthDur, durMissing = monthBlockDurMiss, missing = monthBlockDurMiss / monthDur) rownames(ms) <- format(monthBreaks[-nM], "%Y-%m") mTS <- tapply(ms$missing, list(ms$year, ms$month), mean) mTS <- ts(mTS, start = min(ms$year)) } else { ms <- NULL mTS <- NULL } } effDur <- 1 - (blockDurMiss / blockDur) effDur[abs(effDur) < 0.001] <- 0.0 MAXinfo <- data.frame(start = Breaks[-nBreaks], end = Breaks[-1L], duration = effDur) rownames(MAXinfo) <- blockNames probMiss <- rep(0, 365) first <- TRUE for (i in 1L:nBlock) { ind <- (OTdata$date >= Breaks[i]) & (OTdata$date <= Breaks[i + 1L]) if (keepBlock[i]) { if (any(ind)) { ri <- sum(ind) Ti <- OTdata[ind, "date"] zi <- OTdata[ind, vars] indi <- rev(order(zi)) Ti <- Ti[indi] zi <- zi[indi] if (ri < MAX.r[i]) { if (infMAX) { Ti <- rep(Ti, length.out = MAX.r[i]) Ti[(ri + 1L):MAX.r[i]] <- NA zi <- c(zi, rep(-Inf, MAX.r[i] - ri)) ri <- MAX.r[i] } } else { Ti <- Ti[1L:MAX.r[i]] zi <- zi[1L:MAX.r[i]] ri <- MAX.r[i] } } else { ri <- 0 if (infMAX & (0 < MAX.r[i])) { Ti <- rep(NA, length.out = MAX.r[i]) zi <- rep(-Inf, MAX.r[i]) ri <- MAX.r[i] } } if (ri > 0) { if (first) { MAXdata <- data.frame(block = blockNames[rep(i, ri)], date = Ti, var = zi, comment = rep("", ri)) first <- FALSE } else { MAXdata <- rbind(MAXdata, data.frame(block = blockNames[rep(i, ri)], date = Ti, var = zi, comment = rep("", ri))) } } MAX.r[i] <- ri } else { MAX.r[i] <- NA } if (!is.null(OTmissing)) { ind2 <- (Breaks2 >= Breaks[i]) & (Breaks2 < Breaks[i + 1L]) x <- as.numeric(interp2$x[ind2] - Breaks[i], units = "days") y <- interp2$y[ind2] if (length(y) == 366) y <- y[-60] probMiss <- probMiss + y[1:365] } } names(MAXdata) <- c("block", "date", vars, "comment") probMiss <- probMiss / nBlock MAXinfo <- data.frame(MAXinfo, r = MAX.r) MAXdata[["block"]] <- factor(MAXdata[["block"]], levels = blockNames) if (dataFrames) { res <- list(MAXinfo = MAXinfo, MAXdata = MAXdata, monthGapStat = ms, monthGapTS = mTS) } else { MAXdata <- as.list(MAXdata) ub <- as.logical(keepBlock) if (!infMAX) { ub <- ub & as.logical(table(MAXdata$block)) } effDuration <- MAXinfo[ub, "duration"] r <- MAXinfo[ub, "r"] names(effDuration) <- names(r) <- rownames(MAXinfo[ub, ]) MAXdata[["block"]] <- factor(MAXdata[["block"]]) res <- list(effDuration = effDuration, r = r, data = tapply(MAXdata[[vars]], MAXdata$block, list), monthGapStat = ms, monthGapTS = mTS) if (plot) MAXdata <- as.data.frame(MAXdata) } res$probMissing <- probMiss if (plot) { if (plotType == "max") { cols <- c("white", "lightcyan") y <- MAXdata[ , vars] ry <- range(y[is.finite(y) & !is.na(y)]) plot(range(Breaks), ry, xlab = "Block", ylab = vars[1], type = "n", ...) py <- par()$usr[3:4] py <- py + diff(py) * c(1, -1) / 200 for (i in 1L:nBlock) { rect(xleft = Breaks[i], xright = Breaks[i + 1], ybottom = py[1], ytop = py[2], col = cols[1 + i %% 2], border = NA) } points(x = MAXdata[["date"]], y = MAXdata[[vars]], type = "p", pch = 16, cex = 0.8) lines(x = MAXdata[["date"]], y = MAXdata[[vars]], type = "h") } else { if (!monthGapStat) { stop("the value \"gaps\" for 'plotType' works only when ", "'montStat' is TRUE") } days <- seq(from = as.POSIXct("2001-01-01", tz = TZ), by = "day", length.out = 365) monthMid <- seq(from = as.POSIXct("2001-01-15", tz = TZ), by = "month", length.out = 12) yEnd <- rep(2001, nrow(ms)) yEnd[as.integer(ms$month) == 12] <- 2002 dStart <- as.POSIXct(format(ms$start, format = "2001-%m-%d"), tz = TZ) dEnd <- as.POSIXct(paste(yEnd, format(ms$end, format = "-%m-%d"), sep = ""), tz = TZ) durMiss <- with(ms, tapply(durMissing, month, sum)) dur <- with(ms, tapply(dur, month, sum)) monthRate <- durMiss / dur plot(days, res$probMissing, type = "n", ylim = c(0, 1), xlab = "day in year", ylab = "prob. gap", xaxt = "n", ...) abline(v = monthStart) mtext(side = 1, line = 0.6, at = monthMid, text = monthLab) set.seed(jitterSeed) msMissing <- ms$missing + rnorm(ms$missing, sd = 0.01) barCol <- col2rgb("gray") / 256 barCol <- rgb(red = barCol[1], green = barCol[1], blue = barCol[1], alpha = 0.4) segments(x0 = dStart, x1 = dEnd, y0 = msMissing, y1 = msMissing, col = barCol) lines(x = c(monthStart[1], rep(monthStart[2:12], each = 2), monthStart[13]), y = rep(monthRate, each = 2), col = "orange", lwd = 2) lines(days, res$probMissing, type = "l", lwd = 2, col = "orangered") } } res }
fpolm <- function(dets,vec,vars,nom,garder=NULL){ n<-length(vec) ux=0 for(i in 1:n){xs=max(dets[vec[i]]) if(xs!=0){ux<-ux+t(t(dets[,vec[i]]/xs))*10^{n+1-i} }else{ux<-ux} } ux<-round(ux,digits=4) uxf<-duplicated(ux) dats1<-data.frame(dets[,c(vec,garder)],ux,uxf) names(dats1)<-c(vec,garder,"ux","uxf") ndats1<-dats1[dats1["uxf"]==FALSE,] ndets1<-ndats1[,c(vec,garder,"ux")] names(ndets1)<-c(vec,garder,"ux") vs<-tapply(dets[,vars[1]],ux,sum) id<-as.numeric(names(vs)) for (j in 2:length(vars)) vs<-cbind(vs,tapply(dets[,vars[j]],ux,sum)) rownames(vs)<-NULL tab<-data.frame(id,vs) names(tab)<-c("ux",nom) tab2<-merge(ndets1,tab,by=c("ux","ux")) tab2$ux<-NULL return(tab2) }
compPortfo <- function(xa, xb) { xab=cbind(xa,xb) ouall=rep(NA,3) m1=momentVote(xab) mm1=NROW(m1) m2=m1[mm1,1:2] ouall[1]=as.numeric(sign(m2[1]-m2[2])) d1=decileVote(xab) dd1=d1$out d2=dd1[NROW(dd1),1:2] ouall[2]=as.numeric(sign(d2[1]-d2[2])) s1=exactSdMtx(xab) s11=summaryRank(s1$out) s2=s11[10,] ouall[3]=as.numeric(sign(s2[1]-s2[2])) return(ouall) }
e2e_plot_biomass <- function(model,ci.data=FALSE, use.saved=FALSE, use.example=FALSE, results=NULL ) { oo <- options() on.exit(options(oo)) if (use.example == TRUE) hasExamples() start_par = par()$mfrow on.exit(par(mfrow = start_par)) if(use.saved==TRUE & use.example==TRUE){ stop("use.saved and use.example cannot both be TRUE ! \n") } if(use.saved==TRUE & is.list(results)==TRUE){ stop("use.saved is TRUE but a dataframe object has also been specified ! \n") } if(use.example==TRUE & is.list(results)==TRUE){ stop("use.example is TRUE but a dataframe object has also been specified ! \n") } if(use.saved==FALSE & use.example==FALSE & is.list(results)==FALSE){ stop("no source of data has been specified ! \n") } if(ci.data==FALSE & use.example==TRUE){ stop("no example data available for a single model run - run the model to generate some data ! \n") } if(ci.data==TRUE & use.saved==FALSE & use.example==FALSE & is.list(results)==TRUE){ stop("credible intervals available only from saved or example data ! \n") } if(ci.data == FALSE & use.saved==FALSE & is.list(results)==TRUE ){ plot_inshore_vs_offshore_anavmass(model, use.saved=FALSE,results=results) } if(ci.data == FALSE & use.saved==TRUE ){ plot_inshore_vs_offshore_anavmass(model, use.saved=TRUE) } if(ci.data == TRUE & use.saved==FALSE & use.example==TRUE ){ plot_inshore_vs_offshore_anavmass_with_ci(model, use.example=TRUE) } if(ci.data == TRUE & use.saved==TRUE & use.example==FALSE ){ plot_inshore_vs_offshore_anavmass_with_ci(model, use.example=FALSE) } }
context ("extract-objects") test_all <- (identical (Sys.getenv ("MPADGE_LOCAL"), "true") | identical (Sys.getenv ("GITHUB_WORKFLOW"), "test-coverage")) test_that ("missing objects", { expect_error (extract_osm_objects (), "key must be provided") expect_error (extract_osm_objects (key = "aaa"), "bbox must be provided") }) test_that ("key missing", { bbox <- get_bbox (c (-0.12, 51.51, -0.11, 51.52)) expect_error (extract_osm_objects (bbox = bbox, key = NULL), "key can not be NULL") expect_error (extract_osm_objects (bbox = bbox, key = NA), "key can not be NA") expect_error (extract_osm_objects (bbox = bbox), "key must be provided") }) if (curl::has_internet () & test_all) { test_that ("invalid key", { bbox <- get_bbox (c (-0.12, 51.51, -0.11, 51.52)) expect_warning (suppressMessages ( extract_osm_objects (bbox = bbox, key = "aaa")), "No valid data returned") }) test_that ("valid key", { bbox <- get_bbox (c (-0.12, 51.518, -0.118, 51.52)) dat <- extract_osm_objects (bbox = bbox, key = "building") expect_is (dat, "sf") dat <- extract_osm_objects (bbox = bbox, key = "building", sf = FALSE) expect_is (dat, "SpatialPolygonsDataFrame") }) test_that ("extra_pairs", { key <- "route" value <- "bicycle" extra_pairs <- c ("name", "London Cycle Network") bbox <- get_bbox (c (0, 51.5, 0.1, 51.6)) dat <- extract_osm_objects (bbox = bbox, key = key, value = value, extra_pairs = extra_pairs) expect_true (nrow (dat) > 0) expect_is (dat, "sf") }) test_that ("sp objects", { key <- "route" value <- "bicycle" extra_pairs <- c ("name", "London Cycle Network") bbox <- get_bbox (c (0, 51.5, 0.1, 51.6)) dat <- extract_osm_objects (bbox = bbox, key = key, value = value, extra_pairs = extra_pairs, sf = FALSE) expect_true (nrow (dat) > 0) expect_is (dat, "Spatial") }) }
sim.rm <- function(theta, b, seed = NULL){ if(length(theta) == 1){ if(!is.null(seed)){ set.seed(seed) theta <- stats::rnorm(theta, mean = 0, sd = 1) }else{ theta <- stats::rnorm(theta, mean = 0, sd = 1) } theta <- theta } if(length(b) == 1){ if(!is.null(seed)){ set.seed(seed) b <- stats::rnorm(b, mean = 0, sd = 1) }else{ b <- stats::rnorm(b, mean = 0, sd = 1) } b <- b } if(!is.null(seed)){ set.seed(seed) resp <- outer(theta, b, "-") p_exp <- exp(resp) prop_solve <- p_exp/(1 + p_exp) dat.resp <-(prop_solve > matrix(stats::runif(length(b)*length(theta)),length(theta),length(b)))*1 } else { resp <- outer(theta, b, "-") p_exp <- exp(resp) prop_solve <- p_exp/(1 + p_exp) dat.resp <-(prop_solve > matrix(stats::runif(length(b)*length(theta)),length(theta),length(b)))*1 } if(!is.null(names(b))){ colnames(dat.resp) <- names(b) } return(dat.resp) }
`get.tausB` = function(n, n0B, geneids, min.cnt=50, exclude.prop=.05, Xist.ID="ENSMUSG00000086503"){ out = matrix(sapply(1:ncol(n), get.tauB, n=n, n0B=n0B, geneids=geneids, min.cnt=min.cnt, exclude.prop=exclude.prop, filt=Xist.ID), nrow=4) if(any(unlist(sapply(out, is.null)))){ stop("too stringent criterias for the given counts") } colnames(out) = colnames(n0B) rownames(out) = c("med.tauB", "ave.tauB", "all.genes", "used.genes") return(out) }
splinePath <- function(x, y, degree, knots, detail, type) { .Call('_ggforce_splinePath', PACKAGE = 'ggforce', x, y, degree, knots, detail, type) } getSplines <- function(x, y, id, detail, type = "clamped") { .Call('_ggforce_getSplines', PACKAGE = 'ggforce', x, y, id, detail, type) } bezierPath <- function(x, y, detail) { .Call('_ggforce_bezierPath', PACKAGE = 'ggforce', x, y, detail) } getBeziers <- function(x, y, id, detail) { .Call('_ggforce_getBeziers', PACKAGE = 'ggforce', x, y, id, detail) } enclose_ellip_points <- function(x, y, id, tol) { .Call('_ggforce_enclose_ellip_points', PACKAGE = 'ggforce', x, y, id, tol) } enclose_points <- function(x, y, id) { .Call('_ggforce_enclose_points', PACKAGE = 'ggforce', x, y, id) } points_to_path <- function(pos, path, close) { .Call('_ggforce_points_to_path', PACKAGE = 'ggforce', pos, path, close) }
check.exclude <- function(exclude,nvars){ exclude <- unique(exclude) if(length(exclude)> (nvars-2))stop("cannot retain 1 or less variables") if(length(exclude)==0)exclude <- NULL exclude }
context("gpdRangeFit") test_that("gpdRangeFit behaves as it should", { skip_on_cran() skip_on_travis() par(mfrow=c(2,1)) res <- gpdRangeFit(rain, umin=0, umax=50, nint=19) plot(res, pch=16, main=c("Figure 4.2 of Coles (2001)",""), addNexcesses=FALSE) expect_that(names(res), equals(c("th", "par","hi","lo","data")), label="gpdRangeFit: returned list with correct names") } )
"airbnb_small"
use_template <- function(template, save_as = template, data = list()) { template_contents <- render_template(template, data) new <- base::writeLines(template_contents, save_as) invisible(new) } render_template <- function(template, data = list()) { template_path <- find_template(template) base::strsplit(whisker::whisker.render(read_utf8(template_path), data), "\n")[[1]] } find_template <- function(template_name) { fs::path_package(package = "prodigenr", "templates", template_name) } read_utf8 <- function(path, n = -1L) { base::readLines(path, n = n, encoding = "UTF-8", warn = FALSE) } add_rproj_file <- function(proj_name) { rproj_file <- paste0(proj_name, ".Rproj") new <- use_template( "template-rproj", rproj_file ) } has_git <- function(project_path = ".") { repo <- tryCatch(gert::git_find(project_path), error = function(e) NULL) !is.null(repo) }
read.gal <- function(file, region.id=NULL, override.id=FALSE) { con <- file(file, open="r") line <- unlist(strsplit(readLines(con, 1), " ")) x <- subset(line, nchar(line) > 0) if (length(x) == 1L) { n <- as.integer(x[1]) shpfile <- as.character(NA) ind <- as.character(NA) } else if (length(x) == 4L) { n <- as.integer(x[2]) shpfile <- as.character(x[3]) ind <- as.character(x[4]) } else stop ("Invalid header line in GAL file") if (n < 1) stop("Non-positive number of regions") if (!is.null(region.id)) if (length(unique(region.id)) != length(region.id)) stop("non-unique region.id given") if (is.null(region.id)) region.id <- as.character(1:n) if (n != length(region.id)) stop("Mismatch in dimensions of GAL file and region.id") rn <- character(n) res <- vector(mode="list", length=n) for (i in 1:n) { line <- unlist(strsplit(readLines(con, 1), " ")) x <- subset(line, nchar(line) > 0) rn[i] <- x[1] line <- unlist(strsplit(readLines(con, 1), " ")) y <- subset(line, nchar(line) > 0) if(length(y) != as.integer(x[2])) { close(con) stop(paste("GAL file corrupted at region", i)) } res[[i]] <- y } close(con) if (!override.id) { if (!all(rn %in% region.id)) { stop("GAL file IDs and region.id differ") } } else region.id <- rn mrn <- match(rn, region.id) res1 <- vector(mode="list", length=n) for (i in 1:n) { if (length(res[[i]]) > 0) { x <- match(res[[i]], region.id) if (any(is.na(x)) | (length(x) != length(res[[i]]))) { stop(paste("GAL file corrupted at region", i)) } if(any(x < 0) || any(x > n)) stop("GAL file corrupted") res1[[mrn[i]]] <- sort(x) } else { res1[[mrn[i]]] <- 0L } } class(res1) <- "nb" attr(res1, "region.id") <- region.id attr(res1, "GeoDa") <- list(shpfile=shpfile, ind=ind) attr(res1, "gal") <- TRUE attr(res1, "call") <- TRUE res1 <- sym.attr.nb(res1) res1 } write.nb.gal <- function(nb, file, oldstyle=TRUE, shpfile=NULL, ind=NULL) { if (!inherits(nb, "nb")) stop("not a neighbours list") n <- length(nb) if (n < 1) stop("non-positive number of entities") cn <- card(nb) rn <- attr(nb, "region.id") if (is.null(shpfile)) { tmp <- attr(nb, "GeoDa")$shpfile if (is.null(tmp)) shpfile <- "unknown" else shpfile <- tmp } if (is.null(ind)) { tmp <- attr(nb, "GeoDa")$ind if (is.null(tmp)) ind <- "unknown" else ind <- tmp } con <- file(file, open="w") if (oldstyle) writeLines(paste(n), con) else writeLines(paste("0", n, shpfile, ind, sep=" "), con) for (i in 1:n) { if (oldstyle) writeLines(paste(i, cn[i], collapse=" "), con) else writeLines(paste(rn[i], cn[i], collapse=" "), con) if (oldstyle) writeLines(ifelse(cn[i] > 0, paste(nb[[i]], collapse=" "), ""), con) else writeLines(ifelse(cn[i] > 0, paste(rn[nb[[i]]], collapse=" "), ""), con) } close(con) } read.geoda <- function(file, row.names=NULL, skip=0) { res <- read.csv(file=file, header=TRUE, skip=skip, row.names=row.names) if (ncol(res) < 2) warning("data frame possibly malformed") res }
context("Checking analysis example: raudenbush2009") source("settings.r") dat <- dat.raudenbush1985 test_that("results are correct for the equal-effects model.", { res.EE <- rma(yi, vi, data=dat, digits=3, method="EE") expect_equivalent(coef(res.EE), 0.0604, tolerance=.tol[["coef"]]) expect_equivalent(res.EE$QE, 35.8295, tolerance=.tol[["test"]]) expect_equivalent(res.EE$zval, 1.6553, tolerance=.tol[["test"]]) }) test_that("results are correct for the random-effects model.", { res.RE <- rma(yi, vi, data=dat, digits=3) expect_equivalent(coef(res.RE), 0.0837, tolerance=.tol[["coef"]]) expect_equivalent(res.RE$zval, 1.6208, tolerance=.tol[["test"]]) expect_equivalent(res.RE$tau2, 0.0188, tolerance=.tol[["var"]]) tmp <- predict(res.RE) expect_equivalent(tmp$pi.lb, -0.2036, tolerance=.tol[["ci"]]) expect_equivalent(tmp$pi.ub, 0.3711, tolerance=.tol[["ci"]]) tmp <- range(blup(res.RE)$pred) expect_equivalent(tmp, c(-0.0293, 0.2485), tolerance=.tol[["pred"]]) }) test_that("results are correct for the mixed-effects model.", { dat$weeks.c <- ifelse(dat$weeks > 3, 3, dat$weeks) res.ME <- rma(yi, vi, mods = ~ weeks.c, data=dat, digits=3) expect_equivalent(res.ME$tau2, 0.0000, tolerance=.tol[["var"]]) expect_equivalent(coef(res.ME), c(0.4072, -0.1572), tolerance=.tol[["coef"]]) expect_equivalent(res.ME$QE, 16.5708, tolerance=.tol[["test"]]) expect_equivalent(res.ME$zval, c(4.6782, -4.3884), tolerance=.tol[["test"]]) tmp <- range(blup(res.ME)$pred) expect_equivalent(tmp, c(-0.0646, 0.4072), tolerance=.tol[["pred"]]) }) test_that("results are correct for the random-effects model (conventional approach).", { res.std <- list() res.std$EE <- rma(yi, vi, data=dat, digits=3, method="EE") res.std$ML <- rma(yi, vi, data=dat, digits=3, method="ML") res.std$REML <- rma(yi, vi, data=dat, digits=3, method="REML") res.std$DL <- rma(yi, vi, data=dat, digits=3, method="DL") res.std$HE <- rma(yi, vi, data=dat, digits=3, method="HE") tmp <- t(sapply(res.std, function(x) c(tau2=x$tau2, mu=x$beta, se=x$se, z=x$zval, ci.lb=x$ci.lb, ci.ub=x$ci.ub))) expected <- structure(c(0, 0.0126, 0.0188, 0.0259, 0.0804, 0.0604, 0.0777, 0.0837, 0.0893, 0.1143, 0.0365, 0.0475, 0.0516, 0.0558, 0.0792, 1.6553, 1.6368, 1.6208, 1.6009, 1.4432, -0.0111, -0.0153, -0.0175, -0.02, -0.0409, 0.1318, 0.1708, 0.1849, 0.1987, 0.2696), .Dim = 5:6, .Dimnames = list(c("EE", "ML", "REML", "DL", "HE"), c("tau2", "mu", "se", "z", "ci.lb", "ci.ub"))) expect_equivalent(tmp, expected, tolerance=.tol[["misc"]]) }) test_that("results are correct for the random-effects model (Knapp & Hartung method).", { res.knha <- list() expect_warning(res.knha$EE <- rma(yi, vi, data=dat, digits=3, method="EE", test="knha")) res.knha$ML <- rma(yi, vi, data=dat, digits=3, method="ML", test="knha") res.knha$REML <- rma(yi, vi, data=dat, digits=3, method="REML", test="knha") res.knha$DL <- rma(yi, vi, data=dat, digits=3, method="DL", test="knha") res.knha$HE <- rma(yi, vi, data=dat, digits=3, method="HE", test="knha") tmp <- t(sapply(res.knha, function(x) c(tau2=x$tau2, mu=x$beta, se=x$se, z=x$zval, ci.lb=x$ci.lb, ci.ub=x$ci.ub))) expected <- structure(c(0, 0.0126, 0.0188, 0.0259, 0.0804, 0.0604, 0.0777, 0.0837, 0.0893, 0.1143, 0.0515, 0.0593, 0.0616, 0.0636, 0.0711, 1.1733, 1.311, 1.3593, 1.405, 1.6078, -0.0477, -0.0468, -0.0457, -0.0442, -0.0351, 0.1685, 0.2023, 0.2131, 0.2229, 0.2637), .Dim = 5:6, .Dimnames = list(c("EE", "ML", "REML", "DL", "HE"), c("tau2", "mu", "se", "z", "ci.lb", "ci.ub"))) expect_equivalent(tmp, expected, tolerance=.tol[["misc"]]) }) test_that("results are correct for the random-effects model (Huber-White method).", { res.std <- list() res.std$EE <- rma(yi, vi, data=dat, digits=3, method="EE") res.std$ML <- rma(yi, vi, data=dat, digits=3, method="ML") res.std$REML <- rma(yi, vi, data=dat, digits=3, method="REML") res.std$DL <- rma(yi, vi, data=dat, digits=3, method="DL") res.std$HE <- rma(yi, vi, data=dat, digits=3, method="HE") res.hw <- list() res.hw$EE <- robust(res.std$EE, cluster=study, adjust=FALSE) res.hw$ML <- robust(res.std$ML, cluster=study, adjust=FALSE) res.hw$REML <- robust(res.std$REML, cluster=study, adjust=FALSE) res.hw$DL <- robust(res.std$DL, cluster=study, adjust=FALSE) res.hw$HE <- robust(res.std$HE, cluster=study, adjust=FALSE) out <- capture.output(print(res.hw$REML)) tmp <- t(sapply(res.hw, function(x) c(tau2=x$tau2, mu=x$beta, se=x$se, t=x$zval, ci.lb=x$ci.lb, ci.ub=x$ci.ub))) expected <- structure(c(0, 0.0126, 0.0188, 0.0259, 0.0804, 0.0604, 0.0777, 0.0837, 0.0893, 0.1143, 0.0398, 0.0475, 0.05, 0.0522, 0.0618, 1.5148, 1.6369, 1.6756, 1.7105, 1.8503, -0.0234, -0.022, -0.0213, -0.0204, -0.0155, 0.1441, 0.1775, 0.1887, 0.199, 0.2441), .Dim = 5:6, .Dimnames = list(c("EE", "ML", "REML", "DL", "HE"), c("tau2", "mu", "se", "t", "ci.lb", "ci.ub"))) expect_equivalent(tmp, expected, tolerance=.tol[["misc"]]) }) rm(list=ls())
AutoFitPhenology <- function(data=stop("A dataset must be provided"), progressbar=TRUE, ...) { if (class(data)!="phenologydata") { stop("Data must be formated first using the function add_phenology().") } p3p <- list(...) if (progressbar) pb<-txtProgressBar(min=1, max=8, style=3) if (progressbar) setTxtProgressBar(pb, 1) pfixed <- c(Min=0) parg <- par_init(data = data, fixed.parameters = pfixed) parg <- c(parg, PMinB=5, PMinE=5) pfixed <- NULL p3p_encours <- modifyList(p3p, list(data = data, fitted.parameters = parg, fixed.parameters = pfixed, hessian = FALSE)) fit1 <- do.call("fit_phenology", p3p_encours) if (progressbar) setTxtProgressBar(pb, 2) pfixed <- NULL parg <- fit1$par parg["PMinB"] <- mean(c(parg["PMinB"], parg["PMinE"])) parg <- parg[-which(names(parg)=="PMinE")] names(parg)[which(names(parg)=="PMinB")] <- "PMin" p3p_encours <- modifyList(p3p, list(data = data, fitted.parameters = parg, fixed.parameters = pfixed, hessian = FALSE)) fit2 <- do.call("fit_phenology", p3p_encours) if (progressbar) setTxtProgressBar(pb, 3) pfixed <- c(Min = 0) parg <- fit2$par parg <- parg[-which(names(parg)=="PMin")] p3p_encours <- modifyList(p3p, list(data = data, fitted.parameters = parg, fixed.parameters = pfixed, hessian = FALSE)) fit3 <- do.call("fit_phenology", p3p_encours) if (progressbar) setTxtProgressBar(pb, 4) pfixed <- c(Flat = 0) parg <- fit1$par parg <- parg[-which(names(parg)=="Flat")] p3p_encours <- modifyList(p3p, list(data = data, fitted.parameters = parg, fixed.parameters = pfixed, hessian = FALSE)) fit4 <- do.call("fit_phenology", p3p_encours) if (progressbar) setTxtProgressBar(pb, 5) pfixed <- c(Flat = 0) parg <- fit4$par parg["PMinB"] <- mean(c(parg["PMinB"], parg["PMinE"])) parg <- parg[-which(names(parg)=="PMinE")] names(parg)[which(names(parg)=="PMinB")] <- "PMin" p3p_encours <- modifyList(p3p, list(data = data, fitted.parameters = parg, fixed.parameters = pfixed, hessian = FALSE)) fit5 <- do.call("fit_phenology", p3p_encours) if (progressbar) setTxtProgressBar(pb, 6) pfixed <- c(Min = 0, Flat = 0) parg <- fit5$par parg <- parg[-which(names(parg)=="PMin")] p3p_encours <- modifyList(p3p, list(data = data, fitted.parameters = parg, fixed.parameters = pfixed, hessian = FALSE)) fit6 <- do.call("fit_phenology", p3p_encours) if (progressbar) setTxtProgressBar(pb, 7) parg <- fit1$par parg["LengthB"] <- mean(c(parg["LengthB"], parg["LengthE"])) parg <- parg[-which(names(parg)=="LengthE")] names(parg)[which(names(parg)=="LengthB")] <- "Length" pfixed <- fit1$fixed.parameters p3p_encours <- modifyList(p3p, list(data = data, fitted.parameters = parg, fixed.parameters = pfixed, hessian = FALSE)) fit7 <- do.call("fit_phenology", p3p_encours) if (progressbar) setTxtProgressBar(pb, 8) parg <- fit2$par parg["LengthB"] <- mean(c(parg["LengthB"], parg["LengthE"])) parg <- parg[-which(names(parg)=="LengthE")] names(parg)[which(names(parg)=="LengthB")] <- "Length" pfixed <- fit2$fixed.parameters p3p_encours <- modifyList(p3p, list(data = data, fitted.parameters = parg, fixed.parameters = pfixed, hessian = FALSE)) fit8 <- do.call("fit_phenology", p3p_encours) if (progressbar) setTxtProgressBar(pb, 9) parg <- fit3$par parg["LengthB"] <- mean(c(parg["LengthB"], parg["LengthE"])) parg <- parg[-which(names(parg)=="LengthE")] names(parg)[which(names(parg)=="LengthB")] <- "Length" pfixed <- fit3$fixed.parameters p3p_encours <- modifyList(p3p, list(data = data, fitted.parameters = parg, fixed.parameters = pfixed, hessian = FALSE)) fit9 <- do.call("fit_phenology", p3p_encours) if (progressbar) setTxtProgressBar(pb, 10) parg <- fit4$par parg["LengthB"] <- mean(c(parg["LengthB"], parg["LengthE"])) parg <- parg[-which(names(parg)=="LengthE")] names(parg)[which(names(parg)=="LengthB")] <- "Length" pfixed <- fit4$fixed.parameters p3p_encours <- modifyList(p3p, list(data = data, fitted.parameters = parg, fixed.parameters = pfixed, hessian = FALSE)) fit10 <- do.call("fit_phenology", p3p_encours) if (progressbar) setTxtProgressBar(pb, 11) parg <- fit5$par parg["LengthB"] <- mean(c(parg["LengthB"], parg["LengthE"])) parg <- parg[-which(names(parg)=="LengthE")] names(parg)[which(names(parg)=="LengthB")] <- "Length" pfixed <- fit5$fixed.parameters p3p_encours <- modifyList(p3p, list(data = data, fitted.parameters = parg, fixed.parameters = pfixed, hessian = FALSE)) fit11 <- do.call("fit_phenology", p3p_encours) if (progressbar) setTxtProgressBar(pb, 12) parg <- fit6$par parg["LengthB"] <- mean(c(parg["LengthB"], parg["LengthE"])) parg <- parg[-which(names(parg)=="LengthE")] names(parg)[which(names(parg)=="LengthB")] <- "Length" pfixed <- fit6$fixed.parameters p3p_encours <- modifyList(p3p, list(data = data, fitted.parameters = parg, fixed.parameters = pfixed, hessian = FALSE)) fit12 <- do.call("fit_phenology", p3p_encours) compare_AIC(LengthB_LengthE_Flat_PMinB_PMinE = fit1, LengthB_LengthE_Flat_PMin = fit2, LengthB_LengthE_Flat = fit3, LengthB_LengthE_PMinB_PMinE = fit4, LengthB_LengthE_PMin = fit5, LengthB_LengthE = fit6, Length_Flat_PMinB_PMinE = fit7, Length_Flat_PMin = fit8, Length_Flat = fit9, Length_PMinB_PMinE = fit10, Length_PMin = fit11, Length = fit12) return(list(LengthB_LengthE_Flat_PMinB_PMinE = fit1, LengthB_LengthE_Flat_PMin = fit2, LengthB_LengthE_Flat = fit3, LengthB_LengthE_PMinB_PMinE = fit4, LengthB_LengthE_PMin = fit5, LengthB_LengthE = fit6, Length_Flat_PMinB_PMinE = fit7, Length_Flat_PMin = fit8, Length_Flat = fit9, Length_PMinB_PMinE = fit10, Length_PMin = fit11, Length = fit12)) }
knitr::opts_chunk$set(echo=TRUE, fig.width=6, fig.height=4) library(cowplot) library(PKNCA) library(knitr) library(ggplot2) source("../tests/testthat/generate.data.R") scale_colour_discrete <- scale_colour_hue scale_fill_discrete <- scale_fill_hue cat("ggplot2 is required for this vignette to work correctly. Please install the ggplot2 library and retry building the vignette.") d_conc <- PKNCAconc( generate.conc(nsub=1, ntreat=1, time.points=c(0, 1, 2, 4, 6, 8, 12, 24, 36, 48), nstudies=1, nanalytes=1, resid=0), conc~time|treatment+ID) print(d_conc) d_conc_multi <- superposition(d_conc, tau=168, dose.times=seq(0, 168-24, by=24), n.tau=1) ggplot(d_conc_multi, aes(x=time, y=conc)) + geom_ribbon(data=d_conc_multi[d_conc_multi$time >= 144,], aes(ymax=conc, ymin=0), fill="skyblue") + geom_point() + geom_line() + scale_x_continuous(breaks=seq(0, 168, by=12)) + scale_y_continuous(limits=c(0, NA)) + labs(x="Time Since First Dose (hr)", y="Concentration\n(arbitrary units)") intervals_manual <- data.frame(start=144, end=168, auclast=TRUE) knitr::kable(intervals_manual) PKNCAdata(d_conc, intervals=intervals_manual) intervals_manual <- data.frame( treatment=c("Drug 1 Single", "Drug 1 Multiple", "Drug 1 Multiple"), start=c(0, 0, 216), end=c(Inf, 24, 240), aucinf.obs=c(TRUE, FALSE, FALSE), auclast=c(FALSE, TRUE, TRUE) ) knitr::kable(intervals_manual) d_conc <- PKNCAconc( generate.conc(nsub=1, ntreat=1, time.points=c(0, 1, 2, 4, 6, 8, 12, 24, 36, 48), nstudies=1, nanalytes=1, resid=0), conc~time|treatment+ID) print(d_conc) ggplot(d_conc$data[d_conc$data$time <= 48,], aes(x=time, y=conc)) + geom_ribbon(data=d_conc$data, aes(ymax=conc, ymin=0), fill="skyblue") + geom_point() + geom_line() + scale_x_continuous(breaks=seq(0, 72, by=12)) + scale_y_continuous(limits=c(0, NA)) + labs(x="Time Since First Dose (hr)", y="Concentration\n(arbitrary units)") intervals_manual <- data.frame( start=0, end=Inf, auclast=TRUE, aucinf.obs=TRUE ) print(intervals_manual) my.data <- PKNCAdata(d_conc, intervals=intervals_manual) d_conc <- PKNCAconc( generate.conc(nsub=1, ntreat=1, time.points=c(0, 1, 2, 4, 6, 8, 12, 24, 36, 48), nstudies=1, nanalytes=1, resid=0), conc~time|treatment+ID) print(d_conc) d_conc_multi <- superposition(d_conc, tau=168, dose.times=seq(0, 168-24, by=24), n.tau=1) ggplot(d_conc_multi, aes(x=time, y=conc)) + geom_ribbon(data=d_conc_multi[d_conc_multi$time <= 24,], aes(ymax=conc, ymin=0), fill="skyblue") + geom_ribbon(data=d_conc_multi[d_conc_multi$time >= 144,], aes(ymax=conc, ymin=0), fill="lightgreen") + geom_point() + geom_line() + scale_x_continuous(breaks=seq(0, 168, by=12)) + scale_y_continuous(limits=c(0, NA)) + labs(x="Time Since First Dose (hr)", y="Concentration\n(arbitrary units)") intervals_manual <- data.frame( start=c(0, 144), end=c(24, 168), auclast=TRUE ) knitr::kable(intervals_manual) my.data <- PKNCAdata(d_conc, intervals=intervals_manual) d_conc <- PKNCAconc( generate.conc(nsub=1, ntreat=1, time.points=c(0, 1, 2, 4, 6, 8, 12, 24, 36, 48), nstudies=1, nanalytes=1, resid=0), conc~time|treatment+ID) print(d_conc) ggplot(d_conc$data, aes(x=time, y=conc)) + geom_ribbon(data=d_conc$data, aes(ymax=conc, ymin=0), fill="lightgreen", alpha=0.5) + geom_ribbon(data=d_conc$data[d_conc$data$time <= 24,], aes(ymax=conc, ymin=0), fill="skyblue", alpha=0.5) + geom_point() + geom_line() + scale_x_continuous(breaks=seq(0, 168, by=12)) + scale_y_continuous(limits=c(0, NA)) + labs(x="Time Since First Dose (hr)", y="Concentration\n(arbitrary units)") intervals_manual <- data.frame( start=0, end=c(24, Inf), auclast=TRUE, aucinf.obs=c(FALSE, TRUE) ) knitr::kable(intervals_manual) my.data <- PKNCAdata(d_conc, intervals=intervals_manual) ggplot_intervals <- function(definition, intervals) { intervals$within <- c("No", "Yes")[intervals$interval.start >= min(definition$start.x) & intervals$interval.end >= max(definition$start.x)] intervals$within <- factor(intervals$within, levels=c("Yes", "No")) ggplot(intervals, aes(x=interval.start, xend=interval.end, y=y, yend=y, linetype=within)) + geom_segment() + geom_segment(data=definition, mapping=aes(x=start.x, xend=start.x, y=start.y, yend=end.y), arrow=arrow(), inherit.aes=FALSE) + geom_point(aes(x=interval.start, y=1), shape="|", size=4) + geom_point(aes(x=max(interval.end), y=1), shape="|", size=4) + scale_y_continuous(breaks=NULL) + labs(x="Time", y=NULL) } interval_definition <- data.frame(start.x=c(0, 24), start.y=0.5, end.y=0.9) show_intervals <- data.frame(interval.start=c(0, 4, 12, 24), interval.end=c(4, 12, 24, 48), y=1) ggplot_intervals(interval_definition, show_intervals) interval_definition <- data.frame(start.x=c(0, 16), start.y=0.5, end.y=0.9) show_intervals <- data.frame(interval.start=c(0, 4, 12, 24), interval.end=c(4, 12, 24, 48), y=1) ggplot_intervals(interval_definition, show_intervals) interval_spec <- get.interval.cols() interval_spec <- interval_spec[sort(names(interval_spec))] get_function_for_calc <- function(x) { if (is.na(x$FUN)) { if (is.null(x$depends)) { "(none)" } else { paste("See the parameter name", x$depends) } } else { x$FUN } } kable( data.frame( `Parameter Name`=names(interval_spec), `Parameter Description`=sapply(interval_spec, `[[`, "desc"), `Function for Calculation`=sapply(interval_spec, get_function_for_calc), check.names=FALSE, stringsAsFactors=FALSE ), row.names=FALSE )
`permute` <- function(i, n, control) { complete <- getComplete(control) ap <- getAllperms(control) perm <- if (complete && !is.null(ap)) { ap[i, ] } else { if (complete) { warning("'$all.perms' is NULL, yet '$complete = TRUE'.\nReturning a random permutation.") } shuffle(n, control) } perm }
tracePlot <- function(object, layout=c(3,3), ask=NULL, ...) { objName <- deparse(substitute(object)) plotStuff("trace", object=object, objName=objName, layout=layout, ask=ask, ...) } tracePlot1 <- function(mat, name, dots) { defaultArgs <- list(xlab="Iterations", ylab="", type='l', lty=1) useArgs <- modifyList(defaultArgs, dots) useArgs$y <- mat useArgs$main <- name do.call(matplot, useArgs) abline(h=mean(mat)) } densityPlot <- function(object, layout=c(3,3), ask=NULL, ...) { objName <- deparse(substitute(object)) plotStuff("density", object=object, objName=objName, layout=layout, ask=ask, ...) } densityPlot1 <- function(mat, name, dots) { defaultArgs <- list(ylab="Density", type='l', lty=1, xlab="") useArgs <- modifyList(defaultArgs, dots) densPlot0(mat, useArgs) title(main=name) } acfPlot <- function(object, lag.max=NULL, layout=c(3,3), ask=NULL, ...) { objName <- deparse(substitute(object)) plotStuff("acf", object=object, objName=objName, layout=layout, ask=ask, lag.max=lag.max, ...) } acfPlot1 <- function(mat, name, lag.max, dots) { defaultArgs <- list(ylab="ACF", xlab="Lag", type='h', lty=1) useArgs <- modifyList(defaultArgs, dots) acor <- apply(mat, 2, function(x) acf(x, lag.max=lag.max, plot=FALSE)$acf) if(any(is.na(acor))) { plot(1, 1, type = "n", ann = FALSE, axes = FALSE) text(1,1, "No ACF calculated.") title(main=name) } else { lags <- 0:(nrow(acor) - 1) if (ncol(mat) > 1) { jitt <- seq(-0.2, 0.2, length=ncol(mat)) } else { jitt <- 0 } lags.mat <- outer(lags, jitt, "+") useArgs$main <- name useArgs$x <- lags.mat useArgs$y <- acor do.call(matplot, useArgs) abline(h=0) } }
dt1 <- simulation_model1(seed = 50) test_that("extreme_rank_lenk depth handles unconventional data", { expect_error(extreme_rank_length(dt = list())) expect_error(extreme_rank_length(dt = data.frame()) ) expect_error(extreme_rank_length(dt = matrix(0, nrow = 1, ncol = 3))) expect_error(extreme_rank_length(dt = matrix(c(1:2, NA), nrow = 1, ncol = 3))) expect_error(extreme_rank_length(dt = dt1$data, type = "left")) }) test_that("extreme_rank_lenk depth throws errows on strange type", { expect_error(extreme_rank_length(dt = matrix(1:9, nrow = 3, ncol = 3), type = "one_sided_laft")) }) test_that("extreme_rank_lenk depth produces correct results", { dt <-dt1$data[1:9, 1:7] dtt <- rbind(dt, dt[1,]) expect_equal(extreme_rank_length(dt, type = "one_sided_right")*9, c(4, 7, 8, 9, 2, 6, 3, 1, 5)) expect_equal(extreme_rank_length(dtt, type = "one_sided_right"), c(0.45, 0.80, 0.90, 1.00, 0.20, 0.70, 0.30, 0.10, 0.60, 0.45)) expect_equal(extreme_rank_length(dt, type = "two_sided")*9, c(8, 6, 3, 2, 4, 7, 5, 1, 9)) expect_equal(extreme_rank_length(dtt, type = "two_sided"), c(0.85, 0.60, 0.30, 0.20, 0.40, 0.70, 0.50, 0.10, 1.00, 0.85)) expect_equal(extreme_rank_length(dt, type = "one_sided_left")*9, c(6, 3, 2, 1, 8, 4, 7, 9, 5)) expect_equal(extreme_rank_length(dtt, type = "one_sided_left"), c(0.75, 0.30, 0.20, 0.10, 0.90, 0.40, 0.60, 1.00, 0.50, 0.75)) })
perturbation <- function(x, y){ constSum(x * y) } powering <- function(x, a){ constSum(x^a) }
check.factor <- function(train, test, gfactor) { if (!is.null(gfactor)) { if (length(gfactor$factor) > 0) { test[, match(gfactor$factor, colnames(test))] <- data.frame( mclapply(1:length(gfactor$factor), function(k) { fk.train <- train[, colnames(train) == gfactor$factor[k]] fk.test <- test[ , colnames(test) == gfactor$factor[k]] if (length(setdiff(levels(na.omit(fk.test)), levels(fk.train))) > 0) { stop("Factors in test and training data do not match...\n") } factor(as.character(fk.test), levels = gfactor$levels[[k]], exclude = NULL) })) } if (length(gfactor$order) > 0) { test[, match(gfactor$order, colnames(test))] <- data.frame( mclapply(1:length(gfactor$order), function(k) { fk.train <- train[, colnames(train) == gfactor$order[k]] fk.test <- test[ , colnames(test) == gfactor$order[k]] if (length(setdiff(levels(na.omit(fk.test)), levels(fk.train))) > 0) { stop("Factors in test and training data do not match...\n") } factor(as.character(fk.test), levels = gfactor$order.levels[[k]], ordered = TRUE) })) } } test } is.factor.not.ordered <- function(x) {is.factor(x) && !is.ordered(x)} extract.factor <- function (dat, generic.names = NULL) { generic.types <- gfactor <- gfactor.order <- gfactor.levels <- gfactor.order.levels <- NULL if (is.null(generic.names)) { target.names <- names(dat) } else { target.names <- generic.names } nlevels <- rep(0, length(target.names)) gfactor <- names(dat)[unlist(lapply(dat, is.factor.not.ordered))] gfactor.order <- names(dat)[unlist(lapply(dat, is.ordered))] if (!is.null(generic.names)) gfactor <- intersect(gfactor , generic.names) if (!is.null(generic.names)) gfactor.order <- intersect(gfactor.order , generic.names) if (length(gfactor) > 0) { gfactor.levels <- mclapply(cbind(1:(1+length(gfactor))), function(k) { if (k <= length(gfactor)) { levels(dat[ , names(dat) == gfactor[k]]) } else { NULL } }) gfactor.levels <- gfactor.levels[-(1+length(gfactor))] nlevels[match(gfactor, target.names)] <- unlist(lapply(gfactor.levels, function(g){length(g)})) } if (length(gfactor.order) > 0 ) { gfactor.order.levels <- mclapply(1:(1+length(gfactor.order)), function(k) { if (k <= length(gfactor.order)) { levels(dat[ , names(dat) == gfactor.order[k]]) } else { NULL } }) gfactor.order.levels <- gfactor.order.levels[-(1+length(gfactor.order))] nlevels[match(gfactor.order, target.names)] <- unlist(lapply(gfactor.order.levels, function(g){length(g)})) } if (!is.null(generic.names)) { generic.types <- rep("R", length(generic.names)) if (length(gfactor) > 0) { generic.types[match(gfactor, generic.names)] <- "C" } if (length(gfactor.order) > 0) { generic.types[match(gfactor.order, generic.names)] <- "I" } } else { generic.types <- rep("R", ncol(dat)) if (length(gfactor) > 0) { generic.types[match(gfactor, names(dat))] <- "C" } if (length(gfactor.order) > 0) { generic.types[match(gfactor.order, names(dat))] <- "I" } } if (is.null(gfactor) & is.null(gfactor.order)) { return(NULL) } else { return(list(factor=gfactor, order=gfactor.order, levels=gfactor.levels, order.levels=gfactor.order.levels, nlevels = nlevels, generic.types=generic.types)) } } map.factor <- function (gvar, gfactor) { if (!is.null(gfactor)) { if (length(gfactor$factor) > 0) { gvar[, match(gfactor$factor, colnames(gvar))] <- data.frame( mclapply(1:length(gfactor$factor), function(k) { ptk <- (colnames(gvar) == gfactor$factor[k]) factor.k <- gfactor$levels[[k]][gvar[ , ptk ]] labels.k <- gfactor$levels[[k]][sort(unique(gvar[ , ptk ]))] gk <- factor(factor.k, labels = labels.k, levels = labels.k, exclude = NULL) if (length(setdiff(gfactor$levels[[k]], labels.k)) > 0) { gk <- factor(as.character(gk), levels = gfactor$levels[[k]]) } gk })) } if (length(gfactor$order) > 0) { gvar[, match(gfactor$order, colnames(gvar))] <- data.frame( mclapply(1:length(gfactor$order), function(k) { ptk <- (colnames(gvar) == gfactor$order[k]) factor.k <- gfactor$order.levels[[k]][gvar[ , ptk ]] labels.k <- gfactor$order.levels[[k]][sort(unique(gvar[ , ptk ]))] gk <- factor(factor.k, labels = labels.k, levels = labels.k, exclude = NULL, ordered = TRUE) if (length(setdiff(gfactor$order.levels[[k]], labels.k)) > 0) { gk <- factor(as.character(gk), levels = gfactor$order.levels[[k]], ordered = TRUE) } gk })) } } gvar } rm.na.levels <- function(dat, xvar.names=NULL) { factor.names <- names(dat)[unlist(lapply(dat, is.factor))] if (!is.null(xvar.names)) factor.names <- intersect(factor.names , xvar.names) if (length(factor.names) > 0) { levels.na.pt <- unlist(lapply(1:length(factor.names), function(k) { any(levels(dat[ , names(dat) == factor.names[k]]) == "NA") })) if (any(levels.na.pt)) { factor.names <- factor.names[levels.na.pt] dat[, match(factor.names, names(dat))] <- data.frame(mclapply(1:length(factor.names), function(k) { x <- dat[ , names(dat) == factor.names[k]] levels(x)[levels(x) == "NA"] <- NA x })) } } dat }
svc <- paws::organizations()
dMSGHD <- function(data,p,mu=rep(0,p),alpha=rep(0,p),sigma=diag(p),omegav=rep(1,p),lambdav=rep(0.5,p),gam=NULL,phi=NULL,log=FALSE) { if(!is.matrix(data))data=matrix(data,length(data)/p,p) y=data if(is.null(gam)){gam=eigen(sigma)$vectors phi=eigen(sigma)$values }else if(is.null(phi)){cat("phi cannot be NULL")} x = y %*% (gam) alpha = alpha%*%gam mu =mu%*%gam d = p; chi = omegav; psi = omegav; lambda = lambdav; xmu = sweep(x,2,mu,"-") pa = psi + alpha^2/phi mx = sweep(sweep(xmu^2,2,1/phi, FUN="*"), 2,chi, "+") kx = sqrt(sweep(mx, 2, pa, "*")) lx1 = sweep( sweep(log(mx),2,log(pa),"-"), 2, (lambda - 1/2)/2, "*") lx2 = t(apply(kx, 1, function(z,lam=NULL) { log(besselK( z, nu=lambda-1/2, expon.scaled =TRUE)) - z }, lam=lambda )) lx3 = sweep(xmu, 2, alpha/phi, FUN="*") lv = matrix(0, nrow=d, ncol=3) lv[,1] = - 1/2*log( phi ) - 1/2*(log(2)+log(pi)) lv[,2] = - (log(besselK( sqrt(chi*psi), nu=lambda, expon.scaled =TRUE)) - sqrt(chi*psi) ) lv[,3] = lambda/2*(log(psi)-log(chi) ) if(ncol(y)==1){lx2=t(lx2)} val = apply(lx1 + lx2 + lx3, 1, sum) + sum(lv) if (!log) val = exp( val ) return(val) } dCGHD <- function(data,p,mu=rep(0,p),alpha=rep(0,p),sigma=diag(p),lambda=1,omega=1,omegav=rep(1,p),lambdav=rep(1,p),wg=0.5,gam=NULL,phi=NULL) { if(!is.matrix(data))data=matrix(data,length(data)/p,p) wg=c(wg,1-wg) if (wg[2] != 0 & wg[1]!=0) { val1 = dGHD(data,p,mu,alpha,sigma,omega,lambda) val2= dMSGHD(data,p,mu,alpha,sigma,omegav,lambdav,gam,phi) val = wg[1]*(val1) + wg[2]*(val2) } else if(wg[1]==1) {val = dGHD(data,p,mu,alpha,sigma,omega,lambda)} else{val= dMSGHD(data,p,mu,alpha,sigma,omegav,lambdav,gam,phi)} return( val ) } dGHD <- function(data, p, mu=rep(0,p),alpha=rep(0,p),sigma=diag(p),omega=1,lambda=0.5, log=FALSE) { if(!is.matrix(data))data=matrix(data,length(data)/p,p) x=data if (length(mu) != length(alpha) ) stop("mu and alpha do not have the same length") d = length(mu) omega = exp(log(omega)) invS = ginv(sigma) pa = omega + alpha %*% invS %*% alpha mx = omega + mahalanobis(x, center=mu, cov=invS, inverted=TRUE) pa2=rep(pa,length(mx)) kx = sqrt(mx*pa2) xmu = sweep(x,2,mu) lvx = matrix(0, nrow=nrow(x), 4) lvx[,1] = (lambda - d/2)*log(kx) lvx[,2] = log(besselK( kx, nu=lambda-d/2, expon.scaled =TRUE)) - kx lvx[,3] = xmu %*% invS %*% alpha lv = numeric(6) if(is.nan(log(det( sigma )))){sigma =diag(ncol(mu))} lv[1] = -1/2*log(det( sigma )) -d/2*(log(2)+log(pi)) lv[2] = omega - log(besselK( omega, nu=lambda, expon.scaled =TRUE)) lv[3] = -lambda/2*( log(1) ) lv[4] = lambda*log(omega) *0 lv[5] = (d/2 - lambda)*log( pa ) val = apply(lvx,1,sum) + sum(lv) if (!log) val = exp( val ) return(val) }
slide.nodes.internal <- function(tree, nodes, slide) { parent_edge <- which(tree$edge[,2] %in% nodes) descendant_edge <- which(tree$edge[,1] %in% nodes) if(length(parent_edge) != 0) { tree$edge.length[parent_edge] <- tree$edge.length[parent_edge] + slide if(any(tree$edge.length[parent_edge] < 0)) { return(NULL) } } tree$edge.length[descendant_edge] <- tree$edge.length[descendant_edge] - slide if(any(tree$edge.length[descendant_edge] < 0)) { return(NULL) } return(tree) }
get_time_range <- function(tms) { time_range <- 0 for(tm in tms){ time_range <- max(max(tm[,1]) - min(tm[,1]),time_range) } return(time_range) } get_freq_del <- function(tms) { time_range <- get_time_range(tms) return(.1/time_range) } get_freqs <- function(period_min=1,period_max=100,freq_del=.1/4000) { freq_max <- 1 / period_min freq_min <- 1 / period_max return(2*pi*seq(freq_min,freq_max,freq_del)) }
CreateProjectFolders <- function(ProjectName = input$ID_NewProjectName, RootPath = input$ID_Root_Folder, ExistsButNoProjectList = FALSE, Local = FALSE) { RootPath <- gsub("\\\\", "/", RootPath) RootPath <- tryCatch({normalizePath(RootPath, mustWork = TRUE)}, error = function(x) NULL) if(!is.null(RootPath)) { ProjectList <- list() ProjectList[["ProjectName"]] <- ProjectName if(Local) { ProjectPath <- file.path(normalizePath(RootPath), ProjectName) } else { ProjectPath <- paste0("./",ProjectName) } ProjectList[["ProjectFolderPath"]] <- ProjectPath if(!ExistsButNoProjectList) { DataPath <- normalizePath(file.path(ProjectPath, "Data"), mustWork = FALSE) dir.create(path = DataPath, showWarnings = TRUE, recursive = TRUE) ProjectList[["DataFolderPath"]] <- DataPath ModelsPath <- normalizePath(file.path(ProjectPath, "Models"), mustWork = FALSE) dir.create(path = ModelsPath, showWarnings = TRUE, recursive = TRUE) ProjectList[["ModelsFolderPath"]] <- ModelsPath MetaDataPath <- normalizePath(file.path(ProjectPath, "MetaData"), mustWork = FALSE) dir.create(path = MetaDataPath, showWarnings = TRUE, recursive = TRUE) ProjectList[["MetaDataPath"]] <- MetaDataPath save(ProjectList, file = file.path(MetaDataPath, "ProjectList.Rdata")) } else { DataPath <- normalizePath(file.path(ProjectPath,"Data"), mustWork = FALSE) ProjectList[["DataFolderPath"]] <- DataPath ModelsPath <- normalizePath(file.path(ProjectPath,"Models"), mustWork = FALSE) ProjectList[["ModelsFolderPath"]] <- ModelsPath MetaDataPath <- normalizePath(file.path(ProjectPath,"MetaData"), mustWork = FALSE) ProjectList[["MetaDataPath"]] <- MetaDataPath save(ProjectList, file = file.path(MetaDataPath,paste0(ProjectName,"_ProjectList.Rdata"))) } return(ProjectList) } else { return(NULL) } } DownloadCSVFromStorageExplorer <- function(UploadCSVObjectName = 'data.csv', SaveCSVFilePath = file.path(Root), SaveCSVName = "RawData.csv", UploadLocation = 'Analytics Sandbox/Machine Learning', DataStoreName = NULL) { if(!"azuremlsdk" %chin% installed.packages()) stop("You need to run install.packages('azuremlsdk')") options(warn = -1) ws <- azuremlsdk::load_workspace_from_config() ds <- azuremlsdk::get_datastore(ws, DataStoreName) dset <- azuremlsdk::create_tabular_dataset_from_delimited_files( path = ds$path(file.path(UploadLocation, UploadCSVObjectName)), validate = TRUE, include_path = FALSE, infer_column_types = TRUE, set_column_types = NULL, separator = ",", header = TRUE, partition_format = NULL) data <- dset$to_pandas_dataframe() data <- data.table::as.data.table(data) data.table::fwrite(data, file = file.path(SaveCSVFilePath, SaveCSVName)) options(warn = 0) }
context("LapplyGetModule") test_that("LapplyGetModule works correctly", { a <- list(module = "UKAir", paras = list()) b <- list(module = "UKAir", paras = list()) c <- LapplyGetModule(list(a, b), forceReproducible = FALSE) expect_is(c, "list") expect_equal(names(c[[1]]), c("module", "paras", "func", "version")) expect_equal(names(c[[2]]), c("module", "paras", "func", "version")) expect_equal(c[[1]]$module, "UKAir") expect_equal(c[[2]]$module, "UKAir") expect_equal(c[[1]]$paras, list()) expect_equal(c[[2]]$paras, list()) expect_equal(c[[1]]$func, "UKAir") expect_equal(c[[2]]$func, "UKAir") d <- list(module = "UKAir", paras = list(a = 2, b = "a")) e <- LapplyGetModule(list(a, d), forceReproducible = FALSE) expect_is(e, "list") expect_equal(names(e[[2]]), c("module", "paras", "func", "version")) expect_equal(e[[2]]$module, "UKAir") expect_equal(e[[2]]$paras, list(a = 2, b = "a")) expect_equal(e[[2]]$func, "UKAir") expect_true(exists("UKAir")) })
set.seed(1) nobs <- 50; nvars <- 10 x <- matrix(rnorm(nobs * nvars), nrow = nobs) y <- rowSums(x[, 1:2]) + rnorm(nobs) biny <- ifelse(y > 0, 1, 0) foldid <- sample(rep(seq(5), length = nobs)) weights <- rep(1:2, length.out = nobs) test_that("foldid need not be 1:nfolds", { cv_fit1 <- kfoldcv(x, y, train_fun = glmnet, predict_fun = predict, foldid = foldid, keep = TRUE) cv_fit2 <- kfoldcv(x, y, train_fun = glmnet, predict_fun = predict, foldid = -foldid * 2, keep = TRUE) compare_glmnet_fits(cv_fit1, cv_fit2) }) test_that("foldid need not be 1:nfolds, auc", { cv_fit1 <- kfoldcv(x, biny, type.measure = "auc", family = "binomial", train_fun = glmnet, predict_fun = predict, train_params = list(family = "binomial"), predict_params = list(type = "response"), foldid = foldid, keep = TRUE) cv_fit2 <- kfoldcv(x, biny, type.measure = "auc", family = "binomial", train_fun = glmnet, predict_fun = predict, train_params = list(family = "binomial"), predict_params = list(type = "response"), foldid = -foldid * 2, keep = TRUE) compare_glmnet_fits(cv_fit1, cv_fit2) }) test_that("invalid type.measure", { expect_error(kfoldcv(x, y, train_fun = glmnet, predict_fun = predict, type.measure = "class")) }) test_that("family mismatch", { expect_warning(kfoldcv(x, biny, train_fun = glmnet, predict_fun = predict, type.measure = "deviance", train_params = list(family = "binomial"))) }) test_that("parallel", { cl <- parallel::makeCluster(2) doParallel::registerDoParallel(cl) cv_fit1 <- kfoldcv(x, y, train_fun = glmnet, predict_fun = predict, train_params = list(weights = weights), train_row_params = c("weights"), foldid = foldid, keep = TRUE) cv_fit2 <- kfoldcv(x, y, train_fun = glmnet, predict_fun = predict, train_params = list(weights = weights), train_row_params = c("weights"), foldid = foldid, keep = TRUE, parallel = TRUE) parallel::stopCluster(cl) compare_glmnet_fits(cv_fit1, cv_fit2) })
isBIG5 <- function(string, combine = FALSE) { string <- .verifyChar(string) if (length(string) == 1) { OUT <- .C("CWrapper_encoding_isbig5", characters = as.character(string), numres = 2L) OUT <- as.logical(OUT$numres) } else { if (combine) { OUT <- isBIG5(paste(string, collapse = "")) } else { OUT <- as.vector(sapply(string, isBIG5)) } } return(OUT) }
if (!require("HiTC", quietly = TRUE)) { knitr::opts_chunk$set(eval = FALSE) } library("adjclust") load(system.file("extdata", "hic_imr90_40_XX.rda", package = "adjclust")) HiTC::mapC(hic_imr90_40_XX) fit <- hicClust(hic_imr90_40_XX) binned <- HiTC::binningC(hic_imr90_40_XX, binsize = 1e5) HiTC::mapC(binned) fitB <- hicClust(binned) fitB plot(fitB, mode = "corrected") head(cbind(fitB$merge, fitB$gains)) sessionInfo()
context("MODIStsp Test 8: Exit gracefully on missing internet connection") test_that( "Tests on MODIStsp", { skip_on_cran() expect_message( httptest::without_internet(MODIStsp(test = 5, n_retries = 1)), "Error: http server seems to be down!" ) } )
complete.dtplyr_step <- function(data, ..., fill = list()) { dots <- enquos(...) dots <- dots[!map_lgl(dots, quo_is_null)] if (length(dots) == 0) { return(data) } full <- tidyr::expand(data, !!!dots) full <- dplyr::full_join(full, data, by = full$vars) full <- tidyr::replace_na(full, replace = fill) full } complete.data.table <- function(data, ..., fill = list()) { data <- lazy_dt(data) tidyr::complete(data, ..., fill = fill) }
print.surv_variable_response_explainer <- function(x, ...){ class(x) <- "data.frame" print(head(x, ...)) }
test_that("and doesn't change anything with a single predicate", { and(is.integer)(1L) |> expect_equal(is.integer(1L)) and(is.character)(1L) |> expect_equal(is.character(1L)) }) test_that("and returns a function that returns FALSE if any are FALSE", { and(\(a) FALSE, \(a) TRUE)(1) |> expect_false() and(\(a) TRUE, \(a) FALSE)(1) |> expect_false() and(\(a) FALSE, \(a) FALSE)(1) |> expect_false() }) test_that("and returns a function that returns TRUE if all are TRUE", { and(\(a) TRUE)(1) |> expect_true() and(\(a) TRUE, \(a) TRUE)(1) |> expect_true() })
bct_regression <- function( formula, data, weights=NULL, beta_init=NULL, beta_prior=NULL, df=Inf, lambda_fixed=NULL, est_df=FALSE, use_grad=2, h=1E-5, optimizer="optim", maxiter=300, control=NULL ) { CALL <- match.call() type <- "bct" res <- mdmb_regression( formula=formula, data=data, type=type, weights=weights, beta_init=beta_init, beta_prior=beta_prior, df=df, lambda_fixed=lambda_fixed, est_df=est_df, use_grad=use_grad, h=h, optimizer=optimizer, maxiter=maxiter, control=control ) res$CALL <- CALL class(res) <- 'bct_regression' return(res) }
apply_mask_clima <- function(variable, mask_file_final, climatology_file, temp_dir, country_code, climate_year_start, climate_year_end, accumulate) { acc_string <- "" if (accumulate) { acc_string <- "accumulated_" } outfile <- add_ncdf_ext( construct_filename( variable, "climatology", paste0(climate_year_start, "-", climate_year_end), paste0(acc_string, country_code), "mask" ) ) outfile <- file.path(temp_dir, outfile) if (file.exists(mask_file_final)) { tryCatch({ cmsafops::cmsaf.add( var1 = variable, var2 = get_country_name(country_code), infile1 = climatology_file, infile2 = mask_file_final, outfile = outfile, overwrite = TRUE )}, error = function(cond) { stop(paste0("An error occured while applying final mask file to climatology file.")) }) return(outfile) } else { stop(paste("Applying mask file to climatology file failed: final mask file: ", mask_file_final, " does not exist!")) } }
sits_show_prediction <- function(class) { .check_set_caller("sits_show_prediction") .sits_tibble_test(class) .check_chr_within( x = .config_get("ts_predicted_cols"), within = names(class$predicted[[1]]), msg = "tibble has not been classified" ) return(dplyr::select( dplyr::bind_rows(class$predicted), c("from", "to", "class") )) } .sits_tibble_prediction <- function(data, class_info, prediction) { ref_dates_lst <- class_info$ref_dates[[1]] timeline_global <- class_info$timeline[[1]] labels <- class_info$labels[[1]] n_labels <- length(labels) int_labels <- c(1:n_labels) names(int_labels) <- labels pred <- names(int_labels[max.col(prediction)]) idx <- 1 data_pred <- slider::slide_dfr(data, function(row) { timeline_row <- lubridate::as_date(row$time_series[[1]]$Index) if (timeline_row[1] != timeline_global[1]) { ref_dates_lst <- .sits_timeline_match( timeline = timeline_row, ref_start_date = lubridate::as_date(row$start_date), ref_end_date = lubridate::as_date(row$end_date), num_samples = nrow(row$time_series[[1]]) ) } pred_sample <- ref_dates_lst %>% purrr::map_dfr(function(rd) { probs_date <- rbind.data.frame(prediction[idx,]) names(probs_date) <- names(prediction[idx,]) pred_date <- tibble::tibble( from = as.Date(rd[1]), to = as.Date(rd[2]), class = pred[idx] ) idx <<- idx + 1 pred_date <- dplyr::bind_cols(pred_date, probs_date) }) row$predicted <- list(pred_sample) return(row) } ) return(data_pred) }
makeCRM <-function(acf0 = 1, range = NA, model, anis, kappa = 0.5, add.to, covtable, Err = 0) { stopifnot(class(acf0) == "numeric") stopifnot(class(range) == "numeric" | is.na(range)) if (acf0 < 0 | acf0 > 1) warning("For standardized residuals acf0 argument should be between 0 and 1.") if (missing(anis)) anis <- c(0, 0, 0, 1, 1) if (length(anis) == 2) anis <- c(anis[1], 0, 0, anis[2], 1) else if (length(anis) != 5) stop("anis vector should have length 2 (2D) or 5 (3D)") models <- gstat::vgm()$short if (model %in% models == FALSE) stop("Only models accepted by gstat::vgm are allowed.") if (!is.na(range)) { if (model != "Nug") { if (model != "Lin" && model != "Err" && model != "Int") if (range <= 0) stop("range should be positive") else if (range < 0) stop("range should be non-negative") } else { if (range != 0) stop("Nugget should have zero range") if (anis[4] != 1 || anis[5] != 1) stop("Nugget anisotropy is not meaningful") } } crm <- list(acf0 = acf0, range = range, model = model, anis = anis, kappa = kappa, Err = Err) class(crm) <- c("SpatialCorrelogramModel") crm } makecrm <-function(acf0 = 1, range = NA, model, anis, kappa = 0.5, add.to, covtable, Err = 0) { stopifnot(class(acf0) == "numeric") stopifnot(class(range) == "numeric" | is.na(range)) if (acf0 < 0 | acf0 > 1) warning("For standardized residuals acf0 argument should be between 0 and 1.") if (missing(anis)) anis <- c(0, 0, 0, 1, 1) if (length(anis) == 2) anis <- c(anis[1], 0, 0, anis[2], 1) else if (length(anis) != 5) stop("anis vector should have length 2 (2D) or 5 (3D)") models <- gstat::vgm()$short if (model %in% models == FALSE) stop("Only models accepted by gstat::vgm are allowed.") if (!is.na(range)) { if (model != "Nug") { if (model != "Lin" && model != "Err" && model != "Int") if (range <= 0) stop("range should be positive") else if (range < 0) stop("range should be non-negative") } else { if (range != 0) stop("Nugget should have zero range") if (anis[4] != 1 || anis[5] != 1) stop("Nugget anisotropy is not meaningful") } } crm <- list(acf0 = acf0, range = range, model = model, anis = anis, kappa = kappa, Err = Err) class(crm) <- c("SpatialCorrelogramModel") crm } makecrm <- function(acf0 = 1, range = NA, model, anis, kappa = 0.5, add.to, covtable, Err = 0) { .Deprecated(new = "makeCRM") makeCRM(acf0, range, model, anis, kappa, add.to, covtable, Err) }
extract_key_expressions <- function(text, handle = "i18n") { found <- unlist(str_extract_all(text, glue::glue("{handle}\\$t\\((.*?)\\)"))) ke1 <- str_replace(str_replace(found, glue::glue("{handle}\\$t\\([\"']"), ""), "[\"']\\)", "") found <- unlist(str_extract_all(text, glue::glue("{handle}\\$translate\\((.*?)\\)"))) ke2 <- str_replace(str_replace(found, glue::glue("{handle}\\$translate\\([\"']"), ""), "[\"']\\)", "") key_expressions <- c(ke1, ke2) key_expressions } save_to_json <- function(key_expressions, output_path = NULL) { list_to_save <- list( translation = lapply(key_expressions, function(x) list(key = unbox(x))), languages = "key") json_to_save <- toJSON(list_to_save) if (is.null(output_path)) output_path <- "translation.json" write_json(list_to_save, output_path) } save_to_csv <- function(key_expressions, output_path = NULL) { df_to_save <- data.frame( list(key = key_expressions, lang = rep("", length(key_expressions))) ) if (is.null(output_path)) output_path <- "translate_lang.csv" write.csv(df_to_save, output_path, row.names = FALSE) } create_translation_file <- function(path, type = "json", handle = "i18n", output = NULL) { file_source <- readLines(con <- file(path)) key_expressions <- extract_key_expressions(file_source, handle) switch(type, json = save_to_json(key_expressions, output), csv = save_to_csv(key_expressions, output), stop("'type' of output not recognized, check docs!") ) } create_translation_addin <- function(){ rstudioapi::showDialog("shiny.i18n", "This extension searches for 'i18n$t' wrappers in your file and creates an example of a translation file for you. For more customized behaviour use 'create_translation_file' function.") path <- rstudioapi::getActiveDocumentContext()$path if (nchar(path) == 0) rstudioapi::showDialog("TODOr","No active document detected.") else{ answ <- rstudioapi::showQuestion("shiny.i18n", "What type of file generate?", "json", "csv") create_translation_file(path, ifelse(answ, "json", "csv")) print("Done (create translation file)!") } }
library(tmap) library(terra) elev = rast(system.file("raster/elev.tif", package = "spData")) grain = rast(system.file("raster/grain.tif", package = "spData")) colfunc2 = c("clay" = "brown", "silt" = "sandybrown", "sand" = "rosybrown") p1 = tm_shape(elev) + tm_raster(legend.show = TRUE, style = "cont", title = "") + tm_layout(outer.margins = rep(0.01, 4), inner.margins = 0) + tm_legend(bg.color = "white") p2 = tm_shape(grain) + tm_raster(legend.show = TRUE, title = "", palette = colfunc2) + tm_layout(outer.margins = rep(0.01, 4), inner.margins = 0) + tm_legend(bg.color = "white") tmap_arrange(p1, p2, nrow = 1)
modus <- function(vector) { if (is.data.frame(vector) | is.matrix(vector)) { stop("The first argument is not a vector! If you need to specify ", "a variable from a dataframe, separate the name of the ", "dataframe and the variable name with a dollar sign, for ", "example using 'dat$gender' to extract variable 'gender' from ", "dataframe 'dat'."); } originalClass <- class(vector); vector <- as.factor(vector); freqs <- summary(vector); highestFreq <- max(freqs); categoryVector <- names(freqs[freqs==highestFreq]); if ("factor" %in% originalClass) { categoryVector <- as.factor(categoryVector); } else { suppressWarnings(class(categoryVector) <- originalClass); } return(categoryVector); }
rmaxstab <- function(n, coord, cov.mod = "gauss", grid = FALSE, control = list(), ...){ if (!(cov.mod %in% c("gauss","whitmat","cauchy","powexp","bessel", "iwhitmat", "icauchy", "ipowexp", "ibessel", "gwhitmat", "gcauchy", "gpowexp", "gbessel", "twhitmat", "tcauchy", "tpowexp", "tbessel", "brown"))) stop("'cov.mod' must be one of 'gauss', '(i/g/t)whitmat', '(i/g/t)cauchy', '(i/g/t)powexp', '(i/g/t)bessel' or 'brown'") if (!is.null(control$method) && !(control$method %in% c("direct", "tbm", "circ", "exact"))) stop("the argument 'method' for 'control' must be one of 'exact', 'direct', 'tbm' and 'circ'") if (cov.mod == "gauss") model <- "Smith" else if (cov.mod == "brown") model <- "Brown-Resnick" else if (cov.mod %in% c("whitmat","cauchy","powexp","bessel")) model <- "Schlather" else { if (substr(cov.mod, 1, 1) == "i") model <- "iSchlather" else if (substr(cov.mod, 1, 1) == "g") model <- "Geometric" else model <- "Extremal-t" cov.mod <- substr(cov.mod, 2, 10) } dist.dim <- ncol(coord) if (is.null(dist.dim)) dist.dim <- 1 if (dist.dim > 2) stop("Currently this function is only available for R or R^2") if ((dist.dim == 1) && grid){ warning("You cannot use 'grid = TRUE' in dimension 1. Ignored.") grid <- FALSE } if (model == "Smith"){ if ((dist.dim == 1) && (!("var" %in% names(list(...))))) stop("For one dimensional simulations, you must specify 'var' not 'cov11', 'cov12', 'cov22'.") if ((dist.dim == 2) && (!all(c("cov11", "cov12", "cov22") %in% names(list(...))))) stop("You must specify 'cov11', 'cov12', 'cov22'") var <- list(...)$var cov11 <- list(...)$cov11 cov12 <- list(...)$cov12 cov22 <- list(...)$cov22 cov13 <- list(...)$cov13 cov23 <- list(...)$cov23 cov33 <- list(...)$cov33 } else if (model == "Schlather"){ if (!all(c("nugget", "range", "smooth") %in% names(list(...)))) stop("You must specify 'nugget', 'range', 'smooth'") nugget <- list(...)$nugget range <- list(...)$range smooth <- list(...)$smooth } else if (model == "iSchlather"){ if (!all(c("alpha", "nugget", "range", "smooth") %in% names(list(...)))) stop("You must specify 'alpha', 'nugget', 'range', 'smooth'") nugget <- list(...)$nugget range <- list(...)$range smooth <- list(...)$smooth alpha <- list(...)$alpha } else if (model == "Geometric") { if (!all(c("sigma2", "nugget", "range", "smooth") %in% names(list(...)))) stop("You must specify 'sigma2', 'nugget', 'range', 'smooth'") nugget <- list(...)$nugget range <- list(...)$range smooth <- list(...)$smooth sigma2 <- list(...)$sigma2 } else if (model == "Extremal-t"){ if (!all(c("DoF", "nugget", "range", "smooth") %in% names(list(...)))) stop("You must specify 'DoF', 'nugget', 'range', 'smooth'") nugget <- list(...)$nugget range <- list(...)$range smooth <- list(...)$smooth DoF <- list(...)$DoF } else if (model == "Brown-Resnick"){ range <- list(...)$range smooth <- list(...)$smooth } if (dist.dim !=1){ n.site <- nrow(coord) coord.range <- apply(coord, 2, range) center <- colMeans(coord.range) edge <- max(apply(coord.range, 2, diff)) } else { n.site <- length(coord) coord.range <- range(coord) center <- mean(coord.range) edge <- diff(coord.range) } cov.mod <- switch(cov.mod, "gauss" = "gauss", "whitmat" = 1, "cauchy" = 2, "powexp" = 3, "bessel" = 4) if (grid){ n.eff.site <- n.site^dist.dim reg.grid <- .isregulargrid(coord[,1], coord[,2]) steps <- reg.grid$steps reg.grid <- reg.grid$reg.grid } else n.eff.site <- n.site ans <- rep(-1e10, n * n.eff.site) if (is.null(control$method)){ if (n.eff.site < 1000) method <- "exact" else if (grid && reg.grid) method <- "circ" else if ((length(ans) / n) > 600) method <- "tbm" else method <- "direct" if ((model == "Geometric") && (method == "exact")) method <- "direct" } else method <- control$method if (method == "tbm"){ if (is.null(control$nlines)) nlines <- 1000 else nlines <- control$nlines } if (model == "Smith") ans <- switch(dist.dim, .C(C_rsmith1d, as.double(coord), as.double(center), as.double(edge), as.integer(n), as.integer(n.site), as.double(var), ans = ans)$ans, .C(C_rsmith2d, as.double(coord), as.double(center), as.double(edge), as.integer(n), as.integer(n.site), grid, as.double(cov11), as.double(cov12), as.double(cov22), ans = ans)$ans) else if (model == "Schlather"){ if (is.null(control$uBound)) uBound <- 3.5 else uBound <- control$uBound if (method == "direct") ans <- .C(C_rschlatherdirect, as.double(coord), as.integer(n), as.integer(n.site), as.integer(dist.dim), as.integer(cov.mod), grid, as.double(nugget), as.double(range), as.double(smooth), as.double(uBound), ans = ans)$ans else if (method == "exact") ans <- .C(C_rschlatherexact, as.double(coord), as.integer(n), as.integer(n.site), as.integer(dist.dim), as.integer(cov.mod), as.integer(grid), as.double(nugget), as.double(range), as.double(smooth), ans = ans)$ans else if (method == "circ") ans <- .C(C_rschlathercirc, as.integer(n), as.integer(n.site), as.double(steps), as.integer(dist.dim), as.integer(cov.mod), as.double(nugget), as.double(range), as.double(smooth), as.double(uBound), ans = ans)$ans else ans <- .C(C_rschlathertbm, as.double(coord), as.integer(n), as.integer(n.site), as.integer(dist.dim), as.integer(cov.mod), grid, as.double(nugget), as.double(range), as.double(smooth), as.double(uBound), as.integer(nlines), ans = ans)$ans } else if (model == "Geometric"){ if (is.null(control$uBound)) uBound <- exp(3.5 * sqrt(sigma2) - 0.5 * sigma2) else uBound <- control$uBound if (method == "direct") ans <- .C(C_rgeomdirect, as.double(coord), as.integer(n), as.integer(n.site), as.integer(dist.dim), as.integer(cov.mod), grid, as.double(sigma2), as.double(nugget), as.double(range), as.double(smooth), as.double(uBound), ans = ans)$ans else if (method == "circ") ans <- .C(C_rgeomcirc, as.integer(n), as.integer(n.site), as.double(steps), as.integer(dist.dim), as.integer(cov.mod), as.double(sigma2), as.double(nugget), as.double(range), as.double(smooth), as.double(uBound), ans = ans)$ans else ans <- .C(C_rgeomtbm, as.double(coord), as.integer(n), as.integer(n.site), as.integer(dist.dim), as.integer(cov.mod), grid, as.double(sigma2), as.double(nugget), as.double(range), as.double(smooth), as.double(uBound), as.integer(nlines), ans = ans)$ans } else if (model == "Extremal-t"){ if (is.null(control$uBound)) uBound <- 3^DoF else uBound <- control$uBound if (method == "direct") ans <- .C(C_rextremaltdirect, as.double(coord), as.integer(n), as.integer(n.site), as.integer(dist.dim), as.integer(cov.mod), grid, as.double(nugget), as.double(range), as.double(smooth), as.double(DoF), as.double(uBound), ans = ans)$ans else if (method == "exact") ans <- .C(C_rextremaltexact, as.double(coord), as.integer(n), as.integer(n.site), as.integer(dist.dim), as.integer(cov.mod), grid, as.double(nugget), as.double(range), as.double(smooth), as.double(DoF), ans = ans)$ans else if (method == "circ") ans <- .C(C_rextremaltcirc, as.integer(n), as.integer(n.site), as.double(steps), as.integer(dist.dim), as.integer(cov.mod), as.double(nugget), as.double(range), as.double(smooth), as.double(DoF), as.double(uBound), ans = ans)$ans else ans <- .C(C_rextremalttbm, as.double(coord), as.integer(n), as.integer(n.site), as.integer(dist.dim), as.integer(cov.mod), grid, as.double(nugget), as.double(range), as.double(smooth), as.double(DoF), as.double(uBound), as.integer(nlines), ans = ans)$ans } else if (model == "Brown-Resnick"){ coord <- scale(coord, scale = FALSE) + 10^-6 if (is.null(control$max.sim)) max.sim <- 1000 else max.sim <- control$max.sim if (is.null(control$uBound)) uBound <- 10 else uBound <- control$uBound if (is.null(control$sim.type)) sim.type <- 1 else sim.type <- control$sim.type if (dist.dim == 1) bounds <- range(coord) else bounds <- apply(coord, 2, range) if (is.null(control$nPP)) nPP <- 15 else nPP <- control$nPP if (sim.type == 6){ idx.sub.orig <- getsubregions(coord, bounds, range, smooth, dist.dim) n.sub.orig <- length(idx.sub.orig) } else idx.sub.orig <- n.sub.orig <- 0 if (method == "direct") ans <- .C(C_rbrowndirect, as.double(coord), as.double(bounds), as.integer(n), as.integer(n.site), as.integer(dist.dim), as.integer(grid), as.double(range), as.double(smooth), as.double(uBound), as.integer(sim.type), as.integer(max.sim), as.integer(nPP), as.integer(idx.sub.orig), as.integer(n.sub.orig), ans = ans)$ans else if (method == "exact") ans <- .C(C_rbrownexact, as.double(coord), as.integer(n), as.integer(n.site), as.integer(dist.dim), as.integer(grid), as.double(range), as.double(smooth), ans = ans)$ans } if (grid){ if (n == 1) ans <- matrix(ans, n.site, n.site) else ans <- array(ans, c(n.site, n.site, n)) } else ans <- matrix(ans, nrow = n, ncol = n.site) return(ans) } getsubregions <- function(coord, bounds, range, smooth, dist.dim){ if (dist.dim == 1){ coord <- matrix(coord, ncol = 1) bounds <- matrix(bounds, ncol = 1) } h.star <- 2^(1/smooth) * range n.windows <- 1 + floor(diff(bounds) / h.star) sub.bounds <- list() for (i in 1:dist.dim) sub.bounds <- c(sub.bounds, list(seq(bounds[1,i], bounds[2, i], length = n.windows[i] + 1))) sub.centers <- list() for (i in 1:dist.dim) sub.centers <- c(sub.centers, list(0.5 * (sub.bounds[[i]][-1] + sub.bounds[[i]][-(n.windows + 1)]))) sub.origins <- as.matrix(expand.grid(sub.centers)) n.sub.origins <- prod(n.windows) idx.sub.orig <- rep(NA, n.sub.origins) for (i in 1:n.sub.origins){ dummy <- sqrt(colSums((t(coord) - sub.origins[i,])^2)) idx.sub.orig[i] <- which.min(dummy) } return(idx.sub.orig = idx.sub.orig) }
MIFAMD <- function(X, ncp = 2, method = c("Regularized","EM"), coeff.ridge = 1, threshold = 1e-06, seed = NULL, maxiter = 1000, nboot=20, verbose=T ){ estim.sigma2<-function(Xquanti,Xquali,M,Zhat,ncp,WW,D){ tab.disjonctif.NA <- function(tab) { if(ncol(tab)==0){return(NULL)} tab <- as.data.frame(tab) modalite.disjonctif <- function(i) { moda <- tab[, i] nom <- names(tab)[i] n <- length(moda) moda <- as.factor(moda) x <- matrix(0, n, length(levels(moda))) ind <- (1:n) + n * (unclass(moda) - 1) indNA <- which(is.na(ind)) x[(1:n) + n * (unclass(moda) - 1)] <- 1 x[indNA, ] <- NA if ((ncol(tab) != 1) & (levels(moda)[1] %in% c(1:nlevels(moda), "n", "N", "y", "Y"))) dimnames(x) <- list(row.names(tab), paste(nom, levels(moda), sep = ".")) else dimnames(x) <- list(row.names(tab), levels(moda)) return(x) } if (ncol(tab) == 1) res <- modalite.disjonctif(1) else { res <- lapply(1:ncol(tab), modalite.disjonctif) res <- as.matrix(data.frame(res, check.names = FALSE)) } return(res) } reconst.FAMD<-function(xxquanti,xxquali,M=NULL,D=NULL,ncp,coeff.ridge=1,method="em"){ zz<-cbind.data.frame(xxquanti,xxquali) if(is.null(M)){M<-c(1/apply(xxquanti,2,var),colMeans(zz)[-c(1:ncol(xxquanti))])} if(is.null(D)){D<-rep(1/nrow(zz),nrow(zz))} moy<-colMeans(zz) zzimp<-sweep(zz,MARGIN = 2,FUN = "-",STATS = moy) res.svd<-svd.triplet(zzimp,col.w = M,row.w = D,ncp=ncp) tmp<-seq(ncol(zz)-ncol(xxquali)) if (nrow(zz) > length(tmp)){ moyeig <- mean(res.svd$vs[tmp[-seq(ncp)]]^2) }else{ moyeig <- mean(res.svd$vs[-c(1:ncp)]^2) } moyeig <- min(moyeig * coeff.ridge, res.svd$vs[ncp +1]^2) moyeigret<-moyeig if (method == "em"){ moyeig <- 0 } if(ncp>1){ eig.shrunk <- (res.svd$vs[1:ncp]^2 - moyeig)/res.svd$vs[1:ncp] }else if(ncp==1){ eig.shrunk <- matrix((res.svd$vs[1:ncp]^2 - moyeig)/res.svd$vs[1:ncp],1,1) } zzhat<-tcrossprod(res.svd$U%*%diag(eig.shrunk),res.svd$V[which(apply(is.finite(res.svd$V),1,any)),,drop=FALSE]) zzhat<-sweep(zzhat,MARGIN = 2,FUN = "+",STATS = moy) return(list(zzhat=zzhat,moyeig=moyeigret,res.svd=res.svd,M=M)) } nb.obs<-sum(WW[,-cumsum(sapply(Xquali,nlevels))]) nb.obs.quanti<-sum(WW[,seq(ncol(Xquanti))]) Zhat2<-reconst.FAMD(Zhat[,seq(ncol(Xquanti))],Zhat[,-seq(ncol(Xquanti))],ncp=ncp,D = D,M=M) Residu<-(Zhat-Zhat2$zzhat)%*%diag(M)^{1/2} Residu[is.na(cbind.data.frame(Xquanti,tab.disjonctif.NA(Xquali)))]<-0 sigma2<-sum(WW[,seq(ncol(Xquanti))]*((Residu[,seq(ncol(Xquanti))])^2))/(nb.obs.quanti-(ncol(Xquanti)+ncp*(sum(D)-1)+ncol(Xquanti)-ncp)) return(sigma2) } imputeFAMD.stoch<-function(don, ncp = 4, method = c("Regularized", "EM"), row.w = NULL, coeff.ridge = 1, threshold = 1e-06, seed = NULL, maxiter = 1000, nboot, verbose=FALSE){ normtdc <- function(tab.disj, data.na) { tdc <- tab.disj tdc[tdc < 0] <- 0 tdc[tdc > 1] <- 1 col.suppr <- cumsum(sapply(data.na, function(x) {nlevels(x)})) tdc <- t(apply(tdc, 1, FUN = function(x, col.suppr) { if (sum(x[1:col.suppr[1]]) != 1) { x[1:col.suppr[1]] <- x[1:col.suppr[1]]/sum(x[1:col.suppr[1]]) } if(length(col.suppr)>1){ for (i in 2:length(col.suppr)) { x[(col.suppr[i - 1] + 1):(col.suppr[i])] <- x[(col.suppr[i - 1] + 1):(col.suppr[i])]/sum(x[(col.suppr[i - 1] + 1):col.suppr[i]]) }} return(x) }, col.suppr = col.suppr)) return(tdc) } draw <- function(tabdisj, Don) { nbdummy <- rep(1, ncol(Don)) is.quali <- which(!sapply(Don, is.numeric)) nbdummy[is.quali] <- sapply(Don[, is.quali, drop = FALSE], nlevels) vec = c(0, cumsum(nbdummy)) Donres <- Don for (i in is.quali) { Donres[, i] <- as.factor(levels(Don[, i])[apply(tabdisj[, (vec[i] + 1):vec[i + 1]], 1, function(x) { sample(1:length(x), size = 1, prob = x) })]) Donres[, i] <- factor(Donres[, i], levels(Don[, is.quali,drop=FALSE][, i])) } return(don.imp = Donres) } quanti<-which(sapply(don,is.numeric)) Ncol<-length(quanti)+sum(sapply(don[,-quanti],nlevels)) W<-matrix(0,nrow(don),Ncol);W[!is.na(don)]<-1 if(is.null(row.w)){ Row.w<-as.integer(rep(1,nrow(don))) }else{ Row.w<-row.w } if(is.integer(Row.w)){ D<-Row.w/sum(Row.w) D[which(Row.w==0)]<-1/(1000*nrow(don)) WW<-diag(Row.w)%*%W }else{ stop(paste0("row.w of class ",class(Row.w),", it needs to be an integer")) } res.imp<-imputeFAMD(X=don, ncp = ncp, method = method, row.w = D, coeff.ridge = coeff.ridge, threshold = threshold, seed = seed, maxiter = maxiter) var_homo<-estim.sigma2(Xquanti=don[,quanti,drop=FALSE], Xquali=don[,-quanti,drop=FALSE], M=1/apply(res.imp$tab.disj,2,var), Zhat=res.imp$tab.disj, ncp=ncp, D=D,WW=WW) sigma2<-var_homo/(1/apply(res.imp$tab.disj,2,var)[quanti]) res.imp$fittedX<-res.imp$tab.disj res.imp$quanti.act<-which(sapply(don,is.numeric)) classvar<-unlist(lapply(lapply(don,class),"[",1)) if("integer"%in%classvar){classvar[classvar=="integer"]<-"numeric"} if("ordered"%in%classvar){classvar[classvar=="ordered"]<-"factor"} donimp<-don donimp[,which(classvar=="numeric")]<-res.imp$tab.disj[,seq(length(res.imp$quanti.act))] missing.quanti <-is.na(don[,res.imp$quanti.act]) res.MI<-vector("list",length=nboot);names(res.MI)<-paste("nboot=",1:nboot,sep="") for(i in seq(nboot)){ if(verbose){cat(paste(i, "...", sep = ""))} donimp.tmp<-donimp if(any("factor"%in% classvar)){ tdc.imp <- res.imp$tab.disj[,(length(c(res.imp$quanti.act,res.imp$quanti.sup))+1):(ncol(res.imp$tab.disj)-length(res.imp$quali.sup)),drop=FALSE] tdc.norm <- normtdc(tab.disj = tdc.imp, data.na = don[,which(classvar=="factor"),drop=FALSE]) donimp.quali<-draw(tdc.norm,don[,which(classvar=="factor"),drop=FALSE]) donimp.tmp[,which(classvar=="factor")]<-donimp.quali[,names(which(classvar=="factor"))] } donimp.tmp[,res.imp$quanti.act][missing.quanti]<-res.imp$fittedX[,res.imp$quanti.act][missing.quanti]+rmvnorm(nrow(don),sigma=diag(sigma2))[missing.quanti] res.MI[[paste("nboot=",i,sep="")]]<-donimp.tmp } if (verbose) { cat("\ndone!\n") } res.MI<-list(res.MI=res.MI,sigma2=sigma2) class(res.MI)<-"MIFAMD" return(res.MI) } imputeFAMD.stoch.print <- function(don, ncp, method = c("Regularized", "EM"), row.w = NULL, coeff.ridge = 1, threshold = 1e-06, seed = NULL, maxiter = 1000, verbose, printm) { if (verbose) { cat(paste(printm, "...", sep = "")) } res <- imputeFAMD.stoch(don = don, ncp = ncp, method = method, row.w = row.w, coeff.ridge = coeff.ridge, threshold = threshold, seed = seed, maxiter = maxiter,nboot=1)$res.MI[[1]] return(res) } if(sum(sapply(X,is.numeric))==ncol(X)){stop("All variables are numeric, use MIPCA") }else if(sum(sapply(X,is.numeric))==0){stop("No variable is numeric, use MIMCA")} don<-X[,c(which(sapply(X,is.numeric)),which(!sapply(X,is.numeric)))] temp <- if (coeff.ridge == 1) { "regularized" } else if ((coeff.ridge == 0) |(method=="EM")) { "EM" }else { paste("coeff.ridge=", coeff.ridge) } if (verbose) { cat("Multiple Imputation using", temp, "FAMD using", nboot, "imputed arrays", "\n") } n <- nrow(don) Boot <- matrix(sample(1:n, size = nboot * n, replace = T), n, nboot) Boot<-lapply(as.data.frame(Boot),FUN=function(xx){ yy<-as.factor(xx) levels(yy)<-c(levels(yy),xx[which(!xx%in%as.numeric(as.character(levels(yy))))]) return(yy)}) Weight <- as.data.frame(matrix(0, n, nboot, dimnames = list(1:n,paste("nboot=", 1:nboot, sep = "")))) Boot.table <- lapply(Boot, table) for (i in 1:nboot) { Weight[names(Boot.table[[i]]), i] <- Boot.table[[i]] } Weight <-do.call(cbind.data.frame,lapply(Weight,as.integer)) res.imp <- mapply(Weight, FUN = imputeFAMD.stoch.print, MoreArgs = list(don = don,ncp = ncp, coeff.ridge = coeff.ridge, method =method, threshold = threshold, maxiter = maxiter, verbose=verbose, seed=NULL),printm = as.character(1:nboot), SIMPLIFY = FALSE) res <- list(res.MI = res.imp) res <- list(res.MI = lapply(res$res.MI,function(xx,nom){return(xx[,nom])},nom=colnames(X)), res.imputeFAMD = imputeFAMD(X,ncp = ncp, coeff.ridge = coeff.ridge, method =method, threshold = threshold, maxiter = maxiter,seed=seed), call=list(X = X,nboot = nboot, ncp = ncp, coeff.ridge = coeff.ridge, threshold = threshold, seed = seed, maxiter = maxiter)) class(res) <- c("MIFAMD", "list") if (verbose) { cat("\ndone!\n") } return(res) }
binaryChecks <- function(x, method){ if(length(unique(x)) > 2){ stop(paste(method, "only works for binary outcomes at this time")) } }
mychisq.test=function(x){ result=tryCatch(chisq.test(x),warning=function(w) return("warnings present")) if(class(result)!="htest"){ result1=tryCatch(fisher.test(x), error=function(e) return("error present"), warning=function(w) return("warning present"), message = function(c) "message") if(class(result1)=="htest") result<-result1 } result } extractLabels=function(x){ result=NULL if(!is.null(names(attr(x,"labels")))) result=names(attr(x,"labels")) if(!is.null(names(attr(x,"value.labels")))) result=names(attr(x,"value.labels")) result } x2result=function(x){ warning=0 (result=mychisq.test(x)) (result1=chisq.test(x)) if(class(result)!="htest") { result=result1 warning=1 } cramer=vcd::assocstats(x)$cramer statresult=paste0("Chi-squared=",round(result1$statistic,3),", df=",result1$parameter) statresult=paste0(statresult,", Cramer\'s V=",round(cramer,3)) if(substr(result$method,1,6)=="Fisher") { statresult=paste0(statresult,", Fisher's p") } else { statresult=paste0(statresult,", Chi-squared p") } pvalue=ifelse(result$p.value>=0.001,paste0("=",round(result$p.value,4)),"< 0.001") statresult=paste0(statresult,pvalue) if(warning==1) statresult=paste0(statresult,"; approximation may be incorrect") statresult } x2summary=function(data=NULL,x=NULL,y=NULL,a,b,margin=1,show.percent=TRUE,show.label=TRUE){ if(!is.null(data)){ x=substitute(x) y=as.character(substitute(y)) a=data[[x]] b=data[[y]] } x=table(a,b) labela=sjlabelled::get_label(a) labelb=sjlabelled::get_label(b) ncolb=ncol(x) x=addmargins(x,margin) x x1=scales::percent(round(t(apply(x,margin,function(a) a/sum(a))),3)) if(margin==2) x1=matrix(x1,nrow=nrow(x),byrow=TRUE) if(show.percent) { x3=paste0(x,"\n(",x1,")") } else{ x3<-x } if(margin==1){ x2=matrix(x3,ncol=ncol(x)) rowcol=rowSums(x) if(show.percent) rowcol=paste0(rowcol,"\n(100 %)") x2=cbind(x2,Total=rowcol) } else{ x2=matrix(x3,nrow=nrow(x)) colrow=colSums(x) if(show.percent) colrow=paste0(colrow,"\n(100 %)") x2=rbind(x2,Total=colrow) } x2 x colnames(x) labels=extractLabels(b) labels if(!is.null(labels)) { colnames(x) if(length(colnames(x))==length(labels)+1) { colnames(x)=c(labels,"total") } else{ if(margin==2){ for(i in 1:(length(colnames(x))-1)){ colnames(x)[i]=labels[as.numeric(colnames(x)[i])] } } else{ for(i in 1:(length(colnames(x)))){ colnames(x)[i]=labels[as.numeric(colnames(x)[i])] } } } } if(is.null(labels)) { if(margin==1) { colnames(x2)=c(colnames(x),"Total") } else{ colnames(x2)=c(colnames(x)[1:(ncol(x)-1)],"Total") } } else if(ncol(x2)==length(labels)+1){ colnames(x2)=c(labels,"Total") } else{ if(margin==1) { colnames(x2)=c(colnames(x),"Total") } else{ colnames(x2)=c(colnames(x)[1:(ncol(x)-1)],"Total") } } x2 labels=extractLabels(a) rownames(x2) nrow(x2) rownames(x) if(!is.null(labels)) { colnames(x) if(length(rownames(x))==length(labels)+1) { rownames(x)=c(labels,"total") } else{ if(margin==1){ for(i in 1:(length(rownames(x))-1)){ rownames(x)[i]=labels[as.numeric(rownames(x)[i])] } } else{ for(i in 1:(length(colnames(x)))){ rownames(x)[i]=labels[as.numeric(rownames(x)[i])] } } } } if(is.null(labels)) { if(margin==2){ rownames(x2)=c(rownames(x),"Total") } else{ rownames(x2)=c(rownames(x)[1:(nrow(x)-1)],"Total") } } else if(nrow(x2)==length(labels)+1){ rownames(x2)=c(labels,"Total") } else{ if(margin==2) { rownames(x2)=c(rownames(x),"Total") } else{ rownames(x2)=c(rownames(x)[1:(nrow(x)-1)],"Total") } } x2 as.data.frame(x2) } x2Table=function(data,x,y,margin=1,show.percent=TRUE,show.label=TRUE, show.stat=TRUE,vanilla=FALSE,fontsize=12,...){ x=substitute(x) y=as.character(substitute(y)) a=data[[x]] b=data[[y]] x2=x2summary(a=a,b=b,margin=margin,show.percent=show.percent,show.label=show.label) MyTable=rrtable::df2flextable(x2,add.rownames = TRUE,vanilla=vanilla,fontsize=fontsize,digits=0,...) %>% flextable::align(j=1,align='center',part='body') %>% flextable::align(i=1,align='center',part='header') if(show.stat){ x=table(a,b) statresult=x2result(x) MyTable<- MyTable %>% flextable::add_footer(rowname=statresult) %>% flextable::merge_at(j=1:(ncol(x2)+1),part="footer") %>% flextable::italic(j=1:(ncol(x2)+1),part="footer") %>% flextable::align(align='right',part='footer') %>% flextable::autofit() } color=ifelse(vanilla,"white"," MyTable<- MyTable %>% flextable::color(color=color,i=1,j=1,part='header') MyTable$header$dataset[1]<-y MyTable }
print.prop.comb <- function(x, ...) { summary(x)}