code
stringlengths
1
13.8M
expected <- eval(parse(text="c(\"3\", \"3\", NA, NA, NA, NA, \"4\", \"3\", \"4\", NA, NA, \"2\", \"3\", \"3\", NA, NA, \"2\", \"4\", NA, \"2\", \"5\", \"2\", \"2\", \"4\", \"3\", NA, \"2\", NA, \"3\", \"3\")")); test(id=0, code={ argv <- eval(parse(text="list(c(3, 3, NA, NA, NA, NA, 4, 3, 4, NA, NA, 2, 3, 3, NA, NA, 2, 4, NA, 2, 5, 2, 2, 4, 3, NA, 2, NA, 3, 3))")); do.call(`as.character`, argv); }, o=expected);
test_that("validateIsInteger works as expected", { expect_null(validateIsInteger(5)) expect_null(validateIsInteger(5L)) expect_null(validateIsInteger(c(1L, 5))) expect_null(validateIsInteger(c(1L, 5L))) expect_null(validateIsInteger(NA_integer_)) expect_error(validateIsInteger(c(1.5, 5))) expect_error(validateIsInteger(2.4)) expect_error(validateIsInteger("2")) expect_error(validateIsInteger(TRUE)) expect_error(validateIsInteger(NA_character_)) }) test_that("It accepts an empty string", { expect_error(validatePathIsAbsolute(""), NA) }) test_that("It accepts a path without wildcard", { path <- "Organism|path" expect_error(validatePathIsAbsolute(path), NA) }) test_that("It throws an error for a path with a wildcard", { path <- "Organism|*path" expect_error(validatePathIsAbsolute(path), messages$errorEntityPathNotAbsolute(path)) }) test_that("It does not throw an error when a number is indeed an integer", { validateIsOfType(object = 2, type = "integer") expect_true(TRUE) }) test_that("It does throw an error when a number is not an integer", { expect_error(validateIsOfType(object = 2.5, type = "integer")) }) test_that("It does not throw an error when a validating that a string in an integer", { expect_error(validateIsInteger("s"), messages$errorWrongType(objectName = "\"s\"", expectedType = "integer", type = "character")) }) A <- data.frame( col1 = c(1, 2, 3), col2 = c(4, 5, 6), col3 = c(7, 8, 9) ) B <- data.frame( col1 = c(1, 2, 3), col2 = c(4, 5, 6), col3 = c(7, 8, 9), col4 = c(7, 8, 9) ) test_that("Checks method of type 'validate' work properly", { expect_null(validateIsSameLength(A, A)) expect_null(validateIsOfLength(A, 3)) expect_null(validateIsOfType(A, "data.frame")) expect_null(validateIsIncluded("col3", names(A))) expect_null(validateIsIncluded(NULL, nullAllowed = TRUE)) expect_null(validateIsString("x")) expect_null(validateIsNumeric(1.2)) expect_null(validateIsNumeric(NULL, nullAllowed = TRUE)) expect_null(validateIsInteger(5)) expect_null(validateIsInteger(NULL, nullAllowed = TRUE)) expect_null(validateIsLogical(TRUE)) errorMessageIsSameLength <- "Arguments 'A, B' must have the same length, but they don't!" errorMessageIsOfLength <- "Object should be of length '5', but is of length '3' instead." errorMessageIsOfType <- "argument 'A' is of type 'data.frame', but expected 'character'!" errorMessageIsIncluded <- "Values 'col4' are not in included in parent values: 'col1, col2, col3'." expect_error(validateIsSameLength(A, B), errorMessageIsSameLength) expect_error(validateIsOfLength(A, 5), errorMessageIsOfLength) expect_error(validateIsOfType(A, "character"), errorMessageIsOfType) expect_error(validateIsIncluded("col4", names(A)), errorMessageIsIncluded) }) test_that("enum validation works as expected", { expect_error(validateEnumValue(NULL)) expect_null(validateEnumValue(NULL, nullAllowed = TRUE)) Symbol <- enum(c(Diamond = 1, Triangle = 2, Circle = 2)) expect_null(validateEnumValue(1, Symbol)) expect_error(validateEnumValue(4, Symbol)) })
setClass('vclVector', slots = c(address="externalptr", .context_index = "integer", .platform_index = "integer", .platform = "character", .device_index = "integer", .device = "character")) setClass("vclVectorSlice", contains = "vclVector") setClass("ivclVector", contains = "vclVector", validity = function(object) { if( typeof(object) != "integer"){ return("ivclVector must be of type 'integer'") } TRUE }) setClass("fvclVector", contains = "vclVector", validity = function(object) { if( typeof(object) != "float"){ return("fvclVector must be of type 'float'") } TRUE }) setClass("dvclVector", contains = "vclVector", validity = function(object) { if( typeof(object) != "double"){ return("dvclVector must be of type 'double'") } TRUE }) setClass("ivclVectorSlice", contains = "vclVectorSlice") setClass("fvclVectorSlice", contains = "vclVectorSlice") setClass("dvclVectorSlice", contains = "vclVectorSlice")
sine_up_ <- function(data, grp_id, cols, fs = NULL, periods = NULL, phase = 0, suffix = "_sined", overwrite = FALSE) { num_dims <- length(cols) dim_vectors <- as.list(data[, cols, drop = FALSE]) if (is.null(fs)) { fs <- apply_coordinate_fn_( dim_vectors = dim_vectors, coordinates = fs, fn = create_origin_fn(function(x) { max(x) - min(x) }), num_dims = num_dims, coordinate_name = "fs", fn_name = "fs_fn", dim_var_name = "cols", grp_id = grp_id, allow_len_one = TRUE ) } if (!is.null(periods)) { fs <- fs / periods } print(fs) sined_dim_vectors <- purrr::map2(.x = dim_vectors, .y = fs, .f = ~ { .x * generate_sine_wave(.x, fs = .y, amplitude = 1, phase = phase ) }) data <- add_dimensions_( data = data, new_vectors = setNames(sined_dim_vectors, cols), suffix = suffix, overwrite = overwrite ) data }
test_that("stop if ncol dat !2", { dat1 <- data.frame(x=c(0,0,0)) dat2 <- data.frame(x=c(0,0,0), y=c(10, 10, 10), z=c(10, 10, 10)) expect_error(pi_rho_est(dat=dat1)) expect_error(pi_rho_est(dat=dat2)) }) test_that("adjustment works if all x are 0", { dat <- data.frame(x=c(0,0,0), y=c(10, 10, 10)) pi_rho <- suppressWarnings(pi_rho_est(dat=dat)) expect_equal(round(unname(pi_rho[1]), 4), 0.0167) expect_equal(round(unname(pi_rho[2]), 4), -0.0556) }) test_that("adjustment works if all y are 0", { dat <- data.frame(x=c(10, 10, 10), y=c(0,0,0)) pi_rho <- suppressWarnings(pi_rho_est(dat=dat)) expect_equal(round(unname(pi_rho[1]), 4), 0.9833) expect_equal(round(unname(pi_rho[2]), 4), -0.0556 ) }) test_that("warning if all x are 0", { dat <- data.frame(x=c(0,0,0), y=c(10, 10, 10)) expect_warning(pi_rho_est(dat=dat)) }) test_that("warning if all x are 0", { dat <- data.frame(x=c(10, 10, 10), y=c(0,0,0)) expect_warning(pi_rho_est(dat=dat)) }) test_that("output must be a vector of length 2", { dat <- data.frame(x=c(10, 10, 10), y=c(0,0,0)) pi_rho <- suppressWarnings(pi_rho_est(dat=dat)) expect_equal(length(pi_rho), 2) })
get_ces <- function(srvy, pos = 1){ if(srvy %in% ces_codes){ if(srvy == "ces2019_web"){ hldr <- tempfile(fileext = ".dta") if(!file.exists(hldr)){ cesfile <- "https://dataverse.harvard.edu/api/access/datafile/:persistentId?persistentId=doi:10.7910/DVN/DUS88V/RZFNOV" utils::download.file(cesfile, hldr, quiet = F, mode = "wb") assign("ces2019_web", haven::read_dta(hldr, encoding = "latin1"), envir = as.environment(pos)) unlink(hldr, recursive = T) message(ref2019web) } } else if(srvy == "ces2019_phone"){ hldr <- tempfile(fileext = ".tab") if(!file.exists(hldr)){ cesfile <- "https://dataverse.harvard.edu/api/access/datafile/:persistentId?persistentId=doi:10.7910/DVN/8RHLG1/DW4GZZ" utils::download.file(cesfile, hldr, quiet = F, mode = "wb") assign("ces2019_phone", readr::read_tsv(hldr, show_col_types = F), envir = as.environment(pos)) unlink(hldr, recursive = T) message(ref2019phone) } } else if(srvy == "ces2015_web"){ hldr <- tempfile(fileext = ".zip") fldr <- paste0(tempdir(), "\\ces2015_web") if(!file.exists(hldr)){ cesfile <- "https://ces-eec.sites.olt.ubc.ca/files/2018/07/CES15_CPSPES_Web_SSI-Full-Stata-14.zip" utils::download.file(cesfile, hldr, quiet = F) utils::unzip(hldr, exdir = fldr) datafile <- file.path(fldr, "CES15_CPS+PES_Web_SSI Full Stata 14.dta") assign("ces2015_web", haven::read_dta(hldr), envir = as.environment(pos)) unlink(hldr, recursive = T) unlink(fldr, recursive = T) message(ref2015web) } } else if(srvy == "ces2015_phone"){ hldr <- tempfile(fileext = ".zip") fldr <- paste0(tempdir(), "\\ces2015_phone") if(!file.exists(hldr)){ cesfile <- "https://ces-eec.sites.olt.ubc.ca/files/2018/08/CES2015-phone-Stata.zip" utils::download.file(cesfile, hldr, quiet = F) utils::unzip(hldr, exdir = fldr) datafile <- file.path(fldr, "CES2015_CPS-PES-MBS_complete-v2.dta") assign("ces2015_phone", haven::read_dta(datafile, encoding = "latin1"), envir = as.environment(pos)) unlink(hldr, recursive = T) unlink(fldr, recursive = T) message(ref2015phone) } } else if(srvy == "ces2015_combo"){ hldr <- tempfile(fileext = ".zip") fldr <- paste0(tempdir(), "\\ces2015_combo") if(!file.exists(hldr)){ cesfile <- "https://ces-eec.sites.olt.ubc.ca/files/2017/04/CES2015_Combined_Stata14.zip" utils::download.file(cesfile, hldr, quiet = F) utils::unzip(hldr, exdir = fldr) datafile <- file.path(fldr, "CES2015_Combined_Stata14.dta") assign("ces2015_combo", haven::read_dta(hldr), envir = as.environment(pos)) unlink(hldr, recursive = T) unlink(fldr, recursive = T) message(ref2015combo) } } else if(srvy == "ces2011"){ hldr <- tempfile(fileext = ".zip") fldr <- paste0(tempdir(), "\\ces2011") if(!file.exists(hldr)){ cesfile <- "https://ces-eec.sites.olt.ubc.ca/files/2014/07/CES2011-final-1.zip" utils::download.file(cesfile, hldr, quiet = F) utils::unzip(hldr, exdir = fldr) datafile <- file.path(fldr, "CPS&PES&MBS&WEB_2011_final.dta") assign("ces2011", haven::read_dta(datafile), envir = as.environment(pos)) unlink(hldr, recursive = T) unlink(fldr, recursive = T) message(ref2011) } } else if(srvy == "ces2008"){ hldr <- tempfile(fileext = ".zip") fldr <- paste0(tempdir(), "\\ces2008") if(!file.exists(hldr)){ cesfile <- "https://raw.github.com/hodgettsp/ces_data/master/extdata/CES-E-2008.zip" utils::download.file(cesfile, hldr, quiet = F) utils::unzip(hldr, exdir = fldr) datafile <- file.path(fldr, "CES2015_Combined_Stata14.dta") assign("ces2008", haven::read_sav(hldr), envir = as.environment(pos)) unlink(hldr, recursive = T) unlink(fldr, recursive = T) message(ref2008) } } else if(srvy == "ces2004"){ hldr <- tempfile(fileext = ".zip") fldr <- paste0(tempdir(), "\\ces2004") if(!file.exists(hldr)){ cesfile <- "https://raw.github.com/hodgettsp/ces_data/master/extdata/CES-E-2004.zip" utils::download.file(cesfile, hldr, quiet = F) utils::unzip(hldr, exdir = fldr) datafile <- file.path(fldr, "CES-E-2004_F1.sav") assign("ces2004", haven::read_sav(hldr), envir = as.environment(pos)) unlink(hldr, recursive = T) unlink(fldr, recursive = T) message(ref2004) } } else if(srvy == "ces0411"){ hldr <- tempfile(fileext = ".zip") fldr <- paste0(tempdir(), "\\ces0411") if(!file.exists(hldr)){ cesfile <- "https://ces-eec.sites.olt.ubc.ca/files/2014/07/CES_04060811_final_without-geo-data.zip" utils::download.file(cesfile, hldr, quiet = F) utils::unzip(hldr, exdir = fldr) datafile <- file.path(fldr, "CES_04060811_final_without-geo-data.dta") assign("ces0411", haven::read_dta(hldr, encoding = "latin1"), envir = as.environment(pos)) unlink(hldr, recursive = T) unlink(fldr, recursive = T) message(ref0411) } } else if(srvy == "ces0406"){ hldr <- tempfile(fileext = ".zip") fldr <- paste0(tempdir(), "\\ces0406") if(!file.exists(hldr)){ cesfile <- "https://raw.github.com/hodgettsp/ces_data/master/extdata/CES-E-2004-2006.zip" utils::download.file(cesfile, hldr, quiet = F) utils::unzip(hldr, exdir = fldr) datafile <- file.path(fldr, "CES-E-2004-2006_F1.sav") assign("ces0406", haven::read_sav(hldr), envir = as.environment(pos)) unlink(hldr, recursive = T) unlink(fldr, recursive = T) message(ref0406) } } else if(srvy == "ces2000"){ hldr <- tempfile(fileext = ".zip") fldr <- paste0(tempdir(), "\\ces2000") if(!file.exists(hldr)){ cesfile <- "https://raw.github.com/hodgettsp/ces_data/master/extdata/CES-E-2000.zip" utils::download.file(cesfile, hldr, quiet = F) utils::unzip(hldr, exdir = fldr) datafile <- file.path(fldr, "CES-E-2000_F1.sav") assign("ces2000", haven::read_sav(hldr), envir = as.environment(pos)) unlink(hldr, recursive = T) unlink(fldr, recursive = T) message(ref2000) } } else if(srvy == "ces1997"){ hldr <- tempfile(fileext = ".zip") fldr <- paste0(tempdir(), "\\ces1997") if(!file.exists(hldr)){ cesfile <- "https://raw.github.com/hodgettsp/ces_data/master/extdata/CES-E-1997.zip" utils::download.file(cesfile, hldr, quiet = F) utils::unzip(hldr, exdir = fldr) datafile <- file.path(fldr, "CES-E-1997_F1.sav") assign("ces1997", haven::read_sav(hldr), envir = as.environment(pos)) unlink(hldr, recursive = T) unlink(fldr, recursive = T) message(ref1997) } } else if(srvy == "ces1993"){ hldr <- tempfile(fileext = ".zip") fldr <- paste0(tempdir(), "\\ces1993") if(!file.exists(hldr)){ cesfile <- "https://raw.github.com/hodgettsp/ces_data/master/extdata/CES-E-1993.zip" utils::download.file(cesfile, hldr, quiet = F) utils::unzip(hldr, exdir = fldr) datafile <- file.path(fldr, "CES-E-1993_F1.sav") assign("ces1993", haven::read_sav(hldr), envir = as.environment(pos)) unlink(hldr, recursive = T) unlink(fldr, recursive = T) message(ref1993) } } else if(srvy == "ces1988"){ hldr <- tempfile(fileext = ".zip") fldr <- paste0(tempdir(), "\\ces1988") if(!file.exists(hldr)){ cesfile <- "https://raw.github.com/hodgettsp/ces_data/master/extdata/CES-E-1988.zip" utils::download.file(cesfile, hldr, quiet = F) utils::unzip(hldr, exdir = fldr) datafile <- file.path(fldr, "CES-E-1988_F1.sav") assign("ces1988", haven::read_sav(hldr), envir = as.environment(pos)) unlink(hldr, recursive = T) unlink(fldr, recursive = T) message(ref1988) } } else if(srvy == "ces1984"){ hldr <- tempfile(fileext = ".zip") fldr <- paste0(tempdir(), "\\ces1984") if(!file.exists(hldr)){ cesfile <- "https://raw.github.com/hodgettsp/ces_data/master/extdata/CES-E-1984.zip" utils::download.file(cesfile, hldr, quiet = F) utils::unzip(hldr, exdir = fldr) datafile <- file.path(fldr, "CES-E-1984_F1.sav") assign("ces1984", haven::read_sav(hldr), envir = as.environment(pos)) unlink(hldr, recursive = T) unlink(fldr, recursive = T) message(ref1984) } } else if(srvy == "ces1974"){ hldr <- tempfile(fileext = ".zip") fldr <- paste0(tempdir(), "\\ces1974") if(!file.exists(hldr)){ cesfile <- "https://raw.github.com/hodgettsp/ces_data/master/extdata/CES-E-1974.zip" utils::download.file(cesfile, hldr, quiet = F) utils::unzip(hldr, exdir = fldr) datafile <- file.path(fldr, "CES-E-1974_F1.sav") assign("ces1974", haven::read_sav(hldr), envir = as.environment(pos)) unlink(hldr, recursive = T) unlink(fldr, recursive = T) message(ref1974) } } else if(srvy == "ces7480"){ hldr <- tempfile(fileext = ".zip") fldr <- paste0(tempdir(), "\\ces7480") if(!file.exists(hldr)){ cesfile <- "https://raw.github.com/hodgettsp/ces_data/master/extdata/CES-E-1974-1980.zip" utils::download.file(cesfile, hldr, quiet = F) utils::unzip(hldr, exdir = fldr) datafile <- file.path(fldr, "CES-E-1974-1980_F1.sav") assign("ces7480", haven::read_sav(hldr), as.environment(pos)) unlink(hldr, recursive = T) unlink(fldr, recursive = T) message(ref7480) } } else if(srvy == "ces72_jnjl"){ hldr <- tempfile(fileext = ".zip") fldr <- paste0(tempdir(), "\\ces72jnjl") if(!file.exists(hldr)){ cesfile <- "https://raw.github.com/hodgettsp/ces_data/master/extdata/CES-E-1972-jun-july.zip" utils::download.file(cesfile, hldr, quiet = F) utils::unzip(hldr, exdir = fldr) datafile <- file.path(fldr, "CES-E-1972-jun-july_F1.sav") assign("ces72_jnjl", haven::read_sav(hldr), as.environment(pos)) unlink(hldr, recursive = T) unlink(fldr, recursive = T) message(ref72jnjl) } } else if(srvy == "ces72_sep"){ hldr <- tempfile(fileext = ".zip") fldr <- paste0(tempdir(), "\\ces72sep") if(!file.exists(hldr)){ cesfile <- "https://raw.github.com/hodgettsp/ces_data/master/extdata/CES-E-1972-sept.zip" utils::download.file(cesfile, hldr, quiet = F) utils::unzip(hldr, exdir = fldr) datafile <- file.path(fldr, "CES-E-1972-sept_F1.sav") assign("ces72_sep", haven::read_sav(hldr), as.environment(pos)) unlink(hldr, recursive = T) unlink(fldr, recursive = T) message(ref72sep) } } else if(srvy == "ces72_nov"){ hldr <- tempfile(fileext = ".zip") fldr <- paste0(tempdir(), "\\ces72nov") if(!file.exists(hldr)){ cesfile <- "https://raw.github.com/hodgettsp/ces_data/master/extdata/CES-E-1972-nov.zip" utils::download.file(cesfile, hldr, quiet = F) utils::unzip(hldr, exdir = fldr) datafile <- file.path(fldr, "CES-E-1972-nov_F1.sav") assign("ces72_nov", haven::read_sav(hldr), as.environment(pos)) unlink(hldr, recursive = T) unlink(fldr, recursive = T) message(ref72nov) } } else if(srvy == "ces1968"){ hldr <- tempfile(fileext = ".zip") fldr <- paste0(tempdir(), "\\ces1968") if(!file.exists(hldr)){ cesfile <- "https://raw.github.com/hodgettsp/ces_data/master/extdata/CES-E-1968.zip" utils::download.file(cesfile, hldr, quiet = F) utils::unzip(hldr, exdir = fldr) datafile <- file.path(fldr, "CES-E-1968_F1.sav") assign("ces1968", haven::read_sav(hldr), envir = as.environment(pos)) unlink(hldr, recursive = T) unlink(fldr, recursive = T) message(ref1968) message("\n\nMESSAGE: It is recommended to download the codebook for this dataset to better understand the column names.") } } else if(srvy == "ces1965"){ hldr <- tempfile(fileext = ".zip") fldr <- paste0(tempdir(), "\\ces1965") if(!file.exists(hldr)){ cesfile <- "https://raw.github.com/hodgettsp/ces_data/master/extdata/CES-E-1965.zip" utils::download.file(cesfile, hldr, quiet = F) utils::unzip(hldr, exdir = fldr) datafile <- file.path(fldr, "CES-E-1965_F1.sav") assign("ces1965", haven::read_sav(hldr), envir = as.environment(pos)) unlink(hldr, recursive = T) unlink(fldr, recursive = T) message(ref1965) message("\n\nIt is recommended to download the codebook for this dataset to better understand the column names.") } } } else{ stop("Incorrect CES dataset code provided. Use function get_cescodes() for a printout of useable code calls.") } } ref2019web <- "TO CITE THIS SURVEY FILE:\n - Stephenson, Laura B; Harell, Allison; Rubenson, Daniel; Loewen, Peter John, 2020, '2019 Canadian Election Study - Online Survey', https://doi.org/10.7910/DVN/DUS88V, Harvard Dataverse, V1\n - Stephenson, Laura, Allison Harrel, Daniel Rubenson and Peter Loewen. Forthcoming. 'Measuring Preferences and Behaviour in the 2019 Canadian Election Study,' Canadian Journal of Political Science.\n LINK: https://dataverse.harvard.edu/dataset.xhtml?persistentId=doi:10.7910/DVN/DUS88V" ref2019phone <- "TO CITE THIS SURVEY FILE:\n - Stephenson, Laura B; Harell, Allison; Rubenson, Daniel; Loewen, Peter John, 2020, '2019 Canadian Election Study - Phone Survey', https://doi.org/10.7910/DVN/8RHLG1, Harvard Dataverse, V1, UNF:6:eyR28qaoYlHj9qwPWZmmVQ== [fileUNF]\n - Stephenson, Laura, Allison Harrel, Daniel Rubenson and Peter Loewen. Forthcoming. 'Measuring Preferences and Behaviour in the 2019 Canadian Election Study,' Canadian Journal of Political Science.\n LINK: https://dataverse.harvard.edu/dataset.xhtml?persistentId=doi:10.7910/DVN/8RHLG1" ref2015web <- "TO CITE THIS SURVEY FILE: Fournier, Patrick, Fred Cutler, Stuart Soroka and Dietlind Stolle. 2015. The 2015 Canadian Election Study. [dataset]\n LINK: https://ces-eec.arts.ubc.ca/english-section/surveys/" ref2015phone <- "TO CITE THIS SURVEY FILE: Fournier, Patrick, Fred Cutler, Stuart Soroka and Dietlind Stolle. 2015. The 2015 Canadian Election Study. [dataset]\n LINK:https://ces-eec.arts.ubc.ca/english-section/surveys/" ref2015combo <- "TO CITE THIS SURVEY FILE: Fournier, Patrick, Fred Cutler, Stuart Soroka and Dietlind Stolle. 2015. The 2015 Canadian Election Study. [dataset]\n LINK: https://ces-eec.arts.ubc.ca/english-section/surveys/" ref2011 <- "TO CITE THIS SURVEY FILE: Fournier, Patrick, Fred Cutler, Stuart Soroka and Dietlind Stolle. 2011. The 2011 Canadian Election Study. [dataset]\n LINK: https://ces-eec.arts.ubc.ca/english-section/surveys/" ref2008 <- "TO CITE THIS SURVEY FILE: Gidengil, E, Everitt, J, Fournier, P and Nevitte, N. 2009. The 2008 Canadian Election Study [dataset]. Toronto, Ontario, Canada: Institute for Social Research [producer and distributor].\n LINK: http://odesi2.scholarsportal.info/webview/index.jsp?v=2&previousmode=table&analysismode=table&study=http%3A%2F%2F142.150.190.128%3A80%2Fobj%2FfStudy%2FCES-E-2008&mode=documentation&top=yes" ref2004 <- "TO CITE THIS SURVEY FILE: Blais, A, Everitt, J, Fournier, P, Gidengil, E and Nevitte, N. 2005. The 2004 Canadian Election Study [dataset]. Toronto, Ontario, Canada: Institute for Social Research [producer and distributor].\n LINK: http://odesi2.scholarsportal.info/webview/index.jsp?v=2&submode=abstract&study=http%3A%2F%2F142.150.190.128%3A80%2Fobj%2FfStudy%2FCES-E-2004&mode=documentation&top=yes" ref0411 <- "TO CITE THIS SURVEY FILE: Fournier, P, Stolle, D, Soroka, S, Cutler, F, Blais, A, Everitt, J, Gidengil, E and Nevitte, N. 2011. The 2004-2011 Merged Canadian Election Study [dataset]. Toronto, Ontario, Canada: Institute for Social Research [producer and distributor].\n LINK: https://ces-eec.arts.ubc.ca/english-section/surveys/" ref0406 <- "TO CITE THIS SURVEY FILE: Blais, A, Everitt, J, Fournier, P and Nevitte, N. 2011. The 2011 Canadian Election Study [dataset]. Toronto, Ontario, Canada: Institute for Social Research [producer and distributor].\n LINK: http://odesi2.scholarsportal.info/webview/index.jsp?v=2&submode=abstract&study=http%3A%2F%2F142.150.190.128%3A80%2Fobj%2FfStudy%2FCES-E-2004-2006&mode=documentation&top=yes" ref2000 <- "TO CITE THIS SURVEY FILE: Blais, A, Gidengil, E, Nadeau, R and Nevitte, N. 2001. The 2000 Canadian Election Study [dataset]. Toronto, Ontario, Canada: Institute for Social Research [producer and distributor].\n LINK: http://odesi2.scholarsportal.info/webview/index.jsp?v=2&submode=abstract&study=http%3A%2F%2F142.150.190.128%3A80%2Fobj%2FfStudy%2FCES-E-2000&mode=documentation&top=yes" ref1997 <- "TO CITE THIS SURVEY FILE: Blais, A, Gidengil, E, Nadeau, R and Nevitte, N. 1998. The 1997 Canadian Election Study [dataset]. Toronto, Ontario, Canada: Institute for Social Research [producer and distributor].\n LINK: http://odesi2.scholarsportal.info/webview/index.jsp?v=2&submode=abstract&study=http%3A%2F%2F142.150.190.128%3A80%2Fobj%2FfStudy%2FCES-E-1997&mode=documentation&top=yes" ref1993 <- "TO CITE THIS SURVEY FILE: Blais, A, Brady, H, Gidengil, E, Johnston, R and Nevitte, N. 1994. The 1993 Canadian Election Study [dataset]. Toronto, Ontario, Canada: Institute for Social Research [producer and distributor].\n LINK: http://odesi2.scholarsportal.info/webview/index.jsp?v=2&submode=abstract&study=http%3A%2F%2F142.150.190.128%3A80%2Fobj%2FfStudy%2FCES-E-1993&mode=documentation&top=yes" ref1988 <- "TO CITE THIS SURVEY FILE: Johnston, R, Blais, A, Brady, H. E. and Cr\u00eate, J. 1989. The 1988 Canadian Election Study [dataset]. Toronto, Ontario, Canada: Institute for Social Research [producer and distributor].\n LINK:http://odesi2.scholarsportal.info/webview/index.jsp?v=2&submode=abstract&study=http%3A%2F%2F142.150.190.128%3A80%2Fobj%2FfStudy%2FCES-E-1988&mode=documentation&top=yes" ref1984 <- "TO CITE THIS SURVEY FILE: Lambert, R. D., Brown, S. D., Curtis, J. E., Kay, B. J. and Wilson, J. M. 1985. The 1984 Canadian Election Study [dataset]. Toronto, Ontario, Canada: Institute for Social Research [producer and distributor].\n LINK: http://odesi2.scholarsportal.info/webview/index.jsp?v=2&submode=abstract&study=http%3A%2F%2F142.150.190.128%3A80%2Fobj%2FfStudy%2FCES-E-1984&mode=documentation&top=yes" ref1974 <- "TO CITE THIS SURVEY FILE: Clarke, H, Jenson, J, LeDuc, L and Pammett, J. 1975. The 1974 Canadian Election Study [dataset]. Toronto, Ontario, Canada: Institute for Social Research [producer and distributor].\n LINK: http://odesi2.scholarsportal.info/webview/index.jsp?v=2&submode=abstract&study=http%3A%2F%2F142.150.190.128%3A80%2Fobj%2FfStudy%2FCES-E-1974&mode=documentation&top=yes" ref7480 <- "TO CITE THIS SURVEY FILE: Clarke, H, Jenson, J, LeDuc, L and Pammett, J. 1980. The 1974-1980 Merged Canadian Election Study [dataset]. Toronto, Ontario, Canada: Institute for Social Research [producer and distributor].\n LINK: http://odesi2.scholarsportal.info/webview/index.jsp?v=2&submode=abstract&study=http%3A%2F%2F142.150.190.128%3A80%2Fobj%2FfStudy%2FCES-E-1974-1980&mode=documentation&top=yes" ref72jnjl <- "TO CITE THIS SURVEY FILE: Ruban, C. 1972. The 1972 Canadian Election Study [dataset]. 2nd ICPSR version. Toronto, Ontario, Canada: Market Opinion Research (Canada) Ltd. [producer], 1972. Ann Arbor, MI: Interuniversity Consortium for Political and Social Research [distributor], 2001.\n LINK: http://odesi2.scholarsportal.info/webview/index.jsp?v=2&submode=abstract&study=http%3A%2F%2F142.150.190.128%3A80%2Fobj%2FfStudy%2FCES-E-1972-jun-july&mode=documentation&top=yes" ref72sep <- "TO CITE THIS SURVEY FILE: Ruban, C. 1972. The 1972 Canadian Election Study [dataset]. 2nd ICPSR version. Toronto, Ontario, Canada: Market Opinion Research (Canada) Ltd. [producer], 1972. Ann Arbor, MI: Interuniversity Consortium for Political and Social Research [distributor], 2001.\n LINK: http://odesi2.scholarsportal.info/webview/index.jsp?v=2&submode=abstract&study=http%3A%2F%2F142.150.190.128%3A80%2Fobj%2FfStudy%2FCES-E-1972-sept&mode=documentation&top=yes" ref72nov <- "TO CITE THIS SURVEY FILE: Ruban, C. 1972. The 1972 Canadian Election Study [dataset]. 2nd ICPSR version. Toronto, Ontario, Canada: Market Opinion Research (Canada) Ltd. [producer], 1972. Ann Arbor, MI: Interuniversity Consortium for Political and Social Research [distributor], 2001.\n LINK: http://odesi2.scholarsportal.info/webview/index.jsp?v=2&submode=abstract&study=http%3A%2F%2F142.150.190.128%3A80%2Fobj%2FfStudy%2FCES-E-1972-nov&mode=documentation&top=yes" ref1968 <- "TO CITE THIS SURVEY FILE: Meisel, J. 1968. The 1968 Canadian Election Study [dataset]. Inter-University Consortium for Political and Social Research, University of Michigan, Ann Arbor MI [Producer and distributor].\n LINK: http://odesi2.scholarsportal.info/webview/index.jsp?v=2&submode=abstract&study=http%3A%2F%2F142.150.190.128%3A80%2Fobj%2FfStudy%2FCES-E-1968&mode=documentation&top=yes" ref1965 <- "TO CITE THIS SURVEY FILE: Converse, P, Meisel, J, Pinard, M, Regenstreif, P and Schwartz, M. 1966. Canadian Election Survey, 1965. [Microdata File]. Inter-University Consortium for Political and Social Research, University of Michigan, Ann Arbor MI [Producer].\n LINK: http://odesi2.scholarsportal.info/webview/index.jsp?v=2&submode=abstract&study=http%3A%2F%2F142.150.190.128%3A80%2Fobj%2FfStudy%2FCES-E-1965&mode=documentation&top=yes" ces_codes <- (c("ces2019_web", "ces2019_phone", "ces2015_web", "ces2015_phone", "ces2015_combo", "ces2011", "ces2008", "ces2004", "ces0411", "ces0406", "ces2000", "ces1997", "ces1993", "ces1988", "ces1984", "ces1974", "ces7480", "ces72_jnjl", "ces72_sep", "ces72_nov", "ces1968", "ces1965"))
context("TEST COMBINING MULTIPLE MODELTIME TABLES") m750 <- m4_monthly %>% filter(id == "M750") splits <- time_series_split(m750, assess = "3 years", cumulative = TRUE) model_fit_arima <- arima_reg() %>% set_engine("auto_arima") %>% fit(value ~ date, training(splits)) model_fit_prophet <- prophet_reg() %>% set_engine("prophet") %>% fit(value ~ date, training(splits)) model_fit_ets <- exp_smoothing() %>% set_engine("ets") %>% fit(value ~ date, training(splits)) model_tbl_1 <- modeltime_table(model_fit_arima) model_tbl_2 <- modeltime_table(model_fit_prophet) model_tbl_3 <- modeltime_table(model_fit_ets) calib_tbl <- model_tbl_1 %>% modeltime_calibrate(testing(splits)) test_that("combine_modeltime_table(): succeeds with mdl_time_tbl classes", { model_tbl_combo <- combine_modeltime_tables(model_tbl_1, model_tbl_2, model_tbl_3) expect_s3_class(model_tbl_combo, "mdl_time_tbl") expect_equal(model_tbl_combo$.model_id, 1:3) }) test_that("combine_modeltime_table(): fails with non-mdl_time_tbl classes", { expect_error({ combine_modeltime_tables( model_tbl_1, model_tbl_2, model_tbl_3, model_fit_arima ) }) }) test_that("combine_modeltime_table(): Removes columns when combining calibration tbl", { expect_message({ combine_modeltime_tables( model_tbl_1, model_tbl_2, model_tbl_3, calib_tbl, calib_tbl ) }) combo_tbl <- combine_modeltime_tables( model_tbl_1, model_tbl_2, model_tbl_3, calib_tbl ) expect_equal(ncol(combo_tbl), 3) expect_equal(nrow(combo_tbl), 4) })
NULL extMetricsEnv = new.env() getExternalMetricNames = function() { sort(names(extMetricsEnv)) } defineExternalMetric = function(name, fun, warnIfExists = getOption('latrend.warnMetricOverride', TRUE)) { assert_that(is.function(fun)) assert_that(length(formalArgs(fun)) == 2, msg = 'function must accept two arguments (two lcModels)') .defineMetric(name, fun = fun, warnIfExists = warnIfExists, envir = extMetricsEnv) } getExternalMetricDefinition = function(name) { .getMetricDef(name, envir = extMetricsEnv) } extMetricsEnv$adjustedRand = function(m1, m2) { assert_that(has_same_ids(m1, m2)) mclustcomp::mclustcomp( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, types = 'adjrand' )$scores } extMetricsEnv$CohensKappa = function(m1, m2) { assert_that(has_same_ids(m1, m2)) psych::cohen.kappa( cbind( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer ), alpha = 1 )$kappa } extMetricsEnv$`F` = function(m1, m2) { assert_that(has_same_ids(m1, m2)) mclustcomp::mclustcomp( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, types = 'f' )$scores } extMetricsEnv$F1 = function(m1, m2) { assert_that(has_same_ids(m1, m2)) mclustcomp::mclustcomp( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, types = 'sdc' )$scores } extMetricsEnv$FolkesMallows = function(m1, m2) { assert_that(has_same_ids(m1, m2)) clusterCrit::extCriteria( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, 'Folkes_Mallows' )[[1]] } extMetricsEnv$Hubert = function(m1, m2) { assert_that(has_same_ids(m1, m2)) clusterCrit::extCriteria( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, 'Hubert' )[[1]] } extMetricsEnv$Jaccard = function(m1, m2) { assert_that(has_same_ids(m1, m2)) clusterCrit::extCriteria( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, 'Jaccard' )[[1]] } extMetricsEnv$jointEntropy = function(m1, m2) { assert_that(has_same_ids(m1, m2)) mclustcomp::mclustcomp( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, types = 'jent' )$scores } extMetricsEnv$Kulczynski = function(m1, m2) { assert_that(has_same_ids(m1, m2)) clusterCrit::extCriteria( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, 'Kulczynski' )[[1]] } extMetricsEnv$MaximumMatch = function(m1, m2) { assert_that(has_same_ids(m1, m2)) mclustcomp::mclustcomp( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, types = 'mmm' )$scores } extMetricsEnv$McNemar = function(m1, m2) { assert_that(has_same_ids(m1, m2)) clusterCrit::extCriteria( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, 'McNemar' )[[1]] } extMetricsEnv$MeilaHeckerman = function(m1, m2) { assert_that(has_same_ids(m1, m2)) mclustcomp::mclustcomp( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, types = 'mhm' )$scores } extMetricsEnv$Mirkin = function(m1, m2) { assert_that(has_same_ids(m1, m2)) mclustcomp::mclustcomp( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, types = 'mirkin' )$scores } extMetricsEnv$MI = function(m1, m2) { assert_that(has_same_ids(m1, m2)) mclustcomp::mclustcomp( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, types = 'mi' )$scores } extMetricsEnv$NMI = function(m1, m2) { assert_that(has_same_ids(m1, m2)) igraph::compare( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, method = 'nmi' ) } extMetricsEnv$NSJ = function(m1, m2) { extMetricsEnv$splitJoin(m1, m2) / (2 * nIds(m1)) } extMetricsEnv$NVI = function(m1, m2) { assert_that(has_same_ids(m1, m2)) mclustcomp::mclustcomp( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, types = 'nvi' )$scores } extMetricsEnv$Overlap = function(m1, m2) { assert_that(has_same_ids(m1, m2)) mclustcomp::mclustcomp( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, types = 'overlap' )$scores } extMetricsEnv$PD = function(m1, m2) { assert_that(has_same_ids(m1, m2)) mclustcomp::mclustcomp( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, types = 'pd' )$scores } extMetricsEnv$Phi = function(m1, m2) { assert_that(has_same_ids(m1, m2)) clusterCrit::extCriteria( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, 'Phi' )[[1]] } extMetricsEnv$precision = function(m1, m2) { assert_that(has_same_ids(m1, m2)) clusterCrit::extCriteria( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, 'Precision' )[[1]] } extMetricsEnv$Rand = function(m1, m2) { assert_that(has_same_ids(m1, m2)) clusterCrit::extCriteria( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, 'Rand' )[[1]] } extMetricsEnv$recall = function(m1, m2) { assert_that(has_same_ids(m1, m2)) clusterCrit::extCriteria( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, 'Recall' )[[1]] } extMetricsEnv$RogersTanimoto = function(m1, m2) { assert_that(has_same_ids(m1, m2)) clusterCrit::extCriteria( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, 'Rogers_Tanimoto' )[[1]] } extMetricsEnv$RusselRao = function(m1, m2) { assert_that(has_same_ids(m1, m2)) clusterCrit::extCriteria( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, 'Russel_Rao' )[[1]] } extMetricsEnv$SMC = function(m1, m2) { assert_that(has_same_ids(m1, m2)) mclustcomp::mclustcomp( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, types = 'smc' )$scores } extMetricsEnv$splitJoin = function(m1, m2) { assert_that(has_same_ids(m1, m2)) igraph::split_join_distance( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer ) %>% sum() } extMetricsEnv$splitJoin.ref = function(m1, m2) { assert_that(has_same_ids(m1, m2)) igraph::split_join_distance( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer )[1] } extMetricsEnv$SokalSneath1 = function(m1, m2) { assert_that(has_same_ids(m1, m2)) clusterCrit::extCriteria( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, 'Sokal_Sneath1' )[[1]] } extMetricsEnv$SokalSneath2 = function(m1, m2) { assert_that(has_same_ids(m1, m2)) clusterCrit::extCriteria( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, 'Sokal_Sneath2' )[[1]] } extMetricsEnv$VI = function(m1, m2) { assert_that(has_same_ids(m1, m2)) mclustcomp::mclustcomp( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, types = 'vi' )$scores } extMetricsEnv$Wallace1 = function(m1, m2) { assert_that(has_same_ids(m1, m2)) mclustcomp::mclustcomp( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, types = 'wallace1' )$scores } extMetricsEnv$Wallace2 = function(m1, m2) { assert_that(has_same_ids(m1, m2)) mclustcomp::mclustcomp( trajectoryAssignments(m1) %>% as.integer, trajectoryAssignments(m2) %>% as.integer, types = 'wallace2' )$scores } .wmrss = function(m1, m2, newdata = union(time(m1), time(m2))) { resp1 = responseVariable(m1) resp2 = responseVariable(m2) trajmat1 = clusterTrajectories(m1, at = newdata)[[resp1]] %>% matrix(ncol = nClusters(m1)) trajmat2 = clusterTrajectories(m2, at = newdata)[[resp2]] %>% matrix(ncol = nClusters(m2)) groupMetric1 = foreach(g = seq_len(nClusters(m1)), .combine = c) %do% { min(colSums(sweep(trajmat2, 1, trajmat1[, g]) ^ 2)) } groupMetric2 = foreach(g = seq_len(nClusters(m2)), .combine = c) %do% { min(colSums(sweep(trajmat1, 1, trajmat2[, g]) ^ 2)) } wmsse1 = clusterProportions(m1) * groupMetric1 wmsse2 = clusterProportions(m2) * groupMetric2 c(wmsse1, wmsse2) } extMetricsEnv$WMRSS = function(m1, m2, newdata = union(time(m1), time(m2))) { out = .wmrss(m1, m2, newdata) sum(out) } extMetricsEnv$WMRSS.ref = function(m1, m2, newdata = union(time(m1), time(m2))) { out = .wmrss(m1, m2, newdata) out[2] } extMetricsEnv$WMMSE = function(m1, m2, newdata = union(time(m1), time(m2))) { if (is.data.frame(newdata) || is.matrix(newdata)) { nob = nrow(newdata) } else { nob = length(newdata) } extMetricsEnv$WMRSS(m1, m2, newdata) / (2 * nob) } extMetricsEnv$WMMSE.ref = function(m1, m2, newdata = union(time(m1), time(m2))) { if (is.data.frame(newdata) || is.matrix(newdata)) { nob = nrow(newdata) } else { nob = length(newdata) } extMetricsEnv$WMRSS.ref(m1, m2, newdata) / nob } .wmmae = function(m1, m2, newdata = union(time(m1), time(m2))) { resp1 = responseVariable(m1) resp2 = responseVariable(m2) trajmat1 = clusterTrajectories(m1, at = newdata)[[resp1]] %>% matrix(ncol = nClusters(m1)) trajmat2 = clusterTrajectories(m2, at = newdata)[[resp2]] %>% matrix(ncol = nClusters(m2)) groupMetric1 = foreach(g = seq_len(nClusters(m1)), .combine = c) %do% { min(colMeans(abs(sweep( trajmat2, 1, trajmat1[, g] )))) } groupMetric2 = foreach(g = seq_len(nClusters(m2)), .combine = c) %do% { min(colMeans(abs(sweep( trajmat1, 1, trajmat2[, g] )))) } wmmae1 = clusterProportions(m1) * groupMetric1 wmmae2 = clusterProportions(m2) * groupMetric2 c(wmmae1, wmmae2) } extMetricsEnv$WMMAE = function(m1, m2, newdata = union(time(m1), time(m2))) { out = .wmmae(m1, m2, newdata) mean(out) } extMetricsEnv$WMMAE.ref = function(m1, m2, newdata = union(time(m1), time(m2))) { out = .wmmae(m1, m2, newdata) out[2] }
test_that("add_node works", { expect_equal(add_node(list("test" = 1)), "INSERT INTO nodes VALUES(json('{\"test\":1}'));") })
PBDes<-function(nruns,nfactors,randomize=FALSE) { irun<-1 if (nruns == 12) {irun<-0} if (nruns == 20) {irun<-0} if (nruns == 24) {irun<-0} if(irun>0) {stop("This function only works for nruns=12 or nruns=20, or nruns=24") } if (nruns==12){ if (nfactors < 5) {stop("At least 5 factors required for 12-run PB design")} if (nfactors > 11){stop("No more than 11 factors can be used for 12 run PB design")} } if (nruns==20){ if (nfactors < 8) {stop("At least 8 factors required for 20-run PB design")} if (nfactors > 19){stop("No more than 19 factors can be used for 20 run PB design")} } if (nruns==24){ if (nfactors < 15) {stop("At least 15 factors required for 24-run PB design")} if (nfactors > 23){stop("No more than 23 factors can be used for 20 run PB design")} } if(nruns==12){ pb12r1<-c( 1, 1, -1, 1, 1, 1, -1, -1, -1, 1, -1) pb12r2<-c(pb12r1[11],pb12r1[1:10]) pb12r3<-c(pb12r2[11],pb12r2[1:10]) pb12r4<-c(pb12r3[11],pb12r3[1:10]) pb12r5<-c(pb12r4[11],pb12r4[1:10]) pb12r6<-c(pb12r5[11],pb12r5[1:10]) pb12r7<-c(pb12r6[11],pb12r6[1:10]) pb12r8<-c(pb12r7[11],pb12r7[1:10]) pb12r9<-c(pb12r8[11],pb12r8[1:10]) pb12r10<-c(pb12r9[11],pb12r9[1:10]) pb12r11<-c(pb12r10[11],pb12r10[1:10]) pb12r12<-rep(-1,11) des<-rbind(pb12r1,pb12r2,pb12r3,pb12r4,pb12r5,pb12r6,pb12r7,pb12r8,pb12r9,pb12r10,pb12r11,pb12r12) randord<-sample(1:12) if (randomize==TRUE){des <- des[randord, ] } colnames(des)<-c("A","B","C","D","E","F","G","H","J","K","L") row.names(des)<-c(1:12) } if(nruns==20){ pb20r1<-c(1,1,-1,-1,1,1,1,1,-1,1,-1,1,-1,-1,-1,-1,1,1,-1) pb20r2<-c(pb20r1[19],pb20r1[1:18]) pb20r3<-c(pb20r2[19],pb20r2[1:18]) pb20r4<-c(pb20r3[19],pb20r3[1:18]) pb20r5<-c(pb20r4[19],pb20r4[1:18]) pb20r6<-c(pb20r5[19],pb20r5[1:18]) pb20r7<-c(pb20r6[19],pb20r6[1:18]) pb20r8<-c(pb20r7[19],pb20r7[1:18]) pb20r9<-c(pb20r8[19],pb20r8[1:18]) pb20r10<-c(pb20r9[19],pb20r9[1:18]) pb20r11<-c(pb20r10[19],pb20r10[1:18]) pb20r12<-c(pb20r11[19],pb20r11[1:18]) pb20r13<-c(pb20r12[19],pb20r12[1:18]) pb20r14<-c(pb20r13[19],pb20r13[1:18]) pb20r15<-c(pb20r14[19],pb20r14[1:18]) pb20r16<-c(pb20r15[19],pb20r15[1:18]) pb20r17<-c(pb20r16[19],pb20r16[1:18]) pb20r18<-c(pb20r17[19],pb20r17[1:18]) pb20r19<-c(pb20r18[19],pb20r18[1:18]) pb20r20<-c(rep(-1,19)) des<-rbind(pb20r1,pb20r2,pb20r3,pb20r4,pb20r5,pb20r6, pb20r7,pb20r8,pb20r9,pb20r10,pb20r11,pb20r12, pb20r13,pb20r14,pb20r15,pb20r16,pb20r17,pb20r18, pb20r19,pb20r20) randord<-sample(1:20) if (randomize==TRUE){des <- des[randord, ] } colnames(des)<-c("A","B","C","D","E","F","G","H","J","K", "L","M","N","O","P","Q","R","S","T") row.names(des)<-c(1:20) } if(nruns==24){ pb24r1<-c(1,1,1,1,1,-1,1,-1,1,1,-1,-1,1,1,-1,-1,1,-1,1,-1,-1,-1,-1) pb24r2<-c(pb24r1[23],pb24r1[1:22]) pb24r3<-c(pb24r2[23],pb24r2[1:22]) pb24r4<-c(pb24r3[23],pb24r3[1:22]) pb24r5<-c(pb24r4[23],pb24r4[1:22]) pb24r6<-c(pb24r5[23],pb24r5[1:22]) pb24r7<-c(pb24r6[23],pb24r6[1:22]) pb24r8<-c(pb24r7[23],pb24r7[1:22]) pb24r9<-c(pb24r8[23],pb24r8[1:22]) pb24r10<-c(pb24r9[23],pb24r9[1:22]) pb24r11<-c(pb24r10[23],pb24r10[1:22]) pb24r12<-c(pb24r11[23],pb24r11[1:22]) pb24r13<-c(pb24r12[23],pb24r12[1:22]) pb24r14<-c(pb24r13[23],pb24r13[1:22]) pb24r15<-c(pb24r14[23],pb24r14[1:22]) pb24r16<-c(pb24r15[23],pb24r15[1:22]) pb24r17<-c(pb24r16[23],pb24r16[1:22]) pb24r18<-c(pb24r17[23],pb24r17[1:22]) pb24r19<-c(pb24r18[23],pb24r18[1:22]) pb24r20<-c(pb24r19[23],pb24r19[1:22]) pb24r21<-c(pb24r20[23],pb24r20[1:22]) pb24r22<-c(pb24r21[23],pb24r21[1:22]) pb24r23<-c(pb24r22[23],pb24r22[1:22]) pb24r24<-c(rep(-1,23)) des<-rbind(pb24r1,pb24r2,pb24r3,pb24r4,pb24r5,pb24r6, pb24r7,pb24r8,pb24r9,pb24r10,pb24r11,pb24r12, pb24r13,pb24r14,pb24r15,pb24r16,pb24r17,pb24r18, pb24r19,pb24r20,pb24r21,pb24r22,pb24r23,pb24r24) randord<-sample(1:24) if (randomize==TRUE){des <- des[randord, ] } colnames(des)<-c("A","B","C","D","E","F","G","H","J","K", "L","M","N","O","P","Q","R","S","T","U", "V","W","X") row.names(des)<-c(1:24) } des<-as.data.frame(des[,1:nfactors] ) return(des) }
session <- RevoIOQ:::saveRUnitSession() "reg.BLAS.stress" <- function() { stopifnot(is.na(NA %*% 0), is.na(0 %*% NA)) x <- matrix(c(1, 0, NA, 1), 2, 2) y <- matrix(c(1, 0, 0, 2, 1, 0), 3, 2) (z <- tcrossprod(x, y)) stopifnot(identical(z, x %*% t(y))) stopifnot(is.nan(log(0) %*% 0)) } "test.reg.BLAS.stress" <- function() { res <- try(reg.BLAS.stress()) checkTrue(!is(res, "try-error"), msg="reg.BLAS stress test failed") } "testzzz.restore.session" <- function() { checkTrue(RevoIOQ:::restoreRUnitSession(session), msg="Session restoration failed") }
cumul.rma.peto <- function(x, order, digits, transf, targs, progbar=FALSE, ...) { mstyle <- .get.mstyle("crayon" %in% .packages()) .chkclass(class(x), must="rma.peto") na.act <- getOption("na.action") if (!is.element(na.act, c("na.omit", "na.exclude", "na.fail", "na.pass"))) stop(mstyle$stop("Unknown 'na.action' specified under options().")) if (missing(digits)) { digits <- .get.digits(xdigits=x$digits, dmiss=TRUE) } else { digits <- .get.digits(digits=digits, xdigits=x$digits, dmiss=FALSE) } if (missing(transf)) transf <- FALSE if (missing(targs)) targs <- NULL ddd <- list(...) .chkdots(ddd, c("time", "decreasing")) if (.isTRUE(ddd$time)) time.start <- proc.time() if (is.null(ddd$decreasing)) { decreasing <- FALSE } else { decreasing <- ddd$decreasing } if (grepl("^order\\(", deparse1(substitute(order)))) warning(mstyle$warning("Use of order() in 'order' argument is probably erroneous."), call.=FALSE) if (missing(order)) { order <- seq_len(x$k.all) } else { mf <- match.call() order <- .getx("order", mf=mf, data=x$data) } if (length(order) != x$k.all) stop(mstyle$stop(paste0("Length of the 'order' argument (", length(order), ") does not correspond to the size of the original dataset (", x$k.all, ")."))) if (!is.null(x$subset)) order <- order[x$subset] order <- order(order, decreasing=decreasing) ai.f <- x$ai.f[order] bi.f <- x$bi.f[order] ci.f <- x$ci.f[order] di.f <- x$di.f[order] yi.f <- x$yi.f[order] vi.f <- x$vi.f[order] not.na <- x$not.na[order] slab <- x$slab[order] ids <- x$ids[order] beta <- rep(NA_real_, x$k.f) se <- rep(NA_real_, x$k.f) zval <- rep(NA_real_, x$k.f) pval <- rep(NA_real_, x$k.f) ci.lb <- rep(NA_real_, x$k.f) ci.ub <- rep(NA_real_, x$k.f) QE <- rep(NA_real_, x$k.f) QEp <- rep(NA_real_, x$k.f) I2 <- rep(NA_real_, x$k.f) H2 <- rep(NA_real_, x$k.f) outlist <- "beta=beta, se=se, zval=zval, pval=pval, ci.lb=ci.lb, ci.ub=ci.ub, QE=QE, QEp=QEp, tau2=tau2, I2=I2, H2=H2" if (progbar) pbar <- pbapply::startpb(min=0, max=x$k.f) for (i in seq_len(x$k.f)) { if (progbar) pbapply::setpb(pbar, i) if (!not.na[i]) next args <- list(ai=ai.f, bi=bi.f, ci=ci.f, di=di.f, add=x$add, to=x$to, drop00=x$drop00, level=x$level, subset=seq_len(i), outlist=outlist) res <- try(suppressWarnings(.do.call(rma.peto, args)), silent=TRUE) if (inherits(res, "try-error")) next beta[i] <- res$beta se[i] <- res$se zval[i] <- res$zval pval[i] <- res$pval ci.lb[i] <- res$ci.lb ci.ub[i] <- res$ci.ub QE[i] <- res$QE QEp[i] <- res$QEp I2[i] <- res$I2 H2[i] <- res$H2 } if (progbar) pbapply::closepb(pbar) if (.isTRUE(transf)) transf <- exp if (is.function(transf)) { if (is.null(targs)) { beta <- sapply(beta, transf) se <- rep(NA,x$k.f) ci.lb <- sapply(ci.lb, transf) ci.ub <- sapply(ci.ub, transf) } else { beta <- sapply(beta, transf, targs) se <- rep(NA,x$k.f) ci.lb <- sapply(ci.lb, transf, targs) ci.ub <- sapply(ci.ub, transf, targs) } transf <- TRUE } tmp <- .psort(ci.lb, ci.ub) ci.lb <- tmp[,1] ci.ub <- tmp[,2] if (na.act == "na.omit") { out <- list(estimate=beta[not.na], se=se[not.na], zval=zval[not.na], pval=pval[not.na], ci.lb=ci.lb[not.na], ci.ub=ci.ub[not.na], Q=QE[not.na], Qp=QEp[not.na], I2=I2[not.na], H2=H2[not.na]) out$slab <- slab[not.na] out$ids <- ids[not.na] } if (na.act == "na.exclude" || na.act == "na.pass") { out <- list(estimate=beta, se=se, zval=zval, pval=pval, ci.lb=ci.lb, ci.ub=ci.ub, Q=QE, Qp=QEp, I2=I2, H2=H2) out$slab <- slab out$ids <- ids } if (na.act == "na.fail" && any(!x$not.na)) stop(mstyle$stop("Missing values in results.")) out$digits <- digits out$transf <- transf out$slab.null <- x$slab.null out$level <- x$level out$measure <- x$measure out$test <- x$test attr(out$estimate, "measure") <- x$measure if (.isTRUE(ddd$time)) { time.end <- proc.time() .print.time(unname(time.end - time.start)[3]) } class(out) <- c("list.rma", "cumul.rma") return(out) }
expm <- function(x) { if (length(dim(x)) != 2 || nrow(x) != ncol(x)) { stop("input to omxExponential() must be a square matrix") } .Call(do_expm_eigen, x) } omxExponential <- expm logm <- function(x, tol = .Machine$double.eps) { d <- dim(x) if(length(d) != 2 || d[1] != d[2]) stop("'x' must be a quadratic matrix") .Call(do_logm_eigen, x) }
met.betweenness.single <- function(m, binary = FALSE, shortest.weight = FALSE, normalization = TRUE, sym = TRUE, out = TRUE, df = NULL, dfid = NULL) { name <- colnames(m) if (sym) { m <- m + t(m) } if (binary) { m <- mat_filter(m, 1, 1) colnames(m) <- name rownames(m) <- name } if (shortest.weight == FALSE) { if (normalization) { number.of.links = sum(m > 0) avg_strength <- sum(m) / number.of.links m <- m / avg_strength } m <- 1 / m m[is.infinite(m)] <- 0 } if (out == FALSE) { m <- t(m) } result <- metric_node_betweeness(m) result if (is.null(df)) { attr(result, "names") <- colnames(m) result return(result) } else { if (is.data.frame(df) == FALSE) { stop("Argument df must be a data frame") } if (!is.null(dfid)) { if (is.null(colnames(m))) { stop("Argument m doesn't have column names") } col.id <- df.col.findId(df, dfid) df <- df[match(colnames(m), df[, col.id]), ] } df[, ncol(df) + 1] <- result return(df) } }
gx.scores <- function (xx, tholds, rwts = NULL, setna = FALSE) { if (!is.matrix(xx)) stop(deparse(substitute(xx)), " is not a Matrix") temp.x <- remove.na(xx) x <- temp.x$x n <- temp.x$n ncolx <- temp.x$m nthld <- length(tholds) if (ncolx != nthld) stop("\n Number of variables and thresholds do not match") if (!is.null(rwts) && length(rwts) != nthld) stop("\n Number of thresholds and weights do not match") for (i in 1:n) { for (j in 1:nthld) { x[i,j] <- x[i,j]/tholds[j] if (x[i,j] < 1) x[i,j] <- 0 if (!is.null(rwts)) x[i,j] <- x[i,j] * rwts[j] } } scores <- rowSums(x) scores[scores <= 0] <- 0 if (setna) scores[scores <= 0] <- NA invisible(list(input = deparse(substitute(xx)), tholds = tholds, rwts = rwts, scores = scores)) }
test_that("parallel runs work as planned", { set.seed(123) arrival1 <- rkiToBabsimArrivals(babsim.hospital::rkidata) arrival1 <- data.frame("time" = arrival1[1:1000, ]) para <- babsimHospitalPara() conf <- babsimToolsConf() expect_error( { babsimHospital( arrivalTimes = arrival1, conf = conf, para = para ) }, NA ) })
ena.optimize.set <- function( ) { }
demo("SETUP", package = "rstanarm", verbose = FALSE, echo = FALSE, ask = FALSE) source(paste0(ROOT, "ARM/Ch.3/kidiq.data.R"), local = DATA_ENV, verbose = FALSE) dat <- with(DATA_ENV, data.frame(kid_score, mom_hs, mom_iq)) post1 <- stan_glm(kid_score ~ mom_hs, data = dat, family = gaussian(link = "identity"), seed = SEED, refresh = REFRESH) post2 <- update(post1, formula = kid_score ~ mom_iq) post3 <- stan_lm(kid_score ~ mom_hs + mom_iq, data = dat, prior = R2(location = 0.25, what = "mean"), seed = SEED, refresh = REFRESH) post4 <- update(post3, formula = kid_score ~ mom_hs * mom_iq, prior = R2(location = 0.30, what = "mean")) loo1 <- loo(post1) loo2 <- loo(post2) loo3 <- loo(post3) loo4 <- loo(post4) par(mfrow = c(2,2), mar = c(4,4,2,1) + .1) plot(loo1, label_points = TRUE); title(main = "Model 1") plot(loo2, label_points = TRUE); title(main = "Model 2") plot(loo3, label_points = TRUE); title(main = "Model 3") plot(loo4, label_points = TRUE); title(main = "Model 4") compare(loo1, loo2, loo3, loo4) IQ_SEQ <- seq(from = 75, to = 135, by = 5) y_nohs <- posterior_predict(post4, newdata = data.frame(mom_hs = 0, mom_iq = IQ_SEQ)) y_hs <- posterior_predict(post4, newdata = data.frame(mom_hs = 1, mom_iq = IQ_SEQ)) par(mfrow = c(1:2), mar = c(5,4,2,1)) boxplot(y_hs, axes = FALSE, outline = FALSE, ylim = c(30,160), xlab = "Mom IQ", ylab = "Predicted Kid IQ", main = "Mom HS") axis(1, at = 1:ncol(y_hs), labels = IQ_SEQ, las = 3) axis(2, las = 1) boxplot(y_nohs, outline = FALSE, col = "red", axes = FALSE, ylim = c(30,160), xlab = "Mom IQ", ylab = "Predicted Kid IQ", main = "Mom No HS") axis(1, at = 1:ncol(y_hs), labels = IQ_SEQ, las = 3) axis(2, las = 1) source(paste0(ROOT, "ARM/Ch.3/kids_before1987.data.R"), local = DATA_ENV, verbose = FALSE) source(paste0(ROOT, "ARM/Ch.3/kids_after1987.data.R"), local = DATA_ENV, verbose = FALSE) fit_data <- with(DATA_ENV, data.frame(ppvt, hs, afqt)) pred_data <- with(DATA_ENV, data.frame(ppvt_ev, hs_ev, afqt_ev)) post5 <- stan_lm(ppvt ~ hs + afqt, data = fit_data, prior = R2(location = 0.25, what = "mean"), seed = SEED, refresh = REFRESH) y_ev <- posterior_predict( post5, newdata = with(pred_data, data.frame(hs = hs_ev, afqt = afqt_ev)) ) par(mfrow = c(1,1)) hist(-sweep(y_ev, 2, STATS = pred_data$ppvt_ev, FUN = "-"), prob = TRUE, xlab = "Predictive Errors in ppvt", main = "", las = 2) ANSWER <- tolower(readline("Do you want to remove the objects this demo created? (y/n) ")) if (ANSWER != "n") { rm(IQ_SEQ, y_nohs, y_hs, y_ev, ANSWER) demo("CLEANUP", package = "rstanarm", verbose = FALSE, echo = FALSE, ask = FALSE) }
block_average <- function(data, x = t, y = temp, report = "full") { quo_x <- rlang::enquo(x) quo_y <- rlang::enquo(y) clim <- data$clim %>% dplyr::rename(t = !!quo_x, temp = !!quo_y) year <- temp <- date_start <- temp_mean <- temp_min <- temp_max <- NULL temp_yr <- clim %>% dplyr::group_by(year = lubridate::year(t)) %>% dplyr::summarise(temp_mean = mean(temp, na.rm = TRUE), temp_min = min(temp), temp_max = max(temp)) duration <- count <- int_mean <- int_max <- int_var <- int_cum <- int_mean_rel_thresh <- int_max_rel_thresh <- int_var_rel_thresh <- int_cum_rel_thresh <- int_mean_abs <- int_max_abs <- int_var_abs <- int_cum_abs <- int_mean_norm <- int_max_norm <- rate_onset <- rate_decline <- total_days <- total_icum <- NULL event_block <- data$event %>% dplyr::group_by(year = lubridate::year(date_start)) %>% dplyr::summarise(count = length(duration), int_mean = mean(int_mean), int_max = mean(int_max), int_var = mean(int_var), int_cum = mean(int_cum), int_mean_rel_thresh = mean(int_mean_rel_thresh), int_max_rel_thresh = mean(int_max_rel_thresh), int_var_rel_thresh = mean(int_var_rel_thresh), int_cum_rel_thresh = mean(int_cum_rel_thresh), int_mean_abs = mean(int_mean_abs), int_max_abs = mean(int_max_abs), int_var_abs = mean(int_var_abs), int_cum_abs = mean(int_cum_abs), int_mean_norm = mean(int_mean_norm), int_max_norm = mean(int_max_norm), rate_onset = mean(rate_onset), rate_decline = mean(rate_decline), total_days = sum(duration), total_icum = sum(int_cum)) if (report == "full") { event_block <- dplyr::left_join(temp_yr, event_block, by = "year") } else if (report == "partial") { event_block <- dplyr::inner_join(temp_yr, event_block, by = "year") } else stop("Oops, 'report' must be either 'full' or 'partial'!") event_block$count[is.na(event_block$count)] <- 0 return(event_block) }
wc.phasediff.image <- function(WC, use.sAngle = FALSE, plot.coi = TRUE, plot.contour = TRUE, which.contour = "wp", siglvl = 0.1, col.contour = "white", n.levels = 100, color.palette = "rainbow(n.levels, start = 0, end = .7)", useRaster = TRUE, max.contour.segments = 250000, plot.legend = TRUE, legend.params = list(width = 1.2, shrink = 0.9, mar = 5.1, n.ticks = 6, pi.style = TRUE, label.digits = 1, label.format = "f", lab = NULL, lab.line = 3), label.time.axis = TRUE, show.date = FALSE, date.format = NULL, date.tz = NULL, timelab = NULL, timetck = 0.02, timetcl = 0.5, spec.time.axis = list(at = NULL, labels = TRUE, las = 1, hadj = NA, padj = NA), label.period.axis = TRUE, periodlab = NULL, periodtck = 0.02, periodtcl = 0.5, spec.period.axis = list(at = NULL, labels = TRUE, las = 1, hadj = NA, padj = NA), main = NULL, lwd = 2, lwd.axis = 1, graphics.reset = TRUE, verbose = FALSE) { if(verbose == T){ out <- function(...){ cat(...) } } else{ out <- function(...) { } } default.options = options() options(max.contour.segments = as.integer(max.contour.segments)) if (class(WC) == 'analyze.wavelet') { stop("Your object class is 'analyze.wavelet' --- please use wt.phase.image!") } series.data = WC$series axis.1 <- WC$axis.1 axis.2 <- WC$axis.2 if (use.sAngle == T) { Angle <- WC$sAngle } if (use.sAngle == F) { Angle <- WC$Angle } phasediff.levels = seq(-pi,pi,length.out=n.levels+1) key.cols = rev(eval(parse(text=color.palette))) if (is.null(legend.params$width)) legend.params$width = 1.2 if (is.null(legend.params$shrink)) legend.params$shrink = 0.9 if (is.null(legend.params$mar)) legend.params$mar = ifelse(is.null(legend.params$lab), 5.1, 6.1) if (is.null(legend.params$n.ticks)) legend.params$n.ticks = 6 if (is.null(legend.params$pi.style)) legend.params$pi.style = TRUE if (is.null(legend.params$label.digits)) { if (legend.params$pi.style == TRUE) {legend.params$label.digits = 1} else {legend.params$label.digits = 2} } if (is.null(legend.params$label.format)) legend.params$label.format = "f" if (is.null(legend.params$lab.line)) legend.params$lab.line = 3 if (is.null(date.format)) { date.format = WC$date.format } if (is.null(date.tz)) { date.tz = ifelse(is.null(WC$date.tz),"",WC$date.tz) } if (!is.list(spec.time.axis)) spec.time.axis = list() if (is.null(spec.time.axis$at)) spec.time.axis$at = NULL if (is.null(spec.time.axis$labels)) spec.time.axis$labels = T if (is.null(spec.time.axis$las)) spec.time.axis$las = 1 if (is.null(spec.time.axis$hadj)) spec.time.axis$hadj = NA if (is.null(spec.time.axis$padj)) spec.time.axis$padj = NA time.axis.warning = F time.axis.warning.na = F chronology.warning = F if ( (!is.null(spec.time.axis$at)) & (label.time.axis==F) ) warning("\nPlease set label.time.axis = TRUE to make time axis specification effective.", immediate. = TRUE) if (!is.list(spec.period.axis)) spec.period.axis = list() if (is.null(spec.period.axis$at)) spec.period.axis$at = NULL if (is.null(spec.period.axis$labels)) spec.period.axis$labels = T if (is.null(spec.period.axis$las)) spec.period.axis$las = 1 if (is.null(spec.period.axis$hadj)) spec.period.axis$hadj = NA if (is.null(spec.period.axis$padj)) spec.period.axis$padj = NA period.axis.warning = F period.axis.warning.na = F if ( (!is.null(spec.period.axis$at)) & (label.period.axis==F) ) warning("\nPlease set label.period.axis = TRUE to make period axis specification effective.", immediate. = TRUE) op = par(no.readonly = TRUE) image.plt = par()$plt legend.plt = NULL if (plot.legend == T) { legend.plt = par()$plt char.size = par()$cin[1]/par()$din[1] hoffset = char.size * par()$mar[4] legend.width = char.size * legend.params$width legend.mar = char.size * legend.params$mar legend.plt[2] = 1 - legend.mar legend.plt[1] = legend.plt[2] - legend.width vmar = (legend.plt[4] - legend.plt[3]) * ((1 - legend.params$shrink)/2) legend.plt[4] = legend.plt[4] - vmar legend.plt[3] = legend.plt[3] + vmar image.plt[2] = min(image.plt[2], legend.plt[1] - hoffset) par(plt = legend.plt) key.marks = round(seq(from = 0, to = 1, length.out=legend.params$n.ticks)*n.levels) if (legend.params$pi.style == FALSE) { line.add = 0 key.labels = formatC(as.numeric(phasediff.levels), digits = legend.params$label.digits, format = legend.params$label.format)[key.marks+1] } if (legend.params$pi.style == TRUE) { line.add = 0.6 pi.fac.seq = seq(-1,1,length.out=n.levels+1) neg.ind = (pi.fac.seq<0)[key.marks+1] pos.ind = (pi.fac.seq>0)[key.marks+1] pi.fac = formatC(abs(pi.fac.seq), digits = legend.params$label.digits, format = legend.params$label.format)[key.marks+1] inner.key.labels = NULL for (label.i in (2:(legend.params$n.ticks-1))) { pi.fac.i = pi.fac[label.i] if (neg.ind[label.i] == TRUE) { inner.key.labels = c( inner.key.labels, bquote(-.(pi.fac.i)*pi)) } if ((neg.ind[label.i] == FALSE) & (pos.ind[label.i] == FALSE)) { inner.key.labels = c( inner.key.labels, 0) } if ((neg.ind[label.i] == FALSE) & (pos.ind[label.i] == TRUE)) { inner.key.labels = c( inner.key.labels, bquote(.(pi.fac.i)*pi)) } } key.labels = c(expression(-pi), inner.key.labels, expression(pi)) } image(1, seq(from = 0, to = n.levels), matrix(phasediff.levels, nrow=1), col = key.cols, breaks = phasediff.levels, useRaster=T, xaxt='n', yaxt='n', xlab='', ylab='') axis(4, lwd=lwd.axis, at=key.marks, labels=NA, tck=0.02, tcl=(par()$usr[2]-par()$usr[1])*legend.params$width-0.04) mtext(key.labels, side = 4, at = key.marks, adj=1, line = 0.5 + ( 1 + 0.5*legend.params$label.digits + line.add)*par()$cex.axis, las=2, font = par()$font.axis, cex=par()$cex.axis) text(x = par()$usr[2] + (1.5+legend.params$lab.line)*par()$cxy[1], y=n.levels/2, labels=legend.params$lab, xpd=NA, srt = 270, font = par()$font.lab, cex=par()$cex.lab) box(lwd = lwd.axis) par(new=TRUE, plt = image.plt) } image(axis.1, axis.2, t(Angle), col = key.cols, breaks = phasediff.levels, useRaster = useRaster, ylab = "", xlab = '', axes = FALSE, main = main) if (plot.contour == T) { if (which.contour == 'wc') { W.pval = WC$Coherence.pval } if (which.contour == 'wp') { W.pval = WC$Power.xy.pval } if (is.null(W.pval) == F) { contour(axis.1, axis.2, t(W.pval) < siglvl, levels = 1, lwd = lwd, add = TRUE, col = col.contour, drawlabels = FALSE) } } if (plot.coi == T) { polygon(WC$coi.1, WC$coi.1, border = NA, col = rgb(1, 1, 1, 0.5)) } box(lwd = lwd.axis) if (label.period.axis == T) { period.axis.default = ( is.null(spec.period.axis$at) ) if ( !period.axis.default ) { if ( is.numeric(spec.period.axis$at) ) { period.axis.warning = ( ( sum(spec.period.axis$at<=0, na.rm=T)>0 ) | ( sum(!is.na(spec.period.axis$at)) != sum(is.finite(spec.period.axis$at)) ) ) } else { period.axis.warning = TRUE } if ( is.logical(spec.period.axis$labels) ) { period.axis.warning = ( period.axis.warning | ifelse(length(spec.period.axis$labels)!=1,TRUE, is.na(spec.period.axis$labels)) ) } if ( !is.logical(spec.period.axis$labels) ) { period.axis.warning = ( period.axis.warning | (length(spec.period.axis$labels) != length(spec.period.axis$at)) ) } } period.axis.default = (period.axis.default | period.axis.warning) if ( (is.null(periodlab)) | (!is.null(periodlab) & period.axis.warning) ) {periodlab='period'} if (period.axis.default) { period.tick = unique(trunc(axis.2)) period.tick[period.tick<log2(WC$Period[1])] = NA period.tick = na.omit(period.tick) period.tick.label = 2^(period.tick) axis(2, lwd = lwd.axis, at = period.tick, labels = NA, tck=periodtck, tcl=periodtcl) axis(4, lwd = lwd.axis, at = period.tick, labels = NA, tck=periodtck, tcl=periodtcl) mtext(period.tick.label, side = 2, at = period.tick, las = 1, line = par()$mgp[2]-0.5, font = par()$font.axis, cex=par()$cex.axis) } if (!period.axis.default) { period.tick = log2(spec.period.axis$at) period.tick[(period.tick<log2(WC$Period[1]))] = NA period.tick.label = spec.period.axis$labels which.na = which(is.na(period.tick)) if ( length(which.na)>0 ) { period.axis.warning.na = T } if ( is.logical(period.tick.label) ) { if (period.tick.label == T) { period.tick.label = 2^(period.tick) } } axis(2, lwd = lwd.axis, at = period.tick, labels = period.tick.label, tck=periodtck, tcl=periodtcl, las = spec.period.axis$las, hadj = spec.period.axis$hadj, padj=spec.period.axis$padj, mgp = par()$mgp - c(0,0.5,0), font = par()$font.axis, cex.axis=par()$cex.axis) axis(4, lwd = lwd.axis, at = period.tick, labels = NA, tck=periodtck, tcl=periodtcl) } mtext(periodlab, side = 2, line = par()$mgp[1]-0.5, font = par()$font.lab, cex=par()$cex.lab) } if (label.time.axis == T) { time.axis.default = ( is.null(spec.time.axis$at) ) if (show.date==T) { if (is.element('date',names(series.data))) { my.date = series.data$date } else { my.date = rownames(series.data) } if (is.null(date.format)) { chronology.warning = inherits(try(as.Date(my.date, tz=date.tz), silent=T),'try-error') if (!chronology.warning) { my.date = as.Date(my.date, tz=date.tz) chronology.warning = ifelse( sum(is.na(my.date))> 0, TRUE, sum(diff(my.date, tz=date.tz)<0)>0 ) } } if (!is.null(date.format)) { chronology.warning = inherits(try(as.POSIXct(my.date, format=date.format, tz=date.tz), silent=T),'try-error') if (!chronology.warning) { my.date = as.POSIXct(my.date, format=date.format, tz=date.tz) chronology.warning = ifelse( sum(is.na(my.date))> 0, TRUE, sum(diff(my.date, tz=date.tz)<0)>0 ) } } if (chronology.warning) { show.date = F time.axis.default = T timelab = 'index' } } if ( !time.axis.default ) { if (show.date==F) { time.axis.warning = (!is.numeric(spec.time.axis$at)) } if (show.date==T) { if (is.null(date.format)) { time.axis.warning = inherits(try(as.Date(spec.time.axis$at, tz=date.tz), silent=T), 'try-error') if (!time.axis.warning) { time.axis.warning = (sum(!is.na(as.Date(spec.time.axis$at, tz=date.tz)))==0) } } if (!is.null(date.format)) { time.axis.warning = inherits(try(as.POSIXct(spec.time.axis$at, format=date.format, tz=date.tz), silent=T),'try-error') if (!time.axis.warning) { time.axis.warning = (sum(!is.na(as.POSIXct(spec.time.axis$at, format=date.format, tz=date.tz)))==0) } } } if (!time.axis.warning) { if ( is.logical(spec.time.axis$labels) ) { time.axis.warning = ( ifelse(length(spec.time.axis$labels)!=1,TRUE, is.na(spec.time.axis$labels)) ) } if (!is.logical(spec.time.axis$labels)) { time.axis.warning = ( length(spec.time.axis$labels) != length(spec.time.axis$at) ) } } } time.axis.default = (time.axis.default | time.axis.warning) } half.increment.2 = (axis.2[2]-axis.2[1])/2 my.ylim = c(min(axis.2)-half.increment.2, max(axis.2)+half.increment.2) index.condition = ( (show.date==F) | (label.time.axis==F) ) if ((WC$dt != 1) & (index.condition)) { par(new=TRUE) plot(1:WC$nc, seq(min(axis.2),max(axis.2), length.out=WC$nc), xlim = c(0.5,WC$nc+0.5), ylim = my.ylim, type="n", xaxs = "i", yaxs ='i', xaxt='n', yaxt='n', xlab="", ylab="") } if (label.time.axis == T) { if ( (is.null(timelab) & time.axis.default) | (!is.null(timelab) & time.axis.warning) ) {timelab=ifelse(show.date, 'calendar date','index')} if (show.date == F) { if (time.axis.default) { A.1 = axis(1, lwd = lwd.axis, labels=NA, tck = timetck, tcl = timetcl) mtext(A.1, side = 1, at = A.1, line = par()$mgp[2]-0.5, font = par()$font.axis, cex=par()$cex.axis) } if (!time.axis.default) { time.tick = spec.time.axis$at time.tick.label = spec.time.axis$labels which.na = which(is.na(time.tick)) if ( length(which.na)>0 ) { time.axis.warning.na = T } axis(1, lwd = lwd.axis, at=time.tick, labels=time.tick.label, tck = timetck, tcl = timetcl, las = spec.time.axis$las, hadj = spec.time.axis$hadj, padj=spec.time.axis$padj, mgp = par()$mgp - c(0,0.5,0), font = par()$font.axis, cex.axis=par()$cex.axis) } mtext(timelab, side = 1, line = par()$mgp[1]-1, font = par()$font.lab, cex=par()$cex.lab) } if (show.date == T) { half.increment = difftime(my.date[2],my.date[1], tz=date.tz)/2 if (is.null(date.format)) { my.xlim = as.Date(range(my.date) - c(half.increment,-half.increment),tz=date.tz) } else { my.xlim = as.POSIXct(range(my.date) - c(half.increment,-half.increment),format=date.format, tz=date.tz) } par(new=TRUE) if (time.axis.default) { plot(my.date, seq(min(axis.2),max(axis.2), length.out=WC$nc), xlim = my.xlim, ylim = my.ylim, type="n", xaxs = "i", yaxs ='i', yaxt='n', xlab="", ylab="", lwd = lwd.axis, tck=timetck, tcl=timetcl, mgp = par()$mgp - c(0,0.5,0), font = par()$font.axis, cex.axis=par()$cex.axis) } if (!time.axis.default) { plot(my.date, seq(min(axis.2),max(axis.2), length.out=WC$nc), xlim = my.xlim, ylim = my.ylim, type="n", xaxs = "i", yaxs ='i', xaxt='n', yaxt='n', xlab="", ylab="") if (is.null(date.format)) { time.tick = as.Date(spec.time.axis$at, tz=date.tz) } if (!is.null(date.format)) { time.tick = as.POSIXct(spec.time.axis$at, format=date.format, tz=date.tz) } time.tick.label = spec.time.axis$labels which.na = which(is.na(time.tick)) if ( length(which.na)>0 ) { time.axis.warning.na = T } if ( is.logical(time.tick.label) ) { if (time.tick.label == T) {time.tick.label = time.tick} } axis(1, lwd = lwd.axis, at=time.tick, labels=time.tick.label, tck = timetck, tcl = timetcl, las = spec.time.axis$las, hadj = spec.time.axis$hadj, padj=spec.time.axis$padj, mgp = par()$mgp - c(0,0.5,0), font = par()$font.axis, cex.axis=par()$cex.axis) } mtext(timelab, side = 1, line = par()$mgp[1]-1, font = par()$font.lab, cex=par()$cex.lab) } } options(default.options) if (graphics.reset == T) { par(op) } if (chronology.warning) { warning("\nPlease check your calendar dates, format and time zone: dates may not be in an unambiguous format or chronological. The default numerical axis was used instead.") } if (period.axis.warning == T) { warning("\nPlease check your period axis specifications. Default settings were used.") } if (period.axis.warning.na == T) { warning("\nNAs were produced with your period axis specifications.") } if (time.axis.warning == T) { warning("\nPlease check your time axis specifications. Default settings were used.") } if (time.axis.warning.na == T) { warning("\nNAs were produced with your time axis specifications.") } output = list(op = op, image.plt = image.plt, legend.plt=legend.plt) class(output) = "graphical parameters" out("Class attributes are accessible through following names:\n") out(names(output), "\n") return(invisible(output)) }
gradeAllBus<- function(scores, z, zip.cutoffs){ X<- as.numeric(scores) z<- as.character(z) zip.cutoffs<- as.data.frame(zip.cutoffs) if(length(X) != length(z)) stop("length of X and length of z do not match!") all.bus.grades<- lapply(1:length(X), FUN = function(i) gradeBus(scores[i], z[i], zip.cutoffs)) return(as.character(all.bus.grades)) } gradeBus<- function(x.bar.i, z.i, zip.cutoffs){ x.bar.i<- as.numeric(x.bar.i) z.i<- as.character(z.i) zip.cutoffs<- as.data.frame(zip.cutoffs) if(ncol(zip.cutoffs) >= 3){ for(j in 2:(ncol(zip.cutoffs)-1)){ if(FALSE %in% (as.numeric(zip.cutoffs[,c(j)]) <= as.numeric(zip.cutoffs[,c(j+1)]))) stop("incorrect specification of ZIP code cutoff frame - cutoffs are not ordered from lowest to highest for each ZIP!") } } zip.of.interest<- zip.cutoffs[which(zip.cutoffs[,c(1)] == z.i),] no.grades<- ncol(zip.cutoffs) if(is.na(z.i)==TRUE){ bus.grade=NA } else if(is.na(x.bar.i)==TRUE){ bus.grade= NA } else{ letter.index<-match(TRUE, x.bar.i<= as.numeric(zip.of.interest[,c(2:ncol(zip.cutoffs))]), nomatch = ncol(zip.cutoffs)) bus.grade<- LETTERS[letter.index] } return(bus.grade) }
venn.diagram.crispr<- function (x, filename=NULL, height = 3000, width = 3000, resolution = 500, imagetype = "tiff", units = "px", compression = "lzw", na = "stop", main = NULL, sub = NULL, main.pos = c(0.5, 1.05), main.fontface = "plain", main.fontfamily = "serif", main.col = "black", main.cex = 1, main.just = c(0.5, 1), sub.pos = c(0.5, 1.05), sub.fontface = "plain", sub.fontfamily = "serif", sub.col = "black", sub.cex = 1, sub.just = c(0.5, 1), category.names = names(x), force.unique = TRUE, ...) { VennDiagram::venn.diagram(...) }
context("Generate SSL Data") test_that("generateFourClusters does not return error",{ library(ggplot2) data <- generateFourClusters() expect_silent(ggplot(data,aes(x=X1,y=X2,color=Class)) + geom_point()) }) test_that("generateCrescentMoon does not return error",{ library(ggplot2) data <- generateCrescentMoon() expect_silent(ggplot(data,aes(x=X1,y=X2,color=Class)) + geom_point()) }) test_that("generate2ClassGaussian does not return error",{ library(ggplot2) data <- generate2ClassGaussian() expect_silent(ggplot(data,aes(x=X1,y=X2,color=Class)) + geom_point()) }) test_that("generateTwoCircles does not return error",{ library(ggplot2) data <- generateTwoCircles() expect_silent(ggplot(data,aes(x=X1,y=X2,color=Class)) + geom_point()) })
generateRandomDesign = function(n = 10L, par.set, trafo = FALSE) { doBasicGenDesignChecks(par.set) des = sampleValues(par.set, n, discrete.names = TRUE, trafo = trafo) elementsToDf = function(x) { Map(function(p, v) { if (isScalarNA(v)) { v = as.data.frame(t(rep(v, p$len)), stringsAsFactors = TRUE) } else { as.data.frame(t(v), stringsAsFactors = TRUE) } }, par.set$pars, x) } des = lapply(des, elementsToDf) des = lapply(des, do.call, what = cbind) des = do.call(rbind, des) colnames(des) = getParamIds(par.set, repeated = TRUE, with.nr = TRUE) des = fixDesignFactors(des, par.set) attr(des, "trafo") = trafo return(des) }
html_vignette <- function(fig_width = 6, fig_height = 6, dev = 'png', css = NULL, ...) { if (is.null(css)) { css <- system.file("rmarkdown", "templates", "html_vignette" ,"resources", "vignette.css", package = "rmarkdown") } html_document(fig_width = fig_width, fig_height = fig_height, dev = dev, fig_retina = FALSE, css = css, theme = NULL, highlight = "pygments", ...) } options(repos = c(CRAN="http://cran.r-project.org")) if("caRpools" %in% rownames(installed.packages()) == FALSE) {install.packages("caRpools")} library(caRpools,warn.conflicts = FALSE, quietly = TRUE,verbose =FALSE) load.packages() data(caRpools) CONTROL1.g.annotate=aggregatetogenes(data.frame = CONTROL1, agg.function=sum, extractpattern = expression("^(.+?)(_.+)"), type="annotate") knitr::kable(CONTROL1.g.annotate[1:10,]) CONTROL1.replaced = get.gene.info(CONTROL1, namecolumn=1, host="www.ensembl.org", extractpattern=expression("^(.+?)(_.+)"), database="ENSEMBL_MART_ENSEMBL", dataset="hsapiens_gene_ensembl", filters="hgnc_symbol", attributes =c("ensembl_gene_id"), return.val = "dataset") knitr::kable(CONTROL1.replaced[1:10,]) CONTROL1.replaced.info = get.gene.info(CONTROL1, namecolumn=1, host="www.ensembl.org", extractpattern=expression("^(.+?)(_.+)"), database="ENSEMBL_MART_ENSEMBL", dataset="hsapiens_gene_ensembl", filters="hgnc_symbol", attributes = c("ensembl_gene_id","description"), return.val = "info") knitr::kable(CONTROL1.replaced.info[1:10,]) U1.stats = stats.data(dataset=CONTROL1, namecolumn = 1, fullmatchcolumn = 2, extractpattern=expression("^(.+?)_.+"), type="stats") U2.stats = stats.data(dataset=CONTROL2, namecolumn = 1, fullmatchcolumn = 2, extractpattern=expression("^(.+?)_.+"), type="stats") T1.stats =stats.data(dataset=TREAT1, namecolumn = 1, fullmatchcolumn = 2, extractpattern=expression("^(.+?)_.+"), type="stats") T2.stats =stats.data(dataset=TREAT2, namecolumn = 1, fullmatchcolumn = 2, extractpattern=expression("^(.+?)_.+"), type="stats") combined.stats = cbind.data.frame(U1.stats[,1:2], U2.stats[,2], T1.stats[,2], T2.stats[,2]) colnames(combined.stats) = c("Readcount", d.CONTROL1, d.CONTROL2, d.TREAT1, d.TREAT2) knitr::kable(stats.data(dataset=CONTROL1, namecolumn = 1, fullmatchcolumn = 2, extractpattern=expression("^(.+?)_.+"), readcount.unmapped.total = 1786217, type="mapping")) knitr::kable(stats.data(dataset=CONTROL1, namecolumn = 1, fullmatchcolumn = 2, extractpattern=expression("^(.+?)_.+"), readcount.unmapped.total = 1786217, type="stats")) knitr::kable(stats.data(dataset=CONTROL1, namecolumn = 1, fullmatchcolumn = 2, extractpattern=expression("^(.+?)_.+"), readcount.unmapped.total = 1786217, type="dataset")[1:10,1:5]) U1.unmapped = unmapped.genes(data=CONTROL1, namecolumn=1, fullmatchcolumn=2, genes=NULL, extractpattern=expression("^(.+?)_.+")) xlsx::write.xlsx(U1.unmapped, file="DROPOUT.xls", sheetName=d.CONTROL1, row.names=FALSE) U1.unmapped = unmapped.genes(data=CONTROL1, namecolumn=1, fullmatchcolumn=2, genes="random", extractpattern=expression("^(.+?)_.+")) carpools.read.distribution(CONTROL1, fullmatchcolumn=2,breaks=200, title=d.CONTROL1, xlab="log2 Readcount", ylab=" carpools.read.distribution(CONTROL1, fullmatchcolumn=2,breaks=200, title=d.CONTROL1, xlab="log2 Readcount", ylab=" type="whisker") carpools.read.distribution(CONTROL1, fullmatchcolumn=2,breaks=200, title=d.CONTROL1, xlab="log2 Readcount", ylab=" carpools.read.depth(datasets = list(CONTROL1), namecolumn=1 ,fullmatchcolumn=2, dataset.names=list(d.CONTROL1), extractpattern=expression("^(.+?)_.+"), xlab="Genes", ylab="Read Count per sgRNA",statistics=TRUE, labelgenes = NULL, controls.target = "CASP8", controls.nontarget="random", waterfall=FALSE) carpools.read.depth(datasets = list(CONTROL1), namecolumn=1 ,fullmatchcolumn=2, dataset.names=list(d.CONTROL1), extractpattern=expression("^(.+?)_.+"), xlab="Genes", ylab="Read Count per sgRNA",statistics=TRUE, labelgenes = NULL, controls.target = "CASP8", controls.nontarget="random", waterfall=TRUE) control1.readspergene = carpools.reads.genedesigns(CONTROL1, namecolumn=1, fullmatchcolumn=2, title=paste("% sgRNAs:", d.CONTROL1, sep=" "), xlab="% of sgRNAs present", ylab=" carpools.read.count.vs(dataset=list(TREAT1,CONTROL1), dataset.names = c(d.TREAT1, d.CONTROL1), pairs=FALSE, namecolumn=1, fullmatchcolumn=2, title="", pch=16, normalize=TRUE, norm.function=median, labelgenes="random", labelcolor="blue", center=FALSE, aggregated=FALSE) carpools.read.count.vs(dataset=list(TREAT1,CONTROL1), dataset.names = c(d.TREAT1, d.CONTROL1), pairs=FALSE, namecolumn=1, fullmatchcolumn=2, title="", pch=16, normalize=TRUE, norm.function=median, labelgenes="random", labelcolor="blue", center=TRUE, aggregated=FALSE) carpools.read.count.vs(dataset=list(TREAT1.g,CONTROL1.g), dataset.names = c(d.TREAT1, d.CONTROL1), pairs=FALSE, namecolumn=1, fullmatchcolumn=2, title="", pch=16, normalize=TRUE, norm.function=median, labelgenes="CASP8", labelcolor="red", center=FALSE, aggregated=TRUE) carpools.read.count.vs(dataset=list(TREAT1, TREAT2, CONTROL1, CONTROL2), dataset.names = c(d.TREAT1, d.TREAT2, d.CONTROL1, d.CONTROL2), pairs=TRUE, namecolumn=1, fullmatchcolumn=2, title="", pch=16, normalize=TRUE, norm.function=median, labelgenes="random", labelcolor="blue", center=FALSE, aggregated=FALSE) carpools.read.count.vs(dataset=list(TREAT1.g, TREAT2.g, CONTROL1.g, CONTROL2.g), dataset.names = c(d.TREAT1, d.TREAT2, d.CONTROL1, d.CONTROL2), pairs=TRUE, namecolumn=1, fullmatchcolumn=2, title="", pch=16, normalize=TRUE, norm.function=median, labelgenes="CASP8", labelcolor="blue", center=FALSE, aggregated=TRUE) p1 = carpools.raw.genes(untreated.list = list(CONTROL1, CONTROL2), treated.list = list(TREAT1, TREAT2), genes="CASP8", namecolumn=1, fullmatchcolumn=2, norm.function=median, extractpattern=expression("^(.+?)_.+"), do.plot=TRUE, log=FALSE, put.names=TRUE, type="foldchange" ) p2 = carpools.raw.genes(untreated.list = list(CONTROL1, CONTROL2), treated.list = list(TREAT1, TREAT2), genes="CASP8", namecolumn=1, fullmatchcolumn=2, norm.function=median, extractpattern=expression("^(.+?)_.+"), do.plot=TRUE, log=FALSE, put.names=TRUE, type="z-ratio" ) p3 = carpools.raw.genes(untreated.list = list(CONTROL1, CONTROL2), treated.list = list(TREAT1, TREAT2), genes="CASP8", namecolumn=1, fullmatchcolumn=2, norm.function=median, extractpattern=expression("^(.+?)_.+"), do.plot=TRUE, log=FALSE, put.names=TRUE, type="readcount" ) p4 = carpools.raw.genes(untreated.list = list(CONTROL1, CONTROL2), treated.list = list(TREAT1, TREAT2), genes="CASP8", namecolumn=1, fullmatchcolumn=2, norm.function=median, extractpattern=expression("^(.+?)_.+"), do.plot=TRUE, log=FALSE, put.names=TRUE, type="vioplot" ) data.wilcox = stat.wilcox(untreated.list = list(CONTROL1, CONTROL2), treated.list = list(TREAT1,TREAT2), namecolumn=1, fullmatchcolumn=2, normalize=TRUE, norm.fun=median, sorting=FALSE, controls="random", control.picks=NULL) data.deseq = stat.DESeq(untreated.list = list(CONTROL1, CONTROL2), treated.list = list(TREAT1,TREAT2), namecolumn=1, fullmatchcolumn=2, extractpattern=expression("^(.+?)(_.+)"), sorting=FALSE, filename.deseq = "ANALYSIS-DESeq2-sgRNA.tab", fitType="parametric") data.mageck = stat.mageck(untreated.list = list(CONTROL1, CONTROL2), treated.list = list(TREAT1,TREAT2), namecolumn=1, fullmatchcolumn=2, norm.fun="median", extractpattern=expression("^(.+?)(_.+)"), mageckfolder=NULL, sort.criteria="neg", adjust.method="fdr", filename = "TEST" , fdr.pval = 0.05) carpools.waterfall.pval(type="mageck", dataset=data.mageck, pval=0.05, log=TRUE) mageck.result = carpools.hitident(data.mageck, type="mageck", title="MAGeCK", inches=0.1, print.names=TRUE, plot.p=0.05, offsetplot=1.2, sgRNA.top=1) wilcox.result = carpools.hitident(data.wilcox, type="wilcox", title="Wilcox", inches=0.1, print.names=TRUE, plot.p=0.05, offsetplot=1.2, sgRNA.top=1) carpools.hit.overview(wilcox=data.wilcox, deseq=data.deseq, mageck=data.mageck, cutoff.deseq = 0.001, cutoff.wilcox = 0.05, cutoff.mageck = 0.05, cutoff.override=FALSE, cutoff.hits=NULL, plot.genes="overlapping", type="enriched") venn.enriched = compare.analysis(wilcox=data.wilcox, deseq=data.deseq, mageck=data.mageck, type="enriched", cutoff.deseq = 0.001, cutoff.wilcox = 0.05, cutoff.mageck = 0.05, cutoff.override=FALSE, cutoff.hits=NULL, output="venn") require(VennDiagram) plot.new() grid::grid.draw(VennDiagram::venn.diagram(venn.enriched, file=NULL, fill=c("lightgreen","lightblue2","lightgray"), na="remove", cex=2,lty=2, cat.cex=2)) data.analysis.enriched = compare.analysis(wilcox=data.wilcox, deseq=data.deseq, mageck=data.mageck, type="enriched", cutoff.override = FALSE, cutoff.hits=NULL, output="list", sort.by=c("mageck","fdr","rank")) xlsx::write.xlsx(data.analysis.enriched, file="COMPARE-HITS.xls", sheetName="Enriched") knitr::kable(data.analysis.enriched[1:10,c(2:7)]) data.analysis.enriched = compare.analysis(wilcox=data.wilcox, deseq=data.deseq, mageck=data.mageck, type="enriched", cutoff.override = FALSE, cutoff.hits=NULL, output="rank", sort.by=c("mageck","fdr","rank")) xlsx::write.xlsx(data.analysis.enriched, file="COMPARE-RANKs.xls", sheetName="Enriched") knitr::kable(data.analysis.enriched[1:10,]) compared = compare.analysis( wilcox=data.wilcox, deseq=data.deseq, mageck=data.mageck, type="enriched", cutoff.deseq = 0.001, cutoff.wilcox = 0.05, cutoff.mageck = 0.05, cutoff.override=FALSE, cutoff.hits=NULL, output="3dplot", sort.by=c("mageck","rank","rank"), plot.method=c("wilcox","deseq","mageck"), plot.feature=c("pval","pval","fdr")) final.tab = final.table(wilcox=data.wilcox, deseq=data.deseq, mageck=data.mageck, dataset=CONTROL1.g, namecolumn=1, type="genes") xlsx::write.xlsx(final.tab, "FINAL.xls", sheetName="Genelist", col.names=TRUE, row.names=FALSE, append=FALSE, showNA=TRUE) overlap.enriched = generate.hits(wilcox=data.wilcox, deseq=data.deseq, mageck=data.mageck, type="enriched", cutoff.deseq = 0.001, cutoff.wilcox = 0.05, cutoff.mageck = 0.05, cutoff.override=FALSE, cutoff.hits=NULL , plot.genes="overlapping") plothitsscatter.enriched = carpools.hit.scatter(wilcox=data.wilcox, deseq=data.deseq, mageck=data.mageck, dataset=list(TREAT1, TREAT2, CONTROL1, CONTROL2), dataset.names = c(d.TREAT1, d.TREAT2, d.CONTROL1, d.CONTROL2), namecolumn=1, fullmatchcolumn=2, title="Title", labelgenes="CASP8", labelcolor="orange", extractpattern=expression("^(.+?)(_.+)"), normalize=TRUE, norm.function=median, offsetplot=1.2, center=FALSE, aggregated=FALSE, type="enriched", cutoff.deseq = 0.001, cutoff.wilcox = 0.05, cutoff.mageck = 0.05, cutoff.override=FALSE, cutoff.hits=NULL, pch=16) sgrnas.en = carpools.hit.sgrna(wilcox=data.wilcox, deseq=data.deseq, mageck=data.mageck, dataset=list(CONTROL1, CONTROL2, TREAT1, TREAT2), dataset.names = c(d.CONTROL1, d.CONTROL2, d.TREAT1, d.TREAT2), namecolumn=1, fullmatchcolumn=2, norm.function=median, extractpattern=expression("^(.+?)(_.+)"), put.names=TRUE, type="enriched", labelgenes="CASP8", plot.type=NULL, cutoff.deseq = 0.001, cutoff.wilcox=0.05, cutoff.mageck = 0.05, cutoff.override=FALSE, cutoff.hits=NULL, controls.target="CASP8", controls.nontarget="random") sgrnas.en.table = carpools.sgrna.table(wilcox=data.wilcox, deseq=data.deseq, mageck=data.mageck, dataset=list(CONTROL1, CONTROL2, TREAT1, TREAT2), dataset.names = c(d.CONTROL1, d.CONTROL2, d.TREAT1, d.TREAT2), namecolumn=1, fullmatchcolumn=2, norm.function=median, extractpattern=expression("^(.+?)(_.+)"), type="enriched", labelgenes="CASP8", cutoff.deseq = 0.001, cutoff.wilcox=0.05, cutoff.mageck = 0.05, cutoff.override=FALSE, cutoff.hits=NULL, sgrna.file = libFILE, write=FALSE)
check.type.one.var <- function(data.to.work, show.message=0, variable.name) { typeVars <- vector(mode = "numeric", length = 4) commandAssign <- paste("typeVars[1] <- length(sapply(data.to.work$", variable.name,", is.character)[sapply(data.to.work$", variable.name,", is.character)==TRUE])", sep = "") eval(parse(text=commandAssign)) commandAssign <- paste("typeVars[2] <- length(sapply(data.to.work$", variable.name,", is.integer)[sapply(data.to.work$", variable.name,", is.numeric)==TRUE])", sep = "") eval(parse(text=commandAssign)) commandAssign <- paste("typeVars[3] <- length(sapply(data.to.work$", variable.name,", is.numeric)[sapply(data.to.work$", variable.name,", is.numeric)==TRUE])", sep = "") eval(parse(text=commandAssign)) commandAssign <- paste("typeVars[4] <- length(sapply(data.to.work$", variable.name,", is.factor)[sapply(data.to.work$", variable.name,", is.factor)==TRUE])", sep = "") eval(parse(text=commandAssign)) result.type <- 0 if (typeVars[1] > 0) { result.type <- 8 } else if (typeVars[2] > 0) { result.type <- 1 } else if (typeVars[3] > 0) { if (check.dichotomic.one.var(data.to.work, variable.name) == TRUE) { result.type <- 9 } else { result.type <- 2 } } else if (typeVars[4] > 0) { result.type <- 3 } return(result.type) }
context("is-methods") invisible(linting_opts(suppress_pkgcheck_warnings = TRUE)) test_that("is-methods", { expect_is(is_generator, "function") expect_is(is.point, "function") expect_is(is.multipoint, "function") expect_is(is.linestring, "function") expect_is(is.multilinestring, "function") expect_is(is.polygon, "function") expect_is(is.multipolygon, "function") expect_is(is.feature, "function") expect_is(is.featurecollection, "function") expect_is(is.geometrycollection, "function") pt <- point('{ "type": "Point", "coordinates": [100.0, 0.0] }') mpt <- multipoint('{"type": "MultiPoint", "coordinates": [ [100.0, 0.0], [101.0, 1.0] ] }') ls <- linestring('{ "type": "LineString", "coordinates": [ [100.0, 0.0], [101.0, 1.0] ] }') x <- '{ "type": "MultiLineString", "coordinates": [ [ [100.0, 0.0], [101.0, 1.0] ], [ [102.0, 2.0], [103.0, 3.0] ] ] }' mls <- multilinestring(x) x <- '{ "type": "Polygon", "coordinates": [ [ [100.0, 0.0], [100.0, 1.0], [101.0, 1.0], [101.0, 0.0], [100.0, 0.0] ] ] }' pg <- polygon(x) x <- '{ "type": "MultiPolygon", "coordinates": [ [[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]], [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]], [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]] ] }' mpg <- multipolygon(x) ft <- feature(pt) fc <- featurecollection(geojson_data$polygons_within) x <- '{ "type": "GeometryCollection", "geometries": [ { "type": "Point", "coordinates": [100.0, 0.0] }, { "type": "LineString", "coordinates": [ [101.0, 0.0], [102.0, 1.0] ] } ] }' gc <- geometrycollection(x) expect_null(is.point(pt)) expect_null(is.multipoint(mpt)) expect_null(is.linestring(ls)) expect_null(is.multilinestring(mls)) expect_null(is.polygon(pg)) expect_null(is.multipolygon(mpg)) expect_null(is.feature(ft)) expect_null(is.featurecollection(fc)) expect_null(is.geometrycollection(gc)) }) test_that("is-methods fail well", { expect_error(is_generator(), "argument \"x\" is missing") expect_error(is.point(), "argument \"x\" is missing") expect_error(is.multipoint(), "argument \"x\" is missing") expect_error(is.linestring(), "argument \"x\" is missing") expect_error(is.multilinestring(), "argument \"x\" is missing") expect_error(is.polygon(), "argument \"x\" is missing") expect_error(is.multipolygon(), "argument \"x\" is missing") expect_error(is.feature(), "argument \"x\" is missing") expect_error(is.featurecollection(), "argument \"x\" is missing") expect_error(is.geometrycollection(), "argument \"x\" is missing") expect_error(is.point("foobar"), "x must be of class 'geopoint'") expect_error(is.multipoint("foobar"), "x must be of class 'geomultipoint'") expect_error(is.linestring("foobar"), "x must be of class 'geolinestring'") expect_error(is.multilinestring("foobar"), "x must be of class 'geomultilinestring'") expect_error(is.polygon("foobar"), "x must be of class 'geopolygon'") expect_error(is.multipolygon("foobar"), "x must be of class 'geomultipolygon'") expect_error(is.feature("foobar"), "x must be of class 'geofeature'") expect_error(is.featurecollection("foobar"), "x must be of class 'geofeaturecollection'") expect_error(is.geometrycollection("foobar"), "x must be of class 'geogeometrycollection'") })
context("Negative binomial regression") set.seed(1, kind="Mersenne-Twister", normal.kind="Inversion") n <- 1000L r <- 0.17 df <- data.frame(x1=rnorm(n), x2=runif(n)) mod <- ~ reg(~ 1 + x1 + x2, b0=c(3, 1, 0.5), Q0=1e10*diag(3), name="beta") dat <- generate_data(mod, family="negbinomial", ry=r, r.mod=pr_fixed(value=1), data=df) test_that("fitting a negative binomial model works", { sampler <- create_sampler(dat$y ~ reg(~ 1 + x1 + x2, name="beta"), data=df, family="negbinomial", ry=r, r.mod=pr_fixed(value=1)) sim <- MCMCsim(sampler, n.iter=400L, burnin=150L, n.chain=2L, verbose=FALSE) summ <- summary(sim) expect_equivalent(summ$beta[, "Mean"], dat$pars$beta, tol=0.5) DIC <- compute_DIC(sim) WAIC <- compute_WAIC(sim) expect_true(abs((DIC["DIC"] - WAIC["WAIC2"])/abs(DIC["DIC"])) < 0.05) pred <- as.matrix(predict(sim, type="response", iters=1:100, show.progress=FALSE)) expect_equivalent(r*mean(pred/(1 - pred)), mean(dat$y), tol=2) }) test_that("fitting a negative binomial model with scaled beta prime prior on dispersion parameter works", { sampler <- create_sampler(dat$y ~ x1 + x2, data=df, family="negbinomial", r.mod=pr_invchisq(df=1, scale="modeled")) sim <- MCMCsim(sampler, n.iter=400L, burnin=150L, n.chain=2L, verbose=FALSE) summ <- summary(sim) expect_true(abs(summ$negbin_r_[, "Mean"] - r) < 0.05) compute_DIC(sim) }) test_that("fitting a negative binomial model with chi-squared prior on dispersion parameter works", { sampler <- create_sampler(dat$y ~ x1 + x2, data=df, family="negbinomial", r.mod=pr_invchisq(df=1, scale=1)) sim <- MCMCsim(sampler, n.iter=400L, burnin=150L, n.chain=2L, verbose=FALSE) summ <- summary(sim) expect_true(abs(summ$negbin_r_[, "Mean"] - r) < 0.05) compute_DIC(sim) }) test_that("fitting a negative binomial model with GIG prior on dispersion parameter works", { sampler <- create_sampler(dat$y ~ x1 + x2, data=df, family="negbinomial", r.mod=pr_gig(a=0, b=1, p=-1/2)) sim <- MCMCsim(sampler, n.iter=400L, burnin=150L, n.chain=2L, verbose=FALSE) summ <- summary(sim) expect_true(abs(summ$negbin_r_[, "Mean"] - r) < 0.05) compute_DIC(sim) }) test_that("fitting a negative binomial model with dispersion parameter fixed by prior works", { sampler <- create_sampler(dat$y ~ x1 + x2, data=df, family="negbinomial", r.mod=pr_fixed(value=1/r)) expect_true(all(replicate(10, sampler$rprior()$negbin_r_) == r)) sim <- MCMCsim(sampler, n.iter=400L, burnin=150L, n.chain=2L, verbose=FALSE) summ <- summary(sim) expect_true(abs(summ$negbin_r_[, "Mean"] - r) < 0.05) compute_DIC(sim) }) n <- 1000L r <- 1 df <- data.frame(x1=rnorm(n), x2=runif(n), f=factor(sample(1:25, n, replace=TRUE))) mod <- ~ reg(~ 1 + x1 + x2, b0=c(3, 1, 0.5), Q0=1e10*diag(3), name="beta") + gen(factor=~f, prior=pr_invchisq(df=1000, scale=0.1), name="v") ry <- c(rep.int(1, 500), rep.int(5, 500)) dat <- generate_data(mod, family="negbinomial", ry=ry, r.mod=pr_fixed(value=1/r), data=df) test_that("prediction works well for negative binomial data", { s <- 1:500 sampler <- create_sampler(dat$y[s] ~ x1 + x2 + gen(factor=~f), data=df[s, ], family="negbinomial", ry=ry[s], block=TRUE) sim <- MCMCsim(sampler, n.iter=500L, burnin=200L, n.chain=2L, store.all=TRUE, start=list(list(negbin_r_=2), list(negbin_r_=3)), verbose=FALSE) summ <- summary(sim) expect_true(abs(summ$negbin_r_[, "Mean"] - r) < 0.25) sn <- 501:1000 pred <- predict(sim, newdata=df[sn, ], ry=ry[sn], fun.=function(x) sum(x), show.progress=FALSE) summ <- summary(pred) expect_true(abs(summ[, "Mean"] - sum(dat$y[sn])) < 50000) })
widals.predict <- function(Z, Hs, Ht, Hst.ls, locs, lags, b.lag, Hs0, Hst0.ls, locs0, geodesic=FALSE, wrap.around=NULL, GP, stnd.d=FALSE, ltco=-16) { tau <- nrow(Z) n <- nrow(locs) k <- length(lags) n0 <- nrow(locs0) rho <- GP[ 1 ] reg <- GP[ 2 ] alpha <- GP[ 3 ] beta <- GP[ 4 ] flatten <- GP[ 5 ] locs0.3D <- cbind( locs0, rep(0, n0) ) locs.long.3D <- cbind( rep(locs[ ,1], k), rep(locs[ ,2], k), beta*rep( lags, each=n ) ) z.lags.vec <- rep( lags, each=n ) ALS <- H.als.b(Z=Z, Hs=Hs, Ht=Ht, Hst.ls=Hst.ls, rho=rho, reg=reg, b.lag=b.lag, Hs0=Hs0, Ht0=Ht, Hst0.ls=Hst0.ls) Y.als <- ALS$Z.hat ; dim(Y.als) Y0.als <- ALS$Z0.hat ; dim(Y0.als) rm(ALS) Z.delta <- Z - Y.als Z.delta <- Z.clean.up( Z.delta ) Z.adj <- crispify( locs1=locs0.3D, locs2=locs.long.3D, Z.delta=Z.delta, z.lags.vec=z.lags.vec, geodesic=geodesic, alpha=alpha, flatten=flatten, self.refs=c(-1), lags=lags, stnd.d=stnd.d, log10cutoff=ltco ) Z0.wid <- Y0.als + Z.adj return(Z0.wid) }
generate_data <- function(formula) { print("generate data") df <- seq(from = -pi, to = pi, by = 0.01) %>% expand.grid(x_i = ., y_i = .) %>% dplyr::mutate(!!!formula) return(df) }
NULL .dittodb_env <- new.env(parent = emptyenv()) set_default_db_mock_paths()
material_tab_content <- function(tab_id, ...){ shiny::tagList( shiny::tags$div( class = "col s12 shiny-material-tab-content", id = tab_id, style = "visibility:hidden", ... ), shiny::singleton( shiny::includeScript( system.file("js/shiny-material-tabs.js", package = "shinymaterial") ) ) ) }
test_that("Elasticity function returns 2 for the CES_sigma_2 dataset", { elas <- elasticity(CES_sigma_2, pvar = "prices", qvar = "quantities", pervar = "time", prodID = "prodID", compIndex = "ces") expect_equal(elas$sigma, 2, tolerance = 0.0000001) })
GLVmix <- function (t, s, m, u = 30, v = 30, ...) { n <- length(t) w <- rep(1, n)/n eps <- 1e-04 if(length(m) == 1) m <- rep(m, length(t)) r <- (m - 1)/2 if (length(u) == 1) u <- seq(min(t) - eps, max(t) + eps, length = u) if (length(v) == 1) v <- seq(min(s) - eps, max(s) + eps, length = v) pu <- length(u) du <- rep(1, pu) pv <- length(v) dv <- rep(1, pv) R <- outer(r * s, v, "/") G <- outer(s * gamma(r), rep(1, pv)) r <- outer((m - 1)/2, rep(1, pv)) Av <- outer((exp(-R) * R^r)/G, rep(1,pu)) Av <- aperm(Av,c(1,3,2)) Au <- dnorm(outer(outer(t, u, "-") * outer(sqrt(m), rep(1, pu)), sqrt(v), "/")) Au <- Au/outer(outer(1/sqrt(m), rep(1, pu)), sqrt(v)) Auv <- Av * Au A <- NULL for (j in 1:pv) A <- cbind(A, Auv[, , j]) duv = as.vector(kronecker(du, dv)) f <- KWDual(A, duv, w, ...) fuv <- f$f uv <- expand.grid(alpha = u, theta = v) g <- as.vector(A %*% (duv * fuv)) logLik <- n * sum(w * log(f$g)) du <- A%*%(uv[,1] * duv * fuv)/g dv <- A %*% (uv[,2] * duv * fuv)/g z <- list(u = u, v = v, fuv = fuv, logLik = logLik, du = du, dv = dv, A = A, status = f$status) class(z) <- "GLVmix" z }
"throat.otu.tab"
zip_code <- function (n, k = 10, x = 10000:99999, prob = NULL, name = "Zip") { stopifnot(k < length(x) || k > 0) if (!is.null(prob) && length(prob) != k) stop("length of `prob` must equa `k`") out <- sample(x = lvls <- gsub("(\\w)(\\w*)", "\\U\\1\\L\\2", sample(x, k), perl=TRUE), size = n, replace = TRUE, prob = prob) varname(out, name) }
cv.boosting <- function(training.data,training.y,wt,control) { boost.rounds <- control$boost.rounds n.training <- length(training.y) cv.div <- n.training%/%5 cv.mod <- n.training%%5 error5.list <- vector("list",5) for(i in 1:5) error5.list[[i]] <- matrix(NA_real_,4,boost.rounds) samp5.cv <- sample(1:n.training,replace=FALSE) samp5.n <- rep(cv.div,5) if(cv.mod>0) samp5.n[1:cv.mod] <- samp5.n[1:cv.mod]+1 samp5.ends <- cumsum(samp5.n) samp5.starts <- c(1,samp5.ends[1:4]+1) samp5.list <- vector("list",5) for(i in 1:5) samp5.list[[i]] <- sort(samp5.cv[samp5.starts[i]:samp5.ends[i]]) training5.list <- vector("list",5) test5.list <- vector("list",5) for(i in 1:5) training5.list[[i]] <- training.data[-samp5.list[[i]],] for(i in 1:5) test5.list[[i]] <- training.data[samp5.list[[i]],] trainingy5.list <- vector("list",5) testy5.list <- vector("list",5) for(i in 1:5) trainingy5.list[[i]] <- training.y[-samp5.list[[i]]] for(i in 1:5) testy5.list[[i]] <- training.y[samp5.list[[i]]] wt5.list <- vector("list",5) for(i in 1:5) wt5.list[[i]] <- wt[-samp5.list[[i]]] for(i in 2:5) { print(paste(i,"Boosting Partitions")) control$cut.off.growth <- i for(j in 1:5) { pdfit <- run.boosting(x=training5.list[[j]],y=as.matrix(trainingy5.list[[j]]),wt=wt5.list[[j]],x.test=test5.list[[j]],y.test=testy5.list[[j]],control = control) error5.list[[j]][i-1,] <- pdfit$Test.Set.Errors } } error.5cv <- error5.list[[1]]+error5.list[[2]]+error5.list[[3]]+error5.list[[4]]+error5.list[[5]] min.5partitions <- apply(error.5cv,1,min) order.5min.partitions <- order(min.5partitions)[1] boost.5part <- order.5min.partitions+1 boost.5rounds <- order(error.5cv[order.5min.partitions,])[1] list(boost.5part=boost.5part,boost.5rounds=boost.5rounds) }
analyse_Al2O3C_ITC <- function( object, signal_integral = NULL, dose_points = c(2,4,8,12,16), recordType = c("OSL (UVVIS)"), method_control = NULL, verbose = TRUE, plot = TRUE, ... ){ if(is.list(object)){ if(!all(unique(sapply(object, class)) == "RLum.Analysis")){ stop("[analyse_Al2O3C()] All objects in the list provided by 'objects' need to be of type 'RLum.Analysis'", call. = FALSE) } if(!is.null(signal_integral)){ signal_integral <- rep(list(signal_integral, length = length(object))) } if(is(dose_points, "list")){ dose.points <- rep(dose_points, length = length(object)) }else{ dose_points <- rep(list(dose_points), length = length(object)) } results_full <- lapply(1:length(object), function(x){ results <- try(analyse_Al2O3C_ITC( object = object[[x]], signal_integral = signal_integral[[x]], dose_points = dose_points[[x]], method_control = method_control, verbose = verbose, plot = plot, main = ifelse("main"%in% names(list(...)), list(...)$main, paste0("ALQ ... )) if(inherits(results, "try-error")){ return(NULL) }else{ return(results) } }) return(merge_RLum(results_full)) } if(class(object) != "RLum.Analysis"){ stop("[analyse_Al2O3C_ITC()] 'object' needs to be of type 'RLum.Analysis'", call. = FALSE) } if(!is.null(recordType)){ object <- get_RLum(object, recordType = recordType, drop = FALSE) } method_control_settings <- list( mode = "extrapolation", fit.method = "EXP" ) if(!is.null(method_control)){ method_control_settings <- modifyList(x = method_control_settings, val = method_control) } dose_points <- rep(dose_points, times = length(object)/2) if(is.null(signal_integral)){ signal_integral <- c(1:nrow(object[[1]][])) }else{ if(min(signal_integral) < 1 | max(signal_integral) > nrow(object[[1]][])){ signal_integral <- c(1:nrow(object[[1]][])) warning( paste0( "[analyse_Al2O3C_ITC()] Input for 'signal_integral' corrected to 1:", nrow(object[[1]][]) ), call. = FALSE ) } } net_SIGNAL <- vapply(1:length(object[seq(1,length(object), by = 2)]), function(x){ temp_signal <- sum(object[seq(1,length(object), by = 2)][[x]][,2]) temp_background <- sum(object[seq(2,length(object), by = 2)][[x]][,2]) return(temp_signal - temp_background) }, FUN.VALUE = vector(mode = "numeric", length = 1)) df <- data.frame( DOSE = dose_points, net_SIGNAL = net_SIGNAL, net_SIGNAL.ERROR = 0, net_SIGNAL_NORM = net_SIGNAL/max(net_SIGNAL), net_SIGNAL_NORM.ERROR = 0 ) df_mean <- as.data.frame(data.table::rbindlist(lapply(unique(df$DOSE), function(x){ data.frame( DOSE = x, net_SIGNAL = mean(df[df$DOSE == x, "net_SIGNAL"]), net_SIGNAL.ERROR = sd(df[df$DOSE == x, "net_SIGNAL"]), net_SIGNAL_NORM = mean(df[df$DOSE == x, "net_SIGNAL_NORM"]), net_SIGNAL_NORM.ERROR = sd(df[df$DOSE == x, "net_SIGNAL_NORM"]) ) }))) GC <- plot_GrowthCurve( sample = df_mean, mode = method_control_settings$mode, output.plotExtended = FALSE, output.plot = FALSE, fit.method = method_control_settings$fit.method, verbose = FALSE ) if(verbose){ cat("\n[analyse_Al2O3C_ITC()]\n") cat(paste0("\n Used fit:\t\t",method_control_settings$fit.method)) cat(paste0("\n Time correction value:\t", round(GC$De$De,3), " \u00B1 ", GC$De$De.Error)) cat("\n\n") } if(plot){ plot_settings <- list( xlab = "Dose [s]", ylab = "Integrated net GSL [a.u.]", main = "Irradiation Time Correction", xlim = c(-5, max(df$DOSE)), ylim = c(0,max(df$net_SIGNAL)), legend.pos = "right", legend.text = "dose points", mtext = "" ) plot_settings <- modifyList(x = plot_settings, val = list(...)) plot(NA, NA, xlim = plot_settings$xlim, ylim = plot_settings$ylim, xlab = plot_settings$xlab, ylab = plot_settings$ylab, main = plot_settings$main ) abline(v = 0) abline(h = 0) points(x = df$DOSE, y = df$net_SIGNAL) x <- seq(min(plot_settings$xlim), max(plot_settings$xlim), length.out = 100) lines( x = x, y = eval(GC$Formula) ) x <- 0 lines(x = c(-GC$De[1], -GC$De[1]), y = c(eval(GC$Formula), 0), lty = 2, col = "red") shape::Arrows( x0 = 0, y0 = eval(GC$Formula), x1 = as.numeric(-GC$De[1]), y1 = eval(GC$Formula), arr.type = "triangle", arr.adj = -0.5, col = 'red', cex = par()$cex ) text( x = -GC$De[1] / 2, y = eval(GC$Formula), pos = 3, labels = paste(round(GC$De[1],3), "\u00B1", GC$De[2]), col = 'red', cex = 0.8 ) axis( side = 1, at = axTicks(side = 1), labels = paste0("(",(axTicks(side = 1) + round(as.numeric(GC$De[1]),2)), ")"), line = 1, col.axis = "red", lwd.ticks = 0, lwd = 0, cex.axis = 0.9 ) legend( plot_settings$legend.pos, bty = "n", pch = 1, legend = plot_settings$legend.text ) mtext(side = 3, text = plot_settings$mtext) } return(set_RLum( class = "RLum.Results", data = list( data = data.frame( VALUE = as.numeric(GC$De$De), VALUE_ERROR = as.numeric(sd(GC$De.MC)) ), table = df, table_mean = df_mean, fit = GC$Fit ), info = list(call = sys.call()) )) }
strip_ctl <- function(x, ctl='all', warn=getOption('fansi.warn', TRUE), strip) { if(!missing(strip)) { message("Parameter `strip` has been deprecated; use `ctl` instead.") ctl <- strip } VAL_IN_ENV(x=x, ctl=ctl, warn=warn, warn.mask=get_warn_worst()) if(length(ctl)) .Call(FANSI_strip_csi, x, CTL.INT, WARN.INT) else x } strip_sgr <- function(x, warn=getOption('fansi.warn', TRUE)) { VAL_IN_ENV(x=x, warn=warn, warn.mask=get_warn_worst()) ctl.int <- match(c("sgr", "url"), VALID.CTL) .Call(FANSI_strip_csi, x, ctl.int, WARN.INT) } has_ctl <- function(x, ctl='all', warn=getOption('fansi.warn', TRUE), which) { if(!missing(which)) { message("Parameter `which` has been deprecated; use `ctl` instead.") ctl <- which } VAL_IN_ENV(x=x, ctl=ctl, warn=warn, warn.mask=get_warn_mangled()) if(length(CTL.INT)) { .Call(FANSI_has_csi, x, CTL.INT, WARN.INT) } else rep(FALSE, length(x)) } has_sgr <- function(x, warn=getOption('fansi.warn', TRUE)) has_ctl(x, ctl=c("sgr", "url"), warn=warn) state_at_end <- function( x, warn=getOption('fansi.warn', TRUE), term.cap=getOption('fansi.term.cap', dflt_term_cap()), normalize=getOption('fansi.normalize', FALSE), carry=getOption('fansi.carry', FALSE) ) { VAL_IN_ENV(x=x, ctl='sgr', warn=warn, term.cap=term.cap, carry=carry) .Call( FANSI_state_at_end, x, WARN.INT, TERM.CAP.INT, CTL.INT, normalize, carry, "x", TRUE ) } close_state <- function( x, warn=getOption('fansi.warn', TRUE), normalize=getOption('fansi.normalize', FALSE) ) { VAL_IN_ENV(x=x, warn=warn, normalize=normalize) .Call(FANSI_close_state, x, WARN.INT, 1L, normalize) } process <- function(x, ctl="all") .Call( FANSI_process, enc_to_utf8(x), 1L, match(ctl, VALID.CTL) )
Kdhat <- function(X, r = NULL, ReferenceType, NeighborType = ReferenceType, Weighted = FALSE, Original = TRUE, Approximate = ifelse(X$n < 10000, 0, 1), Adjust = 1, MaxRange = "ThirdW", StartFromMinR = FALSE, CheckArguments = TRUE) { if (CheckArguments) { CheckdbmssArguments() } n <- 512 if (ReferenceType == "") { IsReferenceType <- IsNeighborType <- rep(TRUE, X$n) Y <- X } else { IsReferenceType <- X$marks$PointType==ReferenceType IsNeighborType <- X$marks$PointType==NeighborType if (inherits(X, "Dtable")) { Y <- Dtable(X$Dmatrix[IsReferenceType | IsNeighborType, IsReferenceType | IsNeighborType], PointType = X$marks$PointType[IsReferenceType | IsNeighborType], PointWeight = X$marks$PointWeight[IsReferenceType | IsNeighborType]) diag(Y$Dmatrix) <- NA } else { Y <- X[IsReferenceType | IsNeighborType] } IsReferenceType <- Y$marks$PointType==ReferenceType IsNeighborType <- Y$marks$PointType==NeighborType } if(is.null(r)) { Diameter <- 0 if (inherits(X, "Dtable")) { Diameter <- max(X$Dmatrix) } else { Diameter <- diameter(X$win) } rmax <- switch(MaxRange, HalfW = Diameter/2, ThirdW = Diameter/3, QuarterW = Diameter/4) if(is.null(rmax)) rmax <- Diameter/3 } else { rmax <- max(r) } if (Approximate & !inherits(X, "Dtable")) { rseq <- seq(from=0, to=rmax*2, length.out=2048*Approximate) Nr <- length(rseq) NeighborWeight <- matrix(0.0, nrow=1, ncol=Nr+1) if (Weighted) { Weight <- Y$marks$PointWeight } else { Weight <- rep(1, Y$n) } CountNbdKd(rseq, Y$x, Y$y, Weight, NeighborWeight, IsReferenceType, IsNeighborType) rseq <- c(0, (rseq[2:Nr]+rseq[1:Nr-1])/2) if (Original) { bw <- stats::bw.nrd0(rseq[NeighborWeight[-length(NeighborWeight)]>0]) * Adjust } else { bw <- stats::bw.SJ(rseq[NeighborWeight[-length(NeighborWeight)]>0]) * Adjust } rseq <- c(rseq, rmax*2 + 4*bw) Reflected <- which(rseq <= 4*bw)[-1] rseq <- c(rseq, -rseq[Reflected]) NeighborWeight <- c(NeighborWeight, NeighborWeight[Reflected]) SumNeighborWeight <- sum(NeighborWeight) Density <- stats::density(rseq, weight=NeighborWeight/SumNeighborWeight, from=0, to=rmax, bw=bw, n=n) Mirrored <- stats::density(rseq, weight=NeighborWeight/SumNeighborWeight, to=0, bw=bw) Density$y <- Density$y / (1 - mean(Mirrored$y)*diff(range(Mirrored$x))) } else { if (inherits(X, "Dtable")) { Dist <- as.vector(Y$Dmatrix[IsReferenceType, IsNeighborType]) if (Weighted) { Weight <- Y$marks$PointWeight %*% t(Y$marks$PointWeight) Weight <- as.vector(Weight[IsReferenceType, IsNeighborType]) Weight <- Weight[!is.na(Dist)] } Dist <- Dist[!is.na(Dist)] } else { if (ReferenceType == NeighborType) { NbDist <- sum(IsReferenceType)*(sum(IsReferenceType)-1)/2 } else { NbDist <- sum(IsReferenceType)*sum(IsNeighborType) } Dist <- vector(mode="double", length=NbDist) if (Weighted) { Weight <- vector(mode="double", length=NbDist) } else { Weight <- 1 } DistKd(Y$x, Y$y, Y$marks$PointWeight, Weight, Dist, IsReferenceType, IsNeighborType) } rmin <- ifelse(StartFromMinR, min(Dist), 0) if(is.null(r)) { if (MaxRange == "DO2005") rmax <- stats::median(Dist) } if (Original) { bw <- stats::bw.nrd0(Dist[Dist<=rmax*2]) * Adjust } else { bw <- stats::bw.SJ(Dist[Dist<=rmax*2]) * Adjust } Reflected <- which(Dist <= rmin + 4*bw) Dist <- c(Dist, 2*rmin -Dist[Reflected]) if (Weighted) Weight <- c(Weight, Weight[Reflected]) nDensity <- min(max(n, max(Dist)/rmax*128), 4096) if (Weighted) { Density <- stats::density(Dist, weights=Weight/sum(Weight), from=rmin, to=rmax, bw=bw, n=nDensity) Mirrored <- stats::density(Dist, weights=Weight/sum(Weight), to=rmin, bw=bw) } else { Density <- stats::density(Dist, from=rmin, to=rmax, bw=bw, n=nDensity) Mirrored <- stats::density(Dist, to=rmin, bw=bw) } Density$y <- Density$y / (1- mean(Mirrored$y)*diff(range(Mirrored$x))) } if(is.null(r)) { r <- Density$x Kd <- Density$y } else { Kd <- stats::approx(Density$x, Density$y, xout=r)$y } KdEstimate <- data.frame(r, Kd) colnames(KdEstimate) <- c("r", "Kd") Kd <- fv(KdEstimate, argu="r", ylab=quote(Kd(r)), valu="Kd", fmla= ". ~ r", alim=c(0, max(r)), labl=c("r", paste("hat(%s)(r)", sep="")), desc=c("distance argument r", "Estimated %s"), unitname=X$window$unit, fname="Kd") fvnames(Kd, ".") <- "Kd" return (Kd) }
context("makeDataFrame") test_that("makeDataFrame", { df1 = makeDataFrame(0, 0) df2 = data.frame() expect_equal(df1, df2) df1 = makeDataFrame(3, 0) df2 = data.frame(matrix(nrow = 3, ncol = 0)) expect_equal(df1, df2) df1 = makeDataFrame(0, 2, "character") df2 = data.frame(setColNames(matrix("a", nrow = 0, ncol = 2), c("V1", "V2")), stringsAsFactors = FALSE) expect_equal(df1, df2) df1 = makeDataFrame(3, 1, "integer") df2 = data.frame(V1 = integer(3)) expect_equal(df1, df2) df1 = makeDataFrame(3, 2, "integer") df2 = as.data.frame(matrix(0L, 3, 2)) expect_equal(df1, df2) df1 = makeDataFrame(3, 2, init = "bb") df2 = as.data.frame(matrix("bb", 3, 2), stringsAsFactors = FALSE) expect_equal(df1, df2) df1 = makeDataFrame(3, 2, c("numeric", "integer")) df2 = data.frame(V1 = numeric(3), V2 = integer(3), stringsAsFactors = FALSE) expect_equal(df1, df2) df1 = makeDataFrame(1, 2, "integer", row.names = c("r1"), col.names = c("c1", "c2")) df2 = setRowNames(data.frame(c1 = 0, c2 = 0), "r1") expect_equal(df1, df2) df1 = makeDataFrame(1, 2, "integer", row.names = 1L, col.names = c("c1", "c2")) df2 = setRowNames(data.frame(c1 = 0, c2 = 0), 1L) expect_equal(df1, df2) df1 = makeDataFrame(1, 2, "integer", row.names = NULL, col.names = 1:2) df2 = setColNames(data.frame(c1 = 0, c2 = 0), 1:2) expect_equal(df1, df2) })
OU <- function(N, ...) UseMethod("OU") OU.default <- function(N =100,M=1,x0=2,t0=0,T=1,Dt=NULL,mu=4,sigma=0.2,...) { X <- HWV(N,M,x0,t0,T,Dt,mu,theta=0,sigma) return(X) }
ev.combo <- function(beta, se.beta, beta0 = 0, ci = 99, H0 = c(0, 0), scale = FALSE, H.priors = rep(1/3, 3), se.mult = 1, adjust = FALSE, epsilon = 1e-6, adj.factor = 0.0001, ... ) { if(length(beta) != length(se.beta)) { stop("beta and se.beta must be the same length.") } if(length(H.priors) != 3 || sum(H.priors) != 1 ) { stop("H.priors must have 3 values that sum to one.") } n.studies <- length(beta) se0 <- numeric(n.studies) post.b <- numeric(n.studies) post.se <- numeric(n.studies) res.uni <- matrix(NA, nrow = n.studies, ncol = 3) colnames(res.uni) <- c("H<", "H0", "H>") res <- matrix(NA, nrow = n.studies + 1, ncol = 3) res[1,] <- H.priors colnames(res) <- c("H<", "H0", "H>") for (i in 1:n.studies) { tmp.uni <- pph(beta = beta[i], se.beta = se.beta[i], beta0 = beta0, ci = ci, H0 = H0, H.priors = rep(1/3, 3), se.mult = se.mult, adjust = adjust, epsilon = epsilon, adj.factor = adj.factor, scale=scale) tmp <- pph(beta = beta[i], se.beta = se.beta[i], beta0 = beta0, ci = ci, H0 = H0, H.priors = res[i,], se.mult = se.mult, adjust = adjust, epsilon = epsilon, adj.factor = adj.factor, scale=scale) se0[i] <- tmp$se0 post.b[i] <- tmp$post.b post.se[i] <- tmp$post.se res.uni[i, ] <- tmp.uni$pphs res[i+1,] <- tmp$pphs } if (scale) { beta <- beta/se.beta se.beta <- se.beta/se.beta } return( structure(list(N=n.studies, beta = beta, se.beta = se.beta, beta0 = beta0, ci = ci, se0 = se0, post.b = post.b, post.se = post.se, H.priors = H.priors, pph.uniform = res.uni, pphs = res), class = "EV") ) }
write_fwf_blaise_with_model = function(df, output_data, input_model, output_model = NULL, decimal.mark = '.', digits = getOption('digits'), justify = 'right', max.distance = 0L){ if (tools::file_ext(output_data) == ''){ output_data = paste0(output_data, '.asc') } model = withCallingHandlers( read_model(input_model), integer_size_warning = function(w) invokeRestart('use_value') ) df = convert_df(df, model, max.distance = max.distance) df = write_data(df, model, file = output_data, decimal.mark, justify = justify) if(!is.null(output_model)) write_datamodel(model, output_model) return(invisible(df)) }
copgHsAT <- function(p1, p2, teta, BivD, Ln = FALSE, par2 = NULL, min.dn, min.pr, max.pr){ c.copula.be2 <- c.copula2.be1be2 <- 1 if(BivD %in% c("C90","J90","G90","GAL90") ) { p1 <- 1 - p1 teta <- -teta } if(BivD %in% c("C180","J180","G180","GAL180") ) { p1 <- 1 - p1 p2 <- 1 - p2 } if(BivD %in% c("C270","J270","G270","GAL270") ) { p2 <- 1 - p2 teta <- -teta } if(Ln == FALSE){ if(BivD == "PL"){ c.copula.be2 <- (teta - (0.5 * ((2 * ((p1 + p2) * (teta - 1) + 1) - 4 * (p1 * teta)) * (teta - 1)/sqrt(((p1 + p2) * (teta - 1) + 1)^2 - 4 * (p1 * p2 * teta * (teta - 1)))) + 1))/(2 * (teta - 1)) } if(BivD == "HO"){ c.copula.be2 <- (-log(p2))^(1/teta - 1) * ((-log(p1))^(1/teta) + (-log(p2))^(1/teta))^(teta - 1) * exp(-((-log(p1))^(1/teta) + (-log(p2))^(1/teta))^teta)/p2 } if(BivD == "AMH"){ c.copula.be2 <- p1 * (1 - p2 * teta * (1 - p1)/(1 - teta * (1 - p1) * (1 - p2)))/(1 - teta * (1 - p1) * (1 - p2)) } if(BivD == "FGM"){ c.copula.be2 <- p1 * (1 + teta * (1 - 2 * p2) * (1 - p1)) } if(BivD == "N"){ c.copula.be2 <- pnorm( (qnorm(p1) - teta*qnorm(p2))/sqrt(1 - teta^2) ) } if(BivD == "T"){ c.copula.be2 <- BiCopHfunc2(p1, p2, family = 2, par = teta, par2 = par2) } if(BivD == "F"){ c.copula.be2 <- (exp(teta)* (-1 + exp(p1* teta)))/(-exp((p1 + p2)* teta) + exp(teta)* (-1 + exp(p2* teta) + exp(p1* teta))) } if(BivD %in% c("C0","C90","C180","C270") ){ c.copula.be2 <- (p1^(-teta) + p2^(-teta) - 1)^((-1/teta) - 1) * ((-1/teta) * (p2^((-teta) - 1) * (-teta))) } if(BivD %in% c("GAL0","GAL90","GAL180","GAL270") ){ c.copula.be2 <- p1*(1-1/((-log(p2))^(1+teta)*(1/(-log(p1))^teta+ 1/(-log(p2))^teta)^(1+1/teta)))*exp((1/(-log(p1))^teta+ 1/(-log(p2))^teta)^-(1/teta)) } if(BivD %in% c("G0","G90","G180","G270") ){ c.copula.be2 <- (exp(-((-log(p2))^teta + (-log(p1))^teta)^((1/teta)))* (-log(p2))^(-1 + teta)* ((-log(p2))^teta + (-log(p1))^teta)^(-1 + 1/teta))/p2 } if(BivD %in% c("J0","J90","J180","J270") ){ c.copula.be2 <- ((1 - p1)^teta + (1 - p2)^teta - (1 - p1)^teta * (1 - p2)^teta)^((1/teta) - 1) * ((1/teta) * ((1 - p2)^(teta - 1) * teta - (1 - p1)^teta * ((1 - p2)^(teta - 1) * teta))) } if(BivD %in% c("C90","J90","G90","GAL90") ) c.copula.be2 <- 1 - c.copula.be2 if(BivD %in% c("C180","J180","G180","GAL180") ) c.copula.be2 <- 1 - c.copula.be2 c.copula.be2 <- mm(c.copula.be2, min.pr = min.pr, max.pr = max.pr) } if(Ln == TRUE){ if(BivD == "HO"){ c.copula2.be1be2 <- ((-log(p1))^(1/teta - 1) * (-log(p2))^(1/teta - 1) * ((-log(p1))^(1/teta) + (-log(p2))^(1/teta))^(2 * (teta - 1)) - (-log(p1))^(1/teta - 1) * (-log(p2))^(1/teta - 1) * ((-log(p1))^(1/teta) + (-log(p2))^(1/teta))^(teta - 2) * (teta - 1)/teta) * exp(-((-log(p1))^(1/teta) + (-log(p2))^(1/teta))^teta)/(p1 * p2) } if(BivD == "PL"){ c.copula2.be1be2 <- -(((2 * (teta - 1) - 4 * teta)/sqrt(((p1 + p2) * (teta - 1) + 1)^2 - 4 * (p1 * p2 * teta * (teta - 1))) - 0.5 * ((2 * ((p1 + p2) * (teta - 1) + 1) - 4 * (p1 * teta)) * (2 * ((p1 + p2) * (teta - 1) + 1) - 4 * (p2 * teta)) * (teta - 1)/(((p1 + p2) * (teta - 1) + 1)^2 - 4 * (p1 * p2 * teta * (teta - 1)))^1.5))/4) } if(BivD == "AMH"){ c.copula2.be1be2 <- (1 - teta * (p1 * (1 - p2 * (2 + 2 * (teta * (1 - p1) * (1 - p2)/(1 - teta * (1 - p1) * (1 - p2))))) + p2 * (1 - p1))/(1 - teta * (1 - p1) * (1 - p2)))/(1 - teta * (1 - p1) * (1 - p2)) } if(BivD == "FGM"){ c.copula2.be1be2 <- 1 + teta * (1 - 2 * p1) * (1 - 2 * p2) } if(BivD == "N"){ c.copula2.be1be2 <- 1/sqrt(1 - teta^2)*exp( - (teta^2*( qnorm(p1)^2 + qnorm(p2)^2 ) - 2*teta*qnorm(p1)*qnorm(p2) ) / (2*(1 - teta^2)) ) } if(BivD == "T"){ c.copula2.be1be2 <- BiCopPDF(p1, p2, family = 2, teta, par2) } if(BivD == "F"){ c.copula2.be1be2 <- (exp((1 + p1 + p2)* teta)* (-1 + exp(teta))* teta)/(exp((p1 + p2)* teta) - exp(teta)* (-1 + exp(p1* teta) + exp(p2* teta)))^2 } if(BivD %in% c("C0","C90","C180","C270") ){ c.copula2.be1be2 <- p1^(-1 - teta)* p2^(-1 - teta)* (-1 + p1^-teta + p2^-teta)^(-2 - 1/ teta) *(1 + teta) } if(BivD %in% c("GAL0","GAL90","GAL180","GAL270") ){ c.copula2.be1be2 <- (1+teta*(-log(p2))^(1+teta)*(1+1/teta)* (1/(-log(p1))^teta+1/(-log(p2))^teta)^(1/teta)/((-log(p1))^(1+ teta)*((-log(p2))^(1+teta)*(1/(-log(p1))^teta+1/(-log(p2))^teta)^(1+ 1/teta))^2)-((1-1/((-log(p2))^(1+teta)*(1/(-log(p1))^teta+ 1/(-log(p2))^teta)^(1+1/teta)))/((-log(p1))^(1+teta)* (1/(-log(p1))^teta+1/(-log(p2))^teta)^(1+1/teta))+1/((-log(p2))^(1+ teta)*(1/(-log(p1))^teta+1/(-log(p2))^teta)^(1+1/teta))))* exp((1/(-log(p1))^teta+1/(-log(p2))^teta)^-(1/teta)) } if(BivD %in% c("G0","G90","G180","G270") ){ c.copula2.be1be2 <- (exp(-((-log(p1))^teta + (-log(p2))^teta)^((1/teta)))* (-log(p1))^(-1 + teta) *(-1 + teta + ((-log(p1))^teta + (-log(p2))^teta)^(1/ teta))* ((-log(p1))^teta + (-log(p2))^teta)^(-2 + 1/ teta)* (-log(p2))^(-1 + teta))/(p1 *p2) } if(BivD %in% c("J0","J90","J180","J270") ){ c.copula2.be1be2 <- (1 - p1)^(-1 + teta)* ((1 - p1)^teta - (-1 + (1 - p1)^teta)* (1 - p2)^teta)^(-2 + 1/ teta) *(1 - p2)^(-1 + teta)* (-(-1 + (1 - p1)^teta)* (-1 + (1 - p2)^teta) + teta) } c.copula2.be1be2 <- ifelse(c.copula2.be1be2 < min.dn, min.dn, c.copula2.be1be2) } list(c.copula.be2 = ifef(c.copula.be2), c.copula2.be1be2 = ifef(c.copula2.be1be2)) }
options(width=70) library(hsdar) data(spectral_data) spectral_data str(spectral_data) spectra <- spectra(spectral_data) str(spectra) wavelength <- wavelength(spectral_data) newSpeclib <- speclib(spectra, wavelength) str(newSpeclib) ids <- idSpeclib(spectral_data) idSpeclib(newSpeclib) <- as.character(ids) SI <- SI(spectral_data) head(SI) SI(newSpeclib) <- SI str(newSpeclib) parameter <- data.frame(N = c(rep.int(seq(0.5, 1.4, 0.1), 6)), LAI = c(rep.int(0.5, 10), rep.int(1, 10), rep.int(1.5, 10), rep.int(2, 10), rep.int(2.5, 10), rep.int(3, 10))) spectra <- PROSAIL(parameterList = parameter) rows <- round(nspectra(spectra)/10, 0) cols <- ceiling(nspectra(spectra)/rows) grd <- SpatialGrid(GridTopology(cellcentre.offset = c(1,1,1), cellsize = c(1,1,1), cells.dim = c(cols, rows, 1))) x <- SpatialPixelsDataFrame(grd, data = as.data.frame(spectra(spectra))) writeGDAL(x, fname = "example_in.tif", drivername = "GTiff") infile <- "example_in.tif" wavelength <- wavelength(spectra) ra <- speclib(infile, wavelength) tr <- blockSize(ra) outfile <- "example_result.tif" n_veg <- as.numeric(length(vegindex())) res <- writeStart(ra, outfile, overwrite = TRUE, nl = n_veg) for (i in 1:tr$n) { v <- getValuesBlock(ra, row=tr$row[i], nrows=tr$nrows[i]) mask(v) <- c(1350, 1450) v <- as.matrix(vegindex(v, index=vegindex())) res <- writeValues(res, v, tr$row[i]) } res <- writeStop(res) LAI <- SI(spectra)$LAI SI_file <- "example_SI.tif" SI_raster <- setValues(raster(infile), LAI) SI_raster <- writeRaster(SI_raster, SI_file) outfile <- "example_result_ndvi.tif" SI(ra) <- raster(SI_file) names(SI(ra)) <- "LAI" res <- writeStart(ra, outfile, overwrite = TRUE, nl = 1) for (i in 1:tr$n) { v <- getValuesBlock(ra, row=tr$row[i], nrows=tr$nrows[i]) mask(v) <- c(1350, 1450) LAI <- SI(v)$LAI v <- as.matrix(vegindex(v, index="NDVI")) v[LAI <= 1] <- NA res <- writeValues(res, v, tr$row[i]) } res <- writeStop(res) plot(raster("example_result_ndvi.tif")) par(mfrow = c(2,2), mar = c(4,4,3,0.1), cex = 0.75) plot(spectral_data, main = "Default Plot", ylim = c(0, 70)) plot(spectral_data, FUN = 1, main = "First spectrum of Speclib", ylim = c(0, 70)) plot(spectral_data, FUN = "median", main = "Median spectrum", ylim = c(0, 70)) plot(spectral_data, FUN = "mean", main = "Mean spectrum", ylim = c(0, 70)) par(mar = c(4,4,0.1,0.1), cex = 0.75) plot(spectral_data, FUN = 1, col = "red") plot(spectral_data, FUN = 2, col = "blue", new = FALSE) plot(spectral_data, FUN = 3, col = "orange", new = FALSE) spectrum1 <- PROSPECT(N = 1.3, Cab = 30, Car = 10, Cbrown = 0, Cw = 0.01, Cm = 0.01) spectrum2 <- PROSPECT(N = 1.3, Cab = 60, Car = 10, Cbrown = 0, Cw = 0.01, Cm = 0.01) plot(spectrum1, col = "darkorange4", ylim = c(0,0.5), subset = c(400, 800)) plot(spectrum2, col = "darkgreen", new = FALSE) par(mar = c(4,4,0.1,0.1), cex = 0.75) plot(spectrum1, col = "darkorange4", ylim = c(0,0.5), subset = c(400, 800)) plot(spectrum2, col = "darkgreen", new = FALSE) parameter <- data.frame(tts = seq(15, 85, 0.5)) head(parameter) spectra <- PROSAIL(parameterList = parameter) spectra summary(SI(spectra)) colours <- colorRamp(c("darkorange4", "yellow")) plot(spectra[1,], ylim = c(0, 0.3), col = rgb(colours(SI(spectra)$tts[1]/85), maxColorValue = 255)) for (i in 2:nspectra(spectra)) plot(spectra[i,], new = FALSE, col = rgb(colours(SI(spectra)$tts[i]/85), maxColorValue = 255)) par(mar = c(4,4,0.1,0.1), cex = 0.75) colours <- colorRamp(c("darkorange4", "yellow")) plot(spectra[1,], ylim = c(0, 0.3), col = rgb(colours(SI(spectra)$tts[1]/85), maxColorValue = 255)) for (i in 2:nspectra(spectra)) plot(spectra[i,], new = FALSE, col = rgb(colours(SI(spectra)$tts[i]/85), maxColorValue = 255)) parameter <- data.frame(LAI = rep.int(c(1,2,3),5), TypeLidf = 1, lidfa = c(rep.int(1,3), rep.int(-1,3), rep.int(0,6), rep.int(-0.35,3)), lidfb = c(rep.int(0,6), rep.int(-1,3), rep.int(1,3), rep.int(-0.15,3))) parameter spectra <- PROSAIL(parameterList = parameter) spectra colours <- c("darkblue", "red", "darkgreen") LIDF_type <- as.factor(c(rep.int("Planophile", 3), rep.int("Erectophile", 3), rep.int("Plagiophile", 3), rep.int("Extremophile", 3), rep.int("Spherical", 3))) plot(spectra[1,], ylim = c(0, 0.5), col = colours[SI(spectra)$LAI[1]], lty = which(levels(LIDF_type) == LIDF_type[1])) for (i in 2:nspectra(spectra)) plot(spectra[i,], new= FALSE, col = colours[SI(spectra)$LAI[i]], lty = which(levels(LIDF_type) == LIDF_type[i])) legend("topright", legend = c(paste("LAI =", c(1:3)), "", levels(LIDF_type)), col = c(colours, rep.int("black", 1 + length(levels(LIDF_type)))), lty = c(rep.int(1, 3), 0, 1:length(levels(LIDF_type)))) par(mar = c(4,4,0.1,0.1), cex = 0.75) plot(spectra[1,], ylim = c(0, 0.5), col = colours[SI(spectra)$LAI[1]], lty = which(levels(LIDF_type) == LIDF_type[1])) for (i in 2:nspectra(spectra)) plot(spectra[i,], new= FALSE, col = colours[SI(spectra)$LAI[i]], lty = which(levels(LIDF_type) == LIDF_type[i])) legend("topright", legend = c(paste("LAI =", c(1:3)), "", levels(LIDF_type)), col = c(colours, rep.int("black", 1 + length(levels(LIDF_type)))), lty = c(rep.int(1, 3), 0, 1:length(levels(LIDF_type)))) names(SI(spectral_data)) sp_spring <- subset(spectral_data, season == "spring") sp_summer <- subset(spectral_data, season == "summer") plot(sp_spring, FUN = "mean", col = "darkgreen", ylim = c(0,70)) plot(sp_summer, FUN = "mean", col = "darkred", new = FALSE) par(mar = c(4,4,0.1,0.1), cex = 0.75) plot(sp_spring, FUN = "mean", col = "darkgreen", ylim = c(0,70)) plot(sp_summer, FUN = "mean", col = "darkred", new = FALSE) spectral_data_masked <- spectral_data mask(spectral_data_masked) <- c(1040,1060,1300,1450) par(mfrow = c(1,2)) plot(spectral_data, FUN = 1) plot(spectral_data_masked, FUN = 1) par(mfrow=c(1,2), mar = c(4,4,0.1,0.1), cex = 0.75) plot(spectral_data, FUN = 1) plot(spectral_data_masked, FUN = 1) spectral_data_interpolated <- interpolate.mask(spectral_data_masked) plot(spectral_data_interpolated, FUN = 1) par(mar = c(4,4,0,0.1), cex = 0.75) plot(spectral_data_interpolated, FUN = 1) spectral_data <- spectral_data_masked par(mar = c(4,4,0.1,0.1), cex = 0.75) plot(spectral_data, FUN = 1, subset = c(1200,1300)) sgolay <- noiseFiltering(spectral_data, method = "sgolay", n = 25) lowess <- noiseFiltering(spectral_data, method = "lowess", f = .01) meanflt <- noiseFiltering(spectral_data, method = "mean", p = 5) spline <- noiseFiltering(spectral_data, method = "spline", n = round(nbands(spectral_data)/10, 0)) par(mfrow=c(2,2), mar = c(4,4,3,0.1), cex = 0.75) plot(sgolay, FUN = 1, subset = c(1200,1300), col = "red", main = "Savitzky-Golay-Filter") plot(spectral_data, FUN = 1, new = FALSE) plot(lowess, FUN = 1, subset = c(1200,1300), col = "red", main = "Lowess-Filter") plot(spectral_data, FUN = 1, new = FALSE) plot(meanflt, FUN = 1, subset = c(1200,1300), col = "red", main = "Mean-filter") plot(spectral_data, FUN = 1, new = FALSE) plot(spline, FUN = 1, subset = c(1200,1300), col = "red", main = "Spline-Filter") plot(spectral_data, FUN = 1, new = FALSE) spectral_data_1deriv <- derivative.speclib(spectral_data, m = 1) spectral_data_2deriv <- derivative.speclib(spectral_data, m = 2) redEdgePart <- wavelength(spectral_data_2deriv) >= 600 & wavelength(spectral_data_2deriv) <= 800 spectral_data_1deriv <- spectral_data_1deriv[,redEdgePart] spectral_data_2deriv <- spectral_data_2deriv[,redEdgePart] par(mfrow=c(1,2)) plot(spectral_data_1deriv, FUN = 1, xlim = c(600,800), main = "First derivation") plot(spectral_data_2deriv, FUN = 1, xlim = c(600,800), main = "Second Derivation") par(mfrow = c(1,2), mar = c(4,4,3,0.1), cex = 0.75) plot(spectral_data_1deriv, FUN = 1, xlim = c(600,800), main = "First derivation") plot(spectral_data_2deriv, FUN = 1, xlim = c(600,800), main = "Second Derivation") spectral_data_1deriv <- derivative.speclib(noiseFiltering( spectral_data, method = "sgolay", n = 35), m = 1) spectral_data_2deriv <- derivative.speclib(noiseFiltering( spectral_data, method = "sgolay", n = 35), m = 2) par(mfrow=c(1,2)) plot(spectral_data_1deriv, FUN = 1, xlim = c(600,800), main = "First derivation") plot(spectral_data_2deriv, FUN = 1, xlim = c(600,800), main = "Second Derivation") spectral_data_1deriv <- spectral_data_1deriv[,redEdgePart] spectral_data_2deriv <- spectral_data_2deriv[,redEdgePart] par(mfrow = c(1,2), mar = c(4,4,3,0.1), cex = 0.75) plot(spectral_data_1deriv, FUN = 1, xlim = c(600,800), main = "First derivation") plot(spectral_data_2deriv, FUN = 1, xlim = c(600,800), main = "Second Derivation") get.sensor.characteristics(0) spectral_data_resampled <- spectralResampling(spectral_data, "WorldView2-8") spectral_data_resampled wavelength(spectral_data_resampled) plot(spectral_data_resampled) par(mar = c(4,4,0.1,0.1), cex = 0.75) plot(spectral_data_resampled) parameter <- data.frame(N = c(0.5,1),LAI = 0.5,Car=3) spectra <- PROSAIL(parameterList = parameter) str(transformSpeclib) ch_cline <- transformSpeclib(spectra, method = "ch", out = "raw") ch_bd <- transformSpeclib(spectra, method = "ch", out = "bd") sh_cline <- transformSpeclib(spectra, method = "sh", out = "raw") sh_bd <- transformSpeclib(spectra, method = "sh", out = "bd") par(mfrow=c(2,2), mar = c(4,4,3,0.1), cex = 0.75) plot(ch_cline, ispec = 1, numeratepoints = FALSE, main = "Convex hull - Continuum line") plot(ch_bd, ispec = 1, main = "Convex hull - Band depth") plot(sh_cline, ispec = 1, numeratepoints = FALSE, main = "Segmented hull - Continuum line") plot(sh_bd, ispec = 1, main = "Segmented hull - Band depth") par(mfrow=c(1,2), mar = c(4,4,3,0.1), cex = 0.75) plot(sh_cline, ispec = 1, main = "Continuum line, Spectrum 1", xlim = c(500,800)) plot(sh_cline, ispec = 2, main = "Continuum line, Spectrum 2", xlim = c(500,800)) str(deletecp) getcp(sh_cline, 1, subset = c(500, 600)) sh_cline <- deletecp(sh_cline, 1, c(530:600)) getcp(sh_cline, 1, subset = c(500, 600)) checkhull(sh_cline, 1)$error sh_cline <- addcp(sh_cline, 1, c(2487:2498)) checkhull(sh_cline, 1)$error sh_clineUpdate <- makehull(sh_cline, 1) sh_bd <- updatecl(sh_bd, sh_clineUpdate) par(mfrow=c(1,2), mar = c(4,4,3,0.1), cex = 0.75) plot(sh_cline, ispec = 1, main = "Updated Segmented hull", xlim = c(300,800)) plot(sh_bd[1,], main="Updated hull - Band depth", xlim = c(300,800)) featureSelection <- specfeat(sh_bd, c(450,600, 1500, 2000)) plot(featureSelection, fnumber= 1:4) par(mar = c(4,4,0.1,0.1), cex = 0.75) plot(featureSelection, fnumber=1:4) featuresCut <- cut_specfeat(featureSelection, fnumber = c(1,2), limits = c(c(310, 525), c(530, 800))) plot(featuresCut, 1:2) par(mar = c(4,4,0.1,0.1), cex = 0.75) plot(featuresCut, fnumber= 1:2) featureProp <- feature_properties(featureSelection) head(SI(featureProp)) data(spectral_data) ndvi <- vegindex(spectral_data, "NDVI") ndvi avl <- vegindex() vi <- vegindex(spectral_data, index = avl) data(spectral_data) rd <- rededge(spectral_data) D2 <- derivative.speclib(spectral_data[1,],method="sgolay",m=2, n=33) par(mfrow=c(1,2), mar = c(4,4,0.4,.4)) plot(D2,xlim=c(500,900),ylim=c(-0.03,0.03),ylab="Second derivation") points(rd[1,4],get_reflectance(D2,rd[1,4])) points(rd[1,6],get_reflectance(D2,rd[1,6])) text(c(rd$lp[1],rd$ls[1]),c(get_reflectance(D2,rd$lp[1]),get_reflectance(D2,rd$ls[1])), labels=c("lp","ls"), cex= 0.8,pos=3) plot(spectral_data[1,],xlim=c(500,900),ylim=c(0,50)) points(matrix(c(rd$l0[1],rd$R0[1],rd$lp[1],rd$Rp[1],rd$ls[1],rd$Rs[1]), nrow=3,byrow = TRUE)) text(c(rd$l0[1],rd$lp[1],rd$ls[1]),c(rd$R0[1],rd$Rp[1],rd$Rs[1]), labels=c("l0/R0","lp/Rp","ls/Rs"), cex= 0.8, offset =0.5,pos=2) data(spectral_data) rd <- rededge(spectral_data) par(mar = c(4,4,0.1,0.1), cex = 0.75) boxplot(rd$R0 ~ SI(spectral_data)$season, ylab = "R0") spec_WV <- spectralResampling(spectral_data, "WorldView2-8", response_function = FALSE) str(nri) nri_WV <- nri(spec_WV, recursive = TRUE) nri_WV nri_WV$nri[,,1] spec_WV <- spectralResampling(spectral_data, "WorldView2-8", response_function = FALSE) nri_WV <- nri(spec_WV, recursive = TRUE) chlorophyll <- SI(spec_WV)$chlorophyll cortestnri <- cor.test(nri_WV, chlorophyll) cortestnri par(mar = c(4,4,0.1,0.1), cex = 0.75) plot(cortestnri, coefficient = "p.value") par(mar = c(4,4,0.1,0.1), cex = 0.75) plot(cortestnri, coefficient = "p.value", range = c(0,0.01)) str(lm.nri) lmnri <- lm.nri(nri_WV ~ chlorophyll, preddata = spec_WV) lmnri str(nri_best_performance) nribest <- nri_best_performance(lmnri, n = 1) nribest getNRI(nri_WV, nribest) par(mar = c(4,4,3,0.1), cex = 0.75) plot(lmnri, coefficient = "r.squared", main = "R squared") par(mar = c(4,4,3,0.1), cex = 0.75) plot(lmnri, coefficient = "r.squared", main = "R squared", constraint = "p.value<0.01") parameter <- data.frame(LAI = seq(0, 1, 0.01)) spectral_data <- PROSAIL(parameterList = parameter) spectral_data_qb <- spectralResampling(spectral_data, "Quickbird") grass_spectra_qb <- speclib(spectra = matrix(c(3.190627, 5.137504, 5.797486, 29.68515), nrow = 1), wavelength = c(485, 560, 660, 830)) limestone_qb <- speclib(spectra = matrix(c(16.93489, 18.97302, 21.407, 23.98981), nrow = 1), wavelength = c(485, 560, 660, 830)) em <- speclib(spectra = rbind(spectra(grass_spectra_qb), spectra(limestone_qb))/100, wavelength = wavelength(limestone_qb)) unmix_res <- unmix(spectral_data_qb, em) str(unmix_res) plot(unmix_res$fractions[1,] ~ SI(spectral_data_qb)$LAI, type = "l", xlab = "LAI", ylab = "Unmixed fraction of vegetation") par(mar = c(4,4,0,0.1), cex = 0.75) plot(unmix_res$fractions[1,] ~ SI(spectral_data_qb)$LAI, type = "l", xlab = "LAI", ylab = "Unmixed fraction of vegetation")
get_regional_data <- function(country, level = "1", totals = FALSE, localise = TRUE, steps = FALSE, class = FALSE, verbose = TRUE, regions, include_level_2_regions = deprecated(), localise_regions = deprecated(), ...) { if (is_present(include_level_2_regions)) { deprecate_warn( "0.9.0", "covidregionaldata::get_regional_data(include_level_2_regions = )", "covidregionaldata::get_regional_data(level = )" ) if (include_level_2_regions) { level <- "1" } else { level <- "2" } } if (is_present(localise_regions)) { deprecate_warn( "0.9.0", "covidregionaldata::get_regional_data(localise_regions = )", "covidregionaldata::get_regional_data(localise = )" ) localise <- localise_regions } region_class <- initialise_dataclass( class = country, level = level, regions = regions, totals = totals, localise = localise, verbose = verbose, steps = steps, get = TRUE, type = "regional", ... ) return( return_data(region_class, class = class) ) }
cgm<-function(A, b, x=NULL, iter=500, tol=1e-7){ nROW<-nrow(A) if(is.null(x)) x<-matrix(rep(0, each=nROW), nrow = nROW, byrow=T) conv<-NULL xini<-x SearchDirection<-0 Beta<-0 for(i in 1:iter){ xold<-x residual<-b-A%*%x if(i>1){ Beta<--1L*(t(residual)%*%A%*%SearchDirection)/(t(SearchDirection)%*%A%*%SearchDirection) } SearchDirection<-residual + matrix(rep(Beta, each=nROW), nrow = nROW, byrow=T)*SearchDirection alphaParameter<-(t(SearchDirection)%*%residual) if(alphaParameter==0 & i>1){ return(list("x"=x, "xini"=xini, "itr.conv"=i, "conv"=conv)) } alpha=alphaParameter/(t(SearchDirection)%*%A%*%SearchDirection) x<-x+matrix(rep(alpha, each=nROW), nrow = nROW, byrow=T)*SearchDirection dx<-sqrt(t(x-xold)%*%(x-xold)) conv<-c(conv, dx) if(dx<=tol){ return(list("optimal"=x, "initial"=xini, "itr.conv"=i, "conv"=conv)) } } print("Optimization Failed to Converge...") return(list("x"=x, "xini"=xini, "itr.conv"=i, "conv"=conv)) }
plot.interpolation.cv<-function(x, type="stations",...) { type = match.arg(type, c("stations", "dates")) if(type =="stations") { stationsdf = x$stations par(mfrow=c(3,4), mar=c(4,4,2,2)) if(sum(!is.na(stationsdf$MinTemperature.Bias))>0) { hist(stationsdf$`MinTemperature.Bias`, xlab="Min. temp. bias (degrees C)", main="",...) abline(v=mean(stationsdf$`MinTemperature.Bias`, na.rm=TRUE), col="gray", lwd=2) abline(v=0, col="red", lwd=2) } if(sum(!is.na(stationsdf$MinTemperature.MAE))>0) { hist(stationsdf$`MinTemperature.MAE`, xlab="Min. temp. MAE (degrees C)", main="",...) abline(v=mean(stationsdf$`MinTemperature.MAE`, na.rm=TRUE), col="gray", lwd=2) } if(sum(!is.na(stationsdf$MaxTemperature.Bias))>0) { hist(stationsdf$`MaxTemperature.Bias`, xlab="Max. temp. bias (degrees C)", main="",...) abline(v=mean(stationsdf$`MaxTemperature.Bias`, na.rm=TRUE), col="gray", lwd=2) abline(v=0, col="red", lwd=2) } if(sum(!is.na(stationsdf$MaxTemperature.MAE))>0) { hist(stationsdf$`MaxTemperature.MAE`, xlab="Max. temp. MAE (degrees C)", main="") abline(v=mean(stationsdf$`MaxTemperature.MAE`, na.rm=TRUE), col="gray", lwd=2) } if(sum(!is.na(stationsdf$TotalPrec.Pred))>0) { hist(stationsdf$TotalPrec.Pred - stationsdf$TotalPrec.Obs, xlab="Error in total precipitation (mm)", main="",...) abline(v=mean(stationsdf$TotalPrec.Pred - stationsdf$TotalPrec.Obs, na.rm=TRUE), col="gray", lwd=2) abline(v=0, col="red", lwd=2) } if(sum(!is.na(stationsdf$PrecFreq.Pred))>0) { hist(stationsdf$PrecFreq.Pred - stationsdf$PrecFreq.Obs, xlab="Error in proportion of rainy days (%)", main="",...) abline(v=mean(stationsdf$PrecFreq.Pred - stationsdf$PrecFreq.Ob, na.rm=TRUE), col="gray", lwd=2) abline(v=0, col="red", lwd=2) } if(sum(!is.na(stationsdf$RelativeHumidity.Bias))>0) { hist(stationsdf$`RelativeHumidity.Bias`, xlab= "RelativeHumidity Bias (%)", main="",...) abline(v=mean(stationsdf$`RelativeHumidity.Bias`, na.rm=TRUE), col="gray", lwd=2) abline(v=0, col="red", lwd=2) } if(sum(!is.na(stationsdf$RelativeHumidity.MAE))>0) { hist(stationsdf$`RelativeHumidity.MAE`, xlab= "RelativeHumidity MAE (%)", main="",...) abline(v=mean(stationsdf$`RelativeHumidity.MAE`, na.rm=TRUE), col="gray", lwd=2) } if(sum(!is.na(stationsdf$Radiation.Bias))>0) { hist(stationsdf$`Radiation.Bias`, xlab= "Radiation Bias (MJ/m2)", main="",...) abline(v=mean(stationsdf$`Radiation.Bias`, na.rm=TRUE), col="gray", lwd=2) } if(sum(!is.na(stationsdf$Radiation.MAE))>0) { abline(v=0, col="red", lwd=2) hist(stationsdf$`Radiation.MAE`, xlab= "Radiation MAE (MJ/m2)", main="",...) abline(v=mean(stationsdf$`Radiation.MAE`, na.rm=TRUE), col="gray", lwd=2) } } else if(type=="dates") { datesdf = x$dates par(mfrow=c(5,2), mar=c(4,4,2,2)) if(sum(!is.na(datesdf$`MinTemperature.Bias`))>0) { plot(datesdf$`MinTemperature.Bias`, type="l", ylab="Min. temp. bias (degrees C)", xlab="day", main="",...) abline(h=0, col="red", lwd=1.5) } if(sum(!is.na(datesdf$`MinTemperature.MAE`))>0) { plot(datesdf$`MinTemperature.MAE`, type="l", ylab="Min. temp. MAE (degrees C)", xlab="day", main="",...) } if(sum(!is.na(datesdf$`MaxTemperature.Bias`))>0) { plot(datesdf$`MaxTemperature.Bias`, type="l", ylab="Max. temp. bias (degrees C)", xlab="day", main="",...) abline(h=0, col="red", lwd=1.5) } if(sum(!is.na(datesdf$`MaxTemperature.MAE`))>0) { plot(datesdf$`MaxTemperature.MAE`, type="l", ylab="Max. temp. MAE (degrees C)", xlab="day", main="",...) } if(sum(!is.na(datesdf$`TotalPrec.Pred`))>0) { plot(datesdf$TotalPrec.Pred - datesdf$TotalPrec.Obs, type="l", ylab="Error in daily total precipitation (mm)", xlab="day", main="",...) abline(h=0, col="red", lwd=1.5) } if(sum(!is.na(datesdf$`PrecFreq.Pred`))>0) { plot(datesdf$PrecFreq.Pred - datesdf$PrecFreq.Obs, type="l", ylab="Error in frequency of wet stations (%)", xlab="day", main="",...) abline(h=0, col="red", lwd=1.5) } if(sum(!is.na(datesdf$`RelativeHumidity.Bias`))>0) { plot(datesdf$`RelativeHumidity.Bias`, type="l", ylab="RelativeHumidity bias (%)", xlab="day", main="",...) abline(h=0, col="red", lwd=1.5) } if(sum(!is.na(datesdf$`RelativeHumidity.MAE`))>0) { plot(datesdf$`RelativeHumidity.MAE`, type="l", ylab="RelativeHumidity MAE (%)", xlab="day", main="",...) } if(sum(!is.na(datesdf$`Radiation.Bias`))>0) { plot(datesdf$`Radiation.Bias`, type="l", ylab="Radiation bias (MJ/m2)", xlab="day", main="",...) abline(h=0, col="red", lwd=1.5) } if(sum(!is.na(datesdf$`Radiation.MAE`))>0) { plot(datesdf$`Radiation.MAE`, type="l", ylab="Radiation MAE (MJ/m2)", xlab="day", main="",...) } } }
rangebreak.linear <- function(species.1, species.2, env, type, f = NULL, nreps = 99, nback = 1000, bg.source = "default", low.memory = FALSE, rep.dir = NA, verbose = FALSE, clamp = TRUE, ...){ species.1 <- check.bg(species.1, env, nback = nback, bg.source = bg.source, verbose = verbose) species.2 <- check.bg(species.2, env, nback = nback, bg.source = bg.source, verbose = verbose) rangebreak.linear.precheck(species.1, species.2, env, type, f, nreps) replicate.models <- list() if(low.memory == TRUE){ if(is.na(rep.dir)){ rep.dir <- getwd() } if(substr(rep.dir, nchar(rep.dir), nchar(rep.dir)) != "/"){ rep.dir <- paste0(rep.dir, "/") } if(!dir.exists(rep.dir)){ stop(paste("Specified directory for storing replicates cannot be found!\n\n", getwd())) } } species.1$background.points <- rbind(species.1$background.points, species.2$background.points) species.2$background.points <- rbind(species.1$background.points, species.2$background.points) combined.presence.points <- rbind(species.1$presence.points, species.2$presence.points) if(clamp == TRUE){ this.df <- as.data.frame(extract(env, combined.presence.points)) env <- clamp.env(this.df, env) } message("\nBuilding empirical models...\n") if(type == "glm"){ empirical.species.1.model <- enmtools.glm(species.1, env, f, clamp = FALSE, ...) empirical.species.2.model <- enmtools.glm(species.2, env, f, clamp = FALSE, ...) } if(type == "gam"){ empirical.species.1.model <- enmtools.gam(species.1, env, f, clamp = FALSE, ...) empirical.species.2.model <- enmtools.gam(species.2, env, f, clamp = FALSE, ...) } if(type == "mx"){ empirical.species.1.model <- enmtools.maxent(species.1, env, clamp = FALSE, ...) empirical.species.2.model <- enmtools.maxent(species.2, env, clamp = FALSE, ...) } if(type == "bc"){ empirical.species.1.model <- enmtools.bc(species.1, env, clamp = FALSE, ...) empirical.species.2.model <- enmtools.bc(species.2, env, clamp = FALSE, ...) } if(type == "dm"){ empirical.species.1.model <- enmtools.dm(species.1, env, clamp = FALSE, ...) empirical.species.2.model <- enmtools.dm(species.2, env, clamp = FALSE, ...) } if(type == "rf"){ empirical.species.1.model <- enmtools.rf(species.1, env, clamp = FALSE, ...) empirical.species.2.model <- enmtools.rf(species.2, env, clamp = FALSE, ...) } empirical.overlap <- c(unlist(raster.overlap(empirical.species.1.model, empirical.species.2.model)), unlist(env.overlap(empirical.species.1.model, empirical.species.2.model, env = env)[1:3])) reps.overlap <- empirical.overlap lines.df <- data.frame(slope = rep(NA, nreps), intercept = rep(NA, nreps)) message("\nBuilding replicate models...\n") if (requireNamespace("progress", quietly = TRUE)) { pb <- progress::progress_bar$new( format = " [:bar] :percent eta: :eta", total = nreps, clear = FALSE, width= 60) } for(i in 1:nreps){ if(verbose == TRUE){message(paste("\nReplicate", i, "...\n"))} if (requireNamespace("progress", quietly = TRUE)) { pb$tick() } rep.species.1 <- species.1 rep.species.2 <- species.2 angle <- runif(1, min=0, max=pi) slope <- sin(angle)/cos(angle) part.points <- cbind(combined.presence.points, combined.presence.points[,2] - slope * combined.presence.points[,1]) if(rbinom(1,1,0.5) == 0){ part.points <- part.points[order(part.points[,3]),] } else { part.points <- part.points[order(part.points[,3], decreasing = TRUE),] } intercept <- mean(c(part.points[nrow(species.1$presence.points), 3], part.points[nrow(species.2$presence.points), 3])) rep.species.1$presence.points <- part.points[1:nrow(species.1$presence.points), 1:2] rep.species.2$presence.points <- part.points[(nrow(species.1$presence.points) + 1):nrow(part.points), 1:2] lines.df[i,] <- c(slope, intercept) if(type == "glm"){ rep.species.1.model <- enmtools.glm(rep.species.1, env, f, clamp = FALSE, ...) rep.species.2.model <- enmtools.glm(rep.species.2, env, f, clamp = FALSE, ...) } if(type == "gam"){ rep.species.1.model <- enmtools.gam(rep.species.1, env, f, clamp = FALSE, ...) rep.species.2.model <- enmtools.gam(rep.species.2, env, f, clamp = FALSE, ...) } if(type == "mx"){ rep.species.1.model <- enmtools.maxent(rep.species.1, env, clamp = FALSE, ...) rep.species.2.model <- enmtools.maxent(rep.species.2, env, clamp = FALSE, ...) } if(type == "bc"){ rep.species.1.model <- enmtools.bc(rep.species.1, env, clamp = FALSE, ...) rep.species.2.model <- enmtools.bc(rep.species.2, env, clamp = FALSE, ...) } if(type == "dm"){ rep.species.1.model <- enmtools.dm(rep.species.1, env, clamp = FALSE, ...) rep.species.2.model <- enmtools.dm(rep.species.2, env, clamp = FALSE, ...) } if(type == "rf"){ rep.species.1.model <- enmtools.rf(rep.species.1, env, clamp = FALSE, ...) rep.species.2.model <- enmtools.rf(rep.species.2, env, clamp = FALSE, ...) } if(low.memory == TRUE){ path.1 <- paste0(rep.dir, species.1$species.name, ".rep.", i, ".Rda") path.2 <- paste0(rep.dir, species.2$species.name, ".rep.", i, ".Rda") save(rep.species.1.model, file = path.1) save(rep.species.2.model, file = path.2) replicate.models[[paste0(species.1$species.name, ".rep.", i)]] <- path.1 replicate.models[[paste0(species.2$species.name, ".rep.", i)]] <- path.2 } else { replicate.models[[paste0(species.1$species.name, ".rep.", i)]] <- rep.species.1.model replicate.models[[paste0(species.2$species.name, ".rep.", i)]] <- rep.species.2.model } reps.overlap <- rbind(reps.overlap, c(unlist(raster.overlap(rep.species.1.model, rep.species.2.model)), unlist(env.overlap(rep.species.1.model, rep.species.2.model, env = env)[1:3]))) } rownames(reps.overlap) <- c("empirical", paste("rep", 1:nreps)) p.values <- apply(reps.overlap, 2, function(x) min(rank(x)[1], rank(-x)[1])/length(x)) d.plot <- qplot(reps.overlap[2:nrow(reps.overlap),"D"], geom = "histogram", fill = "density", alpha = 0.5) + geom_vline(xintercept = reps.overlap[1,"D"], linetype = "longdash") + xlim(-.05,1.05) + guides(fill = FALSE, alpha = FALSE) + xlab("D") + ggtitle(paste("Rangebreak test:\n", species.1$species.name, "vs.", species.2$species.name)) i.plot <- qplot(reps.overlap[2:nrow(reps.overlap),"I"], geom = "histogram", fill = "density", alpha = 0.5) + geom_vline(xintercept = reps.overlap[1,"I"], linetype = "longdash") + xlim(-.05,1.05) + guides(fill = FALSE, alpha = FALSE) + xlab("I") + ggtitle(paste("Rangebreak test:\n", species.1$species.name, "vs.", species.2$species.name)) cor.plot <- qplot(reps.overlap[2:nrow(reps.overlap),"rank.cor"], geom = "histogram", fill = "density", alpha = 0.5) + geom_vline(xintercept = reps.overlap[1,"rank.cor"], linetype = "longdash") + xlim(-1.05,1.05) + guides(fill = FALSE, alpha = FALSE) + xlab("Rank Correlation") + ggtitle(paste("Rangebreak test:\n", species.1$species.name, "vs.", species.2$species.name)) env.d.plot <- qplot(reps.overlap[2:nrow(reps.overlap),"env.D"], geom = "histogram", fill = "density", alpha = 0.5) + geom_vline(xintercept = reps.overlap[1,"env.D"], linetype = "longdash") + xlim(-.05,1.05) + guides(fill = FALSE, alpha = FALSE) + xlab("D, Environmental Space") + ggtitle(paste("Rangebreak test:\n", species.1$species.name, "vs.", species.2$species.name)) env.i.plot <- qplot(reps.overlap[2:nrow(reps.overlap),"env.I"], geom = "histogram", fill = "density", alpha = 0.5) + geom_vline(xintercept = reps.overlap[1,"env.I"], linetype = "longdash") + xlim(-.05,1.05) + guides(fill = FALSE, alpha = FALSE) + xlab("I, Environmental Space") + ggtitle(paste("Rangebreak test:\n", species.1$species.name, "vs.", species.2$species.name)) env.cor.plot <- qplot(reps.overlap[2:nrow(reps.overlap),"env.cor"], geom = "histogram", fill = "density", alpha = 0.5) + geom_vline(xintercept = reps.overlap[1,"env.cor"], linetype = "longdash") + xlim(-1.05,1.05) + guides(fill = FALSE, alpha = FALSE) + xlab("Rank Correlation, Environmental Space") + ggtitle(paste("Rangebreak test:\n", species.1$species.name, "vs.", species.2$species.name)) output <- list(description = paste("\n\nLinear rangebreak test", species.1$species.name, "vs.", species.2$species.name), reps.overlap = reps.overlap, p.values = p.values, empirical.species.1.model = empirical.species.1.model, empirical.species.2.model = empirical.species.2.model, replicate.models = replicate.models, lines.df = lines.df, d.plot = d.plot, i.plot = i.plot, cor.plot = cor.plot, env.d.plot = env.d.plot, env.i.plot = env.i.plot, env.cor.plot = env.cor.plot) class(output) <- "enmtools.rangebreak.linear" return(output) } rangebreak.linear.precheck <- function(species.1, species.2, env, type, f, nreps){ if(!inherits(species.1, "enmtools.species")){ stop("Species.1 is not an enmtools.species object!") } if(!inherits(species.2, "enmtools.species")){ stop("Species.2 is not an enmtools.species object!") } if(!inherits(env, c("raster", "RasterLayer", "RasterStack", "RasterBrick"))){ stop("Environmental layers are not a RasterLayer or RasterStack object!") } if(type == "glm"){ if(!is.null(f)){ if(!inherits(f, "formula")){ stop("Type is set to GLM and f is not a formula object!") } } } if(type == "gam"){ if(!is.null(f)){ if(!inherits(f, "formula")){ stop("Type is set to GAM and f is not a formula object!") } } } if(!type %in% c("glm", "mx", "bc", "dm", "gam", "rf")){ stop(paste("Model type", type, "not understood! Select either bc, dm, mx, gam, rf, or glm.")) } check.species(species.1) if(!inherits(species.1$presence.points, "data.frame")){ stop("Species 1 presence.points do not appear to be an object of class data.frame") } if(!inherits(species.1$background.points, "data.frame")){ stop("Species 1 background.points do not appear to be an object of class data.frame") } check.species(species.2) if(!inherits(species.2$presence.points, "data.frame")){ stop("Species 2 presence.points do not appear to be an object of class data.frame") } if(!inherits(species.2$background.points, "data.frame")){ stop("Species 2 background.points do not appear to be an object of class data.frame") } if(any(!colnames(species.1$background.points) %in% colnames(species.2$background.points))){ stop("Column names for species background points do not match!") } if(any(!colnames(species.1$presence.points) %in% colnames(species.2$presence.points))){ stop("Column names for species presence points do not match!") } if(is.na(species.1$species.name)){ stop("Species 1 does not have a species.name set!") } if(is.na(species.2$species.name)){ stop("Species 2 does not have a species.name set!") } } summary.enmtools.rangebreak.linear <- function(object, ...){ cat(paste("\n\n", object$description)) cat("\n\nrangebreak test p-values:\n") print(object$p.values) cat("\n\nReplicates:\n") print(kable(head(object$reps.overlap))) plot(object) } print.enmtools.rangebreak.linear <- function(x, ...){ summary(x) } plot.enmtools.rangebreak.linear <- function(x, ...){ x.raster <- x$empirical.species.1.model$suitability x.raster[!is.na(x.raster)] <- 1 raster::plot(x.raster) for(i in 1:nrow(x$lines.df)){ abline(x$lines.df[i,2], x$lines.df[i,1]) } grid.arrange(x$d.plot, x$env.d.plot, x$i.plot, x$env.i.plot, x$cor.plot, x$env.cor.plot, ncol = 2) + theme(plot.title = element_text(hjust = 0.5)) }
hexen<-function(center_x,center_y,radii,cols,border=FALSE,asp=1){ x<-as.vector(t(outer(radii,tri_x)+center_x)) y<-as.vector(t(outer(radii*asp,tri_y)+center_y)) polygon(x,y,col=as.vector(t(cols)),border=if(border) NA else as.vector(t(cols))) invisible(list(x=x,y=y,col=as.vector(t(cols)))) } sainte_lague= function(votes, nseats){ nparties<-length(votes) denominators=2*(1:nseats)-1 quotients = outer(votes, denominators, "/") last = sort(quotients,decreasing=TRUE)[nseats] clear<-rowSums(quotients>last) borderline<-rowSums(quotients==last) borderline[sample(which(borderline>0),sum(borderline)-(nseats-sum(clear)))]<-0 total<-clear+borderline error<- votes- sum(votes)*total/6 rval<-rep(1:nparties,clear+borderline) attr(rval,"error")<-error rval } hextri<-function(x, ...){ UseMethod("hextri")} hextri.formula<-function(x, data=parent.frame(), class,colours,nbins=10,border=TRUE, diffuse=FALSE, style=c("alpha","size"),weights=NULL,sorted=!diffuse,xlab=NULL, ylab=NULL,...){ if ((length(x)!=3) || length(x[[3]])>2) stop("formula must have one LHS and one RHS term") m<-match.call(expand.dots=FALSE) m$formula<-m$x m$x<-m$colours<-m$nbins<-m$border<-m$diffuse<-m$style<-m$sorted<-m$"..."<-NULL m[[1]]<-as.name("model.frame") mf<-eval.parent(m) .y<-mf[[1]] .x<-mf[[2]] class<-mf[["(class)"]] wt<-mf[["(weights)"]] labels<-sapply(attr(terms(x),"variables"), deparse)[-1] if (is.null(ylab)) ylab<-labels[1] if (is.null(xlab)) xlab<-labels[2] hextri(.x,.y,class=class,weights=wt, colours=colours, nbins=nbins, border=border, diffuse=diffuse, style=style, sorted=sorted, xlab=xlab,ylab=ylab,...) } hextri.default<-function(x,y,class,colours,nbins=10,border=TRUE, diffuse=FALSE, style=c("alpha","size"),weights=NULL,sorted=!diffuse,...){ style<-match.arg(style) if(!diffuse){ switch(style, size=hexclass(x,y,class,colours,nbins=nbins,border=border,weights=weights,sorted=sorted,...), alpha=hexclass1(x,y,class,colours,nbins=nbins,border=border,weights=weights,sorted=sorted,...) ) } else { switch(style, size=hexclass_diffuse(x,y,class,colours,nbins=nbins,border=border,weights=weights,sorted=sorted,...), alpha=hexclass1_diffuse(x,y,class,colours,nbins=nbins,border=border,weights=weights,sorted=sorted,...) ) } } hexclass<-function(x,y,class,colours,nbins=10,border=FALSE,weights=NULL,sorted,...){ plot(x,y,type="n",...) pin<-par("pin") h<-hexbin(x,y,IDs=TRUE,xbins=nbins,shape=pin[2]/pin[1]) centers<-hcell2xy(h) asp<-(diff(h@ybnds)/diff(h@xbnds))/h@shape if (is.null(weights)) tab<-table(h@cID,class) else tab<-xtabs(weights~h@cID+class) allocations<-apply(tab,1,sainte_lague,6) if(!sorted) allocations<-apply(allocations,1,sample) full_radius<-diff(h@xbnds)/h@xbins/sqrt(3) radii<-full_radius*sqrt(h@count/max(h@count)) col_matrix<-matrix(colours[t(allocations)],nrow=ncol(allocations)) hexen(centers$x,centers$y,radii, col_matrix,border=border,asp=asp) } hexclass1<-function(x,y,class,colours,nbins=10,border=FALSE,weights=NULL,sorted,...){ plot(x,y,type="n",...) pin<-par("pin") h<-hexbin(x,y,IDs=TRUE,xbins=nbins,shape=pin[2]/pin[1]) centers<-hcell2xy(h) asp<-(diff(h@ybnds)/diff(h@xbnds))/h@shape if (is.null(weights)) tab<-table(h@cID,class) else tab<-xtabs(weights~h@cID+class) allocations<-apply(tab,1,sainte_lague,6) if(!sorted) allocations<-apply(allocations,1,sample) full_radius<-diff(h@xbnds)/h@xbins/sqrt(3) alpha<-rowSums(tab)/max(rowSums(tab)) all_colours<-colours[t(allocations)] rgb<-col2rgb(all_colours) alpha_colours<-rgb(rgb[1,],rgb[2,],rgb[3,],255*alpha,max=255) col_matrix<-matrix(alpha_colours,nrow=ncol(allocations)) hexen(centers$x,centers$y,rep(0.95*full_radius,length(centers$x)), col_matrix,border=border,asp=asp) } hexclass_diffuse<-function(x,y,class,colours,nbins=10,border=FALSE,weights=NULL,sorted,...){ plot(x,y,type="n",...) pin<-par("pin") h<-hexbin(x,y,IDs=TRUE,xbins=nbins,shape=pin[2]/pin[1]) centers<-hcell2xy(h) asp<-(diff(h@ybnds)/diff(h@xbnds))/h@shape if (is.null(weights)) tab<-table(h@cID,class) else tab<-xtabs(weights~h@cID+class) allocations<-diffuse(h,tab,sorted) full_radius<-diff(h@xbnds)/h@xbins/sqrt(3) radii<-full_radius*sqrt(h@count/max(h@count)) col_matrix<-matrix(colours[t(allocations)],nrow=ncol(allocations)) hexen(centers$x,centers$y,radii, col_matrix,border=border,asp=asp) } hexclass1_diffuse<-function(x,y,class,colours,nbins=10,border=FALSE,weights=NULL,sorted,...){ plot(x,y,type="n",...) pin<-par("pin") h<-hexbin(x,y,IDs=TRUE,xbins=nbins,shape=pin[2]/pin[1]) centers<-hcell2xy(h) asp<-(diff(h@ybnds)/diff(h@xbnds))/h@shape if (is.null(weights)) tab<-table(h@cID,class) else tab<-xtabs(weights~h@cID+class) allocations<-diffuse(h,tab,sorted) full_radius<-diff(h@xbnds)/h@xbins/sqrt(3) alpha<-rowSums(tab)/max(rowSums(tab)) all_colours<-colours[t(allocations)] rgb<-col2rgb(all_colours) alpha_colours<-rgb(rgb[1,],rgb[2,],rgb[3,],255*alpha,max=255) col_matrix<-matrix(alpha_colours,nrow=ncol(allocations)) hexen(centers$x,centers$y,rep(0.95*full_radius,length(centers$x)), col_matrix,border=border,asp=asp) }
'_PACKAGE' localDensity <- function(distance, dc, gaussian = FALSE) { if (gaussian) { res <- gaussianLocalDensity(distance, attr(distance, "Size"), dc) } else { res <- nonGaussianLocalDensity(distance, attr(distance, "Size"), dc) } if (is.null(attr(distance, 'Labels'))) { names(res) <- NULL } else { names(res) <- attr(distance, 'Labels') } res } distanceToPeak <- function(distance, rho) { res <- distanceToPeakCpp(distance, rho); names(res) <- names(rho) res } estimateDc <- function(distance, neighborRateLow = 0.01, neighborRateHigh = 0.02) { size <- attr(distance, 'Size') if (size > 448) { distance <- distance[sample.int(length(distance), 100128)] size <- 448 } low <- min(distance) high <- max(distance) dc <- 0 while (TRUE) { dc <- (low + high) / 2 neighborRate <- (((sum(distance < dc) * 2 + (if (0 <= dc) size)) / size - 1)) / size if (neighborRate >= neighborRateLow && neighborRate <= neighborRateHigh) break if (neighborRate < neighborRateLow) { low <- dc } else { high <- dc } } cat('Distance cutoff calculated to', dc, '\n') dc } densityClust <- function(distance, dc, gaussian=FALSE, verbose = FALSE, ...) { if (class(distance) %in% c('data.frame', 'matrix')) { dp_knn_args <- list(mat = distance, verbose = verbose, ...) res <- do.call(densityClust.knn, dp_knn_args) } else { if (missing(dc)) { if (verbose) message('Calculating the distance cutoff') dc <- estimateDc(distance) } if (verbose) message('Calculating the local density for each sample based on distance cutoff') rho <- localDensity(distance, dc, gaussian = gaussian) if (verbose) message('Calculating the minimal distance of a sample to another sample with higher density') delta <- distanceToPeak(distance, rho) if (verbose) message('Returning result...') res <- list( rho = rho, delta = delta, distance = distance, dc = dc, threshold = c(rho = NA, delta = NA), peaks = NA, clusters = NA, halo = NA, knn_graph = NA, nearest_higher_density_neighbor = NA, nn.index = NA, nn.dist = NA ) class(res) <- 'densityCluster' } res } plot.densityCluster <- function(x, ...) { plot(x$rho, x$delta, main = 'Decision graph', xlab = expression(rho), ylab = expression(delta)) if (!is.na(x$peaks[1])) { points(x$rho[x$peaks], x$delta[x$peaks], col = 2:(1 + length(x$peaks)), pch = 19) } } plotMDS <- function(x, ...) { UseMethod('plotMDS') } plotMDS.densityCluster <- function(x, ...) { if (class(x$distance) %in% c('data.frame', 'matrix')) { mds <- cmdscale(dist(x$distance)) } else { mds <- cmdscale(x$distance) } plot(mds[,1], mds[,2], xlab = '', ylab = '', main = 'MDS plot of observations') if (!is.na(x$peaks[1])) { for (i in 1:length(x$peaks)) { ind <- which(x$clusters == i) points(mds[ind, 1], mds[ind, 2], col = i + 1, pch = ifelse(x$halo[ind], 1, 19)) } legend('topright', legend = c('core', 'halo'), pch = c(19, 1), horiz = TRUE) } } plotTSNE <- function(x, ...) { UseMethod('plotTSNE') } plotTSNE.densityCluster <- function(x, max_components = 2, ...) { if (class(x$distance) %in% c('data.frame', 'matrix')) { data <- as.matrix(dist(x$distance)) } else { data <- as.matrix(x$distance) } dup_id <- which(duplicated(data)) if (length(dup_id) > 0) { data[dup_id, ] <- data[dup_id, ] + rnorm(length(dup_id) * ncol(data), sd = 1e-10) } tsne_res <- Rtsne::Rtsne(as.matrix(data), dims = max_components, pca = T) tsne_data <- tsne_res$Y[, 1:max_components] plot(tsne_data[,1], tsne_data[,2], xlab = '', ylab = '', main = 'tSNE plot of observations') if (!is.na(x$peaks[1])) { for (i in 1:length(x$peaks)) { ind <- which(x$clusters == i) points(tsne_data[ind, 1], tsne_data[ind, 2], col = i + 1, pch = ifelse(x$halo[ind], 1, 19)) } legend('topright', legend = c('core', 'halo'), pch = c(19, 1), horiz = TRUE) } } print.densityCluster <- function(x, ...) { if (is.na(x$peaks[1])) { cat('A densityCluster object with no clusters defined\n\n') cat('Number of observations:', length(x$rho), '\n') } else { cat('A densityCluster object with', length(x$peaks), 'clusters defined\n\n') cat('Number of observations:', length(x$rho), '\n') cat('Observations in core: ', sum(!x$halo), '\n\n') cat('Parameters:\n') cat('dc (distance cutoff) rho threshold delta threshold\n') cat(formatC(x$dc, width = -22), formatC(x$threshold[1], width = -22), x$threshold[2]) } } findClusters <- function(x, ...) { UseMethod("findClusters") } findClusters.densityCluster <- function(x, rho, delta, plot = FALSE, peaks = NULL, verbose = FALSE, ...) { if (class(x$distance) %in% c('data.frame', 'matrix')) { peak_ind <- which(x$rho > rho & x$delta > delta) x$peaks <- peak_ind runOrder <- order(x$rho, decreasing = TRUE) cluster <- rep(NA, length(x$rho)) for (i in x$peaks) { cluster[i] <- match(i, x$peaks) } for (ind in setdiff(runOrder, x$peaks)) { target_lower_density_samples <- which(x$nearest_higher_density_neighbor == ind) cluster[ind] <- cluster[x$nearest_higher_density_neighbor[ind]] } potential_duplicates <- which(is.na(cluster)) for (ind in potential_duplicates) { res <- as.integer(names(which.max(table(cluster[x$nn.index[ind, ]])))) if (length(res) > 0) { cluster[ind] <- res } else { message('try to increase the number of kNN (through argument k) at step of densityClust.') cluster[ind] <- NA } } x$clusters <- factor(cluster) border <- rep(0, length(x$peaks)) if (verbose) message('Identifying core and halo for each cluster') for (i in 1:length(x$peaks)) { if (verbose) message('the current index of the peak is ', i) connect_samples_ind <- intersect(unique(x$nn.index[cluster == i, ]), which(cluster != i)) averageRho <- outer(x$rho[cluster == i], x$rho[connect_samples_ind], '+') / 2 if (any(connect_samples_ind)) border[i] <- max(averageRho[connect_samples_ind]) } x$halo <- x$rho < border[cluster] x$threshold['rho'] <- rho x$threshold['delta'] <- delta } else { if (!is.null(peaks)) { if (verbose) message('peaks are provided, clustering will be performed based on them') x$peaks <- peaks } else { if (missing(rho) || missing(delta)) { x$peaks <- NA plot(x) cat('Click on plot to select thresholds\n') threshold <- locator(1) if (missing(rho)) rho <- threshold$x if (missing(delta)) delta <- threshold$y plot = TRUE } x$peaks <- which(x$rho > rho & x$delta > delta) x$threshold['rho'] <- rho x$threshold['delta'] <- delta } if (plot) { plot(x) } runOrder <- order(x$rho, decreasing = TRUE) cluster <- rep(NA, length(x$rho)) if (verbose) message('Assigning each sample to a cluster based on its nearest density peak') for (i in runOrder) { if ((i %% round(length(runOrder) / 25)) == 0) { if (verbose) message(paste('the runOrder index is', i)) } if (i %in% x$peaks) { cluster[i] <- match(i, x$peaks) } else { higherDensity <- which(x$rho > x$rho[i]) cluster[i] <- cluster[higherDensity[which.min(findDistValueByRowColInd(x$distance, attr(x$distance, 'Size'), i, higherDensity))]] } } x$clusters <- cluster border <- rep(0, length(x$peaks)) if (verbose) message('Identifying core and halo for each cluster') for (i in 1:length(x$peaks)) { if (verbose) message('the current index of the peak is ', i) averageRho <- outer(x$rho[cluster == i], x$rho[cluster != i], '+')/2 index <- findDistValueByRowColInd(x$distance, attr(x$distance, 'Size'), which(cluster == i), which(cluster != i)) <= x$dc if (any(index)) border[i] <- max(averageRho[index]) } x$halo <- x$rho < border[cluster] } x$halo <- x$rho < border[cluster] gamma <- x$rho * x$delta pk.ordr <- order(gamma[x$peaks], decreasing = TRUE) x$peaks <- x$peaks[pk.ordr] x$clusters <- match(x$clusters, pk.ordr) x } clusters <- function(x, ...) { UseMethod("clusters") } clusters.densityCluster <- function(x, as.list = FALSE, halo.rm = TRUE, ...) { if (!clustered(x)) stop('x must be clustered prior to cluster extraction') res <- x$clusters if (halo.rm) { res[x$halo] <- NA } if (as.list) { res <- split(1:length(res), res) } res } clustered <- function(x) { UseMethod("clustered") } clustered.densityCluster <- function(x) { !any(is.na(x$peaks[1]), is.na(x$clusters[1]), is.na(x$halo[1])) } labels.densityCluster <- function(object, ...) { labels(object$distance) } densityClust.knn <- function(mat, k = NULL, verbose = F, ...) { if (is.null(k)) { k <- round(sqrt(nrow(mat)) / 2) k <- max(10, k) } if (verbose) message('Finding kNN using FNN with ', k, ' neighbors') dx <- get.knn(mat, k = k, ...) nn.index <- dx$nn.index nn.dist <- dx$nn.dist N <- nrow(nn.index) knn_graph <- NULL if (verbose) message('Calculating the local density for each sample based on kNNs ...') rho <- apply(nn.dist, 1, function(x) { exp(-mean(x)) }) if (verbose) message('Calculating the minimal distance of a sample to another sample with higher density ...') rho_order <- order(rho) delta <- vector(mode = 'integer', length = N) nearest_higher_density_neighbor <- vector(mode = 'integer', length = N) delta_neighbor_tmp <- smallest_dist_rho_order_coords(rho[rho_order], as.matrix(mat[rho_order, ])) delta[rho_order] <- delta_neighbor_tmp$smallest_dist nearest_higher_density_neighbor[rho_order] <- rho_order[delta_neighbor_tmp$nearest_higher_density_sample + 1] if (verbose) message('Returning result...') res <- list( rho = rho, delta = delta, distance = mat, dc = NULL, threshold = c(rho = NA, delta = NA), peaks = NA, clusters = NA, halo = NA, knn_graph = knn_graph, nearest_higher_density_neighbor = nearest_higher_density_neighbor, nn.index = nn.index, nn.dist = nn.dist ) class(res) <- 'densityCluster' res }
set.seed(1235) N = 10000 k = 2 X = matrix(rnorm(N * k), ncol = k) lp = -.5 + .2 * X[, 1] + .1 * X[, 2] y = rbinom(N, size = 1, prob = plogis(lp)) dfXy = data.frame(X, y) logreg_ML = function(par, X, y) { beta = par N = nrow(X) LP = X %*% beta mu = plogis(LP) L = dbinom(y, size = 1, prob = mu, log = TRUE) -sum(L) } logreg_exp = function(par, X, y) { beta = par LP = X %*% beta L = sum(exp(-ifelse(y, 1, -1) * .5 * LP)) } X = cbind(1, X) init = rep(0, ncol(X)) names(init) = c('intercept', 'b1', 'b2') optlmML = optim( par = init, fn = logreg_ML, X = X, y = y, control = list(reltol = 1e-8) ) optglmClass = optim( par = init, fn = logreg_exp, X = X, y = y, control = list(reltol = 1e-15) ) pars_ML = optlmML$par pars_exp = optglmClass$par modglm = glm(y ~ ., dfXy, family = binomial) rbind( pars_ML, pars_exp, pars_GLM = coef(modglm) )
context("Get parent station") data_path <- system.file("extdata/ggl_gtfs.zip", package = "gtfstools") gtfs <- read_gtfs(data_path) test_that("raises errors due to incorrect input types/value", { no_class_gtfs <- unclass(gtfs) expect_error(get_parent_station(no_class_gtfs)) expect_error(get_parent_station(gtfs, as.factor("N1"))) }) test_that("raises errors if reqrd fields do not exist or have the right type", { no_stops_gtfs <- copy_gtfs_without_file(gtfs, "stops") no_stp_id_gtfs <- copy_gtfs_without_field(gtfs, "stops", "stop_id") no_prt_st_gtfs <- copy_gtfs_without_field(gtfs, "stops", "parent_station") wrong_stp_id_gtfs <- copy_gtfs_diff_field_class( gtfs, "stops", "stop_id", "factor" ) wrong_prt_st_gtfs <- copy_gtfs_diff_field_class( gtfs, "stops", "parent_station", "factor" ) expect_error(get_parent_station(no_stops_gtfs, "N1")) expect_error(get_parent_station(no_stp_id_gtfs, "N1")) expect_error(get_parent_station(no_prt_st_gtfs, "N1")) expect_error(get_parent_station(wrong_stp_id_gtfs, "N1")) expect_error(get_parent_station(wrong_prt_st_gtfs, "N1")) }) test_that("raises warnings if a non_existent stop_id is passed", { expect_warning(get_parent_station(gtfs, c("N1", "ola"))) expect_warning(get_parent_station(gtfs, "ola")) }) test_that("outputs a data.table with adequate columns' classes", { parents <- get_parent_station(gtfs, "N1") expect_s3_class(parents, "data.table") expect_vector(parents$stop_id, character(0)) expect_vector(parents$parent_station, character(0)) expect_warning(parents <- get_parent_station(gtfs, "ola")) expect_s3_class(parents, "data.table") expect_vector(parents$stop_id, character(0)) expect_vector(parents$parent_station, character(0)) }) test_that("returns parents correctly", { parents <- get_parent_station(gtfs, "F12") expect_identical( parents, data.table::data.table(stop_id = "F12", parent_station = "") ) parents <- get_parent_station(gtfs, "B1") expect_identical( parents, data.table::data.table( stop_id = c("B1", "F12S", "F12"), parent_station = c("F12S", "F12", "") ) ) expect_warning(parents <- get_parent_station(gtfs, "ola")) expect_identical( parents, data.table::data.table( stop_id = character(0), parent_station = character(0) ) ) }) test_that("doesn't change original gtfs", { original_gtfs <- read_gtfs(data_path) gtfs <- read_gtfs(data_path) expect_identical(original_gtfs, gtfs) parents <- get_parent_station(gtfs, "B1") expect_identical(original_gtfs, gtfs) }) test_that("unlisted parent_stations do not introduce NAs", { ber_path <- system.file("extdata/ber_gtfs.zip", package = "gtfstools") ber_gtfs <- read_gtfs(ber_path) ber_shapes <- c("14", "2") smaller_ber <- filter_by_shape_id(ber_gtfs, ber_shapes) parents <- get_parent_station(ber_gtfs, smaller_ber$stop_times$stop_id) expect_false(any(is.na(parents$stop_id))) expect_false(any(is.na(parents$parent_station))) })
dbplyr_compatible <- function(function_name) { if (utils::packageVersion('dplyr') >= '0.5.0.9004') { if (!requireNamespace('dbplyr', quietly=TRUE)) { stop(function_name, ' requires the dbplyr package, please install it ', 'first and try again' ) } f <- utils::getFromNamespace(function_name, 'dbplyr') } else { f <- utils::getFromNamespace(function_name, 'dplyr') } return(f) }
context("test scan_test related functions") data(nydf) cases = floor(nydf$cases) pop = nydf$pop ty = sum(cases) tpop = sum(pop) ex = ty / tpop * pop zone = c(52, 50, 53, 38, 49, 48, 15, 39, 37, 1, 16, 44, 47, 40, 14, 2, 51, 13, 43, 45, 17, 55, 11, 3, 12, 46, 36, 35, 54, 10, 5) yin = sum(cases[zone]) ein = sum(ex[zone]) yout = ty - yin eout = ty - ein t1 = scan.stat(yin = yin, ty = ty, ein = ein) t1_ = scan_stat(yin = yin, ty = ty, ein = ein) t2 = stat.poisson(yin = yin, yout = yout, ein = ein, eout = eout) t2_ = stat_poisson(yin = yin, yout = yout, ein = ein, eout = eout) zone = c(1, 2, 3, 12, 13, 14, 15, 35, 47, 49) yin = sum(cases[zone]) popin = sum(pop[zone]) yout = ty - yin popout = tpop - popin t3 = scan.stat(yin = yin, ty = ty, popin = popin, tpop = tpop, type = "binomial") t3_ = scan_stat(yin = yin, ty = ty, popin = popin, tpop = tpop, type = "binomial") t4 = stat.binom(yin = yin, yout = yout, ty = ty, popin = popin, popout = popout, tpop = tpop) t4_ = stat_binom(yin = yin, yout = yout, ty = ty, popin = popin, popout = popout, tpop = tpop) test_that("check accuracy for scan_test for NY data", { expect_equal(round(t1, 6), 14.780276) expect_equal(round(t2, 6), 14.780276) expect_equal(round(t3, 5), 8.47836) expect_equal(round(t4, 5), 8.47836) expect_equal(t1, t1_) expect_equal(t2, t2_) expect_equal(t3, t3_) expect_equal(t4, t4_) })
setup_grass_environment <- function(dem, gisBase, epsg = NULL, sites = NULL, ...){ if(!is.null(sites)) message(writeLines(strwrap("'sites' is no longer a parameter of setup_grass_environment (see help).\n The function will still execute normally. Please update your code.", width = 80))) if(!is.null(epsg)) message(writeLines(strwrap("'epsg' is no longer a parameter of setup_grass_environment (see help).\n The function will still execute normally. Please update your code.", width = 80))) use_sp() dem_grid <- rgdal::readGDAL(dem, silent = TRUE) initGRASS(gisBase = gisBase, SG = dem_grid, mapset = "PERMANENT", ...) execGRASS("g.proj", flags = c("c", "quiet"), parameters = list( georef = dem )) } grass_v.to.db <- function(map, option, type = "line", columns, format){ execGRASS("v.db.addcolumn", flags = "quiet", parameters = list( map = map, columns = paste0(paste(columns, format), collapse = ",") )) check <- try(execGRASS("v.to.db", flags = c("quiet"), parameters = list( map = map, option = option, type = type, columns = paste(columns, collapse = ",") ), ignore.stderr = TRUE), silent = TRUE) if(class(check) == "try-error"){ execGRASS("v.db.dropcolumn", flags = "quiet", parameters = list( map = map, columns = paste0(columns, collapse = ",") )) execGRASS("v.to.db", flags = c("quiet"), parameters = list( map = map, option = option, type = type, columns = paste(columns, collapse = ",") ), ignore.stderr = TRUE) } }
as.mxMatrix <- function(x, name, ...) { if (!is.matrix(x)) { x <- as.matrix(x) } nRow <- nrow(x) nCol <- ncol(x) if (missing(name)) { name <- as.character(match.call())[2] if (grepl("$", name, fixed=TRUE)) { name <- strsplit(name, "$", fixed=TRUE)[[1]][2] } } values <- suppressWarnings(as.numeric(x)) free <- is.na(values) freePara1 <- x[free] if (length(freePara1)>0) { freePara2 <- strsplit(freePara1, "*", fixed=TRUE) values[free] <- suppressWarnings(sapply(freePara2, function(x){ as.numeric(x[1])})) labels <- matrix(NA, ncol=nCol, nrow=nRow) labels[free] <- sapply(freePara2, function(x){ x[2]}) free[grep("data.", labels)] <- FALSE free[grep("\\[|,|\\]", labels)] <- FALSE x_pos <- grep("@", x, fixed=TRUE) if (length(x_pos)>0) { x_at <- strsplit(x=x[x_pos], split="@", fixed=TRUE) for (i in seq_along(x_at)) { values[x_pos[i]] <- as.numeric(x_at[[i]][1]) labels[x_pos[i]] <- x_at[[i]][2] free[x_pos[i]] <- FALSE } } out <- mxMatrix(type = "Full", nrow=nRow, ncol=nCol, values=values, free=free, name=name, labels=labels, ...) } else { out <- mxMatrix(type = "Full", nrow=nRow, ncol=nCol, values=values, free=free, name=name, ...) } if (!is.null(dimnames(x))) { if (!is.null(rownames(x))) { if (rownames(x)[1] != "1") { dim.names <- lapply(dimnames(x), make.names) dimnames(out@values) <- dimnames(out@labels) <- dimnames(out@free) <- dim.names } } } out } as.symMatrix <- function(x) { if (is.list(x)) { for (i in seq_along(x)) { x[[i]][] <- vapply(x[[i]], function(z) gsub(".*\\*", "", z), character(1)) } } else { x[] <- vapply(x, function(z) gsub(".*\\*", "", z), character(1)) } x } as.mxAlgebra <- function(x, name="X") { vars <- sort(all.vars(parse(text=x))) Xvars <- create.mxMatrix(paste0("0*", vars), ncol=1, nrow=length(vars)) Xvars@name <- paste0(name, "vars") xrow <- nrow(x) xcol <- ncol(x) for (j in seq_len(xcol)) for (i in seq_len(xrow)) { Xij <- paste0(name,i,"_",j, " <- mxAlgebra(",x[i,j], ", name='",name,i,"_",j,"')") eval(parse(text=Xij)) } Xmat <- outer(seq_len(xrow), seq_len(xcol), function(x, y) paste0(name,x,"_",y)) Xmat <- paste0("cbind(", apply(Xmat, 1, paste0, collapse=", "), ")") Xmatrix <- paste0(name, " <- mxAlgebra(rbind(", paste0(Xmat, collapse=", "), "), name='", name,"')") eval(parse(text=Xmatrix)) Xlist <- outer(seq_len(xrow), seq_len(xcol), function(x,y) paste0(name,x,"_",y)) Xnames <- c(name, Xvars@name, Xlist) Xlist <- paste0("list(", paste0(Xlist, "=", Xlist, collapse=", "), ")") Xlist <- eval(parse(text=Xlist)) out <- paste0("out <- list(", name, "=", name, ", names=Xnames, ", name, "vars=Xvars, ", name, "list=Xlist",")" ) eval(parse(text=out)) out }
a_full=function(r0){ val=(r0<0.7)*a(r0)+(r0>=0.7)*(r0<=0.997)*a_medium(r0)+(r0>0.997)*exp(2.877)/sqrt(252)/(1-r0)^0.163 return(val) } f_full=function(x){ return(ifelse(x<3,f(x),f(3))) } b=function(r0,N){ r0Nalpha=r0*N^.42 return(exp(f_full(r0Nalpha))*r0^1.6) } theta=function(r0,N,nu,nu_fixed){ myEstimate=a_full(abs(r0))-b(abs(r0),N)*nu^(-1.5) myEstimate=myEstimate * (sign(myEstimate)>0) myEstimate=myEstimate * sign(r0) if(nu_fixed){ myEstimate=myEstimate*(1-(exp(3.7726-6.2661*log(nu))-exp(-0.36538*nu-1.58686)))*(1-0.009248) }else{ myEstimate=myEstimate*((1-(exp(4.4635-6.9240*log(nu))-exp(-0.18441*nu-3.18909)))*(1+exp(-log(nu)*3.2+0.9)-0.009248)) } return(myEstimate) } Test.N = function(x) { x=x[is.finite(x)] n = length(x) q1 = quantile(x,0.2 ) q2 = quantile(x,0.8 ) low = x [ x <= q1 ] med = x [ x > q1 & x < q2 ] high = x [ x >= q2 ] N = var(low)+var(high)-2*var(med) N = N*sqrt(n)/(var(x)*1.8) return(N) } estimateSNR=function(x,numPerm=NA,nu=NA,quantiles=c(0.05,0.95)){ if(is.na(nu)) nu_fixed=FALSE else nu_fixed=TRUE if(length(x)<1){ return(NULL) } x=x[is.finite(x)] N=length(x) if(N<1){ return(NULL) } if(!is.finite(numPerm)){ numPerm=min(100,ceiling(3*log(N))) } x=as.numeric(x) if(is.na(nu) || nu<0 ){ if(abs(Test.N(x))<3){ nu=1e13 }else{ myfit=tryCatch(ghyp::fit.tuv(x,silent=TRUE,nu=6),error=function(e){return(NA)}) if(!class(myfit)=="mle.ghyp"){ nu=1e13 }else{ nu=coef(myfit)$nu } } } R0bar_res=computeR0bar(x,numPerm = numPerm) R0bar=R0bar_res$mean if(abs(R0bar)<1){ R0bar=0 return(list(nu=nu,SNR=0,R0bar=0,N=length(x))) } SNR=theta(R0bar/N,N,nu,nu_fixed) SNR_q1=theta(R0bar_res$q1/N,N,nu,nu_fixed) SNR_q2=theta(R0bar_res$q2/N,N,nu,nu_fixed) return(list(SNR=SNR,SNR.ci=c(SNR_q1,SNR_q2),nu=nu,R0bar=R0bar,N=length(x))) } .onUnload <- function (libpath) { library.dynam.unload("sharpeRratio", libpath) }
"data123"
gjam <- function(formula, xdata, ydata, modelList){ .gjam(formula, xdata, ydata, modelList) }
sampling.robustness <- function(df, subsampling = c(5, 10, 20, 30, 40, 50), metric = "met.strength", assoc.indices = FALSE, actor, receiver, scan, id, index = "sri",progress = TRUE, ...) { op <- par(no.readonly = TRUE) on.exit(par(op)) par(bg = "gray63") percent <- (subsampling * nrow(df)) / 100 if (!assoc.indices) { if(is.null(actor) | is.null(receiver)){stop("Arguments 'actor' and 'receiver' cannot be NULL.")} col.actor <- df.col.findId(df, actor) col.receiver <- df.col.findId(df, receiver) M <- df.to.mat(df, actor = col.actor, receiver = col.receiver) met <- do.call(metric, list(M = M, ...)) names <- colnames(M) result <- rep(list(met), length(subsampling) + 1) for (a in 1:length(subsampling)) { if(progress){cat(" Processing bootstrap : ", a, "\r")} tmp <- df[-sample(1:nrow(df), percent[a], replace = FALSE), ] M <- df.to.mat(tmp, actor = col.actor, receiver = col.receiver) result[[a + 1]] <- do.call(metric, list(M = M)) } } else { if(is.null(scan) | is.null(id)){stop("Arguments 'scan' and 'id' cannot be NULL.")} col.scan <- df.col.findId(df, scan) col.id <- df.col.findId(df, id) gbi <- df.to.gbi(df, scan = col.scan, id = col.id) M <- assoc.indices(gbi, index) met <- do.call(metric, list(M = M, ...)) names <- colnames(M) result <- rep(list(met), length(subsampling) + 1) for (a in 1:length(subsampling)) { if(progress){cat(" Processing bootstrap : ", a, "\r")} tmp <- df[-sample(1:nrow(df), percent[a], replace = FALSE), ] gbi <- df.to.gbi(tmp, scan = col.scan, id = col.id) M <- assoc.indices(gbi, index) result[[a + 1]] <- do.call(metric, list(M = M, ...)) } } if (length(met) > 1){ result <- do.call(rbind, lapply(result, "[", names)) boxplot(result[-1, ], ylim=c(min(result, na.rm = TRUE), max(result, na.rm = TRUE))) stripchart(result[1, ]~c(1:ncol(result)), vertical = T, method = "jitter", pch = 21, col = "white", bg = "white", add = TRUE ) attr(result, "ANT") <- "Bootsraping deletions" return <- list("metrics" = result, "summary" = summary(result[-1, ])) } else{ result <- unlist(result) boxplot(result[-1], ylim=c(min(result, na.rm = TRUE), max(result, na.rm = TRUE))) stripchart(result[1], vertical = T, method = "jitter", pch = 21, col = "white", bg = "white", add = TRUE ) attr(result, "ANT") <- "Bootsrapping deletions" return <- list("metrics" = result, "summary" = summary(result[-1])) } }
context("gnr_resolve") test_that("gnr_resolve returns the correct value", { skip_on_cran() tmp <- gnr_resolve(c("Helianthus annuus", "Homo sapiens")) expect_equal(NCOL(tmp), 5) expect_is(tmp, "data.frame") expect_is(tmp$matched_name, "character") }) test_that("best_match_only works correctly", { skip_on_cran() x <- 'Aconitum degeni subsp. paniculatum' a <- gnr_resolve(x, best_match_only = TRUE) b <- gnr_resolve(x, best_match_only = FALSE) expect_is(a, "data.frame") expect_is(b, "data.frame") expect_equal(NROW(a), 0) expect_equal(attributes(a)$not_known, x) expect_named(attributes(a), c("names", "row.names", "class", "not_known")) expect_is(b$data_source_title, "character") cc <- gnr_resolve(c("Homo sapiens", "Helianthus annuus"), best_match_only = TRUE) expect_identical(cc$user_supplied_name, c("Homo sapiens", "Helianthus annuus")) }) test_that("canonical works correctly", { skip_on_cran() x <- gnr_resolve("Metzgeria", data_source_ids = c(12), canonical = TRUE) y <- "Helianthus annuus" w <- gnr_resolve(y, canonical = TRUE) z <- gnr_resolve(y, canonical = FALSE) expect_is(w, "data.frame") expect_is(z, "data.frame") expect_named(w, c("user_supplied_name", "submitted_name", "data_source_title", "score", "matched_name2")) expect_named(z, c("user_supplied_name", "submitted_name", "matched_name", "data_source_title", "score")) expect_equal(NROW(x), 1) expect_true(is.na(x$matched_name2[2])) }) test_that("fields parameter works correctly", { skip_on_cran() tmp1 <- gnr_resolve(c("Asteraceae", "Plantae"), fields = 'all') tmp2 <- gnr_resolve(c("Asteraceae", "Plantae"), fields = 'minimal') expect_is(tmp1, "data.frame") expect_is(tmp1$matched_name, "character") expect_true(any(grepl("Asteraceae", tmp1$matched_name))) expect_is(tmp2, "data.frame") expect_is(tmp2$matched_name, "character") expect_true(any(grepl("Asteraceae", tmp2$matched_name))) expect_false(identical(tmp1$matched_name, tmp2$matched_name)) expect_lt(NCOL(tmp2), NCOL(tmp1)) }) test_that("works correctly when no data found for preferred data source", { skip_on_cran() aa <- gnr_resolve("Scabiosa triandra", preferred_data_sources = c(21,24), best_match_only = TRUE) expect_is(aa, "data.frame") expect_equal(NROW(aa), 0) expect_equal(length(attributes(aa)$not_known), 1) })
.multinomialCoef <- function(x) { n <- nrow(x) numerator <- factorial(ncol(x)) coef <- numeric(n) for (i in seq_len(n)) coef[i] <- numerator/prod(factorial(tabulate(x[i, ]))) coef } proba.genotype <- function(alleles = c("1", "2"), p, ploidy = 2) { o <- .sort.alleles(alleles, index.only = TRUE) alleles <- alleles[o] p <- if (missing(p)) rep(1/length(alleles), length(alleles)) else p[o] geno <- expand.genotype(length(alleles), ploidy = ploidy, matrix = TRUE) P <- .multinomialCoef(geno) * apply(geno, 1, function(i) prod(p[i])) names(P) <- apply(matrix(alleles[geno], ncol = ploidy), 1, paste, collapse = "/") P } expand.genotype <- function(n, alleles = NULL, ploidy = 2, matrix = FALSE) { if (!is.null(alleles)) { alleles <- .sort.alleles(alleles) n <- length(alleles) } ans <- matrix(0L, 0L, ploidy) foo <- function(i, a) { for (x in a:n) { g[i] <<- x if (i < ploidy) foo(i + 1L, x) else ans <<- rbind(ans, g) } } g <- integer(ploidy) foo(1L, 1L) dimnames(ans) <- NULL if (is.character(alleles)) ans <- matrix(alleles[ans], ncol = ploidy) if (!matrix) ans <- apply(ans, 1, paste, collapse = "/") ans } hw.test <- function (x, B = 1000, ...) UseMethod("hw.test") hw.test.loci <- function(x, B = 1000, ...) { test.polyploid <- function(x, ploidy) { if (ploidy < 2) return(rep(NA_real_, 3)) nms <- names(x$allele) all.prop <- x$allele/sum(x$allele) E <- proba.genotype(nms, all.prop, ploidy = ploidy) O <- E O[] <- 0 O[names(x$genotype)] <- x$genotype E <- sum(O) * E chi2 <- sum((O - E)^2/E) DF <- length(E) - length(nms) c(chi2, DF, 1 - pchisq(chi2, DF)) } y <- summary.loci(x) ploidy <- .checkPloidy(x) if (any(del <- !ploidy)) { msg <- if (sum(del) == 1) "The following locus was ignored: " else "The following loci were ignored: " msg <- paste(msg, names(y)[del], "\n(not the same ploidy for all individuals, or too many missing data)", sep = "") warning(msg) } ans <- t(mapply(test.polyploid, y, ploidy = ploidy)) dimnames(ans) <- list(names(y), c("chi^2", "df", "Pr(chi^2 >)")) if (B) { LN2 <- log(2) test.mc <- function(x, ploidy) { if (ploidy != 2) { warning("Monte Carlo test available only if all individuals are diploid") return(NA_real_) } n <- sum(x$genotype) Nall <- length(x$allele) all.geno <- expand.genotype(Nall) Ngeno <- length(all.geno) p <- numeric(B) ma <- unlist(mapply(rep, 1:Nall, x$allele)) homoz.nms <- paste(1:Nall, 1:Nall, sep = "/") for (k in 1:B) { m <- sample(ma) dim(m) <- c(n, 2) o <- m[, 1] > m[, 2] m[o, 1:2] <- m[o, 2:1] s <- factor(paste(m[, 1], m[, 2], sep = "/"), levels = all.geno) f <- tabulate(s, Ngeno) p[k] <- -sum(lfactorial(f)) + LN2 * sum(f[-match(homoz.nms, all.geno)]) } h <- unlist(lapply(strsplit(names(x$genotype), "/"), function(x) length(unique(x)))) == 1 p0 <- -sum(lfactorial(x$genotype)) + LN2*sum(x$genotype[!h]) sum(p <= p0)/B } ans <- cbind(ans, "Pr.exact" = mapply(test.mc, y, ploidy)) } ans } hw.test.genind <- function(x, B = 1000, ...){ x <- as.loci(x) hw.test.loci(x = x, B = B, ...) }
print.summary.BANOVA.Bernoulli <- function(x, ...){ cat('Call:\n') print(x$call) cat('\nConvergence diagnostics:\n') print(x$conv) print(x$anova.table) cat('\nTable of p-values (Multidimensional): \n') print(x$pvalue.table) cat('\nTable of coefficients: \n') printCoefmat(x$coef.table) cat('\nTable of predictions: \n') table.predictions(x$full_object) }
NULL if (getRversion() >= "2.15.1") utils::globalVariables(c("."))
launch_ggedit <- function(p, output, rstudio, ...) { assign(x = ".p", envir = .ggeditEnv, value = p) assign(x = ".output", envir = .ggeditEnv, value = output) on.exit({ assign(x = ".p", envir = .ggeditEnv, value = NULL) }, add = T) shiny::runApp(appDir = system.file("application", package = "ggedit"), ...) }
export_qgis_ronds_classes <- function(map,cheminDossier,nomFichier,titre1="",titre2="",source="") { sortie <- nomFichier rep_sortie <- cheminDossier files <- paste0(rep_sortie,"/",sortie,".qgs") list_fonds <- extract_fond_leaflet_ronds_classes(map) if(is.null(list_fonds)) stop(simpleError("La legende des ronds ou des classes n'a pas ete creee. Veuillez svp utiliser les fonctions add_legende_ronds(map) et add_legende_classes(map) pour ajouter une legende a votre carte.")) dir.create(paste0(rep_sortie,"/layers"),showWarnings = F) for(i in 1:length(list_fonds[[1]])) { suppressWarnings(st_write(list_fonds[[1]][[i]], paste0(rep_sortie,"/layers/",list_fonds[[2]][[i]],".shp"), delete_dsn = TRUE, quiet = TRUE)) } annee <- format(Sys.time(), format = "%Y") l <- c() if(any(list_fonds[[2]] %in% "fond_ronds_leg")) l <- c(l,"fond_ronds_leg") if(any(list_fonds[[2]] %in% "fond_ronds_classes_carte")) l <- c(l,"fond_ronds_classes_carte") if(any(list_fonds[[2]] %in% "fond_ronds_classes_elargi_carte")) l <- c(l,"fond_ronds_classes_elargi_carte") if(any(list_fonds[[2]] %in% "fond_maille")) l <- c(l,"fond_maille") if(any(list_fonds[[2]] %in% "fond_maille_elargi")) l <- c(l,"fond_maille_elargi") if(any(list_fonds[[2]] %in% "fond_france")) l <- c(l,"fond_france") if(any(list_fonds[[2]] %in% "fond_pays"))l <- c(l,"fond_pays") if(any(list_fonds[[2]] %in% "fond_etranger"))l <- c(l,"fond_etranger") if(any(list_fonds[[2]] %in% "fond_territoire")) l <- c(l,"fond_territoire") if(any(list_fonds[[2]] %in% "fond_departement")) l <- c(l,"fond_departement") if(any(list_fonds[[2]] %in% "fond_region")) l <- c(l,"fond_region") if(is.null(titre1)) titre1 <- list_fonds[[3]] if(is.null(source)) source <- list_fonds[[4]] titre_leg <- list_fonds[[6]] table_classe <- list_fonds[[5]] variable_a_representer <- list_fonds[[7]] export_projet_qgis_ronds_classes(l,rep_sortie,sortie,titre1,titre2,source,titre_leg,table_classe,variable_a_representer,annee) message(simpleMessage(paste0("[INFO] Le projet .qgs se trouve dans ",files))) }
ff_draftpicks.mfl_conn <- function(conn, ...) { future_picks <- .mfl_futurepicks(conn) current_picks <- .mfl_currentpicks(conn) dplyr::bind_rows(current_picks, future_picks) %>% dplyr::left_join( dplyr::select( ff_franchises(conn), dplyr::any_of(c("franchise_id", "franchise_name", "division", "division_name")) ), by = c("franchise_id") ) %>% dplyr::select( dplyr::any_of(c( "season", "division", "division_name", "franchise_id", "franchise_name", "round", "pick", "original_franchise_id" )) ) } .mfl_futurepicks <- function(conn) { future_picks <- mfl_getendpoint(conn, "futureDraftPicks") %>% purrr::pluck("content", "futureDraftPicks", "franchise") if (length(future_picks) == 0) { return(NULL) } future_picks %>% tibble::tibble() %>% tidyr::hoist(1, "futureDraftPick" = "futureDraftPick", "franchise_id" = "id") %>% tidyr::unnest_longer("futureDraftPick") %>% tidyr::hoist("futureDraftPick", "season" = "year", "round" = "round", "original_franchise_id" = "originalPickFor") %>% dplyr::mutate_at(c("season", "round"), as.numeric) } .mfl_currentpicks <- function(conn) { raw_draftresults <- mfl_getendpoint(conn, "draftResults") %>% purrr::pluck("content", "draftResults", "draftUnit") if (!is.null(raw_draftresults$unit) && raw_draftresults$unit == "LEAGUE") { df_draftresults <- .mfl_parse_draftunit(raw_draftresults) if (is.null(df_draftresults)) { return(NULL) } df_draftresults <- df_draftresults %>% dplyr::filter(.data$player_id == "") %>% dplyr::select("franchise_id", "round", "pick") %>% dplyr::mutate(season = conn$season) %>% dplyr::mutate_at(c("season", "round", "pick"), as.numeric) return(df_draftresults) } else { df_draftresults <- purrr::map_df(raw_draftresults, .mfl_parse_draftunit) if (is.null(df_draftresults)) { return(NULL) } df_draftresults <- df_draftresults %>% dplyr::filter(.data$player_id == "") %>% dplyr::select("franchise_id", "round", "pick") %>% dplyr::mutate(season = conn$season) %>% dplyr::mutate_at(c("season", "round", "pick"), as.numeric) return(df_draftresults) } }
test_that("point_from_distance doesn't care about classes", { expect_error(point_from_distance(c( lat = 44.05003, lng = -74.01164 ), 100, 90), NA) })
options(prompt = "R> ", continue = "+ ", width = 70, useFancyQuotes = FALSE) library(dirichletprocess)
gexp.fe_rcbd <- function(x, ...) { ifelse(is.null(x$fe), fe <- list(f1 = rep(1, 3), f2 = rep(1, 2)), fe <- x$fe) ifelse(is.null(x$blke), blke <- rep(1, 3), blke <- x$blke) factors <- list(r = 1:x$r) contrast <- list() ifelse(is.null(x$blkl), { factors$Block <- factor(1:dim(as.matrix(blke))[1]) contrast[["Block"]] <- diag(dim(as.matrix(blke))[1]) }, { factors[[names(x$blkl)]] <- factor(unlist(x$blkl)) contrast[[names(x$blkl)]] <- diag(dim(as.matrix(blke))[1]) }) intee <- makeInteraction(mu = x$mu, fe = fe, inte = x$inte) treatments <- makeTreatments(fl = x$fl, fe = fe, quali = x$qualiquanti$quali, quanti = x$qualiquanti$quanti, posquanti = x$qualiquanti$posquanti) contrasttreatments <- makeContrasts(factors = treatments, quali = x$qualiquanti$quali, quanti = x$qualiquanti$quanti, posquanti = x$qualiquanti$posquanti) contrast <- c(contrast, contrasttreatments) if(!is.null(x$contrasts)){ contrast[names(x$contrasts)] <- x$contrasts contrasts <- contrast }else{ contrasts <- contrast } factors <- c(factors, treatments) cformula <- paste('~', names(factors)[2], '+', paste(names(treatments), collapse = '*')) dados <- expand.grid(factors, KEEP.OUT.ATTRS = FALSE) XB <- makeXBeta(cformula, dados, mu = x$mu, fe = fe, blke = blke, rowe = x$rowe, cole = x$cole, inte = intee, contrasts = contrasts) Z <- NULL if(is.null(x$err)){ e <- mvtnorm::rmvnorm(n = dim(XB$XB)[1], sigma = diag(length(x$mu))) }else{ if(!is.matrix(x$err)) stop("This argument must be a matrix n x 1 univariate or n x p multivariate!") e <- x$err } yl <- XB$XB + e colnames(yl) <- paste('Y', 1:dim(yl)[2], sep = '') Y <- round(yl, x$round) if(!x$qualiquanti$quali){ dados <- lapply(dados, function(x) if(is.ordered(factor(x))) as.numeric(as.character(x)) else x) dados <- as.data.frame(dados) } dados <- cbind(dados, Y) res <- list(X = XB$X, Z = Z, Y = Y, dfm = dados) class(res) <- c(paste('gexp', class(x), sep = '.'), 'gexp', 'list') return(res) }
httr_dr <- function() { check_for_nss() } check_for_nss <- function() { if (!grepl("^NSS", curl::curl_version()$ssl_version)) return() warning(' ------------------------------------------------------------------------ Your installed RCurl is linked to the NSS library (`libcurl4-nss-dev`) which is likely to cause issues. To resolve the problem: 1. Quit R. 2. Install OpenSSL (`apt-get install libcurl4-openssl-dev`) or GnuTLS (`apt-get install libcurl4-gnutls-dev`) variants of libCurl. 3. Restart R. 4. Reinstall RCurl: `install.packages("RCurl")`. ------------------------------------------------------------------------ ', call. = FALSE) }
options( width=200, max.print=10000 ) XRes <- readRDS("RDS/CM.rds") XRes <- as.matrix(XRes$CI) print(XRes) pdf(file="Plots/contour.pdf", height=5, width=6.8) par(mar=c(4,5,0.5,0.5),cex.axis=1.2,cex.lab=1.4) filled.contour( x = -10:10, y = -10:10, z = matrix(XRes[,"Difference"],21,21, byrow=TRUE), xlab = expression(paste(alpha, " (Placebo)")), ylab = expression(paste(alpha, " (Active)")), nlevels = 8, color.palette = colorRampPalette(c( " plot.axis = ( points( XRes[ sign(XRes[,"lb7"]) == sign(XRes[,"ub7"]), c(1,2)], pch=15, cex=0.6, col = c(" ) dev.off()
context("fgeo_topography") describe("fgeo_topography", { elev_ls <- fgeo.x::elevation gridsize <- 20 topo <- fgeo_topography(elev_ls, gridsize = gridsize) it("Outputs the expected data structure", { expect_is(topo, "tbl_df") expect_is(topo, "fgeo_topography") expect_named(topo, c("gx", "gy", "meanelev", "convex", "slope")) n_plot_row <- elev_ls$xdim / gridsize n_plot_col <- elev_ls$ydim / gridsize n_quadrats <- n_plot_row * n_plot_col expect_equal(nrow(topo), n_quadrats) }) it("Works with both elevation list and dataframe", { expect_silent(topo) expect_silent( out_df <- fgeo_topography( elev_ls$col, gridsize, xdim = elev_ls$xdim, ydim = elev_ls$ydim ) ) expect_identical(topo, out_df) }) it("errs with informative message", { expect_error(fgeo_topography(1), "Can't deal with.*numeric") expect_error(fgeo_topography(elev_ls), "gridsize.*is missing") expect_error(fgeo_topography(elev_ls$col), "gridsize.*is missing") expect_error(fgeo_topography(elev_ls$col, gridsize), "xdim.*can't be `NULL`") }) it("works with elevation list and dataframe with x and y, or gx and gy", { elev_ls2 <- elev_ls elev_ls2[[1]] <- setNames(elev_ls2[[1]], c("gx", "gy", "elev")) topo2 <- fgeo_topography(elev_ls2, gridsize = gridsize) expect_silent(topo2) expect_identical(topo2, topo) expect_silent( out_df <- fgeo_topography( elev_ls2$col, gridsize, xdim = elev_ls2$xdim, ydim = elev_ls2$ydim ) ) expect_identical(topo2, out_df) }) }) describe("fgeo_topography()", { it("returns known output", { skip_if_not_installed("bciex") expect_known <- function(object, file, update = FALSE) { testthat::expect_known_output(object, file, update = update, print = TRUE) } elev_luq <- fgeo.x::elevation luq <- fgeo_topography(elev_luq, gridsize = 20) expect_known(head(luq), "ref-fgeo_topography_luq_head") expect_known(tail(luq), "ref-fgeo_topography_luq_tail") elev_bci <- bciex::bci_elevation bci <- fgeo_topography(elev_bci, gridsize = 20, xdim = 1000, ydim = 500) expect_known(head(bci), "ref-fgeo_topography_bci_head") expect_known(tail(bci), "ref-fgeo_topography_bci_tail") }) }) describe("fgeo_topography()", { it("`edgecorrect` works with elevaiton data finer than gridsize / 2 ( degrade_elev <- function(elev_ls, gridsize) { elev_ls$col <- elev_ls$col %>% dplyr::filter(x %% gridsize == 0) %>% dplyr::filter(y %% gridsize == 0) elev_ls } luq_elev <- fgeo.x::elevation msg <- "No elevation data found at `gridsize / 2`" expect_warning( expect_error(fgeo_topography(degrade_elev(luq_elev, 20), gridsize = 20)), msg ) no_warning <- NA expect_warning( fgeo_topography(degrade_elev(luq_elev, 10), gridsize = 20), no_warning ) tian_tong_elev <- readr::read_csv(test_path("test-data-tian_tong_elev.csv")) expect_warning( expect_error( fgeo_topography(tian_tong_elev, gridsize = 20, xdim = 500, ydim = 400) ), msg ) }) }) context("allquadratslopes") elev <- fgeo.x::elevation test_that("works with simple input", { result <- allquadratslopes( elev = elev, gridsize = 20, plotdim = c(1000, 500), edgecorrect = TRUE ) expect_is(result, "data.frame") expect_named(result, c("meanelev", "convex", "slope")) }) test_that("warns if input to eleve is unexpected", { names(elev)[[1]] <- "data" expect_error( expect_warning( allquadratslopes( elev = elev, gridsize = 20, plotdim = c(1000, 500), edgecorrect = TRUE ), "must.*named.*col" ) ) }) context("calcslope") test_that("errs with informative message", { gridsize <- 20 expect_error(calcslope(1:3, gridsize), NA) expect_error(calcslope(1:2, gridsize), "must be of length 3") expect_error(calcslope(1, gridsize), "must be of length 3") expect_error(calcslope(1:4, gridsize), "must be of length 3") }) test_that("with z == 0 returns 0", { expect_equal(calcslope(c(0, 0, 0), 20), 0) expect_equal(calcslope(c(1, 1, 1), 20), 0) }) context("warn_if_no_data_falls_on_half_gridsize") test_that("does what it promises", { col <- tibble::tribble( ~x, ~y, ~elev, 0, 0, 0, 15, 15, 0, ) expect_warning( warn_if_no_data_falls_on_half_gridsize( list(col = col), gridsize = 20, edgecorrect = TRUE ), "elevation.*too coarse" ) })
context("sim_base") test_that("base_add_id", { data(diamonds, envir=environment(), package = "ggplot2") diamonds <- diamonds[1:1000, ] diamonds["clusterVariable"] <- 1:nrow(diamonds) setup <- sim_base(base_add_id(data = diamonds, "clusterVariable")) dat <- sim(setup %>% sim_gen_e())[[1]] expect_equal(nrow(dat), 1000) expect_equal(names(dat), c(c("idD", "idU"), names(diamonds), c("e", "idR", "simName"))) }) test_that("sim_base return setup with simName", { setup <- sim_base() expect_equal(length(setup@simName), 1) })
testthat::context("Testing inconsistency.functions") network <- mbnma.network(dataset) noplac.df <- network$data.ab[network$data.ab$narm>2 & network$data.ab$agent!=1,] net.noplac <- mbnma.network(noplac.df) testthat::test_that(paste0("test.inconsistency.loops for: ", datanam), { expect_error(inconsistency.loops(network$data.ab, incldr = TRUE), NA) comps <- inconsistency.loops(network$data.ab, incldr = TRUE) expect_equal(any(grepl("drparams", comps$path)), TRUE) if (!datanam %in% c("osteopain_2wkabs", "GoutSUA_2wkCFB")) { compsnodr <- inconsistency.loops(network$data.ab, incldr = FALSE) expect_equal(nrow(compsnodr)<nrow(comps), TRUE) incon <- inconsistency.loops(network$data.ab) expect_identical(names(incon), c("t1", "t2", "path")) } if (datanam=="HF2PPITT") { expect_equal(nrow(inconsistency.loops(network$data.ab)), 4) expect_equal(nrow(inconsistency.loops(net.noplac$data.ab)), 8) } }) testthat::test_that(paste0("test.nma.nodesplit for: ", datanam), { if (all(c("y", "se") %in% names(dataset))) { like <- "normal" link <- "identity" } else if (all(c("r", "N") %in% names(dataset))) { like <- "binomial" link <- "logit" } if (!datanam %in% c("osteopain_2wkabs", "GoutSUA_2wkCFB")) { split <- nma.nodesplit(network, likelihood = like, link=link, method="common", n.iter=1000) expect_equal(nrow(inconsistency.loops(network$data.ab)), length(split)) expect_equal(class(split), "nodesplit") expect_identical(names(split[[1]]), c("comparison", "direct", "indirect", "nma", "overlap matrix", "p.values", "quantiles", "forest.plot", "density.plot", "direct.model", "indirect.model", "nma.model")) expect_equal(is.numeric(split[[1]]$p.values), TRUE) expect_equal(is.numeric(split[[1]]$indirect), TRUE) expect_equal(is.numeric(split[[1]]$direct), TRUE) expect_equal(length(split[[1]]$comparison), 2) expect_identical(class(split[[1]]$forest.plot), c("gg", "ggplot")) expect_identical(class(split[[1]]$density.plot), c("gg", "ggplot")) expect_error(print(split), NA) expect_equal(class(summary(split)), "data.frame") comps <- inconsistency.loops(network$data.ab, incldr = FALSE) compsi <- c(comps$t1[1], comps$t2[1]) split <- nma.nodesplit(network, likelihood = "binomial", link="logit", method="random", n.iter=1000, drop.discon = TRUE, comparisons = rbind(compsi)) expect_equal(1, length(split)) expect_error(print(split), NA) expect_equal(class(summary(split)), "data.frame") expect_error(nma.nodesplit(network, likelihood = "binomial", link="logit", method="random", n.iter=1000, drop.discon = FALSE, comparisons = rbind(c("badger","rizatriptan_0.5"))), "Treatment names given") } if (datanam=="HF2PPITT") { split <- nma.nodesplit(net.noplac, likelihood = "binomial", link="logit", method="random", n.iter=1000, drop.discon = TRUE) expect_equal(nrow(inconsistency.loops(net.noplac$data.ab)), length(split)) expect_equal(class(split), "nodesplit") expect_identical(names(split[[1]]), c("comparison", "direct", "indirect", "nma", "overlap matrix", "p.values", "quantiles", "forest.plot", "density.plot", "direct.model", "indirect.model", "nma.model")) expect_equal(is.numeric(split[[1]]$p.values), TRUE) expect_equal(is.numeric(split[[2]]$indirect), TRUE) expect_equal(is.numeric(split[[3]]$direct), TRUE) expect_equal(length(split[[4]]$comparison), 2) expect_identical(class(split[[1]]$forest.plot), c("gg", "ggplot")) expect_identical(class(split[[2]]$density.plot), c("gg", "ggplot")) expect_error(print(split), NA) expect_equal(class(summary(split)), "data.frame") } if (datanam=="HF2PPITT") { expect_error(nma.nodesplit(network, likelihood = "binomial", link="logit", method="random", n.iter=1000, drop.discon = FALSE, comparisons = rbind(c("sumatriptan_0.5","rizatriptan_0.5"), c("zolmitriptan_4", "eletriptan_1"), c("naratriptan_2", "Placebo_0")))) } }) testthat::test_that("test.mbnma.nodesplit", { if (all(c("y", "se") %in% names(dataset))) { like <- "normal" link <- "identity" } else if (all(c("r", "N") %in% names(dataset))) { like <- "binomial" link <- "logit" } comps <- inconsistency.loops(network$data.ab, incldr = TRUE) split <- mbnma.nodesplit(network, fun="rcs", knots=3, likelihood = like, link=link, method="common", n.iter=1000) expect_equal(nrow(comps), length(split)) if (!datanam %in% c("osteopain_2wkabs", "GoutSUA_2wkCFB")) { expect_equal(nrow(inconsistency.loops(network$data.ab, incldr = FALSE))==length(split), FALSE) } expect_equal(class(split), "nodesplit") expect_identical(names(split[[1]]), c("comparison", "direct", "indirect", "mbnma", "overlap matrix", "p.values", "quantiles", "forest.plot", "density.plot", "split.model", "mbnma.model")) expect_equal(is.numeric(split[[1]]$p.values), TRUE) expect_equal(is.numeric(split[[2]]$indirect), TRUE) expect_equal(is.numeric(split[[3]]$direct), TRUE) expect_equal(length(split[[4]]$comparison), 2) expect_identical(class(split[[1]]$forest.plot), c("gg", "ggplot")) expect_identical(class(split[[2]]$density.plot), c("gg", "ggplot")) expect_error(print(split), NA) expect_equal(class(summary(split)), "data.frame") comps.noplac <- inconsistency.loops(net.noplac$data.ab, incldr = TRUE) split <- mbnma.nodesplit(net.noplac, fun="exponential", likelihood = like, link=link, method="random", n.iter=1000) expect_equal(nrow(comps.noplac), length(split)) expect_equal(class(split), "nodesplit") expect_identical(names(split[[1]]), c("comparison", "direct", "indirect", "mbnma", "overlap matrix", "p.values", "quantiles", "forest.plot", "density.plot", "split.model", "mbnma.model")) expect_equal(is.numeric(split[[1]]$p.values), TRUE) expect_equal(is.numeric(split[[2]]$indirect), TRUE) expect_equal(is.numeric(split[[3]]$direct), TRUE) expect_equal(length(split[[4]]$comparison), 2) expect_identical(class(split[[1]]$forest.plot), c("gg", "ggplot")) expect_identical(class(split[[2]]$density.plot), c("gg", "ggplot")) expect_error(print(split), NA) expect_equal(class(summary(split)), "data.frame") split <- mbnma.nodesplit(net.noplac, fun="user", user.fun= ~beta.1 * dose + beta.2 * (dose^2), likelihood = like, link=link, method="random", n.iter=1000, comparisons = rbind(comps.noplac[1,], comps.noplac[3,])) expect_equal(2, length(split)) expect_error(print(split), NA) expect_equal(class(summary(split)), "data.frame") comps <- inconsistency.loops(network$data.ab, incldr = TRUE) split <- mbnma.nodesplit(network, fun="emax", method="random", n.iter=1000, comparisons = rbind(c(network$treatment[comps$t1[2]], network$treatment[comps$t2[2]]))) expect_equal(1, length(split)) expect_error(print(split), NA) expect_equal(class(summary(split)), "data.frame") expect_error(mbnma.nodesplit(network, fum="linear", method="random", n.iter=1000, comparisons = rbind(c("badger","rizatriptan_0.5"))), "Treatment names given") if (datanam=="HF2PPITT") { expect_error(mbnma.nodesplit(network, fun="emax", method="random", n.iter=1000, comparisons = rbind(c("sumatriptan_0.5","rizatriptan_0.5"), c("zolmitriptan_4", "eletriptan_1"), c("naratriptan_2", "Placebo_0")))) } else { expect_error(mbnma.nodesplit(network, fun="emax", method="random", n.iter=1000, comparisons = rbind(c("sumatriptan_0.5","rizatriptan_0.5"), c("zolmitriptan_4", "eletriptan_1"), c("naratriptan_2", "Placebo_0"))), "Treatment names given") } })
resolve_read <- function(handle, data_product, component = NA) { endpoint <- handle$yaml$run_metadata$local_data_registry_url read <- handle$yaml$read if (!all(is.null(names(read)))) read <- list(read) index <- lapply(read, function(x) x$data_product == data_product) %>% unlist() %>% which() if (length(index) == 0) usethis::ui_stop(paste(usethis::ui_field(data_product), "not found in config file")) if (length(index) > 1) usethis::ui_stop("Multiple entries found in config file") this_read <- read[[index]] alias <- this_read$use if (any(names(alias) == "data_product")) { data_product <- this_read$use$data_product } else { data_product <- this_read$data_product } if (any(names(alias) == "component")) { component <- alias$component } else { component <- component } if (any(names(alias) == "version")) { version <- this_read$use$version } else { version <- this_read$version } if (any(names(alias) == "namespace")) { namespace <- alias$namespace } else { namespace <- handle$yaml$run_metadata$default_input_namespace } namespace_id <- get_id("namespace", list(name = namespace)) if (is.null(namespace_id)) usethis::ui_stop(paste("default_input_namespace", usethis::ui_field(namespace), "not present in data registry")) assertthat::assert_that(length(namespace_id) == 1) this_entry <- get_entry("data_product", list(name = data_product, version = version, namespace = namespace_id), endpoint = endpoint) if (is.null(this_entry)) usethis::ui_stop(paste0(usethis::ui_field(namespace), ":", usethis::ui_field(data_product), "@v.", usethis::ui_field(version), " ", "missing from data registry")) assertthat::assert_that(length(this_entry) == 1) this_object <- get_entity(this_entry[[1]]$object) this_object_id <- extract_id(this_object$url, endpoint = endpoint) this_location <- get_entity(this_object$storage_location) this_path <- this_location$path this_root <- get_entity(this_location$storage_root)$root if (grepl("^file://", this_root)) this_root <- gsub("^file://", "", this_root) if (is.na(component)) { component_url <- get_url("object_component", list(object = this_object_id, whole_object = TRUE), endpoint = endpoint) } else { component_url <- get_url("object_component", list(object = this_object_id, name = component), endpoint = endpoint) } assertthat::assert_that(length(component_url) == 1) list(data_product = data_product, component = component, component_url = component_url, version = version, namespace = namespace, path = paste0(this_root, this_path)) }
wield <- function(simulation, force, ..., name, include = TRUE) { stopifnot(is.simulation(simulation)) stopifnot(is.force(force)) include <- enquo(include) universe(simulation) <- add_force( universe(simulation), name = name, train_force(force, particles(simulation), ..., include = include) ) simulation } rewield <- function(simulation, name, ...) { stopifnot(is.simulation(simulation)) universe(simulation) <- modify_force( universe(simulation), name = name, retrain_force(get_force(universe(simulation), name), particles(simulation), ...) ) simulation } unwield <- function(simulation, name) { stopifnot(is.simulation(simulation)) universe(simulation) <- remove_force(universe(simulation), name) simulation }
calculate_risk_measures <- function(data, wgt, varpool, tau1, tau2) { el_emam_risk_measures <- function(data, tau1, tau2) return(list(pRa=mean(data$.cell_count < 1/tau1), pRb=1/min(data$.cell_count), pRc=length(unique(data$.cell_ID))/nrow(data), jRa=mean(data$.mu_argus > tau2), jRb=max(data$.mu_argus), jRc=mean(data$.mu_argus))) stopifnot(!missing(wgt) && !is.null(wgt) && inherits(wgt, "character") && length(wgt) == 1 && wgt %in% names(data)) data <- add_mu_argus_and_statistics(data, wgt, varpool) return(list(data=data, mu_argus_summary=summarize_mu_argus(data, wgt), el_emam_measures=el_emam_risk_measures(data, tau1, tau2))) } calculate_risk_measures_unweighted <- function(data, varpool, tau1) { el_emam_risk_measures <- function(data) return(list(pRa=mean(data$.cell_count < 1/tau1), pRb=1/min(data$.cell_count), pRc=length(unique(data$.cell_ID))/nrow(data))) add_cell_count <- function(data_with_cell_ID) { stopifnot(nrow(data_with_cell_ID) > 0) ids <- data_with_cell_ID$.cell_ID tmp <- data_with_cell_ID[,".cell_ID",drop=FALSE] tbl <- aggregate(tmp, by=list(.cell_ID=ids), FUN=length) names(tbl) <- c(".cell_ID", ".cell_count") return(merge(data_with_cell_ID, tbl)) } data <- add_cell_count(add_cell_ID(data, varpool)) return(list(data=data, el_emam_measures=el_emam_risk_measures(data))) } add_mu_argus_and_statistics <- function(data, wgt, varpool) { get_mu_argus_term <- Vectorize(function(n, f_k, pi_k){ return(factorial(n)*((1-pi_k)^n)/prod(f_k + 1:n)) }, vectorize.args="n") get_score <- function(f_k, pi_k) { if(isTRUE(all.equal(pi_k, 1))) return(1/f_k) if(f_k == 1) return(-log(pi_k)*pi_k/(1 - pi_k)) else if(f_k == 2) return((pi_k*log(pi_k) + 1 - pi_k)*pi_k/((1 - pi_k)^2)) else if(f_k == 3) return(((1 - pi_k)*(3*(1 - pi_k) - 2) - 2*pi_k*pi_k*log(pi_k))*pi_k/ (2*((1-pi_k)^3))) else return((1 + sum(get_mu_argus_term(1:7, f_k, pi_k)))*pi_k/f_k) } data <- add_cell_ID(data, varpool) data <- add_statistics_per_cell(data, wgt) data$.mu_argus <- mapply(get_score, data$.cell_count, data$.pi_k) return(data) } summarize_mu_argus <- function(data, wgt) { max_counts <- c(1:3, Inf) n <- nrow(data) summarize_subset <- function(max_count) { dat <- data[data$.cell_count <= max_count,] sum_mu_argus <- sum(dat$.mu_argus) return(data.frame(num_cases=nrow(dat), total_mu_argus=sum_mu_argus, mean_mu_argus=mean(dat$.mu_argus), total_mu_over_total_obs=sum_mu_argus/n, total_mu_over_sum_wts=sum_mu_argus/sum(data[,wgt]))) } tbl <- do.call(rbind, lapply(max_counts, summarize_subset)) tbl <- cbind(data.frame(max_count=max_counts), tbl) tbl <- tbl[1:(which(tbl$num_cases == tbl$num_cases[4])[1]),] return(tbl) } add_statistics_per_cell <- function(data_with_cell_ID, wgt) { ids <- data_with_cell_ID$.cell_ID tmpdat <- data_with_cell_ID[,wgt,drop=FALSE] tbl <- aggregate(tmpdat, by=list(.cell_ID=ids), FUN=sum) names(tbl) <- c(".cell_ID", ".sum_weights") data <- merge(data_with_cell_ID, tbl) tbl <- aggregate(tmpdat, by=list(.cell_ID=ids), FUN=length) names(tbl) <- c(".cell_ID", ".cell_count") data <- merge(data, tbl) data$.pi_k <- data$.cell_count/data$.sum_weights return(data) }
"pois.approx" <- function(x, pt = 1, conf.level = .95) { Z <- qnorm(0.5*(1 + conf.level)) SE.R <- sqrt(x/pt^2) lower <- x/pt - Z*SE.R upper <- x/pt + Z*SE.R data.frame(x = x, pt = pt, rate = x/pt, lower = lower, upper = upper, conf.level = conf.level ) }
rgk = function(n, A, B, g, k, c=0.8){ z2gk(stats::rnorm(n), A, B, g, k, c) }
calc_creat_neo <- function ( pma = NULL, digits = 1 ) { if(is.null(pma)) { stop("PMA required required.") } if(any(pma < 25)) { stop("PMA < 25 not supported by this equation!") } if(any(pma > 42)) { stop("PMA >42 not supported by this equation!") } scr <- 166.48 - 2.849 * pma return(list( value = round(scr, digits), unit = "micromol/L" )) }
nca.read.sim <- function(simFile="nca_simulation.1.npctab.dta", MDV.rm=FALSE){ sim <- read.table(simFile, skip=1, header=T, fill=T, as.is=T) sim <- as.data.frame(apply(sim,2,function(x) suppressWarnings(as.numeric(x)))) Nro <- min(which(is.na(sim[,1])))-1 sim <- sim[!is.na(sim[,1]),] sim$NSUB <- rep(1:(nrow(sim)/Nro),each=Nro) if(MDV.rm){ if(any(colnames(sim)=='MDV')){sim <- sim[sim[,'MDV']==0,] }else{cat('\nWarning MDV data item not listed in header, Could not remove dose events!')} } assign("nmdf", sim) return(nmdf) }
uci_quit <- function(engine){ uci_cmd(engine,"quit") rslt <- uci_read(engine)$temp engine$pipe$kill() return(rslt) }
nlxb <- function(formula, start, trace = FALSE, data=NULL, lower = -Inf, upper = Inf, masked = NULL, weights=NULL, control=list()) { pnames <- names(start) start <- as.numeric(start) names(start) <- pnames npar <- length(start) if (length(lower) == 1) lower <- rep(lower, npar) if (length(upper) == 1) upper <- rep(upper, npar) if (length(lower) != npar) stop("Wrong length: lower") if (length(upper) != npar) stop("Wrong length: upper") if (any(start < lower) || any(start > upper)) stop("Infeasible start") if (trace) { cat("formula: ") print(formula) cat("lower:") print(lower) cat("upper:") print(upper) } ctrl <- list(watch = FALSE, phi = 1, lamda = 1e-04, offset = 100, laminc = 10, lamdec = 4, femax = 10000, jemax = 5000, rofftest = TRUE, smallsstest = TRUE) ncontrol <- names(control) nctrl <- names(ctrl) for (onename in ncontrol) { if (!(onename %in% nctrl)) { if (trace) cat("control ", onename, " is not in default set\n") stop(onename," is not a control for nlxb") } ctrl[onename] <- control[onename] } if (trace) print(ctrl) phiroot <- sqrt(ctrl$phi) vn <- all.vars(formula) pnum <- start pnames <- names(pnum) bdmsk <- rep(1, npar) maskidx <- union(which(lower==upper), which(pnames %in% masked)) if (length(maskidx) > 0 && trace) { cat("The following parameters are masked:") print(pnames[maskidx]) } bdmsk[maskidx] <- 0 if (trace) { cat("Finished masks check\n") parpos <- match(pnames, vn) datvar <- vn[-parpos] cat("datvar:") print(datvar) for (i in 1:length(datvar)) { dvn <- datvar[[i]] cat("Data variable ", dvn, ":") if (is.null(data)) { print(eval(parse(text = dvn))) } else { print(with(data, eval(parse(text = dvn)))) } } } trjfn<-model2rjfun(formula, pnum, data=data) if (trace) { cat("trjfn:\n") print(trjfn) } resfb <- nlfb(start=pnum, resfn=trjfn, jacfn=trjfn, trace=trace, data=data, lower=lower, upper=upper, maskidx=maskidx, weights=weights, control=ctrl) resfb$formula <- formula pnum <- as.vector(resfb$coefficients) names(pnum) <- pnames result <- resfb class(result) <- "nlsr" result }
`%||%` <- function(lhs, rhs) { if (!is.null(lhs) && length(lhs) > 0) lhs else rhs } polite_fetch_rtxt <- memoise::memoise(function(..., user_agent, delay, verbose){ rt <- robotstxt::robotstxt(...) delay_df <- rt$crawl_delay crawldelays <- as.numeric(delay_df[with(delay_df, useragent==user_agent), "value"]) %||% as.numeric(delay_df[with(delay_df, useragent=="*"), "value"]) %||% 0 rt$delay_rate <- max(crawldelays, delay, 1) if(verbose){ message("Bowing to: ", rt$domain) message("There's ", nrow(delay_df), " crawl delay rule(s) defined for this host.") message("Your rate will be set to 1 request every ", rt$delay_rate, " second(s).")} rt }) check_rtxt <-function(url, delay, user_agent, force, verbose){ url_parsed <- httr::parse_url(url) host_url <- paste0(url_parsed$scheme, "://", url_parsed$hostname) rt <- polite_fetch_rtxt(host_url, force=force, user_agent=user_agent, delay=delay, verbose=verbose) is_scrapable <- rt$check(paths=url_parsed$path, bot=user_agent) if(is_scrapable) Sys.sleep(rt$delay_rate) else warning("robots.txt says this path is NOT scrapable for your user agent!", call. = FALSE) is_scrapable } polite_read_html <- memoise::memoise( function(url, ..., delay = 5, user_agent=paste0("polite ", getOption("HTTPUserAgent"), "bot"), force = FALSE, verbose=FALSE){ if(!check_rtxt(url, delay, user_agent, force, verbose)){ return(NULL) } old_ua <- getOption("HTTPUserAgent") options("HTTPUserAgent"= user_agent) if(verbose) message("Scraping: ", url) res <- httr::GET(url, ...) options("HTTPUserAgent"= old_ua) httr::content(res) }) guess_basename <- function(x) { destfile <- basename(x) if(tools::file_ext(destfile)==""){ hh <- httr::HEAD(x) cds <- httr::headers(hh)$`content-disposition` destfile <- gsub('.*filename=', '', gsub('\\\"','', cds)) } destfile %||% basename(x) } polite_download_file <- memoise::memoise( function(url, destfile=guess_basename(url), ..., quiet=!verbose, mode = "wb", path="downloads/", user_agent=paste0("polite ", getOption("HTTPUserAgent")), delay = 5, force = FALSE, overwrite=FALSE, verbose=FALSE){ if(!check_rtxt(url, delay, user_agent, force, verbose)) return(NULL) if(!dir.exists(path)) dir.create(path) destfile <- paste0(path, destfile) if(file.exists(destfile) && !overwrite){ message("File ", destfile, " already exists!") return(destfile) } old_ua <- getOption("HTTPUserAgent") options("HTTPUserAgent"= user_agent) if(verbose) message("Scraping: ", url) utils::download.file(url=url, destfile=destfile, quiet=quiet, mode=mode, ...) options("HTTPUserAgent"= old_ua) destfile })
pkgconfig_dummy <- function() { pkgconfig::get_config() }
DBSMOTE =function(X,target,dupSize=0,MinPts=NULL,eps=NULL) { ncD=ncol(X) n_target=table(target) classP=names(which.min(n_target)) P_set=subset(X,target==names(which.min(n_target)))[sample(min(n_target)),] N_set=subset(X,target!=names(which.min(n_target))) P_class=rep(names(which.min(n_target)),nrow(P_set)) N_class=target[target!=names(which.min(n_target))] sizeP=nrow(P_set) sizeN=nrow(N_set) set.seed(ceiling(runif(1)*10000)) if(is.null(MinPts)) { MinPts=2+ceiling(log(sizeP,10))-1 } if(is.null(eps)) { FNN::get.knn(P_set, k=MinPts+1, algorithm="kd_tree")->Pknn quantile(Pknn$nn.dist[,MinPts+1],0.75)->eps } ds <- dbscan::dbscan(P_set,eps,MinPts) size_Pgen = nrow(P_set[ds$cluster!=0,]) Outcast = P_set[ds$cluster==0,] sum_dup=n_dup_max(sizeP+sizeN,size_Pgen,sizeN,dupSize) clus=sort(unique(ds$cluster)[unique(ds$cluster)>0]) syn_dat=NULL for(i in clus) { Vert_Cl=which(ds$cluster==i) Adj_m_Cl=matrix(0,length(Vert_Cl),length(Vert_Cl)) colnames(Adj_m_Cl)=Vert_Cl rownames(Adj_m_Cl)=Vert_Cl as.matrix(dist(P_set[Vert_Cl,]))->distP NNq=rowSums(distP<=eps) for(j in 1:length(Vert_Cl)) { if(length(Vert_Cl)>=MinPts+1) { Adj_m_Cl[j,]=(distP[j,]<=eps&distP[j,]>0)*(NNq>=MinPts) } else { Adj_m_Cl[j,]=(distP[j,]<=eps&distP[j,]>0) } } Centroid=colMeans(P_set[Vert_Cl,]) pDCinxD=order(as.matrix(dist(rbind(P_set[Vert_Cl,],Centroid)))[,length(Vert_Cl)+1])[2] pseudo_Cen=P_set[Vert_Cl[pDCinxD],] igraph::graph.adjacency(Adj_m_Cl)->graph_clus igraph::get.shortest.paths(graph_clus, pDCinxD, mode = "all", weights = subset(as.vector(t(distP*Adj_m_Cl)),as.vector(t(distP*Adj_m_Cl))>0))->short_Path syn_dat_cl=NULL for(j in 1:length(Vert_Cl)) { path=short_Path$vpath[[j]] if(length(path)>1) { print(length(path)) rand_edge=ceiling(runif(sum_dup)*(length(path)-1)) g = runif(sum_dup) P_i=P_set[Vert_Cl[path[rand_edge]],] Q_i= P_set[Vert_Cl[path[rand_edge+1]],] syn_i = P_i + g*(Q_i - P_i) syn_dat_cl = rbind(syn_dat_cl,syn_i) } } syn_dat=rbind(syn_dat,syn_dat_cl) } P_set[,ncD+1] = P_class colnames(P_set)=c(colnames(X),"class") N_set[,ncD+1] = N_class colnames(N_set)=c(colnames(X),"class") rownames(syn_dat)= NULL syn_dat = data.frame(syn_dat) syn_dat[,ncD+1] = rep(names(which.min(n_target)),nrow(syn_dat)) colnames(syn_dat)=c(colnames(X),"class") NewD=rbind(P_set,syn_dat,N_set) rownames(NewD) = NULL rownames(Outcast) <- c() new_target_out=rep(classP,nrow(as.matrix(Outcast))) Outcast_df=data.frame(Outcast) Outcast_df[,ncD+1]=new_target_out colnames(Outcast_df)=c(colnames(X),"class") D_result = list(data = NewD, syn_data = syn_dat, orig_N = N_set, orig_P = P_set, K = NULL, K_all = NULL, dup_size = sum_dup, outcast = Outcast_df, eps=eps, method = "DBSMOTE") class(D_result) = "gen_data" print("DBSMOTE is Done") return(D_result) }
post_destroy <- function(destroy_id, token = NULL) { stopifnot(is.character(destroy_id) && length(destroy_id) == 1) query <- sprintf("/1.1/statuses/destroy/%s", destroy_id) r <- TWIT_post(token, query) message("Your tweet has been deleted!") return(invisible(r)) }
apsim_version <- function(which = c("all","inuse"), verbose = TRUE){ fevc <- function(x) as.numeric(sub("r","",strsplit(x, "-", fixed = TRUE)[[1]][2])) which <- match.arg(which) tmp.dat <- data.frame(APSIM = c("Classic", "Next Generation")) if(verbose) cat("OS:",Sys.info()[["sysname"]],"\n") if(.Platform$OS.type == "unix"){ if(grepl("Darwin", Sys.info()[["sysname"]])){ laf <- list.files("/Applications/") find.apsim <- grep("APSIM",laf, ignore.case = TRUE) if(length(find.apsim) == 0) warning("APSIM-X not found") apsimx.versions <- laf[find.apsim] if(length(find.apsim) > 0){ tmp.mat <- matrix(NA, nrow = 2, ncol = length(find.apsim)) tmp.mat[2,seq_along(find.apsim)] <- rev(apsimx.versions) ans <- data.frame(tmp.dat, as.data.frame(tmp.mat)) names(ans) <- c("APSIM",paste0("Version.",seq_along(find.apsim))) } } if(grepl("Linux", Sys.info()[["sysname"]])){ laf <- list.files("/usr/local/lib") find.apsim <- grep("apsim", laf, ignore.case = TRUE) if(length(find.apsim) == 0) warning("APSIM-X not found") apsimx.version <- paste0("/usr/local/lib/apsim/",list.files("/usr/local/lib/apsim")) tmp.mat <- matrix(NA, nrow = 2, ncol = length(find.apsim)) tmp.mat[2,length(find.apsim)] <- list.files("/usr/local/lib/apsim") ans <- data.frame(tmp.dat, as.data.frame(tmp.mat)) names(ans) <- c("APSIM","Version") } } if(.Platform$OS.type == "windows"){ st1 <- "C:/PROGRA~1/" lafx <- list.files(st1) find.apsimx <- grep("APSIM",lafx) st2 <- "C:/PROGRA~2/" laf <- list.files(st2) find.apsim <- grep("APSIM",laf, ignore.case = TRUE) if(length(find.apsim) == 0 && length(find.apsimx) == 0) warning("Could not find APSIM or APSIM-X") ncols <- max(c(length(find.apsim),length(find.apsimx))) if(length(find.apsimx) > 0){ apsimx.versions <- lafx[find.apsimx] tmp.matx <- matrix(NA, nrow = 1, ncol = ncols) tmp.matx[1,seq_along(find.apsimx)] <- rev(apsimx.versions) }else{ tmp.matx <- matrix(NA, nrow = 1, ncol = ncols) } if(length(find.apsim) > 0){ apsim.versions <- laf[find.apsim] apsim.versions <- apsim.versions[order(sapply(apsim.versions, fevc), decreasing = TRUE)] tmp.matc <- matrix(NA, nrow = 1, ncol = ncols) tmp.matc[1,seq_along(find.apsim)] <- apsim.versions }else{ tmp.matc <- matrix(NA, nrow = 1, ncol = ncols) } ans <- data.frame(tmp.dat, as.data.frame(rbind(tmp.matc,tmp.matx))) names(ans) <- c("APSIM",paste0("Version.",1:ncols)) } if(which == "all"){ if(verbose) print(knitr::kable(ans)) } if(which == "inuse"){ if(.Platform$OS.type == "unix"){ if(length(find.apsim) == 1){ if(grepl("Darwin", Sys.info()[["sysname"]])) ans <- laf[find.apsim] if(grepl("Linux", Sys.info()[["sysname"]])) ans <- paste0("apsim", list.files("/usr/local/lib/apsim")) } if(length(find.apsim) > 1){ len.fa <- length(find.apsim) fa.dt <- sapply(laf[find.apsim],.favd, simplify = FALSE)[[len.fa]] if(verbose) cat("APSIM-X version date:",as.character(fa.dt)) newest.version <- laf[find.apsim][len.fa] ans <- newest.version } if(!is.na(apsimx::apsimx.options$exe.path)){ ans <- apsimx::apsimx.options$exe.path } } if(.Platform$OS.type == "windows"){ ansc <- NA ansx <- NA if(length(find.apsim) == 1){ ansc <- laf[find.apsim] } if(length(find.apsim) > 1){ apsim.versions <- sapply(laf[find.apsim],fevc) newest.version <- sort(apsim.versions, decreasing = TRUE)[1] ansc <- names(newest.version) } if(!is.na(apsimx::apsim.options$exe.path)){ ansc <- apsimx::apsim.options$exe.path } if(length(find.apsimx) == 1){ ansx <- lafx[find.apsimx] } if(length(find.apsimx) > 1){ apsimx.versions <- lafx[find.apsimx] len.fa <- length(find.apsimx) newest.version <- lafx[find.apsimx][len.fa] ansx <- newest.version } if(!is.na(apsimx::apsimx.options$exe.path)){ ansx <- apsimx::apsimx.options$exe.path } ans <- data.frame(Classic = ansc, NextGeneration = ansx) } if(verbose) print(knitr::kable(ans)) } invisible(ans) }
if (Sys.getenv("POSTGRES_USER") != "" & Sys.getenv("POSTGRES_HOST") != "" & Sys.getenv("POSTGRES_DATABASE") != "") { stopifnot(require(RPostgreSQL)) stopifnot(require(datasets)) drv <- dbDriver("PostgreSQL") con <- dbConnect(drv, user=Sys.getenv("POSTGRES_USER"), password=Sys.getenv("POSTGRES_PASSWD"), host=Sys.getenv("POSTGRES_HOST"), dbname=Sys.getenv("POSTGRES_DATABASE"), port=ifelse((p<-Sys.getenv("POSTGRES_PORT"))!="", p, 5432)) if (dbExistsTable(con, "rockdata")) { print("Removing rockdata\n") dbRemoveTable(con, "rockdata") } dbWriteTable(con, "rockdata", rock) res <- dbGetQuery(con, "select area as ar, peri as pe, shape as sh, perm as pr from rockdata limit 10") print(res) if (dbExistsTable(con, "rockdata")) { print("Removing rockdata\n") dbRemoveTable(con, "rockdata") } dbDisconnect(con) }
assess_covr_coverage <- function(x, ...) { UseMethod("assess_covr_coverage") } attributes(assess_covr_coverage)$column_name <- "covr_coverage" attributes(assess_covr_coverage)$label <- "Package unit test coverage" assess_covr_coverage.default <- function(x, ...) { as_pkg_metric_na(pkg_metric(class = "pkg_metric_covr_coverage")) } assess_covr_coverage.pkg_source <- function(x, ...) { pkg_metric_eval(class = "pkg_metric_covr_coverage", { covr::coverage_to_list(x$covr_coverage) }) } metric_score.pkg_metric_covr_coverage <- function(x, ...) { x$totalcoverage / 100 } attributes(metric_score.pkg_metric_covr_coverage)$label <- "The fraction of lines of code which are covered by a unit test."
library("aroma.affymetrix") ovars <- ls(all.names=TRUE) oplan <- future::plan() message("*** RmaBackgroundCorrection ...") dataSet <- "GSE9890" chipType <- "HG-U133_Plus_2" csR <- AffymetrixCelSet$byName(dataSet, chipType=chipType) csR <- csR[1:3] print(csR) cdf <- getCdf(csR) acs <- getAromaCellSequenceFile(cdf) print(acs) strategies <- future:::supportedStrategies() strategies <- setdiff(strategies, "multiprocess") if (require("future.BatchJobs")) { strategies <- c(strategies, "batchjobs_local") if (any(grepl("PBS_", names(Sys.getenv())))) { strategies <- c(strategies, "batchjobs_torque") } } if (require("future.batchtools")) { strategies <- c(strategies, "batchtools_local") if (any(grepl("PBS_", names(Sys.getenv())))) { strategies <- c(strategies, "batchtools_torque") } } checksum <- NULL for (strategy in strategies) { message(sprintf("*** Using %s futures ...", sQuote(strategy))) future::plan(strategy) tags <- c("*", strategy) message("- RmaBackgroundCorrection() ...") bg <- RmaBackgroundCorrection(csR, tags=tags) print(bg) csB <- process(bg, verbose=verbose) print(csB) csBz <- getChecksumFileSet(csB) print(csBz[[1]]) checksumT <- readChecksum(csBz[[1]]) if (is.null(checksum)) checksum <- checksumT stopifnot(identical(checksumT, checksum)) message("- RmaBackgroundCorrection() ... DONE") message("- NormExpBackgroundCorrection() ...") bg <- NormExpBackgroundCorrection(csR, tags=tags) print(bg) csB <- process(bg, verbose=verbose) print(csB) csBz <- getChecksumFileSet(csB) print(csBz[[1]]) checksumT <- readChecksum(csBz[[1]]) if (is.null(checksum)) checksum <- checksumT stopifnot(identical(checksumT, checksum)) message("- NormExpBackgroundCorrection() ... DONE") message(sprintf("*** Using %s futures ... DONE", sQuote(strategy))) } message("*** RmaBackgroundCorrection ... DONE") future::plan(oplan) rm(list=setdiff(ls(all.names=TRUE), ovars))
signup <- function(username, email, save = TRUE) { if (missing(username)) username <- verify("username") if (missing(email)) stop("Must specify a valid email") bod <- list( un = username, email = email, platform = "R", version = as.character(get_package_version("plotly")) ) base_url <- file.path(get_domain(), "apimkacct") resp <- httr::RETRY( verb = "POST", base_url, body = bod, times = 5, terminate_on = c(400, 401, 403, 404), terminate_on_success = TRUE ) con <- process(append_class(resp, "signup")) if (save) { cat_profile("username", con$un) cat_profile("api_key", con$api_key) } Sys.setenv("plotly_username" = con$un) Sys.setenv("plotly_api_key" = con$api_key) invisible(con) }
corrRancomp <- function(model) { e = residuals(model) e * (sigma(model) / sqrt(weights(model))) / sqrt(mean(e ^ 2)) }
Var.e=function(y,S){ df=fdata.trace(S) if (is.vector(y)) { n=length(y) y.est=S%*%y se=sum((y-y.est)^2,na.rm=TRUE)/(n-df) var.e=se*diag(ncol(S)) } else { if (!is.fdata(y)) y<-fdata(y) y<-y[["data"]] n=ncol(S) y.est<-t(S%*%t(y)) var.e<-t(y-y.est)%*%(y-y.est)/(n-df) } return(var.e) }
library(hamcrest) expected <- c(0x1.199999999999ap+0 + 0x0p+0i, 0x1.0f4f8d60d3eb4p+0 + 0x0p+0i, 0x1.e666666666667p-1 + -0x1p-56i, 0x1.999999999999ap-1 + 0x1.76cf5d0b09952p-57i, 0x1.4cccccccccccdp-1 + 0x1.8p-55i, 0x1.149418718b5cep-1 + 0x1.8p-54i, 0x1p-1 + 0x0p+0i, 0x1.149418718b5cdp-1 + 0x0p+0i, 0x1.4cccccccccccdp-1 + 0x1p-56i, 0x1.999999999999ap-1 + -0x1.76cf5d0b09952p-57i, 0x1.e666666666667p-1 + -0x1.8p-55i, 0x1.0f4f8d60d3eb3p+0 + -0x1.8p-54i) assertThat(stats:::fft(inverse=TRUE,z=c(0.8+0i, 0.15+0i, 0+0i, 0+0i, 0+0i, 0+0i, 0+0i, 0+0i, 0+0i, 0+0i, 0+0i, 0.15+0i)) , identicalTo( expected, tol = 1e-6 ) )
library(testthat) context("trivial") library(PeakSegJoint) count <- as.integer(c(rep(c(0, 1), each=5), rep(c(10, 11), each=10), rep(c(0, 1), each=5))) test_that("with 1 sample we refine peaks" , { chromEnd <- seq_along(count) profiles <- data.frame(chromStart=chromEnd-1L, chromEnd, sample.id="sample1", count) fit <- PeakSegJointHeuristic(profiles) converted <- ConvertModelList(fit) peak <- converted$peaks expect_equal(peak$chromStart, 10) expect_equal(peak$chromEnd, 30) }) test_that("chromEnd <= chromStart is an error", { bad <- data.frame(chromStart=as.integer(c(0, 100)), chromEnd=as.integer(c(100, 50)), count=0L, sample.id="foo") expect_error({ PeakSegJointHeuristic(bad) }, "chromStart not less than chromEnd") }) test_that("chromStart[i] < chromEnd[i-1] is an error", { bad <- data.frame(chromStart=as.integer(c(0, 100)), chromEnd=as.integer(c(150, 200)), count=0L, sample.id="foo") expect_error({ PeakSegJointHeuristic(bad) }, "chromStart before previous chromEnd", fixed=TRUE) }) empty <- data.frame(sample.id=character(), chrom=character(), chromStart=integer(), chromEnd=integer(), count=integer()) test_that("no computable models error for empty coverage data", { expect_error({ fit <- PeakSegJointSeveral(empty) }, "No computable models") }) test_that("no coverage error for empty coverage data", { expect_error({ fit <- PeakSegJointHeuristic(empty) }, "no coverage data") })
efron.petrosian <- function(X, U=NA, V=NA, wt=NA, error=NA, nmaxit=NA , boot=TRUE, B=NA, alpha=NA, display.F=FALSE, display.S=FALSE){ trunc <- "both" if (all(is.na(U)) == TRUE & !all(is.na(V)) == TRUE) { trunc <- "right" cat("case U=NA","\n") cat("warning: data on one truncation limit are missing; the result is based on an iterative algorithm, but an explicit-form NPMLE (Lynden-Bell estimator) exists","\n") if (any(is.na(V)) == TRUE | any(is.na(X)) == TRUE) { navec <- c(which(is.na(X)), which(is.na(V))) X <- X[-navec] V <- V[-navec] } } if (all(is.na(V)) == TRUE & !all(is.na(U)) == TRUE) { trunc <- "left" cat("case V=NA","\n") cat("warning: data on one truncation limit are missing; the result is based on an iterative algorithm, but an explicit-form NPMLE (Lynden-Bell estimator) exists","\n") if (any(is.na(U)) == TRUE | any(is.na(X)) == TRUE) { navec <- c(which(is.na(X)), which(is.na(U))) X <- X[-navec] U <- U[-navec] } } if (all(is.na(V)) == TRUE & all(is.na(U)) == TRUE) { cat("case U=NA and V=NA","\n") stop("warning: data on at least one truncation limit (left or right) is required","\n") } if (trunc == "both") { if (any(is.na(U)) == TRUE | any(is.na(V)) == TRUE | any(is.na(X)) == TRUE) { navec <- c(which(is.na(X)), which(is.na(U)), which(is.na(V))) X <- X[-navec] U <- U[-navec] V <- V[-navec] } } if (is.na(wt) == TRUE) wt <- rep(1 / length(X), times = length(X)) D <- cbind(X, U, V) if (all(is.na(V)) == TRUE) D[, 3] <- rep(max(D[, 1]) + 1, length(X)) if (all(is.na(U)) == TRUE) { D[, 2] <- rep(min(D[, 1]) - 1, length(X)) D[, 1] <- D[, 1] D[, 3] <- D[, 3] } C<- matrix(0, nrow = nrow(D), ncol = ncol(D)) EE <- matrix(0, nrow = nrow(D), ncol = ncol(D)) ord <- order(D[, 1], method = "auto") C[, 1] <- sort(D[, 1], method = "auto") C[, 2:ncol(D)] <- D[ord, 2:ncol(D)] T<-table(C[,2]<= C[,1]&C[,1]<=C[,3]) if(sum(T[names(T)=="TRUE"])!=length(X) |sum(T[names(T)=="TRUE"]==0)){ stop("Condition of double truncation is violated","\n") } if (is.na(error) == TRUE) error <- 1e-6 au <- outer(C[, 1], C[, 2], ">=") av <- outer(C[, 1], C[, 3], "<=") auu <- outer(C[, 2], C[, 2], "<=") * 1L J <- au * av SC <- colSums(J) ad <- length(which(SC == 1)) if (ad != 0) { cat("Warning. Non-uniqueness or no existence of the NPMLE", "\n") } JI <- t(J) f0 <- matrix(data = 1 / nrow(C), ncol = 1, nrow = nrow(C)) f <- f0 S0 <- 1 if (is.na(nmaxit) == TRUE) nmaxit <- 100000 iter <- 0 while (S0 > error | iter > nmaxit) { iter <- iter + 1 if (iter > nmaxit) stop("Default number of iterations not enough for convergence") F0<-JI%*%f IF0<-1/F0 If1<-J%*%IF0 f<-1/If1 if(sum(f)!=1)f<-f/sum(f) S0<-max(abs(f-f0)) f0<-f } F0<-JI%*%f mult <- tabulate(match(C[,1],unique(C[,1]))) if(sum(mult)==length(unique(C[,1]))){ Fval <- (f*mult)} if(sum(mult)>length(unique(C[,1]))){ weigth<-f[!duplicated(C[,1])] Fval<- (weigth*mult)} x<-unique(C[,1]) events<-sum(mult) n.event<-mult FF<-cumsum(Fval) FFF<-cumsum(f) Sob<-1-FF+Fval Sob[Sob < 1e-12] <- 0 Sob0<-1-FFF+f Sob0[Sob0<1e-12]<-0 if (boot==TRUE){ if (is.na(B)==TRUE) B<-500 B <- 500 if (B < 40) { cat("Warning. Number of replicates less than 40", "\n") cat("Confidence bands cannot be computed", "\n") } if(trunc=="both"|trunc=="left"){ if(!requireNamespace("foreach")){ install.packages("foreach") } if(!requireNamespace("doParallel")){ install.packages("doParallel") } cores=detectCores() if (cores[1] > 1) cl <- makeCluster(cores[1]-1, type = "PSOCK") else cl <- makeCluster(cores[1], type = "PSOCK") registerDoParallel(cl) final_boot <- foreach(i=1:B, .combine='rbind') %dopar% { n_sampling_tries <- 0 M1b <- matrix(0, nrow = nrow(C), ncol = ncol(C)) M2b <- matrix(0, nrow = nrow(C), ncol = ncol(C)) M_IF0<-matrix(0,nrow=nrow(C)) M_IF01<-matrix(0,,nrow=nrow(C)) M_IF0Sob<-matrix(0,nrow=nrow(C)) ind<-seq(1,nrow(C),by=1) indbb<-seq(1,nrow(C),by=1) indbb1<-seq(1,nrow(C),by=1) repeat{ indb <- sample(ind, nrow(C), replace = TRUE) M1b <- C[indb,] ord <- order(M1b[, 1], method = "auto") M2b[, 1] <- sort(M1b[, 1], method = "auto") M2b[, 2:ncol(M1b)] <- M1b[ord, 2:ncol(M1b)] Aun<-unique(M2b) Jb <- matrix(data = 0,ncol = nrow(M2b), nrow = nrow(M2b)) aub <- outer(M2b[, 1], M2b[, 2], ">=") aubun <- outer(Aun[, 1], Aun[, 2], ">=") avb <- outer(M2b[, 1], M2b[, 3], "<=") avbun<-outer(Aun[, 1], Aun[, 3], "<=") auub <- outer(M2b[, 2], M2b[, 2], "<=") * 1L Jb <- aub * avb Jbun<-aubun*avbun SCb <-colSums(Jbun) SCb2<-rowSums(Jbun) adb <- length(which(SCb == 1)) adbb <- length(which(SCb2 == 1)) n_sampling_tries <- n_sampling_tries + 1 if (adb == 0 & adbb==0) break else cat("Warning. Non-uniqueness or no existence of the NPMLE - New Round","\n") } JIb <- t(Jb) f0b <- matrix(data = wt, ncol = 1, nrow = nrow(M2b)) f1b <- f0b S0b <- 1 iterb <- 0 while (S0b > error | iterb > nmaxit) { iterb <- iterb + 1 if (iterb > nmaxit) stop("Default number of iterations not enough for convergence") F0b<-JIb%*%f1b IF0b<-1/F0b If1b<-Jb%*%IF0b f1b<-1/If1b if(sum(f1b)!=1)f1b<-f1b/sum(f1b) S0b<-max(abs(f1b-f0b)) f0b<-f1b } ff0b<-numeric(nrow(C)) for(i in 1:nrow(C)){ indbb1<-(C[,1]==C[i,1]) pos1<-min(which(indbb1==TRUE)) if(pos1==1){ ff0b[indbb1]<-sum(f1b[indbb1]) } if(pos1>1){ ff0b[indbb1]<-sum(f1b[indbb1]) } } FF0b<-numeric(nrow(C)) for(i in 1:nrow(C)){ indbb<-(C[,1]==C[i,1]) pos<-min(which(indbb==TRUE)) if(pos==1){ FF0b[indbb]<-sum(f1b[indbb])} if(pos>1){ FF0b[indbb]<-sum(f1b[indbb])+FF0b[pos-1] } } Sobb <- 1 - FF0b + ff0b Sobb[Sobb < 1e-12] <- 0 M_IF0 <- as.vector(FF0b) M_IF01 <- as.vector(f1b) M_IF0Sob <- as.vector(Sobb) ordA <- order(M2b[, 2], method = "auto") ord3 <- sort(M2b[, 2], method = "auto") ordB <- order(M2b[, 3], method = "auto") ord4 <- sort(M2b[, 3], method = "auto") return(list( M_IF0, M_IF01, M_IF0Sob, n_sampling_tries)) } stopCluster(cl) n_sampling_tries <- 0 M_IF0 <- matrix(0, nrow = nrow(C), ncol = B) M_IF01 <- matrix(0, nrow = nrow(C), ncol = B) M_IF0Sob <- matrix(0, nrow = nrow(C), ncol = B) stderror<-matrix(0, nrow = nrow(C), ncol = 1) BootRepeat<-matrix(0,ncol=B) for(b in 1:B){ M_IF0[,b]<-as.numeric(unlist(final_boot[b,1])) M_IF01[,b]<-as.numeric(unlist(final_boot[b,2])) M_IF0Sob[,b]<-as.numeric(unlist(final_boot[b,3])) BootRepeat[,b]<-as.numeric((unlist(final_boot[b,4]))) } stderror<-apply(M_IF0,1,sd) M_IF0_sort<-matrix(0,nrow=nrow(C),ncol=B) for(i in 1:nrow(M_IF0_sort)){ M_IF0_sort[i,]<-sort(M_IF0[i,]) } if(is.na(alpha)==TRUE) alpha<-0.05 lowerF<-M_IF0_sort[,floor(alpha*B/2)] upperF<-M_IF0_sort[,floor((1-alpha/2)*B)] M_IF0_sort1<-matrix(0,nrow=nrow(C),ncol=B) for(i in 1:nrow(M_IF0_sort1)){ M_IF0_sort1[i,]<-sort(M_IF0Sob[i,]) } lowerS<-M_IF0_sort1[,floor(alpha*B/2)] upperS<-M_IF0_sort1[,floor((1-alpha/2)*B)] } if(trunc=="right"){ if(!requireNamespace("foreach")){ install.packages("foreach") } if(!requireNamespace("doParallel")){ install.packages("doParallel") } cores=detectCores() if (cores[1] > 1) cl <- makeCluster(cores[1]-1, type = "PSOCK") else cl <- makeCluster(cores[1], type = "PSOCK") registerDoParallel(cl) final_boot <- foreach(i=1:B, .combine='rbind') %dopar% { n_sampling_tries <- 0 M1b <- matrix(0, nrow = nrow(C), ncol = ncol(C)) M2b <- matrix(0, nrow = nrow(C), ncol = ncol(C)) M_IF0<-matrix(0,nrow=nrow(C)) M_IF01<-matrix(0,nrow=nrow(C)) M_IF0Sob<-matrix(0,nrow=nrow(C)) ind<-seq(1,nrow(C),by=1) indbb<-seq(1,nrow(C),by=1) indbbb<-seq(1,nrow(C),by=1) repeat{ indb <- sample(ind, nrow(C), replace = TRUE) M1b <- C[indb,] ord <- order(M1b[, 1], method = "auto") M2b[, 1] <- sort(M1b[, 1], method = "auto") M2b[, 2:ncol(M1b)] <- M1b[ord, 2:ncol(M1b)] Aun<-unique(M2b) Jb <- matrix(data = 0,ncol = nrow(M2b), nrow = nrow(M2b)) aub <- outer(M2b[, 1], M2b[, 2], ">=") aubun <- outer(Aun[, 1], Aun[, 2], ">=") avb <- outer(M2b[, 1], M2b[, 3], "<=") avbun<-outer(Aun[, 1], Aun[, 3], "<=") auub <- outer(M2b[, 2], M2b[, 2], "<=") * 1L Jb <- aub * avb Jbun<-aubun*avbun SCb <-colSums(Jbun) SCb2<-rowSums(Jbun) adb <- length(which(SCb == 1)) adbb <- length(which(SCb2 == 1)) n_sampling_tries <- n_sampling_tries + 1 if (adb == 0 & adbb==0) break else cat("Warning. Non-uniqueness or no existence of the NPMLE - New Round","\n") } JIb <- t(Jb) f0b <- matrix(data = wt, ncol = 1, nrow = nrow(M2b)) f1b <- f0b S0b <- 1 iterb <- 0 while (S0b > error | iterb > nmaxit) { iterb <- iterb + 1 if (iterb > nmaxit) stop("Default number of iterations not enough for convergence") F0b<-JIb%*%f1b IF0b<-1/F0b If1b<-Jb%*%IF0b f1b<-1/If1b if(sum(f1b)!=1)f1b<-f1b/sum(f1b) S0b<-max(abs(f1b-f0b)) f0b<-f1b } FF0b<-numeric(nrow(C)) for(i in 1:nrow(C)){ indbb<-(C[,1]==C[i,1]) pos<-min(which(indbb==TRUE)) if(pos==1){ FF0b[indbb]<-sum(f1b[indbb])} if(pos>1){ FF0b[indbb]<-sum(f1b[indbb])+FF0b[pos-1] } } fb<-numeric(nrow(C)) for(i in 1:nrow(C)){ indbbb<-(C[,1]==C[i,1]) pos1<-min(which(indbbb==TRUE)) if(pos1==1){ fb[indbbb]<-sum(f1b[indbbb])} if(pos1>1){ fb[indbbb]<-sum(f1b[indbbb]) } } Sobb<-1-FF0b+fb Sobb[Sobb<1e-12]<-0 FF0b[FF0b<1e-12]<-0 M_IF0 <- as.vector(FF0b) M_IF01 <- as.vector(f1b) M_IF0Sob <- as.vector(Sobb) ordA <- order(M2b[, 2], method = "auto") ord3 <- sort(M2b[, 2], method = "auto") ordB <- order(M2b[, 3], method = "auto") ord4 <- sort(M2b[, 3], method = "auto") return(list( M_IF0, M_IF01, M_IF0Sob,n_sampling_tries)) } stopCluster(cl) n_sampling_tries <- 0 M_IF0 <- matrix(0, nrow = nrow(C), ncol = B) M_IF01 <- matrix(0, nrow = nrow(C), ncol = B) M_IF0Sob <- matrix(0, nrow = nrow(C), ncol = B) stderror<-matrix(0, nrow = nrow(C), ncol = 1) BootRepeat<-matrix(0,ncol=B) for(b in 1:B){ M_IF0[,b]<-as.numeric(unlist(final_boot[b,1])) M_IF01[,b]<-as.numeric(unlist(final_boot[b,2])) M_IF0Sob[,b]<-as.numeric(unlist(final_boot[b,3])) BootRepeat[,b]<-as.numeric((unlist(final_boot[b,4]))) } stderror<-apply(M_IF0,1,sd) M_IF0_sort<-matrix(0,nrow=nrow(C),ncol=B) for(i in 1:nrow(M_IF0_sort)){ M_IF0_sort[i,]<-sort(M_IF0[i,]) } if(is.na(alpha)==TRUE) alpha<-0.05 lowerF<-M_IF0_sort[,floor(alpha*B/2)] upperF<-M_IF0_sort[,floor((1-alpha/2)*B)] M_IF0_sort1<-matrix(0,nrow=nrow(C),ncol=B) for(i in 1:nrow(M_IF0_sort1)){ M_IF0_sort1[i,]<-sort(M_IF0Sob[i,]) } lowerS<-M_IF0_sort1[,floor(alpha*B/2)] upperS<-M_IF0_sort1[,floor((1-alpha/2)*B)] } } if(boot==TRUE){ if(trunc=="both"|trunc=="left"){ x<-unique(C[,1]) if((display.F==TRUE)&(display.S==TRUE)){ dev.new() par(mfrow=c(1,2)) plot(x,FF,ylim=c(0,1),xlim=c(min(x)-(max(x)-min(x))/length(x),max(x)+(max(x)-min(x))/length(x)),type="n",main="CDF", xlab="X",ylab="") segments(min(x)-(max(x)-min(x))/length(x),0,x[1],0) segments(max(x),1,max(x)+(max(x)-min(x))/length(x),1) segments(x[1],0,x[1],FF[1]) for(i in 1:(length(x)-1)){ segments(x[i],FF[i],x[i+1],FF[i]) segments(x[i+1],FF[i],x[i+1],FF[i+1]) } segments(min(C[,1])-(max(C[,1])-min(C[,1]))/length(C[,1]),0,C[,1][1],0,lty=3) segments(max(C[,1]),1,max(C[,1])+(max(C[,1])-min(C[,1]))/length(C[,1]),1,lty=3) segments(C[,1][1],0,C[,1][1],upperF[1], lty=3) for(i in 1:(length(C[,1])-1)){ segments(C[i,1],upperF[i],C[i+1,1],upperF[i], lty=3) segments(C[i+1,1],upperF[i],C[i+1,1],upperF[i+1],lty=3) } segments(min(C[,1])-(max(C[,1])-min(C[,1]))/length(C[,1]),0,C[,1][1],0,lty=3) segments(max(C[,1]),1,max(C[,1])+(max(C[,1])-min(C[,1]))/length(C[,1]),1,lty=3) segments(C[,1][1],0,C[,1][1],lowerF[1], lty=3) for(i in 1:(length(C[,1])-1)){ segments(C[i,1],lowerF[i],C[i+1,1],lowerF[i], lty=3) segments(C[i+1,1],lowerF[i],C[i+1,1],lowerF[i+1],lty=3) } plot(x,Sob,ylim=c(0,1),xlim=c(min(x)-(max(x)-min(x))/length(x),max(x)+(max(x)-min(x))/length(x)),type="n",main="Survival", xlab="X",ylab="") segments(min(x)-(max(x)-min(x))/length(x),1,x[1],1) segments(max(x),0,max(x)+(max(x)-min(x))/length(x),0) segments(max(x),0,max(x),min(Sob0)) for(i in 1:(length(x)-1)){ segments(x[i],Sob[i],x[i+1],Sob[i]) segments(x[i+1],Sob[i],x[i+1],Sob[i+1]) } segments(min(C[,1])-(max(C[,1])-min(C[,1]))/length(C[,1]),1,C[,1][1],1,lty=3) segments(max(C[,1]),0,max(C[,1])+(max(C[,1])-min(C[,1]))/length(C[,1]),0,lty=3) segments(max(C[,1]),0,max(C[,1]),min(upperS), lty=3) for(i in 1:(length(C[,1])-1)){ segments(C[i,1],upperS[i],C[i+1,1],upperS[i], lty=3) segments(C[i+1,1],upperS[i],C[i+1,1],upperS[i+1],lty=3) } segments(min(C[,1])-(max(C[,1])-min(C[,1]))/length(C[,1]),1,C[,1][1],1,lty=3) segments(max(C[,1]),0,max(C[,1])+(max(C[,1])-min(C[,1]))/length(C[,1]),0,lty=3) segments(max(C[,1]),0,max(C[,1]),min(lowerS), lty=3) for(i in 1:(length(C[,1])-1)){ segments(C[i,1],lowerS[i],C[i+1,1],lowerS[i], lty=3) segments(C[i+1,1],lowerS[i],C[i+1,1],lowerS[i+1],lty=3) } } if((display.S==FALSE)&(display.F==TRUE)){ dev.new() plot(x,FF,ylim=c(0,1),xlim=c(min(x)-(max(x)-min(x))/length(x),max(x)+(max(x)-min(x))/length(x)),type="n",main="CDF", xlab="X",ylab="") segments(min(x)-(max(x)-min(x))/length(x),0,x[1],0) segments(max(x),1,max(x)+(max(x)-min(x))/length(x),1) segments(x[1],0,x[1],FF[1]) for(i in 1:(length(x)-1)){ segments(x[i],FF[i],x[i+1],FF[i]) segments(x[i+1],FF[i],x[i+1],FF[i+1]) } segments(min(C[,1])-(max(C[,1])-min(C[,1]))/length(C[,1]),0,C[,1][1],0,lty=3) segments(max(C[,1]),1,max(C[,1])+(max(C[,1])-min(C[,1]))/length(C[,1]),1,lty=3) segments(C[,1][1],0,C[,1][1],upperF[1], lty=3) for(i in 1:(length(C[,1])-1)){ segments(C[i,1],upperF[i],C[i+1,1],upperF[i], lty=3) segments(C[i+1,1],upperF[i],C[i+1,1],upperF[i+1],lty=3) } segments(min(C[,1])-(max(C[,1])-min(C[,1]))/length(C[,1]),0,C[,1][1],0,lty=3) segments(max(C[,1]),1,max(C[,1])+(max(C[,1])-min(C[,1]))/length(x),1,lty=3) segments(C[,1][1],0,C[,1][1],lowerF[1], lty=3) for(i in 1:(length(C[,1])-1)){ segments(C[i,1],lowerF[i],C[i+1,1],lowerF[i], lty=3) segments(C[i+1,1],lowerF[i],C[i+1,1],lowerF[i+1],lty=3) } } if((display.F==FALSE)&(display.S==TRUE)){ dev.new() plot(x,Sob,ylim=c(0,1),xlim=c(min(x)-(max(x)-min(x))/length(x),max(x)+(max(x)-min(x))/length(x)),type="n",main="Survival", xlab="X",ylab="") segments(min(x)-(max(x)-min(x))/length(x),1,x[1],1) segments(max(x),0,max(x)+(max(x)-min(x))/length(x),0) segments(max(x),0,max(x),min(Sob0)) for(i in 1:(length(x)-1)){ segments(x[i],Sob[i],x[i+1],Sob[i]) segments(x[i+1],Sob[i],x[i+1],Sob[i+1]) } segments(min(C[,1])-(max(C[,1])-min(C[,1]))/length(C[,1]),1,C[,1][1],1,lty=3) segments(max(C[,1]),0,max(C[,1])+(max(C[,1])-min(C[,1]))/length(C[,1]),0,lty=3) segments(max(C[,1]),0,max(C[,1]),min(upperS), lty=3) for(i in 1:(length(C[,1])-1)){ segments(C[i,1],upperS[i],C[i+1,1],upperS[i], lty=3) segments(C[i+1,1],upperS[i],C[i+1,1],upperS[i+1],lty=3) } segments(min(C[,1])-(max(C[,1])-min(C[,1]))/length(C[,1]),1,C[,1][1],1,lty=3) segments(max(C[,1]),0,max(C[,1])+(max(C[,1])-min(C[,1]))/length(C[,1]),0,lty=3) segments(max(C[,1]),0,max(C[,1]),min(lowerS), lty=3) for(i in 1:(length(C[,1])-1)){ segments(C[i,1],lowerS[i],C[i+1,1],lowerS[i], lty=3) segments(C[i+1,1],lowerS[i],C[i+1,1],lowerS[i+1],lty=3) } } } if(trunc=="right"){ if((display.F==TRUE)&(display.S==TRUE)){ x<-unique(C[,1]) dev.new() par(mfrow=c(1,2)) plot(x,FF,ylim=c(0,1),xlim=c(min(x)-(max(x)-min(x))/length(x),max(x)+(max(x)-min(x))/length(x)),type="n",main="CDF", xlab="X",ylab="") segments(min(x)-(max(x)-min(x))/length(x),0,x[1],0) segments(max(x),1,max(x)+(max(x)-min(x))/length(x),1) segments(x[1],0,x[1],FFF[1]) for(i in 1:(length(x)-1)){ segments(x[i],FF[i],x[i+1],FF[i]) segments(x[i+1],FF[i],x[i+1],FF[i+1]) } segments(min(C[,1])-(max(C[,1])-min(C[,1]))/length(C[,1]),0,C[,1][1],0,lty=3) segments(max(C[,1]),1,max(C[,1])+(max(C[,1])-min(C[,1]))/length(C[,1]),1,lty=3) segments(max(C[,1]),1,max(C[,1]),max(upperF), lty=3) for(i in 1:(length(C[,1])-1)){ segments(C[,1][i],upperF[i],C[,1][i+1],upperF[i], lty=3) segments(C[,1][i+1],upperF[i],C[,1][i+1],upperF[i+1],lty=3) } segments(min(C[,1])-(max(C[,1])-min(C[,1]))/length(C[,1]),0,C[,1][1],0,lty=3) segments(max(C[,1]),1,max(C[,1])+(max(C[,1])-min(C[,1]))/length(C[,1]),1,lty=3) segments(max(C[,1]),1,max(C[,1]),max(lowerF), lty=3) for(i in 1:(length(C[,1])-1)){ segments(C[,1][i],lowerF[i],C[,1][i+1],lowerF[i], lty=3) segments(C[,1][i+1],lowerF[i],C[,1][i+1],lowerF[i+1],lty=3) } plot(x,Sob,ylim=c(0,1),xlim=c(min(x)-(max(x)-min(x))/length(x),max(x)+(max(x)-min(x))/length(x)),type="n",main="Survival", xlab="X",ylab="") segments(min(x)-(max(x)-min(x))/length(x),1,x[1],1) segments(max(x),0,max(x)+(max(x)-min(x))/length(x),0) segments(max(x),0,max(x),min(Sob0)) for(i in 1:(length(x)-1)){ segments(x[i],Sob[i],x[i+1],Sob[i]) segments(x[i+1],Sob[i],x[i+1],Sob[i+1]) } segments(min(C[,1])-(max(C[,1])-min(C[,1]))/length(C[,1]),1,C[,1][1],1,lty=3) segments(max(C[,1]),0,max(C[,1])+(max(C[,1])-min(C[,1]))/length(C[,1]),0,lty=3) segments(max(C[,1]),0,max(C[,1]),min(upperS), lty=3) for(i in 1:(length(C[,1])-1)){ segments(C[,1][i],upperS[i],C[,1][i+1],upperS[i], lty=3) segments(C[,1][i+1],upperS[i],C[,1][i+1],upperS[i+1],lty=3) } segments(min(C[,1])-(max(C[,1])-min(C[,1]))/length(C[,1]),1,C[,1][1],1,lty=3) segments(max(C[,1]),0,max(C[,1])+(max(C[,1])-min(C[,1]))/length(C[,1]),0,lty=3) segments(max(C[,1]),0,max(C[,1]),min(lowerS), lty=3) for(i in 1:(length(C[,1])-1)){ segments(C[,1][i],lowerS[i],C[,1][i+1],lowerS[i], lty=3) segments(C[,1][i+1],lowerS[i],C[,1][i+1],lowerS[i+1],lty=3) } } if((display.F==FALSE)&(display.S==TRUE)){ x<-unique(C[,1]) dev.new() par(mfrow=c(1,1)) plot(x,Sob,ylim=c(0,1),xlim=c(min(x)-(max(x)-min(x))/length(x),max(x)+(max(x)-min(x))/length(x)),type="n",main="Survival", xlab="X",ylab="") segments(min(x)-(max(x)-min(x))/length(x),1,x[1],1) segments(max(x),0,max(x)+(max(x)-min(x))/length(x),0) segments(max(x),0,max(x),min(Sob0)) for(i in 1:(length(x)-1)){ segments(x[i],Sob[i],x[i+1],Sob[i]) segments(x[i+1],Sob[i],x[i+1],Sob[i+1]) } segments(min(C[,1])-(max(C[,1])-min(C[,1]))/length(C[,1]),1,C[,1][1],1,lty=3) segments(max(C[,1]),0,max(C[,1])+(max(C[,1])-min(C[,1]))/length(C[,1]),0,lty=3) segments(max(C[,1]),0,max(C[,1]),min(upperS), lty=3) for(i in 1:(length(C[,1])-1)){ segments(C[,1][i],upperS[i],C[,1][i+1],upperS[i], lty=3) segments(C[,1][i+1],upperS[i],C[,1][i+1],upperS[i+1],lty=3) } segments(min(C[,1])-(max(C[,1])-min(C[,1]))/length(C[,1]),1,C[,1][1],1,lty=3) segments(max(C[,1]),0,max(C[,1])+(max(C[,1])-min(C[,1]))/length(C[,1]),0,lty=3) segments(max(C[,1]),0,max(C[,1]),min(lowerS), lty=3) for(i in 1:(length(C[,1])-1)){ segments(C[,1][i],lowerS[i],C[,1][i+1],lowerS[i], lty=3) segments(C[,1][i+1],lowerS[i],C[,1][i+1],lowerS[i+1],lty=3) } } if((display.F==TRUE)&(display.S==FALSE)){ x<-unique(C[,1]) dev.new() par(mfrow=c(1,1)) plot(x,FF,ylim=c(0,1),xlim=c(min(x)-(max(x)-min(x))/length(x),max(x)+(max(x)-min(x))/length(x)),type="n",main="CDF", xlab="X",ylab="") segments(min(x)-(max(x)-min(x))/length(x),0,x[1],0) segments(max(x),1,max(x)+(max(x)-min(x))/length(x),1) segments(x[1],0,x[1],FFF[1]) for(i in 1:(length(x)-1)){ segments(x[i],FF[i],x[i+1],FF[i]) segments(x[i+1],FF[i],x[i+1],FF[i+1]) } segments(min(C[,1])-(max(C[,1])-min(C[,1]))/length(C[,1]),0,C[,1][1],0,lty=3) segments(max(C[,1]),1,max(C[,1])+(max(C[,1])-min(C[,1]))/length(C[,1]),1,lty=3) segments(C[,1][1],0,C[,1][1],upperF[1], lty=3) for(i in 1:(length(C[,1])-1)){ segments(C[,1][i],upperF[i],C[,1][i+1],upperF[i], lty=3) segments(C[,1][i+1],upperF[i],C[,1][i+1],upperF[i+1],lty=3) } segments(min(C[,1])-(max(C[,1])-min(C[,1]))/length(C[,1]),0,C[,1][1],0,lty=3) segments(max(C[,1]),1,max(C[,1])+(max(C[,1])-min(C[,1]))/length(C[,1]),1,lty=3) segments(C[,1][1],0,C[,1][1],lowerF[1], lty=3) for(i in 1:(length(C[,1])-1)){ segments(C[,1][i],lowerF[i],C[,1][i+1],lowerF[i], lty=3) segments(C[,1][i+1],lowerF[i],C[,1][i+1],lowerF[i+1],lty=3) } } } } if (boot==FALSE|B<40){ if(trunc=="both"|trunc=="left"){ if((display.F==TRUE)&(display.S==TRUE)){ x<-C[,1] dev.new() par(mfrow=c(1,2)) plot(x,FFF,ylim=c(0,1),xlim=c(min(x)-(max(x)-min(x))/length(x),max(x)+(max(x)-min(x))/length(x)),type="n",main="CDF", xlab="X",ylab="") segments(min(x)-(max(x)-min(x))/length(x),0,x[1],0) segments(max(x),1,max(x)+(max(x)-min(x))/length(x),1) segments(x[1],0,x[1],FFF[1]) for(i in 1:(length(x)-1)){ segments(x[i],FFF[i],x[i+1],FFF[i]) segments(x[i+1],FFF[i],x[i+1],FFF[i+1]) } plot(x,Sob0,ylim=c(0,1),xlim=c(min(x)-(max(x)-min(x))/length(x),max(x)+(max(x)-min(x))/length(x)),type="n",main="Survival", xlab="X",ylab="") segments(min(x)-(max(x)-min(x))/length(x),1,x[1],1) segments(max(x),0,max(x)+(max(x)-min(x))/length(x),0) segments(max(x),0,max(x),min(Sob0)) segments(x0 = min(x), x1 = min(x), y0 = Sob0[1], y1 = 1) for(i in 1:(length(x)-1)){ segments(x[i],Sob0[i],x[i+1],Sob0[i]) segments(x[i+1],Sob0[i],x[i+1],Sob0[i+1]) } } if((display.S==FALSE)&(display.F==TRUE)){ x<-C[,1] dev.new() plot(x,FFF,ylim=c(0,1),xlim=c(min(x)-(max(x)-min(x))/length(x),max(x)+(max(x)-min(x))/length(x)),type="n",main="CDF", xlab="X",ylab="") segments(min(x)-(max(x)-min(x))/length(x),0,x[1],0) segments(max(x),1,max(x)+(max(x)-min(x))/length(x),1) segments(x[1],0,x[1],FFF[1]) for(i in 1:(length(x)-1)){ segments(x[i],FFF[i],x[i+1],FFF[i]) segments(x[i+1],FFF[i],x[i+1],FFF[i+1]) } } if((display.F==FALSE)&(display.S==TRUE)){ x<-C[,1] dev.new() plot(x,Sob0,ylim=c(0,1),xlim=c(min(x)-(max(x)-min(x))/length(x),max(x)+(max(x)-min(x))/length(x)),type="n",main="Survival", xlab="X",ylab="") segments(min(x)-(max(x)-min(x))/length(x),1,x[1],1) segments(max(x),0,max(x)+(max(x)-min(x))/length(x),0) segments(max(x),0,max(x),min(Sob0)) segments(x0 = min(x), x1 = min(x), y0 = Sob0[1], y1 = 1) for(i in 1:(length(x)-1)){ segments(x[i],Sob0[i],x[i+1],Sob0[i]) segments(x[i+1],Sob0[i],x[i+1],Sob0[i+1]) } } } if(trunc=="right"){ Sob0[Sob0<1e-12]<-0 FFF[FFF<1e-12]<-0 if((display.F==TRUE)&(display.S==TRUE)){ x<-C[,1] dev.new() par(mfrow=c(1,2)) plot(x,FFF,ylim=c(0,1),xlim=c(min(x)-(max(x)-min(x))/length(x),max(x)+(max(x)-min(x))/length(x)),type="n",main="CDF", xlab="X",ylab="") segments(min(x)-(max(x)-min(x))/length(x),0,x[1],0) segments(max(x),1,max(x)+(max(x)-min(x))/length(x),1) segments(x[1],0,x[1],FFF[1]) for(i in 1:(length(x)-1)){ segments(x[i],FFF[i],x[i+1],FFF[i]) segments(x[i+1],FFF[i],x[i+1],FFF[i+1]) } plot(x,Sob0,ylim=c(0,1),xlim=c(min(x)-(max(x)-min(x))/length(x),max(x)+(max(x)-min(x))/length(x)),type="n",main="Survival", xlab="X",ylab="") segments(min(x)-(max(x)-min(x))/length(x),1,x[1],1) segments(max(x),0,max(x)+(max(x)-min(x))/length(x),0) segments(max(x),0,max(x),min(Sob0)) segments(x0 = min(x), x1 = min(x), y0 = Sob0[1], y1 = 1) for(i in 1:(length(x)-1)){ segments(x[i],Sob0[i],x[i+1],Sob0[i]) segments(x[i+1],Sob0[i],x[i+1],Sob0[i+1]) } } if((display.F==FALSE)&(display.S==TRUE)){ x<-C[,1] dev.new() par(mfrow=c(1,1)) plot(x,Sob0,ylim=c(0,1),xlim=c(min(x)-(max(x)-min(x))/length(x),max(x)+(max(x)-min(x))/length(x)),type="n",main="Survival", xlab="X",ylab="") segments(min(x)-(max(x)-min(x))/length(x),1,x[1],1) segments(max(x),0,max(x)+(max(x)-min(x))/length(x),0) segments(max(x),0,max(x),min(Sob0)) segments(x0 = min(x), x1 = min(x), y0 = Sob0[1], y1 = 1) for(i in 1:(length(x)-1)){ segments(x[i],Sob0[i],x[i+1],Sob0[i]) segments(x[i+1],Sob0[i],x[i+1],Sob0[i+1]) } } if((display.F==TRUE)&(display.S==FALSE)){ x<-C[,1] dev.new() par(mfrow=c(1,1)) plot(x,FFF,ylim=c(0,1),xlim=c(min(x)-(max(x)-min(x))/length(x),max(x)+(max(x)-min(x))/length(x)),type="n",main="CDF", xlab="X",ylab="") segments(min(x)-(max(x)-min(x))/length(x),0,x[1],0) segments(max(x),1,max(x)+(max(x)-min(x))/length(x),1) segments(x[1],0,x[1],FFF[1]) for(i in 1:(length(x)-1)){ segments(x[i],FFF[i],x[i+1],FFF[i]) segments(x[i+1],FFF[i],x[i+1],FFF[i+1]) } } } } cat("n.iterations",iter,"\n") cat("S0",S0,"\n") cat("events",events,"\n") if(boot==TRUE){ cat("B",B,"\n") cat("alpha",alpha,"\n") return(invisible(list(n.iterations=iter, events=events, B=B, alpha=alpha,time=C[,1], n.event=mult, density=round(as.vector(f),5), cumulative.df=round(FFF,5), survival= round(as.vector(Sob0),5), truncation.probs=round(as.vector(F0),5), upper.df=round(upperF,5),lower.df=round(lowerF,5),upper.Sob=round(upperS,5), lower.Sob=round(lowerS,5), sd.boot=round(stderror,5),boot.repeat=as.vector(BootRepeat)))) } if(boot==FALSE){ return(invisible(list(n.iterations=iter, events=events, time=C[,1], n.event=mult, density=round(as.vector(f),5), cumulative.df=round(FFF,5), survival= round(as.vector(Sob0),5), truncation.probs=round(as.vector(F0),5)))) } }