id
stringlengths
40
40
repo_name
stringlengths
5
110
path
stringlengths
2
233
content
stringlengths
0
1.03M
size
int32
0
60M
license
stringclasses
15 values
233f3e1bbf84fba920c6bbaf638d42a13771c7e6
fingerhuth/NG-resistance-spread
sensitivity/fitness_costs/pn_8/s_g-init-res.R
cost_b <- vec_cost_b[l] cost_v <- vec_cost_v[m] parms <- c(c=c, noG=noG, alpha=alpha, v=v, gamma=gamma, rho=rho, ta=ta, e0_a=e0_a, ea_a=ea_a, mu_0a=mu_0a, mu_a0=mu_a0, cost_b=cost_b, cost_v=cost_v ) init <- unlist(free.out[1])
318
mit
48a213f6b3f77fccdb5a1ad84324167237e54a6b
RcppCore/Rcpp
inst/tinytest/test_client_package.R
## Copyright (C) 2010 - 2019 Dirk Eddelbuettel and Romain Francois ## ## This file is part of Rcpp. ## ## Rcpp is free software: you can redistribute it and/or modify it ## under the terms of the GNU General Public License as published by ## the Free Software Foundation, either version 2 of the License, or ## (at your option) any later version. ## ## Rcpp is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Rcpp. If not, see <http://www.gnu.org/licenses/>. ## This now (Dec 2011) appears to fail on Windows .onWindows <- .Platform$OS.type == "windows" .runThisTest <- Sys.getenv("RunAllRcppTests") == "yes" && Sys.getenv("RunVerboseRcppTests") == "yes" if (! .runThisTest) exit_file("Set 'RunVerboseRcppTests' and 'RunAllRcppTests' to 'yes' to run.") if (.onWindows) exit_file("Skipping on Windows.'") #.client.package <- function(pkg = "testRcppPackage") { td <- tempfile() cwd <- getwd() dir.create(td) pkg <- "testRcppPackage" #file.copy(system.file("unitTests", pkg, package = "Rcpp"), td, recursive = TRUE) file.copy(pkg, td, recursive = TRUE) # simpler direct path thanks to tinytest setwd(td) on.exit( { setwd(cwd); unlink(td, recursive = TRUE) } ) R <- shQuote(file.path( R.home(component = "bin"), "R")) cmd <- paste(R, "CMD build", pkg, " >/dev/null 2>&1") system(cmd) dir.create("templib") pkgfile <- paste0(pkg, "_0.1.0.tar.gz") install.packages(pkgfile, "templib", repos = NULL, type = "source") require(pkg, lib.loc = "templib", character.only = TRUE) hello_world <- get("rcpp_hello_world", asNamespace(pkg)) expect_equal(hello_world(), list(c("foo", "bar"), c(0.0, 1.0)), info = "code from client package") expect_error(.Call("hello_world_ex", PACKAGE = pkg), info = "exception in client package") remove.packages(pkg, lib="templib") unlink("templib", recursive = TRUE) setwd(cwd) unlink(pkgfile)
2,115
gpl-2.0
233f3e1bbf84fba920c6bbaf638d42a13771c7e6
fingerhuth/NG-resistance-spread
sensitivity/fitness_costs/pn_7/s_g-init-res.R
cost_b <- vec_cost_b[l] cost_v <- vec_cost_v[m] parms <- c(c=c, noG=noG, alpha=alpha, v=v, gamma=gamma, rho=rho, ta=ta, e0_a=e0_a, ea_a=ea_a, mu_0a=mu_0a, mu_a0=mu_a0, cost_b=cost_b, cost_v=cost_v ) init <- unlist(free.out[1])
318
mit
48a213f6b3f77fccdb5a1ad84324167237e54a6b
ellert/Rcpp
inst/tinytest/test_client_package.R
## Copyright (C) 2010 - 2019 Dirk Eddelbuettel and Romain Francois ## ## This file is part of Rcpp. ## ## Rcpp is free software: you can redistribute it and/or modify it ## under the terms of the GNU General Public License as published by ## the Free Software Foundation, either version 2 of the License, or ## (at your option) any later version. ## ## Rcpp is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Rcpp. If not, see <http://www.gnu.org/licenses/>. ## This now (Dec 2011) appears to fail on Windows .onWindows <- .Platform$OS.type == "windows" .runThisTest <- Sys.getenv("RunAllRcppTests") == "yes" && Sys.getenv("RunVerboseRcppTests") == "yes" if (! .runThisTest) exit_file("Set 'RunVerboseRcppTests' and 'RunAllRcppTests' to 'yes' to run.") if (.onWindows) exit_file("Skipping on Windows.'") #.client.package <- function(pkg = "testRcppPackage") { td <- tempfile() cwd <- getwd() dir.create(td) pkg <- "testRcppPackage" #file.copy(system.file("unitTests", pkg, package = "Rcpp"), td, recursive = TRUE) file.copy(pkg, td, recursive = TRUE) # simpler direct path thanks to tinytest setwd(td) on.exit( { setwd(cwd); unlink(td, recursive = TRUE) } ) R <- shQuote(file.path( R.home(component = "bin"), "R")) cmd <- paste(R, "CMD build", pkg, " >/dev/null 2>&1") system(cmd) dir.create("templib") pkgfile <- paste0(pkg, "_0.1.0.tar.gz") install.packages(pkgfile, "templib", repos = NULL, type = "source") require(pkg, lib.loc = "templib", character.only = TRUE) hello_world <- get("rcpp_hello_world", asNamespace(pkg)) expect_equal(hello_world(), list(c("foo", "bar"), c(0.0, 1.0)), info = "code from client package") expect_error(.Call("hello_world_ex", PACKAGE = pkg), info = "exception in client package") remove.packages(pkg, lib="templib") unlink("templib", recursive = TRUE) setwd(cwd) unlink(pkgfile)
2,115
gpl-2.0
c6612ccd2a346181452bbe38c3ba222bd55c171c
IALSA/IALSA-2015-Portland
sandbox/shiny-basic/server.R
library(shiny) if(basename(getwd())=="basic"){ dsb <- readRDS('../../data/shared/ds1a.rds') }else{ dsb <- readRDS('./data/shared/ds1a.rds') } dsb <- dsb %>% dplyr::filter(model_number %in% c("u1","b1")) ds <- dsb[ , c("study_name", "model_type","physical_construct","cognitive_construct","physical_measure","cognitive_measure","corr_int","p_cov_int","corr_slope","p_cov_slope")] head(ds) unique(ds$study_name) unique(ds$physical_construct) # Define server logic required to summarize and view the selected # study shinyServer(function(input, output,clientData,session) { # Develope handler for when study variables is empty # use handlers / if() observe({ # browser() # ds_study <- ds[ds$study_name==input$study, ] study_variables <- sort(unique(ds_study()$physical_construct)) updateSelectInput(session, "physical", choices = study_variables, selected=study_variables[1]) }) ds_study <- reactive({ ds[ds$study_name==input$study, ] }) # Generate frequency count for the study output$freqs <- renderPrint({ table(ds_study()$physical_construct,ds_study()$cognitive_construct) # }) # # # Show the first "n" observations output$view <- renderDataTable({ ds_study_physical <- ds_study()[ds_study()$physical_construct==input$physical, ] head(ds_study_physical, n=input$obs) }, options = list( searching = F, paging = FALSE, sort = FALSE, language= list(emptyTable="--<em>This table has no entries</em>--")) ) })
1,513
gpl-2.0
9327fecda1528ba333c2c4ee8d07741af4af8124
gmonette/spida2
R/pch.R
#' Easy pch characters #' #' Fifteen pch symbols and six line types can be generated #' mnemonic names. #' #' @param shape 'square', 'circle', 'triangle', 'diamond', 'ltriangle' (or 1, 2, 3, 4, 5 respectively). Default: 1 #' @param fill 'empty', 'solid', 'fill' (with different color) (or 1, 2, 3 respectively). Default: 1 #' @param line 'solid','dashed','dotted','dash dot','long dash','long dash dot' (or 1, 2, 3, 4, 5, 6 respectively). Default: 1 #' @return value(s) of pch or lty to produce corresponding character or line type #' @export pch <- function(shape = 1, fill = 1){ shapenames <- c('square', 'circle', 'triangle', 'diamond', 'ltriangle') fillnames <- c('empty', 'solid', 'fill') if(!is.numeric(shape)) shape <- sapply(shape, function(s) grep(s,shapenames)[1]) if(!is.numeric(fill)) fill <- sapply(fill, function(s) grep(s,fillnames)[1]) mat <- t(rbind( c(0,1,2,5,6), c(15,16,17,18,25),c(22,21,24,23,25))) mat[cbind(shape,fill)] } #' @describeIn pch Easy line types #' @export lty <- function(line = 1){ linetypes <- c('solid', 'dashed', 'dotted', 'dash dot', 'long dash', 'long dash dot') if(!is.numeric(line)) line <- sapply(line, function(s) grep(s,linetypes)[1]) line }
1,286
gpl-2.0
9327fecda1528ba333c2c4ee8d07741af4af8124
gmonette/yscs
R/pch.R
#' Easy pch characters #' #' Fifteen pch symbols and six line types can be generated #' mnemonic names. #' #' @param shape 'square', 'circle', 'triangle', 'diamond', 'ltriangle' (or 1, 2, 3, 4, 5 respectively). Default: 1 #' @param fill 'empty', 'solid', 'fill' (with different color) (or 1, 2, 3 respectively). Default: 1 #' @param line 'solid','dashed','dotted','dash dot','long dash','long dash dot' (or 1, 2, 3, 4, 5, 6 respectively). Default: 1 #' @return value(s) of pch or lty to produce corresponding character or line type #' @export pch <- function(shape = 1, fill = 1){ shapenames <- c('square', 'circle', 'triangle', 'diamond', 'ltriangle') fillnames <- c('empty', 'solid', 'fill') if(!is.numeric(shape)) shape <- sapply(shape, function(s) grep(s,shapenames)[1]) if(!is.numeric(fill)) fill <- sapply(fill, function(s) grep(s,fillnames)[1]) mat <- t(rbind( c(0,1,2,5,6), c(15,16,17,18,25),c(22,21,24,23,25))) mat[cbind(shape,fill)] } #' @describeIn pch Easy line types #' @export lty <- function(line = 1){ linetypes <- c('solid', 'dashed', 'dotted', 'dash dot', 'long dash', 'long dash dot') if(!is.numeric(line)) line <- sapply(line, function(s) grep(s,linetypes)[1]) line }
1,286
gpl-2.0
fa6e38459c8786fce2be14b040c45427b02d14fd
pssguy/rstudio
src/cpp/r/R/Api.R
.rs.addApiFunction("versionInfo", function() { info <- list() info$citation <- .Call(getNativeSymbolInfo("rs_rstudioCitation", PACKAGE="")) info$mode <- .Call(getNativeSymbolInfo("rs_rstudioProgramMode", PACKAGE="")) info$version <- package_version( .Call(getNativeSymbolInfo("rs_rstudioVersion", PACKAGE="")) ) info }) .rs.addApiFunction("diagnosticsReport", function() { invisible(.Call(getNativeSymbolInfo("rs_sourceDiagnostics", PACKAGE=""))) }) .rs.addApiFunction("previewRd", function(rdFile) { if (!is.character(rdFile) || (length(rdFile) != 1)) stop("rdFile must be a single element character vector.") if (!file.exists(rdFile)) stop("The specified rdFile ' ", rdFile, "' does not exist.") invisible(.Call(getNativeSymbolInfo("rs_previewRd", PACKAGE=""), rdFile)) }) .rs.addApiFunction("viewer", function(url, height = NULL) { if (!is.character(url) || (length(url) != 1)) stop("url must be a single element character vector.") if (identical(height, "maximize")) height <- -1 if (!is.null(height) && (!is.numeric(height) || (length(height) != 1))) stop("height must be a single element numeric vector or 'maximize'.") invisible(.Call(getNativeSymbolInfo("rs_viewer", PACKAGE=""), url, height)) }) .rs.addApiFunction("sourceMarkers", function(name, markers, basePath = NULL, autoSelect = c("none", "first", "error")) { # validate name if (!is.character(name)) stop("name parameter is specified or invalid: ", name, call. = FALSE) # validate autoSelect autoSelect = match.arg(autoSelect) # normalize basePath if (!is.null(basePath)) basePath <- .rs.normalizePath(basePath, mustWork = TRUE) if (is.data.frame(markers)) { cols <- colnames(markers) if (!"type" %in% cols || !is.character(markers$type)) stop("markers type field is unspecified or invalid", call. = FALSE) if (!"file" %in% cols || !is.character(markers$file)) stop("markers file field is unspecified or invalid", call. = FALSE) if (!"line" %in% cols || !is.numeric(markers$line)) stop("markers line field is unspecified or invalid", call. = FALSE) if (!"column" %in% cols || !is.numeric(markers$column)) stop("markers column field is unspecified or invalid", call. = FALSE) if (!"message" %in% cols || !is.character(markers$message)) stop("markers message field is unspecified or invalid", call. = FALSE) # normalize paths cols$file <- .rs.normalizePath(cols$file, mustWork = TRUE) # check for html cols$messageHTML <- .rs.scalar(inherits(cols$message, "html")) } else if (is.list(markers)) { markers <- lapply(markers, function(marker) { markerTypes <- c("error", "warning", "box", "info", "style", "usage") if (is.null(marker$type) || (!marker$type %in% markerTypes)) stop("Invalid marker type (", marker$type, ")", call. = FALSE) if (!is.character(marker$file)) stop("Marker file is unspecified or invalid: ", marker$file, call. = FALSE) if (!is.numeric(marker$line)) stop("Marker line is unspecified or invalid", marker$line, call. = FALSE) if (!is.numeric(marker$column)) stop("Marker column is unspecified or invalid", marker$line, call. = FALSE) if (!is.character(marker$message)) stop("Marker message is unspecified or invalid: ", marker$message, call. = FALSE) marker$type <- .rs.scalar(marker$type) marker$file <- .rs.scalar(.rs.normalizePath(marker$file, mustWork = TRUE)) marker$line <- .rs.scalar(as.numeric(marker$line)) marker$column <- .rs.scalar(as.numeric(marker$column)) marker$message <- .rs.scalar(marker$message) marker$messageHTML <- .rs.scalar(inherits(marker$message, "html")) marker }) } else { stop("markers was not a data.frame or a list", call. = FALSE) } # validate basePath if (is.null(basePath)) basePath <- "" else if (!is.character(basePath)) stop("basePath parameter is not of type character", call. = FALSE) invisible(.Call("rs_sourceMarkers", name, markers, basePath, autoSelect)) })
4,554
agpl-3.0
a8af4e1529bf45c65c4a272505d8a67b15b4a6e0
radfordneal/pqR
tests/subsetting.R
# Test possible bugs involving subset and subassign. # # Added for pqR, 2014, 2017, Radford M. Neal. # General tests of subset extraction with scalar indexes, not array. vi <- 11:15 vr <- (11:15) + 0.1 L <- list(11.1,12L,13.1,14L,TRUE) Ln <- list(e1=11.1,e2=12L,e3=13.1,e4=14L,e5=TRUE) vin <- vi names(vin) <- paste0("a",1:length(vin)) vrn <- vr names(vrn) <- paste0("a",1:length(vrn)) a <- vi[3L] stopifnot(identical(a,13L)) a <- vi[3] stopifnot(identical(a,13L)) a <- vr[3] stopifnot(identical(a,13.1)) a <- vin[3] stopifnot(identical(a,c(a3=13L))) a <- vrn[3] stopifnot(identical(a,c(a3=13.1))) a <- L[3] stopifnot(identical(a,list(13.1))) a <- Ln[3] stopifnot(identical(a,list(e3=13.1))) a <- vi[[3]] stopifnot(identical(a,13L)) a <- vr[[3]] stopifnot(identical(a,13.1)) a <- vin[[3]] stopifnot(identical(a,13L)) a <- vrn[[3]] stopifnot(identical(a,13.1)) a <- L[[3]] stopifnot(identical(a,13.1)) a <- Ln[[3]] stopifnot(identical(a,13.1)) a <- vin["a3"] stopifnot(identical(a,c(a3=13L))) a <- vin[["a3"]] stopifnot(identical(a,13L)) a <- Ln[["e3"]] stopifnot(identical(a,13.1)) a <- Ln$e3 stopifnot(identical(a,13.1)) j <- 2 a <- vi[j+1] stopifnot(identical(a,13L)) a <- vr[j+1] stopifnot(identical(a,13.1)) a <- vin[j+1] stopifnot(identical(a,c(a3=13L))) a <- vrn[j+1] stopifnot(identical(a,c(a3=13.1))) a <- L[j+1] stopifnot(identical(a,list(13.1))) a <- Ln[j+1] stopifnot(identical(a,list(e3=13.1))) a <- vi[[j+1]] stopifnot(identical(a,13L)) a <- vr[[j+1]] stopifnot(identical(a,13.1)) a <- vin[[j+1]] stopifnot(identical(a,13L)) a <- vrn[[j+1]] stopifnot(identical(a,13.1)) a <- L[[j+1]] stopifnot(identical(a,13.1)) a <- Ln[[j+1]] stopifnot(identical(a,13.1)) # General tests of subset replacement with scalar indexes, not array. vi <- 11:15 vr <- (11:15) + 0.1 L <- list(11.1,12L,13.1,14L,TRUE) Ln <- list(e1=11.1,e2=12L,e3=13.1,e4=14L,e5=TRUE) vin <- vi names(vin) <- paste0("a",1:length(vin)) vrn <- vr names(vrn) <- paste0("a",1:length(vrn)) vi[3] <- 20L stopifnot(identical(vi,c(11L,12L,20L,14L,15L))) vi[2] <- 30 stopifnot(identical(vi,c(11,30,20,14,15))) vr[3] <- 20.2 vr[2] <- 30.2 stopifnot(identical(vr,c(11.1,30.2,20.2,14.1,15.1))) vin[3] <- 20L stopifnot(identical(vin,c(a1=11L,a2=12L,a3=20L,a4=14L,a5=15L))) vin[2] <- 30 stopifnot(identical(vin,c(a1=11,a2=30,a3=20,a4=14,a5=15))) vrn[3] <- 20.2 vrn[2] <- 30.2 stopifnot(identical(vrn,c(a1=11.1,a2=30.2,a3=20.2,a4=14.1,a5=15.1))) L[3] <- list(FALSE) stopifnot(identical(L,list(11.1,12L,FALSE,14L,TRUE))) L[[2]] <- 1.1 stopifnot(identical(L,list(11.1,1.1,FALSE,14L,TRUE))) Ln[3] <- list(FALSE) stopifnot(identical(Ln,list(e1=11.1,e2=12L,e3=FALSE,e4=14L,e5=TRUE))) Ln$e5 <- "abc" stopifnot(identical(Ln,list(e1=11.1,e2=12L,e3=FALSE,e4=14L,e5="abc"))) Ln$e1 <- c(1,2) stopifnot(identical(Ln,list(e1=c(1,2),e2=12L,e3=FALSE,e4=14L,e5="abc"))) vi <- 11:15 vr <- (11:15) + 0.1 L <- list(11.1,12L,13.1,14L,TRUE) Ln <- list(e1=11.1,e2=12L,e3=13.1,e4=14L,e5=TRUE) vin <- vi names(vin) <- paste0("a",1:length(vin)) vrn <- vr names(vrn) <- paste0("a",1:length(vrn)) vi[[3]] <- 20L stopifnot(identical(vi,c(11L,12L,20L,14L,15L))) vi[[2]] <- 30 stopifnot(identical(vi,c(11,30,20,14,15))) vr[[3]] <- 20.2 vr[[2]] <- 30.2 stopifnot(identical(vr,c(11.1,30.2,20.2,14.1,15.1))) vin[[3]] <- 20L stopifnot(identical(vin,c(a1=11L,a2=12L,a3=20L,a4=14L,a5=15L))) vin[[2]] <- 30 stopifnot(identical(vin,c(a1=11,a2=30,a3=20,a4=14,a5=15))) vrn[[3]] <- 20.2 vrn[[2]] <- 30.2 stopifnot(identical(vrn,c(a1=11.1,a2=30.2,a3=20.2,a4=14.1,a5=15.1))) vin["a1"] <- 10L stopifnot(identical(vin,c(a1=10,a2=30,a3=20,a4=14,a5=15))) vin[["a1"]] <- 12L stopifnot(identical(vin,c(a1=12,a2=30,a3=20,a4=14,a5=15))) # vin$a4 <- 50L # stopifnot(identical(vin,c(a1=12,a2=30,a3=20,a4=50,a5=15))) vi <- 11:15 vr <- (11:15) + 0.1 L <- list(11.1,12L,13.1,14L,TRUE) Ln <- list(e1=11.1,e2=12L,e3=13.1,e4=14L,e5=TRUE) vin <- vi names(vin) <- paste0("a",1:length(vin)) vrn <- vr names(vrn) <- paste0("a",1:length(vrn)) j <- 2 k <- 20L vi[[j+1]] <- k stopifnot(identical(vi,c(11L,12L,20L,14L,15L))) vi[[j]] <- k+10 stopifnot(identical(vi,c(11,30,20,14,15))) vr[[j+1]] <- k+0.2 vr[[j]] <- k+10.2 stopifnot(identical(vr,c(11.1,30.2,20.2,14.1,15.1))) vin[[j+1]] <- k stopifnot(identical(vin,c(a1=11L,a2=12L,a3=20L,a4=14L,a5=15L))) vin[[j]] <- k+10 stopifnot(identical(vin,c(a1=11,a2=30,a3=20,a4=14,a5=15))) vrn[[j+1]] <- k+0.2 vrn[[j]] <- k+10.2 stopifnot(identical(vrn,c(a1=11.1,a2=30.2,a3=20.2,a4=14.1,a5=15.1))) vin["a1"] <- k-10L stopifnot(identical(vin,c(a1=10,a2=30,a3=20,a4=14,a5=15))) vin[["a1"]] <- k-8L stopifnot(identical(vin,c(a1=12,a2=30,a3=20,a4=14,a5=15))) # vin$a4 <- k+30L # stopifnot(identical(vin,c(a1=12,a2=30,a3=20,a4=50,a5=15))) # Replacement of pairlist or language elements. L <- pairlist(1,2,3) L[[2]] <- 9 stopifnot(identical(L,pairlist(1,9,3))) L[[2]] <- NULL stopifnot(identical(L,pairlist(1,3))) L[[1]] <- NULL stopifnot(identical(L,pairlist(3))) L <- pairlist(a=1,b=2,c=3) L$b <- 9 stopifnot(identical(L,pairlist(a=1,b=9,c=3))) L$b <- NULL stopifnot(identical(L,pairlist(a=1,c=3))) L$a <- NULL stopifnot(identical(L,pairlist(c=3))) L <- parse(text="f(1,2)")[[1]] L[[2]] <- 3 stopifnot(identical(L,parse(text="f(3,2)")[[1]])) L[[1]] <- NULL stopifnot(identical(L,pairlist(3,2))) # Tests with ... M <- matrix(101:112,3,4) f <- function (w,...) stopifnot(identical(M[...],w)) f(104L,4) f(104L,1,2) f(105L,2,2) f(M[]) f <- function (w,x,...) stopifnot(identical(M[x,...],w)) f(104L,4) f(104L,1,2) f(105L,2,2) f <- function (w,...) stopifnot(identical(M[[...]],w)) f(104L,4) f(104L,1,2) f(105L,2,2) f <- function (w,x,...) stopifnot(identical(M[[x,...]],w)) f(104L,4) f(104L,1,2) f(105L,2,2) M2 <- M M2[2,3] <- 9L f <- function (M,W,...) { M[...] <- 9L; stopifnot(identical(M,W)) } f(M,M2,2,3) f <- function (M,W,x,...) { M[x,...] <- 9L; stopifnot(identical(M,W)) } f(M,M2,2,3) f <- function (M,W,...) { M[[...]] <- 9L; stopifnot(identical(M,W)) } f(M,M2,2,3) f <- function (M,W,x,...) { M[[x,...]] <- 9L; stopifnot(identical(M,W)) } f(M,M2,2,3) # Check that name after $ gets dispatched as a string. a <- list(p=3,q=4) class(a) <- "fred" `$.fred` <- function (x,n) { stopifnot(identical(n,substitute(n))); x[[n]] } `$<-.fred` <- function (x,n,value) { stopifnot(identical(n,substitute(n))); x[[n]] <- value; x } a$q <- a$q + 1 stopifnot(identical(a,structure(list(p=3,q=5),class="fred"))) cat("DONE\n") # Check how dimnames are converted to names when result is a vector. M <- matrix(3,2,2) rownames(M) <- c("a","b") stopifnot(identical(M[2,2],c(b=3))) colnames(M) <- c("x","y") stopifnot(identical(M[2,2],3)) stopifnot(identical(M[array(2),2],c(b=3))) stopifnot(identical(M[2,array(2)],c(y=3))) A <- M[1..1,_] stopifnot(identical(A[,2],3)) stopifnot(identical(A[_,2],c(a=3))) A <- M[_,1..1] stopifnot(identical(A[2,],3)) stopifnot(identical(A[2,_],c(x=3))) # Check array indexing. a <- array(1:120,c(2,3,4,5)) a[2,3,4,5] <- 9999L stopifnot(a[2,3,4,5]==9999L) stopifnot(a[length(a)]==9999L) a[2,3,4,5] <- 120L stopifnot(all(c(a)==1:120)) a <- array(1:120,c(2,3,4,5)) a[[2,3,4,5]] <- 9999L stopifnot(a[[2,3,4,5]]==9999L) stopifnot(a[length(a)]==9999L) a[[2,3,4,5]] <- 120L stopifnot(all(c(a)==1:120))
7,206
gpl-2.0
fa6e38459c8786fce2be14b040c45427b02d14fd
sfloresm/rstudio
src/cpp/r/R/Api.R
.rs.addApiFunction("versionInfo", function() { info <- list() info$citation <- .Call(getNativeSymbolInfo("rs_rstudioCitation", PACKAGE="")) info$mode <- .Call(getNativeSymbolInfo("rs_rstudioProgramMode", PACKAGE="")) info$version <- package_version( .Call(getNativeSymbolInfo("rs_rstudioVersion", PACKAGE="")) ) info }) .rs.addApiFunction("diagnosticsReport", function() { invisible(.Call(getNativeSymbolInfo("rs_sourceDiagnostics", PACKAGE=""))) }) .rs.addApiFunction("previewRd", function(rdFile) { if (!is.character(rdFile) || (length(rdFile) != 1)) stop("rdFile must be a single element character vector.") if (!file.exists(rdFile)) stop("The specified rdFile ' ", rdFile, "' does not exist.") invisible(.Call(getNativeSymbolInfo("rs_previewRd", PACKAGE=""), rdFile)) }) .rs.addApiFunction("viewer", function(url, height = NULL) { if (!is.character(url) || (length(url) != 1)) stop("url must be a single element character vector.") if (identical(height, "maximize")) height <- -1 if (!is.null(height) && (!is.numeric(height) || (length(height) != 1))) stop("height must be a single element numeric vector or 'maximize'.") invisible(.Call(getNativeSymbolInfo("rs_viewer", PACKAGE=""), url, height)) }) .rs.addApiFunction("sourceMarkers", function(name, markers, basePath = NULL, autoSelect = c("none", "first", "error")) { # validate name if (!is.character(name)) stop("name parameter is specified or invalid: ", name, call. = FALSE) # validate autoSelect autoSelect = match.arg(autoSelect) # normalize basePath if (!is.null(basePath)) basePath <- .rs.normalizePath(basePath, mustWork = TRUE) if (is.data.frame(markers)) { cols <- colnames(markers) if (!"type" %in% cols || !is.character(markers$type)) stop("markers type field is unspecified or invalid", call. = FALSE) if (!"file" %in% cols || !is.character(markers$file)) stop("markers file field is unspecified or invalid", call. = FALSE) if (!"line" %in% cols || !is.numeric(markers$line)) stop("markers line field is unspecified or invalid", call. = FALSE) if (!"column" %in% cols || !is.numeric(markers$column)) stop("markers column field is unspecified or invalid", call. = FALSE) if (!"message" %in% cols || !is.character(markers$message)) stop("markers message field is unspecified or invalid", call. = FALSE) # normalize paths cols$file <- .rs.normalizePath(cols$file, mustWork = TRUE) # check for html cols$messageHTML <- .rs.scalar(inherits(cols$message, "html")) } else if (is.list(markers)) { markers <- lapply(markers, function(marker) { markerTypes <- c("error", "warning", "box", "info", "style", "usage") if (is.null(marker$type) || (!marker$type %in% markerTypes)) stop("Invalid marker type (", marker$type, ")", call. = FALSE) if (!is.character(marker$file)) stop("Marker file is unspecified or invalid: ", marker$file, call. = FALSE) if (!is.numeric(marker$line)) stop("Marker line is unspecified or invalid", marker$line, call. = FALSE) if (!is.numeric(marker$column)) stop("Marker column is unspecified or invalid", marker$line, call. = FALSE) if (!is.character(marker$message)) stop("Marker message is unspecified or invalid: ", marker$message, call. = FALSE) marker$type <- .rs.scalar(marker$type) marker$file <- .rs.scalar(.rs.normalizePath(marker$file, mustWork = TRUE)) marker$line <- .rs.scalar(as.numeric(marker$line)) marker$column <- .rs.scalar(as.numeric(marker$column)) marker$message <- .rs.scalar(marker$message) marker$messageHTML <- .rs.scalar(inherits(marker$message, "html")) marker }) } else { stop("markers was not a data.frame or a list", call. = FALSE) } # validate basePath if (is.null(basePath)) basePath <- "" else if (!is.character(basePath)) stop("basePath parameter is not of type character", call. = FALSE) invisible(.Call("rs_sourceMarkers", name, markers, basePath, autoSelect)) })
4,554
agpl-3.0
05af94e985d7b8d247fa275d6d1e26b1070bd0a0
dalehurtt/smartphones
run_analysis.R
#### # This script does the following, not necessarily in the listed order. # # 1. Merges the training and the test data sets to create one data set. # 2. Extracts only the measurements on the mean and standard deviation for each measurement. # 3. Uses descriptive activity names to name the activities in the data set. # 4. Appropriately labels the data set with descriptive activity names. # 5. Creates a second, independent tidy data set with the average of each variable for each activity and each subject. ########## # VARIABLE DEFINITION # # This section lists the variables used in multiple functions, either getting or setting their values. It also # provides a convenient location to document each variable's use, for data exploration and debugging purposes. # # activity_data : Map of activity codes to named values (i.e. 1 = "WALKING", etc.) as a data frame # cols : Logical vector indicating the columns to "keep" (i.e. Subject, Activity, and those with mean() or std()) # full : Data frame containing the subject, x, and y (activity) data from both the test and training sets. # labels : Data frame with the labels to each of the 561 columns in the X data files. # test : Data frame containing the subject, x, and y (activity) data from the test set. # tidy : # train : Data frame containing the subject, x, and y (activity) data from the training set. ########## ########## START OF UTILITY FUNCTIONS ########## ########## # Reads the "activity_labels.txt" file into the data frame 'activity_data'. This variable will be used to map # activity codes to text values. ########## getActivity <- function () { activity_data <<- read.table ("UCI HAR Dataset/activity_labels.txt") } ########## # Calculates which of the columns in the test and training data to discard. It looks at the name of each column, # referencing the 'labels' variable, matching exactly on "Subject"or "Activity", or partially on ".mean..." or # ".std..." It sets the logical vector 'cols' indicating which columns are a match. Note that this function is aware # of the two columns added beyond those provided by the 'labels' data frame, and that the label names get transformed # when the data is read in by read.table (). (Specifically, "-mean()-" is transformed to ".mean..." and "-std()-" # to ".std...".) ########## getColumns <- function () { col_labels <- c ("Subject", "Activity", as.character (labelnames$V2)) cols <<- (col_labels == "Subject" | col_labels == "Activity" | grepl (".mean...", col_labels) | grepl (".std...", col_labels)) } ########## # Reads the "features.txt" into the data frame 'labels'. This variable will be used to add column names to the X data. ########## getLabels <- function () { labelnames <<- read.table ("UCI HAR Dataset/features.txt") } ########## # Reads the "X_test.txt", "subject_test.txt", and "y_test.txt" data files, combining them into a single data frame, # and then subsetting the data frame to include only those columns indicated by the 'cols' variable. The final data # is loaded into the variable 'test'. ########## getTest <- function () { # Read in the test data. test_data <- read.table ("UCI HAR Dataset/test/X_test.txt", col.names = as.character (labelnames$V2)) # Produces 2947 obs of 561 vars test_subjects <- read.table ("UCI HAR Dataset/test/subject_test.txt", col.names = "Subject") # Produces 2947 obs of 1 var test_activity <- read.table ("UCI HAR Dataset/test/y_test.txt", col.names = "Activity") # Produces 2947 obs of 1 var test_full <- cbind (test_subjects, test_activity, test_data) # Produces 2947 obs of 563 vars test_full$Activity <- factor (test_full$Activity, levels = activity_data$V1, labels = activity_data$V2) test <<- test_full [cols] } ########## # Reads the "X_train.txt", "subject_train.txt", and "y_train.txt" data files, combining them into a single data frame, # and then subsetting the data frame to include only those columns indicated by the 'cols' variable. The final data # is loaded into the variable 'train'. ########## getTrain <- function () { # Read in the training data. train_data <- read.table ("UCI HAR Dataset/train/X_train.txt", col.names = as.character (labelnames$V2)) # Produces 7352 obs of 561 vars train_subjects <- read.table ("UCI HAR Dataset/train/subject_train.txt", col.names = "Subject") # Produces 7352 obs of 1 var train_activity <- read.table ("UCI HAR Dataset/train/y_train.txt", col.names = "Activity") # Produces 7352 obs of 1 var train_full <- cbind (train_subjects, train_activity, train_data) # Produces 7352 obs of 563 vars train_full$Activity <- factor(train_full$Activity, levels = activity_data$V1, labels = activity_data$V2) train <<- train_full [cols] } ########## END OF UTILITY FUNCTIONS ########## ########## START OF MAIN CODE ########## # Do all of the preparatory file reading and data transformations. if (!exists ("activity_data")) getActivity () if (!exists ("labelnames")) getLabels () if (!exists ("cols")) getColumns () if (!exists ("test")) getTest () if (!exists ("train")) getTrain () # Merge the data sets into one. if (!exists ("full")) { full <- rbind (test, train) full <- full [order (full$Subject),] # Sort the data by Subject ID # Save some memory by flushing the previous data sets from memory. rm (test) rm (train) } # Now create a tidy data set with the mean of each variable for each activity and each subject. if (!exists ("tidy")) { library (plyr) # Group on Subject and Activity, calculating the mean of every other column in the set. tidy <- ddply (full, .(Subject, Activity), .fun = function (x) { colMeans (x [, -c(1:2)]) }) # Modify the data column names by appending "_mean". colnames (tidy)[-c(1:2)] <- paste (colnames (tidy)[-c(1:2)], "_mean", sep = "") } # Save the tidy data as a file. I use CSV for convenience. write.csv (tidy, "tidy_dataset.csv") ########## END OF MAIN CODE ##########
6,210
gpl-2.0
7b11ccb8c87c072cb8f2a3c943a2c2b9e99cfc0c
USGS-R/WQ-Review
inst/shiny/WQReviewGUI/ui_dataImport.R
###This contains all the ui elements for the data import tab. ###It is sourced from the ui-body tab, which is eventually sourced from the ui tab. ###These are contained in individual scripts just for organization sake. fluidPage( pageWithSidebar( headerPanel("User-specified import"), sidebarPanel( selectizeInput("STAIDS",label="Site number",choices=NULL,multiple=TRUE,options=list(create=TRUE)), fileInput("siteFile",label="Site number file",accept="csv"), selectizeInput("projectCd",label="Project code (optional)",choices=NULL,multiple=TRUE,options=list(create=TRUE)), selectizeInput("dl.parms",label="Parameter codes",choices=NULL,multiple=TRUE,options=list(create=TRUE)), selectInput("dl.parms.group","Parameter groups",choices=c("All" = "All", "physical" = "PHY", "cations" = "INM", "anions" = "INN", "nutrients" = "NUT", "microbiological" = "MBI", "biological" = "BIO", "metals" = "IMM", "nonmetals" = "IMN", "pesticides" = "TOX", "pcbs"="OPE", "other organics" = "OPC", "radio chemicals" = "RAD", "stable isotopes" = "XXX", "sediment" = "SED", "population/community" = "POP") ,selectize=FALSE,multiple=TRUE), fileInput("parmFile",label="pCode file",accept="csv"), dateInput(inputId = "begin.date",label="Start date",max=Sys.Date(),value=Sys.Date()-365*10), dateInput(inputId = "end.date",label="End date",max=Sys.Date(),value=Sys.Date()), textInput("DSN",label="Server name (DSN)",value=""), textInput("env.db",label="Environment DB Number",value="01"), textInput("qa.db",label="QA DB Number",value="02"), actionButton(inputId = "dataDownload",label="Get data"), icon = icon("dashboard") ), mainPanel( h3(textOutput("importWarning")), h3(textOutput("samplesRetrieved")), h3(textOutput("resultsRetrieved")), h3(textOutput("sampleModified")), h4(textOutput("recordModified")), h4(textOutput("recordModifiedDate")), h4(textOutput("recordModifiedName")), h3(textOutput("resultModified")), h4(textOutput("resultRecordModified")), h4(textOutput("resultModifiedPARM")), h4(textOutput("resultModifiedDate")), h4(textOutput("resultModifiedName")), verbatimTextOutput("shinyErrors"), verbatimTextOutput("errors") ) ) )
3,320
unlicense
faf45990c006969f610d559038b9df3738bfb05e
AndreyAkinshin/DynamicalSystemsPortraits
SprottChaoticFlow/Input/L/Params.R
kx.y <- 1 kx.z <- 3.9 ky.xx <- 0.9 ky.y <- -1 kz <- 1 kz.x <- -1
75
mit
9eaebf883176dd0a279bc73d661c134decc7688f
michaelrstatfsu/spherical_data_analysis
R_Spherical_Regression_Code/sd_von_Mises_Fisher.R
UNIFORMdirections<-function(m,n){ # generate n uniformly distributed m dim'l random directions # Using the logic: "directions of Normal distribution are uniform on sphere" V = matrix(0,m,n); nr = matrix(rnorm(m*n),m,n); #Normal random for (i in 1:n){ repeat { ni=t(nr[,i])%*%nr[,i] # length of ith vector # exclude too small values to avoid numerical discretization if (ni<1e-10){ # so repeat random generation nr[,i]=matrix(rnorm(m),m,1) } else { V[,i]=nr[,i]/sqrt(ni) break } } } return(V) } rvonMisesFisher<-function(n,m, kappa, mu) { # RANDVONMISESFISHERM Random number generation from von Mises Fisher # distribution. # X = randvonMisesFisherm(m, n, kappa, mu) with direction parameter mu # (m-dimensional column unit vector) # # Sungkyu Jung, Feb 3, 2010. # rewritten in R by Michae Rosenthal if (m < 2){ message('Message from randvonMisesFisherm.m: dimension m must be > 2'); message('Message from randvonMisesFisherm.m: Set m to be 2'); m = 2; } if (kappa < 0){ message('Message from randvonMisesFisherm.m: kappa must be >= 0'); message('Message from randvonMisesFisherm.m: Set kappa to be 0'); kappa = 0; } # # the following algorithm is following the modified Ulrich's algorithm # discussed by Andrew T.A. Wood in "SIMULATION OF THE VON MISES FISHER # DISTRIBUTION", COMMUN. STATIST 23(1), 1994. # step 0 : initialize b = (-2*kappa + sqrt(4*kappa^2 + (m-1)^2))/(m-1); x0 = (1-b)/(1+b); c = kappa*x0 + (m-1)*log(1-x0^2); # step 1 & step 2 nnow = n; #cnt = 0; ntrial = max(round(nnow*1.2),nnow+10) ; Z =matrix(rbeta(ntrial,(m-1)/2,(m-1)/2)) U = matrix(runif(ntrial)); W = (1-(1+b)*Z)/(1-(1-b)*Z); indicator = kappa*W + (m-1)*log(1-x0*W) - c >= log(U); if (sum(indicator) >= nnow) { w1 = matrix(W[indicator]); w = matrix(c(w1[1:nnow])); } else { w = matrix(c( W[indicator])) nnow = nnow-sum(indicator); repeat{ ntrial = max(round(nnow*1.2),nnow+10) ; Z =matrix(rbeta(ntrial,(m-1)/2,(m-1)/2)) U = matrix(runif(ntrial)); W = (1-(1+b)*Z)/(1-(1-b)*Z); indicator = kappa*W + (m-1)*log(1-x0*W) - c >= log(U); if (sum(indicator) >= nnow) { w1 = matrix(W[indicator]); w = matrix(c(w ,w1[1:nnow])); break; } else { w = matrix(c(w , W[indicator])) nnow = nnow-sum(indicator); } } } # step 3 V = UNIFORMdirections(m-1,n); X=rbind(repmat(sqrt(1-t(w)^2),m-1,1)*V ,t(w)) mu = mu / norm(mu); X = rotMat(matrix(c(0,0,1)),mu)%*%X; return(X) } sample_resultant_length<-function(z){dz=dim(z);return(sqrt(sum(rowMeans(z)^2)))} resultant_length<-function(d,kappa){ denom=besselI(kappa,d/2-1,1) if (denom != Inf) { A_p_kappa=besselI(kappa,d/2,1)/denom } else { A_p_kappa=1 } } kappa_tilde<-function(z) { # Sra, S. (2011). "A short note on parameter approximation for von Mises-Fisher distributions: And a fast implementation of I s (x)". Computational Statistics 27: 177–190. #Computes the MSE concentration given VMF data #KAPPA Newton-Rapson method maxitr=3; #Maximum number of iterations (algorithm usuual converges in as little as 2 iterations) kappatilde=matrix(0,maxitr,1); i=1; go=1; dz=dim(z); Rbar=sample_resultant_length(z); kappatilde[1]=(Rbar*(dz[1]-Rbar^2))/(1- Rbar^2); # Initialize Kappa while ((i<maxitr)&(go==1)) { i=i+1; A_p_kappa=resultant_length(dz[1],kappatilde[i-1]); kappa=kappatilde[i-1]; #previous kappa kappatilde[i]=kappa-( (A_p_kappa-Rbar)/(1-A_p_kappa^2- ((dz[1]-1)/kappa)*A_p_kappa)); #update kappa # go=abs(kappatilde(i-1)-kappatilde(i))>.001; # if you want a stopping criterion } return(kappatilde[i]) } mu_tilde<-function(z) { #estimates the MSE mean direction given VMF data xbar=matrix(rowMeans(z)) Rbar=sqrt(sum(xbar^2)) return(xbar/Rbar) } center<-function(mu,y){ dmu=dim(mu); arbitrary_direction= matrix(0,dmu[1],1); arbitrary_direction[dmu[1]]= 1; z=y #initialize and declare dimension of z to avoid dynamic memory allocation for (i in 1:dmu[2]) { z[,i]=rotMat(mu[,i],arbitrary_direction )%*%y[,i]; } } vMF_gof<-function(z,mu=NaN,kappa=NaN){ dz=dim(z) if (is.na(mu)) { xbar=matrix(rowMeans(z)) mu=xbar/sqrt(sum(xbar^2)) } if (is.na(kappa)) {kappa=kappa_tilde(z)} r=2*kappa*(1-t(z)%*%mu) hist(r,10,xlim=c(min(r),max(r))); t=seq(0,max(r),length.out=100); lines(t,n*dchisq(t,dz[1]-1)) if (dz[1]==3) { lrt=vmf_fb_lrt3(z) W=lrt[1] pvalue=lrt[2] W pvalue } } vmf_fb_lrt3 <- function(z) { dz=dim(z); if (dz[1]!=3) {message('p must equal 3') } else { xbar=matrix(rowMeans(z)) Rbar=sqrt(sum(xbar^2)); xbar0=xbar/Rbar; k=kappa_tilde(z); H=rotMat(xbar0,matrix(c(1,0,0))) Y=H%*%z; y=Y[2:dz[1],] l=svd(y%*%t(y)/n) T=(n*(k^3)*(l$d[1]-l$d[2])^2)/(4*(k-3*Rbar)); pvalue=pchisq(T,2,lower.tail=FALSE) return(data.frame('Test.Statistic'=T,'p.value'=pvalue)) } }
5,136
mit
faf45990c006969f610d559038b9df3738bfb05e
CyclicDynamicalSystems/DynamicalSystemsPortraits
SprottChaoticFlow/Input/L/Params.R
kx.y <- 1 kx.z <- 3.9 ky.xx <- 0.9 ky.y <- -1 kz <- 1 kz.x <- -1
75
mit
7f0780488ca3ebb243fa1e153080ed527e1a649c
youngstreetinitiative/lsp
Scripts/example of working with each file.R
#' @export bundle_sheets <- function() { files <- list.files("data-raw") %>% map( ~ list( name = str_replace(.x, ".xls", ""), file_path = glue("data-raw/{.x}") )) %>% set_names(map_chr(., "name")) master_ls <- files %>% map( ~ process_sheet(.x)) nms <- master_ls %>% map_chr("full_name") master_ls <- master_ls %>% set_names(nms) write_rds(master_ls, "data/master_ls.rds") }
425
mit
1dd6e8d540e8297a310eb078144a8326d4effeb0
michalkurka/h2o-3
h2o-r/tests/testdir_algos/gam/runit_PUBDEV_7366_gam_cv_gaussian.R
setwd(normalizePath(dirname(R.utils::commandArgs(asValues=TRUE)$"f"))) source("../../../scripts/h2o-r-test-setup.R") # make sure cross-validation runs properly in R test.model.gam.cross.validation <- function() { data <- h2o.importFile(path = locate("smalldata/glm_test/gaussian_20cols_10000Rows.csv")) data$C1 <- h2o.asfactor(data$C1) data$C2 <- h2o.asfactor(data$C2) data$C3 <- h2o.asfactor(data$C3) data$C4 <- h2o.asfactor(data$C4) data$C5 <- h2o.asfactor(data$C5) data$C6 <- h2o.asfactor(data$C6) data$C7 <- h2o.asfactor(data$C7) data$C8 <- h2o.asfactor(data$C8) data$C9 <- h2o.asfactor(data$C9) data$C10 <- h2o.asfactor(data$C10) splits = h2o.splitFrame(data, ratios=c(0.8), seed=12345) train = splits[[1]] valid = splits[[2]] gam_valid <- h2o.gam(y = "C21", x = c(1:20), gam_columns = c("C11"), training_frame = train, validation_frame = valid, family = "gaussian", nfolds = 5, fold_assignment="modulo") gam_no_valid <- h2o.gam(y = "C21", x = c(1:20), gam_columns = c("C11"), training_frame = train, family = "gaussian", nfolds = 5, fold_assignment="modulo") # coefficients from both models should be the same compareResult <- gam_valid@model$coefficients==gam_no_valid@model$coefficients expect_equal(sum(compareResult), length(gam_valid@model$coefficients)) } doTest("General Additive Model cross validation test with Gaussian family", test.model.gam.cross.validation)
1,488
apache-2.0
14bbee1acd7d81ae66c3081016247518557f6a91
cboettig/pdg_control
R/value_iteration.R
#' Identify the dynamic optimum using backward iteration (dynamic programming) #' @param SDP_Mat the stochastic transition matrix at each h value #' @param x_grid the discrete values allowed for the population size, x #' @param h_grid the discrete values of harvest levels to optimize over #' @param OptTime the stopping time #' @param xT the boundary condition population size at OptTime #' @param delta the discounting rate (1-delta) #' @param epsilon value iteration tolerance #' @param profit the profit function #' (i.e. enforces the boundary condition) #' @return list containing the matrices D and V. D is an x_grid by OptTime #' matrix with the indices of h_grid giving the optimal h at each value x #' as the columns, with a column for each time. #' V is a matrix of x_grid by x_grid, which is used to store the value #' function at each point along the grid at each point in time. #' The returned V gives the value matrix at the first (last) time. #' @export value_iteration <- function(SDP_Mat, x_grid, h_grid, OptTime=100, xT, profit, delta, epsilon = 1e-4){ ## Initialize space for the matrices gridsize <- length(x_grid) HL <- length(h_grid) D <- matrix(NA, nrow=gridsize, ncol=1) V <- rep(0,gridsize) # initialize BC, Vp <- rep(10, gridsize) # initialize previous value (not equal to current value) # loop through time #for(time in 1:OptTime){ time <- 1 while(max(abs(Vp - V)) >= (delta * epsilon / (2 - 2 * delta)) && time < OptTime){ # try all potential havest rates V1 <- sapply(1:HL, function(i){ # Transition matrix times V gives dist in next time SDP_Mat[[i]] %*% V + # then (add) harvested amount times discount profit(x_grid, h_grid[i]) * (1 - delta) }) # find havest, h that gives the maximum value out <- sapply(1:gridsize, function(j){ value <- max(V1[j,], na.rm = T) # each col is a diff h, max over these index <- which.max(V1[j,]) # store index so we can recover h's c(value, index) # returns both profit value & index of optimal h. }) # Sets V[t+1] = max_h V[t] at each possible state value, x Vp <- V V <- out[1,] # The new value-to-go D <- out[2,] # The index positions time <- time+1 } # check for convergence in V # Reed derives a const escapement policy saying to fish the pop down to # the largest population for which you shouldn't harvest: ReedThreshold <- x_grid[max(which(D == 1))] # Format the output list(D=D, V=V, S=ReedThreshold) }
2,634
cc0-1.0
1dd6e8d540e8297a310eb078144a8326d4effeb0
h2oai/h2o-3
h2o-r/tests/testdir_algos/gam/runit_PUBDEV_7366_gam_cv_gaussian.R
setwd(normalizePath(dirname(R.utils::commandArgs(asValues=TRUE)$"f"))) source("../../../scripts/h2o-r-test-setup.R") # make sure cross-validation runs properly in R test.model.gam.cross.validation <- function() { data <- h2o.importFile(path = locate("smalldata/glm_test/gaussian_20cols_10000Rows.csv")) data$C1 <- h2o.asfactor(data$C1) data$C2 <- h2o.asfactor(data$C2) data$C3 <- h2o.asfactor(data$C3) data$C4 <- h2o.asfactor(data$C4) data$C5 <- h2o.asfactor(data$C5) data$C6 <- h2o.asfactor(data$C6) data$C7 <- h2o.asfactor(data$C7) data$C8 <- h2o.asfactor(data$C8) data$C9 <- h2o.asfactor(data$C9) data$C10 <- h2o.asfactor(data$C10) splits = h2o.splitFrame(data, ratios=c(0.8), seed=12345) train = splits[[1]] valid = splits[[2]] gam_valid <- h2o.gam(y = "C21", x = c(1:20), gam_columns = c("C11"), training_frame = train, validation_frame = valid, family = "gaussian", nfolds = 5, fold_assignment="modulo") gam_no_valid <- h2o.gam(y = "C21", x = c(1:20), gam_columns = c("C11"), training_frame = train, family = "gaussian", nfolds = 5, fold_assignment="modulo") # coefficients from both models should be the same compareResult <- gam_valid@model$coefficients==gam_no_valid@model$coefficients expect_equal(sum(compareResult), length(gam_valid@model$coefficients)) } doTest("General Additive Model cross validation test with Gaussian family", test.model.gam.cross.validation)
1,488
apache-2.0
bd8941b60860b6b9fb9b33301cb16ad6434508f3
pchmieli/h2o-3
h2o-test-integ/tests/hdfs-bigdata/runit_RF_7MRows_4.4KCols_xlarge.R
#---------------------------------------------------------------------- # Purpose: This test exercises building 15MRows2KCols # #---------------------------------------------------------------------- test <- function() { hdfs_name_node <- Sys.getenv(c("NAME_NODE")) print(hdfs_name_node) hdfs_data_file = "/datasets/bigdata/7MRows_4400KCols.csv" #---------------------------------------------------------------------- # Parameters for the test. #---------------------------------------------------------------------- url <- sprintf("hdfs://%s%s", hdfs_name_node, hdfs_data_file) parse_time <- system.time(data.hex <- h2o.importFile(url)) print("Time it took to parse") print(parse_time) # Start modeling # Random Forest response="C1" #1:1000 imbalance predictors=c(4:ncol(data.hex)) rf_time <- system.time(mdl.rf <- h2o.randomForest(x=predictors, y=response, training_frame=data.hex, ntrees=10, max_depth=5)) mdl.rf print("Time it took to build RF") print(rf_time) } doTest("Test", test)
1,014
apache-2.0
9c3210c9d939290c3fb3c42589b142ca50fc9d89
danielturek/automated-blocking-examples
code/run_litters.R
source("autoBlock.R") load(file.path("data", "model_litters.RData")) dflitters <- autoBlock(code, constants, data, inits, 2e+05, runList)$summary save(dflitters, file = file.path("results", "results_litters.RData"))
217
mit
bd8941b60860b6b9fb9b33301cb16ad6434508f3
madmax983/h2o-3
h2o-test-integ/tests/hdfs-bigdata/runit_RF_7MRows_4.4KCols_xlarge.R
#---------------------------------------------------------------------- # Purpose: This test exercises building 15MRows2KCols # #---------------------------------------------------------------------- test <- function() { hdfs_name_node <- Sys.getenv(c("NAME_NODE")) print(hdfs_name_node) hdfs_data_file = "/datasets/bigdata/7MRows_4400KCols.csv" #---------------------------------------------------------------------- # Parameters for the test. #---------------------------------------------------------------------- url <- sprintf("hdfs://%s%s", hdfs_name_node, hdfs_data_file) parse_time <- system.time(data.hex <- h2o.importFile(url)) print("Time it took to parse") print(parse_time) # Start modeling # Random Forest response="C1" #1:1000 imbalance predictors=c(4:ncol(data.hex)) rf_time <- system.time(mdl.rf <- h2o.randomForest(x=predictors, y=response, training_frame=data.hex, ntrees=10, max_depth=5)) mdl.rf print("Time it took to build RF") print(rf_time) } doTest("Test", test)
1,014
apache-2.0
b14c86fc50285314d86a561db9a9e9740acb5222
RebeccaSalles/TSPred
R/data.frame.na.R
#' data.frames with filled NA's #' @keywords internal data.frame.na <- function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, stringsAsFactors = FALSE) { data.row.names <- if (check.rows && is.null(row.names)) function(current, new, i) { if (is.character(current)) new <- as.character(new) if (is.character(new)) current <- as.character(current) if (anyDuplicated(new)) return(current) if (is.null(current)) return(new) if (all(current == new) || all(current == "")) return(new) stop(gettextf("mismatch of row names in arguments of 'data.frame', item %d", i), domain = NA) } else function(current, new, i) { if (is.null(current)) { if (anyDuplicated(new)) { warning("some row.names duplicated: ", paste(which(duplicated(new)), collapse = ","), " --> row.names NOT used") current } else new } else current } object <- as.list(substitute(list(...)))[-1L] mrn <- is.null(row.names) x <- list(...) n <- length(x) if (n < 1L) { if (!mrn) { if (is.object(row.names) || !is.integer(row.names)) row.names <- as.character(row.names) if (any(is.na(row.names))) stop("row names contain missing values") if (anyDuplicated(row.names)) stop("duplicate row.names: ", paste(unique(row.names[duplicated(row.names)]), collapse = ", ")) } else row.names <- integer(0L) return(structure(list(), names = character(0L), row.names = row.names, class = "data.frame")) } vnames <- names(x) if (length(vnames) != n) vnames <- character(n) no.vn <- !nzchar(vnames) vlist <- vnames <- as.list(vnames) nrows <- ncols <- integer(n) for (i in seq_len(n)) { xi <- if (is.character(x[[i]]) || is.list(x[[i]])) as.data.frame(x[[i]], optional = TRUE, stringsAsFactors = stringsAsFactors) else as.data.frame(x[[i]], optional = TRUE) nrows[i] <- .row_names_info(xi) ncols[i] <- length(xi) namesi <- names(xi) if (ncols[i] > 1L) { if (length(namesi) == 0L) namesi <- seq_len(ncols[i]) if (no.vn[i]) vnames[[i]] <- namesi else vnames[[i]] <- paste(vnames[[i]], namesi, sep = ".") } else { if (length(namesi)) vnames[[i]] <- namesi else if (no.vn[[i]]) { tmpname <- deparse(object[[i]])[1L] if (substr(tmpname, 1L, 2L) == "I(") { ntmpn <- nchar(tmpname, "c") if (substr(tmpname, ntmpn, ntmpn) == ")") tmpname <- substr(tmpname, 3L, ntmpn - 1L) } vnames[[i]] <- tmpname } } if (missing(row.names) && nrows[i] > 0L) { rowsi <- attr(xi, "row.names") nc <- nchar(rowsi, allowNA = FALSE) nc <- nc[!is.na(nc)] if (length(nc) && any(nc)) row.names <- data.row.names(row.names, rowsi, i) } nrows[i] <- abs(nrows[i]) vlist[[i]] <- xi } nr <- max(nrows) for (i in seq_len(n)[nrows < nr]) { xi <- vlist[[i]] if (nrows[i] > 0L) { xi <- unclass(xi) fixed <- TRUE for (j in seq_along(xi)) { ### added NA fill to max length/nrow xi1 <- xi[[j]] if (is.vector(xi1) || is.factor(xi1)) xi[[j]] <- c(xi1, rep(NA, nr - nrows[i])) else if (is.character(xi1) && class(xi1) == "AsIs") xi[[j]] <- structure(c(xi1, rep(NA, nr - nrows[i])), class = class(xi1)) else if (inherits(xi1, "Date") || inherits(xi1, "POSIXct")) xi[[j]] <- c(xi1, rep(NA, nr - nrows[i])) else { fixed <- FALSE break } } if (fixed) { vlist[[i]] <- xi next } } stop("arguments imply differing number of rows: ", paste(unique(nrows), collapse = ", ")) } value <- unlist(vlist, recursive = FALSE, use.names = FALSE) vnames <- unlist(vnames[ncols > 0L]) noname <- !nzchar(vnames) if (any(noname)) vnames[noname] <- paste("Var", seq_along(vnames), sep = ".")[noname] if (check.names) vnames <- make.names(vnames, unique = TRUE) names(value) <- vnames if (!mrn) { if (length(row.names) == 1L && nr != 1L) { if (is.character(row.names)) row.names <- match(row.names, vnames, 0L) if (length(row.names) != 1L || row.names < 1L || row.names > length(vnames)) stop("row.names should specify one of the variables") i <- row.names row.names <- value[[i]] value <- value[-i] } else if (!is.null(row.names) && length(row.names) != nr) stop("row names supplied are of the wrong length") } else if (!is.null(row.names) && length(row.names) != nr) { warning("row names were found from a short variable and have been discarded") row.names <- NULL } if (is.null(row.names)) row.names <- .set_row_names(nr) else { if (is.object(row.names) || !is.integer(row.names)) row.names <- as.character(row.names) if (any(is.na(row.names))) stop("row names contain missing values") if (anyDuplicated(row.names)) stop("duplicate row.names: ", paste(unique(row.names[duplicated(row.names)]), collapse = ", ")) } attr(value, "row.names") <- row.names attr(value, "class") <- "data.frame" value }
6,176
gpl-3.0
cf87d58d1d55129253ef8455b4c89c6cea5d9f64
wStockhausen/rTCSAM2015
R/writeModelResultsToCSV.PopProcesses.R
#' #'@title Write population processes from model results from TCSAM2015 and rsimTCSAM model runs to a csv file #' #'@description Function to write population processes from model results from TCSAM2015 and rsimTCSAM model runs to a csv file. #' #'@param tcsams - single TCSAM2015 model report object, or named list of such #'@param rsims - single rsimTCSAM results object, or named list of such #'@param csv - base name for csv files to write to #'@param verbose - flag (T/F) to print debug info #' #'@return nothing #' #'@details Extracts natural mortality, mean growth increments, molt-to-maturity, and recruitment #'size distribution information. #' #'@export #' writeModelResultsToCSV.PopProcesses<-function(tcsams=NULL, rsims=NULL, csv="ModelResults.PopProcesses", verbose=FALSE){ if (inherits(tcsams,'tcsam2015.rep')){ tcsams<-list(tcsam=tcsams);#wrap in list } if (class(rsims)=='rsimTCSAM'){ rsims<-list(rsim=rsims);#wrap in list } #natural mortality mdfr<-getMDFR.NatMort(tcsams,rsims); write.csv(mdfr,file=paste0(csv,".NatMort.csv"),row.names=TRUE); #mean growth increments mdfr<-getMDFR.MeanGrowthIncrements(tcsams,rsims); write.csv(mdfr,file=paste0(csv,".MeanGrowthIncrements.csv"),row.names=TRUE); #molt-to-maturity write.csv(mdfr,file=paste0(csv,".prM2M.csv"),row.names=TRUE); #recruitment size distribution mdfr<-getMDFR.RecSizeDistribution(tcsams,rsims,verbose); write.csv(mdfr,file=paste0(csv,".RecSizeDist.csv"),row.names=TRUE); #recruitment sex ratio mdfr<-getMDFR.SexRatio(tcsams,rsims,verbose); write.csv(mdfr,file=paste0(csv,".SexRatio.csv"),row.names=TRUE); #initial size distribution if (verbose) cat("Plotting initial size distribution\n"); path<-'mr/iN_xmsz'; csvp<-paste0(csv,".InitialNatZ.csv"); extractModelResults.RepObjs(tcsams,rsims,path, label.value="Abundance (millions)", cast.formula="x+m+s+z",csv=csvp); if (verbose) cat("Done!\n"); }
2,201
mit
c0b20738b59aa61d84a438b81bc113d4f6aaba28
wch/r-source
src/library/datasets/data/PlantGrowth.R
PlantGrowth <- data.frame(weight = c(4.17, 5.58, 5.18, 6.11, 4.5, 4.61, 5.17, 4.53, 5.33, 5.14, 4.81, 4.17, 4.41, 3.59, 5.87, 3.83, 6.03, 4.89, 4.32, 4.69, 6.31, 5.12, 5.54, 5.5, 5.37, 5.29, 4.92, 6.15, 5.8, 5.26), group = factor(c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3), levels=1:3, labels = c("ctrl", "trt1", "trt2")))
372
gpl-2.0
052d5ab5e401de06571b2f2b2aa4689e3bc56126
vbarrera/thesis
Genomic_Evaluation_of_individual_CpG_Methylation/R/figure23_ADS_ADSC.R
################ ### Figure 23 ### ################ ADSCgiFolder<-paste(baseDIR,"results/20120802/",sep="") ADS_AdiposeCgiFolder<-paste(baseDIR,"results/20120802/",sep="") datos_ADS<-read.table(paste(ADSCgiFolder,"hg18_reads_ads_CGi_status_sd.txt",sep="")) datos_ADS_Adipose<-read.table(paste(ADS_AdiposeCgiFolder,"hg18_reads_ads_adipose_CGi_status_sd.txt",sep="")) colnames(datos_ADS)<-c("id","nCGt","chr","chrStart","chrEnd","CGinf","methCoef","SD","nReads") colnames(datos_ADS_Adipose)<-c("id","nCGt","chr","chrStart","chrEnd","CGinf","methCoef","SD","nReads") ################################# ## With Informativeness filter ## ################################# validDatosADS<-subset(datos_ADS,datos_ADS$methCoef != -1.00 & (datos_ADS$CGinf/2)/datos_ADS$nCGt >=0.25) validDatosADS_Adipose<-subset(datos_ADS_Adipose,datos_ADS_Adipose$methCoef != -1.00 & (datos_ADS_Adipose$CGinf/2)/datos_ADS_Adipose$nCGt >=0.25) validDatosADS_unmeth<-subset(validDatosADS, validDatosADS$methCoef<=0.25) validDatosADS_halfmeth<-subset(validDatosADS, validDatosADS$methCoef>0.25 & validDatosADS$methCoef<0.75) validDatosADS_meth<-subset(validDatosADS, validDatosADS$methCoef>=0.75) validDatosADS_Adipose_unmeth<-subset(validDatosADS_Adipose, validDatosADS_Adipose$methCoef<=0.25) validDatosADS_Adipose_halfmeth<-subset(validDatosADS_Adipose, validDatosADS_Adipose$methCoef>0.25 & validDatosADS_Adipose$methCoef<0.75) validDatosADS_Adipose_meth<-subset(validDatosADS_Adipose, validDatosADS_Adipose$methCoef>=0.75) #Plotting #ADS if (numbered=='TRUE'){ png(paste(resultsDIR,"figure23ADSFilteredBNNumbered.png",sep=""),height=15,width=15,units="cm",res=300) }else{ png(paste(resultsDIR,"figure23ADSFilteredBN.png",sep=""),height=15,width=15,units="cm",res=300) } def.par <- par(no.readonly = TRUE) par(lwd=3) par(cex.axis=1.2) xhist <- hist(validDatosADS$methCoef, breaks=seq(0,1,0.1), plot=FALSE) yhist <- hist(validDatosADS$SD, breaks=seq(0,1,0.1), plot=FALSE) top <- max(c(xhist$counts, yhist$counts)) xrange <- c(0,1) yrange <- c(0,1) nf <- layout(matrix(c(2,0,1,3),2,2,byrow=TRUE), c(3,1), c(1,3), TRUE) par(mar=c(5,5,1,1)) plot(validDatosADS$methCoef,validDatosADS$SD, xlab="",ylab="",pch=20,xlim=c(0,1),col=rgb(0,0,0,0.2),type="n",ylim=c(0,0.6)) ## Plot the points with some noise (jitter) points(jitter(validDatosADS_unmeth$methCoef),jitter(validDatosADS_unmeth$SD,factor=5),pch=16,col=rgb(0,0,0,0.2),cex=0.8) points(jitter(validDatosADS_halfmeth$methCoef),jitter(validDatosADS_halfmeth$SD,factor=5),pch=16,col=rgb(0,0,0,0.2),cex=0.8) points(jitter(validDatosADS_meth$methCoef),jitter(validDatosADS_meth$SD,factor=5),pch=16,col=rgb(0,0,0,0.2),cex=0.8) # Plot the points without noise # points(validDatosADS_unmeth$methCoef,validDatosADS_unmeth$SD,pch=16,col=rgb(0,1,0,0.2),cex=1) # points(validDatosADS_halfmeth$methCoef,validDatosADS_halfmeth$SD,pch=16,col=rgb(0,0,1,0.2),cex=1) # points(validDatosADS_meth$methCoef,validDatosADS_meth$SD,pch=16,col=rgb(1,0,0,0.2),cex=1) if (numbered=='TRUE'){ # Adding the number of points text(0.1,0.4,dim(validDatosADS_unmeth)[1],cex=1.2,col="red") text(0.5,0.4,dim(validDatosADS_halfmeth)[1],cex=1.2,col="red") text(0.9,0.4,dim(validDatosADS_meth)[1],cex=1.2,col="red") }else{} abline(v=0.25,lty=2,lwd=1.5) abline(v=0.75,lty=2,lwd=1.5) par(mar=c(0,5,1,1)) par(lwd=1) barplot(xhist$counts, axes=FALSE, ylim=c(0, top), space=0, ) par(mar=c(5,0,1,1)) barplot(yhist$counts, axes=FALSE, xlim=c(0, top), space=0, horiz=TRUE) par(def.par) dev.off() #ADS_Adipose if (numbered=='TRUE'){ png(paste(resultsDIR,"figure23ADS_AdiposeFilteredBNNumbered.png",sep=""),height=15,width=15,units="cm",res=300) }else{ png(paste(resultsDIR,"figure23ADS_AdiposeFilteredBN.png",sep=""),height=15,width=15,units="cm",res=300) } def.par <- par(no.readonly = TRUE) par(lwd=3) par(cex.axis=1.2) xhist <- hist(validDatosADS_Adipose$methCoef, breaks=seq(0,1,0.1), plot=FALSE) yhist <- hist(validDatosADS_Adipose$SD, breaks=seq(0,1,0.1), plot=FALSE) top <- max(c(xhist$counts, yhist$counts)) xrange <- c(0,1) yrange <- c(0,1) nf <- layout(matrix(c(2,0,1,3),2,2,byrow=TRUE), c(3,1), c(1,3), TRUE) par(mar=c(5,5,1,1)) plot(validDatosADS_Adipose$methCoef,validDatosADS_Adipose$SD, xlab="", ylab="",pch=20,xlim=c(0,1),col=rgb(0,0,0,0.2),main="",type="n",ylim=c(0,0.6)) ## Plot the points with some noise (jitter) points(jitter(validDatosADS_Adipose_unmeth$methCoef),jitter(validDatosADS_Adipose_unmeth$SD,factor=5),pch=16,col=rgb(0,0,0,0.2),cex=0.8) points(jitter(validDatosADS_Adipose_halfmeth$methCoef),jitter(validDatosADS_Adipose_halfmeth$SD,factor=5),pch=16,col=rgb(0,0,0,0.2),cex=0.8) points(jitter(validDatosADS_Adipose_meth$methCoef),jitter(validDatosADS_Adipose_meth$SD,factor=5),pch=16,col=rgb(0,0,0,0.2),cex=0.8) # Plot the points without noise # points(validDatosADS_Adipose_unmeth$methCoef,validDatosADS_Adipose_unmeth$SD,pch=16,col=rgb(0,1,0,0.2),cex=1) # points(validDatosADS_Adipose_halfmeth$methCoef,validDatosADS_Adipose_halfmeth$SD,pch=16,col=rgb(0,0,1,0.2),cex=1) # points(validDatosADS_Adipose_meth$methCoef,validDatosADS_Adipose_meth$SD,pch=16,col=rgb(1,0,0,0.2),cex=1) if (numbered=='TRUE'){ # Adding the number of points text(0.1,0.4,dim(validDatosADS_Adipose_unmeth)[1],cex=1.2,col="red") text(0.5,0.4,dim(validDatosADS_Adipose_halfmeth)[1],cex=1.2,col="red") text(0.9,0.4,dim(validDatosADS_Adipose_meth)[1],cex=1.2,col="red") }else{} abline(v=0.25,lty=2,lwd=1.5) abline(v=0.75,lty=2,lwd=1.5) par(mar=c(0,5,1,1)) par(lwd=1) barplot(xhist$counts, axes=FALSE, ylim=c(0, top), space=0, ) par(mar=c(5,0,1,1)) barplot(yhist$counts, axes=FALSE, xlim=c(0, top), space=0, horiz=TRUE) par(def.par) dev.off() #################################### ## Without Informativeness filter ## #################################### validDatosADS<-subset(datos_ADS,datos_ADS$methCoef != -1.00) validDatosADS_Adipose<-subset(datos_ADS_Adipose,datos_ADS_Adipose$methCoef != -1.00) validDatosADS_unmeth<-subset(validDatosADS, validDatosADS$methCoef<=0.25) validDatosADS_halfmeth<-subset(validDatosADS, validDatosADS$methCoef>0.25 & validDatosADS$methCoef<0.75) validDatosADS_meth<-subset(validDatosADS, validDatosADS$methCoef>=0.75) validDatosADS_Adipose_unmeth<-subset(validDatosADS_Adipose, validDatosADS_Adipose$methCoef<=0.25) validDatosADS_Adipose_halfmeth<-subset(validDatosADS_Adipose, validDatosADS_Adipose$methCoef>0.25 & validDatosADS_Adipose$methCoef<0.75) validDatosADS_Adipose_meth<-subset(validDatosADS_Adipose, validDatosADS_Adipose$methCoef>=0.75) #Plotting #ADS if (numbered=='TRUE'){ png(paste(resultsDIR,"figure23ADSAllBNNumbered.png",sep=""),height=15,width=15,units="cm",res=300) }else{ png(paste(resultsDIR,"figure23ADSAllBN.png",sep=""),height=15,width=15,units="cm",res=300) } def.par <- par(no.readonly = TRUE) par(lwd=3) par(cex.axis=1.2) xhist <- hist(validDatosADS$methCoef, breaks=seq(0,1,0.1), plot=FALSE) yhist <- hist(validDatosADS$SD, breaks=seq(0,1,0.1), plot=FALSE) top <- max(c(xhist$counts, yhist$counts)) xrange <- c(0,1) yrange <- c(0,1) nf <- layout(matrix(c(2,0,1,3),2,2,byrow=TRUE), c(3,1), c(1,3), TRUE) par(mar=c(5,5,1,1)) plot(validDatosADS$methCoef,validDatosADS$SD, xlab="",ylab="",pch=20,xlim=c(0,1),col=rgb(0,0,0,0.2),type="n",ylim=c(0,0.6)) ## Plot the points with some noise (jitter) points(jitter(validDatosADS_unmeth$methCoef),jitter(validDatosADS_unmeth$SD,factor=5),pch=16,col=rgb(0,0,0,0.2),cex=0.8) points(jitter(validDatosADS_halfmeth$methCoef),jitter(validDatosADS_halfmeth$SD,factor=5),pch=16,col=rgb(0,0,0,0.2),cex=0.8) points(jitter(validDatosADS_meth$methCoef),jitter(validDatosADS_meth$SD,factor=5),pch=16,col=rgb(0,0,0,0.2),cex=0.8) # Plot the points without noise # points(validDatosADS_unmeth$methCoef,validDatosADS_unmeth$SD,pch=16,col=rgb(0,1,0,0.2),cex=1) # points(validDatosADS_halfmeth$methCoef,validDatosADS_halfmeth$SD,pch=16,col=rgb(0,0,1,0.2),cex=1) # points(validDatosADS_meth$methCoef,validDatosADS_meth$SD,pch=16,col=rgb(1,0,0,0.2),cex=1) if(numbered=='TRUE'){ # Adding the number of points text(0.1,0.4,dim(validDatosADS_unmeth)[1],cex=1.2,col="red") text(0.5,0.4,dim(validDatosADS_halfmeth)[1],cex=1.2,col="red") text(0.9,0.4,dim(validDatosADS_meth)[1],cex=1.2,col="red") }else{} abline(v=0.25,lty=2,lwd=1.5) abline(v=0.75,lty=2,lwd=1.5) par(mar=c(0,5,1,1)) par(lwd=1) barplot(xhist$counts, axes=FALSE, ylim=c(0, top), space=0, ) par(mar=c(5,0,1,1)) barplot(yhist$counts, axes=FALSE, xlim=c(0, top), space=0, horiz=TRUE) par(def.par) dev.off() #ADS_Adipose if(numbered=='TRUE'){ png(paste(resultsDIR,"figure23ADS_AdiposeAllBNNumbered.png",sep=""),height=15,width=15,units="cm",res=300) }else{ png(paste(resultsDIR,"figure23ADS_AdiposeAllBN.png",sep=""),height=15,width=15,units="cm",res=300) } def.par <- par(no.readonly = TRUE) par(lwd=3) par(cex.axis=1.2) xhist <- hist(validDatosADS_Adipose$methCoef, breaks=seq(0,1,0.1), plot=FALSE) yhist <- hist(validDatosADS_Adipose$SD, breaks=seq(0,1,0.1), plot=FALSE) top <- max(c(xhist$counts, yhist$counts)) xrange <- c(0,1) yrange <- c(0,1) nf <- layout(matrix(c(2,0,1,3),2,2,byrow=TRUE), c(3,1), c(1,3), TRUE) par(mar=c(5,5,1,1)) plot(validDatosADS_Adipose$methCoef,validDatosADS_Adipose$SD, xlab="",ylab="",pch=20,xlim=c(0,1),col=rgb(0,0,0,0.2),type="n",ylim=c(0,0.6)) # Plot the points with some noise (jitter) points(jitter(validDatosADS_Adipose_unmeth$methCoef),jitter(validDatosADS_Adipose_unmeth$SD,factor=5),pch=16,col=rgb(0,0,0,0.2),cex=0.8) points(jitter(validDatosADS_Adipose_halfmeth$methCoef),jitter(validDatosADS_Adipose_halfmeth$SD,factor=5),pch=16,col=rgb(0,0,0,0.2),cex=0.8) points(jitter(validDatosADS_Adipose_meth$methCoef),jitter(validDatosADS_Adipose_meth$SD,factor=5),pch=16,col=rgb(0,0,0,0.2),cex=0.8) # Plot the points without noise # points(validDatosADS_Adipose_unmeth$methCoef,validDatosADS_Adipose_unmeth$SD,pch=16,col=rgb(0,1,0,0.2),cex=1) # points(validDatosADS_Adipose_halfmeth$methCoef,validDatosADS_Adipose_halfmeth$SD,pch=16,col=rgb(0,0,1,0.2),cex=1) # points(validDatosADS_Adipose_meth$methCoef,validDatosADS_Adipose_meth$SD,pch=16,col=rgb(1,0,0,0.2),cex=1) if(numbered=='TRUE'){ # Adding the number of points text(0.1,0.4,dim(validDatosADS_Adipose_unmeth)[1],cex=1.2,col="red") text(0.5,0.4,dim(validDatosADS_Adipose_halfmeth)[1],cex=1.2,col="red") text(0.9,0.4,dim(validDatosADS_Adipose_meth)[1],cex=1.2,col="red") }else{} abline(v=0.25,lty=2,lwd=1.5) abline(v=0.75,lty=2,lwd=1.5) par(mar=c(0,5,1,1)) par(lwd=1) barplot(xhist$counts, axes=FALSE, ylim=c(0, top), space=0, ) par(mar=c(5,0,1,1)) barplot(yhist$counts, axes=FALSE, xlim=c(0, top), space=0, horiz=TRUE) par(def.par) dev.off()
11,332
gpl-2.0
c03ee59ae41431e2ffa3be41e8bc64c1ce15e97a
SantanderMetGroup/transformeR
R/intersectMembers.R
## matchMembers.R Subset two or more grids to the common members ## ## Copyright (C) 2017 Santander Meteorology Group (http://www.meteo.unican.es) ## ## This program is free software: you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## (at your option) any later version. ## ## This program is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with this program. If not, see <http://www.gnu.org/licenses/>. #' @title Subset two or more grids to the common members. #' @description Subset two or more grids to the common members. #' @param ... Grids. #' @return input grids are updated in the global environment. #' @author M. Iturbide #' @export intersectMembers <- function(...){ grids <- list(...) %>% lapply(redim) grids <- list(hist.y, fut.ens) %>% lapply(redim) grids.members <- lapply(grids, "[[", "Members") members <- do.call("intersect", grids.members) if (is.character(members) & length(members) > 0) { ind <- lapply(grids.members, function(m){ lapply(members, function(i) grep(i, m)) %>% unlist }) out <- lapply(1:length(grids), function(x) subsetGrid(grids[[x]], members = ind[[x]])) nmes <- as.character(as.list(substitute(list(...)))[-1L]) if (length(nmes) < length(grids)) nmes <- paste0(nmes, 1:length(grids)) names(out) <- nmes lapply(1:length(out), function(en) .GlobalEnv[[names(out)[en]]] <- out[[en]]) } else { stop("Check input grids. Ensure the member dimension exists.") } } #end
1,898
gpl-3.0
ec5cdeb9d1aacddad5e2adf98870f4b0bc20f37e
burrm/lolcat
R/mean.t.test.onesample.simple.R
#' One Sample t Test for Mean #' #' Calculate one sample t test for mean. #' #' @param x Vector - sample values to be used for mean calculation. #' @param sample.mean Scalar - sample mean to be tested. #' @param sample.variance Scalar - sample variance. #' @param sample.size Scalar - sample size. #' @param null.hypothesis.mean Scalar - null hypothesis mean value, sample.mean is tested against this value. #' @param alternative The alternative hypothesis to use for the test computation. #' @param conf.level The confidence level for this test, between 0 and 1. #' @param finite.population.N Scalar - the population size if finite population adjustment needs to be made. #' @param na.rm Logical - remove NA values prior to running calculation. #' #' @aliases mean.t.test.onesample #' #' @return The results of the statistical test. mean.t.test.onesample.simple<-function( sample.mean ,sample.variance ,sample.size ,null.hypothesis.mean = 0 ,alternative = c("two.sided","less","greater") ,conf.level = 0.95 ,finite.population.N = NA ) { validate.htest.alternative(alternative = alternative) se.est <- sqrt(sample.variance/sample.size) if (!is.na(finite.population.N)) { se.est <- se.est * sqrt((finite.population.N-sample.size)/(finite.population.N-1)) } t <- (sample.mean-null.hypothesis.mean)/se.est df <- sample.size-1 cv <- qt(conf.level+(1-conf.level)/2, df= df) mean.upper <- sample.mean + cv*se.est mean.lower <- sample.mean - cv*se.est var.test.out <- variance.test.onesample.simple(sample.variance = sample.variance ,sample.size = sample.size ,null.hypothesis.variance = 1 ,conf.level = conf.level) var.lower <- var.test.out$conf.int[1] var.upper <- var.test.out$conf.int[2] sd.lower<-sqrt(var.lower) sd.upper<-sqrt(var.upper) p.value <- if (alternative[1] == "two.sided") { tmp<-pt(t, df) min(tmp,1-tmp)*2 } else if (alternative[1] == "greater") { pt(t, df, lower.tail = FALSE) } else if (alternative[1] == "less") { pt(t, df, lower.tail = TRUE) } else { NA } pow <- power.mean.t.onesample(sample.size = sample.size ,effect.size = sample.mean - null.hypothesis.mean ,variance.est = sample.variance ,alpha = 1-conf.level ,alternative = alternative ,details = F) retval<-list(data.name = "sample mean, sample size, and estimated variance", statistic = t, estimate = c(sample.mean = sample.mean ,se.est = se.est ,df = df ,var.lowerci = var.lower ,var = sample.variance ,var.upperci = var.upper ,sd.lowerci = sd.lower ,sd = sqrt(sample.variance) ,sd.upperci = sd.upper ,power = pow), parameter = null.hypothesis.mean, p.value = p.value, null.value = null.hypothesis.mean, alternative = alternative[1], method = "One-Sample t Test For Means", conf.int = c(mean.lower, mean.upper) ) #names(retval$estimate) <- c("sample mean", "df") names(retval$statistic) <- "t statistic" names(retval$null.value) <- "mean" names(retval$parameter) <- "null hypothesis mean" attr(retval$conf.int, "conf.level") <- conf.level class(retval)<-"htest" retval } #require(lolcat) #t.test.onesample.simple(sample.mean = .5,sample.variance = 1,sample.size = 25)
3,925
mit
5c88f1917a194d102c784f708bb689950def7e38
cran/metasens
R/print.summary.copas.R
#' Print detailed results of Copas selection model #' #' @description #' Print method for objects of class \code{summary.copas}. #' #' #' This function prints the following information: #' #' Range of gamma0 values used (see \code{help(copas)}); #' #' Range of gamma1 values used (see \code{help(copas)}); #' #' Largest SE of all studies in meta-analysis; #' #' Range of probability publishing trial with largest SE; #' #' The next table gives details relating to the summary of the contour plot. #' Specifically, it gives details from fitting a straight line to each #' treatment-contour in the contour plot. Column 1 (headed level) shows the #' treatment-contours; column 2 (nobs) shows the number of observations used by #' the contour plot command within the \code{copas} function to plot this #' contour line; column 3 (adj.r.square) shows the adjusted r-square from #' fitting a straight line to this contour; columns 4 & 5 show the slope and #' its standard error from fitting a straight line to this contour. #' #' Next, the printout of \code{summary.copas} is shown. #' #' @aliases print.summary.copas #' #' @param x An object of class \code{summary.copas}. #' @param backtransf A logical indicating whether results should be #' back transformed in printouts and plots. If \code{backtransf = #' TRUE} (default), results are printed as odds ratios rather than #' log odds ratio, for example. #' @param legend A logical indicating whether a legend should be #' printed. #' @param digits Minimal number of significant digits, see #' \code{print.default}. #' @param digits.se Minimal number of significant digits for standard #' deviations and standard errors, see \code{print.default}. #' @param ... Additional arguments (ignored). #' #' @author James Carpenter \email{James.Carpenter@@lshtm.ac.uk}, Guido #' Schwarzer \email{sc@@imbi.uni-freiburg.de} #' #' @seealso \code{\link{copas}}, \code{\link{plot.copas}}, #' \code{\link{summary.copas}} #' #' @keywords print #' #' @examples #' data(Fleiss1993bin, package = "meta") #' #' # Perform meta analysis, effect measure is odds ratio (OR) #' # #' m1 <- metabin(d.asp, n.asp, d.plac, n.plac, data=Fleiss1993bin, sm="OR") #' #' # Print summary of Copas analysis #' # #' summary(copas(m1), level = 0.95) #' #' @method print summary.copas #' @export #' @export print.summary.copas print.summary.copas <- function(x, backtransf = x$backtransf, legend = TRUE, digits = gs("digits"), digits.se = gs("digits.se"), ...) { chkclass(x, "summary.copas") cl <- class(x)[1] addargs <- names(list(...)) ## fun <- "print.summarycopas" ## warnarg("logscale", addargs, fun, otherarg = "backtransf") ## if (is.null(backtransf)) if (!is.null(list(...)[["logscale"]])) backtransf <- !list(...)[["logscale"]] else backtransf <- TRUE else chklogical(backtransf) ## chklogical(legend) chknumeric(digits, min = 0, length = 1) chknumeric(digits.se, min = 0, length = 1) crtitle(x) ## print.copas(x$x, header = FALSE, legend = FALSE, digits = digits, backtransf = backtransf, ...) ## res <- cbind(c("range of gamma0: ", "range of gamma1: "), format(c(round(x$x$gamma0.range[1], digits), round(x$x$gamma1.range[1], digits))), ## format(c(round(x$x$gamma0.range[2], digits), round(x$x$gamma1.range[2], digits)))) ## dimnames(res) <- list(rep("", dim(res)[1]), c("", "min", "max")) cat("\n") prmatrix(res, quote = FALSE, right = TRUE) ## cat("\nLargest standard error (SE):", max(round(x$x$seTE, digits.se)), "\n\n") ## cat("Range of probability publishing trial with largest SE:\n") ## res <- matrix(format(round(range(pnorm(x$x$gamma0 + x$x$gamma1 / max(x$x$seTE))), digits)), nrow = 1) ## dimnames(res) <- list(rep("", dim(res)[1]), c("min", "max")) ## prmatrix(res, quote = FALSE, right = TRUE) ## cat("\nCalculation of orthogonal line:\n\n") ## res <- as.matrix(data.frame(x$x$regr)[ , c("levels", "nobs", "adj.r.squareds", "slopes", "se.slopes")]) dimnames(res) <- list(rep("", dim(res)[1]), c("level", "nobs", "adj.r.square", "slope", "se.slope")) prmatrix(res, quote = FALSE, right = TRUE) ## if (legend) { cat("\n Legend:\n") cat(" p.publ - Probability of publishing study with largest SE\n") cat(" p.trt - P-value for test of overall treatment effect\n") cat(" p.rsb - P-value for test of residual selection bias\n") cat(" N - Estimated number of unpublished studies\n") } invisible(NULL) }
4,974
gpl-2.0
5c88f1917a194d102c784f708bb689950def7e38
guido-s/metasens
R/print.summary.copas.R
#' Print detailed results of Copas selection model #' #' @description #' Print method for objects of class \code{summary.copas}. #' #' #' This function prints the following information: #' #' Range of gamma0 values used (see \code{help(copas)}); #' #' Range of gamma1 values used (see \code{help(copas)}); #' #' Largest SE of all studies in meta-analysis; #' #' Range of probability publishing trial with largest SE; #' #' The next table gives details relating to the summary of the contour plot. #' Specifically, it gives details from fitting a straight line to each #' treatment-contour in the contour plot. Column 1 (headed level) shows the #' treatment-contours; column 2 (nobs) shows the number of observations used by #' the contour plot command within the \code{copas} function to plot this #' contour line; column 3 (adj.r.square) shows the adjusted r-square from #' fitting a straight line to this contour; columns 4 & 5 show the slope and #' its standard error from fitting a straight line to this contour. #' #' Next, the printout of \code{summary.copas} is shown. #' #' @aliases print.summary.copas #' #' @param x An object of class \code{summary.copas}. #' @param backtransf A logical indicating whether results should be #' back transformed in printouts and plots. If \code{backtransf = #' TRUE} (default), results are printed as odds ratios rather than #' log odds ratio, for example. #' @param legend A logical indicating whether a legend should be #' printed. #' @param digits Minimal number of significant digits, see #' \code{print.default}. #' @param digits.se Minimal number of significant digits for standard #' deviations and standard errors, see \code{print.default}. #' @param ... Additional arguments (ignored). #' #' @author James Carpenter \email{James.Carpenter@@lshtm.ac.uk}, Guido #' Schwarzer \email{sc@@imbi.uni-freiburg.de} #' #' @seealso \code{\link{copas}}, \code{\link{plot.copas}}, #' \code{\link{summary.copas}} #' #' @keywords print #' #' @examples #' data(Fleiss1993bin, package = "meta") #' #' # Perform meta analysis, effect measure is odds ratio (OR) #' # #' m1 <- metabin(d.asp, n.asp, d.plac, n.plac, data=Fleiss1993bin, sm="OR") #' #' # Print summary of Copas analysis #' # #' summary(copas(m1), level = 0.95) #' #' @method print summary.copas #' @export #' @export print.summary.copas print.summary.copas <- function(x, backtransf = x$backtransf, legend = TRUE, digits = gs("digits"), digits.se = gs("digits.se"), ...) { chkclass(x, "summary.copas") cl <- class(x)[1] addargs <- names(list(...)) ## fun <- "print.summarycopas" ## warnarg("logscale", addargs, fun, otherarg = "backtransf") ## if (is.null(backtransf)) if (!is.null(list(...)[["logscale"]])) backtransf <- !list(...)[["logscale"]] else backtransf <- TRUE else chklogical(backtransf) ## chklogical(legend) chknumeric(digits, min = 0, length = 1) chknumeric(digits.se, min = 0, length = 1) crtitle(x) ## print.copas(x$x, header = FALSE, legend = FALSE, digits = digits, backtransf = backtransf, ...) ## res <- cbind(c("range of gamma0: ", "range of gamma1: "), format(c(round(x$x$gamma0.range[1], digits), round(x$x$gamma1.range[1], digits))), ## format(c(round(x$x$gamma0.range[2], digits), round(x$x$gamma1.range[2], digits)))) ## dimnames(res) <- list(rep("", dim(res)[1]), c("", "min", "max")) cat("\n") prmatrix(res, quote = FALSE, right = TRUE) ## cat("\nLargest standard error (SE):", max(round(x$x$seTE, digits.se)), "\n\n") ## cat("Range of probability publishing trial with largest SE:\n") ## res <- matrix(format(round(range(pnorm(x$x$gamma0 + x$x$gamma1 / max(x$x$seTE))), digits)), nrow = 1) ## dimnames(res) <- list(rep("", dim(res)[1]), c("min", "max")) ## prmatrix(res, quote = FALSE, right = TRUE) ## cat("\nCalculation of orthogonal line:\n\n") ## res <- as.matrix(data.frame(x$x$regr)[ , c("levels", "nobs", "adj.r.squareds", "slopes", "se.slopes")]) dimnames(res) <- list(rep("", dim(res)[1]), c("level", "nobs", "adj.r.square", "slope", "se.slope")) prmatrix(res, quote = FALSE, right = TRUE) ## if (legend) { cat("\n Legend:\n") cat(" p.publ - Probability of publishing study with largest SE\n") cat(" p.trt - P-value for test of overall treatment effect\n") cat(" p.rsb - P-value for test of residual selection bias\n") cat(" N - Estimated number of unpublished studies\n") } invisible(NULL) }
4,974
gpl-2.0
9dc1af1cb4f518cc0bb8a8d932a20a9ca8e759ee
horver/InstallR
tests/testthat/test_install_from_list.R
test_that("install_from_script::Install libs", { libs <- c("car", "ggplot2") install_from_list(libs, load = FALSE) for (lib in libs) expect_true(lib %in% utils::installed.packages()[, 1]) }) test_that("install_from_script::Install libs and don't load", { libs <- c("mgcv", "lme4") install_from_list(libs, load = FALSE) for (lib in libs) { expect_true(lib %in% utils::installed.packages()[, 1]) expect_false(lib %in% devtools::loaded_packages()[, 1]) } }) test_that("install_from_script::Install libs and load", { libs <- c("gamm4", "MuMIn") install_from_list(libs, load = TRUE) for (lib in libs) { expect_true(lib %in% utils::installed.packages()[, 1]) expect_true(lib %in% devtools::loaded_packages()[, 1]) } })
757
mit
61ce45a3e0a9316eb9f2e801ac92f25999b34506
kingtuna/Hybrid-Darknet-Concept
datas/Attackers.R
# Writen by Terrence Gareau and Zane Witherspoon # Analyzes feed data in R after attacks were inserted into csv by Python # python script is feedme.py library('rworldmap') library('plyr') library('ggplot2') # Date month <- "September 2015" # Import Files Start ------------------- base <- read.csv("attack.csv", header = TRUE) methodColors <- read.csv("colors.csv", header = TRUE) methodColors$Color <- as.character(methodColors$Color) jColors <- methodColors$Color names(jColors) <- methodColors$Method # Import Files End ------------------- ## Footnote --------- #https://ryouready.wordpress.com/2009/02/17/r-good-practice-adding-footnotes-to-graphics/ # basic information at the beginning of each script scriptName <- "Attackers.R" author <- "TG" company <- "Nexusguard, Inc." #footnote <- paste(scriptName, format(Sys.time(), "%d %b %Y"), # author, sep=" / ") footnote <- paste(company, author, sep=" / ") # default footnote is today's date, cex=.7 (size) and color # is a kind of grey makeFootnote <- function(footnoteText= format(Sys.time(), "%d %b %Y"), size= .7, color= grey(.5)) { require(grid) pushViewport(viewport()) grid.text(label= footnoteText , x = unit(1,"npc") - unit(2, "mm"), y= unit(2, "mm"), just=c("right", "bottom"), gp=gpar(cex= size, col=color)) popViewport() } ## Footnote # Top10 Start ------------------- #The number 1 looked like an attack to a service provider poo <- sort(table(base$asn),decreasing=TRUE)[1:10] poo1 <- as.list(poo) poo2 <- ls(poo1) topbase <- base[which(base$asn %in% poo2),] topbase$asn <- as.factor(topbase$asn) # scale_fill_brewer(palette="Paired") + svg("attack_top10_bar.svg",width=11,height=8.5) # scale_fill_brewer(palette="Paired") + print(ggplot(topbase, aes(x = asn, fill = method)) + ggtitle(paste("Top 10 Reflective DDoS Attacks by ASN in",month)) + theme(title = element_text(colour="black", face="bold")) + theme(legend.title = element_text(colour="black", size=12, face="bold")) + geom_histogram(width = 0.7) + scale_fill_manual(values = jColors) + xlab("Observed Autonomous Systems") + ylab("Total Count of Attacks") + labs(fill = "Attack Methods")) dev.off() # Top10 End ------------------- # Top10 PNG Start ------------------- #The number 1 looked like an attack to a service provider poo <- sort(table(base$asn),decreasing=TRUE)[1:10] poo1 <- as.list(poo) poo2 <- ls(poo1) topbase <- base[which(base$asn %in% poo2),] topbase$asn <- as.factor(topbase$asn) # scale_fill_brewer(palette="Paired") + ppi <- 300 png("attack_top10_bar.png", width=11*ppi, height=8.5*ppi, res=ppi) # scale_fill_brewer(palette="Paired") + print(ggplot(topbase, aes(x = asn, fill = method)) + ggtitle(paste("Top 10 Reflective DDoS Attacks by ASN in",month)) + theme(title = element_text(colour="black", face="bold")) + theme(legend.title = element_text(colour="black", size=12, face="bold")) + geom_histogram(width = 0.7) + scale_fill_manual(values = jColors) + xlab("Observed Autonomous Systems") + ylab("Total Count of Attacks") + labs(fill = "Attack Methods")) makeFootnote(footnote) dev.off() # Top10 PNG End ------------------- # Top50 Start ------------------- #The number 1 looked like an attack to a service provider poo <- sort(table(base$asn),decreasing=TRUE)[1:50] poo1 <- as.list(poo) poo2 <- ls(poo1) topbase <- base[which(base$asn %in% poo2),] topbase$asn <- as.factor(topbase$asn) svg("attack_top50_bar.svg",width=11,height=8.5) # scale_fill_brewer(palette="Paired") + print(ggplot(topbase, aes(x = asn, fill = method)) + ggtitle(paste("Top 50 Reflective DDoS Attacks by ASN in",month)) + theme(title = element_text(colour="black", face="bold")) + theme(legend.title = element_text(colour="black", size=12, face="bold")) + geom_histogram(width = 0.7) + scale_fill_manual(values = jColors) + xlab("Observed Autonomous Systems") + ylab("Total Count of Attacks") + labs(fill = "Attack Methods") + coord_flip()) dev.off() # Top50 End ------------------- # Top50 PNG Start ------------------- #The number 1 looked like an attack to a service provider poo <- sort(table(base$asn),decreasing=TRUE)[1:50] poo1 <- as.list(poo) poo2 <- ls(poo1) topbase <- base[which(base$asn %in% poo2),] topbase$asn <- as.factor(topbase$asn) ppi <- 300 png("attack_top50_bar.png", width=11*ppi, height=8.5*ppi, res=ppi) # scale_fill_brewer(palette="Paired") + print(ggplot(topbase, aes(x = asn, fill = method)) + ggtitle(paste("Top 50 Reflective DDoS Attacks by ASN in",month)) + theme(title = element_text(colour="black", face="bold")) + theme(legend.title = element_text(colour="black", size=12, face="bold")) + geom_histogram(width = 0.7) + scale_fill_manual(values = jColors) + xlab("Observed Autonomous Systems") + ylab("Total Count of Attacks") + labs(fill = "Attack Methods") + coord_flip()) dev.off() # Top50 PNG End ------------------- # Pie Start ------------------- attacks_counts <- count(base, "method") bp<- ggplot(attacks_counts, aes(x="", y=freq, fill=method))+ geom_bar(width = 1, stat = "identity") pie <- bp + coord_polar("y", start=0) svg("attack_all_pie.svg",width=11,height=8.5) print(pie + scale_fill_manual(values = jColors) + theme(title = element_text(colour="black", face="bold")) + theme(legend.title = element_text(colour="black", size=12, face="bold")) + ggtitle(paste("Attacks by Method in",month)) + labs(fill = "Attack Methods") + ylab("Total Count of Attacks")) dev.off() # Pie End ------------------- # Pie PNG Start ------------------- attacks_counts <- count(base, "method") bp<- ggplot(attacks_counts, aes(x="", y=freq, fill=method))+ geom_bar(width = 1, stat = "identity") pie <- bp + coord_polar("y", start=0) ppi <- 300 png("attack_all_pie.png", width=11*ppi, height=8.5*ppi, res=ppi) print(pie + scale_fill_manual(values = jColors) + theme(title = element_text(colour="black", face="bold")) + theme(legend.title = element_text(colour="black", size=12, face="bold")) + ggtitle(paste("Attacks by Method in",month)) + labs(fill = "Attack Methods") + ylab("Total Count of Attacks")) dev.off() # Pie PNG End ------------------- # World Start ------------------- svg("attack_all_worldmap.svg",width=11,height=8.5) df <- count(base$cuntry) n <- joinCountryData2Map(df, joinCode="ISO2", nameJoinColumn="x") mapParams <- mapCountryData(n, nameColumnToPlot="freq", mapTitle=paste("Attack Events by Country in",month), addLegend=FALSE, catMethod="logFixedWidth", colourPalette="heat") do.call(addMapLegend, c(mapParams ,legendLabels="all" ,legendWidth=1)) print(mapParams) dev.off() # World End ------------------- # World PNG Start ------------------- ppi <- 300 png("attack_all_worldmap.png", width=11*ppi, height=8.5*ppi, res=ppi) df <- count(base$cuntry) n <- joinCountryData2Map(df, joinCode="ISO2", nameJoinColumn="x") mapParams <- mapCountryData(n, nameColumnToPlot="freq", mapTitle=paste("Attack Events by Country in",month), addLegend=FALSE, catMethod="logFixedWidth", colourPalette="heat") do.call(addMapLegend, c(mapParams ,legendLabels="all" ,legendWidth=1)) print(mapParams) dev.off() # World PNG End ------------------- # Attacks by day Start ------------------- days = strtrim(base$time,10) svg("attacks_byday_bar.svg",width=11,height=8.5) print(ggplot(base, aes(x = days, fill = method)) + ggtitle(paste("Attacks by Day in",month)) + theme(title = element_text(colour="black", face="bold")) + theme(legend.title = element_text(colour="black", size=12, face="bold")) + geom_histogram(width = 0.7) + scale_fill_manual(values = jColors) + xlim(rev(sort(unique((days))))) + xlab("Dates") + ylab("Total Count of Attacks") + labs(fill = "Attack Methods") + coord_flip()) dev.off() # Attacks by day Start ------------------- # Attacks by day PNG Start ------------------- png("attacks_byday_bar.png", width=11*ppi, height=8.5*ppi, res=ppi) print(ggplot(base, aes(x = days, fill = method)) + ggtitle(paste("Attacks by Day in",month)) + theme(title = element_text(colour="black", face="bold")) + theme(legend.title = element_text(colour="black", size=12, face="bold")) + geom_histogram(width = 0.7) + scale_fill_manual(values = jColors) + xlim(rev(sort(unique((days))))) + xlab("Dates") + ylab("Total Count of Attacks") + labs(fill = "Attack Methods") + coord_flip()) dev.off() # Attacks by day PNG Start ------------------- # Attacks Durations by day PNG Start ------------------- days = strtrim(base$time,10) png("attacks_durations_byday_scatter.png", width=11*ppi, height=8.5*ppi, res=ppi) number_ticks <- function(n) {function(limits) pretty(limits, n)} print(ggplot(base, aes(method, duration, color=method)) + xlab("") + ylab("Time in Seconds") + ggtitle(paste("Attack Durations by Day in",month)) + scale_color_manual(name="Attack Methods", values = jColors) + theme(title = element_text(colour="black", face="bold")) + theme(legend.title = element_text(colour="black", size=12, face="bold")) + geom_jitter(shape=1, position=position_jitter(0.3)) + #scale_y_continuous(limits=c(0, 86400)) + scale_y_continuous(breaks=number_ticks(10),limits=c(0, 86400)) + #facet_wrap(~method, nrow=1) + geom_boxplot(outlier.shape = NA,col="Black",fill = NA)) dev.off() # Attacks Durations by day PNG Start ------------------- # Attacks Durations by day SVG Start ------------------- days = strtrim(base$time,10) svg("attacks_durations_byday_scatter.svg",width=11,height=8.5) number_ticks <- function(n) {function(limits) pretty(limits, n)} print(ggplot(base, aes(method, duration, color=method)) + xlab("") + ylab("Time in Seconds") + ggtitle(paste("Attack Durations by Day in",month)) + scale_color_manual(name="Attack Methods", values = jColors) + theme(title = element_text(colour="black", face="bold")) + theme(legend.title = element_text(colour="black", size=12, face="bold")) + geom_jitter(shape=1, position=position_jitter(0.3)) + #scale_y_continuous(limits=c(0, 86400)) + scale_y_continuous(breaks=number_ticks(10),limits=c(0, 86400)) + #facet_wrap(~method, nrow=1) + geom_boxplot(outlier.shape = NA,col="Black",fill = NA)) dev.off() # Attacks Durations by day SVG Start -------------------
11,226
bsd-2-clause
1c7daa954f224dcbed354c34b2591dad0bb52ce3
bheesink/ENCODER
ENCODER/R/private.R
.is.wholenumber <- function(x, tol = .Machine$double.eps^0.5) abs(x - round(x)) < tol .loadCovData <- function(files, gc=NULL, mapa=NULL, black=NULL, excludechr=NULL, datacol=5) { d <- lapply(files, read.delim, header=F) cnames <- .removeCommonFix(files) names(d) <- cnames #checks if(length(unique(sapply(d,nrow))) != 1) { stop("Files have variable number of lines and are not compatible") } #naturally sort data d <- lapply(d, function(x) { x[,1] <- factor(x[,1], levels=mixedsort(levels(x[,1]))) x[order(x[,1], x[,2]),] }) #check row order in data files for (i in 2:length(files)) { if(!isTRUE(all.equal(d[[1]][,1:3], d[[i]][,1:3], check.attributes=FALSE))) stop(paste("Datafiles 1 and", i,"are not in the same order")) } cov <- sapply(d, function(x) x[!(x[,1] %in% excludechr),datacol]) anno <- data.frame(droplevels(d[[1]][!(d[[1]][,1] %in% excludechr),1:3])) colnames(anno) <- c("chr","start","end") annoid <- paste(anno$chr, anno$start, anno$end, sep=":") if(!is.null(gc)) { anno$gc <- gc[match(annoid, paste(gc$chr, gc$start, gc$end, sep=":")),"gc"] } if(!is.null(mapa)) { anno$mapa <- mapa[match(annoid, paste(mapa$chr, mapa$start, mapa$end, sep=":")),"mapa"] } if(!is.null(black)) { anno$black <- rep(F, nrow(anno)) for (c in levels(anno$chr)) { ar <- IRanges(anno$start[anno$chr == c], anno$end[anno$chr == c]) br <- IRanges(black$start[black$chr == c], black$end[black$chr == c]) anno$black[anno$chr == c] <- ar %over% br } } list(cov=cov, anno=anno) } .tng <- function(df, use, correctmapa=TRUE, plot=NULL, verbose=T) { #tests if(!is.logical(use) && length(use) ==nrow(df)) stop("use should be logicval vector with same size as df") #df colums? if(!is.null(plot)) { if(!is.logical(plot)) { if(verbose) cat("Plotting to file", plot,"\n") png(plot, width=700, height=1400) par(mfrow=c(2,1)) on.exit(dev.off()) plot <- TRUE } else if(plot) { par(mfrow=c(2,1)) } } #exclude contains the points to exclude in the #fitting (usually sex chromosomes and blacklisted regions) # gc fits also excludes the low mappability data #correct gc using double lowess gcuse <- (use & !is.na(df$mapa) & df$mapa > .8 & !is.na(df$gc) & df$gc > 0) rough <- loess(count ~ gc, data=df, subset=gcuse, span = 0.03) i <- seq(0, 1, by = 0.001) final <- loess(predict(rough, i) ~ i, span = 0.3) normv <- predict(final, df$gc) df$countgcloess <- df$count/(normv/median(normv, na.rm=T)) if(plot) { plot(count ~ gc, data=df, subset=gcuse, ylim=quantile(df$count[gcuse], c(0.0001, .999)), xlim=c(0,1), pch=".") points(count ~ gc, data=df, subset=!gcuse, col=rgb(1,0,0,.3), pch=".") lines(i, predict(rough, i), col="green") points(df$gc, normv, col="red", pch=".") } #correct mapa using linear function that intercepts zero #if(correctmapa) { #mapause <- (use & !is.na(df$mapa)) #lm(countgcloess~0+mapa, data=df, subset=mapause) ->fll #if(verbose) print(summary(fll)) #if (plot) { # plot(countgcloess ~ mapa, data=df, subset=mapause, ylim=quantile(df$countgcloess, c(0.0001, .999), na.rm=T), pch=".") # points(countgcloess ~ mapa, data=df, subset=!mapause, col=rgb(1,0,0,.3), pch=".") # abline(0, fll$coef, col=2) #} #correct mapa using double lowess -> paired end sequencing if(correctmapa) { mapause <- (use & !is.na(df$mapa)) rough <- loess(countgcloess ~ mapa, data=df, subset=mapause, span = 0.03) i <- seq(0, 1, by = 0.001) final <- loess(predict(rough, i) ~ i, span = 0.3) normv <- predict(final, df$mapa) df$countgcmapaloess <- df$countgcloess/(normv/median(normv, na.rm=T)) if (plot) { plot(countgcloess ~ mapa, data=df, subset=mapause, ylim=quantile(df$countgcloess[mapause], c(0.0001, .999), na.rm=T), xlim=c(0,1), pch=".") points(countgcloess ~ mapa, data=df, subset=!mapause, col=rgb(1,0,0,.3), pch=".") lines(i, predict(rough, i), col="green") points(df$mapa, normv, subset = (!is.na(df$mapa) && !is.na(normv)), col="red", pch=".") } return(log2(df$countgcmapaloess / median(df$countgcmapaloess[use], na.rm=T))) } else { #corerct agains median value (exluding sex chr) log2(df$countgcloess / median(df$countgcloess[use], na.rm=T)) } } .removeCommonFix <- function(names, distance=1) { l <- strsplit(names,"") #clip prefix pclip <- 1 while( length(unique(sapply(l, "[", pclip))) <= distance) { pclip <- pclip + 1 } #reverse strings for end clip pos l <- lapply(l, rev) eclip <- 1 while( length(unique(sapply(l, "[", eclip))) <= distance) { eclip <- eclip + 1 } sapply(names, function(x) substr(x, pclip, nchar(x) - eclip), USE.NAMES=F) }
4,621
gpl-2.0
61ce45a3e0a9316eb9f2e801ac92f25999b34506
kingtuna/honeynet
datas/Attackers.R
# Writen by Terrence Gareau and Zane Witherspoon # Analyzes feed data in R after attacks were inserted into csv by Python # python script is feedme.py library('rworldmap') library('plyr') library('ggplot2') # Date month <- "September 2015" # Import Files Start ------------------- base <- read.csv("attack.csv", header = TRUE) methodColors <- read.csv("colors.csv", header = TRUE) methodColors$Color <- as.character(methodColors$Color) jColors <- methodColors$Color names(jColors) <- methodColors$Method # Import Files End ------------------- ## Footnote --------- #https://ryouready.wordpress.com/2009/02/17/r-good-practice-adding-footnotes-to-graphics/ # basic information at the beginning of each script scriptName <- "Attackers.R" author <- "TG" company <- "Nexusguard, Inc." #footnote <- paste(scriptName, format(Sys.time(), "%d %b %Y"), # author, sep=" / ") footnote <- paste(company, author, sep=" / ") # default footnote is today's date, cex=.7 (size) and color # is a kind of grey makeFootnote <- function(footnoteText= format(Sys.time(), "%d %b %Y"), size= .7, color= grey(.5)) { require(grid) pushViewport(viewport()) grid.text(label= footnoteText , x = unit(1,"npc") - unit(2, "mm"), y= unit(2, "mm"), just=c("right", "bottom"), gp=gpar(cex= size, col=color)) popViewport() } ## Footnote # Top10 Start ------------------- #The number 1 looked like an attack to a service provider poo <- sort(table(base$asn),decreasing=TRUE)[1:10] poo1 <- as.list(poo) poo2 <- ls(poo1) topbase <- base[which(base$asn %in% poo2),] topbase$asn <- as.factor(topbase$asn) # scale_fill_brewer(palette="Paired") + svg("attack_top10_bar.svg",width=11,height=8.5) # scale_fill_brewer(palette="Paired") + print(ggplot(topbase, aes(x = asn, fill = method)) + ggtitle(paste("Top 10 Reflective DDoS Attacks by ASN in",month)) + theme(title = element_text(colour="black", face="bold")) + theme(legend.title = element_text(colour="black", size=12, face="bold")) + geom_histogram(width = 0.7) + scale_fill_manual(values = jColors) + xlab("Observed Autonomous Systems") + ylab("Total Count of Attacks") + labs(fill = "Attack Methods")) dev.off() # Top10 End ------------------- # Top10 PNG Start ------------------- #The number 1 looked like an attack to a service provider poo <- sort(table(base$asn),decreasing=TRUE)[1:10] poo1 <- as.list(poo) poo2 <- ls(poo1) topbase <- base[which(base$asn %in% poo2),] topbase$asn <- as.factor(topbase$asn) # scale_fill_brewer(palette="Paired") + ppi <- 300 png("attack_top10_bar.png", width=11*ppi, height=8.5*ppi, res=ppi) # scale_fill_brewer(palette="Paired") + print(ggplot(topbase, aes(x = asn, fill = method)) + ggtitle(paste("Top 10 Reflective DDoS Attacks by ASN in",month)) + theme(title = element_text(colour="black", face="bold")) + theme(legend.title = element_text(colour="black", size=12, face="bold")) + geom_histogram(width = 0.7) + scale_fill_manual(values = jColors) + xlab("Observed Autonomous Systems") + ylab("Total Count of Attacks") + labs(fill = "Attack Methods")) makeFootnote(footnote) dev.off() # Top10 PNG End ------------------- # Top50 Start ------------------- #The number 1 looked like an attack to a service provider poo <- sort(table(base$asn),decreasing=TRUE)[1:50] poo1 <- as.list(poo) poo2 <- ls(poo1) topbase <- base[which(base$asn %in% poo2),] topbase$asn <- as.factor(topbase$asn) svg("attack_top50_bar.svg",width=11,height=8.5) # scale_fill_brewer(palette="Paired") + print(ggplot(topbase, aes(x = asn, fill = method)) + ggtitle(paste("Top 50 Reflective DDoS Attacks by ASN in",month)) + theme(title = element_text(colour="black", face="bold")) + theme(legend.title = element_text(colour="black", size=12, face="bold")) + geom_histogram(width = 0.7) + scale_fill_manual(values = jColors) + xlab("Observed Autonomous Systems") + ylab("Total Count of Attacks") + labs(fill = "Attack Methods") + coord_flip()) dev.off() # Top50 End ------------------- # Top50 PNG Start ------------------- #The number 1 looked like an attack to a service provider poo <- sort(table(base$asn),decreasing=TRUE)[1:50] poo1 <- as.list(poo) poo2 <- ls(poo1) topbase <- base[which(base$asn %in% poo2),] topbase$asn <- as.factor(topbase$asn) ppi <- 300 png("attack_top50_bar.png", width=11*ppi, height=8.5*ppi, res=ppi) # scale_fill_brewer(palette="Paired") + print(ggplot(topbase, aes(x = asn, fill = method)) + ggtitle(paste("Top 50 Reflective DDoS Attacks by ASN in",month)) + theme(title = element_text(colour="black", face="bold")) + theme(legend.title = element_text(colour="black", size=12, face="bold")) + geom_histogram(width = 0.7) + scale_fill_manual(values = jColors) + xlab("Observed Autonomous Systems") + ylab("Total Count of Attacks") + labs(fill = "Attack Methods") + coord_flip()) dev.off() # Top50 PNG End ------------------- # Pie Start ------------------- attacks_counts <- count(base, "method") bp<- ggplot(attacks_counts, aes(x="", y=freq, fill=method))+ geom_bar(width = 1, stat = "identity") pie <- bp + coord_polar("y", start=0) svg("attack_all_pie.svg",width=11,height=8.5) print(pie + scale_fill_manual(values = jColors) + theme(title = element_text(colour="black", face="bold")) + theme(legend.title = element_text(colour="black", size=12, face="bold")) + ggtitle(paste("Attacks by Method in",month)) + labs(fill = "Attack Methods") + ylab("Total Count of Attacks")) dev.off() # Pie End ------------------- # Pie PNG Start ------------------- attacks_counts <- count(base, "method") bp<- ggplot(attacks_counts, aes(x="", y=freq, fill=method))+ geom_bar(width = 1, stat = "identity") pie <- bp + coord_polar("y", start=0) ppi <- 300 png("attack_all_pie.png", width=11*ppi, height=8.5*ppi, res=ppi) print(pie + scale_fill_manual(values = jColors) + theme(title = element_text(colour="black", face="bold")) + theme(legend.title = element_text(colour="black", size=12, face="bold")) + ggtitle(paste("Attacks by Method in",month)) + labs(fill = "Attack Methods") + ylab("Total Count of Attacks")) dev.off() # Pie PNG End ------------------- # World Start ------------------- svg("attack_all_worldmap.svg",width=11,height=8.5) df <- count(base$cuntry) n <- joinCountryData2Map(df, joinCode="ISO2", nameJoinColumn="x") mapParams <- mapCountryData(n, nameColumnToPlot="freq", mapTitle=paste("Attack Events by Country in",month), addLegend=FALSE, catMethod="logFixedWidth", colourPalette="heat") do.call(addMapLegend, c(mapParams ,legendLabels="all" ,legendWidth=1)) print(mapParams) dev.off() # World End ------------------- # World PNG Start ------------------- ppi <- 300 png("attack_all_worldmap.png", width=11*ppi, height=8.5*ppi, res=ppi) df <- count(base$cuntry) n <- joinCountryData2Map(df, joinCode="ISO2", nameJoinColumn="x") mapParams <- mapCountryData(n, nameColumnToPlot="freq", mapTitle=paste("Attack Events by Country in",month), addLegend=FALSE, catMethod="logFixedWidth", colourPalette="heat") do.call(addMapLegend, c(mapParams ,legendLabels="all" ,legendWidth=1)) print(mapParams) dev.off() # World PNG End ------------------- # Attacks by day Start ------------------- days = strtrim(base$time,10) svg("attacks_byday_bar.svg",width=11,height=8.5) print(ggplot(base, aes(x = days, fill = method)) + ggtitle(paste("Attacks by Day in",month)) + theme(title = element_text(colour="black", face="bold")) + theme(legend.title = element_text(colour="black", size=12, face="bold")) + geom_histogram(width = 0.7) + scale_fill_manual(values = jColors) + xlim(rev(sort(unique((days))))) + xlab("Dates") + ylab("Total Count of Attacks") + labs(fill = "Attack Methods") + coord_flip()) dev.off() # Attacks by day Start ------------------- # Attacks by day PNG Start ------------------- png("attacks_byday_bar.png", width=11*ppi, height=8.5*ppi, res=ppi) print(ggplot(base, aes(x = days, fill = method)) + ggtitle(paste("Attacks by Day in",month)) + theme(title = element_text(colour="black", face="bold")) + theme(legend.title = element_text(colour="black", size=12, face="bold")) + geom_histogram(width = 0.7) + scale_fill_manual(values = jColors) + xlim(rev(sort(unique((days))))) + xlab("Dates") + ylab("Total Count of Attacks") + labs(fill = "Attack Methods") + coord_flip()) dev.off() # Attacks by day PNG Start ------------------- # Attacks Durations by day PNG Start ------------------- days = strtrim(base$time,10) png("attacks_durations_byday_scatter.png", width=11*ppi, height=8.5*ppi, res=ppi) number_ticks <- function(n) {function(limits) pretty(limits, n)} print(ggplot(base, aes(method, duration, color=method)) + xlab("") + ylab("Time in Seconds") + ggtitle(paste("Attack Durations by Day in",month)) + scale_color_manual(name="Attack Methods", values = jColors) + theme(title = element_text(colour="black", face="bold")) + theme(legend.title = element_text(colour="black", size=12, face="bold")) + geom_jitter(shape=1, position=position_jitter(0.3)) + #scale_y_continuous(limits=c(0, 86400)) + scale_y_continuous(breaks=number_ticks(10),limits=c(0, 86400)) + #facet_wrap(~method, nrow=1) + geom_boxplot(outlier.shape = NA,col="Black",fill = NA)) dev.off() # Attacks Durations by day PNG Start ------------------- # Attacks Durations by day SVG Start ------------------- days = strtrim(base$time,10) svg("attacks_durations_byday_scatter.svg",width=11,height=8.5) number_ticks <- function(n) {function(limits) pretty(limits, n)} print(ggplot(base, aes(method, duration, color=method)) + xlab("") + ylab("Time in Seconds") + ggtitle(paste("Attack Durations by Day in",month)) + scale_color_manual(name="Attack Methods", values = jColors) + theme(title = element_text(colour="black", face="bold")) + theme(legend.title = element_text(colour="black", size=12, face="bold")) + geom_jitter(shape=1, position=position_jitter(0.3)) + #scale_y_continuous(limits=c(0, 86400)) + scale_y_continuous(breaks=number_ticks(10),limits=c(0, 86400)) + #facet_wrap(~method, nrow=1) + geom_boxplot(outlier.shape = NA,col="Black",fill = NA)) dev.off() # Attacks Durations by day SVG Start -------------------
11,226
bsd-2-clause
c2a906bfa6d24e9f664757d7e1cde0f6ed351519
KDE/rkward
tests/distributions/logistic_probabilities.rkcommands.R
local({ ## Compute q <- seq (-5, 5, length.out=20) p <- plogis (q, location=0.0, scale=1.0) ## Print result rk.header ("Logistic distribution", parameters=list("Location"="0.0", "Scale"="1.0", "Tail"="Lower tail: P[X ≤ x]")) rk.results (data.frame ("Quantile"=q, "Probability"=p, check.names=FALSE)) })
307
gpl-2.0
4292857b904859232e0c2552e6836b242bdf1872
gdevailly/HeatStarSeq_gh
dataset_fromating/21_modEncode_dm_TF_chipseq.R
# 2016/03/21 # download all file from: ftp://data.modencode.org/D.melanogaster/Transcriptional-Factor/ChIP-seq/computed-peaks_gff3/ # we merged gff3 files # gunzip *.gz # grep -v '^#' --no-filename *.gff3 > ../mergedPeaks.gff3 # negative start values and 0 start values. :( # removing them manually, then: # sortBed -i mergedPeaks.gff3 > mergedPeaks_sorted.gff3 # bedtools merge -i mergedPeaks_sorted.gff3 > mergedPeaks_merged.gff3 setwd("/groups2/joshi_grp/guillaume/otherProject/ChIP_heatmap/data/modEncodeDM/computed-peaks_gff3") library(dplyr) library(readr) library(parallel) library(GenomicRanges) mergedPeaks <- read_tsv("../mergedPeaks_merged.gff3", col_names = FALSE, col_types = "cii") names(mergedPeaks) <- c("chr", "start", "end") table(mergedPeaks$chr) validChr <- c("X", "2L", "2R", "3L", "3R", "4", "Y", "M", "2CEN", "3CEN", "XY", "XHet", "YHet", "2LHet", "2RHet", "3LHet", "3RHet", "2", "3") dim(mergedPeaks) mergedPeaks <- filter(mergedPeaks, chr %in% validChr) dim(mergedPeaks) mergedPeaksGR <- with(mergedPeaks, GRanges(chr, IRanges(start, end))) myFiles <- list.files() t0 <- Sys.time() modData <- mclapply(myFiles, function(x) read_tsv(x, col_names = FALSE, skip = 2, col_types = "c????????"), mc.cores = 32) Sys.time() - t0 # 1 sec t0 <- Sys.time() modDataGR <- lapply( modData, function(x) with(x, GRanges(X1, IRanges(X4, X5))) ) Sys.time() - t0 # 1 s t0 <- Sys.time() listOverlap <- lapply( modDataGR, function(x) overlapsAny(mergedPeaksGR, x) ) Sys.time() - t0 # 3 sec table(sapply(listOverlap, length)) # ok dataMtrix <- do.call(cbind, listOverlap) corMtrix <- cor(dataMtrix) metadata <- sub(".gff3", "", myFiles) strsplit(metadata, split = ":", fixed = TRUE) %>% sapply(. , length) %>% table strsplit(metadata, split = ":", fixed = TRUE) %>% do.call(rbind, .) %>% data.frame(stringsAsFactors = FALSE) -> metadata metadata <- metadata[, c(1, 2, 7)] colnames(metadata) <- c("antibody", "developmentalStage", "id") strsplit(metadata$developmentalStage, split = "#", fixed = TRUE) %>% sapply(. , length) %>% table tempChr <- strsplit(metadata$developmentalStage, split = "#", fixed = TRUE) library(stringr) myMD <- data.frame( cellLine = str_match(metadata$developmentalStage, ".*Cell-Line=(.*)")[, 2], devStage = str_match(metadata$developmentalStage, ".*Developmental-Stage=(.*)")[, 2], strain = str_match(metadata$developmentalStage, ".*Strain=(.*)")[, 2], stringsAsFactors = FALSE ) myMD <- lapply(myMD, function(x) gsub("#.*", "", x)) %>% data.frame(stringsAsFactors = FALSE) metadata <- cbind(metadata[, c("antibody", "id")], myMD) filter(metadata, antibody == "eGFP") metadata[!is.na(metadata$cellLine), "devStage"] <- metadata[!is.na(metadata$cellLine), "cellLine"] # http://stackoverflow.com/questions/13673894/suppress-nas-in-paste paste3 <- function(... ,sep=" ") { L <- list(...) L <- lapply(L,function(x) {x[is.na(x)] <- ""; x}) ret <- gsub(paste0("(^",sep,"|",sep,"$)"),"", gsub(paste0(sep,sep),sep, do.call(paste,c(L,list(sep=sep))))) is.na(ret) <- ret=="" ret } metadata$name <- paste3(metadata$antibody, metadata$devStage, metadata$strain, metadata$id) length(metadata$name) length(unique(metadata$name)) metadata$url <- paste0( "http://data.modencode.org/cgi-bin/findFiles.cgi?download=", sub("modENCODE_", "", metadata$id, fixed = TRUE) ) metadata <- metadata[, c(1:2, 4:7)] rownames(metadata) <- NULL modEncodeD_ChIPseq <- list( dataMatrix = dataMtrix, regionMetaData = mergedPeaksGR, correlationMatrix = cor(dataMtrix), annotation = metadata ) modEncodeD_ChIPseq$annotation$strain[is.na(modEncodeD_ChIPseq$annotation$strain)] <- "unspecify" save(modEncodeD_ChIPseq, file = "../../../heatchipseq/data/modEncodeD_ChIPseq.RData")
3,810
gpl-3.0
936ddb6abc70f3ad69c7100a22b71c01770f03ef
donlelef/som-fault-pattern-recognition
ShinyViewer/Packages/STMDataMining/R/getUniqueColumns.R
#' This function selects a subset of a data.frame's rows and and returns unique values. #' #' @title Subset of a data.frame's rows and and return unique values. #' @export #' @param columns a vector containing the names of the columns that are to be used as ids. #' @param dataFrame a data.frame with the supposed format. #' @return a data.frame with only the selected columns containing unique values. getUniqueColumns = function(dataFrame, columns){ ids = subset(x = dataFrame, select = columns) ids = unique(ids) return(ids) }
540
gpl-3.0
936ddb6abc70f3ad69c7100a22b71c01770f03ef
donlelef/Faut-detection-Thesis
ShinyViewer/Packages/STMDataMining/R/getUniqueColumns.R
#' This function selects a subset of a data.frame's rows and and returns unique values. #' #' @title Subset of a data.frame's rows and and return unique values. #' @export #' @param columns a vector containing the names of the columns that are to be used as ids. #' @param dataFrame a data.frame with the supposed format. #' @return a data.frame with only the selected columns containing unique values. getUniqueColumns = function(dataFrame, columns){ ids = subset(x = dataFrame, select = columns) ids = unique(ids) return(ids) }
540
gpl-3.0
72b145378c6a54bc12576b427d89e6ab929306a9
MazamaScience/MazamaSpatialUtils
tests/testthat/test-getStateCode.R
# ----------------------------------------------------------------------------- testthat::context("getStateCode()") setup_spatial_data <- function() { skip_on_cran() skip_on_travis() # try to set up spatial data. Skip if fails. spatialDataDir <- try(getSpatialDataDir(), silent = TRUE) if (!exists('NaturalEarthAdm1')) { tryCatch(getSpatialDataDir(), error = function(error) { setSpatialDataDir("~/Data/Spatial_0.8") }) tryCatch(loadSpatialData("NaturalEarthAdm1"), error = function(error) { message("Could not load NaturalEarthAdm1") }) } if (!exists("NaturalEarthAdm1")) { skip("Could not load NaturalEarthAdm1") } return(spatialDataDir) } testthat::test_that("handles errors correctly", { skip_on_cran() skip_on_travis() # Setup spatialDataDir <- setup_spatial_data() testthat::expect_error(getStateCode()) testthat::expect_error(getStateCode()) testthat::expect_error(getStateCode(0, 100)) testthat::expect_error(getStateCode(-400, 0)) # Teardown if (class(spatialDataDir) == "character") { setSpatialDataDir(spatialDataDir) } else { .removeSpatialDataDir() } }) # NOTE: Slow! # testthat::test_that("returns correct name", { # # skip_on_cran() # skip_on_travis() # # # Setup # spatialDataDir <- setup_spatial_data() # # # testthat::expect_match(getStateCode(-108, 48), "MT") # # testthat::expect_match(getStateCode(2.1, 41.38), "CT") # # testthat::expect_match(getStateCode(c(-108, 2.1), c(48, 41.38)), "MT|CT") # # testthat::expect_equal(getStateCode(1,1), NA_character_) # # # Teardown # if (class(spatialDataDir) == "character") { # setSpatialDataDir(spatialDataDir) # } else { # .removeSpatialDataDir() # } # # }) testthat::test_that("subsetting with countryCodes works", { skip_on_cran() skip_on_travis() # Setup spatialDataDir <- setup_spatial_data() testthat::expect_match(getStateCode(2.1, 41.38, countryCodes = c("ES")), "CT") testthat::expect_equal(getStateCode(c(2.1, -108), c(41.38, 48), countryCodes = "ES"), c("CT", NA_character_)) # Teardown if (class(spatialDataDir) == "character") { setSpatialDataDir(spatialDataDir) } else { .removeSpatialDataDir() } }) testthat::test_that("allData returns are correct dimension and type", { skip_on_cran() skip_on_travis() # Setup spatialDataDir <- setup_spatial_data() testthat::expect_s3_class(getStateCode(-100, 48, countryCodes = c("US"), allData = TRUE), "data.frame") testthat::expect_equal(dim(getStateCode(-100, 48, countryCodes = c("US"), allData = TRUE)), c(1,ncol(NaturalEarthAdm1) - 1)) # SFDF has an extra 'geometry' column testthat::expect_s3_class(getStateCode(c(-100, -90), c(48, 38), countryCodes = c("US"), allData = TRUE), "data.frame") testthat::expect_equal(dim(getStateCode(c(-100, -90), c(48, 38), countryCodes = c("US"), allData = TRUE)), c(2,ncol(NaturalEarthAdm1) - 1)) # SFDF has an extra 'geometry' column # Teardown if (class(spatialDataDir) == "character") { setSpatialDataDir(spatialDataDir) } else { .removeSpatialDataDir() } })
3,183
gpl-2.0
40ec24d2e3b96ac3ce1ab6be6eb9401b446aba3a
sjewo/tmap
pkg/R/legend_hist.R
legend_hist <- function(x, legend.hist.size, lineHeight, scale, m, attr.color, legend.hist.bg.color) { with(x, { if (is.factor(values)) { numbers <- table(values) xticks <- seq(0, 1, length.out=length(numbers)*2+1)[seq(2,length(numbers)*2,by=2)] ptx <- levels(values) #if (any(nchar(ptx)>5)) ptx <- substr(ptx, 1, 3) colors <- legend.palette } else { values <- na.omit(values) breaks2 <- pretty(values, n=30) toolow <- (breaks2 < min(breaks)) toohigh <- (breaks2 > max(breaks)) startID <- max(sum(toolow), 1) endID <- length(breaks2) - max(sum(toohigh), 1) + 1 breaks2 <- breaks2[startID:endID] bins.mean <- (breaks2[-1] + breaks2[1:(length(breaks2)-1)])/2 cvalues <- cut(values, breaks=breaks2, include.lowest=TRUE, right=FALSE) numbers <- as.vector(table(cvalues)) breaks[1] <- -Inf breaks[length(breaks)] <- Inf colors <- legend.palette[sapply(bins.mean, function(x) which(x<breaks)[1]-1)] ptx <- pretty(breaks2, n=5) ptx <- ptx[ptx>breaks2[1] & ptx<tail(breaks2,1)] rng <- range(breaks2) xticks <- (ptx - rng[1]) / (rng[2] - rng[1]) } maxnumber <- max(numbers) pty <- pretty(c(0, numbers), n=5) hs <- numbers / maxnumber pty <- pty[pty<=maxnumber] hpty <- pty / maxnumber x <- seq(0, 1, length.out=length(numbers)+1)[1:length(numbers)] ws <- 1/length(numbers) # lower 1/2 line hs <- hs * (1- (lineHeight/2)) hpty <- hpty * (1- (lineHeight/2)) formattedY <- format(pty, trim=TRUE) width.npc <- max(convertWidth(stringWidth(paste(ptx, " ")), unitTo="npc", valueOnly=TRUE)) * (length(ptx)+1) height.npc <- convertHeight(unit(length(formattedY)+2, "lines"), "npc", valueOnly=TRUE) my <- lineHeight * legend.hist.size * m mx <- convertWidth(convertHeight(unit(my, "npc"), "inch"), "npc", TRUE) npcx.total <- 1-2*mx npcy.total <- 1-2*my ## decrease factor text_shrink <- (npcx.total/width.npc) if (legend.hist.size/text_shrink>1.5) { draw_x_axis <- FALSE text_shrink <- Inf } else { draw_x_axis <- TRUE } #margin <- 0.05 #npc.total <- 1-2*m size <- min(legend.hist.size, text_shrink, npcy.total/height.npc) width.npc <- width.npc * size height.npc <- height.npc * size width.yaxis <- max(convertWidth(stringWidth(formattedY), unitTo="npc", valueOnly=TRUE)) * size height.xaxis <- lineHeight * size * ifelse(draw_x_axis, 1, .25) axisTicks <- convertWidth(unit(mx, "npc"), "inch", valueOnly=TRUE) mxInch <- convertWidth(unit(mx, "npc"), "inch", valueOnly=TRUE) height.xaxisInch <- convertHeight(unit(height.xaxis, "npc"), "inch", valueOnly=TRUE) vpHist <- viewport(layout=grid.layout(5, 5, heights=unit(c(my, 1, axisTicks, height.xaxis, my), c("npc", "null", "inch", "npc", "npc")), widths=unit(c(width.yaxis, mx, axisTicks, 1, 3*mx), c("npc", "npc", "inch", "null", "npc")))) pushViewport(vpHist) histElems <- gList( if (!is.na(legend.hist.bg.color)) cellplot(2,4,e={ rectGrob(gp=gpar(fill=legend.hist.bg.color, col=attr.color)) }) else NULL, cellplot(2,4, e={ rectGrob(x=x, y=0, width=ws, height=hs, gp=gpar(col=NA,fill=colors), just=c("left", "bottom")) }), # plot y axis cellplot(2,3,e={ axisTicks.npc <- convertWidth(unit(axisTicks, "inch"), "npc", valueOnly=TRUE) polylineGrob(x=c(axisTicks.npc, axisTicks.npc, rep(c(0,axisTicks.npc), length(pty))), y=c(0, 1, rep(hpty, each=2)), id=rep(1:(length(pty)+1),each=2), gp=gpar(col=attr.color, lwd=scale)) }), cellplot(2:4,1,e={ maxWidth <- max(convertWidth(stringWidth(formattedY), unitTo="npc", valueOnly=TRUE)) * size h_total <- convertHeight(unit(1, "npc"), "inch", valueOnly = TRUE) h_extra <- axisTicks+height.xaxisInch h_e <- h_extra / h_total hpty <- h_e + hpty * (1-h_e) textGrob(formattedY, x=maxWidth, y=hpty, just=c(1,.4), gp=gpar(col=attr.color, cex=size)) }), # plot x axis tick marks cellplot(3,4,e={ axisTicks.npc <- convertHeight(unit(axisTicks, "inch"), "npc", valueOnly=TRUE) n <- length(xticks) line_height <- convertHeight(unit(1, "lines"), "npc", valueOnly=TRUE) * size if (draw_x_axis) { gTree(children = gList(linesGrob(x=c(0,1), y=c(1, 1), gp=gpar(lwd=scale)), polylineGrob(x=rep(xticks, each=2), y=rep(c(1, 1-axisTicks.npc), n), id=rep(1:n, each=2), gp=gpar(col=attr.color, lwd=scale)))) } else linesGrob(x=c(0,1), y=c(1, 1), gp=gpar(col=attr.color, lwd=scale)) }), if (draw_x_axis) cellplot(4,4:5,e={ w_total <- convertWidth(unit(1, "npc"), "inch", valueOnly = TRUE) w_extra <- 3*mxInch w_e <- w_extra / w_total xticks <- xticks * (1-w_e) textGrob(ptx, x=xticks, y=.5, gp=gpar(col=attr.color, cex=size)) }) else NULL) treeHist <- gTree(children=histElems, vp=vpHist) upViewport() list(treeHist, 1) }) }
4,996
gpl-3.0
a953582bd7a000e57d2b0d9fe79825e0b61c7b5c
virtualstaticvoid/heroku-buildpack-r
test/ruby/init.R
# used for R buildpack detection
33
mit
4cd2319b842455362dc2ceeb1af0ba2eeca9b366
ganna10/Meteorology_and_Ozone
T_Dep_Indep_Comparisons/Old_stuff/Contours_and_m.R
# Plot O3 contours with m_O3-T as tile. facet run ~ mechanism # Version 0: Jane Coates 09/11/2015 setwd("~/Documents//Analysis//2015_Meteorology_and_Ozone//T_Dep_Indep_Comparisons") get.labels = function (break.points, orig.data, digits) { labels = lapply(break.points, function (i) round ((i * (max(orig.data) - min(orig.data))) + min(orig.data), digits )) return (labels) } contour_mechanism_data_frame = function (mechanism, dataframe) { data = dataframe %>% filter(Mechanism == mechanism) data = data %>% mutate(Scaled.Temperature = (Temperature - min(Temperature))/(max(Temperature) - min(Temperature)), Scaled.NOx.Emissions = (NOx.Emissions - min(NOx.Emissions))/(max(NOx.Emissions) - min(NOx.Emissions))) fld = with(data, interp(x = Scaled.Temperature, y = Scaled.NOx.Emissions, z = O3)) df = melt(fld$z, na.rm = TRUE) names(df) = c("x", "y", "O3") df$Temperature = fld$x[df$x] df$NOx.Emissions = fld$y[df$y] df$Mechanism = rep(mechanism, length(df$NOx)) return (df) } get_contour_data = function (run) { filename = paste0("Temperature_", run, "_data.csv") d = read.csv(filename) data = lapply(mechanisms, contour_mechanism_data_frame, dataframe = d) df = do.call("rbind", data) df$Run = rep(paste("Temperature", run, "\nIsoprene Emissions"), length(df$NOx)) return(df) } get_slope_data = function (run) { filename = paste0("Temperature_", run, "_data.csv") d = read.csv(filename) slopes = d %>% mutate(Scaled.NOx.Emissions = (NOx.Emissions - min(NOx.Emissions))/(max(NOx.Emissions) - min(NOx.Emissions))) %>% select(-NOx.Emissions) %>% group_by(Mechanism, Scaled.NOx.Emissions) %>% do(model = lm(O3 ~ Temperature, data = .)) %>% mutate(Slope = sprintf("%.1f", abs(summary(model)$coeff[2])), R2 = summary(model)$r.squared) %>% select(-model) slopes$Run = rep(paste("Temperature", run, "\nIsoprene Emissions"), length(slopes$Mechanism)) slopes$NOx.Start = slopes$Scaled.NOx.Emissions NOx.End = as.data.frame(as.numeric(levels(factor(slopes$Scaled.NOx.Emissions)))) names(NOx.End) = c("NOx.End") NOx.End = NOx.End %>% filter(NOx.End != 0) NOx.End = rbind(NOx.End, Inf) slopes$NOx.End = NOx.End$NOx.End names(slopes) = c("Mechanism", "NOx.Emissions", "Slope", "R2", "Run", "NOx.Start", "NOx.End") return(slopes) } runs = c("Dependent", "Independent") mechanisms = c("CB05", "RADM2", "MCMv3.2", "MOZART-4", "CRIv2") #O3 Contours contour.data = lapply(runs, get_contour_data) df = do.call("rbind", contour.data) #combining into 1 data frame #m_O3-T slopes.data = lapply(runs, get_slope_data) slopes = do.call("rbind", slopes.data) #labels d = read.csv(file = "Temperature_Dependent_data.csv") %>% filter(Mechanism == "CB05") %>% mutate(Temperature.C = Temperature - 273) temperature.break.points = seq(0, 1, 0.2) temperature.labels = get.labels(temperature.break.points, d$Temperature.C, digits = 2) NOx.Emissions.break.points = seq(0, 1, 0.2) NOx.Emissions.labels = get.labels(NOx.Emissions.break.points, d$NOx.Emissions, digits = 2) NOx.Emissions.labels = lapply(NOx.Emissions.labels, function (i) sprintf("%0.1e", i)) p = ggplot(df, aes(y = NOx.Emissions)) p = p + geom_rect(data = slopes, aes(xmin = 0, xmax = Inf, ymin = NOx.Start, ymax = NOx.End, fill = factor(Slope))) p = p + stat_contour(aes(x = Temperature, z = O3, colour = ..level..), binwidth = 5) p = p + facet_grid(Mechanism ~ Run) p = p + scale_colour_gradient(low = "#cc6329", high = "#ef6638") p = p + scale_fill_grey(limits = rev(levels(factor(slopes$Slope))), name = expression(bold(paste(m[O3-T])))) p = p + xlab(expression(bold(paste("Temperature (", degree, "C)")))) + ylab("NOx Emissions (molecules cm-3 s-1)") p = p + scale_x_continuous(breaks = temperature.break.points, labels = temperature.labels) p = p + scale_y_continuous(breaks = NOx.Emissions.break.points, labels = NOx.Emissions.labels) p = p + theme_tufte() p = p + theme(axis.title = element_text(face = "bold")) p = p + theme(strip.text = element_text(face = "bold")) p = p + theme(strip.text.y = element_text(angle = 0)) #direct.label(p) CairoPDF(file = "O3_contours_with_m.pdf", width = 7, height = 10) print(direct.label(p, list('top.pieces', cex = 0.6))) dev.off()
4,207
gpl-2.0
6fddda59f705933c16751b16ee78e4bd53204cab
MoBiodiv/MoBspatial
examples/Application3_EAR_aggregation.R
# R code to reproduce Fig. S2 in the article # mobsim: An R package for the simulation and measurement of # biodiversity across spatial scales # Felix May # October 17 2017 library(mobsim) # set reference parameters S0 <- 200 N0 <- 10000 cv0 <- 1 # parameters for scenarios with higher aggregation sigma_high <- 0.05 sigma_low <- 0.01 # sampling areas for the evaluation of the endemics-area relationship (EAR) p_area <- c(0.01,0.05,0.1,0.2,0.5,0.6,0.7,0.8,0.9,0.95,0.99,1.0) # number of replicate simulations (1000 in the article) nsim <- 100 # define matrices to store simulation output for the EAR ear_random_mat <- matrix(NA, nrow = nsim, ncol = length(p_area)) ear_sigma_high_mat <- matrix(NA, nrow = nsim, ncol = length(p_area)) ear_sigma_low_mat <- matrix(NA, nrow = nsim, ncol = length(p_area)) ear_clust1_mat <- matrix(NA, nrow = nsim, ncol = length(p_area)) # run replicate simulations for all scenarios for (i in 1:nsim){ # random com_random <- sim_poisson_community(s_pool = S0, n_sim = N0, sad_coef = list(meanlog = 3, sdlog = 1)) divar1 <- divar(com_random, prop_area = p_area) ear_random_mat[i, ] <- divar1$m_endemics # sigma high com_sigma_high <- sim_thomas_community(s_pool = S0, n_sim = N0, sigma = sigma_high, sad_coef = list(meanlog = 3, sdlog = 1)) divar1 <- divar(com_sigma_high, prop_area = p_area) ear_sigma_high_mat[i, ] <- divar1$m_endemics # sigma low com_sigma_low <- sim_thomas_community(s_pool = S0, n_sim = N0, sigma = sigma_low, sad_coef = list(meanlog = 3, sdlog = 1)) divar1 <- divar(com_sigma_low, prop_area = p_area) ear_sigma_low_mat[i, ] <- divar1$m_endemics # one cluster per species com_clust1 <- sim_thomas_community(s_pool = S0, n_sim = N0, sigma = sigma_high, mother_points = 1, sad_coef = list(meanlog = 3, sdlog = 1)) divar1 <- divar(com_clust1, prop_area = p_area) ear_clust1_mat[i, ] <- divar1$m_endemics } # calculate means and 95% confidence intervals ear_random_mean <- colMeans(ear_random_mat, na.rm = T) ear_random_ci <- apply(ear_random_mat, MARGIN = 2, FUN = "quantile", probs = c(0.025, 0.975), na.rm = T) ear_sigma_high_mean <- colMeans(ear_sigma_high_mat, na.rm = T) ear_sigma_high_ci <- apply(ear_sigma_high_mat, MARGIN = 2, FUN = "quantile", probs = c(0.025, 0.975), na.rm = T) ear_sigma_low_mean <- colMeans(ear_sigma_low_mat, na.rm = T) ear_sigma_low_ci <- apply(ear_sigma_low_mat, MARGIN = 2, FUN = "quantile", probs = c(0.025, 0.975), na.rm = T) ear_clust1_mean <- colMeans(ear_clust1_mat, na.rm = T) ear_clust1_ci <- apply(ear_clust1_mat, MARGIN = 2, FUN = "quantile", probs = c(0.025, 0.975), na.rm = T) # Create plot png("FigS2_EAR.png", width = 5, height = 5, units = "in", res = 200) par(las = 1, font.main = 1, cex.lab = 1.2, cex.main = 1.4) plot(p_area, ear_random_mean, type = "n", las = 1, xlab = "Proportion of area lost", ylab = "No. of species lost", main = "Endemics area relationships") polygon(c(p_area, rev(p_area)), c(ear_random_ci[1,], rev(ear_random_ci[2,])), col = adjustcolor(1, alpha.f = 0.1), border = NA) lines(p_area, ear_random_mean) polygon(c(p_area, rev(p_area)), c(ear_sigma_high_ci[1,], rev(ear_sigma_high_ci[2,])), col = adjustcolor(2, alpha.f = 0.1), border = NA) lines(p_area, ear_sigma_high_mean, col = 2) polygon(c(p_area, rev(p_area)), c(ear_sigma_low_ci[1,], rev(ear_sigma_low_ci[2,])), col = adjustcolor(3, alpha.f = 0.1), border = NA) lines(p_area, ear_sigma_low_mean, col = 3) polygon(c(p_area, rev(p_area)), c(ear_clust1_ci[1,], rev(ear_clust1_ci[2,])), col = adjustcolor(4,alpha.f = 0.1), border = NA) lines(p_area, ear_clust1_mean, col = 4) legend("topleft",legend = c("Random","Large clusters", "Small clusters","One large cluster"), title = "Species distributions", lwd = 2, col = 1:4) dev.off()
4,150
gpl-3.0
71c4978aaa94135074227729a1d4da375593bdd9
krlmlr/r-source
src/library/methods/R/MethodsList.R
# File src/library/methods/R/MethodsList.R # Part of the R package, https://www.R-project.org # # Copyright (C) 1995-2016 The R Core Team # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # A copy of the GNU General Public License is available at # https://www.R-project.org/Licenses/ MethodsList <- ## Create a MethodsList object out of the arguments. ## ## Conceptually, this object is a named collection of methods to be ## dispatched when the (first) argument in a function call matches the ## class corresponding to one of the names. A final, unnamed element ## (i.e., with name `""') corresponds to the default method. ## ## The elements can be either a function, or another MethodsList. In ## the second case, this list implies dispatching on the second ## argument to the function using that list, given a selection of this ## element on the first argument. Thus, method dispatching on an ## arbitrary number of arguments is defined. ## ## MethodsList objects are used primarily to dispatch OOP-style ## methods and, in R, to emulate S4-style methods. function(.ArgName, ...) { .MlistDeprecated("MethodsList()") value <- makeMethodsList(list(...)) if(is.name(.ArgName)){} else if(is.character(.ArgName) && length(.ArgName) == 1) .ArgName <- as.name(.ArgName) else stop("invalid first argument: should be the name of the first argument in the dispatch") slot(value, "argument") <- .ArgName value } makeMethodsList <- function(object, level=1) { .MlistDeprecated("makeMethodsList()") mnames <- allNames(object) if(.noMlists()) { keep <- mnames %in% c("", "ANY") mnames <- mnames[keep] object <- object[keep] } value <- new("MethodsList") i <- match("", mnames) if(!is.na(i)) { ## convert to ANY mnames[[i]] <- "ANY" names(object) <- mnames } if(anyDuplicated(mnames)) stop(gettextf("duplicate element names in 'MethodsList' at level %d: %s", level, paste("\"", unique(mnames[duplicated(mnames)]), "\"", collapse=", ")), domain = NA) for(i in seq_along(object)) { eli <- object[[i]] if(is(eli, "function") || is(eli, "MethodsList")) {} else if(is(eli, "list") || is(eli, "named")) object[[i]] <- Recall(eli, NULL, level+1) else stop(gettextf("element %d at level %d (class %s) cannot be interpreted as a function or named list", i, level, dQuote(class(eli))), domain = NA) } slot(value, "methods") <- object value } SignatureMethod <- ## construct a MethodsList object containing (only) this method, corresponding ## to the signature; i.e., such that signature[[1L]] is the match for the first ## argument, signature[[2L]] for the second argument, and so on. The string ## "missing" means a match for a missing argument, and "ANY" means use this as the ## default setting at this level. ## ## The first argument is the argument names to be used for dispatch corresponding to ## the signatures. function(names, signature, definition) { .MlistDeprecated("SignatureMethod()") n <- length(signature) if(n > length(names)) stop("arguments 'names' and 'signature' must have the same length") if(n == 0) return(definition) Class <- signature[[n]] name <- names[[n]] m <- MethodsList(name) slot(m, "methods")[[Class]] <- definition slot(m, "argument") <- as.name(name) SignatureMethod(names[-n], signature[-n], m) } insertMethod <- ## insert the definition `def' into the MethodsList object, `mlist', corresponding to ## the signature, and return the modified MethodsList. function(mlist, signature, args, def, cacheOnly = FALSE) { .MlistDeprecated("insertMethod()") if(.noMlists() && !identical(unique(signature), "ANY")) return(mlist) ## Checks for assertions about valid calls. ## See rev. 1.17 for the code before the assertions added. if(identical(args[1L], "...") && !identical(names(signature), "...")) { if(identical(signature[[1L]], "ANY")) stop(gettextf("inserting method with invalid signature matching argument '...' to class %s", dQuote(signature[[1L]])), domain = NA) args <- args[-1L] signature <- signature[-1L] if(length(signature) == 0L) return(mlist) } if(length(signature) == 0L) stop("inserting method corresponding to empty signature") if(!is(mlist, "MethodsList")) stop(gettextf("inserting method into non-methods-list object (class %s)", dQuote(.class1(mlist))), domain = NA) if(length(args) > 1 && !cacheOnly) mlist <- balanceMethodsList(mlist, args) Class <- signature[[1]] methods <- if(cacheOnly) mlist@allMethods else mlist@methods current <- methods[[Class]] if(is(current, "MethodsList")) { nextArg <- as.character(current@argument) sigArgs <- args n <- length(signature) length(sigArgs) <- n if(is.na(match(nextArg, sigArgs))) { n <- match(nextArg, args) - n if(is.na(n)) { ## not in args eitiher n <- 1 args <- c(args, nextArg) } ## make explicit the trailing ANY's needed signature <- c(signature, rep("ANY", n)) } } if(length(signature) == 1) { if(is.null(current)) { if(!is.null(def)) methods[[Class]] <- def ## else, no change } else { which <- match(Class, names(methods)) if(is.null(def)) ## delete the method methods <- methods[-which] else methods[[which]] <- def } } else { ## recursively merge, initializing current if necessary if(is.null(current)) current <- new("MethodsList", argument = as.name(args[2L])) else if(is.function(current)) current <- new("MethodsList", argument = as.name(args[2L]), methods = list(ANY = current)) methods[[Class]] <- Recall(current, signature[-1L], args[-1L], def, cacheOnly) } mlist@allMethods <- methods if(!cacheOnly) mlist@methods <- methods mlist } MethodsListSelect <- ## select the element of a MethodsList object corresponding to the ## actual arguments (as defined in the suppled environment), ## and return the object, extended to include that method if necessary. ## ## Works recursively. At each level finds an argument name from the current `mlist' ## object, and evaluates this argument (if it is not missing), then uses the ## class of the result to select an element of `mlist'. If such an element ## exists and is another `MethodsList' object, `MethodsListSelect' calls itself recursively ## to resolve using further arguments. Matching includes using a default selection or ## a method specifically linked to class `"missing"'. Once a function is found, it ## is returned as the value. If matching fails, NULL is returned. function(f, env, mlist = NULL, fEnv = if(is(fdef, "genericFunction")) environment(fdef) else baseenv(), finalDefault = finalDefaultMethod(mlist), evalArgs = TRUE, useInherited = TRUE, ## supplied when evalArgs is FALSE fdef = getGeneric(f, where = env), # MUST BE SAFE FROM RECUSIVE METHOD SELECTION resetAllowed = TRUE # FALSE when called from selectMethod, .findNextMethod ) { .MlistDeprecated("MethodsListSelect()") if(!resetAllowed) # ensure we restore the real methods for this function resetMlist <- .getMethodsForDispatch(fdef) ## look for call from C dispatch code during another call to MethodsListSelect if(is.null(f)) {} # Recall, not from C else { fMethods <- .getMethodsForDispatch(fdef) if(is.null(mlist) || (evalArgs && is.function(fMethods))) mlist <- fMethods } resetNeeded <- .setIfBase(f, fdef, mlist) # quickly protect against recursion -- see Methods.R if(resetNeeded) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } if(!is(mlist, "MethodsList")) { if(is.function(mlist)) # call to f, inside MethodsListSelect {on.exit(); return(mlist)} if(is.null(f)) # recursive recall of MethodsListSelect stop("invalid method sublist") else if(!is.null(mlist)) # NULL => 1st call to genericFunction stop(gettextf("%f is not a valid generic function: methods list was an object of class %s", sQuote(f), dQuote(class(mlist))), domain = NA) } if(!is.logical(useInherited)) stop(gettextf("%s must be TRUE, FALSE, or a named logical vector of those values; got an object of class %s", sQuote("useInherited"), dQuote(class(useInherited))), domain = NA) if(identical(mlist, .getMethodsForDispatch(fdef))) { resetNeeded <- TRUE ## On the initial call: ## turn off any further method dispatch on this function, to avoid recursive ## loops if f is a function used in MethodsListSelect. ## TODO: Using namespaces in the methods package would eliminate the need for this .setMethodsForDispatch(f, fdef, finalDefault) if(is(mlist, "MethodsList")) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } } argName <- slot(mlist, "argument") arg <- NULL ## => don't use instance-specific inheritance if(evalArgs) { ## check for missing argument. NB: S sense, not that of R base missing() if(missingArg(argName, env, TRUE)) thisClass <- "missing" else { arg <- eval(as.name(argName), env) ## DO use instance-specific inheritance if(missing(arg)) ## S3 weird R code? Bail out! return(finalDefault) thisClass <- .class1(arg) } } else thisClass <- get(as.character(argName), envir = env, inherits = FALSE) if(identical(useInherited, TRUE) || identical(useInherited, FALSE)) thisInherit <- nextUseInherited <- useInherited else { which <- match(as.character(argName), names(useInherited)) if(is.na(which)) { nextUseInherited <- useInherited thisInherit <- TRUE } else { thisInherit <- useInherited[[which]] nextUseInherited <- useInherited[-which] } } fromClass <- thisClass ## will mark the class actually providing the method allMethods <- mlist@allMethods which <- match(thisClass, names(allMethods)) inherited <- is.na(which) selection <- if(inherited) NULL else allMethods[[which]] if(!inherited) { if(is(selection, "function")) { if(is.null(f)) { ## An inherited method at the next level up. ## only the inherited method should be added mlist <- .trimMlist(mlist, fromClass) } value <- mlist ## no change } else { ## recursive call with NULL function name, to allow search to fail & ## to suppress any reset actions. method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef, ) if(is(method, "EmptyMethodsList")) value <- method else { mlist@allMethods[[which]] <- method value <- mlist } } } if(inherited || is(value, "EmptyMethodsList")) { ## direct selection failed at this level or below method <- NULL if(thisInherit) { allSelections <- inheritedSubMethodLists(arg, fromClass, mlist, env) allClasses <- names(allSelections) for(i in seq_along(allSelections)) { selection <- allSelections[[i]] fromClass <- allClasses[[i]] if(is(selection, "function")) method <- selection else if(is(selection, "MethodsList")) { ## go on to try matching further arguments method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef) if(is(method, "EmptyMethodsList")) selection <- method ## recursive selection failed } if(!is(selection, "EmptyMethodsList")) break } } if((is.null(selection) || is(selection, "EmptyMethodsList")) && !is.null(f) && !is.null(finalDefault)) { ## only use the final default method after exhausting all ## other possibilities, at all levels. method <- finalDefault fromClass <- "ANY" } if(is.null(method) || is(method, "EmptyMethodsList")) value <- emptyMethodsList(mlist, thisClass) ## nothing found else { method <- MethodAddCoerce(method, argName, thisClass, fromClass) value <- .insertCachedMethods(mlist, as.character(argName), thisClass, fromClass, method) } } if(!is.null(f)) { ## top level if(is(value, "EmptyMethodsList")) ## selection failed value <- NULL if(resetNeeded) { on.exit() # cancel the restore of the original mlist if(resetAllowed) { if(is.null(value)) resetMlist <- mlist else resetMlist <- value } .setMethodsForDispatch(f, fdef, resetMlist) if(dispatchIsInternal(fdef)) setPrimitiveMethods(f, finalDefault, "set", fdef, resetMlist) } } value } emptyMethodsList <- function(mlist, thisClass = "ANY", sublist = list()) { .MlistDeprecated("emptyMethodsList()") sublist[thisClass] <- list(NULL) new("EmptyMethodsList", argument = mlist@argument, sublist = sublist) } insertMethodInEmptyList <- function(mlist, def) { .MlistDeprecated("insertMethodInEmptyList()") value <- new("MethodsList", argument = mlist@argument) sublist <- mlist@sublist submethods <- sublist[[1L]] if(is.null(submethods)) sublist[[1L]] <- def else sublist[[1L]] <- Recall(submethods, def) value@allMethods <- sublist value } finalDefaultMethod <- ## Return the default method from the generic (it may be NULL, a method object or a primitive. ## this previously searched in a MethodsList object. Once those are gone, the loop should ## be irrelevant except as an error check. function(method) { repeat { if(is.function(method) # <- somewhat liberal, but catches both methods and primitives || is.null(method)) break if(is(method, "MethodsList")) { .MlistDeprecated() method <- slot(method, "methods")[["ANY"]] } else stop(gettextf( "default method must be a method definition, a primitive or NULL: got an object of class %s", dQuote(class(method))), domain = NA) } method } inheritedSubMethodLists <- ## Utility function to match the object to the elements of a methods list. ## ## The function looks only for an inherited match, and only among ## the methods that are not themselves inherited. (Inherited methods when found are ## stored in the session copy of the methods list, but they themselves should not be ## used for finding inherited matches, because an erroneous match could be found depending ## on which methods were previously used. See the detailed discussion of methods.) function(object, thisClass, mlist, ev) { .MlistDeprecated("inheritedSubMethodLists()") methods <- slot(mlist, "methods")## only direct methods defaultMethod <- methods[["ANY"]]## maybe NULL classes <- names(methods) value <- list() if(.identC(thisClass, "missing")) { ## no superclasses for "missing" } else { ## search in the superclasses, but don't use inherited methods ## There are two cases: if thisClass is formally defined & unsealed, use its ## superclasses. Otherwise, look in the subclasses of those classes for ## which methods exist. classDef <- getClassDef(thisClass, ev) useSuperClasses <- !is.null(classDef) && !classDef@sealed if(useSuperClasses) { ## for consistency, order the available methods by ## the ordering of the superclasses of thisClass superClasses <- names(classDef@contains) classes <- superClasses[!is.na(match(superClasses, classes))] for(which in seq_along(classes)) { tryClass <- classes[[which]] ## TODO: There is potential bug here: If the is relation is conditional, ## we should not cache this selection. Needs another trick in the environment ## to FORCE no caching regardless of what happens elsewhere; e.g., storing a ## special object in .Class if(is.null(object) || is(object, tryClass)) { value[[tryClass]] <- methods[[tryClass]] } } } else { for(which in seq_along(classes)) { tryClass <- classes[[which]] tryClassDef <- getClassDef(tryClass, ev) if(!is.null(tryClassDef) && !is.na(match(thisClass, names(tryClassDef@subclasses)))) value[[tryClass]] <- methods[[which]] } } } if(!is.null(defaultMethod)) value[["ANY"]] <- defaultMethod value } matchSignature <- ## Match the signature object (a partially or completely named subset of the ## arguments of `fun', and return a vector of all the classes in the order specified ## by the signature slot of the generic. The classes not specified by `signature ##' will be `"ANY"' in the value. function(signature, fun, where = baseenv()) { if(!is(fun, "genericFunction")) stop(gettextf("trying to match a method signature to an object (of class %s) that is not a generic function", dQuote(class(fun))), domain = NA) anames <- fun@signature if(length(signature) == 0L) return(character()) if(is(signature,"character")) { pkgs <- packageSlot(signature) # includes case of "ObjectsWithPackage" if(is.null(pkgs)) pkgs <- character(length(signature)) else if(length(pkgs) != length(signature)) stop("invalid 'package' slot or attribute, wrong length") sigClasses <- as.character(signature) } else if(is(signature, "list")) { sigClasses <- pkgs <- character(length(signature)) for(i in seq_along(signature)) { cli <- signature[[i]] if(is(cli, "classRepresentation")) { sigClasses[[i]] <- cli@className pkgs[[i]] <- cli@package } else if(is(cli, "character") && length(cli) == 1) { sigClasses[[i]] <- cli pkgi <- packageSlot(cli) if(is.character(pkgi)) pkgs[[i]] <- pkgi } else stop(gettextf("invalid element in a list for \"signature\" argument; element %d is neither a class definition nor a class name", i), domain = NA) } } else stop(gettextf("trying to match a method signature of class %s; expects a list or a character vector", dQuote(class(signature))), domain = NA) if(!identical(where, baseenv())) { ## fill in package information, warn about undefined classes unknown <- !nzchar(pkgs) for(i in seq_along(sigClasses)[unknown]) { cli <- getClassDef(sigClasses[[i]], where) if(!is.null(cli)) { pkgs[[i]] <- cli@package unknown[[i]] <- FALSE } } if(any(unknown)) { unknown <- unique(sigClasses[unknown]) ## coerce(), i.e., setAs() may use *one* unknown class MSG <- if(identical(as.vector(coerce@generic), "coerce") && length(unknown) == 1) message else function(...) warning(..., call. = FALSE) MSG(.renderSignature(fun@generic, signature), sprintf(ngettext(length(unknown), "no definition for class %s", "no definition for classes %s"), paste(dQuote(unknown), collapse = ", ")), domain = NA) } } signature <- as.list(signature) if(length(sigClasses) != length(signature)) stop(gettextf("object to use as a method signature for function %s does not look like a legitimate signature (a vector of single class names): there were %d class names, but %d elements in the signature object", sQuote(fun@generic), length(sigClasses), length(signature)), domain = NA) if(is.null(names(signature))) { which <- seq_along(signature) if(length(which) > length(anames)) stop(gettextf("more elements in the method signature (%d) than in the generic signature (%d) for function %s", length(which), length(anames), sQuote(fun@generic)), domain = NA) } else { ## construct a function call with the same naming pattern & ## values as signature sigList <- signature for(i in seq_along(sigList)) sigList[[i]] <- c(sigClasses[[i]], pkgs[[i]]) fcall <- do.call("call", c("fun", sigList)) ## match the call to the formal signature (usually the formal args) if(identical(anames, formalArgs(fun))) smatch <- match.call(fun, fcall) else { fmatch <- fun ff <- as.list(anames); names(ff) <- anames formals(fmatch, envir = environment(fun)) <- ff smatch <- match.call(fmatch, fcall) } snames <- names(smatch)[-1L] which <- match(snames, anames) ## Assertion: match.call has permuted the args into the order of formal args, ## and carried along the values. Get the supplied classes in that ## order, from the matched args in the call object. if(anyNA(which)) stop(sprintf(ngettext(sum(is.na(which)), "in the method signature for function %s invalid argument name in the signature: %s", "in the method signature for function %s invalid argument names in the signature: %s"), sQuote(fun@generic), paste(snames[is.na(which)], collapse = ", ")), domain = NA) smatch <- smatch[-1] for(i in seq_along(smatch)) { eli <- smatch[[i]] sigClasses[[i]] <- eli[[1]] pkgs[[i]] <- eli[[2]] } } n <- length(anames) value <- rep("ANY", n) valueP <- rep("methods", n) names(value) <- anames value[which] <- sigClasses valueP[which] <- pkgs unspec <- value == "ANY" ## remove the trailing unspecified classes while(n > 1 && unspec[[n]]) n <- n-1 length(value) <- length(valueP) <- n attr(value, "package") <- valueP ## <FIXME> Is there a reason (bootstrapping?) why this ## is not an actual object from class "signature"? ## See .MakeSignature() </FIXME> value } showMlist <- ## Prints the contents of the MethodsList. If `includeDefs' the signatures and the ## corresponding definitions will be printed; otherwise, only the signatures. ## ## If `includeDefs' is `TRUE', the currently known inherited methods are included; ## otherwise, only the directly defined methods. function(mlist, includeDefs = TRUE, inherited = TRUE, classes = NULL, useArgNames = TRUE, printTo = stdout()) { .MlistDeprecated("showMlist()") if(identical(printTo, FALSE)) { tmp <- tempfile() con <- file(tmp, "w") } else con <- printTo object <- linearizeMlist(mlist, inherited) methods <- object@methods signatures <- object@classes args <- object@arguments if(!is.null(classes) && length(signatures)>0) { keep <- !vapply(signatures, function(x, y) all(is.na(match(x, y))), NA, classes) methods <- methods[keep] signatures <- signatures[keep] args <- args[keep] } if(length(methods) == 0) cat(file=con, "<Empty Methods List>\n") else { n <- length(methods) labels <- character(n) if(useArgNames) { for(i in 1L:n) { sigi <- signatures[[i]] labels[[i]] <- paste(args[[i]], " = \"", sigi, "\"", sep = "", collapse = ", ") } } else { for(i in 1L:n) labels[[i]] <- paste(signatures[[i]], collapse = ", ") } for(i in seq_along(methods)) { cat(file=con, (if(includeDefs) "## Signature:" else ""), labels[[i]]) method <- methods[[i]] if(includeDefs) { cat(file=con, ":\n") if(is(method, "MethodDefinition")) ## really an assertion cat(file=con, deparse(method@.Data), sep="\n") else cat(file=con, deparse(method), sep="\n") } if(is(method, "MethodDefinition") && !identical(method@target, method@defined)) { defFrom <- method@defined cat(file = con, if(includeDefs) "##:" else "\n", " (inherited from ", paste(names(defFrom), " = \"", as.character(defFrom), "\"", sep = "", collapse = ", "), ")", if(includeDefs) "\n", sep="") } cat(file=con, "\n") } } if(identical(printTo, FALSE)) { close(con) value <- readLines(tmp) unlink(tmp) value } } promptMethods <- function(f, filename = NULL, methods) { ## Generate information in the style of 'prompt' for the methods of ## the generic named 'f'. ## ## 'filename' can be a logical or NA or the name of a file to print ## to. If it 'FALSE', the methods skeleton is returned, to be ## included in other printing (typically, the output from 'prompt'). escape <- function(txt) gsub("%", "\\\\%", txt) packageString <- "" fdef <- getGeneric(f) if(!isGeneric(f, fdef=fdef)) stop(gettextf("no generic function found corresponding to %s", sQuote(f)), domain = NA) if(missing(methods)) { methods <- findMethods(fdef) ## try making packageString where <- .genEnv(fdef, topenv(parent.frame())) if(!identical(where, .GlobalEnv)) packageString <- sprintf("in Package \\pkg{%s}", getPackageName(where)) } fullName <- utils:::topicName("methods", f) n <- length(methods) labels <- character(n) aliases <- character(n) signatures <- findMethodSignatures(methods = methods, target=TRUE) args <- colnames(signatures) # the *same* for all for(i in seq_len(n)) { sigi <- signatures[i, ] labels[[i]] <- sprintf("\\code{signature(%s)}", paste(sprintf("%s = \"%s\"", args, escape(sigi)), collapse = ", ")) aliases[[i]] <- paste0("\\alias{", utils:::topicName("method", c(f, signatures[i,])), "}") } text <- paste0("\n\\item{", labels, "}{\n%% ~~describe this method here~~\n}") text <- c("\\section{Methods}{\n\\describe{", text, "}}") aliasText <- c(paste0("\\alias{", escape(fullName), "}"), escape(aliases)) if(identical(filename, FALSE)) return(c(aliasText, text)) if(is.null(filename) || identical(filename, TRUE)) filename <- paste0(fullName, ".Rd") Rdtxt <- list(name = paste0("\\name{", fullName, "}"), type = "\\docType{methods}", aliases = aliasText, ## <FIXME> ## Title and description are ok as auto-generated: should ## they be flagged as such (via '~~' which are quite often ## left in by authors)? title = sprintf("\\title{ ~~ Methods for Function \\code{%s} %s ~~}", f, packageString), description = paste0("\\description{\n ~~ Methods for function", " \\code{", f, "} ", sub("^in Package", "in package", packageString), " ~~\n}"), ## </FIXME> "section{Methods}" = text, keywords = c("\\keyword{methods}", "\\keyword{ ~~ other possible keyword(s) ~~ }")) if(is.na(filename)) return(Rdtxt) cat(unlist(Rdtxt), file = filename, sep = "\n") .message("A shell of methods documentation has been written", .fileDesc(filename), ".\n") invisible(filename) } ##' only called from showMlist() above, which has been deprecated in R 3.2.0 (Apr.2015): linearizeMlist <- ## Undo the recursive nature of the methods list, making a list of ## function definitions, with the names of the list being the ## corresponding signatures (designed for printing; for looping over ## the methods, use `listFromMlist' instead). ## ## The function calls itself recursively. `prev' is the previously ## selected class names. ## ## If argument `classes' is provided, only signatures containing one ## of these classes will be included. function(mlist, inherited = TRUE) { methods <- mlist@methods allMethods <- mlist@allMethods if(inherited && length(allMethods) >= length(methods)) { ## anames <- names(allMethods) ## inh <- is.na(match(anames, names(methods))) methods <- allMethods } preC <- function(y, x)c(x,y) # used with lapply below cnames <- names(methods) value <- list() classes <- list() arguments <- list() argname <- as.character(mlist@argument) for(i in seq_along(cnames)) { mi <- methods[[i]] if(is.function(mi)) { value <- c(value, list(mi)) classes <- c(classes, list(cnames[[i]])) arguments <- c(arguments, list(argname)) } else if(is(mi, "MethodsList")) { .MlistDeprecated() mi <- Recall(mi, inherited) value <- c(value, mi@methods) classes <- c(classes, lapply(mi@classes, preC, cnames[[i]])) arguments <- c(arguments, lapply(mi@arguments, preC, argname)) } else warning(gettextf("skipping methods list element %s of unexpected class %s\n\n", paste(cnames[i], collapse = ", "), dQuote(.class1(mi))), domain = NA) } new("LinearMethodsList", methods = value, classes = classes, arguments = arguments) } print.MethodsList <- function(x, ...) showMlist(x) ## In R's own code, this is *only* used in mergeMethods(), deprecated in R 3.2.0 (Apr.2015) listFromMlist <- ## linearizes the MethodsList object into list(sigs, methods); `prefix' is the partial ## signature (a named list of classes) to be prepended to the signatures in this object. ## ## A utility function used to iterate over all the individual methods in the object. function(mlist, prefix = list(), sigs. = TRUE, methods. = TRUE) { methodSlot <- slot(mlist, "methods") mnames <- names(methodSlot) argName <- as.character(slot(mlist, "argument")) sigs <- list() methods <- list() for(i in seq_along(methodSlot)) { thisMethod <- methodSlot[i] thisClass <- mnames[[i]] prefix[[argName]] <- thisClass if(is.function(thisMethod)) { if(sigs.) sigs <- c(sigs, list(prefix)) if(methods.) methods <- c(methods, list(thisMethod)) } else { more <- Recall(thisMethod, prefix) if(sigs.) sigs <- c(sigs, more[[1]]) if(methods.) methods <- c(methods, more[[2]]) } } list(sigs, methods) } .insertCachedMethods <- function(mlist, argName, Class, fromClass, def) { if(is(def, "MethodsList")) { .MlistDeprecated() ## insert all the cached methods in def newArg <- c(argName, as.character(def@argument)) newDefs <- def@allMethods newSigs <- as.list(names(newDefs)) for(j in seq_along(newDefs)) mlist <- Recall(mlist, newArg, c(Class, newSigs[[j]]), fromClass, newDefs[[j]]) } else { def <- .addMethodFrom(def, argName[1L], Class[1L], fromClass) mlist <- insertMethod(mlist, Class, argName, def, TRUE) } mlist } .addMethodFrom <- function(def, arg, Class, fromClass) { if(is(def, "MethodDefinition")) { ## eventually, we may enforce method definition objects ## If not, just leave raw functions alone (NextMethod won't work) def@target[[arg]] <- Class def@defined[[arg]] <- fromClass } def } ## Define a trivial version of asMethodDefinition for bootstrapping. ## The real version requires several class definitions as well as ## methods for as<- asMethodDefinition <- function(def, signature = list(.anyClassName), sealed = FALSE, fdef = def) { if(is.primitive(def) || is(def, "MethodDefinition")) def else { value = new("MethodDefinition") value@.Data <- def classes <- .MakeSignature(new("signature"), def, signature, fdef) value@target <- classes value@defined <- classes value } } .trimMlist <- function(mlist, fromClass) { mlist@methods <- mlist@methods[fromClass] mlist@allMethods <- mlist@allMethods[fromClass] mlist } .noMlistsFlag <- TRUE .noMlists <- function() { ## if this were to be dynamically variable, but ## it can't, IMO ## identical(getOption("noMlists"), TRUE) ## so instead .noMlistsFlag } .MlistDepTable <- new.env() .MlistDeprecated <- function(this = "<default>", instead) { if(is.character(this)) { if(exists(this, envir = .MlistDepTable, inherits = FALSE)) return() else assign(this, TRUE, envir = .MlistDepTable) } msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is deprecated." else if(is.character(this)) gettextf( "%s, along with other use of the \"MethodsList\" metadata objects, is deprecated.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is deprecated.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList. (This warning is shown once per session.)") base::.Deprecated(msg = msg) } .MlistDefunct <- function(this = "<default>", instead) { msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is defunct." else if(is.character(this)) gettextf("%s, along with other use of the \"MethodsList\" metadata objects, is defunct.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is defunct.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList.") base::.Defunct(msg = msg) }
36,574
gpl-2.0
71c4978aaa94135074227729a1d4da375593bdd9
rho-devel/rho
src/library/methods/R/MethodsList.R
# File src/library/methods/R/MethodsList.R # Part of the R package, https://www.R-project.org # # Copyright (C) 1995-2016 The R Core Team # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # A copy of the GNU General Public License is available at # https://www.R-project.org/Licenses/ MethodsList <- ## Create a MethodsList object out of the arguments. ## ## Conceptually, this object is a named collection of methods to be ## dispatched when the (first) argument in a function call matches the ## class corresponding to one of the names. A final, unnamed element ## (i.e., with name `""') corresponds to the default method. ## ## The elements can be either a function, or another MethodsList. In ## the second case, this list implies dispatching on the second ## argument to the function using that list, given a selection of this ## element on the first argument. Thus, method dispatching on an ## arbitrary number of arguments is defined. ## ## MethodsList objects are used primarily to dispatch OOP-style ## methods and, in R, to emulate S4-style methods. function(.ArgName, ...) { .MlistDeprecated("MethodsList()") value <- makeMethodsList(list(...)) if(is.name(.ArgName)){} else if(is.character(.ArgName) && length(.ArgName) == 1) .ArgName <- as.name(.ArgName) else stop("invalid first argument: should be the name of the first argument in the dispatch") slot(value, "argument") <- .ArgName value } makeMethodsList <- function(object, level=1) { .MlistDeprecated("makeMethodsList()") mnames <- allNames(object) if(.noMlists()) { keep <- mnames %in% c("", "ANY") mnames <- mnames[keep] object <- object[keep] } value <- new("MethodsList") i <- match("", mnames) if(!is.na(i)) { ## convert to ANY mnames[[i]] <- "ANY" names(object) <- mnames } if(anyDuplicated(mnames)) stop(gettextf("duplicate element names in 'MethodsList' at level %d: %s", level, paste("\"", unique(mnames[duplicated(mnames)]), "\"", collapse=", ")), domain = NA) for(i in seq_along(object)) { eli <- object[[i]] if(is(eli, "function") || is(eli, "MethodsList")) {} else if(is(eli, "list") || is(eli, "named")) object[[i]] <- Recall(eli, NULL, level+1) else stop(gettextf("element %d at level %d (class %s) cannot be interpreted as a function or named list", i, level, dQuote(class(eli))), domain = NA) } slot(value, "methods") <- object value } SignatureMethod <- ## construct a MethodsList object containing (only) this method, corresponding ## to the signature; i.e., such that signature[[1L]] is the match for the first ## argument, signature[[2L]] for the second argument, and so on. The string ## "missing" means a match for a missing argument, and "ANY" means use this as the ## default setting at this level. ## ## The first argument is the argument names to be used for dispatch corresponding to ## the signatures. function(names, signature, definition) { .MlistDeprecated("SignatureMethod()") n <- length(signature) if(n > length(names)) stop("arguments 'names' and 'signature' must have the same length") if(n == 0) return(definition) Class <- signature[[n]] name <- names[[n]] m <- MethodsList(name) slot(m, "methods")[[Class]] <- definition slot(m, "argument") <- as.name(name) SignatureMethod(names[-n], signature[-n], m) } insertMethod <- ## insert the definition `def' into the MethodsList object, `mlist', corresponding to ## the signature, and return the modified MethodsList. function(mlist, signature, args, def, cacheOnly = FALSE) { .MlistDeprecated("insertMethod()") if(.noMlists() && !identical(unique(signature), "ANY")) return(mlist) ## Checks for assertions about valid calls. ## See rev. 1.17 for the code before the assertions added. if(identical(args[1L], "...") && !identical(names(signature), "...")) { if(identical(signature[[1L]], "ANY")) stop(gettextf("inserting method with invalid signature matching argument '...' to class %s", dQuote(signature[[1L]])), domain = NA) args <- args[-1L] signature <- signature[-1L] if(length(signature) == 0L) return(mlist) } if(length(signature) == 0L) stop("inserting method corresponding to empty signature") if(!is(mlist, "MethodsList")) stop(gettextf("inserting method into non-methods-list object (class %s)", dQuote(.class1(mlist))), domain = NA) if(length(args) > 1 && !cacheOnly) mlist <- balanceMethodsList(mlist, args) Class <- signature[[1]] methods <- if(cacheOnly) mlist@allMethods else mlist@methods current <- methods[[Class]] if(is(current, "MethodsList")) { nextArg <- as.character(current@argument) sigArgs <- args n <- length(signature) length(sigArgs) <- n if(is.na(match(nextArg, sigArgs))) { n <- match(nextArg, args) - n if(is.na(n)) { ## not in args eitiher n <- 1 args <- c(args, nextArg) } ## make explicit the trailing ANY's needed signature <- c(signature, rep("ANY", n)) } } if(length(signature) == 1) { if(is.null(current)) { if(!is.null(def)) methods[[Class]] <- def ## else, no change } else { which <- match(Class, names(methods)) if(is.null(def)) ## delete the method methods <- methods[-which] else methods[[which]] <- def } } else { ## recursively merge, initializing current if necessary if(is.null(current)) current <- new("MethodsList", argument = as.name(args[2L])) else if(is.function(current)) current <- new("MethodsList", argument = as.name(args[2L]), methods = list(ANY = current)) methods[[Class]] <- Recall(current, signature[-1L], args[-1L], def, cacheOnly) } mlist@allMethods <- methods if(!cacheOnly) mlist@methods <- methods mlist } MethodsListSelect <- ## select the element of a MethodsList object corresponding to the ## actual arguments (as defined in the suppled environment), ## and return the object, extended to include that method if necessary. ## ## Works recursively. At each level finds an argument name from the current `mlist' ## object, and evaluates this argument (if it is not missing), then uses the ## class of the result to select an element of `mlist'. If such an element ## exists and is another `MethodsList' object, `MethodsListSelect' calls itself recursively ## to resolve using further arguments. Matching includes using a default selection or ## a method specifically linked to class `"missing"'. Once a function is found, it ## is returned as the value. If matching fails, NULL is returned. function(f, env, mlist = NULL, fEnv = if(is(fdef, "genericFunction")) environment(fdef) else baseenv(), finalDefault = finalDefaultMethod(mlist), evalArgs = TRUE, useInherited = TRUE, ## supplied when evalArgs is FALSE fdef = getGeneric(f, where = env), # MUST BE SAFE FROM RECUSIVE METHOD SELECTION resetAllowed = TRUE # FALSE when called from selectMethod, .findNextMethod ) { .MlistDeprecated("MethodsListSelect()") if(!resetAllowed) # ensure we restore the real methods for this function resetMlist <- .getMethodsForDispatch(fdef) ## look for call from C dispatch code during another call to MethodsListSelect if(is.null(f)) {} # Recall, not from C else { fMethods <- .getMethodsForDispatch(fdef) if(is.null(mlist) || (evalArgs && is.function(fMethods))) mlist <- fMethods } resetNeeded <- .setIfBase(f, fdef, mlist) # quickly protect against recursion -- see Methods.R if(resetNeeded) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } if(!is(mlist, "MethodsList")) { if(is.function(mlist)) # call to f, inside MethodsListSelect {on.exit(); return(mlist)} if(is.null(f)) # recursive recall of MethodsListSelect stop("invalid method sublist") else if(!is.null(mlist)) # NULL => 1st call to genericFunction stop(gettextf("%f is not a valid generic function: methods list was an object of class %s", sQuote(f), dQuote(class(mlist))), domain = NA) } if(!is.logical(useInherited)) stop(gettextf("%s must be TRUE, FALSE, or a named logical vector of those values; got an object of class %s", sQuote("useInherited"), dQuote(class(useInherited))), domain = NA) if(identical(mlist, .getMethodsForDispatch(fdef))) { resetNeeded <- TRUE ## On the initial call: ## turn off any further method dispatch on this function, to avoid recursive ## loops if f is a function used in MethodsListSelect. ## TODO: Using namespaces in the methods package would eliminate the need for this .setMethodsForDispatch(f, fdef, finalDefault) if(is(mlist, "MethodsList")) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } } argName <- slot(mlist, "argument") arg <- NULL ## => don't use instance-specific inheritance if(evalArgs) { ## check for missing argument. NB: S sense, not that of R base missing() if(missingArg(argName, env, TRUE)) thisClass <- "missing" else { arg <- eval(as.name(argName), env) ## DO use instance-specific inheritance if(missing(arg)) ## S3 weird R code? Bail out! return(finalDefault) thisClass <- .class1(arg) } } else thisClass <- get(as.character(argName), envir = env, inherits = FALSE) if(identical(useInherited, TRUE) || identical(useInherited, FALSE)) thisInherit <- nextUseInherited <- useInherited else { which <- match(as.character(argName), names(useInherited)) if(is.na(which)) { nextUseInherited <- useInherited thisInherit <- TRUE } else { thisInherit <- useInherited[[which]] nextUseInherited <- useInherited[-which] } } fromClass <- thisClass ## will mark the class actually providing the method allMethods <- mlist@allMethods which <- match(thisClass, names(allMethods)) inherited <- is.na(which) selection <- if(inherited) NULL else allMethods[[which]] if(!inherited) { if(is(selection, "function")) { if(is.null(f)) { ## An inherited method at the next level up. ## only the inherited method should be added mlist <- .trimMlist(mlist, fromClass) } value <- mlist ## no change } else { ## recursive call with NULL function name, to allow search to fail & ## to suppress any reset actions. method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef, ) if(is(method, "EmptyMethodsList")) value <- method else { mlist@allMethods[[which]] <- method value <- mlist } } } if(inherited || is(value, "EmptyMethodsList")) { ## direct selection failed at this level or below method <- NULL if(thisInherit) { allSelections <- inheritedSubMethodLists(arg, fromClass, mlist, env) allClasses <- names(allSelections) for(i in seq_along(allSelections)) { selection <- allSelections[[i]] fromClass <- allClasses[[i]] if(is(selection, "function")) method <- selection else if(is(selection, "MethodsList")) { ## go on to try matching further arguments method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef) if(is(method, "EmptyMethodsList")) selection <- method ## recursive selection failed } if(!is(selection, "EmptyMethodsList")) break } } if((is.null(selection) || is(selection, "EmptyMethodsList")) && !is.null(f) && !is.null(finalDefault)) { ## only use the final default method after exhausting all ## other possibilities, at all levels. method <- finalDefault fromClass <- "ANY" } if(is.null(method) || is(method, "EmptyMethodsList")) value <- emptyMethodsList(mlist, thisClass) ## nothing found else { method <- MethodAddCoerce(method, argName, thisClass, fromClass) value <- .insertCachedMethods(mlist, as.character(argName), thisClass, fromClass, method) } } if(!is.null(f)) { ## top level if(is(value, "EmptyMethodsList")) ## selection failed value <- NULL if(resetNeeded) { on.exit() # cancel the restore of the original mlist if(resetAllowed) { if(is.null(value)) resetMlist <- mlist else resetMlist <- value } .setMethodsForDispatch(f, fdef, resetMlist) if(dispatchIsInternal(fdef)) setPrimitiveMethods(f, finalDefault, "set", fdef, resetMlist) } } value } emptyMethodsList <- function(mlist, thisClass = "ANY", sublist = list()) { .MlistDeprecated("emptyMethodsList()") sublist[thisClass] <- list(NULL) new("EmptyMethodsList", argument = mlist@argument, sublist = sublist) } insertMethodInEmptyList <- function(mlist, def) { .MlistDeprecated("insertMethodInEmptyList()") value <- new("MethodsList", argument = mlist@argument) sublist <- mlist@sublist submethods <- sublist[[1L]] if(is.null(submethods)) sublist[[1L]] <- def else sublist[[1L]] <- Recall(submethods, def) value@allMethods <- sublist value } finalDefaultMethod <- ## Return the default method from the generic (it may be NULL, a method object or a primitive. ## this previously searched in a MethodsList object. Once those are gone, the loop should ## be irrelevant except as an error check. function(method) { repeat { if(is.function(method) # <- somewhat liberal, but catches both methods and primitives || is.null(method)) break if(is(method, "MethodsList")) { .MlistDeprecated() method <- slot(method, "methods")[["ANY"]] } else stop(gettextf( "default method must be a method definition, a primitive or NULL: got an object of class %s", dQuote(class(method))), domain = NA) } method } inheritedSubMethodLists <- ## Utility function to match the object to the elements of a methods list. ## ## The function looks only for an inherited match, and only among ## the methods that are not themselves inherited. (Inherited methods when found are ## stored in the session copy of the methods list, but they themselves should not be ## used for finding inherited matches, because an erroneous match could be found depending ## on which methods were previously used. See the detailed discussion of methods.) function(object, thisClass, mlist, ev) { .MlistDeprecated("inheritedSubMethodLists()") methods <- slot(mlist, "methods")## only direct methods defaultMethod <- methods[["ANY"]]## maybe NULL classes <- names(methods) value <- list() if(.identC(thisClass, "missing")) { ## no superclasses for "missing" } else { ## search in the superclasses, but don't use inherited methods ## There are two cases: if thisClass is formally defined & unsealed, use its ## superclasses. Otherwise, look in the subclasses of those classes for ## which methods exist. classDef <- getClassDef(thisClass, ev) useSuperClasses <- !is.null(classDef) && !classDef@sealed if(useSuperClasses) { ## for consistency, order the available methods by ## the ordering of the superclasses of thisClass superClasses <- names(classDef@contains) classes <- superClasses[!is.na(match(superClasses, classes))] for(which in seq_along(classes)) { tryClass <- classes[[which]] ## TODO: There is potential bug here: If the is relation is conditional, ## we should not cache this selection. Needs another trick in the environment ## to FORCE no caching regardless of what happens elsewhere; e.g., storing a ## special object in .Class if(is.null(object) || is(object, tryClass)) { value[[tryClass]] <- methods[[tryClass]] } } } else { for(which in seq_along(classes)) { tryClass <- classes[[which]] tryClassDef <- getClassDef(tryClass, ev) if(!is.null(tryClassDef) && !is.na(match(thisClass, names(tryClassDef@subclasses)))) value[[tryClass]] <- methods[[which]] } } } if(!is.null(defaultMethod)) value[["ANY"]] <- defaultMethod value } matchSignature <- ## Match the signature object (a partially or completely named subset of the ## arguments of `fun', and return a vector of all the classes in the order specified ## by the signature slot of the generic. The classes not specified by `signature ##' will be `"ANY"' in the value. function(signature, fun, where = baseenv()) { if(!is(fun, "genericFunction")) stop(gettextf("trying to match a method signature to an object (of class %s) that is not a generic function", dQuote(class(fun))), domain = NA) anames <- fun@signature if(length(signature) == 0L) return(character()) if(is(signature,"character")) { pkgs <- packageSlot(signature) # includes case of "ObjectsWithPackage" if(is.null(pkgs)) pkgs <- character(length(signature)) else if(length(pkgs) != length(signature)) stop("invalid 'package' slot or attribute, wrong length") sigClasses <- as.character(signature) } else if(is(signature, "list")) { sigClasses <- pkgs <- character(length(signature)) for(i in seq_along(signature)) { cli <- signature[[i]] if(is(cli, "classRepresentation")) { sigClasses[[i]] <- cli@className pkgs[[i]] <- cli@package } else if(is(cli, "character") && length(cli) == 1) { sigClasses[[i]] <- cli pkgi <- packageSlot(cli) if(is.character(pkgi)) pkgs[[i]] <- pkgi } else stop(gettextf("invalid element in a list for \"signature\" argument; element %d is neither a class definition nor a class name", i), domain = NA) } } else stop(gettextf("trying to match a method signature of class %s; expects a list or a character vector", dQuote(class(signature))), domain = NA) if(!identical(where, baseenv())) { ## fill in package information, warn about undefined classes unknown <- !nzchar(pkgs) for(i in seq_along(sigClasses)[unknown]) { cli <- getClassDef(sigClasses[[i]], where) if(!is.null(cli)) { pkgs[[i]] <- cli@package unknown[[i]] <- FALSE } } if(any(unknown)) { unknown <- unique(sigClasses[unknown]) ## coerce(), i.e., setAs() may use *one* unknown class MSG <- if(identical(as.vector(coerce@generic), "coerce") && length(unknown) == 1) message else function(...) warning(..., call. = FALSE) MSG(.renderSignature(fun@generic, signature), sprintf(ngettext(length(unknown), "no definition for class %s", "no definition for classes %s"), paste(dQuote(unknown), collapse = ", ")), domain = NA) } } signature <- as.list(signature) if(length(sigClasses) != length(signature)) stop(gettextf("object to use as a method signature for function %s does not look like a legitimate signature (a vector of single class names): there were %d class names, but %d elements in the signature object", sQuote(fun@generic), length(sigClasses), length(signature)), domain = NA) if(is.null(names(signature))) { which <- seq_along(signature) if(length(which) > length(anames)) stop(gettextf("more elements in the method signature (%d) than in the generic signature (%d) for function %s", length(which), length(anames), sQuote(fun@generic)), domain = NA) } else { ## construct a function call with the same naming pattern & ## values as signature sigList <- signature for(i in seq_along(sigList)) sigList[[i]] <- c(sigClasses[[i]], pkgs[[i]]) fcall <- do.call("call", c("fun", sigList)) ## match the call to the formal signature (usually the formal args) if(identical(anames, formalArgs(fun))) smatch <- match.call(fun, fcall) else { fmatch <- fun ff <- as.list(anames); names(ff) <- anames formals(fmatch, envir = environment(fun)) <- ff smatch <- match.call(fmatch, fcall) } snames <- names(smatch)[-1L] which <- match(snames, anames) ## Assertion: match.call has permuted the args into the order of formal args, ## and carried along the values. Get the supplied classes in that ## order, from the matched args in the call object. if(anyNA(which)) stop(sprintf(ngettext(sum(is.na(which)), "in the method signature for function %s invalid argument name in the signature: %s", "in the method signature for function %s invalid argument names in the signature: %s"), sQuote(fun@generic), paste(snames[is.na(which)], collapse = ", ")), domain = NA) smatch <- smatch[-1] for(i in seq_along(smatch)) { eli <- smatch[[i]] sigClasses[[i]] <- eli[[1]] pkgs[[i]] <- eli[[2]] } } n <- length(anames) value <- rep("ANY", n) valueP <- rep("methods", n) names(value) <- anames value[which] <- sigClasses valueP[which] <- pkgs unspec <- value == "ANY" ## remove the trailing unspecified classes while(n > 1 && unspec[[n]]) n <- n-1 length(value) <- length(valueP) <- n attr(value, "package") <- valueP ## <FIXME> Is there a reason (bootstrapping?) why this ## is not an actual object from class "signature"? ## See .MakeSignature() </FIXME> value } showMlist <- ## Prints the contents of the MethodsList. If `includeDefs' the signatures and the ## corresponding definitions will be printed; otherwise, only the signatures. ## ## If `includeDefs' is `TRUE', the currently known inherited methods are included; ## otherwise, only the directly defined methods. function(mlist, includeDefs = TRUE, inherited = TRUE, classes = NULL, useArgNames = TRUE, printTo = stdout()) { .MlistDeprecated("showMlist()") if(identical(printTo, FALSE)) { tmp <- tempfile() con <- file(tmp, "w") } else con <- printTo object <- linearizeMlist(mlist, inherited) methods <- object@methods signatures <- object@classes args <- object@arguments if(!is.null(classes) && length(signatures)>0) { keep <- !vapply(signatures, function(x, y) all(is.na(match(x, y))), NA, classes) methods <- methods[keep] signatures <- signatures[keep] args <- args[keep] } if(length(methods) == 0) cat(file=con, "<Empty Methods List>\n") else { n <- length(methods) labels <- character(n) if(useArgNames) { for(i in 1L:n) { sigi <- signatures[[i]] labels[[i]] <- paste(args[[i]], " = \"", sigi, "\"", sep = "", collapse = ", ") } } else { for(i in 1L:n) labels[[i]] <- paste(signatures[[i]], collapse = ", ") } for(i in seq_along(methods)) { cat(file=con, (if(includeDefs) "## Signature:" else ""), labels[[i]]) method <- methods[[i]] if(includeDefs) { cat(file=con, ":\n") if(is(method, "MethodDefinition")) ## really an assertion cat(file=con, deparse(method@.Data), sep="\n") else cat(file=con, deparse(method), sep="\n") } if(is(method, "MethodDefinition") && !identical(method@target, method@defined)) { defFrom <- method@defined cat(file = con, if(includeDefs) "##:" else "\n", " (inherited from ", paste(names(defFrom), " = \"", as.character(defFrom), "\"", sep = "", collapse = ", "), ")", if(includeDefs) "\n", sep="") } cat(file=con, "\n") } } if(identical(printTo, FALSE)) { close(con) value <- readLines(tmp) unlink(tmp) value } } promptMethods <- function(f, filename = NULL, methods) { ## Generate information in the style of 'prompt' for the methods of ## the generic named 'f'. ## ## 'filename' can be a logical or NA or the name of a file to print ## to. If it 'FALSE', the methods skeleton is returned, to be ## included in other printing (typically, the output from 'prompt'). escape <- function(txt) gsub("%", "\\\\%", txt) packageString <- "" fdef <- getGeneric(f) if(!isGeneric(f, fdef=fdef)) stop(gettextf("no generic function found corresponding to %s", sQuote(f)), domain = NA) if(missing(methods)) { methods <- findMethods(fdef) ## try making packageString where <- .genEnv(fdef, topenv(parent.frame())) if(!identical(where, .GlobalEnv)) packageString <- sprintf("in Package \\pkg{%s}", getPackageName(where)) } fullName <- utils:::topicName("methods", f) n <- length(methods) labels <- character(n) aliases <- character(n) signatures <- findMethodSignatures(methods = methods, target=TRUE) args <- colnames(signatures) # the *same* for all for(i in seq_len(n)) { sigi <- signatures[i, ] labels[[i]] <- sprintf("\\code{signature(%s)}", paste(sprintf("%s = \"%s\"", args, escape(sigi)), collapse = ", ")) aliases[[i]] <- paste0("\\alias{", utils:::topicName("method", c(f, signatures[i,])), "}") } text <- paste0("\n\\item{", labels, "}{\n%% ~~describe this method here~~\n}") text <- c("\\section{Methods}{\n\\describe{", text, "}}") aliasText <- c(paste0("\\alias{", escape(fullName), "}"), escape(aliases)) if(identical(filename, FALSE)) return(c(aliasText, text)) if(is.null(filename) || identical(filename, TRUE)) filename <- paste0(fullName, ".Rd") Rdtxt <- list(name = paste0("\\name{", fullName, "}"), type = "\\docType{methods}", aliases = aliasText, ## <FIXME> ## Title and description are ok as auto-generated: should ## they be flagged as such (via '~~' which are quite often ## left in by authors)? title = sprintf("\\title{ ~~ Methods for Function \\code{%s} %s ~~}", f, packageString), description = paste0("\\description{\n ~~ Methods for function", " \\code{", f, "} ", sub("^in Package", "in package", packageString), " ~~\n}"), ## </FIXME> "section{Methods}" = text, keywords = c("\\keyword{methods}", "\\keyword{ ~~ other possible keyword(s) ~~ }")) if(is.na(filename)) return(Rdtxt) cat(unlist(Rdtxt), file = filename, sep = "\n") .message("A shell of methods documentation has been written", .fileDesc(filename), ".\n") invisible(filename) } ##' only called from showMlist() above, which has been deprecated in R 3.2.0 (Apr.2015): linearizeMlist <- ## Undo the recursive nature of the methods list, making a list of ## function definitions, with the names of the list being the ## corresponding signatures (designed for printing; for looping over ## the methods, use `listFromMlist' instead). ## ## The function calls itself recursively. `prev' is the previously ## selected class names. ## ## If argument `classes' is provided, only signatures containing one ## of these classes will be included. function(mlist, inherited = TRUE) { methods <- mlist@methods allMethods <- mlist@allMethods if(inherited && length(allMethods) >= length(methods)) { ## anames <- names(allMethods) ## inh <- is.na(match(anames, names(methods))) methods <- allMethods } preC <- function(y, x)c(x,y) # used with lapply below cnames <- names(methods) value <- list() classes <- list() arguments <- list() argname <- as.character(mlist@argument) for(i in seq_along(cnames)) { mi <- methods[[i]] if(is.function(mi)) { value <- c(value, list(mi)) classes <- c(classes, list(cnames[[i]])) arguments <- c(arguments, list(argname)) } else if(is(mi, "MethodsList")) { .MlistDeprecated() mi <- Recall(mi, inherited) value <- c(value, mi@methods) classes <- c(classes, lapply(mi@classes, preC, cnames[[i]])) arguments <- c(arguments, lapply(mi@arguments, preC, argname)) } else warning(gettextf("skipping methods list element %s of unexpected class %s\n\n", paste(cnames[i], collapse = ", "), dQuote(.class1(mi))), domain = NA) } new("LinearMethodsList", methods = value, classes = classes, arguments = arguments) } print.MethodsList <- function(x, ...) showMlist(x) ## In R's own code, this is *only* used in mergeMethods(), deprecated in R 3.2.0 (Apr.2015) listFromMlist <- ## linearizes the MethodsList object into list(sigs, methods); `prefix' is the partial ## signature (a named list of classes) to be prepended to the signatures in this object. ## ## A utility function used to iterate over all the individual methods in the object. function(mlist, prefix = list(), sigs. = TRUE, methods. = TRUE) { methodSlot <- slot(mlist, "methods") mnames <- names(methodSlot) argName <- as.character(slot(mlist, "argument")) sigs <- list() methods <- list() for(i in seq_along(methodSlot)) { thisMethod <- methodSlot[i] thisClass <- mnames[[i]] prefix[[argName]] <- thisClass if(is.function(thisMethod)) { if(sigs.) sigs <- c(sigs, list(prefix)) if(methods.) methods <- c(methods, list(thisMethod)) } else { more <- Recall(thisMethod, prefix) if(sigs.) sigs <- c(sigs, more[[1]]) if(methods.) methods <- c(methods, more[[2]]) } } list(sigs, methods) } .insertCachedMethods <- function(mlist, argName, Class, fromClass, def) { if(is(def, "MethodsList")) { .MlistDeprecated() ## insert all the cached methods in def newArg <- c(argName, as.character(def@argument)) newDefs <- def@allMethods newSigs <- as.list(names(newDefs)) for(j in seq_along(newDefs)) mlist <- Recall(mlist, newArg, c(Class, newSigs[[j]]), fromClass, newDefs[[j]]) } else { def <- .addMethodFrom(def, argName[1L], Class[1L], fromClass) mlist <- insertMethod(mlist, Class, argName, def, TRUE) } mlist } .addMethodFrom <- function(def, arg, Class, fromClass) { if(is(def, "MethodDefinition")) { ## eventually, we may enforce method definition objects ## If not, just leave raw functions alone (NextMethod won't work) def@target[[arg]] <- Class def@defined[[arg]] <- fromClass } def } ## Define a trivial version of asMethodDefinition for bootstrapping. ## The real version requires several class definitions as well as ## methods for as<- asMethodDefinition <- function(def, signature = list(.anyClassName), sealed = FALSE, fdef = def) { if(is.primitive(def) || is(def, "MethodDefinition")) def else { value = new("MethodDefinition") value@.Data <- def classes <- .MakeSignature(new("signature"), def, signature, fdef) value@target <- classes value@defined <- classes value } } .trimMlist <- function(mlist, fromClass) { mlist@methods <- mlist@methods[fromClass] mlist@allMethods <- mlist@allMethods[fromClass] mlist } .noMlistsFlag <- TRUE .noMlists <- function() { ## if this were to be dynamically variable, but ## it can't, IMO ## identical(getOption("noMlists"), TRUE) ## so instead .noMlistsFlag } .MlistDepTable <- new.env() .MlistDeprecated <- function(this = "<default>", instead) { if(is.character(this)) { if(exists(this, envir = .MlistDepTable, inherits = FALSE)) return() else assign(this, TRUE, envir = .MlistDepTable) } msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is deprecated." else if(is.character(this)) gettextf( "%s, along with other use of the \"MethodsList\" metadata objects, is deprecated.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is deprecated.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList. (This warning is shown once per session.)") base::.Deprecated(msg = msg) } .MlistDefunct <- function(this = "<default>", instead) { msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is defunct." else if(is.character(this)) gettextf("%s, along with other use of the \"MethodsList\" metadata objects, is defunct.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is defunct.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList.") base::.Defunct(msg = msg) }
36,574
gpl-2.0
71c4978aaa94135074227729a1d4da375593bdd9
minux/R
src/library/methods/R/MethodsList.R
# File src/library/methods/R/MethodsList.R # Part of the R package, https://www.R-project.org # # Copyright (C) 1995-2016 The R Core Team # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # A copy of the GNU General Public License is available at # https://www.R-project.org/Licenses/ MethodsList <- ## Create a MethodsList object out of the arguments. ## ## Conceptually, this object is a named collection of methods to be ## dispatched when the (first) argument in a function call matches the ## class corresponding to one of the names. A final, unnamed element ## (i.e., with name `""') corresponds to the default method. ## ## The elements can be either a function, or another MethodsList. In ## the second case, this list implies dispatching on the second ## argument to the function using that list, given a selection of this ## element on the first argument. Thus, method dispatching on an ## arbitrary number of arguments is defined. ## ## MethodsList objects are used primarily to dispatch OOP-style ## methods and, in R, to emulate S4-style methods. function(.ArgName, ...) { .MlistDeprecated("MethodsList()") value <- makeMethodsList(list(...)) if(is.name(.ArgName)){} else if(is.character(.ArgName) && length(.ArgName) == 1) .ArgName <- as.name(.ArgName) else stop("invalid first argument: should be the name of the first argument in the dispatch") slot(value, "argument") <- .ArgName value } makeMethodsList <- function(object, level=1) { .MlistDeprecated("makeMethodsList()") mnames <- allNames(object) if(.noMlists()) { keep <- mnames %in% c("", "ANY") mnames <- mnames[keep] object <- object[keep] } value <- new("MethodsList") i <- match("", mnames) if(!is.na(i)) { ## convert to ANY mnames[[i]] <- "ANY" names(object) <- mnames } if(anyDuplicated(mnames)) stop(gettextf("duplicate element names in 'MethodsList' at level %d: %s", level, paste("\"", unique(mnames[duplicated(mnames)]), "\"", collapse=", ")), domain = NA) for(i in seq_along(object)) { eli <- object[[i]] if(is(eli, "function") || is(eli, "MethodsList")) {} else if(is(eli, "list") || is(eli, "named")) object[[i]] <- Recall(eli, NULL, level+1) else stop(gettextf("element %d at level %d (class %s) cannot be interpreted as a function or named list", i, level, dQuote(class(eli))), domain = NA) } slot(value, "methods") <- object value } SignatureMethod <- ## construct a MethodsList object containing (only) this method, corresponding ## to the signature; i.e., such that signature[[1L]] is the match for the first ## argument, signature[[2L]] for the second argument, and so on. The string ## "missing" means a match for a missing argument, and "ANY" means use this as the ## default setting at this level. ## ## The first argument is the argument names to be used for dispatch corresponding to ## the signatures. function(names, signature, definition) { .MlistDeprecated("SignatureMethod()") n <- length(signature) if(n > length(names)) stop("arguments 'names' and 'signature' must have the same length") if(n == 0) return(definition) Class <- signature[[n]] name <- names[[n]] m <- MethodsList(name) slot(m, "methods")[[Class]] <- definition slot(m, "argument") <- as.name(name) SignatureMethod(names[-n], signature[-n], m) } insertMethod <- ## insert the definition `def' into the MethodsList object, `mlist', corresponding to ## the signature, and return the modified MethodsList. function(mlist, signature, args, def, cacheOnly = FALSE) { .MlistDeprecated("insertMethod()") if(.noMlists() && !identical(unique(signature), "ANY")) return(mlist) ## Checks for assertions about valid calls. ## See rev. 1.17 for the code before the assertions added. if(identical(args[1L], "...") && !identical(names(signature), "...")) { if(identical(signature[[1L]], "ANY")) stop(gettextf("inserting method with invalid signature matching argument '...' to class %s", dQuote(signature[[1L]])), domain = NA) args <- args[-1L] signature <- signature[-1L] if(length(signature) == 0L) return(mlist) } if(length(signature) == 0L) stop("inserting method corresponding to empty signature") if(!is(mlist, "MethodsList")) stop(gettextf("inserting method into non-methods-list object (class %s)", dQuote(.class1(mlist))), domain = NA) if(length(args) > 1 && !cacheOnly) mlist <- balanceMethodsList(mlist, args) Class <- signature[[1]] methods <- if(cacheOnly) mlist@allMethods else mlist@methods current <- methods[[Class]] if(is(current, "MethodsList")) { nextArg <- as.character(current@argument) sigArgs <- args n <- length(signature) length(sigArgs) <- n if(is.na(match(nextArg, sigArgs))) { n <- match(nextArg, args) - n if(is.na(n)) { ## not in args eitiher n <- 1 args <- c(args, nextArg) } ## make explicit the trailing ANY's needed signature <- c(signature, rep("ANY", n)) } } if(length(signature) == 1) { if(is.null(current)) { if(!is.null(def)) methods[[Class]] <- def ## else, no change } else { which <- match(Class, names(methods)) if(is.null(def)) ## delete the method methods <- methods[-which] else methods[[which]] <- def } } else { ## recursively merge, initializing current if necessary if(is.null(current)) current <- new("MethodsList", argument = as.name(args[2L])) else if(is.function(current)) current <- new("MethodsList", argument = as.name(args[2L]), methods = list(ANY = current)) methods[[Class]] <- Recall(current, signature[-1L], args[-1L], def, cacheOnly) } mlist@allMethods <- methods if(!cacheOnly) mlist@methods <- methods mlist } MethodsListSelect <- ## select the element of a MethodsList object corresponding to the ## actual arguments (as defined in the suppled environment), ## and return the object, extended to include that method if necessary. ## ## Works recursively. At each level finds an argument name from the current `mlist' ## object, and evaluates this argument (if it is not missing), then uses the ## class of the result to select an element of `mlist'. If such an element ## exists and is another `MethodsList' object, `MethodsListSelect' calls itself recursively ## to resolve using further arguments. Matching includes using a default selection or ## a method specifically linked to class `"missing"'. Once a function is found, it ## is returned as the value. If matching fails, NULL is returned. function(f, env, mlist = NULL, fEnv = if(is(fdef, "genericFunction")) environment(fdef) else baseenv(), finalDefault = finalDefaultMethod(mlist), evalArgs = TRUE, useInherited = TRUE, ## supplied when evalArgs is FALSE fdef = getGeneric(f, where = env), # MUST BE SAFE FROM RECUSIVE METHOD SELECTION resetAllowed = TRUE # FALSE when called from selectMethod, .findNextMethod ) { .MlistDeprecated("MethodsListSelect()") if(!resetAllowed) # ensure we restore the real methods for this function resetMlist <- .getMethodsForDispatch(fdef) ## look for call from C dispatch code during another call to MethodsListSelect if(is.null(f)) {} # Recall, not from C else { fMethods <- .getMethodsForDispatch(fdef) if(is.null(mlist) || (evalArgs && is.function(fMethods))) mlist <- fMethods } resetNeeded <- .setIfBase(f, fdef, mlist) # quickly protect against recursion -- see Methods.R if(resetNeeded) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } if(!is(mlist, "MethodsList")) { if(is.function(mlist)) # call to f, inside MethodsListSelect {on.exit(); return(mlist)} if(is.null(f)) # recursive recall of MethodsListSelect stop("invalid method sublist") else if(!is.null(mlist)) # NULL => 1st call to genericFunction stop(gettextf("%f is not a valid generic function: methods list was an object of class %s", sQuote(f), dQuote(class(mlist))), domain = NA) } if(!is.logical(useInherited)) stop(gettextf("%s must be TRUE, FALSE, or a named logical vector of those values; got an object of class %s", sQuote("useInherited"), dQuote(class(useInherited))), domain = NA) if(identical(mlist, .getMethodsForDispatch(fdef))) { resetNeeded <- TRUE ## On the initial call: ## turn off any further method dispatch on this function, to avoid recursive ## loops if f is a function used in MethodsListSelect. ## TODO: Using namespaces in the methods package would eliminate the need for this .setMethodsForDispatch(f, fdef, finalDefault) if(is(mlist, "MethodsList")) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } } argName <- slot(mlist, "argument") arg <- NULL ## => don't use instance-specific inheritance if(evalArgs) { ## check for missing argument. NB: S sense, not that of R base missing() if(missingArg(argName, env, TRUE)) thisClass <- "missing" else { arg <- eval(as.name(argName), env) ## DO use instance-specific inheritance if(missing(arg)) ## S3 weird R code? Bail out! return(finalDefault) thisClass <- .class1(arg) } } else thisClass <- get(as.character(argName), envir = env, inherits = FALSE) if(identical(useInherited, TRUE) || identical(useInherited, FALSE)) thisInherit <- nextUseInherited <- useInherited else { which <- match(as.character(argName), names(useInherited)) if(is.na(which)) { nextUseInherited <- useInherited thisInherit <- TRUE } else { thisInherit <- useInherited[[which]] nextUseInherited <- useInherited[-which] } } fromClass <- thisClass ## will mark the class actually providing the method allMethods <- mlist@allMethods which <- match(thisClass, names(allMethods)) inherited <- is.na(which) selection <- if(inherited) NULL else allMethods[[which]] if(!inherited) { if(is(selection, "function")) { if(is.null(f)) { ## An inherited method at the next level up. ## only the inherited method should be added mlist <- .trimMlist(mlist, fromClass) } value <- mlist ## no change } else { ## recursive call with NULL function name, to allow search to fail & ## to suppress any reset actions. method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef, ) if(is(method, "EmptyMethodsList")) value <- method else { mlist@allMethods[[which]] <- method value <- mlist } } } if(inherited || is(value, "EmptyMethodsList")) { ## direct selection failed at this level or below method <- NULL if(thisInherit) { allSelections <- inheritedSubMethodLists(arg, fromClass, mlist, env) allClasses <- names(allSelections) for(i in seq_along(allSelections)) { selection <- allSelections[[i]] fromClass <- allClasses[[i]] if(is(selection, "function")) method <- selection else if(is(selection, "MethodsList")) { ## go on to try matching further arguments method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef) if(is(method, "EmptyMethodsList")) selection <- method ## recursive selection failed } if(!is(selection, "EmptyMethodsList")) break } } if((is.null(selection) || is(selection, "EmptyMethodsList")) && !is.null(f) && !is.null(finalDefault)) { ## only use the final default method after exhausting all ## other possibilities, at all levels. method <- finalDefault fromClass <- "ANY" } if(is.null(method) || is(method, "EmptyMethodsList")) value <- emptyMethodsList(mlist, thisClass) ## nothing found else { method <- MethodAddCoerce(method, argName, thisClass, fromClass) value <- .insertCachedMethods(mlist, as.character(argName), thisClass, fromClass, method) } } if(!is.null(f)) { ## top level if(is(value, "EmptyMethodsList")) ## selection failed value <- NULL if(resetNeeded) { on.exit() # cancel the restore of the original mlist if(resetAllowed) { if(is.null(value)) resetMlist <- mlist else resetMlist <- value } .setMethodsForDispatch(f, fdef, resetMlist) if(dispatchIsInternal(fdef)) setPrimitiveMethods(f, finalDefault, "set", fdef, resetMlist) } } value } emptyMethodsList <- function(mlist, thisClass = "ANY", sublist = list()) { .MlistDeprecated("emptyMethodsList()") sublist[thisClass] <- list(NULL) new("EmptyMethodsList", argument = mlist@argument, sublist = sublist) } insertMethodInEmptyList <- function(mlist, def) { .MlistDeprecated("insertMethodInEmptyList()") value <- new("MethodsList", argument = mlist@argument) sublist <- mlist@sublist submethods <- sublist[[1L]] if(is.null(submethods)) sublist[[1L]] <- def else sublist[[1L]] <- Recall(submethods, def) value@allMethods <- sublist value } finalDefaultMethod <- ## Return the default method from the generic (it may be NULL, a method object or a primitive. ## this previously searched in a MethodsList object. Once those are gone, the loop should ## be irrelevant except as an error check. function(method) { repeat { if(is.function(method) # <- somewhat liberal, but catches both methods and primitives || is.null(method)) break if(is(method, "MethodsList")) { .MlistDeprecated() method <- slot(method, "methods")[["ANY"]] } else stop(gettextf( "default method must be a method definition, a primitive or NULL: got an object of class %s", dQuote(class(method))), domain = NA) } method } inheritedSubMethodLists <- ## Utility function to match the object to the elements of a methods list. ## ## The function looks only for an inherited match, and only among ## the methods that are not themselves inherited. (Inherited methods when found are ## stored in the session copy of the methods list, but they themselves should not be ## used for finding inherited matches, because an erroneous match could be found depending ## on which methods were previously used. See the detailed discussion of methods.) function(object, thisClass, mlist, ev) { .MlistDeprecated("inheritedSubMethodLists()") methods <- slot(mlist, "methods")## only direct methods defaultMethod <- methods[["ANY"]]## maybe NULL classes <- names(methods) value <- list() if(.identC(thisClass, "missing")) { ## no superclasses for "missing" } else { ## search in the superclasses, but don't use inherited methods ## There are two cases: if thisClass is formally defined & unsealed, use its ## superclasses. Otherwise, look in the subclasses of those classes for ## which methods exist. classDef <- getClassDef(thisClass, ev) useSuperClasses <- !is.null(classDef) && !classDef@sealed if(useSuperClasses) { ## for consistency, order the available methods by ## the ordering of the superclasses of thisClass superClasses <- names(classDef@contains) classes <- superClasses[!is.na(match(superClasses, classes))] for(which in seq_along(classes)) { tryClass <- classes[[which]] ## TODO: There is potential bug here: If the is relation is conditional, ## we should not cache this selection. Needs another trick in the environment ## to FORCE no caching regardless of what happens elsewhere; e.g., storing a ## special object in .Class if(is.null(object) || is(object, tryClass)) { value[[tryClass]] <- methods[[tryClass]] } } } else { for(which in seq_along(classes)) { tryClass <- classes[[which]] tryClassDef <- getClassDef(tryClass, ev) if(!is.null(tryClassDef) && !is.na(match(thisClass, names(tryClassDef@subclasses)))) value[[tryClass]] <- methods[[which]] } } } if(!is.null(defaultMethod)) value[["ANY"]] <- defaultMethod value } matchSignature <- ## Match the signature object (a partially or completely named subset of the ## arguments of `fun', and return a vector of all the classes in the order specified ## by the signature slot of the generic. The classes not specified by `signature ##' will be `"ANY"' in the value. function(signature, fun, where = baseenv()) { if(!is(fun, "genericFunction")) stop(gettextf("trying to match a method signature to an object (of class %s) that is not a generic function", dQuote(class(fun))), domain = NA) anames <- fun@signature if(length(signature) == 0L) return(character()) if(is(signature,"character")) { pkgs <- packageSlot(signature) # includes case of "ObjectsWithPackage" if(is.null(pkgs)) pkgs <- character(length(signature)) else if(length(pkgs) != length(signature)) stop("invalid 'package' slot or attribute, wrong length") sigClasses <- as.character(signature) } else if(is(signature, "list")) { sigClasses <- pkgs <- character(length(signature)) for(i in seq_along(signature)) { cli <- signature[[i]] if(is(cli, "classRepresentation")) { sigClasses[[i]] <- cli@className pkgs[[i]] <- cli@package } else if(is(cli, "character") && length(cli) == 1) { sigClasses[[i]] <- cli pkgi <- packageSlot(cli) if(is.character(pkgi)) pkgs[[i]] <- pkgi } else stop(gettextf("invalid element in a list for \"signature\" argument; element %d is neither a class definition nor a class name", i), domain = NA) } } else stop(gettextf("trying to match a method signature of class %s; expects a list or a character vector", dQuote(class(signature))), domain = NA) if(!identical(where, baseenv())) { ## fill in package information, warn about undefined classes unknown <- !nzchar(pkgs) for(i in seq_along(sigClasses)[unknown]) { cli <- getClassDef(sigClasses[[i]], where) if(!is.null(cli)) { pkgs[[i]] <- cli@package unknown[[i]] <- FALSE } } if(any(unknown)) { unknown <- unique(sigClasses[unknown]) ## coerce(), i.e., setAs() may use *one* unknown class MSG <- if(identical(as.vector(coerce@generic), "coerce") && length(unknown) == 1) message else function(...) warning(..., call. = FALSE) MSG(.renderSignature(fun@generic, signature), sprintf(ngettext(length(unknown), "no definition for class %s", "no definition for classes %s"), paste(dQuote(unknown), collapse = ", ")), domain = NA) } } signature <- as.list(signature) if(length(sigClasses) != length(signature)) stop(gettextf("object to use as a method signature for function %s does not look like a legitimate signature (a vector of single class names): there were %d class names, but %d elements in the signature object", sQuote(fun@generic), length(sigClasses), length(signature)), domain = NA) if(is.null(names(signature))) { which <- seq_along(signature) if(length(which) > length(anames)) stop(gettextf("more elements in the method signature (%d) than in the generic signature (%d) for function %s", length(which), length(anames), sQuote(fun@generic)), domain = NA) } else { ## construct a function call with the same naming pattern & ## values as signature sigList <- signature for(i in seq_along(sigList)) sigList[[i]] <- c(sigClasses[[i]], pkgs[[i]]) fcall <- do.call("call", c("fun", sigList)) ## match the call to the formal signature (usually the formal args) if(identical(anames, formalArgs(fun))) smatch <- match.call(fun, fcall) else { fmatch <- fun ff <- as.list(anames); names(ff) <- anames formals(fmatch, envir = environment(fun)) <- ff smatch <- match.call(fmatch, fcall) } snames <- names(smatch)[-1L] which <- match(snames, anames) ## Assertion: match.call has permuted the args into the order of formal args, ## and carried along the values. Get the supplied classes in that ## order, from the matched args in the call object. if(anyNA(which)) stop(sprintf(ngettext(sum(is.na(which)), "in the method signature for function %s invalid argument name in the signature: %s", "in the method signature for function %s invalid argument names in the signature: %s"), sQuote(fun@generic), paste(snames[is.na(which)], collapse = ", ")), domain = NA) smatch <- smatch[-1] for(i in seq_along(smatch)) { eli <- smatch[[i]] sigClasses[[i]] <- eli[[1]] pkgs[[i]] <- eli[[2]] } } n <- length(anames) value <- rep("ANY", n) valueP <- rep("methods", n) names(value) <- anames value[which] <- sigClasses valueP[which] <- pkgs unspec <- value == "ANY" ## remove the trailing unspecified classes while(n > 1 && unspec[[n]]) n <- n-1 length(value) <- length(valueP) <- n attr(value, "package") <- valueP ## <FIXME> Is there a reason (bootstrapping?) why this ## is not an actual object from class "signature"? ## See .MakeSignature() </FIXME> value } showMlist <- ## Prints the contents of the MethodsList. If `includeDefs' the signatures and the ## corresponding definitions will be printed; otherwise, only the signatures. ## ## If `includeDefs' is `TRUE', the currently known inherited methods are included; ## otherwise, only the directly defined methods. function(mlist, includeDefs = TRUE, inherited = TRUE, classes = NULL, useArgNames = TRUE, printTo = stdout()) { .MlistDeprecated("showMlist()") if(identical(printTo, FALSE)) { tmp <- tempfile() con <- file(tmp, "w") } else con <- printTo object <- linearizeMlist(mlist, inherited) methods <- object@methods signatures <- object@classes args <- object@arguments if(!is.null(classes) && length(signatures)>0) { keep <- !vapply(signatures, function(x, y) all(is.na(match(x, y))), NA, classes) methods <- methods[keep] signatures <- signatures[keep] args <- args[keep] } if(length(methods) == 0) cat(file=con, "<Empty Methods List>\n") else { n <- length(methods) labels <- character(n) if(useArgNames) { for(i in 1L:n) { sigi <- signatures[[i]] labels[[i]] <- paste(args[[i]], " = \"", sigi, "\"", sep = "", collapse = ", ") } } else { for(i in 1L:n) labels[[i]] <- paste(signatures[[i]], collapse = ", ") } for(i in seq_along(methods)) { cat(file=con, (if(includeDefs) "## Signature:" else ""), labels[[i]]) method <- methods[[i]] if(includeDefs) { cat(file=con, ":\n") if(is(method, "MethodDefinition")) ## really an assertion cat(file=con, deparse(method@.Data), sep="\n") else cat(file=con, deparse(method), sep="\n") } if(is(method, "MethodDefinition") && !identical(method@target, method@defined)) { defFrom <- method@defined cat(file = con, if(includeDefs) "##:" else "\n", " (inherited from ", paste(names(defFrom), " = \"", as.character(defFrom), "\"", sep = "", collapse = ", "), ")", if(includeDefs) "\n", sep="") } cat(file=con, "\n") } } if(identical(printTo, FALSE)) { close(con) value <- readLines(tmp) unlink(tmp) value } } promptMethods <- function(f, filename = NULL, methods) { ## Generate information in the style of 'prompt' for the methods of ## the generic named 'f'. ## ## 'filename' can be a logical or NA or the name of a file to print ## to. If it 'FALSE', the methods skeleton is returned, to be ## included in other printing (typically, the output from 'prompt'). escape <- function(txt) gsub("%", "\\\\%", txt) packageString <- "" fdef <- getGeneric(f) if(!isGeneric(f, fdef=fdef)) stop(gettextf("no generic function found corresponding to %s", sQuote(f)), domain = NA) if(missing(methods)) { methods <- findMethods(fdef) ## try making packageString where <- .genEnv(fdef, topenv(parent.frame())) if(!identical(where, .GlobalEnv)) packageString <- sprintf("in Package \\pkg{%s}", getPackageName(where)) } fullName <- utils:::topicName("methods", f) n <- length(methods) labels <- character(n) aliases <- character(n) signatures <- findMethodSignatures(methods = methods, target=TRUE) args <- colnames(signatures) # the *same* for all for(i in seq_len(n)) { sigi <- signatures[i, ] labels[[i]] <- sprintf("\\code{signature(%s)}", paste(sprintf("%s = \"%s\"", args, escape(sigi)), collapse = ", ")) aliases[[i]] <- paste0("\\alias{", utils:::topicName("method", c(f, signatures[i,])), "}") } text <- paste0("\n\\item{", labels, "}{\n%% ~~describe this method here~~\n}") text <- c("\\section{Methods}{\n\\describe{", text, "}}") aliasText <- c(paste0("\\alias{", escape(fullName), "}"), escape(aliases)) if(identical(filename, FALSE)) return(c(aliasText, text)) if(is.null(filename) || identical(filename, TRUE)) filename <- paste0(fullName, ".Rd") Rdtxt <- list(name = paste0("\\name{", fullName, "}"), type = "\\docType{methods}", aliases = aliasText, ## <FIXME> ## Title and description are ok as auto-generated: should ## they be flagged as such (via '~~' which are quite often ## left in by authors)? title = sprintf("\\title{ ~~ Methods for Function \\code{%s} %s ~~}", f, packageString), description = paste0("\\description{\n ~~ Methods for function", " \\code{", f, "} ", sub("^in Package", "in package", packageString), " ~~\n}"), ## </FIXME> "section{Methods}" = text, keywords = c("\\keyword{methods}", "\\keyword{ ~~ other possible keyword(s) ~~ }")) if(is.na(filename)) return(Rdtxt) cat(unlist(Rdtxt), file = filename, sep = "\n") .message("A shell of methods documentation has been written", .fileDesc(filename), ".\n") invisible(filename) } ##' only called from showMlist() above, which has been deprecated in R 3.2.0 (Apr.2015): linearizeMlist <- ## Undo the recursive nature of the methods list, making a list of ## function definitions, with the names of the list being the ## corresponding signatures (designed for printing; for looping over ## the methods, use `listFromMlist' instead). ## ## The function calls itself recursively. `prev' is the previously ## selected class names. ## ## If argument `classes' is provided, only signatures containing one ## of these classes will be included. function(mlist, inherited = TRUE) { methods <- mlist@methods allMethods <- mlist@allMethods if(inherited && length(allMethods) >= length(methods)) { ## anames <- names(allMethods) ## inh <- is.na(match(anames, names(methods))) methods <- allMethods } preC <- function(y, x)c(x,y) # used with lapply below cnames <- names(methods) value <- list() classes <- list() arguments <- list() argname <- as.character(mlist@argument) for(i in seq_along(cnames)) { mi <- methods[[i]] if(is.function(mi)) { value <- c(value, list(mi)) classes <- c(classes, list(cnames[[i]])) arguments <- c(arguments, list(argname)) } else if(is(mi, "MethodsList")) { .MlistDeprecated() mi <- Recall(mi, inherited) value <- c(value, mi@methods) classes <- c(classes, lapply(mi@classes, preC, cnames[[i]])) arguments <- c(arguments, lapply(mi@arguments, preC, argname)) } else warning(gettextf("skipping methods list element %s of unexpected class %s\n\n", paste(cnames[i], collapse = ", "), dQuote(.class1(mi))), domain = NA) } new("LinearMethodsList", methods = value, classes = classes, arguments = arguments) } print.MethodsList <- function(x, ...) showMlist(x) ## In R's own code, this is *only* used in mergeMethods(), deprecated in R 3.2.0 (Apr.2015) listFromMlist <- ## linearizes the MethodsList object into list(sigs, methods); `prefix' is the partial ## signature (a named list of classes) to be prepended to the signatures in this object. ## ## A utility function used to iterate over all the individual methods in the object. function(mlist, prefix = list(), sigs. = TRUE, methods. = TRUE) { methodSlot <- slot(mlist, "methods") mnames <- names(methodSlot) argName <- as.character(slot(mlist, "argument")) sigs <- list() methods <- list() for(i in seq_along(methodSlot)) { thisMethod <- methodSlot[i] thisClass <- mnames[[i]] prefix[[argName]] <- thisClass if(is.function(thisMethod)) { if(sigs.) sigs <- c(sigs, list(prefix)) if(methods.) methods <- c(methods, list(thisMethod)) } else { more <- Recall(thisMethod, prefix) if(sigs.) sigs <- c(sigs, more[[1]]) if(methods.) methods <- c(methods, more[[2]]) } } list(sigs, methods) } .insertCachedMethods <- function(mlist, argName, Class, fromClass, def) { if(is(def, "MethodsList")) { .MlistDeprecated() ## insert all the cached methods in def newArg <- c(argName, as.character(def@argument)) newDefs <- def@allMethods newSigs <- as.list(names(newDefs)) for(j in seq_along(newDefs)) mlist <- Recall(mlist, newArg, c(Class, newSigs[[j]]), fromClass, newDefs[[j]]) } else { def <- .addMethodFrom(def, argName[1L], Class[1L], fromClass) mlist <- insertMethod(mlist, Class, argName, def, TRUE) } mlist } .addMethodFrom <- function(def, arg, Class, fromClass) { if(is(def, "MethodDefinition")) { ## eventually, we may enforce method definition objects ## If not, just leave raw functions alone (NextMethod won't work) def@target[[arg]] <- Class def@defined[[arg]] <- fromClass } def } ## Define a trivial version of asMethodDefinition for bootstrapping. ## The real version requires several class definitions as well as ## methods for as<- asMethodDefinition <- function(def, signature = list(.anyClassName), sealed = FALSE, fdef = def) { if(is.primitive(def) || is(def, "MethodDefinition")) def else { value = new("MethodDefinition") value@.Data <- def classes <- .MakeSignature(new("signature"), def, signature, fdef) value@target <- classes value@defined <- classes value } } .trimMlist <- function(mlist, fromClass) { mlist@methods <- mlist@methods[fromClass] mlist@allMethods <- mlist@allMethods[fromClass] mlist } .noMlistsFlag <- TRUE .noMlists <- function() { ## if this were to be dynamically variable, but ## it can't, IMO ## identical(getOption("noMlists"), TRUE) ## so instead .noMlistsFlag } .MlistDepTable <- new.env() .MlistDeprecated <- function(this = "<default>", instead) { if(is.character(this)) { if(exists(this, envir = .MlistDepTable, inherits = FALSE)) return() else assign(this, TRUE, envir = .MlistDepTable) } msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is deprecated." else if(is.character(this)) gettextf( "%s, along with other use of the \"MethodsList\" metadata objects, is deprecated.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is deprecated.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList. (This warning is shown once per session.)") base::.Deprecated(msg = msg) } .MlistDefunct <- function(this = "<default>", instead) { msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is defunct." else if(is.character(this)) gettextf("%s, along with other use of the \"MethodsList\" metadata objects, is defunct.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is defunct.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList.") base::.Defunct(msg = msg) }
36,574
gpl-2.0
2610ec21896dc44d63a9b7c3b1e6b541426da9e3
BEAST2-Dev/codonmodels
perftest/pipeline/EvolerUtils.R
# evolver ### evolver.out # Note: evolver tree uses the same format as APE tree #evo.out <- readLines(paste0("t",n.taxa,".out.txt")) # return a list of true sequences at internal nodes simulated by evolver. # list names are the internal node index. getSeqsEvoOut <- function(out.file="ancestral.txt", n.taxa=NULL, nod.name="node[0-9]+", genetic.code="universal") { require(tidyverse) evo.anc <- readLines(out.file) # extract node map nod.map <- evo.anc[grepl("[0-9]+\\.\\.[0-9]+", evo.anc)] # "33..34 34..35 " # extract states anc.tru <- evo.anc[grepl(paste0("^",nod.name), evo.anc)] # "^node[0-9]+" if (!is.null(n.taxa)) stopifnot(length(anc.tru) == n.taxa-1) nod.names <- gsub(paste0("^(",nod.name,").*"), "\\1", anc.tru) # "^(node[0-9]+).*" seqs <- gsub(paste0("^(",nod.name,")\\s+(.*)"), "\\2", anc.tru) # "^(node[0-9]+)\\s+(.*)" # rm spaces seqs <- gsub("\\s+", "", seqs) states <- lapply(seqs, seqToStates, genetic.code=genetic.code) # internal nodes index nod.idx <- gsub("^node", "", nod.names) names(states) <- as.character(nod.idx) # parse edges: parent node .. child edges <- nod.map %>% str_split("\\s+") %>% unlist %>% enframe(name = NULL) %>% # suppress warning becasue of blank spaces separate(value, c("parent", "child"), fill="right") %>% drop_na # branches == 2 * internal nodes stopifnot(nrow(edges) == 2*length(states)) # add edges states[["edges"]] <- edges return(states) }
1,492
lgpl-2.1
ffe69b4399e92ba696b8f08c652300325bc0b014
mtennekes/tmap
examples/tmap_format.R
# available formats tmap_format() # create option list to be used as a new format World_small <- tmap_format("World") World_small$scale <- 2 # add format tmap_format_add(World_small, name = "World_small") # observe that World_small is successfully added: tmap_format() data(World) qtm(World, fill="HPI", format="World_small")
331
gpl-3.0
71c4978aaa94135074227729a1d4da375593bdd9
kmillar/cxxr
src/library/methods/R/MethodsList.R
# File src/library/methods/R/MethodsList.R # Part of the R package, https://www.R-project.org # # Copyright (C) 1995-2016 The R Core Team # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # A copy of the GNU General Public License is available at # https://www.R-project.org/Licenses/ MethodsList <- ## Create a MethodsList object out of the arguments. ## ## Conceptually, this object is a named collection of methods to be ## dispatched when the (first) argument in a function call matches the ## class corresponding to one of the names. A final, unnamed element ## (i.e., with name `""') corresponds to the default method. ## ## The elements can be either a function, or another MethodsList. In ## the second case, this list implies dispatching on the second ## argument to the function using that list, given a selection of this ## element on the first argument. Thus, method dispatching on an ## arbitrary number of arguments is defined. ## ## MethodsList objects are used primarily to dispatch OOP-style ## methods and, in R, to emulate S4-style methods. function(.ArgName, ...) { .MlistDeprecated("MethodsList()") value <- makeMethodsList(list(...)) if(is.name(.ArgName)){} else if(is.character(.ArgName) && length(.ArgName) == 1) .ArgName <- as.name(.ArgName) else stop("invalid first argument: should be the name of the first argument in the dispatch") slot(value, "argument") <- .ArgName value } makeMethodsList <- function(object, level=1) { .MlistDeprecated("makeMethodsList()") mnames <- allNames(object) if(.noMlists()) { keep <- mnames %in% c("", "ANY") mnames <- mnames[keep] object <- object[keep] } value <- new("MethodsList") i <- match("", mnames) if(!is.na(i)) { ## convert to ANY mnames[[i]] <- "ANY" names(object) <- mnames } if(anyDuplicated(mnames)) stop(gettextf("duplicate element names in 'MethodsList' at level %d: %s", level, paste("\"", unique(mnames[duplicated(mnames)]), "\"", collapse=", ")), domain = NA) for(i in seq_along(object)) { eli <- object[[i]] if(is(eli, "function") || is(eli, "MethodsList")) {} else if(is(eli, "list") || is(eli, "named")) object[[i]] <- Recall(eli, NULL, level+1) else stop(gettextf("element %d at level %d (class %s) cannot be interpreted as a function or named list", i, level, dQuote(class(eli))), domain = NA) } slot(value, "methods") <- object value } SignatureMethod <- ## construct a MethodsList object containing (only) this method, corresponding ## to the signature; i.e., such that signature[[1L]] is the match for the first ## argument, signature[[2L]] for the second argument, and so on. The string ## "missing" means a match for a missing argument, and "ANY" means use this as the ## default setting at this level. ## ## The first argument is the argument names to be used for dispatch corresponding to ## the signatures. function(names, signature, definition) { .MlistDeprecated("SignatureMethod()") n <- length(signature) if(n > length(names)) stop("arguments 'names' and 'signature' must have the same length") if(n == 0) return(definition) Class <- signature[[n]] name <- names[[n]] m <- MethodsList(name) slot(m, "methods")[[Class]] <- definition slot(m, "argument") <- as.name(name) SignatureMethod(names[-n], signature[-n], m) } insertMethod <- ## insert the definition `def' into the MethodsList object, `mlist', corresponding to ## the signature, and return the modified MethodsList. function(mlist, signature, args, def, cacheOnly = FALSE) { .MlistDeprecated("insertMethod()") if(.noMlists() && !identical(unique(signature), "ANY")) return(mlist) ## Checks for assertions about valid calls. ## See rev. 1.17 for the code before the assertions added. if(identical(args[1L], "...") && !identical(names(signature), "...")) { if(identical(signature[[1L]], "ANY")) stop(gettextf("inserting method with invalid signature matching argument '...' to class %s", dQuote(signature[[1L]])), domain = NA) args <- args[-1L] signature <- signature[-1L] if(length(signature) == 0L) return(mlist) } if(length(signature) == 0L) stop("inserting method corresponding to empty signature") if(!is(mlist, "MethodsList")) stop(gettextf("inserting method into non-methods-list object (class %s)", dQuote(.class1(mlist))), domain = NA) if(length(args) > 1 && !cacheOnly) mlist <- balanceMethodsList(mlist, args) Class <- signature[[1]] methods <- if(cacheOnly) mlist@allMethods else mlist@methods current <- methods[[Class]] if(is(current, "MethodsList")) { nextArg <- as.character(current@argument) sigArgs <- args n <- length(signature) length(sigArgs) <- n if(is.na(match(nextArg, sigArgs))) { n <- match(nextArg, args) - n if(is.na(n)) { ## not in args eitiher n <- 1 args <- c(args, nextArg) } ## make explicit the trailing ANY's needed signature <- c(signature, rep("ANY", n)) } } if(length(signature) == 1) { if(is.null(current)) { if(!is.null(def)) methods[[Class]] <- def ## else, no change } else { which <- match(Class, names(methods)) if(is.null(def)) ## delete the method methods <- methods[-which] else methods[[which]] <- def } } else { ## recursively merge, initializing current if necessary if(is.null(current)) current <- new("MethodsList", argument = as.name(args[2L])) else if(is.function(current)) current <- new("MethodsList", argument = as.name(args[2L]), methods = list(ANY = current)) methods[[Class]] <- Recall(current, signature[-1L], args[-1L], def, cacheOnly) } mlist@allMethods <- methods if(!cacheOnly) mlist@methods <- methods mlist } MethodsListSelect <- ## select the element of a MethodsList object corresponding to the ## actual arguments (as defined in the suppled environment), ## and return the object, extended to include that method if necessary. ## ## Works recursively. At each level finds an argument name from the current `mlist' ## object, and evaluates this argument (if it is not missing), then uses the ## class of the result to select an element of `mlist'. If such an element ## exists and is another `MethodsList' object, `MethodsListSelect' calls itself recursively ## to resolve using further arguments. Matching includes using a default selection or ## a method specifically linked to class `"missing"'. Once a function is found, it ## is returned as the value. If matching fails, NULL is returned. function(f, env, mlist = NULL, fEnv = if(is(fdef, "genericFunction")) environment(fdef) else baseenv(), finalDefault = finalDefaultMethod(mlist), evalArgs = TRUE, useInherited = TRUE, ## supplied when evalArgs is FALSE fdef = getGeneric(f, where = env), # MUST BE SAFE FROM RECUSIVE METHOD SELECTION resetAllowed = TRUE # FALSE when called from selectMethod, .findNextMethod ) { .MlistDeprecated("MethodsListSelect()") if(!resetAllowed) # ensure we restore the real methods for this function resetMlist <- .getMethodsForDispatch(fdef) ## look for call from C dispatch code during another call to MethodsListSelect if(is.null(f)) {} # Recall, not from C else { fMethods <- .getMethodsForDispatch(fdef) if(is.null(mlist) || (evalArgs && is.function(fMethods))) mlist <- fMethods } resetNeeded <- .setIfBase(f, fdef, mlist) # quickly protect against recursion -- see Methods.R if(resetNeeded) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } if(!is(mlist, "MethodsList")) { if(is.function(mlist)) # call to f, inside MethodsListSelect {on.exit(); return(mlist)} if(is.null(f)) # recursive recall of MethodsListSelect stop("invalid method sublist") else if(!is.null(mlist)) # NULL => 1st call to genericFunction stop(gettextf("%f is not a valid generic function: methods list was an object of class %s", sQuote(f), dQuote(class(mlist))), domain = NA) } if(!is.logical(useInherited)) stop(gettextf("%s must be TRUE, FALSE, or a named logical vector of those values; got an object of class %s", sQuote("useInherited"), dQuote(class(useInherited))), domain = NA) if(identical(mlist, .getMethodsForDispatch(fdef))) { resetNeeded <- TRUE ## On the initial call: ## turn off any further method dispatch on this function, to avoid recursive ## loops if f is a function used in MethodsListSelect. ## TODO: Using namespaces in the methods package would eliminate the need for this .setMethodsForDispatch(f, fdef, finalDefault) if(is(mlist, "MethodsList")) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } } argName <- slot(mlist, "argument") arg <- NULL ## => don't use instance-specific inheritance if(evalArgs) { ## check for missing argument. NB: S sense, not that of R base missing() if(missingArg(argName, env, TRUE)) thisClass <- "missing" else { arg <- eval(as.name(argName), env) ## DO use instance-specific inheritance if(missing(arg)) ## S3 weird R code? Bail out! return(finalDefault) thisClass <- .class1(arg) } } else thisClass <- get(as.character(argName), envir = env, inherits = FALSE) if(identical(useInherited, TRUE) || identical(useInherited, FALSE)) thisInherit <- nextUseInherited <- useInherited else { which <- match(as.character(argName), names(useInherited)) if(is.na(which)) { nextUseInherited <- useInherited thisInherit <- TRUE } else { thisInherit <- useInherited[[which]] nextUseInherited <- useInherited[-which] } } fromClass <- thisClass ## will mark the class actually providing the method allMethods <- mlist@allMethods which <- match(thisClass, names(allMethods)) inherited <- is.na(which) selection <- if(inherited) NULL else allMethods[[which]] if(!inherited) { if(is(selection, "function")) { if(is.null(f)) { ## An inherited method at the next level up. ## only the inherited method should be added mlist <- .trimMlist(mlist, fromClass) } value <- mlist ## no change } else { ## recursive call with NULL function name, to allow search to fail & ## to suppress any reset actions. method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef, ) if(is(method, "EmptyMethodsList")) value <- method else { mlist@allMethods[[which]] <- method value <- mlist } } } if(inherited || is(value, "EmptyMethodsList")) { ## direct selection failed at this level or below method <- NULL if(thisInherit) { allSelections <- inheritedSubMethodLists(arg, fromClass, mlist, env) allClasses <- names(allSelections) for(i in seq_along(allSelections)) { selection <- allSelections[[i]] fromClass <- allClasses[[i]] if(is(selection, "function")) method <- selection else if(is(selection, "MethodsList")) { ## go on to try matching further arguments method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef) if(is(method, "EmptyMethodsList")) selection <- method ## recursive selection failed } if(!is(selection, "EmptyMethodsList")) break } } if((is.null(selection) || is(selection, "EmptyMethodsList")) && !is.null(f) && !is.null(finalDefault)) { ## only use the final default method after exhausting all ## other possibilities, at all levels. method <- finalDefault fromClass <- "ANY" } if(is.null(method) || is(method, "EmptyMethodsList")) value <- emptyMethodsList(mlist, thisClass) ## nothing found else { method <- MethodAddCoerce(method, argName, thisClass, fromClass) value <- .insertCachedMethods(mlist, as.character(argName), thisClass, fromClass, method) } } if(!is.null(f)) { ## top level if(is(value, "EmptyMethodsList")) ## selection failed value <- NULL if(resetNeeded) { on.exit() # cancel the restore of the original mlist if(resetAllowed) { if(is.null(value)) resetMlist <- mlist else resetMlist <- value } .setMethodsForDispatch(f, fdef, resetMlist) if(dispatchIsInternal(fdef)) setPrimitiveMethods(f, finalDefault, "set", fdef, resetMlist) } } value } emptyMethodsList <- function(mlist, thisClass = "ANY", sublist = list()) { .MlistDeprecated("emptyMethodsList()") sublist[thisClass] <- list(NULL) new("EmptyMethodsList", argument = mlist@argument, sublist = sublist) } insertMethodInEmptyList <- function(mlist, def) { .MlistDeprecated("insertMethodInEmptyList()") value <- new("MethodsList", argument = mlist@argument) sublist <- mlist@sublist submethods <- sublist[[1L]] if(is.null(submethods)) sublist[[1L]] <- def else sublist[[1L]] <- Recall(submethods, def) value@allMethods <- sublist value } finalDefaultMethod <- ## Return the default method from the generic (it may be NULL, a method object or a primitive. ## this previously searched in a MethodsList object. Once those are gone, the loop should ## be irrelevant except as an error check. function(method) { repeat { if(is.function(method) # <- somewhat liberal, but catches both methods and primitives || is.null(method)) break if(is(method, "MethodsList")) { .MlistDeprecated() method <- slot(method, "methods")[["ANY"]] } else stop(gettextf( "default method must be a method definition, a primitive or NULL: got an object of class %s", dQuote(class(method))), domain = NA) } method } inheritedSubMethodLists <- ## Utility function to match the object to the elements of a methods list. ## ## The function looks only for an inherited match, and only among ## the methods that are not themselves inherited. (Inherited methods when found are ## stored in the session copy of the methods list, but they themselves should not be ## used for finding inherited matches, because an erroneous match could be found depending ## on which methods were previously used. See the detailed discussion of methods.) function(object, thisClass, mlist, ev) { .MlistDeprecated("inheritedSubMethodLists()") methods <- slot(mlist, "methods")## only direct methods defaultMethod <- methods[["ANY"]]## maybe NULL classes <- names(methods) value <- list() if(.identC(thisClass, "missing")) { ## no superclasses for "missing" } else { ## search in the superclasses, but don't use inherited methods ## There are two cases: if thisClass is formally defined & unsealed, use its ## superclasses. Otherwise, look in the subclasses of those classes for ## which methods exist. classDef <- getClassDef(thisClass, ev) useSuperClasses <- !is.null(classDef) && !classDef@sealed if(useSuperClasses) { ## for consistency, order the available methods by ## the ordering of the superclasses of thisClass superClasses <- names(classDef@contains) classes <- superClasses[!is.na(match(superClasses, classes))] for(which in seq_along(classes)) { tryClass <- classes[[which]] ## TODO: There is potential bug here: If the is relation is conditional, ## we should not cache this selection. Needs another trick in the environment ## to FORCE no caching regardless of what happens elsewhere; e.g., storing a ## special object in .Class if(is.null(object) || is(object, tryClass)) { value[[tryClass]] <- methods[[tryClass]] } } } else { for(which in seq_along(classes)) { tryClass <- classes[[which]] tryClassDef <- getClassDef(tryClass, ev) if(!is.null(tryClassDef) && !is.na(match(thisClass, names(tryClassDef@subclasses)))) value[[tryClass]] <- methods[[which]] } } } if(!is.null(defaultMethod)) value[["ANY"]] <- defaultMethod value } matchSignature <- ## Match the signature object (a partially or completely named subset of the ## arguments of `fun', and return a vector of all the classes in the order specified ## by the signature slot of the generic. The classes not specified by `signature ##' will be `"ANY"' in the value. function(signature, fun, where = baseenv()) { if(!is(fun, "genericFunction")) stop(gettextf("trying to match a method signature to an object (of class %s) that is not a generic function", dQuote(class(fun))), domain = NA) anames <- fun@signature if(length(signature) == 0L) return(character()) if(is(signature,"character")) { pkgs <- packageSlot(signature) # includes case of "ObjectsWithPackage" if(is.null(pkgs)) pkgs <- character(length(signature)) else if(length(pkgs) != length(signature)) stop("invalid 'package' slot or attribute, wrong length") sigClasses <- as.character(signature) } else if(is(signature, "list")) { sigClasses <- pkgs <- character(length(signature)) for(i in seq_along(signature)) { cli <- signature[[i]] if(is(cli, "classRepresentation")) { sigClasses[[i]] <- cli@className pkgs[[i]] <- cli@package } else if(is(cli, "character") && length(cli) == 1) { sigClasses[[i]] <- cli pkgi <- packageSlot(cli) if(is.character(pkgi)) pkgs[[i]] <- pkgi } else stop(gettextf("invalid element in a list for \"signature\" argument; element %d is neither a class definition nor a class name", i), domain = NA) } } else stop(gettextf("trying to match a method signature of class %s; expects a list or a character vector", dQuote(class(signature))), domain = NA) if(!identical(where, baseenv())) { ## fill in package information, warn about undefined classes unknown <- !nzchar(pkgs) for(i in seq_along(sigClasses)[unknown]) { cli <- getClassDef(sigClasses[[i]], where) if(!is.null(cli)) { pkgs[[i]] <- cli@package unknown[[i]] <- FALSE } } if(any(unknown)) { unknown <- unique(sigClasses[unknown]) ## coerce(), i.e., setAs() may use *one* unknown class MSG <- if(identical(as.vector(coerce@generic), "coerce") && length(unknown) == 1) message else function(...) warning(..., call. = FALSE) MSG(.renderSignature(fun@generic, signature), sprintf(ngettext(length(unknown), "no definition for class %s", "no definition for classes %s"), paste(dQuote(unknown), collapse = ", ")), domain = NA) } } signature <- as.list(signature) if(length(sigClasses) != length(signature)) stop(gettextf("object to use as a method signature for function %s does not look like a legitimate signature (a vector of single class names): there were %d class names, but %d elements in the signature object", sQuote(fun@generic), length(sigClasses), length(signature)), domain = NA) if(is.null(names(signature))) { which <- seq_along(signature) if(length(which) > length(anames)) stop(gettextf("more elements in the method signature (%d) than in the generic signature (%d) for function %s", length(which), length(anames), sQuote(fun@generic)), domain = NA) } else { ## construct a function call with the same naming pattern & ## values as signature sigList <- signature for(i in seq_along(sigList)) sigList[[i]] <- c(sigClasses[[i]], pkgs[[i]]) fcall <- do.call("call", c("fun", sigList)) ## match the call to the formal signature (usually the formal args) if(identical(anames, formalArgs(fun))) smatch <- match.call(fun, fcall) else { fmatch <- fun ff <- as.list(anames); names(ff) <- anames formals(fmatch, envir = environment(fun)) <- ff smatch <- match.call(fmatch, fcall) } snames <- names(smatch)[-1L] which <- match(snames, anames) ## Assertion: match.call has permuted the args into the order of formal args, ## and carried along the values. Get the supplied classes in that ## order, from the matched args in the call object. if(anyNA(which)) stop(sprintf(ngettext(sum(is.na(which)), "in the method signature for function %s invalid argument name in the signature: %s", "in the method signature for function %s invalid argument names in the signature: %s"), sQuote(fun@generic), paste(snames[is.na(which)], collapse = ", ")), domain = NA) smatch <- smatch[-1] for(i in seq_along(smatch)) { eli <- smatch[[i]] sigClasses[[i]] <- eli[[1]] pkgs[[i]] <- eli[[2]] } } n <- length(anames) value <- rep("ANY", n) valueP <- rep("methods", n) names(value) <- anames value[which] <- sigClasses valueP[which] <- pkgs unspec <- value == "ANY" ## remove the trailing unspecified classes while(n > 1 && unspec[[n]]) n <- n-1 length(value) <- length(valueP) <- n attr(value, "package") <- valueP ## <FIXME> Is there a reason (bootstrapping?) why this ## is not an actual object from class "signature"? ## See .MakeSignature() </FIXME> value } showMlist <- ## Prints the contents of the MethodsList. If `includeDefs' the signatures and the ## corresponding definitions will be printed; otherwise, only the signatures. ## ## If `includeDefs' is `TRUE', the currently known inherited methods are included; ## otherwise, only the directly defined methods. function(mlist, includeDefs = TRUE, inherited = TRUE, classes = NULL, useArgNames = TRUE, printTo = stdout()) { .MlistDeprecated("showMlist()") if(identical(printTo, FALSE)) { tmp <- tempfile() con <- file(tmp, "w") } else con <- printTo object <- linearizeMlist(mlist, inherited) methods <- object@methods signatures <- object@classes args <- object@arguments if(!is.null(classes) && length(signatures)>0) { keep <- !vapply(signatures, function(x, y) all(is.na(match(x, y))), NA, classes) methods <- methods[keep] signatures <- signatures[keep] args <- args[keep] } if(length(methods) == 0) cat(file=con, "<Empty Methods List>\n") else { n <- length(methods) labels <- character(n) if(useArgNames) { for(i in 1L:n) { sigi <- signatures[[i]] labels[[i]] <- paste(args[[i]], " = \"", sigi, "\"", sep = "", collapse = ", ") } } else { for(i in 1L:n) labels[[i]] <- paste(signatures[[i]], collapse = ", ") } for(i in seq_along(methods)) { cat(file=con, (if(includeDefs) "## Signature:" else ""), labels[[i]]) method <- methods[[i]] if(includeDefs) { cat(file=con, ":\n") if(is(method, "MethodDefinition")) ## really an assertion cat(file=con, deparse(method@.Data), sep="\n") else cat(file=con, deparse(method), sep="\n") } if(is(method, "MethodDefinition") && !identical(method@target, method@defined)) { defFrom <- method@defined cat(file = con, if(includeDefs) "##:" else "\n", " (inherited from ", paste(names(defFrom), " = \"", as.character(defFrom), "\"", sep = "", collapse = ", "), ")", if(includeDefs) "\n", sep="") } cat(file=con, "\n") } } if(identical(printTo, FALSE)) { close(con) value <- readLines(tmp) unlink(tmp) value } } promptMethods <- function(f, filename = NULL, methods) { ## Generate information in the style of 'prompt' for the methods of ## the generic named 'f'. ## ## 'filename' can be a logical or NA or the name of a file to print ## to. If it 'FALSE', the methods skeleton is returned, to be ## included in other printing (typically, the output from 'prompt'). escape <- function(txt) gsub("%", "\\\\%", txt) packageString <- "" fdef <- getGeneric(f) if(!isGeneric(f, fdef=fdef)) stop(gettextf("no generic function found corresponding to %s", sQuote(f)), domain = NA) if(missing(methods)) { methods <- findMethods(fdef) ## try making packageString where <- .genEnv(fdef, topenv(parent.frame())) if(!identical(where, .GlobalEnv)) packageString <- sprintf("in Package \\pkg{%s}", getPackageName(where)) } fullName <- utils:::topicName("methods", f) n <- length(methods) labels <- character(n) aliases <- character(n) signatures <- findMethodSignatures(methods = methods, target=TRUE) args <- colnames(signatures) # the *same* for all for(i in seq_len(n)) { sigi <- signatures[i, ] labels[[i]] <- sprintf("\\code{signature(%s)}", paste(sprintf("%s = \"%s\"", args, escape(sigi)), collapse = ", ")) aliases[[i]] <- paste0("\\alias{", utils:::topicName("method", c(f, signatures[i,])), "}") } text <- paste0("\n\\item{", labels, "}{\n%% ~~describe this method here~~\n}") text <- c("\\section{Methods}{\n\\describe{", text, "}}") aliasText <- c(paste0("\\alias{", escape(fullName), "}"), escape(aliases)) if(identical(filename, FALSE)) return(c(aliasText, text)) if(is.null(filename) || identical(filename, TRUE)) filename <- paste0(fullName, ".Rd") Rdtxt <- list(name = paste0("\\name{", fullName, "}"), type = "\\docType{methods}", aliases = aliasText, ## <FIXME> ## Title and description are ok as auto-generated: should ## they be flagged as such (via '~~' which are quite often ## left in by authors)? title = sprintf("\\title{ ~~ Methods for Function \\code{%s} %s ~~}", f, packageString), description = paste0("\\description{\n ~~ Methods for function", " \\code{", f, "} ", sub("^in Package", "in package", packageString), " ~~\n}"), ## </FIXME> "section{Methods}" = text, keywords = c("\\keyword{methods}", "\\keyword{ ~~ other possible keyword(s) ~~ }")) if(is.na(filename)) return(Rdtxt) cat(unlist(Rdtxt), file = filename, sep = "\n") .message("A shell of methods documentation has been written", .fileDesc(filename), ".\n") invisible(filename) } ##' only called from showMlist() above, which has been deprecated in R 3.2.0 (Apr.2015): linearizeMlist <- ## Undo the recursive nature of the methods list, making a list of ## function definitions, with the names of the list being the ## corresponding signatures (designed for printing; for looping over ## the methods, use `listFromMlist' instead). ## ## The function calls itself recursively. `prev' is the previously ## selected class names. ## ## If argument `classes' is provided, only signatures containing one ## of these classes will be included. function(mlist, inherited = TRUE) { methods <- mlist@methods allMethods <- mlist@allMethods if(inherited && length(allMethods) >= length(methods)) { ## anames <- names(allMethods) ## inh <- is.na(match(anames, names(methods))) methods <- allMethods } preC <- function(y, x)c(x,y) # used with lapply below cnames <- names(methods) value <- list() classes <- list() arguments <- list() argname <- as.character(mlist@argument) for(i in seq_along(cnames)) { mi <- methods[[i]] if(is.function(mi)) { value <- c(value, list(mi)) classes <- c(classes, list(cnames[[i]])) arguments <- c(arguments, list(argname)) } else if(is(mi, "MethodsList")) { .MlistDeprecated() mi <- Recall(mi, inherited) value <- c(value, mi@methods) classes <- c(classes, lapply(mi@classes, preC, cnames[[i]])) arguments <- c(arguments, lapply(mi@arguments, preC, argname)) } else warning(gettextf("skipping methods list element %s of unexpected class %s\n\n", paste(cnames[i], collapse = ", "), dQuote(.class1(mi))), domain = NA) } new("LinearMethodsList", methods = value, classes = classes, arguments = arguments) } print.MethodsList <- function(x, ...) showMlist(x) ## In R's own code, this is *only* used in mergeMethods(), deprecated in R 3.2.0 (Apr.2015) listFromMlist <- ## linearizes the MethodsList object into list(sigs, methods); `prefix' is the partial ## signature (a named list of classes) to be prepended to the signatures in this object. ## ## A utility function used to iterate over all the individual methods in the object. function(mlist, prefix = list(), sigs. = TRUE, methods. = TRUE) { methodSlot <- slot(mlist, "methods") mnames <- names(methodSlot) argName <- as.character(slot(mlist, "argument")) sigs <- list() methods <- list() for(i in seq_along(methodSlot)) { thisMethod <- methodSlot[i] thisClass <- mnames[[i]] prefix[[argName]] <- thisClass if(is.function(thisMethod)) { if(sigs.) sigs <- c(sigs, list(prefix)) if(methods.) methods <- c(methods, list(thisMethod)) } else { more <- Recall(thisMethod, prefix) if(sigs.) sigs <- c(sigs, more[[1]]) if(methods.) methods <- c(methods, more[[2]]) } } list(sigs, methods) } .insertCachedMethods <- function(mlist, argName, Class, fromClass, def) { if(is(def, "MethodsList")) { .MlistDeprecated() ## insert all the cached methods in def newArg <- c(argName, as.character(def@argument)) newDefs <- def@allMethods newSigs <- as.list(names(newDefs)) for(j in seq_along(newDefs)) mlist <- Recall(mlist, newArg, c(Class, newSigs[[j]]), fromClass, newDefs[[j]]) } else { def <- .addMethodFrom(def, argName[1L], Class[1L], fromClass) mlist <- insertMethod(mlist, Class, argName, def, TRUE) } mlist } .addMethodFrom <- function(def, arg, Class, fromClass) { if(is(def, "MethodDefinition")) { ## eventually, we may enforce method definition objects ## If not, just leave raw functions alone (NextMethod won't work) def@target[[arg]] <- Class def@defined[[arg]] <- fromClass } def } ## Define a trivial version of asMethodDefinition for bootstrapping. ## The real version requires several class definitions as well as ## methods for as<- asMethodDefinition <- function(def, signature = list(.anyClassName), sealed = FALSE, fdef = def) { if(is.primitive(def) || is(def, "MethodDefinition")) def else { value = new("MethodDefinition") value@.Data <- def classes <- .MakeSignature(new("signature"), def, signature, fdef) value@target <- classes value@defined <- classes value } } .trimMlist <- function(mlist, fromClass) { mlist@methods <- mlist@methods[fromClass] mlist@allMethods <- mlist@allMethods[fromClass] mlist } .noMlistsFlag <- TRUE .noMlists <- function() { ## if this were to be dynamically variable, but ## it can't, IMO ## identical(getOption("noMlists"), TRUE) ## so instead .noMlistsFlag } .MlistDepTable <- new.env() .MlistDeprecated <- function(this = "<default>", instead) { if(is.character(this)) { if(exists(this, envir = .MlistDepTable, inherits = FALSE)) return() else assign(this, TRUE, envir = .MlistDepTable) } msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is deprecated." else if(is.character(this)) gettextf( "%s, along with other use of the \"MethodsList\" metadata objects, is deprecated.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is deprecated.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList. (This warning is shown once per session.)") base::.Deprecated(msg = msg) } .MlistDefunct <- function(this = "<default>", instead) { msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is defunct." else if(is.character(this)) gettextf("%s, along with other use of the \"MethodsList\" metadata objects, is defunct.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is defunct.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList.") base::.Defunct(msg = msg) }
36,574
gpl-2.0
71c4978aaa94135074227729a1d4da375593bdd9
aviralg/R-dyntrace
src/library/methods/R/MethodsList.R
# File src/library/methods/R/MethodsList.R # Part of the R package, https://www.R-project.org # # Copyright (C) 1995-2016 The R Core Team # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # A copy of the GNU General Public License is available at # https://www.R-project.org/Licenses/ MethodsList <- ## Create a MethodsList object out of the arguments. ## ## Conceptually, this object is a named collection of methods to be ## dispatched when the (first) argument in a function call matches the ## class corresponding to one of the names. A final, unnamed element ## (i.e., with name `""') corresponds to the default method. ## ## The elements can be either a function, or another MethodsList. In ## the second case, this list implies dispatching on the second ## argument to the function using that list, given a selection of this ## element on the first argument. Thus, method dispatching on an ## arbitrary number of arguments is defined. ## ## MethodsList objects are used primarily to dispatch OOP-style ## methods and, in R, to emulate S4-style methods. function(.ArgName, ...) { .MlistDeprecated("MethodsList()") value <- makeMethodsList(list(...)) if(is.name(.ArgName)){} else if(is.character(.ArgName) && length(.ArgName) == 1) .ArgName <- as.name(.ArgName) else stop("invalid first argument: should be the name of the first argument in the dispatch") slot(value, "argument") <- .ArgName value } makeMethodsList <- function(object, level=1) { .MlistDeprecated("makeMethodsList()") mnames <- allNames(object) if(.noMlists()) { keep <- mnames %in% c("", "ANY") mnames <- mnames[keep] object <- object[keep] } value <- new("MethodsList") i <- match("", mnames) if(!is.na(i)) { ## convert to ANY mnames[[i]] <- "ANY" names(object) <- mnames } if(anyDuplicated(mnames)) stop(gettextf("duplicate element names in 'MethodsList' at level %d: %s", level, paste("\"", unique(mnames[duplicated(mnames)]), "\"", collapse=", ")), domain = NA) for(i in seq_along(object)) { eli <- object[[i]] if(is(eli, "function") || is(eli, "MethodsList")) {} else if(is(eli, "list") || is(eli, "named")) object[[i]] <- Recall(eli, NULL, level+1) else stop(gettextf("element %d at level %d (class %s) cannot be interpreted as a function or named list", i, level, dQuote(class(eli))), domain = NA) } slot(value, "methods") <- object value } SignatureMethod <- ## construct a MethodsList object containing (only) this method, corresponding ## to the signature; i.e., such that signature[[1L]] is the match for the first ## argument, signature[[2L]] for the second argument, and so on. The string ## "missing" means a match for a missing argument, and "ANY" means use this as the ## default setting at this level. ## ## The first argument is the argument names to be used for dispatch corresponding to ## the signatures. function(names, signature, definition) { .MlistDeprecated("SignatureMethod()") n <- length(signature) if(n > length(names)) stop("arguments 'names' and 'signature' must have the same length") if(n == 0) return(definition) Class <- signature[[n]] name <- names[[n]] m <- MethodsList(name) slot(m, "methods")[[Class]] <- definition slot(m, "argument") <- as.name(name) SignatureMethod(names[-n], signature[-n], m) } insertMethod <- ## insert the definition `def' into the MethodsList object, `mlist', corresponding to ## the signature, and return the modified MethodsList. function(mlist, signature, args, def, cacheOnly = FALSE) { .MlistDeprecated("insertMethod()") if(.noMlists() && !identical(unique(signature), "ANY")) return(mlist) ## Checks for assertions about valid calls. ## See rev. 1.17 for the code before the assertions added. if(identical(args[1L], "...") && !identical(names(signature), "...")) { if(identical(signature[[1L]], "ANY")) stop(gettextf("inserting method with invalid signature matching argument '...' to class %s", dQuote(signature[[1L]])), domain = NA) args <- args[-1L] signature <- signature[-1L] if(length(signature) == 0L) return(mlist) } if(length(signature) == 0L) stop("inserting method corresponding to empty signature") if(!is(mlist, "MethodsList")) stop(gettextf("inserting method into non-methods-list object (class %s)", dQuote(.class1(mlist))), domain = NA) if(length(args) > 1 && !cacheOnly) mlist <- balanceMethodsList(mlist, args) Class <- signature[[1]] methods <- if(cacheOnly) mlist@allMethods else mlist@methods current <- methods[[Class]] if(is(current, "MethodsList")) { nextArg <- as.character(current@argument) sigArgs <- args n <- length(signature) length(sigArgs) <- n if(is.na(match(nextArg, sigArgs))) { n <- match(nextArg, args) - n if(is.na(n)) { ## not in args eitiher n <- 1 args <- c(args, nextArg) } ## make explicit the trailing ANY's needed signature <- c(signature, rep("ANY", n)) } } if(length(signature) == 1) { if(is.null(current)) { if(!is.null(def)) methods[[Class]] <- def ## else, no change } else { which <- match(Class, names(methods)) if(is.null(def)) ## delete the method methods <- methods[-which] else methods[[which]] <- def } } else { ## recursively merge, initializing current if necessary if(is.null(current)) current <- new("MethodsList", argument = as.name(args[2L])) else if(is.function(current)) current <- new("MethodsList", argument = as.name(args[2L]), methods = list(ANY = current)) methods[[Class]] <- Recall(current, signature[-1L], args[-1L], def, cacheOnly) } mlist@allMethods <- methods if(!cacheOnly) mlist@methods <- methods mlist } MethodsListSelect <- ## select the element of a MethodsList object corresponding to the ## actual arguments (as defined in the suppled environment), ## and return the object, extended to include that method if necessary. ## ## Works recursively. At each level finds an argument name from the current `mlist' ## object, and evaluates this argument (if it is not missing), then uses the ## class of the result to select an element of `mlist'. If such an element ## exists and is another `MethodsList' object, `MethodsListSelect' calls itself recursively ## to resolve using further arguments. Matching includes using a default selection or ## a method specifically linked to class `"missing"'. Once a function is found, it ## is returned as the value. If matching fails, NULL is returned. function(f, env, mlist = NULL, fEnv = if(is(fdef, "genericFunction")) environment(fdef) else baseenv(), finalDefault = finalDefaultMethod(mlist), evalArgs = TRUE, useInherited = TRUE, ## supplied when evalArgs is FALSE fdef = getGeneric(f, where = env), # MUST BE SAFE FROM RECUSIVE METHOD SELECTION resetAllowed = TRUE # FALSE when called from selectMethod, .findNextMethod ) { .MlistDeprecated("MethodsListSelect()") if(!resetAllowed) # ensure we restore the real methods for this function resetMlist <- .getMethodsForDispatch(fdef) ## look for call from C dispatch code during another call to MethodsListSelect if(is.null(f)) {} # Recall, not from C else { fMethods <- .getMethodsForDispatch(fdef) if(is.null(mlist) || (evalArgs && is.function(fMethods))) mlist <- fMethods } resetNeeded <- .setIfBase(f, fdef, mlist) # quickly protect against recursion -- see Methods.R if(resetNeeded) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } if(!is(mlist, "MethodsList")) { if(is.function(mlist)) # call to f, inside MethodsListSelect {on.exit(); return(mlist)} if(is.null(f)) # recursive recall of MethodsListSelect stop("invalid method sublist") else if(!is.null(mlist)) # NULL => 1st call to genericFunction stop(gettextf("%f is not a valid generic function: methods list was an object of class %s", sQuote(f), dQuote(class(mlist))), domain = NA) } if(!is.logical(useInherited)) stop(gettextf("%s must be TRUE, FALSE, or a named logical vector of those values; got an object of class %s", sQuote("useInherited"), dQuote(class(useInherited))), domain = NA) if(identical(mlist, .getMethodsForDispatch(fdef))) { resetNeeded <- TRUE ## On the initial call: ## turn off any further method dispatch on this function, to avoid recursive ## loops if f is a function used in MethodsListSelect. ## TODO: Using namespaces in the methods package would eliminate the need for this .setMethodsForDispatch(f, fdef, finalDefault) if(is(mlist, "MethodsList")) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } } argName <- slot(mlist, "argument") arg <- NULL ## => don't use instance-specific inheritance if(evalArgs) { ## check for missing argument. NB: S sense, not that of R base missing() if(missingArg(argName, env, TRUE)) thisClass <- "missing" else { arg <- eval(as.name(argName), env) ## DO use instance-specific inheritance if(missing(arg)) ## S3 weird R code? Bail out! return(finalDefault) thisClass <- .class1(arg) } } else thisClass <- get(as.character(argName), envir = env, inherits = FALSE) if(identical(useInherited, TRUE) || identical(useInherited, FALSE)) thisInherit <- nextUseInherited <- useInherited else { which <- match(as.character(argName), names(useInherited)) if(is.na(which)) { nextUseInherited <- useInherited thisInherit <- TRUE } else { thisInherit <- useInherited[[which]] nextUseInherited <- useInherited[-which] } } fromClass <- thisClass ## will mark the class actually providing the method allMethods <- mlist@allMethods which <- match(thisClass, names(allMethods)) inherited <- is.na(which) selection <- if(inherited) NULL else allMethods[[which]] if(!inherited) { if(is(selection, "function")) { if(is.null(f)) { ## An inherited method at the next level up. ## only the inherited method should be added mlist <- .trimMlist(mlist, fromClass) } value <- mlist ## no change } else { ## recursive call with NULL function name, to allow search to fail & ## to suppress any reset actions. method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef, ) if(is(method, "EmptyMethodsList")) value <- method else { mlist@allMethods[[which]] <- method value <- mlist } } } if(inherited || is(value, "EmptyMethodsList")) { ## direct selection failed at this level or below method <- NULL if(thisInherit) { allSelections <- inheritedSubMethodLists(arg, fromClass, mlist, env) allClasses <- names(allSelections) for(i in seq_along(allSelections)) { selection <- allSelections[[i]] fromClass <- allClasses[[i]] if(is(selection, "function")) method <- selection else if(is(selection, "MethodsList")) { ## go on to try matching further arguments method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef) if(is(method, "EmptyMethodsList")) selection <- method ## recursive selection failed } if(!is(selection, "EmptyMethodsList")) break } } if((is.null(selection) || is(selection, "EmptyMethodsList")) && !is.null(f) && !is.null(finalDefault)) { ## only use the final default method after exhausting all ## other possibilities, at all levels. method <- finalDefault fromClass <- "ANY" } if(is.null(method) || is(method, "EmptyMethodsList")) value <- emptyMethodsList(mlist, thisClass) ## nothing found else { method <- MethodAddCoerce(method, argName, thisClass, fromClass) value <- .insertCachedMethods(mlist, as.character(argName), thisClass, fromClass, method) } } if(!is.null(f)) { ## top level if(is(value, "EmptyMethodsList")) ## selection failed value <- NULL if(resetNeeded) { on.exit() # cancel the restore of the original mlist if(resetAllowed) { if(is.null(value)) resetMlist <- mlist else resetMlist <- value } .setMethodsForDispatch(f, fdef, resetMlist) if(dispatchIsInternal(fdef)) setPrimitiveMethods(f, finalDefault, "set", fdef, resetMlist) } } value } emptyMethodsList <- function(mlist, thisClass = "ANY", sublist = list()) { .MlistDeprecated("emptyMethodsList()") sublist[thisClass] <- list(NULL) new("EmptyMethodsList", argument = mlist@argument, sublist = sublist) } insertMethodInEmptyList <- function(mlist, def) { .MlistDeprecated("insertMethodInEmptyList()") value <- new("MethodsList", argument = mlist@argument) sublist <- mlist@sublist submethods <- sublist[[1L]] if(is.null(submethods)) sublist[[1L]] <- def else sublist[[1L]] <- Recall(submethods, def) value@allMethods <- sublist value } finalDefaultMethod <- ## Return the default method from the generic (it may be NULL, a method object or a primitive. ## this previously searched in a MethodsList object. Once those are gone, the loop should ## be irrelevant except as an error check. function(method) { repeat { if(is.function(method) # <- somewhat liberal, but catches both methods and primitives || is.null(method)) break if(is(method, "MethodsList")) { .MlistDeprecated() method <- slot(method, "methods")[["ANY"]] } else stop(gettextf( "default method must be a method definition, a primitive or NULL: got an object of class %s", dQuote(class(method))), domain = NA) } method } inheritedSubMethodLists <- ## Utility function to match the object to the elements of a methods list. ## ## The function looks only for an inherited match, and only among ## the methods that are not themselves inherited. (Inherited methods when found are ## stored in the session copy of the methods list, but they themselves should not be ## used for finding inherited matches, because an erroneous match could be found depending ## on which methods were previously used. See the detailed discussion of methods.) function(object, thisClass, mlist, ev) { .MlistDeprecated("inheritedSubMethodLists()") methods <- slot(mlist, "methods")## only direct methods defaultMethod <- methods[["ANY"]]## maybe NULL classes <- names(methods) value <- list() if(.identC(thisClass, "missing")) { ## no superclasses for "missing" } else { ## search in the superclasses, but don't use inherited methods ## There are two cases: if thisClass is formally defined & unsealed, use its ## superclasses. Otherwise, look in the subclasses of those classes for ## which methods exist. classDef <- getClassDef(thisClass, ev) useSuperClasses <- !is.null(classDef) && !classDef@sealed if(useSuperClasses) { ## for consistency, order the available methods by ## the ordering of the superclasses of thisClass superClasses <- names(classDef@contains) classes <- superClasses[!is.na(match(superClasses, classes))] for(which in seq_along(classes)) { tryClass <- classes[[which]] ## TODO: There is potential bug here: If the is relation is conditional, ## we should not cache this selection. Needs another trick in the environment ## to FORCE no caching regardless of what happens elsewhere; e.g., storing a ## special object in .Class if(is.null(object) || is(object, tryClass)) { value[[tryClass]] <- methods[[tryClass]] } } } else { for(which in seq_along(classes)) { tryClass <- classes[[which]] tryClassDef <- getClassDef(tryClass, ev) if(!is.null(tryClassDef) && !is.na(match(thisClass, names(tryClassDef@subclasses)))) value[[tryClass]] <- methods[[which]] } } } if(!is.null(defaultMethod)) value[["ANY"]] <- defaultMethod value } matchSignature <- ## Match the signature object (a partially or completely named subset of the ## arguments of `fun', and return a vector of all the classes in the order specified ## by the signature slot of the generic. The classes not specified by `signature ##' will be `"ANY"' in the value. function(signature, fun, where = baseenv()) { if(!is(fun, "genericFunction")) stop(gettextf("trying to match a method signature to an object (of class %s) that is not a generic function", dQuote(class(fun))), domain = NA) anames <- fun@signature if(length(signature) == 0L) return(character()) if(is(signature,"character")) { pkgs <- packageSlot(signature) # includes case of "ObjectsWithPackage" if(is.null(pkgs)) pkgs <- character(length(signature)) else if(length(pkgs) != length(signature)) stop("invalid 'package' slot or attribute, wrong length") sigClasses <- as.character(signature) } else if(is(signature, "list")) { sigClasses <- pkgs <- character(length(signature)) for(i in seq_along(signature)) { cli <- signature[[i]] if(is(cli, "classRepresentation")) { sigClasses[[i]] <- cli@className pkgs[[i]] <- cli@package } else if(is(cli, "character") && length(cli) == 1) { sigClasses[[i]] <- cli pkgi <- packageSlot(cli) if(is.character(pkgi)) pkgs[[i]] <- pkgi } else stop(gettextf("invalid element in a list for \"signature\" argument; element %d is neither a class definition nor a class name", i), domain = NA) } } else stop(gettextf("trying to match a method signature of class %s; expects a list or a character vector", dQuote(class(signature))), domain = NA) if(!identical(where, baseenv())) { ## fill in package information, warn about undefined classes unknown <- !nzchar(pkgs) for(i in seq_along(sigClasses)[unknown]) { cli <- getClassDef(sigClasses[[i]], where) if(!is.null(cli)) { pkgs[[i]] <- cli@package unknown[[i]] <- FALSE } } if(any(unknown)) { unknown <- unique(sigClasses[unknown]) ## coerce(), i.e., setAs() may use *one* unknown class MSG <- if(identical(as.vector(coerce@generic), "coerce") && length(unknown) == 1) message else function(...) warning(..., call. = FALSE) MSG(.renderSignature(fun@generic, signature), sprintf(ngettext(length(unknown), "no definition for class %s", "no definition for classes %s"), paste(dQuote(unknown), collapse = ", ")), domain = NA) } } signature <- as.list(signature) if(length(sigClasses) != length(signature)) stop(gettextf("object to use as a method signature for function %s does not look like a legitimate signature (a vector of single class names): there were %d class names, but %d elements in the signature object", sQuote(fun@generic), length(sigClasses), length(signature)), domain = NA) if(is.null(names(signature))) { which <- seq_along(signature) if(length(which) > length(anames)) stop(gettextf("more elements in the method signature (%d) than in the generic signature (%d) for function %s", length(which), length(anames), sQuote(fun@generic)), domain = NA) } else { ## construct a function call with the same naming pattern & ## values as signature sigList <- signature for(i in seq_along(sigList)) sigList[[i]] <- c(sigClasses[[i]], pkgs[[i]]) fcall <- do.call("call", c("fun", sigList)) ## match the call to the formal signature (usually the formal args) if(identical(anames, formalArgs(fun))) smatch <- match.call(fun, fcall) else { fmatch <- fun ff <- as.list(anames); names(ff) <- anames formals(fmatch, envir = environment(fun)) <- ff smatch <- match.call(fmatch, fcall) } snames <- names(smatch)[-1L] which <- match(snames, anames) ## Assertion: match.call has permuted the args into the order of formal args, ## and carried along the values. Get the supplied classes in that ## order, from the matched args in the call object. if(anyNA(which)) stop(sprintf(ngettext(sum(is.na(which)), "in the method signature for function %s invalid argument name in the signature: %s", "in the method signature for function %s invalid argument names in the signature: %s"), sQuote(fun@generic), paste(snames[is.na(which)], collapse = ", ")), domain = NA) smatch <- smatch[-1] for(i in seq_along(smatch)) { eli <- smatch[[i]] sigClasses[[i]] <- eli[[1]] pkgs[[i]] <- eli[[2]] } } n <- length(anames) value <- rep("ANY", n) valueP <- rep("methods", n) names(value) <- anames value[which] <- sigClasses valueP[which] <- pkgs unspec <- value == "ANY" ## remove the trailing unspecified classes while(n > 1 && unspec[[n]]) n <- n-1 length(value) <- length(valueP) <- n attr(value, "package") <- valueP ## <FIXME> Is there a reason (bootstrapping?) why this ## is not an actual object from class "signature"? ## See .MakeSignature() </FIXME> value } showMlist <- ## Prints the contents of the MethodsList. If `includeDefs' the signatures and the ## corresponding definitions will be printed; otherwise, only the signatures. ## ## If `includeDefs' is `TRUE', the currently known inherited methods are included; ## otherwise, only the directly defined methods. function(mlist, includeDefs = TRUE, inherited = TRUE, classes = NULL, useArgNames = TRUE, printTo = stdout()) { .MlistDeprecated("showMlist()") if(identical(printTo, FALSE)) { tmp <- tempfile() con <- file(tmp, "w") } else con <- printTo object <- linearizeMlist(mlist, inherited) methods <- object@methods signatures <- object@classes args <- object@arguments if(!is.null(classes) && length(signatures)>0) { keep <- !vapply(signatures, function(x, y) all(is.na(match(x, y))), NA, classes) methods <- methods[keep] signatures <- signatures[keep] args <- args[keep] } if(length(methods) == 0) cat(file=con, "<Empty Methods List>\n") else { n <- length(methods) labels <- character(n) if(useArgNames) { for(i in 1L:n) { sigi <- signatures[[i]] labels[[i]] <- paste(args[[i]], " = \"", sigi, "\"", sep = "", collapse = ", ") } } else { for(i in 1L:n) labels[[i]] <- paste(signatures[[i]], collapse = ", ") } for(i in seq_along(methods)) { cat(file=con, (if(includeDefs) "## Signature:" else ""), labels[[i]]) method <- methods[[i]] if(includeDefs) { cat(file=con, ":\n") if(is(method, "MethodDefinition")) ## really an assertion cat(file=con, deparse(method@.Data), sep="\n") else cat(file=con, deparse(method), sep="\n") } if(is(method, "MethodDefinition") && !identical(method@target, method@defined)) { defFrom <- method@defined cat(file = con, if(includeDefs) "##:" else "\n", " (inherited from ", paste(names(defFrom), " = \"", as.character(defFrom), "\"", sep = "", collapse = ", "), ")", if(includeDefs) "\n", sep="") } cat(file=con, "\n") } } if(identical(printTo, FALSE)) { close(con) value <- readLines(tmp) unlink(tmp) value } } promptMethods <- function(f, filename = NULL, methods) { ## Generate information in the style of 'prompt' for the methods of ## the generic named 'f'. ## ## 'filename' can be a logical or NA or the name of a file to print ## to. If it 'FALSE', the methods skeleton is returned, to be ## included in other printing (typically, the output from 'prompt'). escape <- function(txt) gsub("%", "\\\\%", txt) packageString <- "" fdef <- getGeneric(f) if(!isGeneric(f, fdef=fdef)) stop(gettextf("no generic function found corresponding to %s", sQuote(f)), domain = NA) if(missing(methods)) { methods <- findMethods(fdef) ## try making packageString where <- .genEnv(fdef, topenv(parent.frame())) if(!identical(where, .GlobalEnv)) packageString <- sprintf("in Package \\pkg{%s}", getPackageName(where)) } fullName <- utils:::topicName("methods", f) n <- length(methods) labels <- character(n) aliases <- character(n) signatures <- findMethodSignatures(methods = methods, target=TRUE) args <- colnames(signatures) # the *same* for all for(i in seq_len(n)) { sigi <- signatures[i, ] labels[[i]] <- sprintf("\\code{signature(%s)}", paste(sprintf("%s = \"%s\"", args, escape(sigi)), collapse = ", ")) aliases[[i]] <- paste0("\\alias{", utils:::topicName("method", c(f, signatures[i,])), "}") } text <- paste0("\n\\item{", labels, "}{\n%% ~~describe this method here~~\n}") text <- c("\\section{Methods}{\n\\describe{", text, "}}") aliasText <- c(paste0("\\alias{", escape(fullName), "}"), escape(aliases)) if(identical(filename, FALSE)) return(c(aliasText, text)) if(is.null(filename) || identical(filename, TRUE)) filename <- paste0(fullName, ".Rd") Rdtxt <- list(name = paste0("\\name{", fullName, "}"), type = "\\docType{methods}", aliases = aliasText, ## <FIXME> ## Title and description are ok as auto-generated: should ## they be flagged as such (via '~~' which are quite often ## left in by authors)? title = sprintf("\\title{ ~~ Methods for Function \\code{%s} %s ~~}", f, packageString), description = paste0("\\description{\n ~~ Methods for function", " \\code{", f, "} ", sub("^in Package", "in package", packageString), " ~~\n}"), ## </FIXME> "section{Methods}" = text, keywords = c("\\keyword{methods}", "\\keyword{ ~~ other possible keyword(s) ~~ }")) if(is.na(filename)) return(Rdtxt) cat(unlist(Rdtxt), file = filename, sep = "\n") .message("A shell of methods documentation has been written", .fileDesc(filename), ".\n") invisible(filename) } ##' only called from showMlist() above, which has been deprecated in R 3.2.0 (Apr.2015): linearizeMlist <- ## Undo the recursive nature of the methods list, making a list of ## function definitions, with the names of the list being the ## corresponding signatures (designed for printing; for looping over ## the methods, use `listFromMlist' instead). ## ## The function calls itself recursively. `prev' is the previously ## selected class names. ## ## If argument `classes' is provided, only signatures containing one ## of these classes will be included. function(mlist, inherited = TRUE) { methods <- mlist@methods allMethods <- mlist@allMethods if(inherited && length(allMethods) >= length(methods)) { ## anames <- names(allMethods) ## inh <- is.na(match(anames, names(methods))) methods <- allMethods } preC <- function(y, x)c(x,y) # used with lapply below cnames <- names(methods) value <- list() classes <- list() arguments <- list() argname <- as.character(mlist@argument) for(i in seq_along(cnames)) { mi <- methods[[i]] if(is.function(mi)) { value <- c(value, list(mi)) classes <- c(classes, list(cnames[[i]])) arguments <- c(arguments, list(argname)) } else if(is(mi, "MethodsList")) { .MlistDeprecated() mi <- Recall(mi, inherited) value <- c(value, mi@methods) classes <- c(classes, lapply(mi@classes, preC, cnames[[i]])) arguments <- c(arguments, lapply(mi@arguments, preC, argname)) } else warning(gettextf("skipping methods list element %s of unexpected class %s\n\n", paste(cnames[i], collapse = ", "), dQuote(.class1(mi))), domain = NA) } new("LinearMethodsList", methods = value, classes = classes, arguments = arguments) } print.MethodsList <- function(x, ...) showMlist(x) ## In R's own code, this is *only* used in mergeMethods(), deprecated in R 3.2.0 (Apr.2015) listFromMlist <- ## linearizes the MethodsList object into list(sigs, methods); `prefix' is the partial ## signature (a named list of classes) to be prepended to the signatures in this object. ## ## A utility function used to iterate over all the individual methods in the object. function(mlist, prefix = list(), sigs. = TRUE, methods. = TRUE) { methodSlot <- slot(mlist, "methods") mnames <- names(methodSlot) argName <- as.character(slot(mlist, "argument")) sigs <- list() methods <- list() for(i in seq_along(methodSlot)) { thisMethod <- methodSlot[i] thisClass <- mnames[[i]] prefix[[argName]] <- thisClass if(is.function(thisMethod)) { if(sigs.) sigs <- c(sigs, list(prefix)) if(methods.) methods <- c(methods, list(thisMethod)) } else { more <- Recall(thisMethod, prefix) if(sigs.) sigs <- c(sigs, more[[1]]) if(methods.) methods <- c(methods, more[[2]]) } } list(sigs, methods) } .insertCachedMethods <- function(mlist, argName, Class, fromClass, def) { if(is(def, "MethodsList")) { .MlistDeprecated() ## insert all the cached methods in def newArg <- c(argName, as.character(def@argument)) newDefs <- def@allMethods newSigs <- as.list(names(newDefs)) for(j in seq_along(newDefs)) mlist <- Recall(mlist, newArg, c(Class, newSigs[[j]]), fromClass, newDefs[[j]]) } else { def <- .addMethodFrom(def, argName[1L], Class[1L], fromClass) mlist <- insertMethod(mlist, Class, argName, def, TRUE) } mlist } .addMethodFrom <- function(def, arg, Class, fromClass) { if(is(def, "MethodDefinition")) { ## eventually, we may enforce method definition objects ## If not, just leave raw functions alone (NextMethod won't work) def@target[[arg]] <- Class def@defined[[arg]] <- fromClass } def } ## Define a trivial version of asMethodDefinition for bootstrapping. ## The real version requires several class definitions as well as ## methods for as<- asMethodDefinition <- function(def, signature = list(.anyClassName), sealed = FALSE, fdef = def) { if(is.primitive(def) || is(def, "MethodDefinition")) def else { value = new("MethodDefinition") value@.Data <- def classes <- .MakeSignature(new("signature"), def, signature, fdef) value@target <- classes value@defined <- classes value } } .trimMlist <- function(mlist, fromClass) { mlist@methods <- mlist@methods[fromClass] mlist@allMethods <- mlist@allMethods[fromClass] mlist } .noMlistsFlag <- TRUE .noMlists <- function() { ## if this were to be dynamically variable, but ## it can't, IMO ## identical(getOption("noMlists"), TRUE) ## so instead .noMlistsFlag } .MlistDepTable <- new.env() .MlistDeprecated <- function(this = "<default>", instead) { if(is.character(this)) { if(exists(this, envir = .MlistDepTable, inherits = FALSE)) return() else assign(this, TRUE, envir = .MlistDepTable) } msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is deprecated." else if(is.character(this)) gettextf( "%s, along with other use of the \"MethodsList\" metadata objects, is deprecated.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is deprecated.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList. (This warning is shown once per session.)") base::.Deprecated(msg = msg) } .MlistDefunct <- function(this = "<default>", instead) { msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is defunct." else if(is.character(this)) gettextf("%s, along with other use of the \"MethodsList\" metadata objects, is defunct.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is defunct.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList.") base::.Defunct(msg = msg) }
36,574
gpl-2.0
71c4978aaa94135074227729a1d4da375593bdd9
krlmlr/cxxr
src/library/methods/R/MethodsList.R
# File src/library/methods/R/MethodsList.R # Part of the R package, https://www.R-project.org # # Copyright (C) 1995-2016 The R Core Team # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # A copy of the GNU General Public License is available at # https://www.R-project.org/Licenses/ MethodsList <- ## Create a MethodsList object out of the arguments. ## ## Conceptually, this object is a named collection of methods to be ## dispatched when the (first) argument in a function call matches the ## class corresponding to one of the names. A final, unnamed element ## (i.e., with name `""') corresponds to the default method. ## ## The elements can be either a function, or another MethodsList. In ## the second case, this list implies dispatching on the second ## argument to the function using that list, given a selection of this ## element on the first argument. Thus, method dispatching on an ## arbitrary number of arguments is defined. ## ## MethodsList objects are used primarily to dispatch OOP-style ## methods and, in R, to emulate S4-style methods. function(.ArgName, ...) { .MlistDeprecated("MethodsList()") value <- makeMethodsList(list(...)) if(is.name(.ArgName)){} else if(is.character(.ArgName) && length(.ArgName) == 1) .ArgName <- as.name(.ArgName) else stop("invalid first argument: should be the name of the first argument in the dispatch") slot(value, "argument") <- .ArgName value } makeMethodsList <- function(object, level=1) { .MlistDeprecated("makeMethodsList()") mnames <- allNames(object) if(.noMlists()) { keep <- mnames %in% c("", "ANY") mnames <- mnames[keep] object <- object[keep] } value <- new("MethodsList") i <- match("", mnames) if(!is.na(i)) { ## convert to ANY mnames[[i]] <- "ANY" names(object) <- mnames } if(anyDuplicated(mnames)) stop(gettextf("duplicate element names in 'MethodsList' at level %d: %s", level, paste("\"", unique(mnames[duplicated(mnames)]), "\"", collapse=", ")), domain = NA) for(i in seq_along(object)) { eli <- object[[i]] if(is(eli, "function") || is(eli, "MethodsList")) {} else if(is(eli, "list") || is(eli, "named")) object[[i]] <- Recall(eli, NULL, level+1) else stop(gettextf("element %d at level %d (class %s) cannot be interpreted as a function or named list", i, level, dQuote(class(eli))), domain = NA) } slot(value, "methods") <- object value } SignatureMethod <- ## construct a MethodsList object containing (only) this method, corresponding ## to the signature; i.e., such that signature[[1L]] is the match for the first ## argument, signature[[2L]] for the second argument, and so on. The string ## "missing" means a match for a missing argument, and "ANY" means use this as the ## default setting at this level. ## ## The first argument is the argument names to be used for dispatch corresponding to ## the signatures. function(names, signature, definition) { .MlistDeprecated("SignatureMethod()") n <- length(signature) if(n > length(names)) stop("arguments 'names' and 'signature' must have the same length") if(n == 0) return(definition) Class <- signature[[n]] name <- names[[n]] m <- MethodsList(name) slot(m, "methods")[[Class]] <- definition slot(m, "argument") <- as.name(name) SignatureMethod(names[-n], signature[-n], m) } insertMethod <- ## insert the definition `def' into the MethodsList object, `mlist', corresponding to ## the signature, and return the modified MethodsList. function(mlist, signature, args, def, cacheOnly = FALSE) { .MlistDeprecated("insertMethod()") if(.noMlists() && !identical(unique(signature), "ANY")) return(mlist) ## Checks for assertions about valid calls. ## See rev. 1.17 for the code before the assertions added. if(identical(args[1L], "...") && !identical(names(signature), "...")) { if(identical(signature[[1L]], "ANY")) stop(gettextf("inserting method with invalid signature matching argument '...' to class %s", dQuote(signature[[1L]])), domain = NA) args <- args[-1L] signature <- signature[-1L] if(length(signature) == 0L) return(mlist) } if(length(signature) == 0L) stop("inserting method corresponding to empty signature") if(!is(mlist, "MethodsList")) stop(gettextf("inserting method into non-methods-list object (class %s)", dQuote(.class1(mlist))), domain = NA) if(length(args) > 1 && !cacheOnly) mlist <- balanceMethodsList(mlist, args) Class <- signature[[1]] methods <- if(cacheOnly) mlist@allMethods else mlist@methods current <- methods[[Class]] if(is(current, "MethodsList")) { nextArg <- as.character(current@argument) sigArgs <- args n <- length(signature) length(sigArgs) <- n if(is.na(match(nextArg, sigArgs))) { n <- match(nextArg, args) - n if(is.na(n)) { ## not in args eitiher n <- 1 args <- c(args, nextArg) } ## make explicit the trailing ANY's needed signature <- c(signature, rep("ANY", n)) } } if(length(signature) == 1) { if(is.null(current)) { if(!is.null(def)) methods[[Class]] <- def ## else, no change } else { which <- match(Class, names(methods)) if(is.null(def)) ## delete the method methods <- methods[-which] else methods[[which]] <- def } } else { ## recursively merge, initializing current if necessary if(is.null(current)) current <- new("MethodsList", argument = as.name(args[2L])) else if(is.function(current)) current <- new("MethodsList", argument = as.name(args[2L]), methods = list(ANY = current)) methods[[Class]] <- Recall(current, signature[-1L], args[-1L], def, cacheOnly) } mlist@allMethods <- methods if(!cacheOnly) mlist@methods <- methods mlist } MethodsListSelect <- ## select the element of a MethodsList object corresponding to the ## actual arguments (as defined in the suppled environment), ## and return the object, extended to include that method if necessary. ## ## Works recursively. At each level finds an argument name from the current `mlist' ## object, and evaluates this argument (if it is not missing), then uses the ## class of the result to select an element of `mlist'. If such an element ## exists and is another `MethodsList' object, `MethodsListSelect' calls itself recursively ## to resolve using further arguments. Matching includes using a default selection or ## a method specifically linked to class `"missing"'. Once a function is found, it ## is returned as the value. If matching fails, NULL is returned. function(f, env, mlist = NULL, fEnv = if(is(fdef, "genericFunction")) environment(fdef) else baseenv(), finalDefault = finalDefaultMethod(mlist), evalArgs = TRUE, useInherited = TRUE, ## supplied when evalArgs is FALSE fdef = getGeneric(f, where = env), # MUST BE SAFE FROM RECUSIVE METHOD SELECTION resetAllowed = TRUE # FALSE when called from selectMethod, .findNextMethod ) { .MlistDeprecated("MethodsListSelect()") if(!resetAllowed) # ensure we restore the real methods for this function resetMlist <- .getMethodsForDispatch(fdef) ## look for call from C dispatch code during another call to MethodsListSelect if(is.null(f)) {} # Recall, not from C else { fMethods <- .getMethodsForDispatch(fdef) if(is.null(mlist) || (evalArgs && is.function(fMethods))) mlist <- fMethods } resetNeeded <- .setIfBase(f, fdef, mlist) # quickly protect against recursion -- see Methods.R if(resetNeeded) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } if(!is(mlist, "MethodsList")) { if(is.function(mlist)) # call to f, inside MethodsListSelect {on.exit(); return(mlist)} if(is.null(f)) # recursive recall of MethodsListSelect stop("invalid method sublist") else if(!is.null(mlist)) # NULL => 1st call to genericFunction stop(gettextf("%f is not a valid generic function: methods list was an object of class %s", sQuote(f), dQuote(class(mlist))), domain = NA) } if(!is.logical(useInherited)) stop(gettextf("%s must be TRUE, FALSE, or a named logical vector of those values; got an object of class %s", sQuote("useInherited"), dQuote(class(useInherited))), domain = NA) if(identical(mlist, .getMethodsForDispatch(fdef))) { resetNeeded <- TRUE ## On the initial call: ## turn off any further method dispatch on this function, to avoid recursive ## loops if f is a function used in MethodsListSelect. ## TODO: Using namespaces in the methods package would eliminate the need for this .setMethodsForDispatch(f, fdef, finalDefault) if(is(mlist, "MethodsList")) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } } argName <- slot(mlist, "argument") arg <- NULL ## => don't use instance-specific inheritance if(evalArgs) { ## check for missing argument. NB: S sense, not that of R base missing() if(missingArg(argName, env, TRUE)) thisClass <- "missing" else { arg <- eval(as.name(argName), env) ## DO use instance-specific inheritance if(missing(arg)) ## S3 weird R code? Bail out! return(finalDefault) thisClass <- .class1(arg) } } else thisClass <- get(as.character(argName), envir = env, inherits = FALSE) if(identical(useInherited, TRUE) || identical(useInherited, FALSE)) thisInherit <- nextUseInherited <- useInherited else { which <- match(as.character(argName), names(useInherited)) if(is.na(which)) { nextUseInherited <- useInherited thisInherit <- TRUE } else { thisInherit <- useInherited[[which]] nextUseInherited <- useInherited[-which] } } fromClass <- thisClass ## will mark the class actually providing the method allMethods <- mlist@allMethods which <- match(thisClass, names(allMethods)) inherited <- is.na(which) selection <- if(inherited) NULL else allMethods[[which]] if(!inherited) { if(is(selection, "function")) { if(is.null(f)) { ## An inherited method at the next level up. ## only the inherited method should be added mlist <- .trimMlist(mlist, fromClass) } value <- mlist ## no change } else { ## recursive call with NULL function name, to allow search to fail & ## to suppress any reset actions. method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef, ) if(is(method, "EmptyMethodsList")) value <- method else { mlist@allMethods[[which]] <- method value <- mlist } } } if(inherited || is(value, "EmptyMethodsList")) { ## direct selection failed at this level or below method <- NULL if(thisInherit) { allSelections <- inheritedSubMethodLists(arg, fromClass, mlist, env) allClasses <- names(allSelections) for(i in seq_along(allSelections)) { selection <- allSelections[[i]] fromClass <- allClasses[[i]] if(is(selection, "function")) method <- selection else if(is(selection, "MethodsList")) { ## go on to try matching further arguments method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef) if(is(method, "EmptyMethodsList")) selection <- method ## recursive selection failed } if(!is(selection, "EmptyMethodsList")) break } } if((is.null(selection) || is(selection, "EmptyMethodsList")) && !is.null(f) && !is.null(finalDefault)) { ## only use the final default method after exhausting all ## other possibilities, at all levels. method <- finalDefault fromClass <- "ANY" } if(is.null(method) || is(method, "EmptyMethodsList")) value <- emptyMethodsList(mlist, thisClass) ## nothing found else { method <- MethodAddCoerce(method, argName, thisClass, fromClass) value <- .insertCachedMethods(mlist, as.character(argName), thisClass, fromClass, method) } } if(!is.null(f)) { ## top level if(is(value, "EmptyMethodsList")) ## selection failed value <- NULL if(resetNeeded) { on.exit() # cancel the restore of the original mlist if(resetAllowed) { if(is.null(value)) resetMlist <- mlist else resetMlist <- value } .setMethodsForDispatch(f, fdef, resetMlist) if(dispatchIsInternal(fdef)) setPrimitiveMethods(f, finalDefault, "set", fdef, resetMlist) } } value } emptyMethodsList <- function(mlist, thisClass = "ANY", sublist = list()) { .MlistDeprecated("emptyMethodsList()") sublist[thisClass] <- list(NULL) new("EmptyMethodsList", argument = mlist@argument, sublist = sublist) } insertMethodInEmptyList <- function(mlist, def) { .MlistDeprecated("insertMethodInEmptyList()") value <- new("MethodsList", argument = mlist@argument) sublist <- mlist@sublist submethods <- sublist[[1L]] if(is.null(submethods)) sublist[[1L]] <- def else sublist[[1L]] <- Recall(submethods, def) value@allMethods <- sublist value } finalDefaultMethod <- ## Return the default method from the generic (it may be NULL, a method object or a primitive. ## this previously searched in a MethodsList object. Once those are gone, the loop should ## be irrelevant except as an error check. function(method) { repeat { if(is.function(method) # <- somewhat liberal, but catches both methods and primitives || is.null(method)) break if(is(method, "MethodsList")) { .MlistDeprecated() method <- slot(method, "methods")[["ANY"]] } else stop(gettextf( "default method must be a method definition, a primitive or NULL: got an object of class %s", dQuote(class(method))), domain = NA) } method } inheritedSubMethodLists <- ## Utility function to match the object to the elements of a methods list. ## ## The function looks only for an inherited match, and only among ## the methods that are not themselves inherited. (Inherited methods when found are ## stored in the session copy of the methods list, but they themselves should not be ## used for finding inherited matches, because an erroneous match could be found depending ## on which methods were previously used. See the detailed discussion of methods.) function(object, thisClass, mlist, ev) { .MlistDeprecated("inheritedSubMethodLists()") methods <- slot(mlist, "methods")## only direct methods defaultMethod <- methods[["ANY"]]## maybe NULL classes <- names(methods) value <- list() if(.identC(thisClass, "missing")) { ## no superclasses for "missing" } else { ## search in the superclasses, but don't use inherited methods ## There are two cases: if thisClass is formally defined & unsealed, use its ## superclasses. Otherwise, look in the subclasses of those classes for ## which methods exist. classDef <- getClassDef(thisClass, ev) useSuperClasses <- !is.null(classDef) && !classDef@sealed if(useSuperClasses) { ## for consistency, order the available methods by ## the ordering of the superclasses of thisClass superClasses <- names(classDef@contains) classes <- superClasses[!is.na(match(superClasses, classes))] for(which in seq_along(classes)) { tryClass <- classes[[which]] ## TODO: There is potential bug here: If the is relation is conditional, ## we should not cache this selection. Needs another trick in the environment ## to FORCE no caching regardless of what happens elsewhere; e.g., storing a ## special object in .Class if(is.null(object) || is(object, tryClass)) { value[[tryClass]] <- methods[[tryClass]] } } } else { for(which in seq_along(classes)) { tryClass <- classes[[which]] tryClassDef <- getClassDef(tryClass, ev) if(!is.null(tryClassDef) && !is.na(match(thisClass, names(tryClassDef@subclasses)))) value[[tryClass]] <- methods[[which]] } } } if(!is.null(defaultMethod)) value[["ANY"]] <- defaultMethod value } matchSignature <- ## Match the signature object (a partially or completely named subset of the ## arguments of `fun', and return a vector of all the classes in the order specified ## by the signature slot of the generic. The classes not specified by `signature ##' will be `"ANY"' in the value. function(signature, fun, where = baseenv()) { if(!is(fun, "genericFunction")) stop(gettextf("trying to match a method signature to an object (of class %s) that is not a generic function", dQuote(class(fun))), domain = NA) anames <- fun@signature if(length(signature) == 0L) return(character()) if(is(signature,"character")) { pkgs <- packageSlot(signature) # includes case of "ObjectsWithPackage" if(is.null(pkgs)) pkgs <- character(length(signature)) else if(length(pkgs) != length(signature)) stop("invalid 'package' slot or attribute, wrong length") sigClasses <- as.character(signature) } else if(is(signature, "list")) { sigClasses <- pkgs <- character(length(signature)) for(i in seq_along(signature)) { cli <- signature[[i]] if(is(cli, "classRepresentation")) { sigClasses[[i]] <- cli@className pkgs[[i]] <- cli@package } else if(is(cli, "character") && length(cli) == 1) { sigClasses[[i]] <- cli pkgi <- packageSlot(cli) if(is.character(pkgi)) pkgs[[i]] <- pkgi } else stop(gettextf("invalid element in a list for \"signature\" argument; element %d is neither a class definition nor a class name", i), domain = NA) } } else stop(gettextf("trying to match a method signature of class %s; expects a list or a character vector", dQuote(class(signature))), domain = NA) if(!identical(where, baseenv())) { ## fill in package information, warn about undefined classes unknown <- !nzchar(pkgs) for(i in seq_along(sigClasses)[unknown]) { cli <- getClassDef(sigClasses[[i]], where) if(!is.null(cli)) { pkgs[[i]] <- cli@package unknown[[i]] <- FALSE } } if(any(unknown)) { unknown <- unique(sigClasses[unknown]) ## coerce(), i.e., setAs() may use *one* unknown class MSG <- if(identical(as.vector(coerce@generic), "coerce") && length(unknown) == 1) message else function(...) warning(..., call. = FALSE) MSG(.renderSignature(fun@generic, signature), sprintf(ngettext(length(unknown), "no definition for class %s", "no definition for classes %s"), paste(dQuote(unknown), collapse = ", ")), domain = NA) } } signature <- as.list(signature) if(length(sigClasses) != length(signature)) stop(gettextf("object to use as a method signature for function %s does not look like a legitimate signature (a vector of single class names): there were %d class names, but %d elements in the signature object", sQuote(fun@generic), length(sigClasses), length(signature)), domain = NA) if(is.null(names(signature))) { which <- seq_along(signature) if(length(which) > length(anames)) stop(gettextf("more elements in the method signature (%d) than in the generic signature (%d) for function %s", length(which), length(anames), sQuote(fun@generic)), domain = NA) } else { ## construct a function call with the same naming pattern & ## values as signature sigList <- signature for(i in seq_along(sigList)) sigList[[i]] <- c(sigClasses[[i]], pkgs[[i]]) fcall <- do.call("call", c("fun", sigList)) ## match the call to the formal signature (usually the formal args) if(identical(anames, formalArgs(fun))) smatch <- match.call(fun, fcall) else { fmatch <- fun ff <- as.list(anames); names(ff) <- anames formals(fmatch, envir = environment(fun)) <- ff smatch <- match.call(fmatch, fcall) } snames <- names(smatch)[-1L] which <- match(snames, anames) ## Assertion: match.call has permuted the args into the order of formal args, ## and carried along the values. Get the supplied classes in that ## order, from the matched args in the call object. if(anyNA(which)) stop(sprintf(ngettext(sum(is.na(which)), "in the method signature for function %s invalid argument name in the signature: %s", "in the method signature for function %s invalid argument names in the signature: %s"), sQuote(fun@generic), paste(snames[is.na(which)], collapse = ", ")), domain = NA) smatch <- smatch[-1] for(i in seq_along(smatch)) { eli <- smatch[[i]] sigClasses[[i]] <- eli[[1]] pkgs[[i]] <- eli[[2]] } } n <- length(anames) value <- rep("ANY", n) valueP <- rep("methods", n) names(value) <- anames value[which] <- sigClasses valueP[which] <- pkgs unspec <- value == "ANY" ## remove the trailing unspecified classes while(n > 1 && unspec[[n]]) n <- n-1 length(value) <- length(valueP) <- n attr(value, "package") <- valueP ## <FIXME> Is there a reason (bootstrapping?) why this ## is not an actual object from class "signature"? ## See .MakeSignature() </FIXME> value } showMlist <- ## Prints the contents of the MethodsList. If `includeDefs' the signatures and the ## corresponding definitions will be printed; otherwise, only the signatures. ## ## If `includeDefs' is `TRUE', the currently known inherited methods are included; ## otherwise, only the directly defined methods. function(mlist, includeDefs = TRUE, inherited = TRUE, classes = NULL, useArgNames = TRUE, printTo = stdout()) { .MlistDeprecated("showMlist()") if(identical(printTo, FALSE)) { tmp <- tempfile() con <- file(tmp, "w") } else con <- printTo object <- linearizeMlist(mlist, inherited) methods <- object@methods signatures <- object@classes args <- object@arguments if(!is.null(classes) && length(signatures)>0) { keep <- !vapply(signatures, function(x, y) all(is.na(match(x, y))), NA, classes) methods <- methods[keep] signatures <- signatures[keep] args <- args[keep] } if(length(methods) == 0) cat(file=con, "<Empty Methods List>\n") else { n <- length(methods) labels <- character(n) if(useArgNames) { for(i in 1L:n) { sigi <- signatures[[i]] labels[[i]] <- paste(args[[i]], " = \"", sigi, "\"", sep = "", collapse = ", ") } } else { for(i in 1L:n) labels[[i]] <- paste(signatures[[i]], collapse = ", ") } for(i in seq_along(methods)) { cat(file=con, (if(includeDefs) "## Signature:" else ""), labels[[i]]) method <- methods[[i]] if(includeDefs) { cat(file=con, ":\n") if(is(method, "MethodDefinition")) ## really an assertion cat(file=con, deparse(method@.Data), sep="\n") else cat(file=con, deparse(method), sep="\n") } if(is(method, "MethodDefinition") && !identical(method@target, method@defined)) { defFrom <- method@defined cat(file = con, if(includeDefs) "##:" else "\n", " (inherited from ", paste(names(defFrom), " = \"", as.character(defFrom), "\"", sep = "", collapse = ", "), ")", if(includeDefs) "\n", sep="") } cat(file=con, "\n") } } if(identical(printTo, FALSE)) { close(con) value <- readLines(tmp) unlink(tmp) value } } promptMethods <- function(f, filename = NULL, methods) { ## Generate information in the style of 'prompt' for the methods of ## the generic named 'f'. ## ## 'filename' can be a logical or NA or the name of a file to print ## to. If it 'FALSE', the methods skeleton is returned, to be ## included in other printing (typically, the output from 'prompt'). escape <- function(txt) gsub("%", "\\\\%", txt) packageString <- "" fdef <- getGeneric(f) if(!isGeneric(f, fdef=fdef)) stop(gettextf("no generic function found corresponding to %s", sQuote(f)), domain = NA) if(missing(methods)) { methods <- findMethods(fdef) ## try making packageString where <- .genEnv(fdef, topenv(parent.frame())) if(!identical(where, .GlobalEnv)) packageString <- sprintf("in Package \\pkg{%s}", getPackageName(where)) } fullName <- utils:::topicName("methods", f) n <- length(methods) labels <- character(n) aliases <- character(n) signatures <- findMethodSignatures(methods = methods, target=TRUE) args <- colnames(signatures) # the *same* for all for(i in seq_len(n)) { sigi <- signatures[i, ] labels[[i]] <- sprintf("\\code{signature(%s)}", paste(sprintf("%s = \"%s\"", args, escape(sigi)), collapse = ", ")) aliases[[i]] <- paste0("\\alias{", utils:::topicName("method", c(f, signatures[i,])), "}") } text <- paste0("\n\\item{", labels, "}{\n%% ~~describe this method here~~\n}") text <- c("\\section{Methods}{\n\\describe{", text, "}}") aliasText <- c(paste0("\\alias{", escape(fullName), "}"), escape(aliases)) if(identical(filename, FALSE)) return(c(aliasText, text)) if(is.null(filename) || identical(filename, TRUE)) filename <- paste0(fullName, ".Rd") Rdtxt <- list(name = paste0("\\name{", fullName, "}"), type = "\\docType{methods}", aliases = aliasText, ## <FIXME> ## Title and description are ok as auto-generated: should ## they be flagged as such (via '~~' which are quite often ## left in by authors)? title = sprintf("\\title{ ~~ Methods for Function \\code{%s} %s ~~}", f, packageString), description = paste0("\\description{\n ~~ Methods for function", " \\code{", f, "} ", sub("^in Package", "in package", packageString), " ~~\n}"), ## </FIXME> "section{Methods}" = text, keywords = c("\\keyword{methods}", "\\keyword{ ~~ other possible keyword(s) ~~ }")) if(is.na(filename)) return(Rdtxt) cat(unlist(Rdtxt), file = filename, sep = "\n") .message("A shell of methods documentation has been written", .fileDesc(filename), ".\n") invisible(filename) } ##' only called from showMlist() above, which has been deprecated in R 3.2.0 (Apr.2015): linearizeMlist <- ## Undo the recursive nature of the methods list, making a list of ## function definitions, with the names of the list being the ## corresponding signatures (designed for printing; for looping over ## the methods, use `listFromMlist' instead). ## ## The function calls itself recursively. `prev' is the previously ## selected class names. ## ## If argument `classes' is provided, only signatures containing one ## of these classes will be included. function(mlist, inherited = TRUE) { methods <- mlist@methods allMethods <- mlist@allMethods if(inherited && length(allMethods) >= length(methods)) { ## anames <- names(allMethods) ## inh <- is.na(match(anames, names(methods))) methods <- allMethods } preC <- function(y, x)c(x,y) # used with lapply below cnames <- names(methods) value <- list() classes <- list() arguments <- list() argname <- as.character(mlist@argument) for(i in seq_along(cnames)) { mi <- methods[[i]] if(is.function(mi)) { value <- c(value, list(mi)) classes <- c(classes, list(cnames[[i]])) arguments <- c(arguments, list(argname)) } else if(is(mi, "MethodsList")) { .MlistDeprecated() mi <- Recall(mi, inherited) value <- c(value, mi@methods) classes <- c(classes, lapply(mi@classes, preC, cnames[[i]])) arguments <- c(arguments, lapply(mi@arguments, preC, argname)) } else warning(gettextf("skipping methods list element %s of unexpected class %s\n\n", paste(cnames[i], collapse = ", "), dQuote(.class1(mi))), domain = NA) } new("LinearMethodsList", methods = value, classes = classes, arguments = arguments) } print.MethodsList <- function(x, ...) showMlist(x) ## In R's own code, this is *only* used in mergeMethods(), deprecated in R 3.2.0 (Apr.2015) listFromMlist <- ## linearizes the MethodsList object into list(sigs, methods); `prefix' is the partial ## signature (a named list of classes) to be prepended to the signatures in this object. ## ## A utility function used to iterate over all the individual methods in the object. function(mlist, prefix = list(), sigs. = TRUE, methods. = TRUE) { methodSlot <- slot(mlist, "methods") mnames <- names(methodSlot) argName <- as.character(slot(mlist, "argument")) sigs <- list() methods <- list() for(i in seq_along(methodSlot)) { thisMethod <- methodSlot[i] thisClass <- mnames[[i]] prefix[[argName]] <- thisClass if(is.function(thisMethod)) { if(sigs.) sigs <- c(sigs, list(prefix)) if(methods.) methods <- c(methods, list(thisMethod)) } else { more <- Recall(thisMethod, prefix) if(sigs.) sigs <- c(sigs, more[[1]]) if(methods.) methods <- c(methods, more[[2]]) } } list(sigs, methods) } .insertCachedMethods <- function(mlist, argName, Class, fromClass, def) { if(is(def, "MethodsList")) { .MlistDeprecated() ## insert all the cached methods in def newArg <- c(argName, as.character(def@argument)) newDefs <- def@allMethods newSigs <- as.list(names(newDefs)) for(j in seq_along(newDefs)) mlist <- Recall(mlist, newArg, c(Class, newSigs[[j]]), fromClass, newDefs[[j]]) } else { def <- .addMethodFrom(def, argName[1L], Class[1L], fromClass) mlist <- insertMethod(mlist, Class, argName, def, TRUE) } mlist } .addMethodFrom <- function(def, arg, Class, fromClass) { if(is(def, "MethodDefinition")) { ## eventually, we may enforce method definition objects ## If not, just leave raw functions alone (NextMethod won't work) def@target[[arg]] <- Class def@defined[[arg]] <- fromClass } def } ## Define a trivial version of asMethodDefinition for bootstrapping. ## The real version requires several class definitions as well as ## methods for as<- asMethodDefinition <- function(def, signature = list(.anyClassName), sealed = FALSE, fdef = def) { if(is.primitive(def) || is(def, "MethodDefinition")) def else { value = new("MethodDefinition") value@.Data <- def classes <- .MakeSignature(new("signature"), def, signature, fdef) value@target <- classes value@defined <- classes value } } .trimMlist <- function(mlist, fromClass) { mlist@methods <- mlist@methods[fromClass] mlist@allMethods <- mlist@allMethods[fromClass] mlist } .noMlistsFlag <- TRUE .noMlists <- function() { ## if this were to be dynamically variable, but ## it can't, IMO ## identical(getOption("noMlists"), TRUE) ## so instead .noMlistsFlag } .MlistDepTable <- new.env() .MlistDeprecated <- function(this = "<default>", instead) { if(is.character(this)) { if(exists(this, envir = .MlistDepTable, inherits = FALSE)) return() else assign(this, TRUE, envir = .MlistDepTable) } msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is deprecated." else if(is.character(this)) gettextf( "%s, along with other use of the \"MethodsList\" metadata objects, is deprecated.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is deprecated.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList. (This warning is shown once per session.)") base::.Deprecated(msg = msg) } .MlistDefunct <- function(this = "<default>", instead) { msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is defunct." else if(is.character(this)) gettextf("%s, along with other use of the \"MethodsList\" metadata objects, is defunct.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is defunct.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList.") base::.Defunct(msg = msg) }
36,574
gpl-2.0
71c4978aaa94135074227729a1d4da375593bdd9
allr/r-instrumented
src/library/methods/R/MethodsList.R
# File src/library/methods/R/MethodsList.R # Part of the R package, https://www.R-project.org # # Copyright (C) 1995-2016 The R Core Team # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # A copy of the GNU General Public License is available at # https://www.R-project.org/Licenses/ MethodsList <- ## Create a MethodsList object out of the arguments. ## ## Conceptually, this object is a named collection of methods to be ## dispatched when the (first) argument in a function call matches the ## class corresponding to one of the names. A final, unnamed element ## (i.e., with name `""') corresponds to the default method. ## ## The elements can be either a function, or another MethodsList. In ## the second case, this list implies dispatching on the second ## argument to the function using that list, given a selection of this ## element on the first argument. Thus, method dispatching on an ## arbitrary number of arguments is defined. ## ## MethodsList objects are used primarily to dispatch OOP-style ## methods and, in R, to emulate S4-style methods. function(.ArgName, ...) { .MlistDeprecated("MethodsList()") value <- makeMethodsList(list(...)) if(is.name(.ArgName)){} else if(is.character(.ArgName) && length(.ArgName) == 1) .ArgName <- as.name(.ArgName) else stop("invalid first argument: should be the name of the first argument in the dispatch") slot(value, "argument") <- .ArgName value } makeMethodsList <- function(object, level=1) { .MlistDeprecated("makeMethodsList()") mnames <- allNames(object) if(.noMlists()) { keep <- mnames %in% c("", "ANY") mnames <- mnames[keep] object <- object[keep] } value <- new("MethodsList") i <- match("", mnames) if(!is.na(i)) { ## convert to ANY mnames[[i]] <- "ANY" names(object) <- mnames } if(anyDuplicated(mnames)) stop(gettextf("duplicate element names in 'MethodsList' at level %d: %s", level, paste("\"", unique(mnames[duplicated(mnames)]), "\"", collapse=", ")), domain = NA) for(i in seq_along(object)) { eli <- object[[i]] if(is(eli, "function") || is(eli, "MethodsList")) {} else if(is(eli, "list") || is(eli, "named")) object[[i]] <- Recall(eli, NULL, level+1) else stop(gettextf("element %d at level %d (class %s) cannot be interpreted as a function or named list", i, level, dQuote(class(eli))), domain = NA) } slot(value, "methods") <- object value } SignatureMethod <- ## construct a MethodsList object containing (only) this method, corresponding ## to the signature; i.e., such that signature[[1L]] is the match for the first ## argument, signature[[2L]] for the second argument, and so on. The string ## "missing" means a match for a missing argument, and "ANY" means use this as the ## default setting at this level. ## ## The first argument is the argument names to be used for dispatch corresponding to ## the signatures. function(names, signature, definition) { .MlistDeprecated("SignatureMethod()") n <- length(signature) if(n > length(names)) stop("arguments 'names' and 'signature' must have the same length") if(n == 0) return(definition) Class <- signature[[n]] name <- names[[n]] m <- MethodsList(name) slot(m, "methods")[[Class]] <- definition slot(m, "argument") <- as.name(name) SignatureMethod(names[-n], signature[-n], m) } insertMethod <- ## insert the definition `def' into the MethodsList object, `mlist', corresponding to ## the signature, and return the modified MethodsList. function(mlist, signature, args, def, cacheOnly = FALSE) { .MlistDeprecated("insertMethod()") if(.noMlists() && !identical(unique(signature), "ANY")) return(mlist) ## Checks for assertions about valid calls. ## See rev. 1.17 for the code before the assertions added. if(identical(args[1L], "...") && !identical(names(signature), "...")) { if(identical(signature[[1L]], "ANY")) stop(gettextf("inserting method with invalid signature matching argument '...' to class %s", dQuote(signature[[1L]])), domain = NA) args <- args[-1L] signature <- signature[-1L] if(length(signature) == 0L) return(mlist) } if(length(signature) == 0L) stop("inserting method corresponding to empty signature") if(!is(mlist, "MethodsList")) stop(gettextf("inserting method into non-methods-list object (class %s)", dQuote(.class1(mlist))), domain = NA) if(length(args) > 1 && !cacheOnly) mlist <- balanceMethodsList(mlist, args) Class <- signature[[1]] methods <- if(cacheOnly) mlist@allMethods else mlist@methods current <- methods[[Class]] if(is(current, "MethodsList")) { nextArg <- as.character(current@argument) sigArgs <- args n <- length(signature) length(sigArgs) <- n if(is.na(match(nextArg, sigArgs))) { n <- match(nextArg, args) - n if(is.na(n)) { ## not in args eitiher n <- 1 args <- c(args, nextArg) } ## make explicit the trailing ANY's needed signature <- c(signature, rep("ANY", n)) } } if(length(signature) == 1) { if(is.null(current)) { if(!is.null(def)) methods[[Class]] <- def ## else, no change } else { which <- match(Class, names(methods)) if(is.null(def)) ## delete the method methods <- methods[-which] else methods[[which]] <- def } } else { ## recursively merge, initializing current if necessary if(is.null(current)) current <- new("MethodsList", argument = as.name(args[2L])) else if(is.function(current)) current <- new("MethodsList", argument = as.name(args[2L]), methods = list(ANY = current)) methods[[Class]] <- Recall(current, signature[-1L], args[-1L], def, cacheOnly) } mlist@allMethods <- methods if(!cacheOnly) mlist@methods <- methods mlist } MethodsListSelect <- ## select the element of a MethodsList object corresponding to the ## actual arguments (as defined in the suppled environment), ## and return the object, extended to include that method if necessary. ## ## Works recursively. At each level finds an argument name from the current `mlist' ## object, and evaluates this argument (if it is not missing), then uses the ## class of the result to select an element of `mlist'. If such an element ## exists and is another `MethodsList' object, `MethodsListSelect' calls itself recursively ## to resolve using further arguments. Matching includes using a default selection or ## a method specifically linked to class `"missing"'. Once a function is found, it ## is returned as the value. If matching fails, NULL is returned. function(f, env, mlist = NULL, fEnv = if(is(fdef, "genericFunction")) environment(fdef) else baseenv(), finalDefault = finalDefaultMethod(mlist), evalArgs = TRUE, useInherited = TRUE, ## supplied when evalArgs is FALSE fdef = getGeneric(f, where = env), # MUST BE SAFE FROM RECUSIVE METHOD SELECTION resetAllowed = TRUE # FALSE when called from selectMethod, .findNextMethod ) { .MlistDeprecated("MethodsListSelect()") if(!resetAllowed) # ensure we restore the real methods for this function resetMlist <- .getMethodsForDispatch(fdef) ## look for call from C dispatch code during another call to MethodsListSelect if(is.null(f)) {} # Recall, not from C else { fMethods <- .getMethodsForDispatch(fdef) if(is.null(mlist) || (evalArgs && is.function(fMethods))) mlist <- fMethods } resetNeeded <- .setIfBase(f, fdef, mlist) # quickly protect against recursion -- see Methods.R if(resetNeeded) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } if(!is(mlist, "MethodsList")) { if(is.function(mlist)) # call to f, inside MethodsListSelect {on.exit(); return(mlist)} if(is.null(f)) # recursive recall of MethodsListSelect stop("invalid method sublist") else if(!is.null(mlist)) # NULL => 1st call to genericFunction stop(gettextf("%f is not a valid generic function: methods list was an object of class %s", sQuote(f), dQuote(class(mlist))), domain = NA) } if(!is.logical(useInherited)) stop(gettextf("%s must be TRUE, FALSE, or a named logical vector of those values; got an object of class %s", sQuote("useInherited"), dQuote(class(useInherited))), domain = NA) if(identical(mlist, .getMethodsForDispatch(fdef))) { resetNeeded <- TRUE ## On the initial call: ## turn off any further method dispatch on this function, to avoid recursive ## loops if f is a function used in MethodsListSelect. ## TODO: Using namespaces in the methods package would eliminate the need for this .setMethodsForDispatch(f, fdef, finalDefault) if(is(mlist, "MethodsList")) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } } argName <- slot(mlist, "argument") arg <- NULL ## => don't use instance-specific inheritance if(evalArgs) { ## check for missing argument. NB: S sense, not that of R base missing() if(missingArg(argName, env, TRUE)) thisClass <- "missing" else { arg <- eval(as.name(argName), env) ## DO use instance-specific inheritance if(missing(arg)) ## S3 weird R code? Bail out! return(finalDefault) thisClass <- .class1(arg) } } else thisClass <- get(as.character(argName), envir = env, inherits = FALSE) if(identical(useInherited, TRUE) || identical(useInherited, FALSE)) thisInherit <- nextUseInherited <- useInherited else { which <- match(as.character(argName), names(useInherited)) if(is.na(which)) { nextUseInherited <- useInherited thisInherit <- TRUE } else { thisInherit <- useInherited[[which]] nextUseInherited <- useInherited[-which] } } fromClass <- thisClass ## will mark the class actually providing the method allMethods <- mlist@allMethods which <- match(thisClass, names(allMethods)) inherited <- is.na(which) selection <- if(inherited) NULL else allMethods[[which]] if(!inherited) { if(is(selection, "function")) { if(is.null(f)) { ## An inherited method at the next level up. ## only the inherited method should be added mlist <- .trimMlist(mlist, fromClass) } value <- mlist ## no change } else { ## recursive call with NULL function name, to allow search to fail & ## to suppress any reset actions. method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef, ) if(is(method, "EmptyMethodsList")) value <- method else { mlist@allMethods[[which]] <- method value <- mlist } } } if(inherited || is(value, "EmptyMethodsList")) { ## direct selection failed at this level or below method <- NULL if(thisInherit) { allSelections <- inheritedSubMethodLists(arg, fromClass, mlist, env) allClasses <- names(allSelections) for(i in seq_along(allSelections)) { selection <- allSelections[[i]] fromClass <- allClasses[[i]] if(is(selection, "function")) method <- selection else if(is(selection, "MethodsList")) { ## go on to try matching further arguments method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef) if(is(method, "EmptyMethodsList")) selection <- method ## recursive selection failed } if(!is(selection, "EmptyMethodsList")) break } } if((is.null(selection) || is(selection, "EmptyMethodsList")) && !is.null(f) && !is.null(finalDefault)) { ## only use the final default method after exhausting all ## other possibilities, at all levels. method <- finalDefault fromClass <- "ANY" } if(is.null(method) || is(method, "EmptyMethodsList")) value <- emptyMethodsList(mlist, thisClass) ## nothing found else { method <- MethodAddCoerce(method, argName, thisClass, fromClass) value <- .insertCachedMethods(mlist, as.character(argName), thisClass, fromClass, method) } } if(!is.null(f)) { ## top level if(is(value, "EmptyMethodsList")) ## selection failed value <- NULL if(resetNeeded) { on.exit() # cancel the restore of the original mlist if(resetAllowed) { if(is.null(value)) resetMlist <- mlist else resetMlist <- value } .setMethodsForDispatch(f, fdef, resetMlist) if(dispatchIsInternal(fdef)) setPrimitiveMethods(f, finalDefault, "set", fdef, resetMlist) } } value } emptyMethodsList <- function(mlist, thisClass = "ANY", sublist = list()) { .MlistDeprecated("emptyMethodsList()") sublist[thisClass] <- list(NULL) new("EmptyMethodsList", argument = mlist@argument, sublist = sublist) } insertMethodInEmptyList <- function(mlist, def) { .MlistDeprecated("insertMethodInEmptyList()") value <- new("MethodsList", argument = mlist@argument) sublist <- mlist@sublist submethods <- sublist[[1L]] if(is.null(submethods)) sublist[[1L]] <- def else sublist[[1L]] <- Recall(submethods, def) value@allMethods <- sublist value } finalDefaultMethod <- ## Return the default method from the generic (it may be NULL, a method object or a primitive. ## this previously searched in a MethodsList object. Once those are gone, the loop should ## be irrelevant except as an error check. function(method) { repeat { if(is.function(method) # <- somewhat liberal, but catches both methods and primitives || is.null(method)) break if(is(method, "MethodsList")) { .MlistDeprecated() method <- slot(method, "methods")[["ANY"]] } else stop(gettextf( "default method must be a method definition, a primitive or NULL: got an object of class %s", dQuote(class(method))), domain = NA) } method } inheritedSubMethodLists <- ## Utility function to match the object to the elements of a methods list. ## ## The function looks only for an inherited match, and only among ## the methods that are not themselves inherited. (Inherited methods when found are ## stored in the session copy of the methods list, but they themselves should not be ## used for finding inherited matches, because an erroneous match could be found depending ## on which methods were previously used. See the detailed discussion of methods.) function(object, thisClass, mlist, ev) { .MlistDeprecated("inheritedSubMethodLists()") methods <- slot(mlist, "methods")## only direct methods defaultMethod <- methods[["ANY"]]## maybe NULL classes <- names(methods) value <- list() if(.identC(thisClass, "missing")) { ## no superclasses for "missing" } else { ## search in the superclasses, but don't use inherited methods ## There are two cases: if thisClass is formally defined & unsealed, use its ## superclasses. Otherwise, look in the subclasses of those classes for ## which methods exist. classDef <- getClassDef(thisClass, ev) useSuperClasses <- !is.null(classDef) && !classDef@sealed if(useSuperClasses) { ## for consistency, order the available methods by ## the ordering of the superclasses of thisClass superClasses <- names(classDef@contains) classes <- superClasses[!is.na(match(superClasses, classes))] for(which in seq_along(classes)) { tryClass <- classes[[which]] ## TODO: There is potential bug here: If the is relation is conditional, ## we should not cache this selection. Needs another trick in the environment ## to FORCE no caching regardless of what happens elsewhere; e.g., storing a ## special object in .Class if(is.null(object) || is(object, tryClass)) { value[[tryClass]] <- methods[[tryClass]] } } } else { for(which in seq_along(classes)) { tryClass <- classes[[which]] tryClassDef <- getClassDef(tryClass, ev) if(!is.null(tryClassDef) && !is.na(match(thisClass, names(tryClassDef@subclasses)))) value[[tryClass]] <- methods[[which]] } } } if(!is.null(defaultMethod)) value[["ANY"]] <- defaultMethod value } matchSignature <- ## Match the signature object (a partially or completely named subset of the ## arguments of `fun', and return a vector of all the classes in the order specified ## by the signature slot of the generic. The classes not specified by `signature ##' will be `"ANY"' in the value. function(signature, fun, where = baseenv()) { if(!is(fun, "genericFunction")) stop(gettextf("trying to match a method signature to an object (of class %s) that is not a generic function", dQuote(class(fun))), domain = NA) anames <- fun@signature if(length(signature) == 0L) return(character()) if(is(signature,"character")) { pkgs <- packageSlot(signature) # includes case of "ObjectsWithPackage" if(is.null(pkgs)) pkgs <- character(length(signature)) else if(length(pkgs) != length(signature)) stop("invalid 'package' slot or attribute, wrong length") sigClasses <- as.character(signature) } else if(is(signature, "list")) { sigClasses <- pkgs <- character(length(signature)) for(i in seq_along(signature)) { cli <- signature[[i]] if(is(cli, "classRepresentation")) { sigClasses[[i]] <- cli@className pkgs[[i]] <- cli@package } else if(is(cli, "character") && length(cli) == 1) { sigClasses[[i]] <- cli pkgi <- packageSlot(cli) if(is.character(pkgi)) pkgs[[i]] <- pkgi } else stop(gettextf("invalid element in a list for \"signature\" argument; element %d is neither a class definition nor a class name", i), domain = NA) } } else stop(gettextf("trying to match a method signature of class %s; expects a list or a character vector", dQuote(class(signature))), domain = NA) if(!identical(where, baseenv())) { ## fill in package information, warn about undefined classes unknown <- !nzchar(pkgs) for(i in seq_along(sigClasses)[unknown]) { cli <- getClassDef(sigClasses[[i]], where) if(!is.null(cli)) { pkgs[[i]] <- cli@package unknown[[i]] <- FALSE } } if(any(unknown)) { unknown <- unique(sigClasses[unknown]) ## coerce(), i.e., setAs() may use *one* unknown class MSG <- if(identical(as.vector(coerce@generic), "coerce") && length(unknown) == 1) message else function(...) warning(..., call. = FALSE) MSG(.renderSignature(fun@generic, signature), sprintf(ngettext(length(unknown), "no definition for class %s", "no definition for classes %s"), paste(dQuote(unknown), collapse = ", ")), domain = NA) } } signature <- as.list(signature) if(length(sigClasses) != length(signature)) stop(gettextf("object to use as a method signature for function %s does not look like a legitimate signature (a vector of single class names): there were %d class names, but %d elements in the signature object", sQuote(fun@generic), length(sigClasses), length(signature)), domain = NA) if(is.null(names(signature))) { which <- seq_along(signature) if(length(which) > length(anames)) stop(gettextf("more elements in the method signature (%d) than in the generic signature (%d) for function %s", length(which), length(anames), sQuote(fun@generic)), domain = NA) } else { ## construct a function call with the same naming pattern & ## values as signature sigList <- signature for(i in seq_along(sigList)) sigList[[i]] <- c(sigClasses[[i]], pkgs[[i]]) fcall <- do.call("call", c("fun", sigList)) ## match the call to the formal signature (usually the formal args) if(identical(anames, formalArgs(fun))) smatch <- match.call(fun, fcall) else { fmatch <- fun ff <- as.list(anames); names(ff) <- anames formals(fmatch, envir = environment(fun)) <- ff smatch <- match.call(fmatch, fcall) } snames <- names(smatch)[-1L] which <- match(snames, anames) ## Assertion: match.call has permuted the args into the order of formal args, ## and carried along the values. Get the supplied classes in that ## order, from the matched args in the call object. if(anyNA(which)) stop(sprintf(ngettext(sum(is.na(which)), "in the method signature for function %s invalid argument name in the signature: %s", "in the method signature for function %s invalid argument names in the signature: %s"), sQuote(fun@generic), paste(snames[is.na(which)], collapse = ", ")), domain = NA) smatch <- smatch[-1] for(i in seq_along(smatch)) { eli <- smatch[[i]] sigClasses[[i]] <- eli[[1]] pkgs[[i]] <- eli[[2]] } } n <- length(anames) value <- rep("ANY", n) valueP <- rep("methods", n) names(value) <- anames value[which] <- sigClasses valueP[which] <- pkgs unspec <- value == "ANY" ## remove the trailing unspecified classes while(n > 1 && unspec[[n]]) n <- n-1 length(value) <- length(valueP) <- n attr(value, "package") <- valueP ## <FIXME> Is there a reason (bootstrapping?) why this ## is not an actual object from class "signature"? ## See .MakeSignature() </FIXME> value } showMlist <- ## Prints the contents of the MethodsList. If `includeDefs' the signatures and the ## corresponding definitions will be printed; otherwise, only the signatures. ## ## If `includeDefs' is `TRUE', the currently known inherited methods are included; ## otherwise, only the directly defined methods. function(mlist, includeDefs = TRUE, inherited = TRUE, classes = NULL, useArgNames = TRUE, printTo = stdout()) { .MlistDeprecated("showMlist()") if(identical(printTo, FALSE)) { tmp <- tempfile() con <- file(tmp, "w") } else con <- printTo object <- linearizeMlist(mlist, inherited) methods <- object@methods signatures <- object@classes args <- object@arguments if(!is.null(classes) && length(signatures)>0) { keep <- !vapply(signatures, function(x, y) all(is.na(match(x, y))), NA, classes) methods <- methods[keep] signatures <- signatures[keep] args <- args[keep] } if(length(methods) == 0) cat(file=con, "<Empty Methods List>\n") else { n <- length(methods) labels <- character(n) if(useArgNames) { for(i in 1L:n) { sigi <- signatures[[i]] labels[[i]] <- paste(args[[i]], " = \"", sigi, "\"", sep = "", collapse = ", ") } } else { for(i in 1L:n) labels[[i]] <- paste(signatures[[i]], collapse = ", ") } for(i in seq_along(methods)) { cat(file=con, (if(includeDefs) "## Signature:" else ""), labels[[i]]) method <- methods[[i]] if(includeDefs) { cat(file=con, ":\n") if(is(method, "MethodDefinition")) ## really an assertion cat(file=con, deparse(method@.Data), sep="\n") else cat(file=con, deparse(method), sep="\n") } if(is(method, "MethodDefinition") && !identical(method@target, method@defined)) { defFrom <- method@defined cat(file = con, if(includeDefs) "##:" else "\n", " (inherited from ", paste(names(defFrom), " = \"", as.character(defFrom), "\"", sep = "", collapse = ", "), ")", if(includeDefs) "\n", sep="") } cat(file=con, "\n") } } if(identical(printTo, FALSE)) { close(con) value <- readLines(tmp) unlink(tmp) value } } promptMethods <- function(f, filename = NULL, methods) { ## Generate information in the style of 'prompt' for the methods of ## the generic named 'f'. ## ## 'filename' can be a logical or NA or the name of a file to print ## to. If it 'FALSE', the methods skeleton is returned, to be ## included in other printing (typically, the output from 'prompt'). escape <- function(txt) gsub("%", "\\\\%", txt) packageString <- "" fdef <- getGeneric(f) if(!isGeneric(f, fdef=fdef)) stop(gettextf("no generic function found corresponding to %s", sQuote(f)), domain = NA) if(missing(methods)) { methods <- findMethods(fdef) ## try making packageString where <- .genEnv(fdef, topenv(parent.frame())) if(!identical(where, .GlobalEnv)) packageString <- sprintf("in Package \\pkg{%s}", getPackageName(where)) } fullName <- utils:::topicName("methods", f) n <- length(methods) labels <- character(n) aliases <- character(n) signatures <- findMethodSignatures(methods = methods, target=TRUE) args <- colnames(signatures) # the *same* for all for(i in seq_len(n)) { sigi <- signatures[i, ] labels[[i]] <- sprintf("\\code{signature(%s)}", paste(sprintf("%s = \"%s\"", args, escape(sigi)), collapse = ", ")) aliases[[i]] <- paste0("\\alias{", utils:::topicName("method", c(f, signatures[i,])), "}") } text <- paste0("\n\\item{", labels, "}{\n%% ~~describe this method here~~\n}") text <- c("\\section{Methods}{\n\\describe{", text, "}}") aliasText <- c(paste0("\\alias{", escape(fullName), "}"), escape(aliases)) if(identical(filename, FALSE)) return(c(aliasText, text)) if(is.null(filename) || identical(filename, TRUE)) filename <- paste0(fullName, ".Rd") Rdtxt <- list(name = paste0("\\name{", fullName, "}"), type = "\\docType{methods}", aliases = aliasText, ## <FIXME> ## Title and description are ok as auto-generated: should ## they be flagged as such (via '~~' which are quite often ## left in by authors)? title = sprintf("\\title{ ~~ Methods for Function \\code{%s} %s ~~}", f, packageString), description = paste0("\\description{\n ~~ Methods for function", " \\code{", f, "} ", sub("^in Package", "in package", packageString), " ~~\n}"), ## </FIXME> "section{Methods}" = text, keywords = c("\\keyword{methods}", "\\keyword{ ~~ other possible keyword(s) ~~ }")) if(is.na(filename)) return(Rdtxt) cat(unlist(Rdtxt), file = filename, sep = "\n") .message("A shell of methods documentation has been written", .fileDesc(filename), ".\n") invisible(filename) } ##' only called from showMlist() above, which has been deprecated in R 3.2.0 (Apr.2015): linearizeMlist <- ## Undo the recursive nature of the methods list, making a list of ## function definitions, with the names of the list being the ## corresponding signatures (designed for printing; for looping over ## the methods, use `listFromMlist' instead). ## ## The function calls itself recursively. `prev' is the previously ## selected class names. ## ## If argument `classes' is provided, only signatures containing one ## of these classes will be included. function(mlist, inherited = TRUE) { methods <- mlist@methods allMethods <- mlist@allMethods if(inherited && length(allMethods) >= length(methods)) { ## anames <- names(allMethods) ## inh <- is.na(match(anames, names(methods))) methods <- allMethods } preC <- function(y, x)c(x,y) # used with lapply below cnames <- names(methods) value <- list() classes <- list() arguments <- list() argname <- as.character(mlist@argument) for(i in seq_along(cnames)) { mi <- methods[[i]] if(is.function(mi)) { value <- c(value, list(mi)) classes <- c(classes, list(cnames[[i]])) arguments <- c(arguments, list(argname)) } else if(is(mi, "MethodsList")) { .MlistDeprecated() mi <- Recall(mi, inherited) value <- c(value, mi@methods) classes <- c(classes, lapply(mi@classes, preC, cnames[[i]])) arguments <- c(arguments, lapply(mi@arguments, preC, argname)) } else warning(gettextf("skipping methods list element %s of unexpected class %s\n\n", paste(cnames[i], collapse = ", "), dQuote(.class1(mi))), domain = NA) } new("LinearMethodsList", methods = value, classes = classes, arguments = arguments) } print.MethodsList <- function(x, ...) showMlist(x) ## In R's own code, this is *only* used in mergeMethods(), deprecated in R 3.2.0 (Apr.2015) listFromMlist <- ## linearizes the MethodsList object into list(sigs, methods); `prefix' is the partial ## signature (a named list of classes) to be prepended to the signatures in this object. ## ## A utility function used to iterate over all the individual methods in the object. function(mlist, prefix = list(), sigs. = TRUE, methods. = TRUE) { methodSlot <- slot(mlist, "methods") mnames <- names(methodSlot) argName <- as.character(slot(mlist, "argument")) sigs <- list() methods <- list() for(i in seq_along(methodSlot)) { thisMethod <- methodSlot[i] thisClass <- mnames[[i]] prefix[[argName]] <- thisClass if(is.function(thisMethod)) { if(sigs.) sigs <- c(sigs, list(prefix)) if(methods.) methods <- c(methods, list(thisMethod)) } else { more <- Recall(thisMethod, prefix) if(sigs.) sigs <- c(sigs, more[[1]]) if(methods.) methods <- c(methods, more[[2]]) } } list(sigs, methods) } .insertCachedMethods <- function(mlist, argName, Class, fromClass, def) { if(is(def, "MethodsList")) { .MlistDeprecated() ## insert all the cached methods in def newArg <- c(argName, as.character(def@argument)) newDefs <- def@allMethods newSigs <- as.list(names(newDefs)) for(j in seq_along(newDefs)) mlist <- Recall(mlist, newArg, c(Class, newSigs[[j]]), fromClass, newDefs[[j]]) } else { def <- .addMethodFrom(def, argName[1L], Class[1L], fromClass) mlist <- insertMethod(mlist, Class, argName, def, TRUE) } mlist } .addMethodFrom <- function(def, arg, Class, fromClass) { if(is(def, "MethodDefinition")) { ## eventually, we may enforce method definition objects ## If not, just leave raw functions alone (NextMethod won't work) def@target[[arg]] <- Class def@defined[[arg]] <- fromClass } def } ## Define a trivial version of asMethodDefinition for bootstrapping. ## The real version requires several class definitions as well as ## methods for as<- asMethodDefinition <- function(def, signature = list(.anyClassName), sealed = FALSE, fdef = def) { if(is.primitive(def) || is(def, "MethodDefinition")) def else { value = new("MethodDefinition") value@.Data <- def classes <- .MakeSignature(new("signature"), def, signature, fdef) value@target <- classes value@defined <- classes value } } .trimMlist <- function(mlist, fromClass) { mlist@methods <- mlist@methods[fromClass] mlist@allMethods <- mlist@allMethods[fromClass] mlist } .noMlistsFlag <- TRUE .noMlists <- function() { ## if this were to be dynamically variable, but ## it can't, IMO ## identical(getOption("noMlists"), TRUE) ## so instead .noMlistsFlag } .MlistDepTable <- new.env() .MlistDeprecated <- function(this = "<default>", instead) { if(is.character(this)) { if(exists(this, envir = .MlistDepTable, inherits = FALSE)) return() else assign(this, TRUE, envir = .MlistDepTable) } msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is deprecated." else if(is.character(this)) gettextf( "%s, along with other use of the \"MethodsList\" metadata objects, is deprecated.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is deprecated.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList. (This warning is shown once per session.)") base::.Deprecated(msg = msg) } .MlistDefunct <- function(this = "<default>", instead) { msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is defunct." else if(is.character(this)) gettextf("%s, along with other use of the \"MethodsList\" metadata objects, is defunct.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is defunct.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList.") base::.Defunct(msg = msg) }
36,574
gpl-2.0
71c4978aaa94135074227729a1d4da375593bdd9
allr/timeR
src/library/methods/R/MethodsList.R
# File src/library/methods/R/MethodsList.R # Part of the R package, https://www.R-project.org # # Copyright (C) 1995-2016 The R Core Team # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # A copy of the GNU General Public License is available at # https://www.R-project.org/Licenses/ MethodsList <- ## Create a MethodsList object out of the arguments. ## ## Conceptually, this object is a named collection of methods to be ## dispatched when the (first) argument in a function call matches the ## class corresponding to one of the names. A final, unnamed element ## (i.e., with name `""') corresponds to the default method. ## ## The elements can be either a function, or another MethodsList. In ## the second case, this list implies dispatching on the second ## argument to the function using that list, given a selection of this ## element on the first argument. Thus, method dispatching on an ## arbitrary number of arguments is defined. ## ## MethodsList objects are used primarily to dispatch OOP-style ## methods and, in R, to emulate S4-style methods. function(.ArgName, ...) { .MlistDeprecated("MethodsList()") value <- makeMethodsList(list(...)) if(is.name(.ArgName)){} else if(is.character(.ArgName) && length(.ArgName) == 1) .ArgName <- as.name(.ArgName) else stop("invalid first argument: should be the name of the first argument in the dispatch") slot(value, "argument") <- .ArgName value } makeMethodsList <- function(object, level=1) { .MlistDeprecated("makeMethodsList()") mnames <- allNames(object) if(.noMlists()) { keep <- mnames %in% c("", "ANY") mnames <- mnames[keep] object <- object[keep] } value <- new("MethodsList") i <- match("", mnames) if(!is.na(i)) { ## convert to ANY mnames[[i]] <- "ANY" names(object) <- mnames } if(anyDuplicated(mnames)) stop(gettextf("duplicate element names in 'MethodsList' at level %d: %s", level, paste("\"", unique(mnames[duplicated(mnames)]), "\"", collapse=", ")), domain = NA) for(i in seq_along(object)) { eli <- object[[i]] if(is(eli, "function") || is(eli, "MethodsList")) {} else if(is(eli, "list") || is(eli, "named")) object[[i]] <- Recall(eli, NULL, level+1) else stop(gettextf("element %d at level %d (class %s) cannot be interpreted as a function or named list", i, level, dQuote(class(eli))), domain = NA) } slot(value, "methods") <- object value } SignatureMethod <- ## construct a MethodsList object containing (only) this method, corresponding ## to the signature; i.e., such that signature[[1L]] is the match for the first ## argument, signature[[2L]] for the second argument, and so on. The string ## "missing" means a match for a missing argument, and "ANY" means use this as the ## default setting at this level. ## ## The first argument is the argument names to be used for dispatch corresponding to ## the signatures. function(names, signature, definition) { .MlistDeprecated("SignatureMethod()") n <- length(signature) if(n > length(names)) stop("arguments 'names' and 'signature' must have the same length") if(n == 0) return(definition) Class <- signature[[n]] name <- names[[n]] m <- MethodsList(name) slot(m, "methods")[[Class]] <- definition slot(m, "argument") <- as.name(name) SignatureMethod(names[-n], signature[-n], m) } insertMethod <- ## insert the definition `def' into the MethodsList object, `mlist', corresponding to ## the signature, and return the modified MethodsList. function(mlist, signature, args, def, cacheOnly = FALSE) { .MlistDeprecated("insertMethod()") if(.noMlists() && !identical(unique(signature), "ANY")) return(mlist) ## Checks for assertions about valid calls. ## See rev. 1.17 for the code before the assertions added. if(identical(args[1L], "...") && !identical(names(signature), "...")) { if(identical(signature[[1L]], "ANY")) stop(gettextf("inserting method with invalid signature matching argument '...' to class %s", dQuote(signature[[1L]])), domain = NA) args <- args[-1L] signature <- signature[-1L] if(length(signature) == 0L) return(mlist) } if(length(signature) == 0L) stop("inserting method corresponding to empty signature") if(!is(mlist, "MethodsList")) stop(gettextf("inserting method into non-methods-list object (class %s)", dQuote(.class1(mlist))), domain = NA) if(length(args) > 1 && !cacheOnly) mlist <- balanceMethodsList(mlist, args) Class <- signature[[1]] methods <- if(cacheOnly) mlist@allMethods else mlist@methods current <- methods[[Class]] if(is(current, "MethodsList")) { nextArg <- as.character(current@argument) sigArgs <- args n <- length(signature) length(sigArgs) <- n if(is.na(match(nextArg, sigArgs))) { n <- match(nextArg, args) - n if(is.na(n)) { ## not in args eitiher n <- 1 args <- c(args, nextArg) } ## make explicit the trailing ANY's needed signature <- c(signature, rep("ANY", n)) } } if(length(signature) == 1) { if(is.null(current)) { if(!is.null(def)) methods[[Class]] <- def ## else, no change } else { which <- match(Class, names(methods)) if(is.null(def)) ## delete the method methods <- methods[-which] else methods[[which]] <- def } } else { ## recursively merge, initializing current if necessary if(is.null(current)) current <- new("MethodsList", argument = as.name(args[2L])) else if(is.function(current)) current <- new("MethodsList", argument = as.name(args[2L]), methods = list(ANY = current)) methods[[Class]] <- Recall(current, signature[-1L], args[-1L], def, cacheOnly) } mlist@allMethods <- methods if(!cacheOnly) mlist@methods <- methods mlist } MethodsListSelect <- ## select the element of a MethodsList object corresponding to the ## actual arguments (as defined in the suppled environment), ## and return the object, extended to include that method if necessary. ## ## Works recursively. At each level finds an argument name from the current `mlist' ## object, and evaluates this argument (if it is not missing), then uses the ## class of the result to select an element of `mlist'. If such an element ## exists and is another `MethodsList' object, `MethodsListSelect' calls itself recursively ## to resolve using further arguments. Matching includes using a default selection or ## a method specifically linked to class `"missing"'. Once a function is found, it ## is returned as the value. If matching fails, NULL is returned. function(f, env, mlist = NULL, fEnv = if(is(fdef, "genericFunction")) environment(fdef) else baseenv(), finalDefault = finalDefaultMethod(mlist), evalArgs = TRUE, useInherited = TRUE, ## supplied when evalArgs is FALSE fdef = getGeneric(f, where = env), # MUST BE SAFE FROM RECUSIVE METHOD SELECTION resetAllowed = TRUE # FALSE when called from selectMethod, .findNextMethod ) { .MlistDeprecated("MethodsListSelect()") if(!resetAllowed) # ensure we restore the real methods for this function resetMlist <- .getMethodsForDispatch(fdef) ## look for call from C dispatch code during another call to MethodsListSelect if(is.null(f)) {} # Recall, not from C else { fMethods <- .getMethodsForDispatch(fdef) if(is.null(mlist) || (evalArgs && is.function(fMethods))) mlist <- fMethods } resetNeeded <- .setIfBase(f, fdef, mlist) # quickly protect against recursion -- see Methods.R if(resetNeeded) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } if(!is(mlist, "MethodsList")) { if(is.function(mlist)) # call to f, inside MethodsListSelect {on.exit(); return(mlist)} if(is.null(f)) # recursive recall of MethodsListSelect stop("invalid method sublist") else if(!is.null(mlist)) # NULL => 1st call to genericFunction stop(gettextf("%f is not a valid generic function: methods list was an object of class %s", sQuote(f), dQuote(class(mlist))), domain = NA) } if(!is.logical(useInherited)) stop(gettextf("%s must be TRUE, FALSE, or a named logical vector of those values; got an object of class %s", sQuote("useInherited"), dQuote(class(useInherited))), domain = NA) if(identical(mlist, .getMethodsForDispatch(fdef))) { resetNeeded <- TRUE ## On the initial call: ## turn off any further method dispatch on this function, to avoid recursive ## loops if f is a function used in MethodsListSelect. ## TODO: Using namespaces in the methods package would eliminate the need for this .setMethodsForDispatch(f, fdef, finalDefault) if(is(mlist, "MethodsList")) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } } argName <- slot(mlist, "argument") arg <- NULL ## => don't use instance-specific inheritance if(evalArgs) { ## check for missing argument. NB: S sense, not that of R base missing() if(missingArg(argName, env, TRUE)) thisClass <- "missing" else { arg <- eval(as.name(argName), env) ## DO use instance-specific inheritance if(missing(arg)) ## S3 weird R code? Bail out! return(finalDefault) thisClass <- .class1(arg) } } else thisClass <- get(as.character(argName), envir = env, inherits = FALSE) if(identical(useInherited, TRUE) || identical(useInherited, FALSE)) thisInherit <- nextUseInherited <- useInherited else { which <- match(as.character(argName), names(useInherited)) if(is.na(which)) { nextUseInherited <- useInherited thisInherit <- TRUE } else { thisInherit <- useInherited[[which]] nextUseInherited <- useInherited[-which] } } fromClass <- thisClass ## will mark the class actually providing the method allMethods <- mlist@allMethods which <- match(thisClass, names(allMethods)) inherited <- is.na(which) selection <- if(inherited) NULL else allMethods[[which]] if(!inherited) { if(is(selection, "function")) { if(is.null(f)) { ## An inherited method at the next level up. ## only the inherited method should be added mlist <- .trimMlist(mlist, fromClass) } value <- mlist ## no change } else { ## recursive call with NULL function name, to allow search to fail & ## to suppress any reset actions. method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef, ) if(is(method, "EmptyMethodsList")) value <- method else { mlist@allMethods[[which]] <- method value <- mlist } } } if(inherited || is(value, "EmptyMethodsList")) { ## direct selection failed at this level or below method <- NULL if(thisInherit) { allSelections <- inheritedSubMethodLists(arg, fromClass, mlist, env) allClasses <- names(allSelections) for(i in seq_along(allSelections)) { selection <- allSelections[[i]] fromClass <- allClasses[[i]] if(is(selection, "function")) method <- selection else if(is(selection, "MethodsList")) { ## go on to try matching further arguments method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef) if(is(method, "EmptyMethodsList")) selection <- method ## recursive selection failed } if(!is(selection, "EmptyMethodsList")) break } } if((is.null(selection) || is(selection, "EmptyMethodsList")) && !is.null(f) && !is.null(finalDefault)) { ## only use the final default method after exhausting all ## other possibilities, at all levels. method <- finalDefault fromClass <- "ANY" } if(is.null(method) || is(method, "EmptyMethodsList")) value <- emptyMethodsList(mlist, thisClass) ## nothing found else { method <- MethodAddCoerce(method, argName, thisClass, fromClass) value <- .insertCachedMethods(mlist, as.character(argName), thisClass, fromClass, method) } } if(!is.null(f)) { ## top level if(is(value, "EmptyMethodsList")) ## selection failed value <- NULL if(resetNeeded) { on.exit() # cancel the restore of the original mlist if(resetAllowed) { if(is.null(value)) resetMlist <- mlist else resetMlist <- value } .setMethodsForDispatch(f, fdef, resetMlist) if(dispatchIsInternal(fdef)) setPrimitiveMethods(f, finalDefault, "set", fdef, resetMlist) } } value } emptyMethodsList <- function(mlist, thisClass = "ANY", sublist = list()) { .MlistDeprecated("emptyMethodsList()") sublist[thisClass] <- list(NULL) new("EmptyMethodsList", argument = mlist@argument, sublist = sublist) } insertMethodInEmptyList <- function(mlist, def) { .MlistDeprecated("insertMethodInEmptyList()") value <- new("MethodsList", argument = mlist@argument) sublist <- mlist@sublist submethods <- sublist[[1L]] if(is.null(submethods)) sublist[[1L]] <- def else sublist[[1L]] <- Recall(submethods, def) value@allMethods <- sublist value } finalDefaultMethod <- ## Return the default method from the generic (it may be NULL, a method object or a primitive. ## this previously searched in a MethodsList object. Once those are gone, the loop should ## be irrelevant except as an error check. function(method) { repeat { if(is.function(method) # <- somewhat liberal, but catches both methods and primitives || is.null(method)) break if(is(method, "MethodsList")) { .MlistDeprecated() method <- slot(method, "methods")[["ANY"]] } else stop(gettextf( "default method must be a method definition, a primitive or NULL: got an object of class %s", dQuote(class(method))), domain = NA) } method } inheritedSubMethodLists <- ## Utility function to match the object to the elements of a methods list. ## ## The function looks only for an inherited match, and only among ## the methods that are not themselves inherited. (Inherited methods when found are ## stored in the session copy of the methods list, but they themselves should not be ## used for finding inherited matches, because an erroneous match could be found depending ## on which methods were previously used. See the detailed discussion of methods.) function(object, thisClass, mlist, ev) { .MlistDeprecated("inheritedSubMethodLists()") methods <- slot(mlist, "methods")## only direct methods defaultMethod <- methods[["ANY"]]## maybe NULL classes <- names(methods) value <- list() if(.identC(thisClass, "missing")) { ## no superclasses for "missing" } else { ## search in the superclasses, but don't use inherited methods ## There are two cases: if thisClass is formally defined & unsealed, use its ## superclasses. Otherwise, look in the subclasses of those classes for ## which methods exist. classDef <- getClassDef(thisClass, ev) useSuperClasses <- !is.null(classDef) && !classDef@sealed if(useSuperClasses) { ## for consistency, order the available methods by ## the ordering of the superclasses of thisClass superClasses <- names(classDef@contains) classes <- superClasses[!is.na(match(superClasses, classes))] for(which in seq_along(classes)) { tryClass <- classes[[which]] ## TODO: There is potential bug here: If the is relation is conditional, ## we should not cache this selection. Needs another trick in the environment ## to FORCE no caching regardless of what happens elsewhere; e.g., storing a ## special object in .Class if(is.null(object) || is(object, tryClass)) { value[[tryClass]] <- methods[[tryClass]] } } } else { for(which in seq_along(classes)) { tryClass <- classes[[which]] tryClassDef <- getClassDef(tryClass, ev) if(!is.null(tryClassDef) && !is.na(match(thisClass, names(tryClassDef@subclasses)))) value[[tryClass]] <- methods[[which]] } } } if(!is.null(defaultMethod)) value[["ANY"]] <- defaultMethod value } matchSignature <- ## Match the signature object (a partially or completely named subset of the ## arguments of `fun', and return a vector of all the classes in the order specified ## by the signature slot of the generic. The classes not specified by `signature ##' will be `"ANY"' in the value. function(signature, fun, where = baseenv()) { if(!is(fun, "genericFunction")) stop(gettextf("trying to match a method signature to an object (of class %s) that is not a generic function", dQuote(class(fun))), domain = NA) anames <- fun@signature if(length(signature) == 0L) return(character()) if(is(signature,"character")) { pkgs <- packageSlot(signature) # includes case of "ObjectsWithPackage" if(is.null(pkgs)) pkgs <- character(length(signature)) else if(length(pkgs) != length(signature)) stop("invalid 'package' slot or attribute, wrong length") sigClasses <- as.character(signature) } else if(is(signature, "list")) { sigClasses <- pkgs <- character(length(signature)) for(i in seq_along(signature)) { cli <- signature[[i]] if(is(cli, "classRepresentation")) { sigClasses[[i]] <- cli@className pkgs[[i]] <- cli@package } else if(is(cli, "character") && length(cli) == 1) { sigClasses[[i]] <- cli pkgi <- packageSlot(cli) if(is.character(pkgi)) pkgs[[i]] <- pkgi } else stop(gettextf("invalid element in a list for \"signature\" argument; element %d is neither a class definition nor a class name", i), domain = NA) } } else stop(gettextf("trying to match a method signature of class %s; expects a list or a character vector", dQuote(class(signature))), domain = NA) if(!identical(where, baseenv())) { ## fill in package information, warn about undefined classes unknown <- !nzchar(pkgs) for(i in seq_along(sigClasses)[unknown]) { cli <- getClassDef(sigClasses[[i]], where) if(!is.null(cli)) { pkgs[[i]] <- cli@package unknown[[i]] <- FALSE } } if(any(unknown)) { unknown <- unique(sigClasses[unknown]) ## coerce(), i.e., setAs() may use *one* unknown class MSG <- if(identical(as.vector(coerce@generic), "coerce") && length(unknown) == 1) message else function(...) warning(..., call. = FALSE) MSG(.renderSignature(fun@generic, signature), sprintf(ngettext(length(unknown), "no definition for class %s", "no definition for classes %s"), paste(dQuote(unknown), collapse = ", ")), domain = NA) } } signature <- as.list(signature) if(length(sigClasses) != length(signature)) stop(gettextf("object to use as a method signature for function %s does not look like a legitimate signature (a vector of single class names): there were %d class names, but %d elements in the signature object", sQuote(fun@generic), length(sigClasses), length(signature)), domain = NA) if(is.null(names(signature))) { which <- seq_along(signature) if(length(which) > length(anames)) stop(gettextf("more elements in the method signature (%d) than in the generic signature (%d) for function %s", length(which), length(anames), sQuote(fun@generic)), domain = NA) } else { ## construct a function call with the same naming pattern & ## values as signature sigList <- signature for(i in seq_along(sigList)) sigList[[i]] <- c(sigClasses[[i]], pkgs[[i]]) fcall <- do.call("call", c("fun", sigList)) ## match the call to the formal signature (usually the formal args) if(identical(anames, formalArgs(fun))) smatch <- match.call(fun, fcall) else { fmatch <- fun ff <- as.list(anames); names(ff) <- anames formals(fmatch, envir = environment(fun)) <- ff smatch <- match.call(fmatch, fcall) } snames <- names(smatch)[-1L] which <- match(snames, anames) ## Assertion: match.call has permuted the args into the order of formal args, ## and carried along the values. Get the supplied classes in that ## order, from the matched args in the call object. if(anyNA(which)) stop(sprintf(ngettext(sum(is.na(which)), "in the method signature for function %s invalid argument name in the signature: %s", "in the method signature for function %s invalid argument names in the signature: %s"), sQuote(fun@generic), paste(snames[is.na(which)], collapse = ", ")), domain = NA) smatch <- smatch[-1] for(i in seq_along(smatch)) { eli <- smatch[[i]] sigClasses[[i]] <- eli[[1]] pkgs[[i]] <- eli[[2]] } } n <- length(anames) value <- rep("ANY", n) valueP <- rep("methods", n) names(value) <- anames value[which] <- sigClasses valueP[which] <- pkgs unspec <- value == "ANY" ## remove the trailing unspecified classes while(n > 1 && unspec[[n]]) n <- n-1 length(value) <- length(valueP) <- n attr(value, "package") <- valueP ## <FIXME> Is there a reason (bootstrapping?) why this ## is not an actual object from class "signature"? ## See .MakeSignature() </FIXME> value } showMlist <- ## Prints the contents of the MethodsList. If `includeDefs' the signatures and the ## corresponding definitions will be printed; otherwise, only the signatures. ## ## If `includeDefs' is `TRUE', the currently known inherited methods are included; ## otherwise, only the directly defined methods. function(mlist, includeDefs = TRUE, inherited = TRUE, classes = NULL, useArgNames = TRUE, printTo = stdout()) { .MlistDeprecated("showMlist()") if(identical(printTo, FALSE)) { tmp <- tempfile() con <- file(tmp, "w") } else con <- printTo object <- linearizeMlist(mlist, inherited) methods <- object@methods signatures <- object@classes args <- object@arguments if(!is.null(classes) && length(signatures)>0) { keep <- !vapply(signatures, function(x, y) all(is.na(match(x, y))), NA, classes) methods <- methods[keep] signatures <- signatures[keep] args <- args[keep] } if(length(methods) == 0) cat(file=con, "<Empty Methods List>\n") else { n <- length(methods) labels <- character(n) if(useArgNames) { for(i in 1L:n) { sigi <- signatures[[i]] labels[[i]] <- paste(args[[i]], " = \"", sigi, "\"", sep = "", collapse = ", ") } } else { for(i in 1L:n) labels[[i]] <- paste(signatures[[i]], collapse = ", ") } for(i in seq_along(methods)) { cat(file=con, (if(includeDefs) "## Signature:" else ""), labels[[i]]) method <- methods[[i]] if(includeDefs) { cat(file=con, ":\n") if(is(method, "MethodDefinition")) ## really an assertion cat(file=con, deparse(method@.Data), sep="\n") else cat(file=con, deparse(method), sep="\n") } if(is(method, "MethodDefinition") && !identical(method@target, method@defined)) { defFrom <- method@defined cat(file = con, if(includeDefs) "##:" else "\n", " (inherited from ", paste(names(defFrom), " = \"", as.character(defFrom), "\"", sep = "", collapse = ", "), ")", if(includeDefs) "\n", sep="") } cat(file=con, "\n") } } if(identical(printTo, FALSE)) { close(con) value <- readLines(tmp) unlink(tmp) value } } promptMethods <- function(f, filename = NULL, methods) { ## Generate information in the style of 'prompt' for the methods of ## the generic named 'f'. ## ## 'filename' can be a logical or NA or the name of a file to print ## to. If it 'FALSE', the methods skeleton is returned, to be ## included in other printing (typically, the output from 'prompt'). escape <- function(txt) gsub("%", "\\\\%", txt) packageString <- "" fdef <- getGeneric(f) if(!isGeneric(f, fdef=fdef)) stop(gettextf("no generic function found corresponding to %s", sQuote(f)), domain = NA) if(missing(methods)) { methods <- findMethods(fdef) ## try making packageString where <- .genEnv(fdef, topenv(parent.frame())) if(!identical(where, .GlobalEnv)) packageString <- sprintf("in Package \\pkg{%s}", getPackageName(where)) } fullName <- utils:::topicName("methods", f) n <- length(methods) labels <- character(n) aliases <- character(n) signatures <- findMethodSignatures(methods = methods, target=TRUE) args <- colnames(signatures) # the *same* for all for(i in seq_len(n)) { sigi <- signatures[i, ] labels[[i]] <- sprintf("\\code{signature(%s)}", paste(sprintf("%s = \"%s\"", args, escape(sigi)), collapse = ", ")) aliases[[i]] <- paste0("\\alias{", utils:::topicName("method", c(f, signatures[i,])), "}") } text <- paste0("\n\\item{", labels, "}{\n%% ~~describe this method here~~\n}") text <- c("\\section{Methods}{\n\\describe{", text, "}}") aliasText <- c(paste0("\\alias{", escape(fullName), "}"), escape(aliases)) if(identical(filename, FALSE)) return(c(aliasText, text)) if(is.null(filename) || identical(filename, TRUE)) filename <- paste0(fullName, ".Rd") Rdtxt <- list(name = paste0("\\name{", fullName, "}"), type = "\\docType{methods}", aliases = aliasText, ## <FIXME> ## Title and description are ok as auto-generated: should ## they be flagged as such (via '~~' which are quite often ## left in by authors)? title = sprintf("\\title{ ~~ Methods for Function \\code{%s} %s ~~}", f, packageString), description = paste0("\\description{\n ~~ Methods for function", " \\code{", f, "} ", sub("^in Package", "in package", packageString), " ~~\n}"), ## </FIXME> "section{Methods}" = text, keywords = c("\\keyword{methods}", "\\keyword{ ~~ other possible keyword(s) ~~ }")) if(is.na(filename)) return(Rdtxt) cat(unlist(Rdtxt), file = filename, sep = "\n") .message("A shell of methods documentation has been written", .fileDesc(filename), ".\n") invisible(filename) } ##' only called from showMlist() above, which has been deprecated in R 3.2.0 (Apr.2015): linearizeMlist <- ## Undo the recursive nature of the methods list, making a list of ## function definitions, with the names of the list being the ## corresponding signatures (designed for printing; for looping over ## the methods, use `listFromMlist' instead). ## ## The function calls itself recursively. `prev' is the previously ## selected class names. ## ## If argument `classes' is provided, only signatures containing one ## of these classes will be included. function(mlist, inherited = TRUE) { methods <- mlist@methods allMethods <- mlist@allMethods if(inherited && length(allMethods) >= length(methods)) { ## anames <- names(allMethods) ## inh <- is.na(match(anames, names(methods))) methods <- allMethods } preC <- function(y, x)c(x,y) # used with lapply below cnames <- names(methods) value <- list() classes <- list() arguments <- list() argname <- as.character(mlist@argument) for(i in seq_along(cnames)) { mi <- methods[[i]] if(is.function(mi)) { value <- c(value, list(mi)) classes <- c(classes, list(cnames[[i]])) arguments <- c(arguments, list(argname)) } else if(is(mi, "MethodsList")) { .MlistDeprecated() mi <- Recall(mi, inherited) value <- c(value, mi@methods) classes <- c(classes, lapply(mi@classes, preC, cnames[[i]])) arguments <- c(arguments, lapply(mi@arguments, preC, argname)) } else warning(gettextf("skipping methods list element %s of unexpected class %s\n\n", paste(cnames[i], collapse = ", "), dQuote(.class1(mi))), domain = NA) } new("LinearMethodsList", methods = value, classes = classes, arguments = arguments) } print.MethodsList <- function(x, ...) showMlist(x) ## In R's own code, this is *only* used in mergeMethods(), deprecated in R 3.2.0 (Apr.2015) listFromMlist <- ## linearizes the MethodsList object into list(sigs, methods); `prefix' is the partial ## signature (a named list of classes) to be prepended to the signatures in this object. ## ## A utility function used to iterate over all the individual methods in the object. function(mlist, prefix = list(), sigs. = TRUE, methods. = TRUE) { methodSlot <- slot(mlist, "methods") mnames <- names(methodSlot) argName <- as.character(slot(mlist, "argument")) sigs <- list() methods <- list() for(i in seq_along(methodSlot)) { thisMethod <- methodSlot[i] thisClass <- mnames[[i]] prefix[[argName]] <- thisClass if(is.function(thisMethod)) { if(sigs.) sigs <- c(sigs, list(prefix)) if(methods.) methods <- c(methods, list(thisMethod)) } else { more <- Recall(thisMethod, prefix) if(sigs.) sigs <- c(sigs, more[[1]]) if(methods.) methods <- c(methods, more[[2]]) } } list(sigs, methods) } .insertCachedMethods <- function(mlist, argName, Class, fromClass, def) { if(is(def, "MethodsList")) { .MlistDeprecated() ## insert all the cached methods in def newArg <- c(argName, as.character(def@argument)) newDefs <- def@allMethods newSigs <- as.list(names(newDefs)) for(j in seq_along(newDefs)) mlist <- Recall(mlist, newArg, c(Class, newSigs[[j]]), fromClass, newDefs[[j]]) } else { def <- .addMethodFrom(def, argName[1L], Class[1L], fromClass) mlist <- insertMethod(mlist, Class, argName, def, TRUE) } mlist } .addMethodFrom <- function(def, arg, Class, fromClass) { if(is(def, "MethodDefinition")) { ## eventually, we may enforce method definition objects ## If not, just leave raw functions alone (NextMethod won't work) def@target[[arg]] <- Class def@defined[[arg]] <- fromClass } def } ## Define a trivial version of asMethodDefinition for bootstrapping. ## The real version requires several class definitions as well as ## methods for as<- asMethodDefinition <- function(def, signature = list(.anyClassName), sealed = FALSE, fdef = def) { if(is.primitive(def) || is(def, "MethodDefinition")) def else { value = new("MethodDefinition") value@.Data <- def classes <- .MakeSignature(new("signature"), def, signature, fdef) value@target <- classes value@defined <- classes value } } .trimMlist <- function(mlist, fromClass) { mlist@methods <- mlist@methods[fromClass] mlist@allMethods <- mlist@allMethods[fromClass] mlist } .noMlistsFlag <- TRUE .noMlists <- function() { ## if this were to be dynamically variable, but ## it can't, IMO ## identical(getOption("noMlists"), TRUE) ## so instead .noMlistsFlag } .MlistDepTable <- new.env() .MlistDeprecated <- function(this = "<default>", instead) { if(is.character(this)) { if(exists(this, envir = .MlistDepTable, inherits = FALSE)) return() else assign(this, TRUE, envir = .MlistDepTable) } msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is deprecated." else if(is.character(this)) gettextf( "%s, along with other use of the \"MethodsList\" metadata objects, is deprecated.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is deprecated.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList. (This warning is shown once per session.)") base::.Deprecated(msg = msg) } .MlistDefunct <- function(this = "<default>", instead) { msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is defunct." else if(is.character(this)) gettextf("%s, along with other use of the \"MethodsList\" metadata objects, is defunct.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is defunct.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList.") base::.Defunct(msg = msg) }
36,574
gpl-2.0
71c4978aaa94135074227729a1d4da375593bdd9
kmillar/rho
src/library/methods/R/MethodsList.R
# File src/library/methods/R/MethodsList.R # Part of the R package, https://www.R-project.org # # Copyright (C) 1995-2016 The R Core Team # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # A copy of the GNU General Public License is available at # https://www.R-project.org/Licenses/ MethodsList <- ## Create a MethodsList object out of the arguments. ## ## Conceptually, this object is a named collection of methods to be ## dispatched when the (first) argument in a function call matches the ## class corresponding to one of the names. A final, unnamed element ## (i.e., with name `""') corresponds to the default method. ## ## The elements can be either a function, or another MethodsList. In ## the second case, this list implies dispatching on the second ## argument to the function using that list, given a selection of this ## element on the first argument. Thus, method dispatching on an ## arbitrary number of arguments is defined. ## ## MethodsList objects are used primarily to dispatch OOP-style ## methods and, in R, to emulate S4-style methods. function(.ArgName, ...) { .MlistDeprecated("MethodsList()") value <- makeMethodsList(list(...)) if(is.name(.ArgName)){} else if(is.character(.ArgName) && length(.ArgName) == 1) .ArgName <- as.name(.ArgName) else stop("invalid first argument: should be the name of the first argument in the dispatch") slot(value, "argument") <- .ArgName value } makeMethodsList <- function(object, level=1) { .MlistDeprecated("makeMethodsList()") mnames <- allNames(object) if(.noMlists()) { keep <- mnames %in% c("", "ANY") mnames <- mnames[keep] object <- object[keep] } value <- new("MethodsList") i <- match("", mnames) if(!is.na(i)) { ## convert to ANY mnames[[i]] <- "ANY" names(object) <- mnames } if(anyDuplicated(mnames)) stop(gettextf("duplicate element names in 'MethodsList' at level %d: %s", level, paste("\"", unique(mnames[duplicated(mnames)]), "\"", collapse=", ")), domain = NA) for(i in seq_along(object)) { eli <- object[[i]] if(is(eli, "function") || is(eli, "MethodsList")) {} else if(is(eli, "list") || is(eli, "named")) object[[i]] <- Recall(eli, NULL, level+1) else stop(gettextf("element %d at level %d (class %s) cannot be interpreted as a function or named list", i, level, dQuote(class(eli))), domain = NA) } slot(value, "methods") <- object value } SignatureMethod <- ## construct a MethodsList object containing (only) this method, corresponding ## to the signature; i.e., such that signature[[1L]] is the match for the first ## argument, signature[[2L]] for the second argument, and so on. The string ## "missing" means a match for a missing argument, and "ANY" means use this as the ## default setting at this level. ## ## The first argument is the argument names to be used for dispatch corresponding to ## the signatures. function(names, signature, definition) { .MlistDeprecated("SignatureMethod()") n <- length(signature) if(n > length(names)) stop("arguments 'names' and 'signature' must have the same length") if(n == 0) return(definition) Class <- signature[[n]] name <- names[[n]] m <- MethodsList(name) slot(m, "methods")[[Class]] <- definition slot(m, "argument") <- as.name(name) SignatureMethod(names[-n], signature[-n], m) } insertMethod <- ## insert the definition `def' into the MethodsList object, `mlist', corresponding to ## the signature, and return the modified MethodsList. function(mlist, signature, args, def, cacheOnly = FALSE) { .MlistDeprecated("insertMethod()") if(.noMlists() && !identical(unique(signature), "ANY")) return(mlist) ## Checks for assertions about valid calls. ## See rev. 1.17 for the code before the assertions added. if(identical(args[1L], "...") && !identical(names(signature), "...")) { if(identical(signature[[1L]], "ANY")) stop(gettextf("inserting method with invalid signature matching argument '...' to class %s", dQuote(signature[[1L]])), domain = NA) args <- args[-1L] signature <- signature[-1L] if(length(signature) == 0L) return(mlist) } if(length(signature) == 0L) stop("inserting method corresponding to empty signature") if(!is(mlist, "MethodsList")) stop(gettextf("inserting method into non-methods-list object (class %s)", dQuote(.class1(mlist))), domain = NA) if(length(args) > 1 && !cacheOnly) mlist <- balanceMethodsList(mlist, args) Class <- signature[[1]] methods <- if(cacheOnly) mlist@allMethods else mlist@methods current <- methods[[Class]] if(is(current, "MethodsList")) { nextArg <- as.character(current@argument) sigArgs <- args n <- length(signature) length(sigArgs) <- n if(is.na(match(nextArg, sigArgs))) { n <- match(nextArg, args) - n if(is.na(n)) { ## not in args eitiher n <- 1 args <- c(args, nextArg) } ## make explicit the trailing ANY's needed signature <- c(signature, rep("ANY", n)) } } if(length(signature) == 1) { if(is.null(current)) { if(!is.null(def)) methods[[Class]] <- def ## else, no change } else { which <- match(Class, names(methods)) if(is.null(def)) ## delete the method methods <- methods[-which] else methods[[which]] <- def } } else { ## recursively merge, initializing current if necessary if(is.null(current)) current <- new("MethodsList", argument = as.name(args[2L])) else if(is.function(current)) current <- new("MethodsList", argument = as.name(args[2L]), methods = list(ANY = current)) methods[[Class]] <- Recall(current, signature[-1L], args[-1L], def, cacheOnly) } mlist@allMethods <- methods if(!cacheOnly) mlist@methods <- methods mlist } MethodsListSelect <- ## select the element of a MethodsList object corresponding to the ## actual arguments (as defined in the suppled environment), ## and return the object, extended to include that method if necessary. ## ## Works recursively. At each level finds an argument name from the current `mlist' ## object, and evaluates this argument (if it is not missing), then uses the ## class of the result to select an element of `mlist'. If such an element ## exists and is another `MethodsList' object, `MethodsListSelect' calls itself recursively ## to resolve using further arguments. Matching includes using a default selection or ## a method specifically linked to class `"missing"'. Once a function is found, it ## is returned as the value. If matching fails, NULL is returned. function(f, env, mlist = NULL, fEnv = if(is(fdef, "genericFunction")) environment(fdef) else baseenv(), finalDefault = finalDefaultMethod(mlist), evalArgs = TRUE, useInherited = TRUE, ## supplied when evalArgs is FALSE fdef = getGeneric(f, where = env), # MUST BE SAFE FROM RECUSIVE METHOD SELECTION resetAllowed = TRUE # FALSE when called from selectMethod, .findNextMethod ) { .MlistDeprecated("MethodsListSelect()") if(!resetAllowed) # ensure we restore the real methods for this function resetMlist <- .getMethodsForDispatch(fdef) ## look for call from C dispatch code during another call to MethodsListSelect if(is.null(f)) {} # Recall, not from C else { fMethods <- .getMethodsForDispatch(fdef) if(is.null(mlist) || (evalArgs && is.function(fMethods))) mlist <- fMethods } resetNeeded <- .setIfBase(f, fdef, mlist) # quickly protect against recursion -- see Methods.R if(resetNeeded) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } if(!is(mlist, "MethodsList")) { if(is.function(mlist)) # call to f, inside MethodsListSelect {on.exit(); return(mlist)} if(is.null(f)) # recursive recall of MethodsListSelect stop("invalid method sublist") else if(!is.null(mlist)) # NULL => 1st call to genericFunction stop(gettextf("%f is not a valid generic function: methods list was an object of class %s", sQuote(f), dQuote(class(mlist))), domain = NA) } if(!is.logical(useInherited)) stop(gettextf("%s must be TRUE, FALSE, or a named logical vector of those values; got an object of class %s", sQuote("useInherited"), dQuote(class(useInherited))), domain = NA) if(identical(mlist, .getMethodsForDispatch(fdef))) { resetNeeded <- TRUE ## On the initial call: ## turn off any further method dispatch on this function, to avoid recursive ## loops if f is a function used in MethodsListSelect. ## TODO: Using namespaces in the methods package would eliminate the need for this .setMethodsForDispatch(f, fdef, finalDefault) if(is(mlist, "MethodsList")) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } } argName <- slot(mlist, "argument") arg <- NULL ## => don't use instance-specific inheritance if(evalArgs) { ## check for missing argument. NB: S sense, not that of R base missing() if(missingArg(argName, env, TRUE)) thisClass <- "missing" else { arg <- eval(as.name(argName), env) ## DO use instance-specific inheritance if(missing(arg)) ## S3 weird R code? Bail out! return(finalDefault) thisClass <- .class1(arg) } } else thisClass <- get(as.character(argName), envir = env, inherits = FALSE) if(identical(useInherited, TRUE) || identical(useInherited, FALSE)) thisInherit <- nextUseInherited <- useInherited else { which <- match(as.character(argName), names(useInherited)) if(is.na(which)) { nextUseInherited <- useInherited thisInherit <- TRUE } else { thisInherit <- useInherited[[which]] nextUseInherited <- useInherited[-which] } } fromClass <- thisClass ## will mark the class actually providing the method allMethods <- mlist@allMethods which <- match(thisClass, names(allMethods)) inherited <- is.na(which) selection <- if(inherited) NULL else allMethods[[which]] if(!inherited) { if(is(selection, "function")) { if(is.null(f)) { ## An inherited method at the next level up. ## only the inherited method should be added mlist <- .trimMlist(mlist, fromClass) } value <- mlist ## no change } else { ## recursive call with NULL function name, to allow search to fail & ## to suppress any reset actions. method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef, ) if(is(method, "EmptyMethodsList")) value <- method else { mlist@allMethods[[which]] <- method value <- mlist } } } if(inherited || is(value, "EmptyMethodsList")) { ## direct selection failed at this level or below method <- NULL if(thisInherit) { allSelections <- inheritedSubMethodLists(arg, fromClass, mlist, env) allClasses <- names(allSelections) for(i in seq_along(allSelections)) { selection <- allSelections[[i]] fromClass <- allClasses[[i]] if(is(selection, "function")) method <- selection else if(is(selection, "MethodsList")) { ## go on to try matching further arguments method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef) if(is(method, "EmptyMethodsList")) selection <- method ## recursive selection failed } if(!is(selection, "EmptyMethodsList")) break } } if((is.null(selection) || is(selection, "EmptyMethodsList")) && !is.null(f) && !is.null(finalDefault)) { ## only use the final default method after exhausting all ## other possibilities, at all levels. method <- finalDefault fromClass <- "ANY" } if(is.null(method) || is(method, "EmptyMethodsList")) value <- emptyMethodsList(mlist, thisClass) ## nothing found else { method <- MethodAddCoerce(method, argName, thisClass, fromClass) value <- .insertCachedMethods(mlist, as.character(argName), thisClass, fromClass, method) } } if(!is.null(f)) { ## top level if(is(value, "EmptyMethodsList")) ## selection failed value <- NULL if(resetNeeded) { on.exit() # cancel the restore of the original mlist if(resetAllowed) { if(is.null(value)) resetMlist <- mlist else resetMlist <- value } .setMethodsForDispatch(f, fdef, resetMlist) if(dispatchIsInternal(fdef)) setPrimitiveMethods(f, finalDefault, "set", fdef, resetMlist) } } value } emptyMethodsList <- function(mlist, thisClass = "ANY", sublist = list()) { .MlistDeprecated("emptyMethodsList()") sublist[thisClass] <- list(NULL) new("EmptyMethodsList", argument = mlist@argument, sublist = sublist) } insertMethodInEmptyList <- function(mlist, def) { .MlistDeprecated("insertMethodInEmptyList()") value <- new("MethodsList", argument = mlist@argument) sublist <- mlist@sublist submethods <- sublist[[1L]] if(is.null(submethods)) sublist[[1L]] <- def else sublist[[1L]] <- Recall(submethods, def) value@allMethods <- sublist value } finalDefaultMethod <- ## Return the default method from the generic (it may be NULL, a method object or a primitive. ## this previously searched in a MethodsList object. Once those are gone, the loop should ## be irrelevant except as an error check. function(method) { repeat { if(is.function(method) # <- somewhat liberal, but catches both methods and primitives || is.null(method)) break if(is(method, "MethodsList")) { .MlistDeprecated() method <- slot(method, "methods")[["ANY"]] } else stop(gettextf( "default method must be a method definition, a primitive or NULL: got an object of class %s", dQuote(class(method))), domain = NA) } method } inheritedSubMethodLists <- ## Utility function to match the object to the elements of a methods list. ## ## The function looks only for an inherited match, and only among ## the methods that are not themselves inherited. (Inherited methods when found are ## stored in the session copy of the methods list, but they themselves should not be ## used for finding inherited matches, because an erroneous match could be found depending ## on which methods were previously used. See the detailed discussion of methods.) function(object, thisClass, mlist, ev) { .MlistDeprecated("inheritedSubMethodLists()") methods <- slot(mlist, "methods")## only direct methods defaultMethod <- methods[["ANY"]]## maybe NULL classes <- names(methods) value <- list() if(.identC(thisClass, "missing")) { ## no superclasses for "missing" } else { ## search in the superclasses, but don't use inherited methods ## There are two cases: if thisClass is formally defined & unsealed, use its ## superclasses. Otherwise, look in the subclasses of those classes for ## which methods exist. classDef <- getClassDef(thisClass, ev) useSuperClasses <- !is.null(classDef) && !classDef@sealed if(useSuperClasses) { ## for consistency, order the available methods by ## the ordering of the superclasses of thisClass superClasses <- names(classDef@contains) classes <- superClasses[!is.na(match(superClasses, classes))] for(which in seq_along(classes)) { tryClass <- classes[[which]] ## TODO: There is potential bug here: If the is relation is conditional, ## we should not cache this selection. Needs another trick in the environment ## to FORCE no caching regardless of what happens elsewhere; e.g., storing a ## special object in .Class if(is.null(object) || is(object, tryClass)) { value[[tryClass]] <- methods[[tryClass]] } } } else { for(which in seq_along(classes)) { tryClass <- classes[[which]] tryClassDef <- getClassDef(tryClass, ev) if(!is.null(tryClassDef) && !is.na(match(thisClass, names(tryClassDef@subclasses)))) value[[tryClass]] <- methods[[which]] } } } if(!is.null(defaultMethod)) value[["ANY"]] <- defaultMethod value } matchSignature <- ## Match the signature object (a partially or completely named subset of the ## arguments of `fun', and return a vector of all the classes in the order specified ## by the signature slot of the generic. The classes not specified by `signature ##' will be `"ANY"' in the value. function(signature, fun, where = baseenv()) { if(!is(fun, "genericFunction")) stop(gettextf("trying to match a method signature to an object (of class %s) that is not a generic function", dQuote(class(fun))), domain = NA) anames <- fun@signature if(length(signature) == 0L) return(character()) if(is(signature,"character")) { pkgs <- packageSlot(signature) # includes case of "ObjectsWithPackage" if(is.null(pkgs)) pkgs <- character(length(signature)) else if(length(pkgs) != length(signature)) stop("invalid 'package' slot or attribute, wrong length") sigClasses <- as.character(signature) } else if(is(signature, "list")) { sigClasses <- pkgs <- character(length(signature)) for(i in seq_along(signature)) { cli <- signature[[i]] if(is(cli, "classRepresentation")) { sigClasses[[i]] <- cli@className pkgs[[i]] <- cli@package } else if(is(cli, "character") && length(cli) == 1) { sigClasses[[i]] <- cli pkgi <- packageSlot(cli) if(is.character(pkgi)) pkgs[[i]] <- pkgi } else stop(gettextf("invalid element in a list for \"signature\" argument; element %d is neither a class definition nor a class name", i), domain = NA) } } else stop(gettextf("trying to match a method signature of class %s; expects a list or a character vector", dQuote(class(signature))), domain = NA) if(!identical(where, baseenv())) { ## fill in package information, warn about undefined classes unknown <- !nzchar(pkgs) for(i in seq_along(sigClasses)[unknown]) { cli <- getClassDef(sigClasses[[i]], where) if(!is.null(cli)) { pkgs[[i]] <- cli@package unknown[[i]] <- FALSE } } if(any(unknown)) { unknown <- unique(sigClasses[unknown]) ## coerce(), i.e., setAs() may use *one* unknown class MSG <- if(identical(as.vector(coerce@generic), "coerce") && length(unknown) == 1) message else function(...) warning(..., call. = FALSE) MSG(.renderSignature(fun@generic, signature), sprintf(ngettext(length(unknown), "no definition for class %s", "no definition for classes %s"), paste(dQuote(unknown), collapse = ", ")), domain = NA) } } signature <- as.list(signature) if(length(sigClasses) != length(signature)) stop(gettextf("object to use as a method signature for function %s does not look like a legitimate signature (a vector of single class names): there were %d class names, but %d elements in the signature object", sQuote(fun@generic), length(sigClasses), length(signature)), domain = NA) if(is.null(names(signature))) { which <- seq_along(signature) if(length(which) > length(anames)) stop(gettextf("more elements in the method signature (%d) than in the generic signature (%d) for function %s", length(which), length(anames), sQuote(fun@generic)), domain = NA) } else { ## construct a function call with the same naming pattern & ## values as signature sigList <- signature for(i in seq_along(sigList)) sigList[[i]] <- c(sigClasses[[i]], pkgs[[i]]) fcall <- do.call("call", c("fun", sigList)) ## match the call to the formal signature (usually the formal args) if(identical(anames, formalArgs(fun))) smatch <- match.call(fun, fcall) else { fmatch <- fun ff <- as.list(anames); names(ff) <- anames formals(fmatch, envir = environment(fun)) <- ff smatch <- match.call(fmatch, fcall) } snames <- names(smatch)[-1L] which <- match(snames, anames) ## Assertion: match.call has permuted the args into the order of formal args, ## and carried along the values. Get the supplied classes in that ## order, from the matched args in the call object. if(anyNA(which)) stop(sprintf(ngettext(sum(is.na(which)), "in the method signature for function %s invalid argument name in the signature: %s", "in the method signature for function %s invalid argument names in the signature: %s"), sQuote(fun@generic), paste(snames[is.na(which)], collapse = ", ")), domain = NA) smatch <- smatch[-1] for(i in seq_along(smatch)) { eli <- smatch[[i]] sigClasses[[i]] <- eli[[1]] pkgs[[i]] <- eli[[2]] } } n <- length(anames) value <- rep("ANY", n) valueP <- rep("methods", n) names(value) <- anames value[which] <- sigClasses valueP[which] <- pkgs unspec <- value == "ANY" ## remove the trailing unspecified classes while(n > 1 && unspec[[n]]) n <- n-1 length(value) <- length(valueP) <- n attr(value, "package") <- valueP ## <FIXME> Is there a reason (bootstrapping?) why this ## is not an actual object from class "signature"? ## See .MakeSignature() </FIXME> value } showMlist <- ## Prints the contents of the MethodsList. If `includeDefs' the signatures and the ## corresponding definitions will be printed; otherwise, only the signatures. ## ## If `includeDefs' is `TRUE', the currently known inherited methods are included; ## otherwise, only the directly defined methods. function(mlist, includeDefs = TRUE, inherited = TRUE, classes = NULL, useArgNames = TRUE, printTo = stdout()) { .MlistDeprecated("showMlist()") if(identical(printTo, FALSE)) { tmp <- tempfile() con <- file(tmp, "w") } else con <- printTo object <- linearizeMlist(mlist, inherited) methods <- object@methods signatures <- object@classes args <- object@arguments if(!is.null(classes) && length(signatures)>0) { keep <- !vapply(signatures, function(x, y) all(is.na(match(x, y))), NA, classes) methods <- methods[keep] signatures <- signatures[keep] args <- args[keep] } if(length(methods) == 0) cat(file=con, "<Empty Methods List>\n") else { n <- length(methods) labels <- character(n) if(useArgNames) { for(i in 1L:n) { sigi <- signatures[[i]] labels[[i]] <- paste(args[[i]], " = \"", sigi, "\"", sep = "", collapse = ", ") } } else { for(i in 1L:n) labels[[i]] <- paste(signatures[[i]], collapse = ", ") } for(i in seq_along(methods)) { cat(file=con, (if(includeDefs) "## Signature:" else ""), labels[[i]]) method <- methods[[i]] if(includeDefs) { cat(file=con, ":\n") if(is(method, "MethodDefinition")) ## really an assertion cat(file=con, deparse(method@.Data), sep="\n") else cat(file=con, deparse(method), sep="\n") } if(is(method, "MethodDefinition") && !identical(method@target, method@defined)) { defFrom <- method@defined cat(file = con, if(includeDefs) "##:" else "\n", " (inherited from ", paste(names(defFrom), " = \"", as.character(defFrom), "\"", sep = "", collapse = ", "), ")", if(includeDefs) "\n", sep="") } cat(file=con, "\n") } } if(identical(printTo, FALSE)) { close(con) value <- readLines(tmp) unlink(tmp) value } } promptMethods <- function(f, filename = NULL, methods) { ## Generate information in the style of 'prompt' for the methods of ## the generic named 'f'. ## ## 'filename' can be a logical or NA or the name of a file to print ## to. If it 'FALSE', the methods skeleton is returned, to be ## included in other printing (typically, the output from 'prompt'). escape <- function(txt) gsub("%", "\\\\%", txt) packageString <- "" fdef <- getGeneric(f) if(!isGeneric(f, fdef=fdef)) stop(gettextf("no generic function found corresponding to %s", sQuote(f)), domain = NA) if(missing(methods)) { methods <- findMethods(fdef) ## try making packageString where <- .genEnv(fdef, topenv(parent.frame())) if(!identical(where, .GlobalEnv)) packageString <- sprintf("in Package \\pkg{%s}", getPackageName(where)) } fullName <- utils:::topicName("methods", f) n <- length(methods) labels <- character(n) aliases <- character(n) signatures <- findMethodSignatures(methods = methods, target=TRUE) args <- colnames(signatures) # the *same* for all for(i in seq_len(n)) { sigi <- signatures[i, ] labels[[i]] <- sprintf("\\code{signature(%s)}", paste(sprintf("%s = \"%s\"", args, escape(sigi)), collapse = ", ")) aliases[[i]] <- paste0("\\alias{", utils:::topicName("method", c(f, signatures[i,])), "}") } text <- paste0("\n\\item{", labels, "}{\n%% ~~describe this method here~~\n}") text <- c("\\section{Methods}{\n\\describe{", text, "}}") aliasText <- c(paste0("\\alias{", escape(fullName), "}"), escape(aliases)) if(identical(filename, FALSE)) return(c(aliasText, text)) if(is.null(filename) || identical(filename, TRUE)) filename <- paste0(fullName, ".Rd") Rdtxt <- list(name = paste0("\\name{", fullName, "}"), type = "\\docType{methods}", aliases = aliasText, ## <FIXME> ## Title and description are ok as auto-generated: should ## they be flagged as such (via '~~' which are quite often ## left in by authors)? title = sprintf("\\title{ ~~ Methods for Function \\code{%s} %s ~~}", f, packageString), description = paste0("\\description{\n ~~ Methods for function", " \\code{", f, "} ", sub("^in Package", "in package", packageString), " ~~\n}"), ## </FIXME> "section{Methods}" = text, keywords = c("\\keyword{methods}", "\\keyword{ ~~ other possible keyword(s) ~~ }")) if(is.na(filename)) return(Rdtxt) cat(unlist(Rdtxt), file = filename, sep = "\n") .message("A shell of methods documentation has been written", .fileDesc(filename), ".\n") invisible(filename) } ##' only called from showMlist() above, which has been deprecated in R 3.2.0 (Apr.2015): linearizeMlist <- ## Undo the recursive nature of the methods list, making a list of ## function definitions, with the names of the list being the ## corresponding signatures (designed for printing; for looping over ## the methods, use `listFromMlist' instead). ## ## The function calls itself recursively. `prev' is the previously ## selected class names. ## ## If argument `classes' is provided, only signatures containing one ## of these classes will be included. function(mlist, inherited = TRUE) { methods <- mlist@methods allMethods <- mlist@allMethods if(inherited && length(allMethods) >= length(methods)) { ## anames <- names(allMethods) ## inh <- is.na(match(anames, names(methods))) methods <- allMethods } preC <- function(y, x)c(x,y) # used with lapply below cnames <- names(methods) value <- list() classes <- list() arguments <- list() argname <- as.character(mlist@argument) for(i in seq_along(cnames)) { mi <- methods[[i]] if(is.function(mi)) { value <- c(value, list(mi)) classes <- c(classes, list(cnames[[i]])) arguments <- c(arguments, list(argname)) } else if(is(mi, "MethodsList")) { .MlistDeprecated() mi <- Recall(mi, inherited) value <- c(value, mi@methods) classes <- c(classes, lapply(mi@classes, preC, cnames[[i]])) arguments <- c(arguments, lapply(mi@arguments, preC, argname)) } else warning(gettextf("skipping methods list element %s of unexpected class %s\n\n", paste(cnames[i], collapse = ", "), dQuote(.class1(mi))), domain = NA) } new("LinearMethodsList", methods = value, classes = classes, arguments = arguments) } print.MethodsList <- function(x, ...) showMlist(x) ## In R's own code, this is *only* used in mergeMethods(), deprecated in R 3.2.0 (Apr.2015) listFromMlist <- ## linearizes the MethodsList object into list(sigs, methods); `prefix' is the partial ## signature (a named list of classes) to be prepended to the signatures in this object. ## ## A utility function used to iterate over all the individual methods in the object. function(mlist, prefix = list(), sigs. = TRUE, methods. = TRUE) { methodSlot <- slot(mlist, "methods") mnames <- names(methodSlot) argName <- as.character(slot(mlist, "argument")) sigs <- list() methods <- list() for(i in seq_along(methodSlot)) { thisMethod <- methodSlot[i] thisClass <- mnames[[i]] prefix[[argName]] <- thisClass if(is.function(thisMethod)) { if(sigs.) sigs <- c(sigs, list(prefix)) if(methods.) methods <- c(methods, list(thisMethod)) } else { more <- Recall(thisMethod, prefix) if(sigs.) sigs <- c(sigs, more[[1]]) if(methods.) methods <- c(methods, more[[2]]) } } list(sigs, methods) } .insertCachedMethods <- function(mlist, argName, Class, fromClass, def) { if(is(def, "MethodsList")) { .MlistDeprecated() ## insert all the cached methods in def newArg <- c(argName, as.character(def@argument)) newDefs <- def@allMethods newSigs <- as.list(names(newDefs)) for(j in seq_along(newDefs)) mlist <- Recall(mlist, newArg, c(Class, newSigs[[j]]), fromClass, newDefs[[j]]) } else { def <- .addMethodFrom(def, argName[1L], Class[1L], fromClass) mlist <- insertMethod(mlist, Class, argName, def, TRUE) } mlist } .addMethodFrom <- function(def, arg, Class, fromClass) { if(is(def, "MethodDefinition")) { ## eventually, we may enforce method definition objects ## If not, just leave raw functions alone (NextMethod won't work) def@target[[arg]] <- Class def@defined[[arg]] <- fromClass } def } ## Define a trivial version of asMethodDefinition for bootstrapping. ## The real version requires several class definitions as well as ## methods for as<- asMethodDefinition <- function(def, signature = list(.anyClassName), sealed = FALSE, fdef = def) { if(is.primitive(def) || is(def, "MethodDefinition")) def else { value = new("MethodDefinition") value@.Data <- def classes <- .MakeSignature(new("signature"), def, signature, fdef) value@target <- classes value@defined <- classes value } } .trimMlist <- function(mlist, fromClass) { mlist@methods <- mlist@methods[fromClass] mlist@allMethods <- mlist@allMethods[fromClass] mlist } .noMlistsFlag <- TRUE .noMlists <- function() { ## if this were to be dynamically variable, but ## it can't, IMO ## identical(getOption("noMlists"), TRUE) ## so instead .noMlistsFlag } .MlistDepTable <- new.env() .MlistDeprecated <- function(this = "<default>", instead) { if(is.character(this)) { if(exists(this, envir = .MlistDepTable, inherits = FALSE)) return() else assign(this, TRUE, envir = .MlistDepTable) } msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is deprecated." else if(is.character(this)) gettextf( "%s, along with other use of the \"MethodsList\" metadata objects, is deprecated.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is deprecated.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList. (This warning is shown once per session.)") base::.Deprecated(msg = msg) } .MlistDefunct <- function(this = "<default>", instead) { msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is defunct." else if(is.character(this)) gettextf("%s, along with other use of the \"MethodsList\" metadata objects, is defunct.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is defunct.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList.") base::.Defunct(msg = msg) }
36,574
gpl-2.0
787cb690ce0b0ecd96ae8bf6d4f0605b806116fb
jukiewiczm/renjin
test-packages/dataTest/R/generateData.R
generateData <- function() { (1:8)^2 }
40
gpl-3.0
71c4978aaa94135074227729a1d4da375593bdd9
MouseGenomics/R
src/library/methods/R/MethodsList.R
# File src/library/methods/R/MethodsList.R # Part of the R package, https://www.R-project.org # # Copyright (C) 1995-2016 The R Core Team # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # A copy of the GNU General Public License is available at # https://www.R-project.org/Licenses/ MethodsList <- ## Create a MethodsList object out of the arguments. ## ## Conceptually, this object is a named collection of methods to be ## dispatched when the (first) argument in a function call matches the ## class corresponding to one of the names. A final, unnamed element ## (i.e., with name `""') corresponds to the default method. ## ## The elements can be either a function, or another MethodsList. In ## the second case, this list implies dispatching on the second ## argument to the function using that list, given a selection of this ## element on the first argument. Thus, method dispatching on an ## arbitrary number of arguments is defined. ## ## MethodsList objects are used primarily to dispatch OOP-style ## methods and, in R, to emulate S4-style methods. function(.ArgName, ...) { .MlistDeprecated("MethodsList()") value <- makeMethodsList(list(...)) if(is.name(.ArgName)){} else if(is.character(.ArgName) && length(.ArgName) == 1) .ArgName <- as.name(.ArgName) else stop("invalid first argument: should be the name of the first argument in the dispatch") slot(value, "argument") <- .ArgName value } makeMethodsList <- function(object, level=1) { .MlistDeprecated("makeMethodsList()") mnames <- allNames(object) if(.noMlists()) { keep <- mnames %in% c("", "ANY") mnames <- mnames[keep] object <- object[keep] } value <- new("MethodsList") i <- match("", mnames) if(!is.na(i)) { ## convert to ANY mnames[[i]] <- "ANY" names(object) <- mnames } if(anyDuplicated(mnames)) stop(gettextf("duplicate element names in 'MethodsList' at level %d: %s", level, paste("\"", unique(mnames[duplicated(mnames)]), "\"", collapse=", ")), domain = NA) for(i in seq_along(object)) { eli <- object[[i]] if(is(eli, "function") || is(eli, "MethodsList")) {} else if(is(eli, "list") || is(eli, "named")) object[[i]] <- Recall(eli, NULL, level+1) else stop(gettextf("element %d at level %d (class %s) cannot be interpreted as a function or named list", i, level, dQuote(class(eli))), domain = NA) } slot(value, "methods") <- object value } SignatureMethod <- ## construct a MethodsList object containing (only) this method, corresponding ## to the signature; i.e., such that signature[[1L]] is the match for the first ## argument, signature[[2L]] for the second argument, and so on. The string ## "missing" means a match for a missing argument, and "ANY" means use this as the ## default setting at this level. ## ## The first argument is the argument names to be used for dispatch corresponding to ## the signatures. function(names, signature, definition) { .MlistDeprecated("SignatureMethod()") n <- length(signature) if(n > length(names)) stop("arguments 'names' and 'signature' must have the same length") if(n == 0) return(definition) Class <- signature[[n]] name <- names[[n]] m <- MethodsList(name) slot(m, "methods")[[Class]] <- definition slot(m, "argument") <- as.name(name) SignatureMethod(names[-n], signature[-n], m) } insertMethod <- ## insert the definition `def' into the MethodsList object, `mlist', corresponding to ## the signature, and return the modified MethodsList. function(mlist, signature, args, def, cacheOnly = FALSE) { .MlistDeprecated("insertMethod()") if(.noMlists() && !identical(unique(signature), "ANY")) return(mlist) ## Checks for assertions about valid calls. ## See rev. 1.17 for the code before the assertions added. if(identical(args[1L], "...") && !identical(names(signature), "...")) { if(identical(signature[[1L]], "ANY")) stop(gettextf("inserting method with invalid signature matching argument '...' to class %s", dQuote(signature[[1L]])), domain = NA) args <- args[-1L] signature <- signature[-1L] if(length(signature) == 0L) return(mlist) } if(length(signature) == 0L) stop("inserting method corresponding to empty signature") if(!is(mlist, "MethodsList")) stop(gettextf("inserting method into non-methods-list object (class %s)", dQuote(.class1(mlist))), domain = NA) if(length(args) > 1 && !cacheOnly) mlist <- balanceMethodsList(mlist, args) Class <- signature[[1]] methods <- if(cacheOnly) mlist@allMethods else mlist@methods current <- methods[[Class]] if(is(current, "MethodsList")) { nextArg <- as.character(current@argument) sigArgs <- args n <- length(signature) length(sigArgs) <- n if(is.na(match(nextArg, sigArgs))) { n <- match(nextArg, args) - n if(is.na(n)) { ## not in args eitiher n <- 1 args <- c(args, nextArg) } ## make explicit the trailing ANY's needed signature <- c(signature, rep("ANY", n)) } } if(length(signature) == 1) { if(is.null(current)) { if(!is.null(def)) methods[[Class]] <- def ## else, no change } else { which <- match(Class, names(methods)) if(is.null(def)) ## delete the method methods <- methods[-which] else methods[[which]] <- def } } else { ## recursively merge, initializing current if necessary if(is.null(current)) current <- new("MethodsList", argument = as.name(args[2L])) else if(is.function(current)) current <- new("MethodsList", argument = as.name(args[2L]), methods = list(ANY = current)) methods[[Class]] <- Recall(current, signature[-1L], args[-1L], def, cacheOnly) } mlist@allMethods <- methods if(!cacheOnly) mlist@methods <- methods mlist } MethodsListSelect <- ## select the element of a MethodsList object corresponding to the ## actual arguments (as defined in the suppled environment), ## and return the object, extended to include that method if necessary. ## ## Works recursively. At each level finds an argument name from the current `mlist' ## object, and evaluates this argument (if it is not missing), then uses the ## class of the result to select an element of `mlist'. If such an element ## exists and is another `MethodsList' object, `MethodsListSelect' calls itself recursively ## to resolve using further arguments. Matching includes using a default selection or ## a method specifically linked to class `"missing"'. Once a function is found, it ## is returned as the value. If matching fails, NULL is returned. function(f, env, mlist = NULL, fEnv = if(is(fdef, "genericFunction")) environment(fdef) else baseenv(), finalDefault = finalDefaultMethod(mlist), evalArgs = TRUE, useInherited = TRUE, ## supplied when evalArgs is FALSE fdef = getGeneric(f, where = env), # MUST BE SAFE FROM RECUSIVE METHOD SELECTION resetAllowed = TRUE # FALSE when called from selectMethod, .findNextMethod ) { .MlistDeprecated("MethodsListSelect()") if(!resetAllowed) # ensure we restore the real methods for this function resetMlist <- .getMethodsForDispatch(fdef) ## look for call from C dispatch code during another call to MethodsListSelect if(is.null(f)) {} # Recall, not from C else { fMethods <- .getMethodsForDispatch(fdef) if(is.null(mlist) || (evalArgs && is.function(fMethods))) mlist <- fMethods } resetNeeded <- .setIfBase(f, fdef, mlist) # quickly protect against recursion -- see Methods.R if(resetNeeded) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } if(!is(mlist, "MethodsList")) { if(is.function(mlist)) # call to f, inside MethodsListSelect {on.exit(); return(mlist)} if(is.null(f)) # recursive recall of MethodsListSelect stop("invalid method sublist") else if(!is.null(mlist)) # NULL => 1st call to genericFunction stop(gettextf("%f is not a valid generic function: methods list was an object of class %s", sQuote(f), dQuote(class(mlist))), domain = NA) } if(!is.logical(useInherited)) stop(gettextf("%s must be TRUE, FALSE, or a named logical vector of those values; got an object of class %s", sQuote("useInherited"), dQuote(class(useInherited))), domain = NA) if(identical(mlist, .getMethodsForDispatch(fdef))) { resetNeeded <- TRUE ## On the initial call: ## turn off any further method dispatch on this function, to avoid recursive ## loops if f is a function used in MethodsListSelect. ## TODO: Using namespaces in the methods package would eliminate the need for this .setMethodsForDispatch(f, fdef, finalDefault) if(is(mlist, "MethodsList")) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } } argName <- slot(mlist, "argument") arg <- NULL ## => don't use instance-specific inheritance if(evalArgs) { ## check for missing argument. NB: S sense, not that of R base missing() if(missingArg(argName, env, TRUE)) thisClass <- "missing" else { arg <- eval(as.name(argName), env) ## DO use instance-specific inheritance if(missing(arg)) ## S3 weird R code? Bail out! return(finalDefault) thisClass <- .class1(arg) } } else thisClass <- get(as.character(argName), envir = env, inherits = FALSE) if(identical(useInherited, TRUE) || identical(useInherited, FALSE)) thisInherit <- nextUseInherited <- useInherited else { which <- match(as.character(argName), names(useInherited)) if(is.na(which)) { nextUseInherited <- useInherited thisInherit <- TRUE } else { thisInherit <- useInherited[[which]] nextUseInherited <- useInherited[-which] } } fromClass <- thisClass ## will mark the class actually providing the method allMethods <- mlist@allMethods which <- match(thisClass, names(allMethods)) inherited <- is.na(which) selection <- if(inherited) NULL else allMethods[[which]] if(!inherited) { if(is(selection, "function")) { if(is.null(f)) { ## An inherited method at the next level up. ## only the inherited method should be added mlist <- .trimMlist(mlist, fromClass) } value <- mlist ## no change } else { ## recursive call with NULL function name, to allow search to fail & ## to suppress any reset actions. method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef, ) if(is(method, "EmptyMethodsList")) value <- method else { mlist@allMethods[[which]] <- method value <- mlist } } } if(inherited || is(value, "EmptyMethodsList")) { ## direct selection failed at this level or below method <- NULL if(thisInherit) { allSelections <- inheritedSubMethodLists(arg, fromClass, mlist, env) allClasses <- names(allSelections) for(i in seq_along(allSelections)) { selection <- allSelections[[i]] fromClass <- allClasses[[i]] if(is(selection, "function")) method <- selection else if(is(selection, "MethodsList")) { ## go on to try matching further arguments method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef) if(is(method, "EmptyMethodsList")) selection <- method ## recursive selection failed } if(!is(selection, "EmptyMethodsList")) break } } if((is.null(selection) || is(selection, "EmptyMethodsList")) && !is.null(f) && !is.null(finalDefault)) { ## only use the final default method after exhausting all ## other possibilities, at all levels. method <- finalDefault fromClass <- "ANY" } if(is.null(method) || is(method, "EmptyMethodsList")) value <- emptyMethodsList(mlist, thisClass) ## nothing found else { method <- MethodAddCoerce(method, argName, thisClass, fromClass) value <- .insertCachedMethods(mlist, as.character(argName), thisClass, fromClass, method) } } if(!is.null(f)) { ## top level if(is(value, "EmptyMethodsList")) ## selection failed value <- NULL if(resetNeeded) { on.exit() # cancel the restore of the original mlist if(resetAllowed) { if(is.null(value)) resetMlist <- mlist else resetMlist <- value } .setMethodsForDispatch(f, fdef, resetMlist) if(dispatchIsInternal(fdef)) setPrimitiveMethods(f, finalDefault, "set", fdef, resetMlist) } } value } emptyMethodsList <- function(mlist, thisClass = "ANY", sublist = list()) { .MlistDeprecated("emptyMethodsList()") sublist[thisClass] <- list(NULL) new("EmptyMethodsList", argument = mlist@argument, sublist = sublist) } insertMethodInEmptyList <- function(mlist, def) { .MlistDeprecated("insertMethodInEmptyList()") value <- new("MethodsList", argument = mlist@argument) sublist <- mlist@sublist submethods <- sublist[[1L]] if(is.null(submethods)) sublist[[1L]] <- def else sublist[[1L]] <- Recall(submethods, def) value@allMethods <- sublist value } finalDefaultMethod <- ## Return the default method from the generic (it may be NULL, a method object or a primitive. ## this previously searched in a MethodsList object. Once those are gone, the loop should ## be irrelevant except as an error check. function(method) { repeat { if(is.function(method) # <- somewhat liberal, but catches both methods and primitives || is.null(method)) break if(is(method, "MethodsList")) { .MlistDeprecated() method <- slot(method, "methods")[["ANY"]] } else stop(gettextf( "default method must be a method definition, a primitive or NULL: got an object of class %s", dQuote(class(method))), domain = NA) } method } inheritedSubMethodLists <- ## Utility function to match the object to the elements of a methods list. ## ## The function looks only for an inherited match, and only among ## the methods that are not themselves inherited. (Inherited methods when found are ## stored in the session copy of the methods list, but they themselves should not be ## used for finding inherited matches, because an erroneous match could be found depending ## on which methods were previously used. See the detailed discussion of methods.) function(object, thisClass, mlist, ev) { .MlistDeprecated("inheritedSubMethodLists()") methods <- slot(mlist, "methods")## only direct methods defaultMethod <- methods[["ANY"]]## maybe NULL classes <- names(methods) value <- list() if(.identC(thisClass, "missing")) { ## no superclasses for "missing" } else { ## search in the superclasses, but don't use inherited methods ## There are two cases: if thisClass is formally defined & unsealed, use its ## superclasses. Otherwise, look in the subclasses of those classes for ## which methods exist. classDef <- getClassDef(thisClass, ev) useSuperClasses <- !is.null(classDef) && !classDef@sealed if(useSuperClasses) { ## for consistency, order the available methods by ## the ordering of the superclasses of thisClass superClasses <- names(classDef@contains) classes <- superClasses[!is.na(match(superClasses, classes))] for(which in seq_along(classes)) { tryClass <- classes[[which]] ## TODO: There is potential bug here: If the is relation is conditional, ## we should not cache this selection. Needs another trick in the environment ## to FORCE no caching regardless of what happens elsewhere; e.g., storing a ## special object in .Class if(is.null(object) || is(object, tryClass)) { value[[tryClass]] <- methods[[tryClass]] } } } else { for(which in seq_along(classes)) { tryClass <- classes[[which]] tryClassDef <- getClassDef(tryClass, ev) if(!is.null(tryClassDef) && !is.na(match(thisClass, names(tryClassDef@subclasses)))) value[[tryClass]] <- methods[[which]] } } } if(!is.null(defaultMethod)) value[["ANY"]] <- defaultMethod value } matchSignature <- ## Match the signature object (a partially or completely named subset of the ## arguments of `fun', and return a vector of all the classes in the order specified ## by the signature slot of the generic. The classes not specified by `signature ##' will be `"ANY"' in the value. function(signature, fun, where = baseenv()) { if(!is(fun, "genericFunction")) stop(gettextf("trying to match a method signature to an object (of class %s) that is not a generic function", dQuote(class(fun))), domain = NA) anames <- fun@signature if(length(signature) == 0L) return(character()) if(is(signature,"character")) { pkgs <- packageSlot(signature) # includes case of "ObjectsWithPackage" if(is.null(pkgs)) pkgs <- character(length(signature)) else if(length(pkgs) != length(signature)) stop("invalid 'package' slot or attribute, wrong length") sigClasses <- as.character(signature) } else if(is(signature, "list")) { sigClasses <- pkgs <- character(length(signature)) for(i in seq_along(signature)) { cli <- signature[[i]] if(is(cli, "classRepresentation")) { sigClasses[[i]] <- cli@className pkgs[[i]] <- cli@package } else if(is(cli, "character") && length(cli) == 1) { sigClasses[[i]] <- cli pkgi <- packageSlot(cli) if(is.character(pkgi)) pkgs[[i]] <- pkgi } else stop(gettextf("invalid element in a list for \"signature\" argument; element %d is neither a class definition nor a class name", i), domain = NA) } } else stop(gettextf("trying to match a method signature of class %s; expects a list or a character vector", dQuote(class(signature))), domain = NA) if(!identical(where, baseenv())) { ## fill in package information, warn about undefined classes unknown <- !nzchar(pkgs) for(i in seq_along(sigClasses)[unknown]) { cli <- getClassDef(sigClasses[[i]], where) if(!is.null(cli)) { pkgs[[i]] <- cli@package unknown[[i]] <- FALSE } } if(any(unknown)) { unknown <- unique(sigClasses[unknown]) ## coerce(), i.e., setAs() may use *one* unknown class MSG <- if(identical(as.vector(coerce@generic), "coerce") && length(unknown) == 1) message else function(...) warning(..., call. = FALSE) MSG(.renderSignature(fun@generic, signature), sprintf(ngettext(length(unknown), "no definition for class %s", "no definition for classes %s"), paste(dQuote(unknown), collapse = ", ")), domain = NA) } } signature <- as.list(signature) if(length(sigClasses) != length(signature)) stop(gettextf("object to use as a method signature for function %s does not look like a legitimate signature (a vector of single class names): there were %d class names, but %d elements in the signature object", sQuote(fun@generic), length(sigClasses), length(signature)), domain = NA) if(is.null(names(signature))) { which <- seq_along(signature) if(length(which) > length(anames)) stop(gettextf("more elements in the method signature (%d) than in the generic signature (%d) for function %s", length(which), length(anames), sQuote(fun@generic)), domain = NA) } else { ## construct a function call with the same naming pattern & ## values as signature sigList <- signature for(i in seq_along(sigList)) sigList[[i]] <- c(sigClasses[[i]], pkgs[[i]]) fcall <- do.call("call", c("fun", sigList)) ## match the call to the formal signature (usually the formal args) if(identical(anames, formalArgs(fun))) smatch <- match.call(fun, fcall) else { fmatch <- fun ff <- as.list(anames); names(ff) <- anames formals(fmatch, envir = environment(fun)) <- ff smatch <- match.call(fmatch, fcall) } snames <- names(smatch)[-1L] which <- match(snames, anames) ## Assertion: match.call has permuted the args into the order of formal args, ## and carried along the values. Get the supplied classes in that ## order, from the matched args in the call object. if(anyNA(which)) stop(sprintf(ngettext(sum(is.na(which)), "in the method signature for function %s invalid argument name in the signature: %s", "in the method signature for function %s invalid argument names in the signature: %s"), sQuote(fun@generic), paste(snames[is.na(which)], collapse = ", ")), domain = NA) smatch <- smatch[-1] for(i in seq_along(smatch)) { eli <- smatch[[i]] sigClasses[[i]] <- eli[[1]] pkgs[[i]] <- eli[[2]] } } n <- length(anames) value <- rep("ANY", n) valueP <- rep("methods", n) names(value) <- anames value[which] <- sigClasses valueP[which] <- pkgs unspec <- value == "ANY" ## remove the trailing unspecified classes while(n > 1 && unspec[[n]]) n <- n-1 length(value) <- length(valueP) <- n attr(value, "package") <- valueP ## <FIXME> Is there a reason (bootstrapping?) why this ## is not an actual object from class "signature"? ## See .MakeSignature() </FIXME> value } showMlist <- ## Prints the contents of the MethodsList. If `includeDefs' the signatures and the ## corresponding definitions will be printed; otherwise, only the signatures. ## ## If `includeDefs' is `TRUE', the currently known inherited methods are included; ## otherwise, only the directly defined methods. function(mlist, includeDefs = TRUE, inherited = TRUE, classes = NULL, useArgNames = TRUE, printTo = stdout()) { .MlistDeprecated("showMlist()") if(identical(printTo, FALSE)) { tmp <- tempfile() con <- file(tmp, "w") } else con <- printTo object <- linearizeMlist(mlist, inherited) methods <- object@methods signatures <- object@classes args <- object@arguments if(!is.null(classes) && length(signatures)>0) { keep <- !vapply(signatures, function(x, y) all(is.na(match(x, y))), NA, classes) methods <- methods[keep] signatures <- signatures[keep] args <- args[keep] } if(length(methods) == 0) cat(file=con, "<Empty Methods List>\n") else { n <- length(methods) labels <- character(n) if(useArgNames) { for(i in 1L:n) { sigi <- signatures[[i]] labels[[i]] <- paste(args[[i]], " = \"", sigi, "\"", sep = "", collapse = ", ") } } else { for(i in 1L:n) labels[[i]] <- paste(signatures[[i]], collapse = ", ") } for(i in seq_along(methods)) { cat(file=con, (if(includeDefs) "## Signature:" else ""), labels[[i]]) method <- methods[[i]] if(includeDefs) { cat(file=con, ":\n") if(is(method, "MethodDefinition")) ## really an assertion cat(file=con, deparse(method@.Data), sep="\n") else cat(file=con, deparse(method), sep="\n") } if(is(method, "MethodDefinition") && !identical(method@target, method@defined)) { defFrom <- method@defined cat(file = con, if(includeDefs) "##:" else "\n", " (inherited from ", paste(names(defFrom), " = \"", as.character(defFrom), "\"", sep = "", collapse = ", "), ")", if(includeDefs) "\n", sep="") } cat(file=con, "\n") } } if(identical(printTo, FALSE)) { close(con) value <- readLines(tmp) unlink(tmp) value } } promptMethods <- function(f, filename = NULL, methods) { ## Generate information in the style of 'prompt' for the methods of ## the generic named 'f'. ## ## 'filename' can be a logical or NA or the name of a file to print ## to. If it 'FALSE', the methods skeleton is returned, to be ## included in other printing (typically, the output from 'prompt'). escape <- function(txt) gsub("%", "\\\\%", txt) packageString <- "" fdef <- getGeneric(f) if(!isGeneric(f, fdef=fdef)) stop(gettextf("no generic function found corresponding to %s", sQuote(f)), domain = NA) if(missing(methods)) { methods <- findMethods(fdef) ## try making packageString where <- .genEnv(fdef, topenv(parent.frame())) if(!identical(where, .GlobalEnv)) packageString <- sprintf("in Package \\pkg{%s}", getPackageName(where)) } fullName <- utils:::topicName("methods", f) n <- length(methods) labels <- character(n) aliases <- character(n) signatures <- findMethodSignatures(methods = methods, target=TRUE) args <- colnames(signatures) # the *same* for all for(i in seq_len(n)) { sigi <- signatures[i, ] labels[[i]] <- sprintf("\\code{signature(%s)}", paste(sprintf("%s = \"%s\"", args, escape(sigi)), collapse = ", ")) aliases[[i]] <- paste0("\\alias{", utils:::topicName("method", c(f, signatures[i,])), "}") } text <- paste0("\n\\item{", labels, "}{\n%% ~~describe this method here~~\n}") text <- c("\\section{Methods}{\n\\describe{", text, "}}") aliasText <- c(paste0("\\alias{", escape(fullName), "}"), escape(aliases)) if(identical(filename, FALSE)) return(c(aliasText, text)) if(is.null(filename) || identical(filename, TRUE)) filename <- paste0(fullName, ".Rd") Rdtxt <- list(name = paste0("\\name{", fullName, "}"), type = "\\docType{methods}", aliases = aliasText, ## <FIXME> ## Title and description are ok as auto-generated: should ## they be flagged as such (via '~~' which are quite often ## left in by authors)? title = sprintf("\\title{ ~~ Methods for Function \\code{%s} %s ~~}", f, packageString), description = paste0("\\description{\n ~~ Methods for function", " \\code{", f, "} ", sub("^in Package", "in package", packageString), " ~~\n}"), ## </FIXME> "section{Methods}" = text, keywords = c("\\keyword{methods}", "\\keyword{ ~~ other possible keyword(s) ~~ }")) if(is.na(filename)) return(Rdtxt) cat(unlist(Rdtxt), file = filename, sep = "\n") .message("A shell of methods documentation has been written", .fileDesc(filename), ".\n") invisible(filename) } ##' only called from showMlist() above, which has been deprecated in R 3.2.0 (Apr.2015): linearizeMlist <- ## Undo the recursive nature of the methods list, making a list of ## function definitions, with the names of the list being the ## corresponding signatures (designed for printing; for looping over ## the methods, use `listFromMlist' instead). ## ## The function calls itself recursively. `prev' is the previously ## selected class names. ## ## If argument `classes' is provided, only signatures containing one ## of these classes will be included. function(mlist, inherited = TRUE) { methods <- mlist@methods allMethods <- mlist@allMethods if(inherited && length(allMethods) >= length(methods)) { ## anames <- names(allMethods) ## inh <- is.na(match(anames, names(methods))) methods <- allMethods } preC <- function(y, x)c(x,y) # used with lapply below cnames <- names(methods) value <- list() classes <- list() arguments <- list() argname <- as.character(mlist@argument) for(i in seq_along(cnames)) { mi <- methods[[i]] if(is.function(mi)) { value <- c(value, list(mi)) classes <- c(classes, list(cnames[[i]])) arguments <- c(arguments, list(argname)) } else if(is(mi, "MethodsList")) { .MlistDeprecated() mi <- Recall(mi, inherited) value <- c(value, mi@methods) classes <- c(classes, lapply(mi@classes, preC, cnames[[i]])) arguments <- c(arguments, lapply(mi@arguments, preC, argname)) } else warning(gettextf("skipping methods list element %s of unexpected class %s\n\n", paste(cnames[i], collapse = ", "), dQuote(.class1(mi))), domain = NA) } new("LinearMethodsList", methods = value, classes = classes, arguments = arguments) } print.MethodsList <- function(x, ...) showMlist(x) ## In R's own code, this is *only* used in mergeMethods(), deprecated in R 3.2.0 (Apr.2015) listFromMlist <- ## linearizes the MethodsList object into list(sigs, methods); `prefix' is the partial ## signature (a named list of classes) to be prepended to the signatures in this object. ## ## A utility function used to iterate over all the individual methods in the object. function(mlist, prefix = list(), sigs. = TRUE, methods. = TRUE) { methodSlot <- slot(mlist, "methods") mnames <- names(methodSlot) argName <- as.character(slot(mlist, "argument")) sigs <- list() methods <- list() for(i in seq_along(methodSlot)) { thisMethod <- methodSlot[i] thisClass <- mnames[[i]] prefix[[argName]] <- thisClass if(is.function(thisMethod)) { if(sigs.) sigs <- c(sigs, list(prefix)) if(methods.) methods <- c(methods, list(thisMethod)) } else { more <- Recall(thisMethod, prefix) if(sigs.) sigs <- c(sigs, more[[1]]) if(methods.) methods <- c(methods, more[[2]]) } } list(sigs, methods) } .insertCachedMethods <- function(mlist, argName, Class, fromClass, def) { if(is(def, "MethodsList")) { .MlistDeprecated() ## insert all the cached methods in def newArg <- c(argName, as.character(def@argument)) newDefs <- def@allMethods newSigs <- as.list(names(newDefs)) for(j in seq_along(newDefs)) mlist <- Recall(mlist, newArg, c(Class, newSigs[[j]]), fromClass, newDefs[[j]]) } else { def <- .addMethodFrom(def, argName[1L], Class[1L], fromClass) mlist <- insertMethod(mlist, Class, argName, def, TRUE) } mlist } .addMethodFrom <- function(def, arg, Class, fromClass) { if(is(def, "MethodDefinition")) { ## eventually, we may enforce method definition objects ## If not, just leave raw functions alone (NextMethod won't work) def@target[[arg]] <- Class def@defined[[arg]] <- fromClass } def } ## Define a trivial version of asMethodDefinition for bootstrapping. ## The real version requires several class definitions as well as ## methods for as<- asMethodDefinition <- function(def, signature = list(.anyClassName), sealed = FALSE, fdef = def) { if(is.primitive(def) || is(def, "MethodDefinition")) def else { value = new("MethodDefinition") value@.Data <- def classes <- .MakeSignature(new("signature"), def, signature, fdef) value@target <- classes value@defined <- classes value } } .trimMlist <- function(mlist, fromClass) { mlist@methods <- mlist@methods[fromClass] mlist@allMethods <- mlist@allMethods[fromClass] mlist } .noMlistsFlag <- TRUE .noMlists <- function() { ## if this were to be dynamically variable, but ## it can't, IMO ## identical(getOption("noMlists"), TRUE) ## so instead .noMlistsFlag } .MlistDepTable <- new.env() .MlistDeprecated <- function(this = "<default>", instead) { if(is.character(this)) { if(exists(this, envir = .MlistDepTable, inherits = FALSE)) return() else assign(this, TRUE, envir = .MlistDepTable) } msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is deprecated." else if(is.character(this)) gettextf( "%s, along with other use of the \"MethodsList\" metadata objects, is deprecated.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is deprecated.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList. (This warning is shown once per session.)") base::.Deprecated(msg = msg) } .MlistDefunct <- function(this = "<default>", instead) { msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is defunct." else if(is.character(this)) gettextf("%s, along with other use of the \"MethodsList\" metadata objects, is defunct.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is defunct.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList.") base::.Defunct(msg = msg) }
36,574
gpl-2.0
75b9bda139852e4d82422cb316601769e1b83266
pchmieli/h2o-3
h2o-r/tests/testdir_munging/exec/runit_eq2_slotAssign_basic.R
## # Test: [<- & $<- # Description: Select a dataset, select columns, change values in the column, re-assign col ## #setupRandomSeed(1689636624) test.basic.slot.assignment <- function() { Log.info("Uploading iris data...") hex <- h2o.importFile(locate("smalldata/iris/iris_wheader.csv"), "iris.hex") oldVal <- hex[1,1] Log.info("Changing the first element in the first column of iris") Log.info("Initial value is: ") Log.info(head(oldVal)) hex[1,1] <- 48 print(head(hex)) hex$sepal_len <- 90 # new column print(head(hex)) } doTest("EQ2 Tests: [<- and $<-", test.basic.slot.assignment)
619
apache-2.0
75b9bda139852e4d82422cb316601769e1b83266
madmax983/h2o-3
h2o-r/tests/testdir_munging/exec/runit_eq2_slotAssign_basic.R
## # Test: [<- & $<- # Description: Select a dataset, select columns, change values in the column, re-assign col ## #setupRandomSeed(1689636624) test.basic.slot.assignment <- function() { Log.info("Uploading iris data...") hex <- h2o.importFile(locate("smalldata/iris/iris_wheader.csv"), "iris.hex") oldVal <- hex[1,1] Log.info("Changing the first element in the first column of iris") Log.info("Initial value is: ") Log.info(head(oldVal)) hex[1,1] <- 48 print(head(hex)) hex$sepal_len <- 90 # new column print(head(hex)) } doTest("EQ2 Tests: [<- and $<-", test.basic.slot.assignment)
619
apache-2.0
71c4978aaa94135074227729a1d4da375593bdd9
ArunChauhan/cxxr
src/library/methods/R/MethodsList.R
# File src/library/methods/R/MethodsList.R # Part of the R package, https://www.R-project.org # # Copyright (C) 1995-2016 The R Core Team # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # A copy of the GNU General Public License is available at # https://www.R-project.org/Licenses/ MethodsList <- ## Create a MethodsList object out of the arguments. ## ## Conceptually, this object is a named collection of methods to be ## dispatched when the (first) argument in a function call matches the ## class corresponding to one of the names. A final, unnamed element ## (i.e., with name `""') corresponds to the default method. ## ## The elements can be either a function, or another MethodsList. In ## the second case, this list implies dispatching on the second ## argument to the function using that list, given a selection of this ## element on the first argument. Thus, method dispatching on an ## arbitrary number of arguments is defined. ## ## MethodsList objects are used primarily to dispatch OOP-style ## methods and, in R, to emulate S4-style methods. function(.ArgName, ...) { .MlistDeprecated("MethodsList()") value <- makeMethodsList(list(...)) if(is.name(.ArgName)){} else if(is.character(.ArgName) && length(.ArgName) == 1) .ArgName <- as.name(.ArgName) else stop("invalid first argument: should be the name of the first argument in the dispatch") slot(value, "argument") <- .ArgName value } makeMethodsList <- function(object, level=1) { .MlistDeprecated("makeMethodsList()") mnames <- allNames(object) if(.noMlists()) { keep <- mnames %in% c("", "ANY") mnames <- mnames[keep] object <- object[keep] } value <- new("MethodsList") i <- match("", mnames) if(!is.na(i)) { ## convert to ANY mnames[[i]] <- "ANY" names(object) <- mnames } if(anyDuplicated(mnames)) stop(gettextf("duplicate element names in 'MethodsList' at level %d: %s", level, paste("\"", unique(mnames[duplicated(mnames)]), "\"", collapse=", ")), domain = NA) for(i in seq_along(object)) { eli <- object[[i]] if(is(eli, "function") || is(eli, "MethodsList")) {} else if(is(eli, "list") || is(eli, "named")) object[[i]] <- Recall(eli, NULL, level+1) else stop(gettextf("element %d at level %d (class %s) cannot be interpreted as a function or named list", i, level, dQuote(class(eli))), domain = NA) } slot(value, "methods") <- object value } SignatureMethod <- ## construct a MethodsList object containing (only) this method, corresponding ## to the signature; i.e., such that signature[[1L]] is the match for the first ## argument, signature[[2L]] for the second argument, and so on. The string ## "missing" means a match for a missing argument, and "ANY" means use this as the ## default setting at this level. ## ## The first argument is the argument names to be used for dispatch corresponding to ## the signatures. function(names, signature, definition) { .MlistDeprecated("SignatureMethod()") n <- length(signature) if(n > length(names)) stop("arguments 'names' and 'signature' must have the same length") if(n == 0) return(definition) Class <- signature[[n]] name <- names[[n]] m <- MethodsList(name) slot(m, "methods")[[Class]] <- definition slot(m, "argument") <- as.name(name) SignatureMethod(names[-n], signature[-n], m) } insertMethod <- ## insert the definition `def' into the MethodsList object, `mlist', corresponding to ## the signature, and return the modified MethodsList. function(mlist, signature, args, def, cacheOnly = FALSE) { .MlistDeprecated("insertMethod()") if(.noMlists() && !identical(unique(signature), "ANY")) return(mlist) ## Checks for assertions about valid calls. ## See rev. 1.17 for the code before the assertions added. if(identical(args[1L], "...") && !identical(names(signature), "...")) { if(identical(signature[[1L]], "ANY")) stop(gettextf("inserting method with invalid signature matching argument '...' to class %s", dQuote(signature[[1L]])), domain = NA) args <- args[-1L] signature <- signature[-1L] if(length(signature) == 0L) return(mlist) } if(length(signature) == 0L) stop("inserting method corresponding to empty signature") if(!is(mlist, "MethodsList")) stop(gettextf("inserting method into non-methods-list object (class %s)", dQuote(.class1(mlist))), domain = NA) if(length(args) > 1 && !cacheOnly) mlist <- balanceMethodsList(mlist, args) Class <- signature[[1]] methods <- if(cacheOnly) mlist@allMethods else mlist@methods current <- methods[[Class]] if(is(current, "MethodsList")) { nextArg <- as.character(current@argument) sigArgs <- args n <- length(signature) length(sigArgs) <- n if(is.na(match(nextArg, sigArgs))) { n <- match(nextArg, args) - n if(is.na(n)) { ## not in args eitiher n <- 1 args <- c(args, nextArg) } ## make explicit the trailing ANY's needed signature <- c(signature, rep("ANY", n)) } } if(length(signature) == 1) { if(is.null(current)) { if(!is.null(def)) methods[[Class]] <- def ## else, no change } else { which <- match(Class, names(methods)) if(is.null(def)) ## delete the method methods <- methods[-which] else methods[[which]] <- def } } else { ## recursively merge, initializing current if necessary if(is.null(current)) current <- new("MethodsList", argument = as.name(args[2L])) else if(is.function(current)) current <- new("MethodsList", argument = as.name(args[2L]), methods = list(ANY = current)) methods[[Class]] <- Recall(current, signature[-1L], args[-1L], def, cacheOnly) } mlist@allMethods <- methods if(!cacheOnly) mlist@methods <- methods mlist } MethodsListSelect <- ## select the element of a MethodsList object corresponding to the ## actual arguments (as defined in the suppled environment), ## and return the object, extended to include that method if necessary. ## ## Works recursively. At each level finds an argument name from the current `mlist' ## object, and evaluates this argument (if it is not missing), then uses the ## class of the result to select an element of `mlist'. If such an element ## exists and is another `MethodsList' object, `MethodsListSelect' calls itself recursively ## to resolve using further arguments. Matching includes using a default selection or ## a method specifically linked to class `"missing"'. Once a function is found, it ## is returned as the value. If matching fails, NULL is returned. function(f, env, mlist = NULL, fEnv = if(is(fdef, "genericFunction")) environment(fdef) else baseenv(), finalDefault = finalDefaultMethod(mlist), evalArgs = TRUE, useInherited = TRUE, ## supplied when evalArgs is FALSE fdef = getGeneric(f, where = env), # MUST BE SAFE FROM RECUSIVE METHOD SELECTION resetAllowed = TRUE # FALSE when called from selectMethod, .findNextMethod ) { .MlistDeprecated("MethodsListSelect()") if(!resetAllowed) # ensure we restore the real methods for this function resetMlist <- .getMethodsForDispatch(fdef) ## look for call from C dispatch code during another call to MethodsListSelect if(is.null(f)) {} # Recall, not from C else { fMethods <- .getMethodsForDispatch(fdef) if(is.null(mlist) || (evalArgs && is.function(fMethods))) mlist <- fMethods } resetNeeded <- .setIfBase(f, fdef, mlist) # quickly protect against recursion -- see Methods.R if(resetNeeded) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } if(!is(mlist, "MethodsList")) { if(is.function(mlist)) # call to f, inside MethodsListSelect {on.exit(); return(mlist)} if(is.null(f)) # recursive recall of MethodsListSelect stop("invalid method sublist") else if(!is.null(mlist)) # NULL => 1st call to genericFunction stop(gettextf("%f is not a valid generic function: methods list was an object of class %s", sQuote(f), dQuote(class(mlist))), domain = NA) } if(!is.logical(useInherited)) stop(gettextf("%s must be TRUE, FALSE, or a named logical vector of those values; got an object of class %s", sQuote("useInherited"), dQuote(class(useInherited))), domain = NA) if(identical(mlist, .getMethodsForDispatch(fdef))) { resetNeeded <- TRUE ## On the initial call: ## turn off any further method dispatch on this function, to avoid recursive ## loops if f is a function used in MethodsListSelect. ## TODO: Using namespaces in the methods package would eliminate the need for this .setMethodsForDispatch(f, fdef, finalDefault) if(is(mlist, "MethodsList")) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } } argName <- slot(mlist, "argument") arg <- NULL ## => don't use instance-specific inheritance if(evalArgs) { ## check for missing argument. NB: S sense, not that of R base missing() if(missingArg(argName, env, TRUE)) thisClass <- "missing" else { arg <- eval(as.name(argName), env) ## DO use instance-specific inheritance if(missing(arg)) ## S3 weird R code? Bail out! return(finalDefault) thisClass <- .class1(arg) } } else thisClass <- get(as.character(argName), envir = env, inherits = FALSE) if(identical(useInherited, TRUE) || identical(useInherited, FALSE)) thisInherit <- nextUseInherited <- useInherited else { which <- match(as.character(argName), names(useInherited)) if(is.na(which)) { nextUseInherited <- useInherited thisInherit <- TRUE } else { thisInherit <- useInherited[[which]] nextUseInherited <- useInherited[-which] } } fromClass <- thisClass ## will mark the class actually providing the method allMethods <- mlist@allMethods which <- match(thisClass, names(allMethods)) inherited <- is.na(which) selection <- if(inherited) NULL else allMethods[[which]] if(!inherited) { if(is(selection, "function")) { if(is.null(f)) { ## An inherited method at the next level up. ## only the inherited method should be added mlist <- .trimMlist(mlist, fromClass) } value <- mlist ## no change } else { ## recursive call with NULL function name, to allow search to fail & ## to suppress any reset actions. method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef, ) if(is(method, "EmptyMethodsList")) value <- method else { mlist@allMethods[[which]] <- method value <- mlist } } } if(inherited || is(value, "EmptyMethodsList")) { ## direct selection failed at this level or below method <- NULL if(thisInherit) { allSelections <- inheritedSubMethodLists(arg, fromClass, mlist, env) allClasses <- names(allSelections) for(i in seq_along(allSelections)) { selection <- allSelections[[i]] fromClass <- allClasses[[i]] if(is(selection, "function")) method <- selection else if(is(selection, "MethodsList")) { ## go on to try matching further arguments method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef) if(is(method, "EmptyMethodsList")) selection <- method ## recursive selection failed } if(!is(selection, "EmptyMethodsList")) break } } if((is.null(selection) || is(selection, "EmptyMethodsList")) && !is.null(f) && !is.null(finalDefault)) { ## only use the final default method after exhausting all ## other possibilities, at all levels. method <- finalDefault fromClass <- "ANY" } if(is.null(method) || is(method, "EmptyMethodsList")) value <- emptyMethodsList(mlist, thisClass) ## nothing found else { method <- MethodAddCoerce(method, argName, thisClass, fromClass) value <- .insertCachedMethods(mlist, as.character(argName), thisClass, fromClass, method) } } if(!is.null(f)) { ## top level if(is(value, "EmptyMethodsList")) ## selection failed value <- NULL if(resetNeeded) { on.exit() # cancel the restore of the original mlist if(resetAllowed) { if(is.null(value)) resetMlist <- mlist else resetMlist <- value } .setMethodsForDispatch(f, fdef, resetMlist) if(dispatchIsInternal(fdef)) setPrimitiveMethods(f, finalDefault, "set", fdef, resetMlist) } } value } emptyMethodsList <- function(mlist, thisClass = "ANY", sublist = list()) { .MlistDeprecated("emptyMethodsList()") sublist[thisClass] <- list(NULL) new("EmptyMethodsList", argument = mlist@argument, sublist = sublist) } insertMethodInEmptyList <- function(mlist, def) { .MlistDeprecated("insertMethodInEmptyList()") value <- new("MethodsList", argument = mlist@argument) sublist <- mlist@sublist submethods <- sublist[[1L]] if(is.null(submethods)) sublist[[1L]] <- def else sublist[[1L]] <- Recall(submethods, def) value@allMethods <- sublist value } finalDefaultMethod <- ## Return the default method from the generic (it may be NULL, a method object or a primitive. ## this previously searched in a MethodsList object. Once those are gone, the loop should ## be irrelevant except as an error check. function(method) { repeat { if(is.function(method) # <- somewhat liberal, but catches both methods and primitives || is.null(method)) break if(is(method, "MethodsList")) { .MlistDeprecated() method <- slot(method, "methods")[["ANY"]] } else stop(gettextf( "default method must be a method definition, a primitive or NULL: got an object of class %s", dQuote(class(method))), domain = NA) } method } inheritedSubMethodLists <- ## Utility function to match the object to the elements of a methods list. ## ## The function looks only for an inherited match, and only among ## the methods that are not themselves inherited. (Inherited methods when found are ## stored in the session copy of the methods list, but they themselves should not be ## used for finding inherited matches, because an erroneous match could be found depending ## on which methods were previously used. See the detailed discussion of methods.) function(object, thisClass, mlist, ev) { .MlistDeprecated("inheritedSubMethodLists()") methods <- slot(mlist, "methods")## only direct methods defaultMethod <- methods[["ANY"]]## maybe NULL classes <- names(methods) value <- list() if(.identC(thisClass, "missing")) { ## no superclasses for "missing" } else { ## search in the superclasses, but don't use inherited methods ## There are two cases: if thisClass is formally defined & unsealed, use its ## superclasses. Otherwise, look in the subclasses of those classes for ## which methods exist. classDef <- getClassDef(thisClass, ev) useSuperClasses <- !is.null(classDef) && !classDef@sealed if(useSuperClasses) { ## for consistency, order the available methods by ## the ordering of the superclasses of thisClass superClasses <- names(classDef@contains) classes <- superClasses[!is.na(match(superClasses, classes))] for(which in seq_along(classes)) { tryClass <- classes[[which]] ## TODO: There is potential bug here: If the is relation is conditional, ## we should not cache this selection. Needs another trick in the environment ## to FORCE no caching regardless of what happens elsewhere; e.g., storing a ## special object in .Class if(is.null(object) || is(object, tryClass)) { value[[tryClass]] <- methods[[tryClass]] } } } else { for(which in seq_along(classes)) { tryClass <- classes[[which]] tryClassDef <- getClassDef(tryClass, ev) if(!is.null(tryClassDef) && !is.na(match(thisClass, names(tryClassDef@subclasses)))) value[[tryClass]] <- methods[[which]] } } } if(!is.null(defaultMethod)) value[["ANY"]] <- defaultMethod value } matchSignature <- ## Match the signature object (a partially or completely named subset of the ## arguments of `fun', and return a vector of all the classes in the order specified ## by the signature slot of the generic. The classes not specified by `signature ##' will be `"ANY"' in the value. function(signature, fun, where = baseenv()) { if(!is(fun, "genericFunction")) stop(gettextf("trying to match a method signature to an object (of class %s) that is not a generic function", dQuote(class(fun))), domain = NA) anames <- fun@signature if(length(signature) == 0L) return(character()) if(is(signature,"character")) { pkgs <- packageSlot(signature) # includes case of "ObjectsWithPackage" if(is.null(pkgs)) pkgs <- character(length(signature)) else if(length(pkgs) != length(signature)) stop("invalid 'package' slot or attribute, wrong length") sigClasses <- as.character(signature) } else if(is(signature, "list")) { sigClasses <- pkgs <- character(length(signature)) for(i in seq_along(signature)) { cli <- signature[[i]] if(is(cli, "classRepresentation")) { sigClasses[[i]] <- cli@className pkgs[[i]] <- cli@package } else if(is(cli, "character") && length(cli) == 1) { sigClasses[[i]] <- cli pkgi <- packageSlot(cli) if(is.character(pkgi)) pkgs[[i]] <- pkgi } else stop(gettextf("invalid element in a list for \"signature\" argument; element %d is neither a class definition nor a class name", i), domain = NA) } } else stop(gettextf("trying to match a method signature of class %s; expects a list or a character vector", dQuote(class(signature))), domain = NA) if(!identical(where, baseenv())) { ## fill in package information, warn about undefined classes unknown <- !nzchar(pkgs) for(i in seq_along(sigClasses)[unknown]) { cli <- getClassDef(sigClasses[[i]], where) if(!is.null(cli)) { pkgs[[i]] <- cli@package unknown[[i]] <- FALSE } } if(any(unknown)) { unknown <- unique(sigClasses[unknown]) ## coerce(), i.e., setAs() may use *one* unknown class MSG <- if(identical(as.vector(coerce@generic), "coerce") && length(unknown) == 1) message else function(...) warning(..., call. = FALSE) MSG(.renderSignature(fun@generic, signature), sprintf(ngettext(length(unknown), "no definition for class %s", "no definition for classes %s"), paste(dQuote(unknown), collapse = ", ")), domain = NA) } } signature <- as.list(signature) if(length(sigClasses) != length(signature)) stop(gettextf("object to use as a method signature for function %s does not look like a legitimate signature (a vector of single class names): there were %d class names, but %d elements in the signature object", sQuote(fun@generic), length(sigClasses), length(signature)), domain = NA) if(is.null(names(signature))) { which <- seq_along(signature) if(length(which) > length(anames)) stop(gettextf("more elements in the method signature (%d) than in the generic signature (%d) for function %s", length(which), length(anames), sQuote(fun@generic)), domain = NA) } else { ## construct a function call with the same naming pattern & ## values as signature sigList <- signature for(i in seq_along(sigList)) sigList[[i]] <- c(sigClasses[[i]], pkgs[[i]]) fcall <- do.call("call", c("fun", sigList)) ## match the call to the formal signature (usually the formal args) if(identical(anames, formalArgs(fun))) smatch <- match.call(fun, fcall) else { fmatch <- fun ff <- as.list(anames); names(ff) <- anames formals(fmatch, envir = environment(fun)) <- ff smatch <- match.call(fmatch, fcall) } snames <- names(smatch)[-1L] which <- match(snames, anames) ## Assertion: match.call has permuted the args into the order of formal args, ## and carried along the values. Get the supplied classes in that ## order, from the matched args in the call object. if(anyNA(which)) stop(sprintf(ngettext(sum(is.na(which)), "in the method signature for function %s invalid argument name in the signature: %s", "in the method signature for function %s invalid argument names in the signature: %s"), sQuote(fun@generic), paste(snames[is.na(which)], collapse = ", ")), domain = NA) smatch <- smatch[-1] for(i in seq_along(smatch)) { eli <- smatch[[i]] sigClasses[[i]] <- eli[[1]] pkgs[[i]] <- eli[[2]] } } n <- length(anames) value <- rep("ANY", n) valueP <- rep("methods", n) names(value) <- anames value[which] <- sigClasses valueP[which] <- pkgs unspec <- value == "ANY" ## remove the trailing unspecified classes while(n > 1 && unspec[[n]]) n <- n-1 length(value) <- length(valueP) <- n attr(value, "package") <- valueP ## <FIXME> Is there a reason (bootstrapping?) why this ## is not an actual object from class "signature"? ## See .MakeSignature() </FIXME> value } showMlist <- ## Prints the contents of the MethodsList. If `includeDefs' the signatures and the ## corresponding definitions will be printed; otherwise, only the signatures. ## ## If `includeDefs' is `TRUE', the currently known inherited methods are included; ## otherwise, only the directly defined methods. function(mlist, includeDefs = TRUE, inherited = TRUE, classes = NULL, useArgNames = TRUE, printTo = stdout()) { .MlistDeprecated("showMlist()") if(identical(printTo, FALSE)) { tmp <- tempfile() con <- file(tmp, "w") } else con <- printTo object <- linearizeMlist(mlist, inherited) methods <- object@methods signatures <- object@classes args <- object@arguments if(!is.null(classes) && length(signatures)>0) { keep <- !vapply(signatures, function(x, y) all(is.na(match(x, y))), NA, classes) methods <- methods[keep] signatures <- signatures[keep] args <- args[keep] } if(length(methods) == 0) cat(file=con, "<Empty Methods List>\n") else { n <- length(methods) labels <- character(n) if(useArgNames) { for(i in 1L:n) { sigi <- signatures[[i]] labels[[i]] <- paste(args[[i]], " = \"", sigi, "\"", sep = "", collapse = ", ") } } else { for(i in 1L:n) labels[[i]] <- paste(signatures[[i]], collapse = ", ") } for(i in seq_along(methods)) { cat(file=con, (if(includeDefs) "## Signature:" else ""), labels[[i]]) method <- methods[[i]] if(includeDefs) { cat(file=con, ":\n") if(is(method, "MethodDefinition")) ## really an assertion cat(file=con, deparse(method@.Data), sep="\n") else cat(file=con, deparse(method), sep="\n") } if(is(method, "MethodDefinition") && !identical(method@target, method@defined)) { defFrom <- method@defined cat(file = con, if(includeDefs) "##:" else "\n", " (inherited from ", paste(names(defFrom), " = \"", as.character(defFrom), "\"", sep = "", collapse = ", "), ")", if(includeDefs) "\n", sep="") } cat(file=con, "\n") } } if(identical(printTo, FALSE)) { close(con) value <- readLines(tmp) unlink(tmp) value } } promptMethods <- function(f, filename = NULL, methods) { ## Generate information in the style of 'prompt' for the methods of ## the generic named 'f'. ## ## 'filename' can be a logical or NA or the name of a file to print ## to. If it 'FALSE', the methods skeleton is returned, to be ## included in other printing (typically, the output from 'prompt'). escape <- function(txt) gsub("%", "\\\\%", txt) packageString <- "" fdef <- getGeneric(f) if(!isGeneric(f, fdef=fdef)) stop(gettextf("no generic function found corresponding to %s", sQuote(f)), domain = NA) if(missing(methods)) { methods <- findMethods(fdef) ## try making packageString where <- .genEnv(fdef, topenv(parent.frame())) if(!identical(where, .GlobalEnv)) packageString <- sprintf("in Package \\pkg{%s}", getPackageName(where)) } fullName <- utils:::topicName("methods", f) n <- length(methods) labels <- character(n) aliases <- character(n) signatures <- findMethodSignatures(methods = methods, target=TRUE) args <- colnames(signatures) # the *same* for all for(i in seq_len(n)) { sigi <- signatures[i, ] labels[[i]] <- sprintf("\\code{signature(%s)}", paste(sprintf("%s = \"%s\"", args, escape(sigi)), collapse = ", ")) aliases[[i]] <- paste0("\\alias{", utils:::topicName("method", c(f, signatures[i,])), "}") } text <- paste0("\n\\item{", labels, "}{\n%% ~~describe this method here~~\n}") text <- c("\\section{Methods}{\n\\describe{", text, "}}") aliasText <- c(paste0("\\alias{", escape(fullName), "}"), escape(aliases)) if(identical(filename, FALSE)) return(c(aliasText, text)) if(is.null(filename) || identical(filename, TRUE)) filename <- paste0(fullName, ".Rd") Rdtxt <- list(name = paste0("\\name{", fullName, "}"), type = "\\docType{methods}", aliases = aliasText, ## <FIXME> ## Title and description are ok as auto-generated: should ## they be flagged as such (via '~~' which are quite often ## left in by authors)? title = sprintf("\\title{ ~~ Methods for Function \\code{%s} %s ~~}", f, packageString), description = paste0("\\description{\n ~~ Methods for function", " \\code{", f, "} ", sub("^in Package", "in package", packageString), " ~~\n}"), ## </FIXME> "section{Methods}" = text, keywords = c("\\keyword{methods}", "\\keyword{ ~~ other possible keyword(s) ~~ }")) if(is.na(filename)) return(Rdtxt) cat(unlist(Rdtxt), file = filename, sep = "\n") .message("A shell of methods documentation has been written", .fileDesc(filename), ".\n") invisible(filename) } ##' only called from showMlist() above, which has been deprecated in R 3.2.0 (Apr.2015): linearizeMlist <- ## Undo the recursive nature of the methods list, making a list of ## function definitions, with the names of the list being the ## corresponding signatures (designed for printing; for looping over ## the methods, use `listFromMlist' instead). ## ## The function calls itself recursively. `prev' is the previously ## selected class names. ## ## If argument `classes' is provided, only signatures containing one ## of these classes will be included. function(mlist, inherited = TRUE) { methods <- mlist@methods allMethods <- mlist@allMethods if(inherited && length(allMethods) >= length(methods)) { ## anames <- names(allMethods) ## inh <- is.na(match(anames, names(methods))) methods <- allMethods } preC <- function(y, x)c(x,y) # used with lapply below cnames <- names(methods) value <- list() classes <- list() arguments <- list() argname <- as.character(mlist@argument) for(i in seq_along(cnames)) { mi <- methods[[i]] if(is.function(mi)) { value <- c(value, list(mi)) classes <- c(classes, list(cnames[[i]])) arguments <- c(arguments, list(argname)) } else if(is(mi, "MethodsList")) { .MlistDeprecated() mi <- Recall(mi, inherited) value <- c(value, mi@methods) classes <- c(classes, lapply(mi@classes, preC, cnames[[i]])) arguments <- c(arguments, lapply(mi@arguments, preC, argname)) } else warning(gettextf("skipping methods list element %s of unexpected class %s\n\n", paste(cnames[i], collapse = ", "), dQuote(.class1(mi))), domain = NA) } new("LinearMethodsList", methods = value, classes = classes, arguments = arguments) } print.MethodsList <- function(x, ...) showMlist(x) ## In R's own code, this is *only* used in mergeMethods(), deprecated in R 3.2.0 (Apr.2015) listFromMlist <- ## linearizes the MethodsList object into list(sigs, methods); `prefix' is the partial ## signature (a named list of classes) to be prepended to the signatures in this object. ## ## A utility function used to iterate over all the individual methods in the object. function(mlist, prefix = list(), sigs. = TRUE, methods. = TRUE) { methodSlot <- slot(mlist, "methods") mnames <- names(methodSlot) argName <- as.character(slot(mlist, "argument")) sigs <- list() methods <- list() for(i in seq_along(methodSlot)) { thisMethod <- methodSlot[i] thisClass <- mnames[[i]] prefix[[argName]] <- thisClass if(is.function(thisMethod)) { if(sigs.) sigs <- c(sigs, list(prefix)) if(methods.) methods <- c(methods, list(thisMethod)) } else { more <- Recall(thisMethod, prefix) if(sigs.) sigs <- c(sigs, more[[1]]) if(methods.) methods <- c(methods, more[[2]]) } } list(sigs, methods) } .insertCachedMethods <- function(mlist, argName, Class, fromClass, def) { if(is(def, "MethodsList")) { .MlistDeprecated() ## insert all the cached methods in def newArg <- c(argName, as.character(def@argument)) newDefs <- def@allMethods newSigs <- as.list(names(newDefs)) for(j in seq_along(newDefs)) mlist <- Recall(mlist, newArg, c(Class, newSigs[[j]]), fromClass, newDefs[[j]]) } else { def <- .addMethodFrom(def, argName[1L], Class[1L], fromClass) mlist <- insertMethod(mlist, Class, argName, def, TRUE) } mlist } .addMethodFrom <- function(def, arg, Class, fromClass) { if(is(def, "MethodDefinition")) { ## eventually, we may enforce method definition objects ## If not, just leave raw functions alone (NextMethod won't work) def@target[[arg]] <- Class def@defined[[arg]] <- fromClass } def } ## Define a trivial version of asMethodDefinition for bootstrapping. ## The real version requires several class definitions as well as ## methods for as<- asMethodDefinition <- function(def, signature = list(.anyClassName), sealed = FALSE, fdef = def) { if(is.primitive(def) || is(def, "MethodDefinition")) def else { value = new("MethodDefinition") value@.Data <- def classes <- .MakeSignature(new("signature"), def, signature, fdef) value@target <- classes value@defined <- classes value } } .trimMlist <- function(mlist, fromClass) { mlist@methods <- mlist@methods[fromClass] mlist@allMethods <- mlist@allMethods[fromClass] mlist } .noMlistsFlag <- TRUE .noMlists <- function() { ## if this were to be dynamically variable, but ## it can't, IMO ## identical(getOption("noMlists"), TRUE) ## so instead .noMlistsFlag } .MlistDepTable <- new.env() .MlistDeprecated <- function(this = "<default>", instead) { if(is.character(this)) { if(exists(this, envir = .MlistDepTable, inherits = FALSE)) return() else assign(this, TRUE, envir = .MlistDepTable) } msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is deprecated." else if(is.character(this)) gettextf( "%s, along with other use of the \"MethodsList\" metadata objects, is deprecated.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is deprecated.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList. (This warning is shown once per session.)") base::.Deprecated(msg = msg) } .MlistDefunct <- function(this = "<default>", instead) { msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is defunct." else if(is.character(this)) gettextf("%s, along with other use of the \"MethodsList\" metadata objects, is defunct.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is defunct.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList.") base::.Defunct(msg = msg) }
36,574
gpl-2.0
71c4978aaa94135074227729a1d4da375593bdd9
SurajGupta/r-source
src/library/methods/R/MethodsList.R
# File src/library/methods/R/MethodsList.R # Part of the R package, https://www.R-project.org # # Copyright (C) 1995-2016 The R Core Team # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # A copy of the GNU General Public License is available at # https://www.R-project.org/Licenses/ MethodsList <- ## Create a MethodsList object out of the arguments. ## ## Conceptually, this object is a named collection of methods to be ## dispatched when the (first) argument in a function call matches the ## class corresponding to one of the names. A final, unnamed element ## (i.e., with name `""') corresponds to the default method. ## ## The elements can be either a function, or another MethodsList. In ## the second case, this list implies dispatching on the second ## argument to the function using that list, given a selection of this ## element on the first argument. Thus, method dispatching on an ## arbitrary number of arguments is defined. ## ## MethodsList objects are used primarily to dispatch OOP-style ## methods and, in R, to emulate S4-style methods. function(.ArgName, ...) { .MlistDeprecated("MethodsList()") value <- makeMethodsList(list(...)) if(is.name(.ArgName)){} else if(is.character(.ArgName) && length(.ArgName) == 1) .ArgName <- as.name(.ArgName) else stop("invalid first argument: should be the name of the first argument in the dispatch") slot(value, "argument") <- .ArgName value } makeMethodsList <- function(object, level=1) { .MlistDeprecated("makeMethodsList()") mnames <- allNames(object) if(.noMlists()) { keep <- mnames %in% c("", "ANY") mnames <- mnames[keep] object <- object[keep] } value <- new("MethodsList") i <- match("", mnames) if(!is.na(i)) { ## convert to ANY mnames[[i]] <- "ANY" names(object) <- mnames } if(anyDuplicated(mnames)) stop(gettextf("duplicate element names in 'MethodsList' at level %d: %s", level, paste("\"", unique(mnames[duplicated(mnames)]), "\"", collapse=", ")), domain = NA) for(i in seq_along(object)) { eli <- object[[i]] if(is(eli, "function") || is(eli, "MethodsList")) {} else if(is(eli, "list") || is(eli, "named")) object[[i]] <- Recall(eli, NULL, level+1) else stop(gettextf("element %d at level %d (class %s) cannot be interpreted as a function or named list", i, level, dQuote(class(eli))), domain = NA) } slot(value, "methods") <- object value } SignatureMethod <- ## construct a MethodsList object containing (only) this method, corresponding ## to the signature; i.e., such that signature[[1L]] is the match for the first ## argument, signature[[2L]] for the second argument, and so on. The string ## "missing" means a match for a missing argument, and "ANY" means use this as the ## default setting at this level. ## ## The first argument is the argument names to be used for dispatch corresponding to ## the signatures. function(names, signature, definition) { .MlistDeprecated("SignatureMethod()") n <- length(signature) if(n > length(names)) stop("arguments 'names' and 'signature' must have the same length") if(n == 0) return(definition) Class <- signature[[n]] name <- names[[n]] m <- MethodsList(name) slot(m, "methods")[[Class]] <- definition slot(m, "argument") <- as.name(name) SignatureMethod(names[-n], signature[-n], m) } insertMethod <- ## insert the definition `def' into the MethodsList object, `mlist', corresponding to ## the signature, and return the modified MethodsList. function(mlist, signature, args, def, cacheOnly = FALSE) { .MlistDeprecated("insertMethod()") if(.noMlists() && !identical(unique(signature), "ANY")) return(mlist) ## Checks for assertions about valid calls. ## See rev. 1.17 for the code before the assertions added. if(identical(args[1L], "...") && !identical(names(signature), "...")) { if(identical(signature[[1L]], "ANY")) stop(gettextf("inserting method with invalid signature matching argument '...' to class %s", dQuote(signature[[1L]])), domain = NA) args <- args[-1L] signature <- signature[-1L] if(length(signature) == 0L) return(mlist) } if(length(signature) == 0L) stop("inserting method corresponding to empty signature") if(!is(mlist, "MethodsList")) stop(gettextf("inserting method into non-methods-list object (class %s)", dQuote(.class1(mlist))), domain = NA) if(length(args) > 1 && !cacheOnly) mlist <- balanceMethodsList(mlist, args) Class <- signature[[1]] methods <- if(cacheOnly) mlist@allMethods else mlist@methods current <- methods[[Class]] if(is(current, "MethodsList")) { nextArg <- as.character(current@argument) sigArgs <- args n <- length(signature) length(sigArgs) <- n if(is.na(match(nextArg, sigArgs))) { n <- match(nextArg, args) - n if(is.na(n)) { ## not in args eitiher n <- 1 args <- c(args, nextArg) } ## make explicit the trailing ANY's needed signature <- c(signature, rep("ANY", n)) } } if(length(signature) == 1) { if(is.null(current)) { if(!is.null(def)) methods[[Class]] <- def ## else, no change } else { which <- match(Class, names(methods)) if(is.null(def)) ## delete the method methods <- methods[-which] else methods[[which]] <- def } } else { ## recursively merge, initializing current if necessary if(is.null(current)) current <- new("MethodsList", argument = as.name(args[2L])) else if(is.function(current)) current <- new("MethodsList", argument = as.name(args[2L]), methods = list(ANY = current)) methods[[Class]] <- Recall(current, signature[-1L], args[-1L], def, cacheOnly) } mlist@allMethods <- methods if(!cacheOnly) mlist@methods <- methods mlist } MethodsListSelect <- ## select the element of a MethodsList object corresponding to the ## actual arguments (as defined in the suppled environment), ## and return the object, extended to include that method if necessary. ## ## Works recursively. At each level finds an argument name from the current `mlist' ## object, and evaluates this argument (if it is not missing), then uses the ## class of the result to select an element of `mlist'. If such an element ## exists and is another `MethodsList' object, `MethodsListSelect' calls itself recursively ## to resolve using further arguments. Matching includes using a default selection or ## a method specifically linked to class `"missing"'. Once a function is found, it ## is returned as the value. If matching fails, NULL is returned. function(f, env, mlist = NULL, fEnv = if(is(fdef, "genericFunction")) environment(fdef) else baseenv(), finalDefault = finalDefaultMethod(mlist), evalArgs = TRUE, useInherited = TRUE, ## supplied when evalArgs is FALSE fdef = getGeneric(f, where = env), # MUST BE SAFE FROM RECUSIVE METHOD SELECTION resetAllowed = TRUE # FALSE when called from selectMethod, .findNextMethod ) { .MlistDeprecated("MethodsListSelect()") if(!resetAllowed) # ensure we restore the real methods for this function resetMlist <- .getMethodsForDispatch(fdef) ## look for call from C dispatch code during another call to MethodsListSelect if(is.null(f)) {} # Recall, not from C else { fMethods <- .getMethodsForDispatch(fdef) if(is.null(mlist) || (evalArgs && is.function(fMethods))) mlist <- fMethods } resetNeeded <- .setIfBase(f, fdef, mlist) # quickly protect against recursion -- see Methods.R if(resetNeeded) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } if(!is(mlist, "MethodsList")) { if(is.function(mlist)) # call to f, inside MethodsListSelect {on.exit(); return(mlist)} if(is.null(f)) # recursive recall of MethodsListSelect stop("invalid method sublist") else if(!is.null(mlist)) # NULL => 1st call to genericFunction stop(gettextf("%f is not a valid generic function: methods list was an object of class %s", sQuote(f), dQuote(class(mlist))), domain = NA) } if(!is.logical(useInherited)) stop(gettextf("%s must be TRUE, FALSE, or a named logical vector of those values; got an object of class %s", sQuote("useInherited"), dQuote(class(useInherited))), domain = NA) if(identical(mlist, .getMethodsForDispatch(fdef))) { resetNeeded <- TRUE ## On the initial call: ## turn off any further method dispatch on this function, to avoid recursive ## loops if f is a function used in MethodsListSelect. ## TODO: Using namespaces in the methods package would eliminate the need for this .setMethodsForDispatch(f, fdef, finalDefault) if(is(mlist, "MethodsList")) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } } argName <- slot(mlist, "argument") arg <- NULL ## => don't use instance-specific inheritance if(evalArgs) { ## check for missing argument. NB: S sense, not that of R base missing() if(missingArg(argName, env, TRUE)) thisClass <- "missing" else { arg <- eval(as.name(argName), env) ## DO use instance-specific inheritance if(missing(arg)) ## S3 weird R code? Bail out! return(finalDefault) thisClass <- .class1(arg) } } else thisClass <- get(as.character(argName), envir = env, inherits = FALSE) if(identical(useInherited, TRUE) || identical(useInherited, FALSE)) thisInherit <- nextUseInherited <- useInherited else { which <- match(as.character(argName), names(useInherited)) if(is.na(which)) { nextUseInherited <- useInherited thisInherit <- TRUE } else { thisInherit <- useInherited[[which]] nextUseInherited <- useInherited[-which] } } fromClass <- thisClass ## will mark the class actually providing the method allMethods <- mlist@allMethods which <- match(thisClass, names(allMethods)) inherited <- is.na(which) selection <- if(inherited) NULL else allMethods[[which]] if(!inherited) { if(is(selection, "function")) { if(is.null(f)) { ## An inherited method at the next level up. ## only the inherited method should be added mlist <- .trimMlist(mlist, fromClass) } value <- mlist ## no change } else { ## recursive call with NULL function name, to allow search to fail & ## to suppress any reset actions. method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef, ) if(is(method, "EmptyMethodsList")) value <- method else { mlist@allMethods[[which]] <- method value <- mlist } } } if(inherited || is(value, "EmptyMethodsList")) { ## direct selection failed at this level or below method <- NULL if(thisInherit) { allSelections <- inheritedSubMethodLists(arg, fromClass, mlist, env) allClasses <- names(allSelections) for(i in seq_along(allSelections)) { selection <- allSelections[[i]] fromClass <- allClasses[[i]] if(is(selection, "function")) method <- selection else if(is(selection, "MethodsList")) { ## go on to try matching further arguments method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef) if(is(method, "EmptyMethodsList")) selection <- method ## recursive selection failed } if(!is(selection, "EmptyMethodsList")) break } } if((is.null(selection) || is(selection, "EmptyMethodsList")) && !is.null(f) && !is.null(finalDefault)) { ## only use the final default method after exhausting all ## other possibilities, at all levels. method <- finalDefault fromClass <- "ANY" } if(is.null(method) || is(method, "EmptyMethodsList")) value <- emptyMethodsList(mlist, thisClass) ## nothing found else { method <- MethodAddCoerce(method, argName, thisClass, fromClass) value <- .insertCachedMethods(mlist, as.character(argName), thisClass, fromClass, method) } } if(!is.null(f)) { ## top level if(is(value, "EmptyMethodsList")) ## selection failed value <- NULL if(resetNeeded) { on.exit() # cancel the restore of the original mlist if(resetAllowed) { if(is.null(value)) resetMlist <- mlist else resetMlist <- value } .setMethodsForDispatch(f, fdef, resetMlist) if(dispatchIsInternal(fdef)) setPrimitiveMethods(f, finalDefault, "set", fdef, resetMlist) } } value } emptyMethodsList <- function(mlist, thisClass = "ANY", sublist = list()) { .MlistDeprecated("emptyMethodsList()") sublist[thisClass] <- list(NULL) new("EmptyMethodsList", argument = mlist@argument, sublist = sublist) } insertMethodInEmptyList <- function(mlist, def) { .MlistDeprecated("insertMethodInEmptyList()") value <- new("MethodsList", argument = mlist@argument) sublist <- mlist@sublist submethods <- sublist[[1L]] if(is.null(submethods)) sublist[[1L]] <- def else sublist[[1L]] <- Recall(submethods, def) value@allMethods <- sublist value } finalDefaultMethod <- ## Return the default method from the generic (it may be NULL, a method object or a primitive. ## this previously searched in a MethodsList object. Once those are gone, the loop should ## be irrelevant except as an error check. function(method) { repeat { if(is.function(method) # <- somewhat liberal, but catches both methods and primitives || is.null(method)) break if(is(method, "MethodsList")) { .MlistDeprecated() method <- slot(method, "methods")[["ANY"]] } else stop(gettextf( "default method must be a method definition, a primitive or NULL: got an object of class %s", dQuote(class(method))), domain = NA) } method } inheritedSubMethodLists <- ## Utility function to match the object to the elements of a methods list. ## ## The function looks only for an inherited match, and only among ## the methods that are not themselves inherited. (Inherited methods when found are ## stored in the session copy of the methods list, but they themselves should not be ## used for finding inherited matches, because an erroneous match could be found depending ## on which methods were previously used. See the detailed discussion of methods.) function(object, thisClass, mlist, ev) { .MlistDeprecated("inheritedSubMethodLists()") methods <- slot(mlist, "methods")## only direct methods defaultMethod <- methods[["ANY"]]## maybe NULL classes <- names(methods) value <- list() if(.identC(thisClass, "missing")) { ## no superclasses for "missing" } else { ## search in the superclasses, but don't use inherited methods ## There are two cases: if thisClass is formally defined & unsealed, use its ## superclasses. Otherwise, look in the subclasses of those classes for ## which methods exist. classDef <- getClassDef(thisClass, ev) useSuperClasses <- !is.null(classDef) && !classDef@sealed if(useSuperClasses) { ## for consistency, order the available methods by ## the ordering of the superclasses of thisClass superClasses <- names(classDef@contains) classes <- superClasses[!is.na(match(superClasses, classes))] for(which in seq_along(classes)) { tryClass <- classes[[which]] ## TODO: There is potential bug here: If the is relation is conditional, ## we should not cache this selection. Needs another trick in the environment ## to FORCE no caching regardless of what happens elsewhere; e.g., storing a ## special object in .Class if(is.null(object) || is(object, tryClass)) { value[[tryClass]] <- methods[[tryClass]] } } } else { for(which in seq_along(classes)) { tryClass <- classes[[which]] tryClassDef <- getClassDef(tryClass, ev) if(!is.null(tryClassDef) && !is.na(match(thisClass, names(tryClassDef@subclasses)))) value[[tryClass]] <- methods[[which]] } } } if(!is.null(defaultMethod)) value[["ANY"]] <- defaultMethod value } matchSignature <- ## Match the signature object (a partially or completely named subset of the ## arguments of `fun', and return a vector of all the classes in the order specified ## by the signature slot of the generic. The classes not specified by `signature ##' will be `"ANY"' in the value. function(signature, fun, where = baseenv()) { if(!is(fun, "genericFunction")) stop(gettextf("trying to match a method signature to an object (of class %s) that is not a generic function", dQuote(class(fun))), domain = NA) anames <- fun@signature if(length(signature) == 0L) return(character()) if(is(signature,"character")) { pkgs <- packageSlot(signature) # includes case of "ObjectsWithPackage" if(is.null(pkgs)) pkgs <- character(length(signature)) else if(length(pkgs) != length(signature)) stop("invalid 'package' slot or attribute, wrong length") sigClasses <- as.character(signature) } else if(is(signature, "list")) { sigClasses <- pkgs <- character(length(signature)) for(i in seq_along(signature)) { cli <- signature[[i]] if(is(cli, "classRepresentation")) { sigClasses[[i]] <- cli@className pkgs[[i]] <- cli@package } else if(is(cli, "character") && length(cli) == 1) { sigClasses[[i]] <- cli pkgi <- packageSlot(cli) if(is.character(pkgi)) pkgs[[i]] <- pkgi } else stop(gettextf("invalid element in a list for \"signature\" argument; element %d is neither a class definition nor a class name", i), domain = NA) } } else stop(gettextf("trying to match a method signature of class %s; expects a list or a character vector", dQuote(class(signature))), domain = NA) if(!identical(where, baseenv())) { ## fill in package information, warn about undefined classes unknown <- !nzchar(pkgs) for(i in seq_along(sigClasses)[unknown]) { cli <- getClassDef(sigClasses[[i]], where) if(!is.null(cli)) { pkgs[[i]] <- cli@package unknown[[i]] <- FALSE } } if(any(unknown)) { unknown <- unique(sigClasses[unknown]) ## coerce(), i.e., setAs() may use *one* unknown class MSG <- if(identical(as.vector(coerce@generic), "coerce") && length(unknown) == 1) message else function(...) warning(..., call. = FALSE) MSG(.renderSignature(fun@generic, signature), sprintf(ngettext(length(unknown), "no definition for class %s", "no definition for classes %s"), paste(dQuote(unknown), collapse = ", ")), domain = NA) } } signature <- as.list(signature) if(length(sigClasses) != length(signature)) stop(gettextf("object to use as a method signature for function %s does not look like a legitimate signature (a vector of single class names): there were %d class names, but %d elements in the signature object", sQuote(fun@generic), length(sigClasses), length(signature)), domain = NA) if(is.null(names(signature))) { which <- seq_along(signature) if(length(which) > length(anames)) stop(gettextf("more elements in the method signature (%d) than in the generic signature (%d) for function %s", length(which), length(anames), sQuote(fun@generic)), domain = NA) } else { ## construct a function call with the same naming pattern & ## values as signature sigList <- signature for(i in seq_along(sigList)) sigList[[i]] <- c(sigClasses[[i]], pkgs[[i]]) fcall <- do.call("call", c("fun", sigList)) ## match the call to the formal signature (usually the formal args) if(identical(anames, formalArgs(fun))) smatch <- match.call(fun, fcall) else { fmatch <- fun ff <- as.list(anames); names(ff) <- anames formals(fmatch, envir = environment(fun)) <- ff smatch <- match.call(fmatch, fcall) } snames <- names(smatch)[-1L] which <- match(snames, anames) ## Assertion: match.call has permuted the args into the order of formal args, ## and carried along the values. Get the supplied classes in that ## order, from the matched args in the call object. if(anyNA(which)) stop(sprintf(ngettext(sum(is.na(which)), "in the method signature for function %s invalid argument name in the signature: %s", "in the method signature for function %s invalid argument names in the signature: %s"), sQuote(fun@generic), paste(snames[is.na(which)], collapse = ", ")), domain = NA) smatch <- smatch[-1] for(i in seq_along(smatch)) { eli <- smatch[[i]] sigClasses[[i]] <- eli[[1]] pkgs[[i]] <- eli[[2]] } } n <- length(anames) value <- rep("ANY", n) valueP <- rep("methods", n) names(value) <- anames value[which] <- sigClasses valueP[which] <- pkgs unspec <- value == "ANY" ## remove the trailing unspecified classes while(n > 1 && unspec[[n]]) n <- n-1 length(value) <- length(valueP) <- n attr(value, "package") <- valueP ## <FIXME> Is there a reason (bootstrapping?) why this ## is not an actual object from class "signature"? ## See .MakeSignature() </FIXME> value } showMlist <- ## Prints the contents of the MethodsList. If `includeDefs' the signatures and the ## corresponding definitions will be printed; otherwise, only the signatures. ## ## If `includeDefs' is `TRUE', the currently known inherited methods are included; ## otherwise, only the directly defined methods. function(mlist, includeDefs = TRUE, inherited = TRUE, classes = NULL, useArgNames = TRUE, printTo = stdout()) { .MlistDeprecated("showMlist()") if(identical(printTo, FALSE)) { tmp <- tempfile() con <- file(tmp, "w") } else con <- printTo object <- linearizeMlist(mlist, inherited) methods <- object@methods signatures <- object@classes args <- object@arguments if(!is.null(classes) && length(signatures)>0) { keep <- !vapply(signatures, function(x, y) all(is.na(match(x, y))), NA, classes) methods <- methods[keep] signatures <- signatures[keep] args <- args[keep] } if(length(methods) == 0) cat(file=con, "<Empty Methods List>\n") else { n <- length(methods) labels <- character(n) if(useArgNames) { for(i in 1L:n) { sigi <- signatures[[i]] labels[[i]] <- paste(args[[i]], " = \"", sigi, "\"", sep = "", collapse = ", ") } } else { for(i in 1L:n) labels[[i]] <- paste(signatures[[i]], collapse = ", ") } for(i in seq_along(methods)) { cat(file=con, (if(includeDefs) "## Signature:" else ""), labels[[i]]) method <- methods[[i]] if(includeDefs) { cat(file=con, ":\n") if(is(method, "MethodDefinition")) ## really an assertion cat(file=con, deparse(method@.Data), sep="\n") else cat(file=con, deparse(method), sep="\n") } if(is(method, "MethodDefinition") && !identical(method@target, method@defined)) { defFrom <- method@defined cat(file = con, if(includeDefs) "##:" else "\n", " (inherited from ", paste(names(defFrom), " = \"", as.character(defFrom), "\"", sep = "", collapse = ", "), ")", if(includeDefs) "\n", sep="") } cat(file=con, "\n") } } if(identical(printTo, FALSE)) { close(con) value <- readLines(tmp) unlink(tmp) value } } promptMethods <- function(f, filename = NULL, methods) { ## Generate information in the style of 'prompt' for the methods of ## the generic named 'f'. ## ## 'filename' can be a logical or NA or the name of a file to print ## to. If it 'FALSE', the methods skeleton is returned, to be ## included in other printing (typically, the output from 'prompt'). escape <- function(txt) gsub("%", "\\\\%", txt) packageString <- "" fdef <- getGeneric(f) if(!isGeneric(f, fdef=fdef)) stop(gettextf("no generic function found corresponding to %s", sQuote(f)), domain = NA) if(missing(methods)) { methods <- findMethods(fdef) ## try making packageString where <- .genEnv(fdef, topenv(parent.frame())) if(!identical(where, .GlobalEnv)) packageString <- sprintf("in Package \\pkg{%s}", getPackageName(where)) } fullName <- utils:::topicName("methods", f) n <- length(methods) labels <- character(n) aliases <- character(n) signatures <- findMethodSignatures(methods = methods, target=TRUE) args <- colnames(signatures) # the *same* for all for(i in seq_len(n)) { sigi <- signatures[i, ] labels[[i]] <- sprintf("\\code{signature(%s)}", paste(sprintf("%s = \"%s\"", args, escape(sigi)), collapse = ", ")) aliases[[i]] <- paste0("\\alias{", utils:::topicName("method", c(f, signatures[i,])), "}") } text <- paste0("\n\\item{", labels, "}{\n%% ~~describe this method here~~\n}") text <- c("\\section{Methods}{\n\\describe{", text, "}}") aliasText <- c(paste0("\\alias{", escape(fullName), "}"), escape(aliases)) if(identical(filename, FALSE)) return(c(aliasText, text)) if(is.null(filename) || identical(filename, TRUE)) filename <- paste0(fullName, ".Rd") Rdtxt <- list(name = paste0("\\name{", fullName, "}"), type = "\\docType{methods}", aliases = aliasText, ## <FIXME> ## Title and description are ok as auto-generated: should ## they be flagged as such (via '~~' which are quite often ## left in by authors)? title = sprintf("\\title{ ~~ Methods for Function \\code{%s} %s ~~}", f, packageString), description = paste0("\\description{\n ~~ Methods for function", " \\code{", f, "} ", sub("^in Package", "in package", packageString), " ~~\n}"), ## </FIXME> "section{Methods}" = text, keywords = c("\\keyword{methods}", "\\keyword{ ~~ other possible keyword(s) ~~ }")) if(is.na(filename)) return(Rdtxt) cat(unlist(Rdtxt), file = filename, sep = "\n") .message("A shell of methods documentation has been written", .fileDesc(filename), ".\n") invisible(filename) } ##' only called from showMlist() above, which has been deprecated in R 3.2.0 (Apr.2015): linearizeMlist <- ## Undo the recursive nature of the methods list, making a list of ## function definitions, with the names of the list being the ## corresponding signatures (designed for printing; for looping over ## the methods, use `listFromMlist' instead). ## ## The function calls itself recursively. `prev' is the previously ## selected class names. ## ## If argument `classes' is provided, only signatures containing one ## of these classes will be included. function(mlist, inherited = TRUE) { methods <- mlist@methods allMethods <- mlist@allMethods if(inherited && length(allMethods) >= length(methods)) { ## anames <- names(allMethods) ## inh <- is.na(match(anames, names(methods))) methods <- allMethods } preC <- function(y, x)c(x,y) # used with lapply below cnames <- names(methods) value <- list() classes <- list() arguments <- list() argname <- as.character(mlist@argument) for(i in seq_along(cnames)) { mi <- methods[[i]] if(is.function(mi)) { value <- c(value, list(mi)) classes <- c(classes, list(cnames[[i]])) arguments <- c(arguments, list(argname)) } else if(is(mi, "MethodsList")) { .MlistDeprecated() mi <- Recall(mi, inherited) value <- c(value, mi@methods) classes <- c(classes, lapply(mi@classes, preC, cnames[[i]])) arguments <- c(arguments, lapply(mi@arguments, preC, argname)) } else warning(gettextf("skipping methods list element %s of unexpected class %s\n\n", paste(cnames[i], collapse = ", "), dQuote(.class1(mi))), domain = NA) } new("LinearMethodsList", methods = value, classes = classes, arguments = arguments) } print.MethodsList <- function(x, ...) showMlist(x) ## In R's own code, this is *only* used in mergeMethods(), deprecated in R 3.2.0 (Apr.2015) listFromMlist <- ## linearizes the MethodsList object into list(sigs, methods); `prefix' is the partial ## signature (a named list of classes) to be prepended to the signatures in this object. ## ## A utility function used to iterate over all the individual methods in the object. function(mlist, prefix = list(), sigs. = TRUE, methods. = TRUE) { methodSlot <- slot(mlist, "methods") mnames <- names(methodSlot) argName <- as.character(slot(mlist, "argument")) sigs <- list() methods <- list() for(i in seq_along(methodSlot)) { thisMethod <- methodSlot[i] thisClass <- mnames[[i]] prefix[[argName]] <- thisClass if(is.function(thisMethod)) { if(sigs.) sigs <- c(sigs, list(prefix)) if(methods.) methods <- c(methods, list(thisMethod)) } else { more <- Recall(thisMethod, prefix) if(sigs.) sigs <- c(sigs, more[[1]]) if(methods.) methods <- c(methods, more[[2]]) } } list(sigs, methods) } .insertCachedMethods <- function(mlist, argName, Class, fromClass, def) { if(is(def, "MethodsList")) { .MlistDeprecated() ## insert all the cached methods in def newArg <- c(argName, as.character(def@argument)) newDefs <- def@allMethods newSigs <- as.list(names(newDefs)) for(j in seq_along(newDefs)) mlist <- Recall(mlist, newArg, c(Class, newSigs[[j]]), fromClass, newDefs[[j]]) } else { def <- .addMethodFrom(def, argName[1L], Class[1L], fromClass) mlist <- insertMethod(mlist, Class, argName, def, TRUE) } mlist } .addMethodFrom <- function(def, arg, Class, fromClass) { if(is(def, "MethodDefinition")) { ## eventually, we may enforce method definition objects ## If not, just leave raw functions alone (NextMethod won't work) def@target[[arg]] <- Class def@defined[[arg]] <- fromClass } def } ## Define a trivial version of asMethodDefinition for bootstrapping. ## The real version requires several class definitions as well as ## methods for as<- asMethodDefinition <- function(def, signature = list(.anyClassName), sealed = FALSE, fdef = def) { if(is.primitive(def) || is(def, "MethodDefinition")) def else { value = new("MethodDefinition") value@.Data <- def classes <- .MakeSignature(new("signature"), def, signature, fdef) value@target <- classes value@defined <- classes value } } .trimMlist <- function(mlist, fromClass) { mlist@methods <- mlist@methods[fromClass] mlist@allMethods <- mlist@allMethods[fromClass] mlist } .noMlistsFlag <- TRUE .noMlists <- function() { ## if this were to be dynamically variable, but ## it can't, IMO ## identical(getOption("noMlists"), TRUE) ## so instead .noMlistsFlag } .MlistDepTable <- new.env() .MlistDeprecated <- function(this = "<default>", instead) { if(is.character(this)) { if(exists(this, envir = .MlistDepTable, inherits = FALSE)) return() else assign(this, TRUE, envir = .MlistDepTable) } msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is deprecated." else if(is.character(this)) gettextf( "%s, along with other use of the \"MethodsList\" metadata objects, is deprecated.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is deprecated.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList. (This warning is shown once per session.)") base::.Deprecated(msg = msg) } .MlistDefunct <- function(this = "<default>", instead) { msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is defunct." else if(is.character(this)) gettextf("%s, along with other use of the \"MethodsList\" metadata objects, is defunct.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is defunct.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList.") base::.Defunct(msg = msg) }
36,574
gpl-2.0
71c4978aaa94135074227729a1d4da375593bdd9
Mouseomics/R
src/library/methods/R/MethodsList.R
# File src/library/methods/R/MethodsList.R # Part of the R package, https://www.R-project.org # # Copyright (C) 1995-2016 The R Core Team # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # A copy of the GNU General Public License is available at # https://www.R-project.org/Licenses/ MethodsList <- ## Create a MethodsList object out of the arguments. ## ## Conceptually, this object is a named collection of methods to be ## dispatched when the (first) argument in a function call matches the ## class corresponding to one of the names. A final, unnamed element ## (i.e., with name `""') corresponds to the default method. ## ## The elements can be either a function, or another MethodsList. In ## the second case, this list implies dispatching on the second ## argument to the function using that list, given a selection of this ## element on the first argument. Thus, method dispatching on an ## arbitrary number of arguments is defined. ## ## MethodsList objects are used primarily to dispatch OOP-style ## methods and, in R, to emulate S4-style methods. function(.ArgName, ...) { .MlistDeprecated("MethodsList()") value <- makeMethodsList(list(...)) if(is.name(.ArgName)){} else if(is.character(.ArgName) && length(.ArgName) == 1) .ArgName <- as.name(.ArgName) else stop("invalid first argument: should be the name of the first argument in the dispatch") slot(value, "argument") <- .ArgName value } makeMethodsList <- function(object, level=1) { .MlistDeprecated("makeMethodsList()") mnames <- allNames(object) if(.noMlists()) { keep <- mnames %in% c("", "ANY") mnames <- mnames[keep] object <- object[keep] } value <- new("MethodsList") i <- match("", mnames) if(!is.na(i)) { ## convert to ANY mnames[[i]] <- "ANY" names(object) <- mnames } if(anyDuplicated(mnames)) stop(gettextf("duplicate element names in 'MethodsList' at level %d: %s", level, paste("\"", unique(mnames[duplicated(mnames)]), "\"", collapse=", ")), domain = NA) for(i in seq_along(object)) { eli <- object[[i]] if(is(eli, "function") || is(eli, "MethodsList")) {} else if(is(eli, "list") || is(eli, "named")) object[[i]] <- Recall(eli, NULL, level+1) else stop(gettextf("element %d at level %d (class %s) cannot be interpreted as a function or named list", i, level, dQuote(class(eli))), domain = NA) } slot(value, "methods") <- object value } SignatureMethod <- ## construct a MethodsList object containing (only) this method, corresponding ## to the signature; i.e., such that signature[[1L]] is the match for the first ## argument, signature[[2L]] for the second argument, and so on. The string ## "missing" means a match for a missing argument, and "ANY" means use this as the ## default setting at this level. ## ## The first argument is the argument names to be used for dispatch corresponding to ## the signatures. function(names, signature, definition) { .MlistDeprecated("SignatureMethod()") n <- length(signature) if(n > length(names)) stop("arguments 'names' and 'signature' must have the same length") if(n == 0) return(definition) Class <- signature[[n]] name <- names[[n]] m <- MethodsList(name) slot(m, "methods")[[Class]] <- definition slot(m, "argument") <- as.name(name) SignatureMethod(names[-n], signature[-n], m) } insertMethod <- ## insert the definition `def' into the MethodsList object, `mlist', corresponding to ## the signature, and return the modified MethodsList. function(mlist, signature, args, def, cacheOnly = FALSE) { .MlistDeprecated("insertMethod()") if(.noMlists() && !identical(unique(signature), "ANY")) return(mlist) ## Checks for assertions about valid calls. ## See rev. 1.17 for the code before the assertions added. if(identical(args[1L], "...") && !identical(names(signature), "...")) { if(identical(signature[[1L]], "ANY")) stop(gettextf("inserting method with invalid signature matching argument '...' to class %s", dQuote(signature[[1L]])), domain = NA) args <- args[-1L] signature <- signature[-1L] if(length(signature) == 0L) return(mlist) } if(length(signature) == 0L) stop("inserting method corresponding to empty signature") if(!is(mlist, "MethodsList")) stop(gettextf("inserting method into non-methods-list object (class %s)", dQuote(.class1(mlist))), domain = NA) if(length(args) > 1 && !cacheOnly) mlist <- balanceMethodsList(mlist, args) Class <- signature[[1]] methods <- if(cacheOnly) mlist@allMethods else mlist@methods current <- methods[[Class]] if(is(current, "MethodsList")) { nextArg <- as.character(current@argument) sigArgs <- args n <- length(signature) length(sigArgs) <- n if(is.na(match(nextArg, sigArgs))) { n <- match(nextArg, args) - n if(is.na(n)) { ## not in args eitiher n <- 1 args <- c(args, nextArg) } ## make explicit the trailing ANY's needed signature <- c(signature, rep("ANY", n)) } } if(length(signature) == 1) { if(is.null(current)) { if(!is.null(def)) methods[[Class]] <- def ## else, no change } else { which <- match(Class, names(methods)) if(is.null(def)) ## delete the method methods <- methods[-which] else methods[[which]] <- def } } else { ## recursively merge, initializing current if necessary if(is.null(current)) current <- new("MethodsList", argument = as.name(args[2L])) else if(is.function(current)) current <- new("MethodsList", argument = as.name(args[2L]), methods = list(ANY = current)) methods[[Class]] <- Recall(current, signature[-1L], args[-1L], def, cacheOnly) } mlist@allMethods <- methods if(!cacheOnly) mlist@methods <- methods mlist } MethodsListSelect <- ## select the element of a MethodsList object corresponding to the ## actual arguments (as defined in the suppled environment), ## and return the object, extended to include that method if necessary. ## ## Works recursively. At each level finds an argument name from the current `mlist' ## object, and evaluates this argument (if it is not missing), then uses the ## class of the result to select an element of `mlist'. If such an element ## exists and is another `MethodsList' object, `MethodsListSelect' calls itself recursively ## to resolve using further arguments. Matching includes using a default selection or ## a method specifically linked to class `"missing"'. Once a function is found, it ## is returned as the value. If matching fails, NULL is returned. function(f, env, mlist = NULL, fEnv = if(is(fdef, "genericFunction")) environment(fdef) else baseenv(), finalDefault = finalDefaultMethod(mlist), evalArgs = TRUE, useInherited = TRUE, ## supplied when evalArgs is FALSE fdef = getGeneric(f, where = env), # MUST BE SAFE FROM RECUSIVE METHOD SELECTION resetAllowed = TRUE # FALSE when called from selectMethod, .findNextMethod ) { .MlistDeprecated("MethodsListSelect()") if(!resetAllowed) # ensure we restore the real methods for this function resetMlist <- .getMethodsForDispatch(fdef) ## look for call from C dispatch code during another call to MethodsListSelect if(is.null(f)) {} # Recall, not from C else { fMethods <- .getMethodsForDispatch(fdef) if(is.null(mlist) || (evalArgs && is.function(fMethods))) mlist <- fMethods } resetNeeded <- .setIfBase(f, fdef, mlist) # quickly protect against recursion -- see Methods.R if(resetNeeded) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } if(!is(mlist, "MethodsList")) { if(is.function(mlist)) # call to f, inside MethodsListSelect {on.exit(); return(mlist)} if(is.null(f)) # recursive recall of MethodsListSelect stop("invalid method sublist") else if(!is.null(mlist)) # NULL => 1st call to genericFunction stop(gettextf("%f is not a valid generic function: methods list was an object of class %s", sQuote(f), dQuote(class(mlist))), domain = NA) } if(!is.logical(useInherited)) stop(gettextf("%s must be TRUE, FALSE, or a named logical vector of those values; got an object of class %s", sQuote("useInherited"), dQuote(class(useInherited))), domain = NA) if(identical(mlist, .getMethodsForDispatch(fdef))) { resetNeeded <- TRUE ## On the initial call: ## turn off any further method dispatch on this function, to avoid recursive ## loops if f is a function used in MethodsListSelect. ## TODO: Using namespaces in the methods package would eliminate the need for this .setMethodsForDispatch(f, fdef, finalDefault) if(is(mlist, "MethodsList")) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } } argName <- slot(mlist, "argument") arg <- NULL ## => don't use instance-specific inheritance if(evalArgs) { ## check for missing argument. NB: S sense, not that of R base missing() if(missingArg(argName, env, TRUE)) thisClass <- "missing" else { arg <- eval(as.name(argName), env) ## DO use instance-specific inheritance if(missing(arg)) ## S3 weird R code? Bail out! return(finalDefault) thisClass <- .class1(arg) } } else thisClass <- get(as.character(argName), envir = env, inherits = FALSE) if(identical(useInherited, TRUE) || identical(useInherited, FALSE)) thisInherit <- nextUseInherited <- useInherited else { which <- match(as.character(argName), names(useInherited)) if(is.na(which)) { nextUseInherited <- useInherited thisInherit <- TRUE } else { thisInherit <- useInherited[[which]] nextUseInherited <- useInherited[-which] } } fromClass <- thisClass ## will mark the class actually providing the method allMethods <- mlist@allMethods which <- match(thisClass, names(allMethods)) inherited <- is.na(which) selection <- if(inherited) NULL else allMethods[[which]] if(!inherited) { if(is(selection, "function")) { if(is.null(f)) { ## An inherited method at the next level up. ## only the inherited method should be added mlist <- .trimMlist(mlist, fromClass) } value <- mlist ## no change } else { ## recursive call with NULL function name, to allow search to fail & ## to suppress any reset actions. method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef, ) if(is(method, "EmptyMethodsList")) value <- method else { mlist@allMethods[[which]] <- method value <- mlist } } } if(inherited || is(value, "EmptyMethodsList")) { ## direct selection failed at this level or below method <- NULL if(thisInherit) { allSelections <- inheritedSubMethodLists(arg, fromClass, mlist, env) allClasses <- names(allSelections) for(i in seq_along(allSelections)) { selection <- allSelections[[i]] fromClass <- allClasses[[i]] if(is(selection, "function")) method <- selection else if(is(selection, "MethodsList")) { ## go on to try matching further arguments method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef) if(is(method, "EmptyMethodsList")) selection <- method ## recursive selection failed } if(!is(selection, "EmptyMethodsList")) break } } if((is.null(selection) || is(selection, "EmptyMethodsList")) && !is.null(f) && !is.null(finalDefault)) { ## only use the final default method after exhausting all ## other possibilities, at all levels. method <- finalDefault fromClass <- "ANY" } if(is.null(method) || is(method, "EmptyMethodsList")) value <- emptyMethodsList(mlist, thisClass) ## nothing found else { method <- MethodAddCoerce(method, argName, thisClass, fromClass) value <- .insertCachedMethods(mlist, as.character(argName), thisClass, fromClass, method) } } if(!is.null(f)) { ## top level if(is(value, "EmptyMethodsList")) ## selection failed value <- NULL if(resetNeeded) { on.exit() # cancel the restore of the original mlist if(resetAllowed) { if(is.null(value)) resetMlist <- mlist else resetMlist <- value } .setMethodsForDispatch(f, fdef, resetMlist) if(dispatchIsInternal(fdef)) setPrimitiveMethods(f, finalDefault, "set", fdef, resetMlist) } } value } emptyMethodsList <- function(mlist, thisClass = "ANY", sublist = list()) { .MlistDeprecated("emptyMethodsList()") sublist[thisClass] <- list(NULL) new("EmptyMethodsList", argument = mlist@argument, sublist = sublist) } insertMethodInEmptyList <- function(mlist, def) { .MlistDeprecated("insertMethodInEmptyList()") value <- new("MethodsList", argument = mlist@argument) sublist <- mlist@sublist submethods <- sublist[[1L]] if(is.null(submethods)) sublist[[1L]] <- def else sublist[[1L]] <- Recall(submethods, def) value@allMethods <- sublist value } finalDefaultMethod <- ## Return the default method from the generic (it may be NULL, a method object or a primitive. ## this previously searched in a MethodsList object. Once those are gone, the loop should ## be irrelevant except as an error check. function(method) { repeat { if(is.function(method) # <- somewhat liberal, but catches both methods and primitives || is.null(method)) break if(is(method, "MethodsList")) { .MlistDeprecated() method <- slot(method, "methods")[["ANY"]] } else stop(gettextf( "default method must be a method definition, a primitive or NULL: got an object of class %s", dQuote(class(method))), domain = NA) } method } inheritedSubMethodLists <- ## Utility function to match the object to the elements of a methods list. ## ## The function looks only for an inherited match, and only among ## the methods that are not themselves inherited. (Inherited methods when found are ## stored in the session copy of the methods list, but they themselves should not be ## used for finding inherited matches, because an erroneous match could be found depending ## on which methods were previously used. See the detailed discussion of methods.) function(object, thisClass, mlist, ev) { .MlistDeprecated("inheritedSubMethodLists()") methods <- slot(mlist, "methods")## only direct methods defaultMethod <- methods[["ANY"]]## maybe NULL classes <- names(methods) value <- list() if(.identC(thisClass, "missing")) { ## no superclasses for "missing" } else { ## search in the superclasses, but don't use inherited methods ## There are two cases: if thisClass is formally defined & unsealed, use its ## superclasses. Otherwise, look in the subclasses of those classes for ## which methods exist. classDef <- getClassDef(thisClass, ev) useSuperClasses <- !is.null(classDef) && !classDef@sealed if(useSuperClasses) { ## for consistency, order the available methods by ## the ordering of the superclasses of thisClass superClasses <- names(classDef@contains) classes <- superClasses[!is.na(match(superClasses, classes))] for(which in seq_along(classes)) { tryClass <- classes[[which]] ## TODO: There is potential bug here: If the is relation is conditional, ## we should not cache this selection. Needs another trick in the environment ## to FORCE no caching regardless of what happens elsewhere; e.g., storing a ## special object in .Class if(is.null(object) || is(object, tryClass)) { value[[tryClass]] <- methods[[tryClass]] } } } else { for(which in seq_along(classes)) { tryClass <- classes[[which]] tryClassDef <- getClassDef(tryClass, ev) if(!is.null(tryClassDef) && !is.na(match(thisClass, names(tryClassDef@subclasses)))) value[[tryClass]] <- methods[[which]] } } } if(!is.null(defaultMethod)) value[["ANY"]] <- defaultMethod value } matchSignature <- ## Match the signature object (a partially or completely named subset of the ## arguments of `fun', and return a vector of all the classes in the order specified ## by the signature slot of the generic. The classes not specified by `signature ##' will be `"ANY"' in the value. function(signature, fun, where = baseenv()) { if(!is(fun, "genericFunction")) stop(gettextf("trying to match a method signature to an object (of class %s) that is not a generic function", dQuote(class(fun))), domain = NA) anames <- fun@signature if(length(signature) == 0L) return(character()) if(is(signature,"character")) { pkgs <- packageSlot(signature) # includes case of "ObjectsWithPackage" if(is.null(pkgs)) pkgs <- character(length(signature)) else if(length(pkgs) != length(signature)) stop("invalid 'package' slot or attribute, wrong length") sigClasses <- as.character(signature) } else if(is(signature, "list")) { sigClasses <- pkgs <- character(length(signature)) for(i in seq_along(signature)) { cli <- signature[[i]] if(is(cli, "classRepresentation")) { sigClasses[[i]] <- cli@className pkgs[[i]] <- cli@package } else if(is(cli, "character") && length(cli) == 1) { sigClasses[[i]] <- cli pkgi <- packageSlot(cli) if(is.character(pkgi)) pkgs[[i]] <- pkgi } else stop(gettextf("invalid element in a list for \"signature\" argument; element %d is neither a class definition nor a class name", i), domain = NA) } } else stop(gettextf("trying to match a method signature of class %s; expects a list or a character vector", dQuote(class(signature))), domain = NA) if(!identical(where, baseenv())) { ## fill in package information, warn about undefined classes unknown <- !nzchar(pkgs) for(i in seq_along(sigClasses)[unknown]) { cli <- getClassDef(sigClasses[[i]], where) if(!is.null(cli)) { pkgs[[i]] <- cli@package unknown[[i]] <- FALSE } } if(any(unknown)) { unknown <- unique(sigClasses[unknown]) ## coerce(), i.e., setAs() may use *one* unknown class MSG <- if(identical(as.vector(coerce@generic), "coerce") && length(unknown) == 1) message else function(...) warning(..., call. = FALSE) MSG(.renderSignature(fun@generic, signature), sprintf(ngettext(length(unknown), "no definition for class %s", "no definition for classes %s"), paste(dQuote(unknown), collapse = ", ")), domain = NA) } } signature <- as.list(signature) if(length(sigClasses) != length(signature)) stop(gettextf("object to use as a method signature for function %s does not look like a legitimate signature (a vector of single class names): there were %d class names, but %d elements in the signature object", sQuote(fun@generic), length(sigClasses), length(signature)), domain = NA) if(is.null(names(signature))) { which <- seq_along(signature) if(length(which) > length(anames)) stop(gettextf("more elements in the method signature (%d) than in the generic signature (%d) for function %s", length(which), length(anames), sQuote(fun@generic)), domain = NA) } else { ## construct a function call with the same naming pattern & ## values as signature sigList <- signature for(i in seq_along(sigList)) sigList[[i]] <- c(sigClasses[[i]], pkgs[[i]]) fcall <- do.call("call", c("fun", sigList)) ## match the call to the formal signature (usually the formal args) if(identical(anames, formalArgs(fun))) smatch <- match.call(fun, fcall) else { fmatch <- fun ff <- as.list(anames); names(ff) <- anames formals(fmatch, envir = environment(fun)) <- ff smatch <- match.call(fmatch, fcall) } snames <- names(smatch)[-1L] which <- match(snames, anames) ## Assertion: match.call has permuted the args into the order of formal args, ## and carried along the values. Get the supplied classes in that ## order, from the matched args in the call object. if(anyNA(which)) stop(sprintf(ngettext(sum(is.na(which)), "in the method signature for function %s invalid argument name in the signature: %s", "in the method signature for function %s invalid argument names in the signature: %s"), sQuote(fun@generic), paste(snames[is.na(which)], collapse = ", ")), domain = NA) smatch <- smatch[-1] for(i in seq_along(smatch)) { eli <- smatch[[i]] sigClasses[[i]] <- eli[[1]] pkgs[[i]] <- eli[[2]] } } n <- length(anames) value <- rep("ANY", n) valueP <- rep("methods", n) names(value) <- anames value[which] <- sigClasses valueP[which] <- pkgs unspec <- value == "ANY" ## remove the trailing unspecified classes while(n > 1 && unspec[[n]]) n <- n-1 length(value) <- length(valueP) <- n attr(value, "package") <- valueP ## <FIXME> Is there a reason (bootstrapping?) why this ## is not an actual object from class "signature"? ## See .MakeSignature() </FIXME> value } showMlist <- ## Prints the contents of the MethodsList. If `includeDefs' the signatures and the ## corresponding definitions will be printed; otherwise, only the signatures. ## ## If `includeDefs' is `TRUE', the currently known inherited methods are included; ## otherwise, only the directly defined methods. function(mlist, includeDefs = TRUE, inherited = TRUE, classes = NULL, useArgNames = TRUE, printTo = stdout()) { .MlistDeprecated("showMlist()") if(identical(printTo, FALSE)) { tmp <- tempfile() con <- file(tmp, "w") } else con <- printTo object <- linearizeMlist(mlist, inherited) methods <- object@methods signatures <- object@classes args <- object@arguments if(!is.null(classes) && length(signatures)>0) { keep <- !vapply(signatures, function(x, y) all(is.na(match(x, y))), NA, classes) methods <- methods[keep] signatures <- signatures[keep] args <- args[keep] } if(length(methods) == 0) cat(file=con, "<Empty Methods List>\n") else { n <- length(methods) labels <- character(n) if(useArgNames) { for(i in 1L:n) { sigi <- signatures[[i]] labels[[i]] <- paste(args[[i]], " = \"", sigi, "\"", sep = "", collapse = ", ") } } else { for(i in 1L:n) labels[[i]] <- paste(signatures[[i]], collapse = ", ") } for(i in seq_along(methods)) { cat(file=con, (if(includeDefs) "## Signature:" else ""), labels[[i]]) method <- methods[[i]] if(includeDefs) { cat(file=con, ":\n") if(is(method, "MethodDefinition")) ## really an assertion cat(file=con, deparse(method@.Data), sep="\n") else cat(file=con, deparse(method), sep="\n") } if(is(method, "MethodDefinition") && !identical(method@target, method@defined)) { defFrom <- method@defined cat(file = con, if(includeDefs) "##:" else "\n", " (inherited from ", paste(names(defFrom), " = \"", as.character(defFrom), "\"", sep = "", collapse = ", "), ")", if(includeDefs) "\n", sep="") } cat(file=con, "\n") } } if(identical(printTo, FALSE)) { close(con) value <- readLines(tmp) unlink(tmp) value } } promptMethods <- function(f, filename = NULL, methods) { ## Generate information in the style of 'prompt' for the methods of ## the generic named 'f'. ## ## 'filename' can be a logical or NA or the name of a file to print ## to. If it 'FALSE', the methods skeleton is returned, to be ## included in other printing (typically, the output from 'prompt'). escape <- function(txt) gsub("%", "\\\\%", txt) packageString <- "" fdef <- getGeneric(f) if(!isGeneric(f, fdef=fdef)) stop(gettextf("no generic function found corresponding to %s", sQuote(f)), domain = NA) if(missing(methods)) { methods <- findMethods(fdef) ## try making packageString where <- .genEnv(fdef, topenv(parent.frame())) if(!identical(where, .GlobalEnv)) packageString <- sprintf("in Package \\pkg{%s}", getPackageName(where)) } fullName <- utils:::topicName("methods", f) n <- length(methods) labels <- character(n) aliases <- character(n) signatures <- findMethodSignatures(methods = methods, target=TRUE) args <- colnames(signatures) # the *same* for all for(i in seq_len(n)) { sigi <- signatures[i, ] labels[[i]] <- sprintf("\\code{signature(%s)}", paste(sprintf("%s = \"%s\"", args, escape(sigi)), collapse = ", ")) aliases[[i]] <- paste0("\\alias{", utils:::topicName("method", c(f, signatures[i,])), "}") } text <- paste0("\n\\item{", labels, "}{\n%% ~~describe this method here~~\n}") text <- c("\\section{Methods}{\n\\describe{", text, "}}") aliasText <- c(paste0("\\alias{", escape(fullName), "}"), escape(aliases)) if(identical(filename, FALSE)) return(c(aliasText, text)) if(is.null(filename) || identical(filename, TRUE)) filename <- paste0(fullName, ".Rd") Rdtxt <- list(name = paste0("\\name{", fullName, "}"), type = "\\docType{methods}", aliases = aliasText, ## <FIXME> ## Title and description are ok as auto-generated: should ## they be flagged as such (via '~~' which are quite often ## left in by authors)? title = sprintf("\\title{ ~~ Methods for Function \\code{%s} %s ~~}", f, packageString), description = paste0("\\description{\n ~~ Methods for function", " \\code{", f, "} ", sub("^in Package", "in package", packageString), " ~~\n}"), ## </FIXME> "section{Methods}" = text, keywords = c("\\keyword{methods}", "\\keyword{ ~~ other possible keyword(s) ~~ }")) if(is.na(filename)) return(Rdtxt) cat(unlist(Rdtxt), file = filename, sep = "\n") .message("A shell of methods documentation has been written", .fileDesc(filename), ".\n") invisible(filename) } ##' only called from showMlist() above, which has been deprecated in R 3.2.0 (Apr.2015): linearizeMlist <- ## Undo the recursive nature of the methods list, making a list of ## function definitions, with the names of the list being the ## corresponding signatures (designed for printing; for looping over ## the methods, use `listFromMlist' instead). ## ## The function calls itself recursively. `prev' is the previously ## selected class names. ## ## If argument `classes' is provided, only signatures containing one ## of these classes will be included. function(mlist, inherited = TRUE) { methods <- mlist@methods allMethods <- mlist@allMethods if(inherited && length(allMethods) >= length(methods)) { ## anames <- names(allMethods) ## inh <- is.na(match(anames, names(methods))) methods <- allMethods } preC <- function(y, x)c(x,y) # used with lapply below cnames <- names(methods) value <- list() classes <- list() arguments <- list() argname <- as.character(mlist@argument) for(i in seq_along(cnames)) { mi <- methods[[i]] if(is.function(mi)) { value <- c(value, list(mi)) classes <- c(classes, list(cnames[[i]])) arguments <- c(arguments, list(argname)) } else if(is(mi, "MethodsList")) { .MlistDeprecated() mi <- Recall(mi, inherited) value <- c(value, mi@methods) classes <- c(classes, lapply(mi@classes, preC, cnames[[i]])) arguments <- c(arguments, lapply(mi@arguments, preC, argname)) } else warning(gettextf("skipping methods list element %s of unexpected class %s\n\n", paste(cnames[i], collapse = ", "), dQuote(.class1(mi))), domain = NA) } new("LinearMethodsList", methods = value, classes = classes, arguments = arguments) } print.MethodsList <- function(x, ...) showMlist(x) ## In R's own code, this is *only* used in mergeMethods(), deprecated in R 3.2.0 (Apr.2015) listFromMlist <- ## linearizes the MethodsList object into list(sigs, methods); `prefix' is the partial ## signature (a named list of classes) to be prepended to the signatures in this object. ## ## A utility function used to iterate over all the individual methods in the object. function(mlist, prefix = list(), sigs. = TRUE, methods. = TRUE) { methodSlot <- slot(mlist, "methods") mnames <- names(methodSlot) argName <- as.character(slot(mlist, "argument")) sigs <- list() methods <- list() for(i in seq_along(methodSlot)) { thisMethod <- methodSlot[i] thisClass <- mnames[[i]] prefix[[argName]] <- thisClass if(is.function(thisMethod)) { if(sigs.) sigs <- c(sigs, list(prefix)) if(methods.) methods <- c(methods, list(thisMethod)) } else { more <- Recall(thisMethod, prefix) if(sigs.) sigs <- c(sigs, more[[1]]) if(methods.) methods <- c(methods, more[[2]]) } } list(sigs, methods) } .insertCachedMethods <- function(mlist, argName, Class, fromClass, def) { if(is(def, "MethodsList")) { .MlistDeprecated() ## insert all the cached methods in def newArg <- c(argName, as.character(def@argument)) newDefs <- def@allMethods newSigs <- as.list(names(newDefs)) for(j in seq_along(newDefs)) mlist <- Recall(mlist, newArg, c(Class, newSigs[[j]]), fromClass, newDefs[[j]]) } else { def <- .addMethodFrom(def, argName[1L], Class[1L], fromClass) mlist <- insertMethod(mlist, Class, argName, def, TRUE) } mlist } .addMethodFrom <- function(def, arg, Class, fromClass) { if(is(def, "MethodDefinition")) { ## eventually, we may enforce method definition objects ## If not, just leave raw functions alone (NextMethod won't work) def@target[[arg]] <- Class def@defined[[arg]] <- fromClass } def } ## Define a trivial version of asMethodDefinition for bootstrapping. ## The real version requires several class definitions as well as ## methods for as<- asMethodDefinition <- function(def, signature = list(.anyClassName), sealed = FALSE, fdef = def) { if(is.primitive(def) || is(def, "MethodDefinition")) def else { value = new("MethodDefinition") value@.Data <- def classes <- .MakeSignature(new("signature"), def, signature, fdef) value@target <- classes value@defined <- classes value } } .trimMlist <- function(mlist, fromClass) { mlist@methods <- mlist@methods[fromClass] mlist@allMethods <- mlist@allMethods[fromClass] mlist } .noMlistsFlag <- TRUE .noMlists <- function() { ## if this were to be dynamically variable, but ## it can't, IMO ## identical(getOption("noMlists"), TRUE) ## so instead .noMlistsFlag } .MlistDepTable <- new.env() .MlistDeprecated <- function(this = "<default>", instead) { if(is.character(this)) { if(exists(this, envir = .MlistDepTable, inherits = FALSE)) return() else assign(this, TRUE, envir = .MlistDepTable) } msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is deprecated." else if(is.character(this)) gettextf( "%s, along with other use of the \"MethodsList\" metadata objects, is deprecated.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is deprecated.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList. (This warning is shown once per session.)") base::.Deprecated(msg = msg) } .MlistDefunct <- function(this = "<default>", instead) { msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is defunct." else if(is.character(this)) gettextf("%s, along with other use of the \"MethodsList\" metadata objects, is defunct.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is defunct.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList.") base::.Defunct(msg = msg) }
36,574
gpl-2.0
71c4978aaa94135074227729a1d4da375593bdd9
cxxr-devel/cxxr
src/library/methods/R/MethodsList.R
# File src/library/methods/R/MethodsList.R # Part of the R package, https://www.R-project.org # # Copyright (C) 1995-2016 The R Core Team # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # A copy of the GNU General Public License is available at # https://www.R-project.org/Licenses/ MethodsList <- ## Create a MethodsList object out of the arguments. ## ## Conceptually, this object is a named collection of methods to be ## dispatched when the (first) argument in a function call matches the ## class corresponding to one of the names. A final, unnamed element ## (i.e., with name `""') corresponds to the default method. ## ## The elements can be either a function, or another MethodsList. In ## the second case, this list implies dispatching on the second ## argument to the function using that list, given a selection of this ## element on the first argument. Thus, method dispatching on an ## arbitrary number of arguments is defined. ## ## MethodsList objects are used primarily to dispatch OOP-style ## methods and, in R, to emulate S4-style methods. function(.ArgName, ...) { .MlistDeprecated("MethodsList()") value <- makeMethodsList(list(...)) if(is.name(.ArgName)){} else if(is.character(.ArgName) && length(.ArgName) == 1) .ArgName <- as.name(.ArgName) else stop("invalid first argument: should be the name of the first argument in the dispatch") slot(value, "argument") <- .ArgName value } makeMethodsList <- function(object, level=1) { .MlistDeprecated("makeMethodsList()") mnames <- allNames(object) if(.noMlists()) { keep <- mnames %in% c("", "ANY") mnames <- mnames[keep] object <- object[keep] } value <- new("MethodsList") i <- match("", mnames) if(!is.na(i)) { ## convert to ANY mnames[[i]] <- "ANY" names(object) <- mnames } if(anyDuplicated(mnames)) stop(gettextf("duplicate element names in 'MethodsList' at level %d: %s", level, paste("\"", unique(mnames[duplicated(mnames)]), "\"", collapse=", ")), domain = NA) for(i in seq_along(object)) { eli <- object[[i]] if(is(eli, "function") || is(eli, "MethodsList")) {} else if(is(eli, "list") || is(eli, "named")) object[[i]] <- Recall(eli, NULL, level+1) else stop(gettextf("element %d at level %d (class %s) cannot be interpreted as a function or named list", i, level, dQuote(class(eli))), domain = NA) } slot(value, "methods") <- object value } SignatureMethod <- ## construct a MethodsList object containing (only) this method, corresponding ## to the signature; i.e., such that signature[[1L]] is the match for the first ## argument, signature[[2L]] for the second argument, and so on. The string ## "missing" means a match for a missing argument, and "ANY" means use this as the ## default setting at this level. ## ## The first argument is the argument names to be used for dispatch corresponding to ## the signatures. function(names, signature, definition) { .MlistDeprecated("SignatureMethod()") n <- length(signature) if(n > length(names)) stop("arguments 'names' and 'signature' must have the same length") if(n == 0) return(definition) Class <- signature[[n]] name <- names[[n]] m <- MethodsList(name) slot(m, "methods")[[Class]] <- definition slot(m, "argument") <- as.name(name) SignatureMethod(names[-n], signature[-n], m) } insertMethod <- ## insert the definition `def' into the MethodsList object, `mlist', corresponding to ## the signature, and return the modified MethodsList. function(mlist, signature, args, def, cacheOnly = FALSE) { .MlistDeprecated("insertMethod()") if(.noMlists() && !identical(unique(signature), "ANY")) return(mlist) ## Checks for assertions about valid calls. ## See rev. 1.17 for the code before the assertions added. if(identical(args[1L], "...") && !identical(names(signature), "...")) { if(identical(signature[[1L]], "ANY")) stop(gettextf("inserting method with invalid signature matching argument '...' to class %s", dQuote(signature[[1L]])), domain = NA) args <- args[-1L] signature <- signature[-1L] if(length(signature) == 0L) return(mlist) } if(length(signature) == 0L) stop("inserting method corresponding to empty signature") if(!is(mlist, "MethodsList")) stop(gettextf("inserting method into non-methods-list object (class %s)", dQuote(.class1(mlist))), domain = NA) if(length(args) > 1 && !cacheOnly) mlist <- balanceMethodsList(mlist, args) Class <- signature[[1]] methods <- if(cacheOnly) mlist@allMethods else mlist@methods current <- methods[[Class]] if(is(current, "MethodsList")) { nextArg <- as.character(current@argument) sigArgs <- args n <- length(signature) length(sigArgs) <- n if(is.na(match(nextArg, sigArgs))) { n <- match(nextArg, args) - n if(is.na(n)) { ## not in args eitiher n <- 1 args <- c(args, nextArg) } ## make explicit the trailing ANY's needed signature <- c(signature, rep("ANY", n)) } } if(length(signature) == 1) { if(is.null(current)) { if(!is.null(def)) methods[[Class]] <- def ## else, no change } else { which <- match(Class, names(methods)) if(is.null(def)) ## delete the method methods <- methods[-which] else methods[[which]] <- def } } else { ## recursively merge, initializing current if necessary if(is.null(current)) current <- new("MethodsList", argument = as.name(args[2L])) else if(is.function(current)) current <- new("MethodsList", argument = as.name(args[2L]), methods = list(ANY = current)) methods[[Class]] <- Recall(current, signature[-1L], args[-1L], def, cacheOnly) } mlist@allMethods <- methods if(!cacheOnly) mlist@methods <- methods mlist } MethodsListSelect <- ## select the element of a MethodsList object corresponding to the ## actual arguments (as defined in the suppled environment), ## and return the object, extended to include that method if necessary. ## ## Works recursively. At each level finds an argument name from the current `mlist' ## object, and evaluates this argument (if it is not missing), then uses the ## class of the result to select an element of `mlist'. If such an element ## exists and is another `MethodsList' object, `MethodsListSelect' calls itself recursively ## to resolve using further arguments. Matching includes using a default selection or ## a method specifically linked to class `"missing"'. Once a function is found, it ## is returned as the value. If matching fails, NULL is returned. function(f, env, mlist = NULL, fEnv = if(is(fdef, "genericFunction")) environment(fdef) else baseenv(), finalDefault = finalDefaultMethod(mlist), evalArgs = TRUE, useInherited = TRUE, ## supplied when evalArgs is FALSE fdef = getGeneric(f, where = env), # MUST BE SAFE FROM RECUSIVE METHOD SELECTION resetAllowed = TRUE # FALSE when called from selectMethod, .findNextMethod ) { .MlistDeprecated("MethodsListSelect()") if(!resetAllowed) # ensure we restore the real methods for this function resetMlist <- .getMethodsForDispatch(fdef) ## look for call from C dispatch code during another call to MethodsListSelect if(is.null(f)) {} # Recall, not from C else { fMethods <- .getMethodsForDispatch(fdef) if(is.null(mlist) || (evalArgs && is.function(fMethods))) mlist <- fMethods } resetNeeded <- .setIfBase(f, fdef, mlist) # quickly protect against recursion -- see Methods.R if(resetNeeded) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } if(!is(mlist, "MethodsList")) { if(is.function(mlist)) # call to f, inside MethodsListSelect {on.exit(); return(mlist)} if(is.null(f)) # recursive recall of MethodsListSelect stop("invalid method sublist") else if(!is.null(mlist)) # NULL => 1st call to genericFunction stop(gettextf("%f is not a valid generic function: methods list was an object of class %s", sQuote(f), dQuote(class(mlist))), domain = NA) } if(!is.logical(useInherited)) stop(gettextf("%s must be TRUE, FALSE, or a named logical vector of those values; got an object of class %s", sQuote("useInherited"), dQuote(class(useInherited))), domain = NA) if(identical(mlist, .getMethodsForDispatch(fdef))) { resetNeeded <- TRUE ## On the initial call: ## turn off any further method dispatch on this function, to avoid recursive ## loops if f is a function used in MethodsListSelect. ## TODO: Using namespaces in the methods package would eliminate the need for this .setMethodsForDispatch(f, fdef, finalDefault) if(is(mlist, "MethodsList")) { on.exit(.setMethodsForDispatch(f, fdef, mlist)) } } argName <- slot(mlist, "argument") arg <- NULL ## => don't use instance-specific inheritance if(evalArgs) { ## check for missing argument. NB: S sense, not that of R base missing() if(missingArg(argName, env, TRUE)) thisClass <- "missing" else { arg <- eval(as.name(argName), env) ## DO use instance-specific inheritance if(missing(arg)) ## S3 weird R code? Bail out! return(finalDefault) thisClass <- .class1(arg) } } else thisClass <- get(as.character(argName), envir = env, inherits = FALSE) if(identical(useInherited, TRUE) || identical(useInherited, FALSE)) thisInherit <- nextUseInherited <- useInherited else { which <- match(as.character(argName), names(useInherited)) if(is.na(which)) { nextUseInherited <- useInherited thisInherit <- TRUE } else { thisInherit <- useInherited[[which]] nextUseInherited <- useInherited[-which] } } fromClass <- thisClass ## will mark the class actually providing the method allMethods <- mlist@allMethods which <- match(thisClass, names(allMethods)) inherited <- is.na(which) selection <- if(inherited) NULL else allMethods[[which]] if(!inherited) { if(is(selection, "function")) { if(is.null(f)) { ## An inherited method at the next level up. ## only the inherited method should be added mlist <- .trimMlist(mlist, fromClass) } value <- mlist ## no change } else { ## recursive call with NULL function name, to allow search to fail & ## to suppress any reset actions. method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef, ) if(is(method, "EmptyMethodsList")) value <- method else { mlist@allMethods[[which]] <- method value <- mlist } } } if(inherited || is(value, "EmptyMethodsList")) { ## direct selection failed at this level or below method <- NULL if(thisInherit) { allSelections <- inheritedSubMethodLists(arg, fromClass, mlist, env) allClasses <- names(allSelections) for(i in seq_along(allSelections)) { selection <- allSelections[[i]] fromClass <- allClasses[[i]] if(is(selection, "function")) method <- selection else if(is(selection, "MethodsList")) { ## go on to try matching further arguments method <- Recall(NULL, env, selection, finalDefault = finalDefault, evalArgs = evalArgs, useInherited = nextUseInherited, fdef = fdef) if(is(method, "EmptyMethodsList")) selection <- method ## recursive selection failed } if(!is(selection, "EmptyMethodsList")) break } } if((is.null(selection) || is(selection, "EmptyMethodsList")) && !is.null(f) && !is.null(finalDefault)) { ## only use the final default method after exhausting all ## other possibilities, at all levels. method <- finalDefault fromClass <- "ANY" } if(is.null(method) || is(method, "EmptyMethodsList")) value <- emptyMethodsList(mlist, thisClass) ## nothing found else { method <- MethodAddCoerce(method, argName, thisClass, fromClass) value <- .insertCachedMethods(mlist, as.character(argName), thisClass, fromClass, method) } } if(!is.null(f)) { ## top level if(is(value, "EmptyMethodsList")) ## selection failed value <- NULL if(resetNeeded) { on.exit() # cancel the restore of the original mlist if(resetAllowed) { if(is.null(value)) resetMlist <- mlist else resetMlist <- value } .setMethodsForDispatch(f, fdef, resetMlist) if(dispatchIsInternal(fdef)) setPrimitiveMethods(f, finalDefault, "set", fdef, resetMlist) } } value } emptyMethodsList <- function(mlist, thisClass = "ANY", sublist = list()) { .MlistDeprecated("emptyMethodsList()") sublist[thisClass] <- list(NULL) new("EmptyMethodsList", argument = mlist@argument, sublist = sublist) } insertMethodInEmptyList <- function(mlist, def) { .MlistDeprecated("insertMethodInEmptyList()") value <- new("MethodsList", argument = mlist@argument) sublist <- mlist@sublist submethods <- sublist[[1L]] if(is.null(submethods)) sublist[[1L]] <- def else sublist[[1L]] <- Recall(submethods, def) value@allMethods <- sublist value } finalDefaultMethod <- ## Return the default method from the generic (it may be NULL, a method object or a primitive. ## this previously searched in a MethodsList object. Once those are gone, the loop should ## be irrelevant except as an error check. function(method) { repeat { if(is.function(method) # <- somewhat liberal, but catches both methods and primitives || is.null(method)) break if(is(method, "MethodsList")) { .MlistDeprecated() method <- slot(method, "methods")[["ANY"]] } else stop(gettextf( "default method must be a method definition, a primitive or NULL: got an object of class %s", dQuote(class(method))), domain = NA) } method } inheritedSubMethodLists <- ## Utility function to match the object to the elements of a methods list. ## ## The function looks only for an inherited match, and only among ## the methods that are not themselves inherited. (Inherited methods when found are ## stored in the session copy of the methods list, but they themselves should not be ## used for finding inherited matches, because an erroneous match could be found depending ## on which methods were previously used. See the detailed discussion of methods.) function(object, thisClass, mlist, ev) { .MlistDeprecated("inheritedSubMethodLists()") methods <- slot(mlist, "methods")## only direct methods defaultMethod <- methods[["ANY"]]## maybe NULL classes <- names(methods) value <- list() if(.identC(thisClass, "missing")) { ## no superclasses for "missing" } else { ## search in the superclasses, but don't use inherited methods ## There are two cases: if thisClass is formally defined & unsealed, use its ## superclasses. Otherwise, look in the subclasses of those classes for ## which methods exist. classDef <- getClassDef(thisClass, ev) useSuperClasses <- !is.null(classDef) && !classDef@sealed if(useSuperClasses) { ## for consistency, order the available methods by ## the ordering of the superclasses of thisClass superClasses <- names(classDef@contains) classes <- superClasses[!is.na(match(superClasses, classes))] for(which in seq_along(classes)) { tryClass <- classes[[which]] ## TODO: There is potential bug here: If the is relation is conditional, ## we should not cache this selection. Needs another trick in the environment ## to FORCE no caching regardless of what happens elsewhere; e.g., storing a ## special object in .Class if(is.null(object) || is(object, tryClass)) { value[[tryClass]] <- methods[[tryClass]] } } } else { for(which in seq_along(classes)) { tryClass <- classes[[which]] tryClassDef <- getClassDef(tryClass, ev) if(!is.null(tryClassDef) && !is.na(match(thisClass, names(tryClassDef@subclasses)))) value[[tryClass]] <- methods[[which]] } } } if(!is.null(defaultMethod)) value[["ANY"]] <- defaultMethod value } matchSignature <- ## Match the signature object (a partially or completely named subset of the ## arguments of `fun', and return a vector of all the classes in the order specified ## by the signature slot of the generic. The classes not specified by `signature ##' will be `"ANY"' in the value. function(signature, fun, where = baseenv()) { if(!is(fun, "genericFunction")) stop(gettextf("trying to match a method signature to an object (of class %s) that is not a generic function", dQuote(class(fun))), domain = NA) anames <- fun@signature if(length(signature) == 0L) return(character()) if(is(signature,"character")) { pkgs <- packageSlot(signature) # includes case of "ObjectsWithPackage" if(is.null(pkgs)) pkgs <- character(length(signature)) else if(length(pkgs) != length(signature)) stop("invalid 'package' slot or attribute, wrong length") sigClasses <- as.character(signature) } else if(is(signature, "list")) { sigClasses <- pkgs <- character(length(signature)) for(i in seq_along(signature)) { cli <- signature[[i]] if(is(cli, "classRepresentation")) { sigClasses[[i]] <- cli@className pkgs[[i]] <- cli@package } else if(is(cli, "character") && length(cli) == 1) { sigClasses[[i]] <- cli pkgi <- packageSlot(cli) if(is.character(pkgi)) pkgs[[i]] <- pkgi } else stop(gettextf("invalid element in a list for \"signature\" argument; element %d is neither a class definition nor a class name", i), domain = NA) } } else stop(gettextf("trying to match a method signature of class %s; expects a list or a character vector", dQuote(class(signature))), domain = NA) if(!identical(where, baseenv())) { ## fill in package information, warn about undefined classes unknown <- !nzchar(pkgs) for(i in seq_along(sigClasses)[unknown]) { cli <- getClassDef(sigClasses[[i]], where) if(!is.null(cli)) { pkgs[[i]] <- cli@package unknown[[i]] <- FALSE } } if(any(unknown)) { unknown <- unique(sigClasses[unknown]) ## coerce(), i.e., setAs() may use *one* unknown class MSG <- if(identical(as.vector(coerce@generic), "coerce") && length(unknown) == 1) message else function(...) warning(..., call. = FALSE) MSG(.renderSignature(fun@generic, signature), sprintf(ngettext(length(unknown), "no definition for class %s", "no definition for classes %s"), paste(dQuote(unknown), collapse = ", ")), domain = NA) } } signature <- as.list(signature) if(length(sigClasses) != length(signature)) stop(gettextf("object to use as a method signature for function %s does not look like a legitimate signature (a vector of single class names): there were %d class names, but %d elements in the signature object", sQuote(fun@generic), length(sigClasses), length(signature)), domain = NA) if(is.null(names(signature))) { which <- seq_along(signature) if(length(which) > length(anames)) stop(gettextf("more elements in the method signature (%d) than in the generic signature (%d) for function %s", length(which), length(anames), sQuote(fun@generic)), domain = NA) } else { ## construct a function call with the same naming pattern & ## values as signature sigList <- signature for(i in seq_along(sigList)) sigList[[i]] <- c(sigClasses[[i]], pkgs[[i]]) fcall <- do.call("call", c("fun", sigList)) ## match the call to the formal signature (usually the formal args) if(identical(anames, formalArgs(fun))) smatch <- match.call(fun, fcall) else { fmatch <- fun ff <- as.list(anames); names(ff) <- anames formals(fmatch, envir = environment(fun)) <- ff smatch <- match.call(fmatch, fcall) } snames <- names(smatch)[-1L] which <- match(snames, anames) ## Assertion: match.call has permuted the args into the order of formal args, ## and carried along the values. Get the supplied classes in that ## order, from the matched args in the call object. if(anyNA(which)) stop(sprintf(ngettext(sum(is.na(which)), "in the method signature for function %s invalid argument name in the signature: %s", "in the method signature for function %s invalid argument names in the signature: %s"), sQuote(fun@generic), paste(snames[is.na(which)], collapse = ", ")), domain = NA) smatch <- smatch[-1] for(i in seq_along(smatch)) { eli <- smatch[[i]] sigClasses[[i]] <- eli[[1]] pkgs[[i]] <- eli[[2]] } } n <- length(anames) value <- rep("ANY", n) valueP <- rep("methods", n) names(value) <- anames value[which] <- sigClasses valueP[which] <- pkgs unspec <- value == "ANY" ## remove the trailing unspecified classes while(n > 1 && unspec[[n]]) n <- n-1 length(value) <- length(valueP) <- n attr(value, "package") <- valueP ## <FIXME> Is there a reason (bootstrapping?) why this ## is not an actual object from class "signature"? ## See .MakeSignature() </FIXME> value } showMlist <- ## Prints the contents of the MethodsList. If `includeDefs' the signatures and the ## corresponding definitions will be printed; otherwise, only the signatures. ## ## If `includeDefs' is `TRUE', the currently known inherited methods are included; ## otherwise, only the directly defined methods. function(mlist, includeDefs = TRUE, inherited = TRUE, classes = NULL, useArgNames = TRUE, printTo = stdout()) { .MlistDeprecated("showMlist()") if(identical(printTo, FALSE)) { tmp <- tempfile() con <- file(tmp, "w") } else con <- printTo object <- linearizeMlist(mlist, inherited) methods <- object@methods signatures <- object@classes args <- object@arguments if(!is.null(classes) && length(signatures)>0) { keep <- !vapply(signatures, function(x, y) all(is.na(match(x, y))), NA, classes) methods <- methods[keep] signatures <- signatures[keep] args <- args[keep] } if(length(methods) == 0) cat(file=con, "<Empty Methods List>\n") else { n <- length(methods) labels <- character(n) if(useArgNames) { for(i in 1L:n) { sigi <- signatures[[i]] labels[[i]] <- paste(args[[i]], " = \"", sigi, "\"", sep = "", collapse = ", ") } } else { for(i in 1L:n) labels[[i]] <- paste(signatures[[i]], collapse = ", ") } for(i in seq_along(methods)) { cat(file=con, (if(includeDefs) "## Signature:" else ""), labels[[i]]) method <- methods[[i]] if(includeDefs) { cat(file=con, ":\n") if(is(method, "MethodDefinition")) ## really an assertion cat(file=con, deparse(method@.Data), sep="\n") else cat(file=con, deparse(method), sep="\n") } if(is(method, "MethodDefinition") && !identical(method@target, method@defined)) { defFrom <- method@defined cat(file = con, if(includeDefs) "##:" else "\n", " (inherited from ", paste(names(defFrom), " = \"", as.character(defFrom), "\"", sep = "", collapse = ", "), ")", if(includeDefs) "\n", sep="") } cat(file=con, "\n") } } if(identical(printTo, FALSE)) { close(con) value <- readLines(tmp) unlink(tmp) value } } promptMethods <- function(f, filename = NULL, methods) { ## Generate information in the style of 'prompt' for the methods of ## the generic named 'f'. ## ## 'filename' can be a logical or NA or the name of a file to print ## to. If it 'FALSE', the methods skeleton is returned, to be ## included in other printing (typically, the output from 'prompt'). escape <- function(txt) gsub("%", "\\\\%", txt) packageString <- "" fdef <- getGeneric(f) if(!isGeneric(f, fdef=fdef)) stop(gettextf("no generic function found corresponding to %s", sQuote(f)), domain = NA) if(missing(methods)) { methods <- findMethods(fdef) ## try making packageString where <- .genEnv(fdef, topenv(parent.frame())) if(!identical(where, .GlobalEnv)) packageString <- sprintf("in Package \\pkg{%s}", getPackageName(where)) } fullName <- utils:::topicName("methods", f) n <- length(methods) labels <- character(n) aliases <- character(n) signatures <- findMethodSignatures(methods = methods, target=TRUE) args <- colnames(signatures) # the *same* for all for(i in seq_len(n)) { sigi <- signatures[i, ] labels[[i]] <- sprintf("\\code{signature(%s)}", paste(sprintf("%s = \"%s\"", args, escape(sigi)), collapse = ", ")) aliases[[i]] <- paste0("\\alias{", utils:::topicName("method", c(f, signatures[i,])), "}") } text <- paste0("\n\\item{", labels, "}{\n%% ~~describe this method here~~\n}") text <- c("\\section{Methods}{\n\\describe{", text, "}}") aliasText <- c(paste0("\\alias{", escape(fullName), "}"), escape(aliases)) if(identical(filename, FALSE)) return(c(aliasText, text)) if(is.null(filename) || identical(filename, TRUE)) filename <- paste0(fullName, ".Rd") Rdtxt <- list(name = paste0("\\name{", fullName, "}"), type = "\\docType{methods}", aliases = aliasText, ## <FIXME> ## Title and description are ok as auto-generated: should ## they be flagged as such (via '~~' which are quite often ## left in by authors)? title = sprintf("\\title{ ~~ Methods for Function \\code{%s} %s ~~}", f, packageString), description = paste0("\\description{\n ~~ Methods for function", " \\code{", f, "} ", sub("^in Package", "in package", packageString), " ~~\n}"), ## </FIXME> "section{Methods}" = text, keywords = c("\\keyword{methods}", "\\keyword{ ~~ other possible keyword(s) ~~ }")) if(is.na(filename)) return(Rdtxt) cat(unlist(Rdtxt), file = filename, sep = "\n") .message("A shell of methods documentation has been written", .fileDesc(filename), ".\n") invisible(filename) } ##' only called from showMlist() above, which has been deprecated in R 3.2.0 (Apr.2015): linearizeMlist <- ## Undo the recursive nature of the methods list, making a list of ## function definitions, with the names of the list being the ## corresponding signatures (designed for printing; for looping over ## the methods, use `listFromMlist' instead). ## ## The function calls itself recursively. `prev' is the previously ## selected class names. ## ## If argument `classes' is provided, only signatures containing one ## of these classes will be included. function(mlist, inherited = TRUE) { methods <- mlist@methods allMethods <- mlist@allMethods if(inherited && length(allMethods) >= length(methods)) { ## anames <- names(allMethods) ## inh <- is.na(match(anames, names(methods))) methods <- allMethods } preC <- function(y, x)c(x,y) # used with lapply below cnames <- names(methods) value <- list() classes <- list() arguments <- list() argname <- as.character(mlist@argument) for(i in seq_along(cnames)) { mi <- methods[[i]] if(is.function(mi)) { value <- c(value, list(mi)) classes <- c(classes, list(cnames[[i]])) arguments <- c(arguments, list(argname)) } else if(is(mi, "MethodsList")) { .MlistDeprecated() mi <- Recall(mi, inherited) value <- c(value, mi@methods) classes <- c(classes, lapply(mi@classes, preC, cnames[[i]])) arguments <- c(arguments, lapply(mi@arguments, preC, argname)) } else warning(gettextf("skipping methods list element %s of unexpected class %s\n\n", paste(cnames[i], collapse = ", "), dQuote(.class1(mi))), domain = NA) } new("LinearMethodsList", methods = value, classes = classes, arguments = arguments) } print.MethodsList <- function(x, ...) showMlist(x) ## In R's own code, this is *only* used in mergeMethods(), deprecated in R 3.2.0 (Apr.2015) listFromMlist <- ## linearizes the MethodsList object into list(sigs, methods); `prefix' is the partial ## signature (a named list of classes) to be prepended to the signatures in this object. ## ## A utility function used to iterate over all the individual methods in the object. function(mlist, prefix = list(), sigs. = TRUE, methods. = TRUE) { methodSlot <- slot(mlist, "methods") mnames <- names(methodSlot) argName <- as.character(slot(mlist, "argument")) sigs <- list() methods <- list() for(i in seq_along(methodSlot)) { thisMethod <- methodSlot[i] thisClass <- mnames[[i]] prefix[[argName]] <- thisClass if(is.function(thisMethod)) { if(sigs.) sigs <- c(sigs, list(prefix)) if(methods.) methods <- c(methods, list(thisMethod)) } else { more <- Recall(thisMethod, prefix) if(sigs.) sigs <- c(sigs, more[[1]]) if(methods.) methods <- c(methods, more[[2]]) } } list(sigs, methods) } .insertCachedMethods <- function(mlist, argName, Class, fromClass, def) { if(is(def, "MethodsList")) { .MlistDeprecated() ## insert all the cached methods in def newArg <- c(argName, as.character(def@argument)) newDefs <- def@allMethods newSigs <- as.list(names(newDefs)) for(j in seq_along(newDefs)) mlist <- Recall(mlist, newArg, c(Class, newSigs[[j]]), fromClass, newDefs[[j]]) } else { def <- .addMethodFrom(def, argName[1L], Class[1L], fromClass) mlist <- insertMethod(mlist, Class, argName, def, TRUE) } mlist } .addMethodFrom <- function(def, arg, Class, fromClass) { if(is(def, "MethodDefinition")) { ## eventually, we may enforce method definition objects ## If not, just leave raw functions alone (NextMethod won't work) def@target[[arg]] <- Class def@defined[[arg]] <- fromClass } def } ## Define a trivial version of asMethodDefinition for bootstrapping. ## The real version requires several class definitions as well as ## methods for as<- asMethodDefinition <- function(def, signature = list(.anyClassName), sealed = FALSE, fdef = def) { if(is.primitive(def) || is(def, "MethodDefinition")) def else { value = new("MethodDefinition") value@.Data <- def classes <- .MakeSignature(new("signature"), def, signature, fdef) value@target <- classes value@defined <- classes value } } .trimMlist <- function(mlist, fromClass) { mlist@methods <- mlist@methods[fromClass] mlist@allMethods <- mlist@allMethods[fromClass] mlist } .noMlistsFlag <- TRUE .noMlists <- function() { ## if this were to be dynamically variable, but ## it can't, IMO ## identical(getOption("noMlists"), TRUE) ## so instead .noMlistsFlag } .MlistDepTable <- new.env() .MlistDeprecated <- function(this = "<default>", instead) { if(is.character(this)) { if(exists(this, envir = .MlistDepTable, inherits = FALSE)) return() else assign(this, TRUE, envir = .MlistDepTable) } msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is deprecated." else if(is.character(this)) gettextf( "%s, along with other use of the \"MethodsList\" metadata objects, is deprecated.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is deprecated.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList. (This warning is shown once per session.)") base::.Deprecated(msg = msg) } .MlistDefunct <- function(this = "<default>", instead) { msg <- if(missing(this)) "Use of the \"MethodsList\" meta data objects is defunct." else if(is.character(this)) gettextf("%s, along with other use of the \"MethodsList\" metadata objects, is defunct.", dQuote(this)) else gettextf("in %s: use of \"MethodsList\" metadata objects is defunct.", deparse(this)) if(!missing(instead)) msg <- paste(msg, gettextf("use %s instead.", dQuote(instead))) msg <- paste(msg, "see ?MethodsList.") base::.Defunct(msg = msg) }
36,574
gpl-2.0
8298e1ad0077132f653ef643f8a30877fe2cb5fe
DavidNovo/ExplorationsWithR
directoryManipulationAndReadingCSV.R
getwd() setwd("C:/Users/ahall/Documents/GitHub/ExplorationsWithR") reddit <- read.csv('reddit.csv') table(reddit$employment.status) ''' Employed full time Freelance 14814 1948 Not employed and not looking for work Not employed, but looking for work 682 2087 Retired Student 85 12987' levels(reddit$age.range) ''' [1] "18-24" "25-34" "35-44" "45-54" "55-64" "65 or Above" "Under 18" ' levels(reddit$employment.status) ''' [1] "Employed full time" "Freelance" [3] "Not employed and not looking for work" "Not employed, but looking for work" [5] "Retired" "Student" ' ''' installing better graphic package ' install.packages('ggplot2', dependencies = T) library(ggplot2) qplot(data=reddit, x= age.range)
1,142
apache-2.0
ba2b5389d065f40ced7fe778a7c2469363030c62
sebastianueckert/mirt
R/mirt.model.R
#' Specify model information #' #' The \code{mirt.model} function scans/reads user input to specify the #' confirmatory model. Item locations must be used in the specifications if no #' \code{itemnames} argument is supplied. This is called implicitly by estimation functions #' when a string is passed to the \code{model} argument. #' #' Factors are first named and then specify which numerical items they affect #' (i.e., where the slope is not equal to 0), separated either by commas or by #' - to indicate a range of items. Products between factors may be specified #' by enclosing the left hand term within brackets. To finish the declaration of #' a model simply enter a blank line with only a carriage return (i.e., the #' 'enter' or 'return' key), or instead read in an input version of the model syntax. #' The associated slopes throughout the package label these coefficients as #' \code{a1, a2, ..., ak}, where the associated number is assigned according to the #' respective order of the defined factors. #' #' For example, if the syntax were #' #' \code{"G = 1-10 #' F = 1-5 #' A = 6-10"} #' #' then the \code{G} factor would be assigned the slopes \code{a1} for each item, \code{F} assigned #' the slopes \code{a2}, and \code{A} assigned the slopes \code{a3}. The same principle applies to the #' \code{\link{bfactor}} function whereby the slopes are automatically included for the specific factors #' after the general factor structure has been assigned. #' #' There is an optional keyword for specifying the correlation between relationships between factors #' called \code{COV}, and non-linear factor products can be included by enclosing the product #' combination on the left hand side of the declaration (e.g., \code{(F1*F1)} would create a #' quadratic factor for \code{F1}). #' #' The keywords \code{CONSTRAIN, CONSTRAINB, PRIOR, FIXED, FREE, START, UBOUND, LBOUND} can #' be applied to specific sub-groups in multiple-group models by included square brackets before the #' = sign, where groups are separated by commas. For example, to apply within-group equality #' constraints to a group called "male", then specifying: #' #' \code{CONSTRAIN [male] = (1-5, a1)} #' #' is appropriate, while specifying the same constraints to the sub-groups #' "male" and "female" would appear as #' #' \code{CONSTRAIN [male, female] = (1-5, a1)} #' #' For all other groups in the multi-group model, these within-group equality constraints would not appear. Therefore, these #' bracketed group specifications are useful when modifying priors, starting values, between/within group equality constraints, #' and so on when the specifications for each sub-group may differ. #' #' Finally, the keyword \code{GROUP} can be used to specify the group-level #' hyper-parameter terms, such as the means and variance of the default Gaussian #' distribution. For example, to set the starting value of the variance #' parameter (\code{COV_11}) to 1.5: #' #' \code{START = (GROUP, COV_11, 1.5)} #' #' \describe{ #' \item{COV}{Specify the relationship between the latent factors. #' Estimating a correlation between factors is declared by joining the two #' factors with an asterisk (e.g., F1*F2), or with an asterisk between three or more factors #' to estimate all the possible correlations (e.g., F1*F2*F3)} #' #' \item{MEAN}{A comma separated list specifying which latent factor means to freely estimate. #' E.g., \code{MEAN = F1, F2} will free the latent means for factors F1 and F2} #' #' \item{CONSTRAIN}{A bracketed, comma separated list specifying equality constrains between items. #' The input format is #' \code{CONSTRAIN = (items, ..., parameterName(s)), #' (items, ..., parameterName)}. #' #' For example, in a single group 10-item dichotomous tests, using the default 2PL model, #' the first and last 5 item slopes (a1) can be constrained to be equal by using #' \code{CONSTRAIN = (1-5, a1), (6-10, a1)}, or some combination #' such as \code{CONSTRAIN = (1-3,4,5,a1), (6,7,8-10,a1)}. #' #' When constraining parameters to be equal across items with different parameter names, a #' balanced bracketed vector must be supplied. E.g., setting the first slope for item 1 equal to #' the second slope in item 3 would be \code{CONSTRAIN = (1, 3, a1, a2)} #' } #' #' \item{CONSTRAINB}{A bracketed, comma separate list specifying equality constrains between groups. #' The input format is \code{CONSTRAINB = (items, ..., parameterName), #' (items, ..., parameterName)}. #' #' For example, in a two group 10-item dichotomous tests, using the default 2PL model, the first #' 5 item slopes (a1) can be constrained to be equal across both groups by using #' \code{CONSTRAINB = (1-5, a1)}, or some combination such as \code{CONSTRAINB = (1-3,4,5,a1)}} #' #' \item{PRIOR}{A bracketed, comma separate list specifying prior parameter distributions. #' The input format is #' \code{PRIOR = (items, ..., parameterName, priorType, val1, val2), #' (items, ..., parameterName, priorType, val1, val2)}. #' For example, in a single group 10-item dichotomous tests, using the default 2PL model, #' defining a normal prior of N(0,2) for the first 5 item intercepts (d) can be defined by #' \code{PRIOR = (1-5, d, norm, 0, 2)} #' #' Currently supported priors are of the form: \code{(items, norm, mean, sd)} #' for the normal/Gaussian, \code{(items, lnorm, log_mean, log_sd)} for log-normal, #' \code{(items, beta, alpha, beta)} for beta, and \code{(items, expbeta, alpha, beta)} #' for the beta distribution after applying the #' function \code{\link{plogis}} to the input value (note, this is specifically for applying a beta #' prior to the lower-bound parameters in 3/4PL models)} #' #' \item{LBOUND}{A bracketed, comma separate list specifying lower bounds for estimated #' parameters (used in optimizers such as \code{L-BFGS-B} and \code{nlminb}). #' The input format is \code{LBOUND = (items, ..., parameterName, value), #' (items, ..., parameterName, value)}. #' #' For example, in a single group 10-item dichotomous tests, using the 3PL model and #' setting lower bounds for the 'g' parameters for the first 5 items to 0.2 is accomplished with #' \code{LBOUND = (1-5, g, 0.2)}} #' #' \item{UBOUND}{same as LBOUND, but specifying upper bounds in estimated parameters} #' #' \item{START}{A bracketed, comma separate list specifying the starting values for individual parameters. #' The input is of the form \code{(items, ..., parameterName, value)}. For instance, setting the 10th and #' 12th to 15th item slope parameters (a1) to 1.0 is specified with \code{START = (10, 12-15, a1, 1.0)} #' #' For more hands on control of the starting values pass the argument \code{pars = 'values'} through #' whatever estimation function is being used} #' #' \item{FIXED}{A bracketed, comma separate list specifying which parameters should be fixed at their #' starting values (i.e., not freely estimated). #' The input is of the form \code{(items, ..., parameterName)}. For instance, fixing the 10th and #' 12th to 15th item slope parameters (a1) is accomplished with \code{FIXED = (10, 12-15, a1)} #' #' For more hands on control of the estimated values pass the argument \code{pars = 'values'} through #' whatever estimation function is being used} #' #' \item{FREE}{Equivalent to the \code{FIXED} input, except that parameters are freely estimated instead #' of fixed at their starting value} #' #' \item{NEXPLORE}{Number of exploratory factors to extract. Usually this is not required #' because passing a numeric value to the \code{model} argument in the estimation function #' will generate an exploratory factor analysis model, however if different start values, #' priors, lower and upper bounds, etc, are desired then this input can be used} #' #' } #' #' @param input input for writing out the model syntax. Can either be a string declaration of #' class character or the so-called Q-matrix or class \code{matrix} that specifies the model #' either with integer or logical values. If the Q-matrix method #' is chosen covariances terms can be specified with the \code{COV} input #' @param itemnames a character vector or factor indicating the item names. If a data.frame or #' matrix object is supplied the names will be extracted using \code{colnames(itemnames)}. #' Supplying this input allows the syntax to be specified with the raw item names rather than #' item locations #' @param file a input specifying an external file that declares the input. #' @param COV a symmetric, logical matrix used to declare which covariance terms are estimated #' @param quiet logical argument passed to \code{scan()} to suppress console read message #' @param ... additional arguments for \code{scan()} #' @return Returns a model specification object to be used in #' \code{\link{mirt}}, \code{\link{bfactor}}, \code{\link{multipleGroup}}, or #' \code{\link{mixedmirt}} #' @author Phil Chalmers \email{rphilip.chalmers@@gmail.com} and Alexander Robitzsch #' @references #' Chalmers, R., P. (2012). mirt: A Multidimensional Item Response Theory #' Package for the R Environment. \emph{Journal of Statistical Software, 48}(6), 1-29. #' \doi{10.18637/jss.v048.i06} #' @export mirt.model #' @examples #' #' \dontrun{ #' #' # interactively through the console (not run) #' #model <- mirt.model() #' # F1 = 1,2,3,4-10 #' # F2 = 10-20 #' # (F1*F2) = 1,2,3,4-10 #' # COV = F1*F2 #' #' #' #Or alternatively with a string input #' s <- 'F1 = 1,2,3,4-10 #' F2 = 10-20 #' (F1*F2) = 1,2,3,4-10 #' COV = F1*F2' #' model <- mirt.model(s) #' #' # strings can also be passed to the estimation functions directly, #' # which silently calls mirt.model(). E.g., using the string above: #' # mod <- mirt(data, s) #' #' #' #Q-matrix specification #' Q <- matrix(c(1,1,1,0,0,0,0,0,0,1,1,1), ncol=2, dimnames = list(NULL, c('Factor1', 'Factor2'))) #' COV <- matrix(c(FALSE, TRUE, TRUE, FALSE), 2) #' model <- mirt.model(Q, COV=COV) #' #' ## constrain various items slopes and all intercepts in single group model to be equal, #' # and use a log-normal prior for all the slopes #' s <- 'F = 1-10 #' CONSTRAIN = (1-3, 5, 6, a1), (1-10, d) #' PRIOR = (1-10, a1, lnorm, .2, .2)' #' model <- mirt.model(s) #' #' #' ## constrain various items slopes and intercepts across groups for use in multipleGroup(), #' # and constrain first two slopes within 'group1' to be equal #' s <- 'F = 1-10 #' CONSTRAIN = (1-2, a1) #' CONSTRAINB = (1-3, 5, 6, a1), (1-10, d)' #' model <- mirt.model(s) #' #' #' ## specify model using raw item names #' data(data.read, package = 'sirt') #' dat <- data.read #' #' # syntax with variable names #' mirtsyn2 <- " #' F1 = A1,B2,B3,C4 #' F2 = A1-A4,C2,C4 #' MEAN = F1 #' COV = F1*F1, F1*F2 #' CONSTRAIN=(A2-A4,a2),(A3,C2,d) #' PRIOR = (C3,A2-A4,a2,lnorm, .2, .2),(B3,d,norm,0,.0001)" #' # create a mirt model #' mirtmodel <- mirt.model(mirtsyn2, itemnames=dat) #' # or equivalently: #' # mirtmodel <- mirt.model(mirtsyn2, itemnames=colnames(dat)) #' #' # mod <- mirt(dat , mirtmodel) #' #' } mirt.model <- function(input = NULL, itemnames = NULL, file = "", COV = NULL, quiet = TRUE, ...) { # split_syn_string vectorized input split_syn_string_vec <- function( syn, vecstr ){ for (vv in vecstr){ syn <- split_syn_string( syn , vv ) } return(syn) } # cleans syntax in a vector from strings vv split_syn_string <- function( syn , vv ){ syn <- as.list(syn ) syn.vv <- grep( vv , syn ) LL <- length(syn.vv) if (LL>0){ for (ii in 1:LL){ ll <- syn.vv[ii] syn.ll <- syn[[ll]] syn[[ll]] <- split_conc( syn.ll , vv ) } } syn <- unlist(syn) return(syn) } # splits a string syn.ll and concatanates it with string vv split_conc <- function( syn.ll , vv ){ g1 <- strsplit( syn.ll , vv , perl=FALSE )[[1]] Lg1 <- length(g1) vec <- NULL if (Lg1 == 1 ){ vec <- c( g1 , vv ) } if (Lg1 > 1 ){ vec <- rep("" , Lg1 + (Lg1-1) ) vec[ seq( 1 , 2*Lg1 , 2 ) ] <- g1 vec[ seq( 2 , 2*Lg1 - 1 , 2 ) ] <- vv Ls1 <- nchar(syn.ll) if ( substring( syn.ll , Ls1 , Ls1 ) == vv ){ vec <- c( vec , vv ) } } return(vec) } remove_temp <- FALSE if(!is.null(itemnames)){ # the following block of code and above functions were largely contributed by Alexander # mirt syntax splitted inputsyntax <- input mirtsyn2 <- gsub( ";" , "\n" , input ) msyn0 <- strsplit( mirtsyn2 , c(" ") )[[1]] syn <- msyn0 if (is.matrix(itemnames) || is.data.frame(itemnames)){ items <- colnames(itemnames) } else items <- as.character(itemnames) tmpmod <- mirt.model(input) if(any(tmpmod$x[,1] %in% itemnames)) stop('Keywords and latent trait/class names must differ from colnames(data)', call.=FALSE) # admissible strings vecstr <- c( "\n" , "\\(" , "=" , "-" , "," , "\\)" ) # process syntax for (vv in vecstr){ syn <- split_syn_string( syn , vv ) } # postprocess syntax syn <- syn[ syn != "" ] syn[ syn == "\\(" ] <- "(" syn[ syn == "\\)" ] <- ")" # substitute variables by numbers VV <- length(items) useditems <- NULL for (vv in 1:VV){ ind <- which( syn == items[vv] ) if (length(ind) > 0 ){ syn[ ind ] <- vv useditems <- c( useditems , items[vv] ) } } syn <- paste0( syn , collapse="") mirtmodel <- mirt.model(syn) attr(mirtmodel, 'item_syntax') <- inputsyntax return(mirtmodel) } else { if(is.matrix(input)){ fnames <- colnames(input) if(is.null(fnames)) fnames <- paste0('F', 1:ncol(input)) string <- c() vals <- 1:nrow(input) input <- matrix(as.logical(input), nrow(input), ncol(input)) for(i in seq_len(ncol(input))){ tmp <- vals[input[,i]] if(length(tmp) > 1L){ string <- c(string, paste(c(fnames[i], ' = ', paste0(tmp[-length(tmp)], ','), tmp[length(tmp)], '\n'), collapse='')) } else { string <- c(string, paste(c(fnames[i], ' = ', tmp[length(tmp)], '\n'), collapse='')) } } if(!is.null(COV) && any(COV)){ tmp <- outer(fnames, fnames, FUN=function(x, y) paste0(x, paste0('*', y))) sel <- upper.tri(COV,TRUE) & COV tmp <- tmp[sel] if(length(tmp) > 1L){ string <- c(string, paste(c('COV = ', paste0(tmp[-length(tmp)], ','), tmp[length(tmp)], '\n'), collapse='')) } else { string <- c(string, paste(c('COV = ', tmp[length(tmp)], '\n'), collapse='')) } } input <- paste(string, collapse='') } if(!is.null(input)){ minput <- strsplit(input, '\\n') for(j in length(minput[[1L]]):1L){ if(!grepl(pattern='=', minput[[1L]][j])){ minput[[1L]][j-1L] <- paste(minput[[1L]][j-1L], minput[[1L]][j]) minput[[1L]] <- minput[[1L]][-j] } } file <- tempfile() remove_temp <- TRUE write.table(minput, file=file, row.names=FALSE, col.names=FALSE, quote=FALSE) } mod <- scan(file = file, what = list(type = "", pars = ""), sep = "=", strip.white = TRUE, comment.char = "#", fill = TRUE, quiet=quiet, ...) mod$pars <- gsub(' ', '', mod$pars) if(remove_temp) unlink(file) mod <- cbind(mod$type, mod$pars) colnames(mod) <- c("Type","Parameters") mod <- list(x = mod) class(mod) <- 'mirt.model' return(mod) } }
16,350
gpl-2.0
1219c5b3244a8546d7af5890cbfc19e8cd1969e9
cran/Zelig
tests/testthat/test-zelig.R
#### Integration tests for the Zelig estimate, set, sim, plot workflow #### # FAIL TEST sim workflow ------------------------------------------------------- test_that('FAIL TEST sim method warning if insufficient inputs', { z5 <- zls$new() expect_output(z5$zelig(Fertility ~ Education, model="ls", data = swiss), 'Argument model is only valid for the Zelig wrapper, but not the Zelig method, and will be ignored.') expect_warning(z5$sim(), 'No simulations drawn, likely due to insufficient inputs.') expect_error(z5$graph(), 'No simulated quantities of interest found.') }) # FAIL TEST ci.plot range > length = 1 ----------------------------------------- test_that('FAIL TEST ci.plot range > length = 1', { z <- zls$new() z$zelig(Fertility ~ Education, data = swiss) expect_warning(z$setrange(Education = 5), 'Only one fitted observation provided to setrange.\nConsider using setx instead.') z$sim() expect_error(z$graph(), 'Simulations for more than one fitted observation are required.') expect_warning(z$setrange1(Education = 5), 'Only one fitted observation provided to setrange.\nConsider using setx instead.') expect_error(z$graph(), 'Simulations for more than one fitted observation are required.') }) # REQUIRE TEST for by estimation workflow -------------------------------------- test_that('REQUIRE TEST for by estimation workflow', { # Majority Catholic dummy swiss$maj_catholic <- cut(swiss$Catholic, breaks = c(0, 51, 100)) z5 <- zls$new() z5$zelig(Fertility ~ Education, data = swiss, by = 'maj_catholic') z5$setrange(Education = 5:15) z5$sim() expect_error(z5$graph(), NA) }) # FAIL TEST for get_qi when applied to an object with no simulations ------------ test_that('FAIL TEST for get_qi when applied to an object with no simulations', { z <- zls$new() z$zelig(Fertility ~ Education, data = swiss) expect_error(z$get_qi(), 'No simulated quantities of interest found.') }) # FAIL TEST for get_qi when unsupported qi supplied ---------------------------- test_that('FAIL TEST for get_qi when unsupported qi supplied', { z5 <- zls$new() z5$zelig(Fertility ~ Education, data = swiss) z5$setrange(Education = 5:15) z5$sim() expect_error(z5$get_qi(qi = "fa", xvalue = "range"), 'qi must be ev or pv.') }) # FAIL TEST for estimation model failure --------------------------------------- test_that('FAIL TEST for estimation model failure', { no_vary_df <- data.frame(y = rep(1, 10), x = rep(2, 10)) z <- zarima$new() expect_error(z$zelig(y ~ x, data = no_vary_df), 'Dependent variable does not vary for at least one of the cases.') expect_error(summary(z), 'Zelig model has not been estimated.') }) # REQUIRE TEST for sim num argument -------------------------------------------- test_that('REQUIRE TEST for sim num argument', { z5 <- zls$new() z5$zelig(Fertility ~ Education, data = swiss) z5$setx(Education = 5) z5$sim() expect_equal(length(z5$get_qi()), 1000) z5$sim(num = 10) # Look into unexpected behaviour if sim order is reversed expect_equal(length(z5$get_qi()), 10) }) # REQUIRE TEST from_zelig_model returns expected fitted model object ----------------- test_that('REQUIRE TEST from_zelig_model returns expected fitted model object', { z5 <- zls$new() z5$zelig(Fertility ~ Education, data = swiss) model_object <- z5$from_zelig_model() expect_is(model_object, class = 'lm') expect_equal(as.character(model_object$call[1]), 'lm') }) # REQUIRE TEST from_zelig_model returns each fitted model object from mi ------------- test_that('REQUIRE TEST from_zelig_model returns each fitted model object from mi', { set.seed(123) n <- 100 x1 <- runif(n) x2 <- runif(n) y <- rnorm(n) data.1 <- data.frame(y = y, x = x1) data.2 <- data.frame(y = y, x = x2) mi.out <- to_zelig_mi(data.1, data.2) z.out <- zelig(y ~ x, model = "ls", data = mi.out) model_list <- z.out$from_zelig_model() expect_is(model_list, class = 'list') expect_equal(as.character(model_list[[2]]$call[1]), 'lm') }) # REQUIRE TEST functioning simparam with by and ATT ---------------------------- test_that('REQUIRE TEST functioning simparam with by and ATT', { set.seed(123) n <- 100 xx <- rbinom(n = n, size = 1, prob = 0.3) zz <- runif(n) ss <- runif(n) rr <- rbinom(n, size = 1, prob = 0.5) mypi <- 1/(1 + exp(-xx -3*zz -0.5)) yb <- rbinom(n, size = 1, prob = mypi) data <- data.frame(rr, ss, xx, zz, yb) zb.out <- zlogit$new() zb.out$zelig(yb ~ xx + zz, data = data, by = "rr") zb.out$ATT(treatment = "xx") out <- zb.out$get_qi(qi = "ATT", xvalue = "TE") expect_equal(length(out), 1000) }) # REQUIRE TEST getters values and dimensions and plot does not fail------------- test_that("REQUIRE TEST getters values and dimensions and plot does not fail", { set.seed(123) n <- 1000 myseq <- 1:n x <- myseq/n y <- x + (-1)^(myseq) * 0.1 mydata <- data.frame(y = y, x = x) mydata2 <- data.frame(y = y, x = x + 2) z.out <- zelig(y ~ x, model = "ls", data = mydata) expect_equivalent(round(as.numeric(z.out$get_coef()[[1]]), 2), c(0, 1)) expect_equivalent(length(z.out$get_predict()[[1]]), n) expect_equivalent(length(z.out$get_fitted()[[1]]), n) expect_equivalent(dim(z.out$get_vcov()[[1]]), c(2, 2)) z.out$setx(x = 0) z.out$setx1(x = 1) show.setx <- summary(z.out) z.out$sim() show.sim <- summary(z.out) expect_equivalent(length(z.out$get_qi(qi = "ev", xvalue = "x")), n) expect_equivalent(round(mean(z.out$get_qi(qi = "ev", xvalue = "x")), 2), 0) expect_equivalent(length(z.out$get_qi(qi = "ev", xvalue = "x1")), n) expect_equivalent(round(mean(z.out$get_qi(qi = "ev", xvalue = "x1")), 2), 1) expect_equivalent(length(z.out$get_qi(qi = "pv", xvalue = "x")), n) expect_equivalent(round(mean(z.out$get_qi(qi = "pv", xvalue = "x")), 2), 0) expect_equivalent(length(z.out$get_qi(qi = "pv", xvalue = "x1")), n) expect_equivalent(round(mean(z.out$get_qi(qi = "pv", xvalue = "x1")), 2), 1) expect_equivalent(length(z.out$get_qi(qi = "fd", xvalue = "x1")), n) expect_equivalent(round(mean(z.out$get_qi(qi = "fd", xvalue = "x1")), 2), 1) expect_false(show.setx[[1]]) expect_false(show.sim[[1]]) expect_true(is.null(plot(z.out))) xseq <- seq(from = 0, to = 1, length = 10) z.out$setrange(x = xseq) z.out$sim() expect_true(is.null(plot(z.out))) myref <- capture.output(z.out$references()) expect_equivalent(substr(myref[1], 1, 11), "R Core Team") set.seed(123) boot.out <- zelig(y ~ x, model = "ls", bootstrap = 20, data = mydata) expect_equivalent(round(as.numeric(boot.out$get_coef()[[1]]), 2), c(0, 1)) show.boot <- summary(boot.out, bagging = TRUE) expect_false(show.boot[[1]]) show.boot <- summary(boot.out, subset=2:3) expect_false(show.boot[[1]]) set.seed(123) mi.out <- zelig(y ~ x, model = "ls", data = mi(mydata, mydata2)) expect_equivalent(round(as.numeric(mi.out$get_coef()[[1]]), 2), c(0, 1)) expect_equivalent(round(as.numeric(mi.out$get_coef()[[2]]), 2), c(-2, 1)) expect_equivalent(length(mi.out$toJSON()), 1) show.mi <- summary(mi.out) expect_false(show.mi[[1]]) show.mi.subset <- summary(mi.out, subset = 1) expect_false(show.mi.subset[[1]]) }) # REQUIRE TEST Binary QI's and ATT effects and BY argument------------- test_that('REQUIRE TEST Binary QIs and ATT effects and BY argument', { set.seed(123) # Simulate data n <- 100 xx <- rbinom(n = n, size = 1, prob = 0.5) zz <- runif(n) ss <- runif(n) rr <- rbinom(n, size = 1, prob = 0.5) mypi <- 1/ (1+exp(-xx -3*zz -0.5)) yb <- rbinom(n, size = 1, prob = mypi) data <- data.frame(rr, ss, xx, zz, yb) # Estimate Zelig Logit models zb.out <- zlogit$new() zb.out$zelig(yb ~ xx + zz, data=data, by="rr") show.logit <- summary(zb.out) expect_false(show.logit[[1]]) zb2.out <- zlogit$new() zb2.out$zelig(yb ~ xx, data=data) zb3.out <- zlogit$new() zb3.out$zelig(yb ~ xx + zz, data=data) x.high <- setx(zb.out, xx = quantile(data$xx, prob = 0.75)) x.low <- setx(zb.out, xx = quantile(data$xx, prob = 0.25)) s.out <- sim(zb.out, x = x.high, x1 = x.low) show.logit <- summary(s.out) expect_false(show.logit[[1]]) expect_true(is.null(plot(s.out))) # Method to calculate ATT zb.out$ATT(treatment = "xx") # Getter to extract ATT out <- zb.out$get_qi(qi="ATT", xvalue="TE") expect_equal(length(out), 1000) # Plot ROC expect_true(is.null(rocplot(zb2.out, zb3.out))) }) # REQUIRE TEST for get_names method---------------------------------------------- test_that('REQUIRE TEST for names field', { z <- zls$new() z$zelig(Fertility ~ Education, data = swiss) expect_is(z$get_names(), class = 'character') expect_false(is.null(names(z))) }) # REQUIRE TEST for get_residuals method ----------------------------------------- test_that('REQUIRE TEST for get_residuals method', { z <- zls$new() z$zelig(Fertility ~ Education, data = swiss) expect_is(z$get_residuals(), class = 'list') expect_false(is.null(residuals(z))) }) # REQUIRE TEST for get_df_residual method ----------------------------------------- test_that('REQUIRE TEST for get_df_residual method', { z <- zls$new() z$zelig(Fertility ~ Education, data = swiss) expect_equal(length(z$get_df_residual()), 1) expect_equal(length(df.residual(z)), 1) }) # REQUIRE TEST for get_model_data method --------------------------------------- test_that('REQUIRE TEST for get_model_data method', { z <- zls$new() z$zelig(Fertility ~ Education, data = swiss) expect_is(z$get_model_data(), class = 'data.frame') }) # REQUIRE TEST for get_pvalue method --------------------------------------- test_that('REQUIRE TEST for get_pvalue', { z <- zls$new() z$zelig(Fertility ~ Education, data = swiss) expect_is(z$get_pvalue()[[1]], class = 'numeric') expect_equal(z$get_pvalue()[[1]], get_pvalue(z)[[1]]) }) # REQUIRE TEST for get_se method --------------------------------------- test_that('REQUIRE TEST for get_se', { z <- zls$new() z$zelig(Fertility ~ Education, data = swiss) expect_is(z$get_se()[[1]], class = 'numeric') expect_equal(z$get_se()[[1]], get_se(z)[[1]]) }) # REQUIRE TEST setx with logical covariates ------------------------------------ test_that('REQUIRE TEST setx with logical covariates', { swiss$maj_catholic <- cut(swiss$Catholic, breaks = c(0, 51, 100)) swiss$maj_catholic_logical <- FALSE swiss$maj_catholic_logical[swiss$maj_catholic == '(51,100]'] <- TRUE z5l <- zls$new() z5l$zelig(Fertility ~ Education + maj_catholic_logical, data = swiss) z5l$setx(maj_catholic_logical = TRUE) expect_is(z5l$setx.out$x, class = c("rowwise_df", "tbl_df", "tbl", "data.frame")) }) # REQUIRE TESTS for standard R methods with zelig models ----------------------- test_that('REQUIRE TESTS for standard R methods with zelig models', { z5 <- zls$new() z5$zelig(Fertility ~ Education, data = swiss) expect_equal(length(coefficients(z5)), length(coef(z5)), 2) expect_equal(nrow(vcov(z5)[[1]]), 2) expect_equal(length(fitted(z5)[[1]]), 47) expect_equal(length(predict(z5)[[1]]), 47) })
11,702
gpl-2.0
ab36322908d899d1a33aedd0178faf0fd2c14e52
llattes/datasciencecoursera
Exploratory/Week3/plot1.R
plot1 <- function() { require("RColorBrewer") NEI <- readRDS("summarySCC_PM25.rds") s1 <- subset(x = NEI, subset = NEI$year == 1999) s2 <- subset(x = NEI, subset = NEI$year == 2002) s3 <- subset(x = NEI, subset = NEI$year == 2005) s4 <- subset(x = NEI, subset = NEI$year == 2008) emissions_by_year = data.frame(c("1999", "2002", "2005", "2008"), c(sum(s1$Emissions), sum(s2$Emissions), sum(s3$Emissions), sum(s4$Emissions)), stringsAsFactors = FALSE) colnames(emissions_by_year) <- c("Year", "Total_Emissions") palette <- brewer.pal(4, "Blues") png(filename = paste("plot1.png", sep = ""), width = 800, height = 600, units = "px") barplot(emissions_by_year$Total_Emissions, names.arg = emissions_by_year$Year, col = palette, main = "PM2.5 emissions by year in the US", xlab="Year", ylab="Total Emissions (in tons.)") dev.off() }
875
mit
31868c67c6eb1f1b19ef54ba61c3af389d1e0358
diegofernandes/servicemanager
plugins/feedbackDemo:1.0/feedbackDemo:1.0.R
#!/usr/bin/env Rscript # # Meccano IOT ServiceManager # # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # library(RMySQL) config.database.dbname <- Sys.getenv("MYSQL_DATABASE") config.database.host <- Sys.getenv("MYSQL_HOST") config.database.port <- as.numeric(Sys.getenv("MYSQL_PORT")) config.database.user <- Sys.getenv("MYSQL_USER") config.database.password <- Sys.getenv("MYSQL_PASSWORD") print("Connecting to database...") conn <- dbConnect(MySQL(), dbname = config.database.dbname, port = config.database.port, host = config.database.host, user = config.database.user, password = config.database.password ) summary(conn) # Carregar dados de visitacao diaria do Redshift print("Reading training data...") rs <- dbSendQuery(conn, "select 'bad' as feedback, count(*) as votes from Facts where channel = 'feedback' and data = -100 union select 'average' as feedback, count(*) as votes from Facts where channel = 'feedback' and data = 50 union select 'good' as feedback, count(*) as votes from Facts where channel = 'feedback' and data = 100 ") v <- fetch(rs) dbDisconnect(conn) setwd("./assets/") png('output.png') mp <- barplot(v$votes, names.arg = v$feedback, xlab = "feedback", ylab="number of votes (un.)", col = c("firebrick", "goldenrod", "darkolivegreen3")) text(mp, v$votes, labels = v$votes, pos = 1) dev.off() q()
2,042
gpl-3.0
9e25f12ce82a9d8bcdd048f5614b2796e31ed7eb
cheerzzh/R_for_Quantitative_Finance
rate-analysis/INR266/INR266_index.R
library(xts) library(xtsExtra) index <- read.csv('NSERO_index.csv',stringsAsFactors = FALSE) # for currency first data <- index dates <- data$Date rates <- data[,-1] dates <- as.POSIXct(dates,format ="%m/%d/%Y") t <- as.xts(rates, order.by = dates) rate_name <- names(t) span <- 0.08 tsoutliers <- function(x,plot=TRUE,span=0.1,name="",percentile = c(0.25,0.75),k=3,range = c(-1.1)) { # x <- as.ts(x) if(frequency(x)>1) resid <- stl(x,s.window="periodic",robust=TRUE)$time.series[,3] else { tt <- 1:length(x) #resid <- residuals(loess(x ~ tt,span=span)) loe <- loess(x~tt, span = span) pred <- predict(loe,tt,se=TRUE) resid <- loe$residuals } # can adjust the parameters to control the outlier resid.q <- quantile(resid,prob= percentile) iqr <- diff(resid.q) limits <- resid.q + k*iqr*range score <- abs(pmin((resid-limits[1])/iqr,0) + pmax((resid - limits[2])/iqr,0)) indicator <- ifelse(score>0,1,0) indi <- cbind(indicator,x)[,1] if(plot) { custom.panel <- function(index,x,...) { default.panel(index,x,...) points(x=index(indi[indi == 1]), y=x[,1][index(indi[indi == 1])],cex=0.9,pch=19, col="blue") #abline(v=index(indi[indi == 1]),col="grey") } newlist <- list(score = score, resid = resid,indicator = indicator) plot.xts(x=cbind(x,fitted=loe$fitted,residual=loe$residuals),panel = custom.panel, screens = factor(1, 1), auto.legend = TRUE, main = paste("LOESS plot",rate_name[i],sep=" ")) cat("Number of outliers for ",name," is ", sum(indicator),"\n") return(invisible(newlist)) } else return(list(score,resid,indicator)) } jpeg(file = "INR266 index LOESS plot %d.jpeg",quality=100,width = 1200, height = 800,units = 'px', pointsize = 12) indi <- rep(0,nrow(t)) # initialize the indicator vector for (i in 1:ncol(t)) { a <- tsoutliers(t[,i],name = rate_name[i],span=span, percentile = c(0.1,0.9),k=3,range=c(-0.85,1)) # if any col in one raw has 1, label this row as 1 indi <- indi | a$indicator } dev.off() # combine result indi <- cbind(indi,t)[,1] num <- sum(indi) per <-sum(indi)/nrow(t) cat("\ntotal number of outliers is ", num) cat("\npercentage of outliers is ",per) # percenatge of potential outlier jpeg(file = "INR266 index.jpeg",quality=100,width = 1200,height = 800,units = 'px', pointsize = 12) # try to add points to show outlier # index(indi[indi == 1]) get outlier custom.panel <- function(index,x,...) { default.panel(index,x,...) abline(v=index(indi[indi == 1]),col=rgb(1,0,0,0.2),lwd=0.7) usr <- par( "usr" ) text( usr[ 2 ], usr[ 4 ], paste("number of outliers: ",num,"\n","ratio: ",format(per,digits=4)), adj = c( 1, 1 ), col = "blue" ,cex=1.5) } plot.xts(t,main="INR266 index",panel = custom.panel) dev.off() # write the index into file data <- cbind(indi,t) data <- data.frame(date=index(data), coredata(data)) colnames(data)[2] <- "indicator" colnames(data)[3] <- "Overnight" write.csv(data, file = "INR266_index_outlier.csv",row.names=TRUE) # single tenor, no need to compare across tenors
3,151
mit
9e25f12ce82a9d8bcdd048f5614b2796e31ed7eb
WealthCity/R_for_Quantitative_Finance
rate-analysis/INR266/INR266_index.R
library(xts) library(xtsExtra) index <- read.csv('NSERO_index.csv',stringsAsFactors = FALSE) # for currency first data <- index dates <- data$Date rates <- data[,-1] dates <- as.POSIXct(dates,format ="%m/%d/%Y") t <- as.xts(rates, order.by = dates) rate_name <- names(t) span <- 0.08 tsoutliers <- function(x,plot=TRUE,span=0.1,name="",percentile = c(0.25,0.75),k=3,range = c(-1.1)) { # x <- as.ts(x) if(frequency(x)>1) resid <- stl(x,s.window="periodic",robust=TRUE)$time.series[,3] else { tt <- 1:length(x) #resid <- residuals(loess(x ~ tt,span=span)) loe <- loess(x~tt, span = span) pred <- predict(loe,tt,se=TRUE) resid <- loe$residuals } # can adjust the parameters to control the outlier resid.q <- quantile(resid,prob= percentile) iqr <- diff(resid.q) limits <- resid.q + k*iqr*range score <- abs(pmin((resid-limits[1])/iqr,0) + pmax((resid - limits[2])/iqr,0)) indicator <- ifelse(score>0,1,0) indi <- cbind(indicator,x)[,1] if(plot) { custom.panel <- function(index,x,...) { default.panel(index,x,...) points(x=index(indi[indi == 1]), y=x[,1][index(indi[indi == 1])],cex=0.9,pch=19, col="blue") #abline(v=index(indi[indi == 1]),col="grey") } newlist <- list(score = score, resid = resid,indicator = indicator) plot.xts(x=cbind(x,fitted=loe$fitted,residual=loe$residuals),panel = custom.panel, screens = factor(1, 1), auto.legend = TRUE, main = paste("LOESS plot",rate_name[i],sep=" ")) cat("Number of outliers for ",name," is ", sum(indicator),"\n") return(invisible(newlist)) } else return(list(score,resid,indicator)) } jpeg(file = "INR266 index LOESS plot %d.jpeg",quality=100,width = 1200, height = 800,units = 'px', pointsize = 12) indi <- rep(0,nrow(t)) # initialize the indicator vector for (i in 1:ncol(t)) { a <- tsoutliers(t[,i],name = rate_name[i],span=span, percentile = c(0.1,0.9),k=3,range=c(-0.85,1)) # if any col in one raw has 1, label this row as 1 indi <- indi | a$indicator } dev.off() # combine result indi <- cbind(indi,t)[,1] num <- sum(indi) per <-sum(indi)/nrow(t) cat("\ntotal number of outliers is ", num) cat("\npercentage of outliers is ",per) # percenatge of potential outlier jpeg(file = "INR266 index.jpeg",quality=100,width = 1200,height = 800,units = 'px', pointsize = 12) # try to add points to show outlier # index(indi[indi == 1]) get outlier custom.panel <- function(index,x,...) { default.panel(index,x,...) abline(v=index(indi[indi == 1]),col=rgb(1,0,0,0.2),lwd=0.7) usr <- par( "usr" ) text( usr[ 2 ], usr[ 4 ], paste("number of outliers: ",num,"\n","ratio: ",format(per,digits=4)), adj = c( 1, 1 ), col = "blue" ,cex=1.5) } plot.xts(t,main="INR266 index",panel = custom.panel) dev.off() # write the index into file data <- cbind(indi,t) data <- data.frame(date=index(data), coredata(data)) colnames(data)[2] <- "indicator" colnames(data)[3] <- "Overnight" write.csv(data, file = "INR266_index_outlier.csv",row.names=TRUE) # single tenor, no need to compare across tenors
3,151
mit
9e25f12ce82a9d8bcdd048f5614b2796e31ed7eb
jond3k/R_for_Quantitative_Finance
rate-analysis/INR266/INR266_index.R
library(xts) library(xtsExtra) index <- read.csv('NSERO_index.csv',stringsAsFactors = FALSE) # for currency first data <- index dates <- data$Date rates <- data[,-1] dates <- as.POSIXct(dates,format ="%m/%d/%Y") t <- as.xts(rates, order.by = dates) rate_name <- names(t) span <- 0.08 tsoutliers <- function(x,plot=TRUE,span=0.1,name="",percentile = c(0.25,0.75),k=3,range = c(-1.1)) { # x <- as.ts(x) if(frequency(x)>1) resid <- stl(x,s.window="periodic",robust=TRUE)$time.series[,3] else { tt <- 1:length(x) #resid <- residuals(loess(x ~ tt,span=span)) loe <- loess(x~tt, span = span) pred <- predict(loe,tt,se=TRUE) resid <- loe$residuals } # can adjust the parameters to control the outlier resid.q <- quantile(resid,prob= percentile) iqr <- diff(resid.q) limits <- resid.q + k*iqr*range score <- abs(pmin((resid-limits[1])/iqr,0) + pmax((resid - limits[2])/iqr,0)) indicator <- ifelse(score>0,1,0) indi <- cbind(indicator,x)[,1] if(plot) { custom.panel <- function(index,x,...) { default.panel(index,x,...) points(x=index(indi[indi == 1]), y=x[,1][index(indi[indi == 1])],cex=0.9,pch=19, col="blue") #abline(v=index(indi[indi == 1]),col="grey") } newlist <- list(score = score, resid = resid,indicator = indicator) plot.xts(x=cbind(x,fitted=loe$fitted,residual=loe$residuals),panel = custom.panel, screens = factor(1, 1), auto.legend = TRUE, main = paste("LOESS plot",rate_name[i],sep=" ")) cat("Number of outliers for ",name," is ", sum(indicator),"\n") return(invisible(newlist)) } else return(list(score,resid,indicator)) } jpeg(file = "INR266 index LOESS plot %d.jpeg",quality=100,width = 1200, height = 800,units = 'px', pointsize = 12) indi <- rep(0,nrow(t)) # initialize the indicator vector for (i in 1:ncol(t)) { a <- tsoutliers(t[,i],name = rate_name[i],span=span, percentile = c(0.1,0.9),k=3,range=c(-0.85,1)) # if any col in one raw has 1, label this row as 1 indi <- indi | a$indicator } dev.off() # combine result indi <- cbind(indi,t)[,1] num <- sum(indi) per <-sum(indi)/nrow(t) cat("\ntotal number of outliers is ", num) cat("\npercentage of outliers is ",per) # percenatge of potential outlier jpeg(file = "INR266 index.jpeg",quality=100,width = 1200,height = 800,units = 'px', pointsize = 12) # try to add points to show outlier # index(indi[indi == 1]) get outlier custom.panel <- function(index,x,...) { default.panel(index,x,...) abline(v=index(indi[indi == 1]),col=rgb(1,0,0,0.2),lwd=0.7) usr <- par( "usr" ) text( usr[ 2 ], usr[ 4 ], paste("number of outliers: ",num,"\n","ratio: ",format(per,digits=4)), adj = c( 1, 1 ), col = "blue" ,cex=1.5) } plot.xts(t,main="INR266 index",panel = custom.panel) dev.off() # write the index into file data <- cbind(indi,t) data <- data.frame(date=index(data), coredata(data)) colnames(data)[2] <- "indicator" colnames(data)[3] <- "Overnight" write.csv(data, file = "INR266_index_outlier.csv",row.names=TRUE) # single tenor, no need to compare across tenors
3,151
mit
7e278e86677d18ee4d35325e6309d3be7ee7b4fa
bcgov/rcaaqs
tests/testthat/test-7_pm_caaqs.R
context("pm caaqs wrappers") d1 <- readRDS("pm_raw1.rds") d2 <- readRDS("pm_raw2.rds") pm2.5_24h_caaqs_one <- NULL pm2.5_24h_caaqs_mult <- NULL pm2.5_annual_caaqs_one <- NULL pm2.5_annual_caaqs_mult <- NULL test_that("classes and extractors for pm2.5_24h", { expect_message(pm2.5_24h_caaqs_one <<- pm_24h_caaqs(d1), "Calculating PM 2.5 daily average") expect_is(pm2.5_24h_caaqs_one, c("caaqs", "pm2.5_24h")) expect_length(pm2.5_24h_caaqs_one, 4) expect_named(pm2.5_24h_caaqs_one, c("daily_avg", "yearly_98", "three_yr_rolling", "caaqs")) for (d in pm2.5_24h_caaqs_one) { expect_is(d, "data.frame") } expect_is(get_caaqs(pm2.5_24h_caaqs_one), "data.frame") expect_is(get_daily(pm2.5_24h_caaqs_one),"data.frame") expect_is(get_yearly(pm2.5_24h_caaqs_one), "data.frame") expect_is(get_three_yr_rolling(pm2.5_24h_caaqs_one), "data.frame") saveRDS(pm2.5_24h_caaqs_one, "pm_24h_caaqs1.rds") }) test_that("pm2.5_24h_caaqs single", { caaqs <- get_caaqs(pm2.5_24h_caaqs_one) expect_length(caaqs$caaqs, 3) expect_true(all(is.na(caaqs$metric_value[caaqs$caaqs == "Insufficient Data"]))) expect_true(all(!is.na(caaqs$metric_value[caaqs$caaqs != "Insufficient Data"]))) expect_true(all(caaqs$caaqs[caaqs$metric_value <= get_std("pm2.5_24h")] == "Achieved", na.rm = TRUE)) expect_true(all(caaqs$caaqs[caaqs$metric_value > get_std("pm2.5_24h")] == "Not Achieved", na.rm = TRUE)) expect_length(get_caaqs(pm2.5_24h_caaqs_one), 10) expect_length(get_daily(pm2.5_24h_caaqs_one), 6) expect_length(get_yearly(pm2.5_24h_caaqs_one), 12) expect_length(get_three_yr_rolling(pm2.5_24h_caaqs_one), 19) }) test_that("pm2.5_24h_caaqs groups", { expect_message( pm2.5_24h_caaqs_mult <<- pm_24h_caaqs(d2, by = c("ems_id", "site")), "Calculating PM 2.5 daily average" ) caaqs <- get_caaqs(pm2.5_24h_caaqs_mult) expect_length(caaqs$caaqs, 6) expect_true(all(is.na(caaqs$metric_value[caaqs$caaqs == "Insufficient Data"]))) expect_true(all(!is.na(caaqs$metric_value[caaqs$caaqs != "Insufficient Data"]))) expect_true(all(caaqs$caaqs[caaqs$metric_value <= get_std("pm2.5_24h")] == "Achieved", na.rm = TRUE)) expect_true(all(caaqs$caaqs[caaqs$metric_value > get_std("pm2.5_24h")] == "Not Achieved", na.rm = TRUE)) expect_length(get_caaqs(pm2.5_24h_caaqs_mult), 12) expect_length(get_daily(pm2.5_24h_caaqs_mult), 8) expect_length(get_yearly(pm2.5_24h_caaqs_mult), 14) expect_length(get_three_yr_rolling(pm2.5_24h_caaqs_mult), 21) saveRDS(pm2.5_24h_caaqs_mult, "pm_24h_caaqs2.rds") }) test_that("caaqs_management for pm2.5_24h", { expect_is(pm2.5_24h_caaqs_one_mgmt <- caaqs_management(pm2.5_24h_caaqs_one), "caaqs_mgmt") expect_length(pm2.5_24h_caaqs_one_mgmt, 4) expect_length(get_caaqs(pm2.5_24h_caaqs_one_mgmt), 13) expect_length(get_daily(pm2.5_24h_caaqs_one_mgmt), 6) expect_length(get_yearly(pm2.5_24h_caaqs_one_mgmt), 15) expect_length(get_three_yr_rolling(pm2.5_24h_caaqs_one_mgmt), 22) saveRDS(pm2.5_24h_caaqs_one_mgmt, "pm_24h_caaqs1_mgmt.rds") }) test_that("caaqs_management for pm2.5_24h with groups", { expect_is(pm2.5_24h_caaqs_mult_mgmt <- caaqs_management(pm2.5_24h_caaqs_mult), "caaqs_mgmt") expect_length(pm2.5_24h_caaqs_mult_mgmt, 4) expect_length(get_caaqs(pm2.5_24h_caaqs_mult_mgmt), 15) expect_length(get_daily(pm2.5_24h_caaqs_mult_mgmt), 8) expect_length(get_yearly(pm2.5_24h_caaqs_mult_mgmt), 17) expect_length(get_three_yr_rolling(pm2.5_24h_caaqs_mult_mgmt), 24) saveRDS(pm2.5_24h_caaqs_mult_mgmt, "pm_24h_caaqs2_mgmt.rds") }) test_that("classes and extractors for pm2.5_annual", { expect_message(pm2.5_annual_caaqs_one <<- pm_annual_caaqs(d1), "Calculating PM 2.5 daily average") expect_is(pm2.5_annual_caaqs_one, c("caaqs", "pm2.5_annual")) expect_length(pm2.5_annual_caaqs_one, 4) expect_named(pm2.5_annual_caaqs_one, c("daily_avg", "yearly_avg", "three_yr_rolling", "caaqs")) for (d in pm2.5_annual_caaqs_one) { expect_is(d, "data.frame") } expect_is(get_caaqs(pm2.5_annual_caaqs_one), "data.frame") expect_is(get_daily(pm2.5_annual_caaqs_one),"data.frame") expect_is(get_yearly(pm2.5_annual_caaqs_one), "data.frame") expect_is(get_three_yr_rolling(pm2.5_annual_caaqs_one), "data.frame") saveRDS(pm2.5_annual_caaqs_one, "pm_annual_caaqs1.rds") }) test_that("pm2.5_annual_caaqs single", { caaqs <- get_caaqs(pm2.5_annual_caaqs_one) expect_length(caaqs$caaqs, 3) expect_true(all(is.na(caaqs$metric_value[caaqs$caaqs == "Insufficient Data"]))) expect_true(all(!is.na(caaqs$metric_value[caaqs$caaqs != "Insufficient Data"]))) expect_true(all(caaqs$caaqs[caaqs$metric_value <= get_std("pm2.5_annual")] == "Achieved", na.rm = TRUE)) expect_true(all(caaqs$caaqs[caaqs$metric_value > get_std("pm2.5_annual")] == "Not Achieved", na.rm = TRUE)) expect_length(get_caaqs(pm2.5_annual_caaqs_one), 10) expect_length(get_daily(pm2.5_annual_caaqs_one), 6) expect_length(get_yearly(pm2.5_annual_caaqs_one), 12) expect_length(get_three_yr_rolling(pm2.5_annual_caaqs_one), 19) }) test_that("pm2.5_annual_caaqs groups", { expect_message( pm2.5_annual_caaqs_mult <<- pm_annual_caaqs(d2, by = c("ems_id", "site")), "Calculating PM 2.5 daily average" ) caaqs <- get_caaqs(pm2.5_annual_caaqs_mult) expect_length(caaqs$caaqs, 6) expect_true(all(is.na(caaqs$metric_value[caaqs$caaqs == "Insufficient Data"]))) expect_true(all(!is.na(caaqs$metric_value[caaqs$caaqs != "Insufficient Data"]))) expect_true(all(caaqs$caaqs[caaqs$metric_value <= get_std("pm2.5_annual")] == "Achieved", na.rm = TRUE)) expect_true(all(caaqs$caaqs[caaqs$metric_value > get_std("pm2.5_annual")] == "Not Achieved", na.rm = TRUE)) expect_length(get_caaqs(pm2.5_annual_caaqs_mult), 12) expect_length(get_daily(pm2.5_annual_caaqs_mult), 8) expect_length(get_yearly(pm2.5_annual_caaqs_mult), 14) expect_length(get_three_yr_rolling(pm2.5_annual_caaqs_mult), 21) saveRDS(pm2.5_annual_caaqs_mult, "pm_annual_caaqs2.rds") }) test_that("caaqs_management for pm2.5_annual", { expect_is(pm2.5_annual_caaqs_one_mgmt <- caaqs_management(pm2.5_annual_caaqs_one), "caaqs_mgmt") expect_length(pm2.5_annual_caaqs_one_mgmt, 4) expect_length(get_caaqs(pm2.5_annual_caaqs_one_mgmt), 13) expect_length(get_daily(pm2.5_annual_caaqs_one_mgmt), 6) expect_length(get_yearly(pm2.5_annual_caaqs_one_mgmt), 15) expect_length(get_three_yr_rolling(pm2.5_annual_caaqs_one_mgmt), 22) saveRDS(pm2.5_annual_caaqs_one_mgmt, "pm_annual_caaqs1_mgmt.rds") }) test_that("caaqs_management for pm2.5_annual with groups", { expect_is(pm2.5_annual_caaqs_mult_mgmt <- caaqs_management(pm2.5_annual_caaqs_mult), "caaqs_mgmt") expect_length(pm2.5_annual_caaqs_mult_mgmt, 4) expect_length(get_caaqs(pm2.5_annual_caaqs_mult_mgmt), 15) expect_length(get_daily(pm2.5_annual_caaqs_mult_mgmt), 8) expect_length(get_yearly(pm2.5_annual_caaqs_mult_mgmt), 17) expect_length(get_three_yr_rolling(pm2.5_annual_caaqs_mult_mgmt), 24) saveRDS(pm2.5_annual_caaqs_mult_mgmt, "pm_annual_caaqs2_mgmt.rds") })
7,261
apache-2.0
d487b1a6274d7949911e12d6011fd6ab3215d5ff
R-Lum/Luminescence
R/plot_AbanicoPlot.R
#' Function to create an Abanico Plot. #' #' A plot is produced which allows comprehensive presentation of data precision #' and its dispersion around a central value as well as illustration of a #' kernel density estimate, histogram and/or dot plot of the dose values. #' #' The Abanico Plot is a combination of the classic Radial Plot #' (`plot_RadialPlot`) and a kernel density estimate plot (e.g #' `plot_KDE`). It allows straightforward visualisation of data precision, #' error scatter around a user-defined central value and the combined #' distribution of the values, on the actual scale of the measured data (e.g. #' seconds, equivalent dose, years). The principle of the plot is shown in #' Galbraith & Green (1990). The function authors are thankful for the #' thought provoking figure in this article. #' #' The semi circle (z-axis) of the classic Radial Plot is bent to a straight #' line here, which actually is the basis for combining this polar (radial) #' part of the plot with any other Cartesian visualisation method #' (KDE, histogram, PDF and so on). Note that the plot allows displaying #' two measures of distribution. One is the 2-sigma #' bar, which illustrates the spread in value errors, and the other is the #' polygon, which stretches over both parts of the Abanico Plot (polar and #' Cartesian) and illustrates the actual spread in the values themselves. #' #' Since the 2-sigma-bar is a polygon, it can be (and is) filled with shaded #' lines. To change density (lines per inch, default is 15) and angle (default #' is 45 degrees) of the shading lines, specify these parameters. See #' `?polygon()` for further help. #' #' The Abanico Plot supports other than the weighted mean as measure of #' centrality. When it is obvious that the data #' is not (log-)normally distributed, the mean (weighted or not) cannot be a #' valid measure of centrality and hence central dose. Accordingly, the median #' and the weighted median can be chosen as well to represent a proper measure #' of centrality (e.g. `centrality = "median.weighted"`). Also #' user-defined numeric values (e.g. from the central age model) can be used if #' this appears appropriate. #' #' The proportion of the polar part and the cartesian part of the Abanico Plot #' can be modified for display reasons (`plot.ratio = 0.75`). By default, #' the polar part spreads over 75 \% and leaves 25 \% for the part that #' shows the KDE graph. #' #' #' A statistic summary, i.e. a collection of statistic measures of #' centrality and dispersion (and further measures) can be added by specifying #' one or more of the following keywords: #' #' - `"n"` (number of samples) #' - `"mean"` (mean De value) #' - `"median"` (median of the De values) #' - `"sd.rel"` (relative standard deviation in percent) #' - `"sd.abs"` (absolute standard deviation) #' - `"se.rel"` (relative standard error) #' - `"se.abs"` (absolute standard error) #' - `"in.2s"` (percent of samples in 2-sigma range) #' - `"kurtosis"` (kurtosis) #' - `"skewness"` (skewness) #' #' **Note** that the input data for the statistic summary is sent to the function #' `calc_Statistics()` depending on the log-option for the z-scale. If #' `"log.z = TRUE"`, the summary is based on the logarithms of the input #' data. If `"log.z = FALSE"` the linearly scaled data is used. #' #' **Note** as well, that `"calc_Statistics()"` calculates these statistic #' measures in three different ways: `unweighted`, `weighted` and #' `MCM-based` (i.e., based on Monte Carlo Methods). By default, the #' MCM-based version is used. If you wish to use another method, indicate this #' with the appropriate keyword using the argument `summary.method`. #' #' The optional parameter `layout` allows to modify the entire plot more #' sophisticated. Each element of the plot can be addressed and its properties #' can be defined. This includes font type, size and decoration, colours and #' sizes of all plot items. To infer the definition of a specific layout style #' cf. `get_Layout()` or type e.g., for the layout type `"journal"` #' `get_Layout("journal")`. A layout type can be modified by the user by #' assigning new values to the list object. #' #' It is possible for the z-scale to specify where ticks are to be drawn #' by using the parameter `at`, e.g. `at = seq(80, 200, 20)`, cf. function #' documentation of `axis`. Specifying tick positions manually overrides a #' `zlim`-definition. #' #' @param data [data.frame] or [RLum.Results-class] object (**required**): #' for `data.frame` two columns: De (`data[,1]`) and De error (`data[,2]`). #' To plot several data sets in one plot the data sets must be provided as #' `list`, e.g. `list(data.1, data.2)`. #' #' @param na.rm [logical] (*with default*): #' exclude NA values from the data set prior to any further operations. #' #' @param log.z [logical] (*with default*): #' Option to display the z-axis in logarithmic scale. Default is `TRUE`. #' #' @param z.0 [character] or [numeric]: #' User-defined central value, used for centring of data. One out of `"mean"`, #' `"mean.weighted"` and `"median"` or a numeric value (not its logarithm). #' Default is `"mean.weighted"`. #' #' @param dispersion [character] (*with default*): #' measure of dispersion, used for drawing the scatter polygon. One out of #' - `"qr"` (quartile range), #' - `"pnn"` (symmetric percentile range with `nn` the lower percentile, e.g. #' - `"p05"` depicting the range between 5 and 95 %), #' - `"sd"` (standard deviation) and #' - `"2sd"` (2 standard deviations), #' #' The default is `"qr"`. Note that `"sd"` and `"2sd"` are only meaningful in #' combination with `"z.0 = 'mean'"` because the unweighted mean is used to #' centre the polygon. #' #' @param plot.ratio [numeric]: #' Relative space, given to the radial versus the cartesian plot part, #' default is `0.75`. #' #' @param rotate [logical]: #' Option to turn the plot by 90 degrees. #' #' @param mtext [character]: #' additional text below the plot title. #' #' @param summary [character] (*optional*): #' add statistic measures of centrality and dispersion to the plot. #' Can be one or more of several keywords. See details for available keywords. #' Results differ depending on the log-option for the z-scale (see details). #' #' @param summary.pos [numeric] or [character] (*with default*): #' optional position coordinates or keyword (e.g. `"topright"`) for the #' statistical summary. Alternatively, the keyword `"sub"` may be #' specified to place the summary below the plot header. However, this latter #' option in only possible if `mtext` is not used. #' #' @param summary.method [character] (*with default*): #' keyword indicating the method used to calculate the statistic summary. #' One out of #' - `"unweighted"`, #' - `"weighted"` and #' - `"MCM"`. #' #' See [calc_Statistics] for details. #' #' @param legend [character] vector (*optional*): #' legend content to be added to the plot. #' #' @param legend.pos [numeric] or [character] (*with default*): #' optional position coordinates or keyword (e.g. `"topright"`) #' for the legend to be plotted. #' #' @param stats [character]: #' additional labels of statistically important values in the plot. #' One or more out of the following: #' - `"min"`, #' - `"max"`, #' - `"median"`. #' #' @param rug [logical]: #' Option to add a rug to the KDE part, to indicate the location of individual values. #' #' @param kde [logical]: #' Option to add a KDE plot to the dispersion part, default is `TRUE`. #' #' @param hist [logical]: #' Option to add a histogram to the dispersion part. Only meaningful when not #' more than one data set is plotted. #' #' @param dots [logical]: #' Option to add a dot plot to the dispersion part. If number of dots exceeds #' space in the dispersion part, a square indicates this. #' #' @param boxplot [logical]: #' Option to add a boxplot to the dispersion part, default is `FALSE`. #' #' @param y.axis [logical]: Option to hide standard y-axis labels and show 0 only. #' Useful for data with small scatter. If you want to suppress the y-axis entirely #' please use `yaxt == 'n'` (the standard [graphics::par] setting) instead. #' #' @param error.bars [logical]: #' Option to show De-errors as error bars on De-points. Useful in combination #' with `y.axis = FALSE, bar.col = "none"`. #' #' @param bar [numeric] (*with default*): #' option to add one or more dispersion bars (i.e., bar showing the 2-sigma range) #' centred at the defined values. By default a bar is drawn according to `"z.0"`. #' To omit the bar set `"bar = FALSE"`. #' #' @param bar.col [character] or [numeric] (*with default*): #' colour of the dispersion bar. Default is `"grey60"`. #' #' @param polygon.col [character] or [numeric] (*with default*): #' colour of the polygon showing the data scatter. Sometimes this #' polygon may be omitted for clarity. To disable it use `FALSE` or #' `polygon = FALSE`. Default is `"grey80"`. #' #' @param line [numeric]: #' numeric values of the additional lines to be added. #' #' @param line.col [character] or [numeric]: #' colour of the additional lines. #' #' @param line.lty [integer]: #' line type of additional lines #' #' @param line.label [character]: #' labels for the additional lines. #' #' @param grid.col [character] or [numeric] (*with default*): #' colour of the grid lines (originating at `[0,0]` and stretching to #' the z-scale). To disable grid lines use `FALSE`. Default is `"grey"`. #' #' @param frame [numeric] (*with default*): #' option to modify the plot frame type. Can be one out of #' - `0` (no frame), #' - `1` (frame originates at 0,0 and runs along min/max isochrons), #' - `2` (frame embraces the 2-sigma bar), #' - `3` (frame embraces the entire plot as a rectangle). #' #' Default is `1`. #' #' @param bw [character] (*with default*): #' bin-width for KDE, choose a numeric value for manual setting. #' #' @param interactive [logical] (*with default*): #' create an interactive abanico plot (requires the `'plotly'` package) #' #' @param ... Further plot arguments to pass (see [graphics::plot.default]). Supported are: `main`, `sub`, `ylab`, `xlab`, `zlab`, `zlim`, `ylim`, `cex`, `lty`, `lwd`, `pch`, `col`, `tck`, `tcl`, `at`, `breaks`. `xlab` must be a vector of length two, specifying the upper and lower x-axes labels. #' #' @return #' returns a plot object and, optionally, a list with plot calculus data. #' #' @section Function version: 0.1.17 #' #' @author #' Michael Dietze, GFZ Potsdam (Germany)\cr #' Sebastian Kreutzer, Institute of Geography, Heidelberg University (Germany)\cr #' Inspired by a plot introduced by Galbraith & Green (1990) #' #' @seealso [plot_RadialPlot], [plot_KDE], [plot_Histogram], [plot_ViolinPlot] #' #' @references #' Galbraith, R. & Green, P., 1990. Estimating the component ages #' in a finite mixture. International Journal of Radiation Applications and #' Instrumentation. Part D. Nuclear Tracks and Radiation Measurements, 17 (3), #' 197-206. #' #' Dietze, M., Kreutzer, S., Burow, C., Fuchs, M.C., Fischer, M., Schmidt, C., 2015. #' The abanico plot: visualising chronometric data with individual standard errors. #' Quaternary Geochronology. doi:10.1016/j.quageo.2015.09.003 #' #' @examples #' #' ## load example data and recalculate to Gray #' data(ExampleData.DeValues, envir = environment()) #' ExampleData.DeValues <- ExampleData.DeValues$CA1 #' #' ## plot the example data straightforward #' plot_AbanicoPlot(data = ExampleData.DeValues) #' #' ## now with linear z-scale #' plot_AbanicoPlot(data = ExampleData.DeValues, #' log.z = FALSE) #' #' ## now with output of the plot parameters #' plot1 <- plot_AbanicoPlot(data = ExampleData.DeValues, #' output = TRUE) #' str(plot1) #' plot1$zlim #' #' ## now with adjusted z-scale limits #' plot_AbanicoPlot(data = ExampleData.DeValues, #' zlim = c(10, 200)) #' #' ## now with adjusted x-scale limits #' plot_AbanicoPlot(data = ExampleData.DeValues, #' xlim = c(0, 20)) #' #' ## now with rug to indicate individual values in KDE part #' plot_AbanicoPlot(data = ExampleData.DeValues, #' rug = TRUE) #' #' ## now with a smaller bandwidth for the KDE plot #' plot_AbanicoPlot(data = ExampleData.DeValues, #' bw = 0.04) #' #' ## now with a histogram instead of the KDE plot #' plot_AbanicoPlot(data = ExampleData.DeValues, #' hist = TRUE, #' kde = FALSE) #' #' ## now with a KDE plot and histogram with manual number of bins #' plot_AbanicoPlot(data = ExampleData.DeValues, #' hist = TRUE, #' breaks = 20) #' #' ## now with a KDE plot and a dot plot #' plot_AbanicoPlot(data = ExampleData.DeValues, #' dots = TRUE) #' #' ## now with user-defined plot ratio #' plot_AbanicoPlot(data = ExampleData.DeValues, #' plot.ratio = 0.5) #' ## now with user-defined central value #' plot_AbanicoPlot(data = ExampleData.DeValues, #' z.0 = 70) #' #' ## now with median as central value #' plot_AbanicoPlot(data = ExampleData.DeValues, #' z.0 = "median") #' #' ## now with the 17-83 percentile range as definition of scatter #' plot_AbanicoPlot(data = ExampleData.DeValues, #' z.0 = "median", #' dispersion = "p17") #' #' ## now with user-defined green line for minimum age model #' CAM <- calc_CentralDose(ExampleData.DeValues, #' plot = FALSE) #' #' plot_AbanicoPlot(data = ExampleData.DeValues, #' line = CAM, #' line.col = "darkgreen", #' line.label = "CAM") #' #' ## now create plot with legend, colour, different points and smaller scale #' plot_AbanicoPlot(data = ExampleData.DeValues, #' legend = "Sample 1", #' col = "tomato4", #' bar.col = "peachpuff", #' pch = "R", #' cex = 0.8) #' #' ## now without 2-sigma bar, polygon, grid lines and central value line #' plot_AbanicoPlot(data = ExampleData.DeValues, #' bar.col = FALSE, #' polygon.col = FALSE, #' grid.col = FALSE, #' y.axis = FALSE, #' lwd = 0) #' #' ## now with direct display of De errors, without 2-sigma bar #' plot_AbanicoPlot(data = ExampleData.DeValues, #' bar.col = FALSE, #' ylab = "", #' y.axis = FALSE, #' error.bars = TRUE) #' #' ## now with user-defined axes labels #' plot_AbanicoPlot(data = ExampleData.DeValues, #' xlab = c("Data error (%)", #' "Data precision"), #' ylab = "Scatter", #' zlab = "Equivalent dose [Gy]") #' #' ## now with minimum, maximum and median value indicated #' plot_AbanicoPlot(data = ExampleData.DeValues, #' stats = c("min", "max", "median")) #' #' ## now with a brief statistical summary as subheader #' plot_AbanicoPlot(data = ExampleData.DeValues, #' summary = c("n", "in.2s")) #' #' ## now with another statistical summary #' plot_AbanicoPlot(data = ExampleData.DeValues, #' summary = c("mean.weighted", "median"), #' summary.pos = "topleft") #' #' ## now a plot with two 2-sigma bars for one data set #' plot_AbanicoPlot(data = ExampleData.DeValues, #' bar = c(30, 100)) #' #' ## now the data set is split into sub-groups, one is manipulated #' data.1 <- ExampleData.DeValues[1:30,] #' data.2 <- ExampleData.DeValues[31:62,] * 1.3 #' #' ## now a common dataset is created from the two subgroups #' data.3 <- list(data.1, data.2) #' #' ## now the two data sets are plotted in one plot #' plot_AbanicoPlot(data = data.3) #' #' ## now with some graphical modification #' plot_AbanicoPlot(data = data.3, #' z.0 = "median", #' col = c("steelblue4", "orange4"), #' bar.col = c("steelblue3", "orange3"), #' polygon.col = c("steelblue1", "orange1"), #' pch = c(2, 6), #' angle = c(30, 50), #' summary = c("n", "in.2s", "median")) #' #' ## create Abanico plot with predefined layout definition #' plot_AbanicoPlot(data = ExampleData.DeValues, #' layout = "journal") #' #' ## now with predefined layout definition and further modifications #' plot_AbanicoPlot( #' data = data.3, #' z.0 = "median", #' layout = "journal", #' col = c("steelblue4", "orange4"), #' bar.col = adjustcolor(c("steelblue3", "orange3"), #' alpha.f = 0.5), #' polygon.col = c("steelblue3", "orange3")) #' #' ## for further information on layout definitions see documentation #' ## of function get_Layout() #' #' ## now with manually added plot content #' ## create empty plot with numeric output #' AP <- plot_AbanicoPlot(data = ExampleData.DeValues, #' pch = NA, #' output = TRUE) #' #' ## identify data in 2 sigma range #' in_2sigma <- AP$data[[1]]$data.in.2s #' #' ## restore function-internal plot parameters #' par(AP$par) #' #' ## add points inside 2-sigma range #' points(x = AP$data[[1]]$precision[in_2sigma], #' y = AP$data[[1]]$std.estimate.plot[in_2sigma], #' pch = 16) #' #' ## add points outside 2-sigma range #' points(x = AP$data[[1]]$precision[!in_2sigma], #' y = AP$data[[1]]$std.estimate.plot[!in_2sigma], #' pch = 1) #' #' @md #' @export plot_AbanicoPlot <- function( data, na.rm = TRUE, log.z = TRUE, z.0 = "mean.weighted", dispersion = "qr", plot.ratio = 0.75, rotate = FALSE, mtext, summary, summary.pos, summary.method = "MCM", legend, legend.pos, stats, rug = FALSE, kde = TRUE, hist = FALSE, dots = FALSE, boxplot = FALSE, y.axis = TRUE, error.bars = FALSE, bar, bar.col, polygon.col, line, line.col, line.lty, line.label, grid.col, frame = 1, bw = "SJ", interactive = FALSE, ... ) { ## check data and parameter consistency-------------------------------------- ## Homogenise input data format if(is(data, "list") == FALSE) { data <- list(data) } ## Check input data for(i in 1:length(data)) { if(is(data[[i]], "RLum.Results") == FALSE & is(data[[i]], "data.frame") == FALSE) { stop(paste("[plot_AbanicoPlot()] Input data format is neither", "'data.frame' nor 'RLum.Results'")) } else { if(is(data[[i]], "RLum.Results")) data[[i]] <- get_RLum(data[[i]], "data") data[[i]] <- data[[i]][,c(1:2)] } } ## optionally, remove NA-values if(na.rm == TRUE) { for(i in 1:length(data)) { n.NA <- sum(!complete.cases(data[[i]])) if(n.NA == 1) {message(paste0("[plot_AbanicoPlot()] data set (", i, "): 1 NA value excluded.")) } else if(n.NA > 1) { message(paste0("[plot_AbanicoPlot()] data set (", i,"): ", n.NA, " NA values excluded.")) } data[[i]] <- na.exclude(data[[i]]) } } ##AFTER NA removal, we should check the data set carefully again ... ##(1) ##check if there is still data left in the entire set if(all(sapply(data, nrow) == 0)){ try(stop("[plot_AbanicoPlot()] Nothing plotted, your data set is empty!", call. = FALSE)) return(NULL) } ##(2) ##check for sets with only 1 row or 0 rows at all else if(any(sapply(data, nrow) <= 1)){ ##select problematic sets and remove the entries from the list NArm.id <- which(sapply(data, nrow) <= 1) data[NArm.id] <- NULL warning(paste0("[plot_AbanicoPlot()] Data sets ", paste(NArm.id, collapse = ", "), " are found to be empty or consisting of only 1 row. Sets removed!")) rm(NArm.id) ##unfortunately, the data set might become now empty at all if(length(data) == 0){ try(stop("[plot_AbanicoPlot()] After removing invalid entries, nothing is plotted!", call. = FALSE)) return(NULL) } } ## check for zero-error values for(i in 1:length(data)) { if(length(data[[i]]) < 2) { stop("Data without errors cannot be displayed!") } if(sum(data[[i]][,2] == 0) > 0) { data[[i]] <- data[[i]][data[[i]][,2] > 0,] if(nrow(data[[i]]) < 1) { stop("[plot_AbanicoPlot()] Data set contains only values with zero errors.", call. = FALSE) } warning("[plot_AbanicoPlot()] values with zero errors cannot be displayed and were removed!",call. = FALSE) } } ## save original plot parameters and restore them upon end or stop par.old.full <- par(no.readonly = TRUE) cex_old <- par()$cex ## this ensures par() is respected for several plots on one page if(sum(par()$mfrow) == 2 & sum(par()$mfcol) == 2){ on.exit(par(par.old.full)) } ## check/set layout definitions if("layout" %in% names(list(...))) { layout = get_Layout(layout = list(...)$layout) } else { layout <- get_Layout(layout = "default") } if(missing(stats) == TRUE) { stats <- numeric(0) } if(missing(bar) == TRUE) { bar <- rep(TRUE, length(data)) } if(missing(bar.col) == TRUE) { bar.fill <- rep(x = rep(x = layout$abanico$colour$bar.fill, length.out = length(data)), length(bar)) bar.line <- rep(rep(layout$abanico$colour$bar.line, length.out = length(data)), length(bar)) } else { bar.fill <- bar.col bar.line <- NA } if(missing(polygon.col) == TRUE) { polygon.fill <- rep(layout$abanico$colour$poly.fill, length.out = length(data)) polygon.line <- rep(layout$abanico$colour$poly.line, length.out = length(data)) } else { polygon.fill <- polygon.col polygon.line <- NA } if(missing(grid.col) == TRUE) { grid.major <- layout$abanico$colour$grid.major grid.minor <- layout$abanico$colour$grid.minor } else { if(length(grid.col) == 1) { grid.major <- grid.col[1] grid.minor <- grid.col[1] } else { grid.major <- grid.col[1] grid.minor <- grid.col[2] } } if(missing(summary) == TRUE) { summary <- c("n", "in.2s") } if(missing(summary.pos) == TRUE) { summary.pos <- "sub" } if(missing(mtext) == TRUE) { mtext <- "" } ## create preliminary global data set De.global <- data[[1]][,1] if(length(data) > 1) { for(i in 2:length(data)) { De.global <- c(De.global, data[[i]][,1]) } } ## calculate major preliminary tick values and tick difference extraArgs <- list(...) if("zlim" %in% names(extraArgs)) { limits.z <- extraArgs$zlim } else { z.span <- (mean(De.global) * 0.5) / (sd(De.global) * 100) z.span <- ifelse(z.span > 1, 0.9, z.span) limits.z <- c((ifelse(min(De.global) <= 0, 1.1, 0.9) - z.span) * min(De.global), (1.1 + z.span) * max(De.global)) } if("at" %in% names(extraArgs)) { ticks <- extraArgs$at } else { ticks <- round(pretty(limits.z, n = 5), 3) } if("breaks" %in% names(extraArgs)) { breaks <- extraArgs$breaks } else { breaks <- "Sturges" } ## check/set bw-parameter for(i in 1:length(data)) { bw.test <- try(density(x = data[[i]][,1], bw = bw), silent = TRUE) if(grepl(pattern = "Error", x = bw.test[1]) == TRUE) { bw <- "nrd0" warning("[plot_AbanicoPlot()] Option for bw not possible. Set to nrd0!", call. = FALSE) } } if ("fun" %in% names(extraArgs)) { fun <- list(...)$fun } else { fun <- FALSE } ## check for negative values, stop function, but do not stop if(min(De.global) < 0) { if("zlim" %in% names(extraArgs)) { De.add <- abs(extraArgs$zlim[1]) } else { ## estimate delta De to add to all data De.add <- min(10^ceiling(log10(abs(De.global))) * 10) ## optionally readjust delta De for extreme values if(De.add <= abs(min(De.global))) { De.add <- De.add * 10 } } } else { De.add <- 0 } ## optionally add correction dose to data set and adjust error if(log.z == TRUE) { for(i in 1:length(data)) { data[[i]][,1] <- data[[i]][,1] + De.add } De.global <- De.global + De.add } ## calculate and append statistical measures -------------------------------- ## z-values based on log-option z <- lapply(1:length(data), function(x){ if(log.z == TRUE) { log(data[[x]][,1]) } else { data[[x]][,1] } }) if(is(z, "list") == FALSE) { z <- list(z) } data <- lapply(1:length(data), function(x) { cbind(data[[x]], z[[x]]) }) rm(z) ## calculate dispersion based on log-option se <- lapply(1:length(data), function(x, De.add){ if(log.z == TRUE) { if(De.add != 0) { data[[x]][,2] <- data[[x]][,2] / (data[[x]][,1] + De.add) } else { data[[x]][,2] / data[[x]][,1] } } else { data[[x]][,2] }}, De.add = De.add) if(is(se, "list") == FALSE) { se <- list(se) } data <- lapply(1:length(data), function(x) { cbind(data[[x]], se[[x]]) }) rm(se) ## calculate initial data statistics stats.init <- list(NA) for(i in 1:length(data)) { stats.init[[length(stats.init) + 1]] <- calc_Statistics(data = data[[i]][,3:4]) } stats.init[[1]] <- NULL ## calculate central values if(z.0 == "mean") { z.central <- lapply(1:length(data), function(x){ rep(stats.init[[x]]$unweighted$mean, length(data[[x]][,3]))}) } else if(z.0 == "median") { z.central <- lapply(1:length(data), function(x){ rep(stats.init[[x]]$unweighted$median, length(data[[x]][,3]))}) } else if(z.0 == "mean.weighted") { z.central <- lapply(1:length(data), function(x){ rep(stats.init[[x]]$weighted$mean, length(data[[x]][,3]))}) } else if(is.numeric(z.0) == TRUE) { z.central <- lapply(1:length(data), function(x){ rep(ifelse(log.z == TRUE, log(z.0), z.0), length(data[[x]][,3]))}) } else { stop("Value for z.0 not supported!") } data <- lapply(1:length(data), function(x) { cbind(data[[x]], z.central[[x]])}) rm(z.central) ## calculate precision precision <- lapply(1:length(data), function(x){ 1 / data[[x]][,4]}) if(is(precision, "list") == FALSE) {precision <- list(precision)} data <- lapply(1:length(data), function(x) { cbind(data[[x]], precision[[x]])}) rm(precision) ## calculate standardised estimate std.estimate <- lapply(1:length(data), function(x){ (data[[x]][,3] - data[[x]][,5]) / data[[x]][,4]}) if(is(std.estimate, "list") == FALSE) {std.estimate <- list(std.estimate)} data <- lapply(1:length(data), function(x) { cbind(data[[x]], std.estimate[[x]])}) ## append empty standard estimate for plotting data <- lapply(1:length(data), function(x) { cbind(data[[x]], std.estimate[[x]])}) rm(std.estimate) ## append optional weights for KDE curve if("weights" %in% names(extraArgs)) { if(extraArgs$weights == TRUE) { wgt <- lapply(1:length(data), function(x){ (1 / data[[x]][,2]) / sum(1 / data[[x]][,2]^2) }) if(is(wgt, "list") == FALSE) { wgt <- list(wgt) } data <- lapply(1:length(data), function(x) { cbind(data[[x]], wgt[[x]])}) rm(wgt) } else { wgt <- lapply(1:length(data), function(x){ rep(x = 1, times = nrow(data[[x]])) / sum(rep(x = 1, times = nrow(data[[x]]))) }) if(is(wgt, "list") == FALSE) { wgt <- list(wgt) } data <- lapply(1:length(data), function(x) { cbind(data[[x]], wgt[[x]])}) rm(wgt) } } else { wgt <- lapply(1:length(data), function(x){ rep(x = 1, times = nrow(data[[x]])) / sum(rep(x = 1, times = nrow(data[[x]]))) }) if(is(wgt, "list") == FALSE) { wgt <- list(wgt) } data <- lapply(1:length(data), function(x) { cbind(data[[x]], wgt[[x]])}) rm(wgt) } ## generate global data set data.global <- cbind(data[[1]], rep(x = 1, times = nrow(data[[1]]))) colnames(data.global) <- rep("", 10) if(length(data) > 1) { for(i in 2:length(data)) { data.add <- cbind(data[[i]], rep(x = i, times = nrow(data[[i]]))) colnames(data.add) <- rep("", 10) data.global <- rbind(data.global, data.add) } } ## create column names colnames(data.global) <- c("De", "error", "z", "se", "z.central", "precision", "std.estimate", "std.estimate.plot", "weights", "data set") ## calculate global data statistics stats.global <- calc_Statistics(data = data.global[,3:4]) ## calculate global central value if(z.0 == "mean") { z.central.global <- stats.global$unweighted$mean } else if(z.0 == "median") { z.central.global <- stats.global$unweighted$median } else if(z.0 == "mean.weighted") { z.central.global <- stats.global$weighted$mean } else if(is.numeric(z.0) == TRUE) { z.central.global <- ifelse(log.z == TRUE, log(z.0), z.0) } else { stop("Value for z.0 not supported!") } ## create column names for(i in 1:length(data)) { colnames(data[[i]]) <- c("De", "error", "z", "se", "z.central", "precision", "std.estimate", "std.estimate.plot", "weights") } ## re-calculate standardised estimate for plotting for(i in 1:length(data)) { data[[i]][,8] <- (data[[i]][,3] - z.central.global) / data[[i]][,4] } data.global.plot <- data[[1]][,8] if(length(data) > 1) { for(i in 2:length(data)) { data.global.plot <- c(data.global.plot, data[[i]][,8]) } } data.global[,8] <- data.global.plot ## print message for too small scatter if(max(abs(1 / data.global[6])) < 0.02) { small.sigma <- TRUE message("[plot_AbanicoPlot()] Attention, small standardised estimate scatter. Toggle off y.axis?") } ## read out additional arguments--------------------------------------------- extraArgs <- list(...) main <- if("main" %in% names(extraArgs)) { extraArgs$main } else { expression(paste(D[e], " distribution")) } sub <- if("sub" %in% names(extraArgs)) { extraArgs$sub } else { "" } if("xlab" %in% names(extraArgs)) { if(length(extraArgs$xlab) != 2) { if (length(extraArgs$xlab) == 3) { xlab <- c(extraArgs$xlab[1:2], "Density") } else { stop("Argmuent xlab is not of length 2!") } } else {xlab <- c(extraArgs$xlab, "Density")} } else { xlab <- c(if(log.z == TRUE) { "Relative standard error (%)" } else { "Standard error" }, "Precision", "Density") } ylab <- if("ylab" %in% names(extraArgs)) { extraArgs$ylab } else { "Standardised estimate" } zlab <- if("zlab" %in% names(extraArgs)) { extraArgs$zlab } else { expression(paste(D[e], " [Gy]")) } if("zlim" %in% names(extraArgs)) { limits.z <- extraArgs$zlim } else { z.span <- (mean(data.global[,1]) * 0.5) / (sd(data.global[,1]) * 100) z.span <- ifelse(z.span > 1, 0.9, z.span) limits.z <- c((0.9 - z.span) * min(data.global[[1]]), (1.1 + z.span) * max(data.global[[1]])) } if("xlim" %in% names(extraArgs)) { limits.x <- extraArgs$xlim } else { limits.x <- c(0, max(data.global[,6]) * 1.05) } if(limits.x[1] != 0) { limits.x[1] <- 0 warning("Lower x-axis limit not set to zero, issue corrected!") } if("ylim" %in% names(extraArgs)) { limits.y <- extraArgs$ylim } else { y.span <- (mean(data.global[,1]) * 10) / (sd(data.global[,1]) * 100) y.span <- ifelse(y.span > 1, 0.98, y.span) limits.y <- c(-(1 + y.span) * max(abs(data.global[,7])), (1 + y.span) * max(abs(data.global[,7]))) } cex <- if("cex" %in% names(extraArgs)) { extraArgs$cex } else { 1 } lty <- if("lty" %in% names(extraArgs)) { extraArgs$lty } else { rep(rep(2, length(data)), length(bar)) } lwd <- if("lwd" %in% names(extraArgs)) { extraArgs$lwd } else { rep(rep(1, length(data)), length(bar)) } pch <- if("pch" %in% names(extraArgs)) { extraArgs$pch } else { rep(20, length(data)) } if("col" %in% names(extraArgs)) { bar.col <- extraArgs$col kde.line <- extraArgs$col kde.fill <- NA value.dot <- extraArgs$col value.bar <- extraArgs$col value.rug <- extraArgs$col summary.col <- extraArgs$col centrality.col <- extraArgs$col } else { if(length(layout$abanico$colour$bar) == 1) { bar.col <- 1:length(data) } else { bar.col <- layout$abanico$colour$bar.col } if(length(layout$abanico$colour$kde.line) == 1) { kde.line <- 1:length(data) } else { kde.line <- layout$abanico$colour$kde.line } if(length(layout$abanico$colour$kde.fill) == 1) { kde.fill <- rep(layout$abanico$colour$kde.fill, length(data)) } else { kde.fill <- layout$abanico$colour$kde.fill } if(length(layout$abanico$colour$value.dot) == 1) { value.dot <- 1:length(data) } else { value.dot <- layout$abanico$colour$value.dot } if(length(layout$abanico$colour$value.bar) == 1) { value.bar <- 1:length(data) } else { value.bar <- layout$abanico$colour$value.bar } if(length(layout$abanico$colour$value.rug) == 1) { value.rug <- 1:length(data) } else { value.rug <- layout$abanico$colour$value.rug } if(length(layout$abanico$colour$summary) == 1) { summary.col <- 1:length(data) } else { summary.col <- layout$abanico$colour$summary } if(length(layout$abanico$colour$centrality) == 1) { centrality.col <- rep(x = 1:length(data), times = length(bar)) } else { centrality.col <- rep(x = layout$abanico$colour$centrality, times = length(bar)) } } ## update central line colour centrality.col <- rep(centrality.col, length(bar)) tck <- if("tck" %in% names(extraArgs)) { extraArgs$tck } else { NA } tcl <- if("tcl" %in% names(extraArgs)) { extraArgs$tcl } else { -0.5 } ## define auxiliary plot parameters ----------------------------------------- ## set space between z-axis and baseline of cartesian part if(boxplot == TRUE) { lostintranslation <- 1.03 } else { lostintranslation <- 1.03 plot.ratio <- plot.ratio * 1.05 } ## create empty plot to update plot parameters if(rotate == FALSE) { plot(NA, xlim = c(limits.x[1], limits.x[2] * (1 / plot.ratio)), ylim = limits.y, main = "", sub = "", xlab = "", ylab = "", xaxs = "i", yaxs = "i", frame.plot = FALSE, axes = FALSE) } else { plot(NA, xlim = limits.y, ylim = c(limits.x[1], limits.x[2] * (1 / plot.ratio)), main = "", sub = "", xlab = "", ylab = "", xaxs = "i", yaxs = "i", frame.plot = FALSE, axes = FALSE) } ## calculate conversion factor for plot coordinates f <- 0 ## calculate major and minor z-tick values if("at" %in% names(extraArgs)) { tick.values.major <- extraArgs$at tick.values.minor <- extraArgs$at } else { tick.values.major <- signif(pretty(limits.z, n = 5), 3) tick.values.minor <- signif(pretty(limits.z, n = 25), 3) } tick.values.major <- tick.values.major[tick.values.major >= min(tick.values.minor)] tick.values.major <- tick.values.major[tick.values.major <= max(tick.values.minor)] tick.values.major <- tick.values.major[tick.values.major >= limits.z[1]] tick.values.major <- tick.values.major[tick.values.major <= limits.z[2]] tick.values.minor <- tick.values.minor[tick.values.minor >= limits.z[1]] tick.values.minor <- tick.values.minor[tick.values.minor <= limits.z[2]] if(log.z == TRUE) { tick.values.major[which(tick.values.major==0)] <- 1 tick.values.minor[which(tick.values.minor==0)] <- 1 tick.values.major <- log(tick.values.major) tick.values.minor <- log(tick.values.minor) } ## calculate z-axis radius r <- max(sqrt((limits.x[2])^2 + (data.global[,7] * f)^2)) ## create z-axes labels if(log.z == TRUE) { label.z.text <- signif(exp(tick.values.major), 3) } else { label.z.text <- signif(tick.values.major, 3) } ## calculate node coordinates for semi-circle ellipse.values <- c(min(ifelse(log.z == TRUE, log(limits.z[1]), limits.z[1]), tick.values.major, tick.values.minor), max(ifelse(log.z == TRUE, log(limits.z[2]), limits.z[2]), tick.values.major, tick.values.minor)) ## correct for unpleasant value ellipse.values[ellipse.values == -Inf] <- 0 if(rotate == FALSE) { ellipse.x <- r / sqrt(1 + f^2 * (ellipse.values - z.central.global)^2) ellipse.y <- (ellipse.values - z.central.global) * ellipse.x } else { ellipse.y <- r / sqrt(1 + f^2 * (ellipse.values - z.central.global)^2) ellipse.x <- (ellipse.values - z.central.global) * ellipse.y } ellipse <- cbind(ellipse.x, ellipse.y) ## calculate statistical labels if(length(stats == 1)) {stats <- rep(stats, 2)} stats.data <- matrix(nrow = 3, ncol = 3) data.stats <- as.numeric(data.global[,1]) if("min" %in% stats == TRUE) { stats.data[1, 3] <- data.stats[data.stats == min(data.stats)][1] stats.data[1, 1] <- data.global[data.stats == stats.data[1, 3], 6][1] stats.data[1, 2] <- data.global[data.stats == stats.data[1, 3], 8][1] } if("max" %in% stats == TRUE) { stats.data[2, 3] <- data.stats[data.stats == max(data.stats)][1] stats.data[2, 1] <- data.global[data.stats == stats.data[2, 3], 6][1] stats.data[2, 2] <- data.global[data.stats == stats.data[2, 3], 8][1] } if("median" %in% stats == TRUE) { stats.data[3, 3] <- data.stats[data.stats == quantile(data.stats, 0.5, type = 3)] stats.data[3, 1] <- data.global[data.stats == stats.data[3, 3], 6][1] stats.data[3, 2] <- data.global[data.stats == stats.data[3, 3], 8][1] } ## re-calculate axes limits if necessary if(rotate == FALSE) { limits.z.x <- range(ellipse[,1]) limits.z.y <- range(ellipse[,2]) } else { limits.z.x <- range(ellipse[,2]) limits.z.y <- range(ellipse[,1]) } if(!("ylim" %in% names(extraArgs))) { if(limits.z.y[1] < 0.66 * limits.y[1]) { limits.y[1] <- 1.8 * limits.z.y[1] } if(limits.z.y[2] > 0.77 * limits.y[2]) { limits.y[2] <- 1.3 * limits.z.y[2] } if(rotate == TRUE) { limits.y <- c(-max(abs(limits.y)), max(abs(limits.y))) } } if(!("xlim" %in% names(extraArgs))) { if(limits.z.x[2] > 1.1 * limits.x[2]) { limits.x[2] <- limits.z.x[2] } } ## calculate and paste statistical summary De.stats <- matrix(nrow = length(data), ncol = 12) colnames(De.stats) <- c("n", "mean", "median", "kde.max", "sd.abs", "sd.rel", "se.abs", "se.rel", "q.25", "q.75", "skewness", "kurtosis") for(i in 1:length(data)) { statistics <- calc_Statistics(data[[i]])[[summary.method]] statistics.2 <- calc_Statistics(data[[i]][,3:4])[[summary.method]] De.stats[i,1] <- statistics$n De.stats[i,2] <- statistics.2$mean De.stats[i,3] <- statistics.2$median De.stats[i,5] <- statistics$sd.abs De.stats[i,6] <- statistics$sd.rel De.stats[i,7] <- statistics$se.abs De.stats[i,8] <- statistics$se.rel De.stats[i,9] <- quantile(data[[i]][,1], 0.25) De.stats[i,10] <- quantile(data[[i]][,1], 0.75) De.stats[i,11] <- statistics$skewness De.stats[i,12] <- statistics$kurtosis ## account for log.z-option if(log.z == TRUE) { De.stats[i,2:4] <- exp(De.stats[i,2:4]) } ## kdemax - here a little doubled as it appears below again De.density <- try(density(x = data[[i]][,1], kernel = "gaussian", bw = bw, from = limits.z[1], to = limits.z[2]), silent = TRUE) if(inherits(De.density, "try-error")) { De.stats[i,4] <- NA } else { De.stats[i,4] <- De.density$x[which.max(De.density$y)] } } label.text = list(NA) if(summary.pos[1] != "sub") { n.rows <- length(summary) for(i in 1:length(data)) { stops <- paste(rep("\n", (i - 1) * n.rows), collapse = "") summary.text <- character(0) for(j in 1:length(summary)) { summary.text <- c(summary.text, paste( "", ifelse("n" %in% summary[j] == TRUE, paste("n = ", De.stats[i,1], "\n", sep = ""), ""), ifelse("mean" %in% summary[j] == TRUE, paste("mean = ", round(De.stats[i,2], 2), "\n", sep = ""), ""), ifelse("median" %in% summary[j] == TRUE, paste("median = ", round(De.stats[i,3], 2), "\n", sep = ""), ""), ifelse("kde.max" %in% summary[j] == TRUE, paste("kdemax = ", round(De.stats[i,4], 2), " \n ", sep = ""), ""), ifelse("sd.abs" %in% summary[j] == TRUE, paste("abs. sd = ", round(De.stats[i,5], 2), "\n", sep = ""), ""), ifelse("sd.rel" %in% summary[j] == TRUE, paste("rel. sd = ", round(De.stats[i,6], 2), " %", "\n", sep = ""), ""), ifelse("se.abs" %in% summary[j] == TRUE, paste("se = ", round(De.stats[i,7], 2), "\n", sep = ""), ""), ifelse("se.rel" %in% summary[j] == TRUE, paste("rel. se = ", round(De.stats[i,8], 2), " %", "\n", sep = ""), ""), ifelse("skewness" %in% summary[j] == TRUE, paste("skewness = ", round(De.stats[i,11], 2), "\n", sep = ""), ""), ifelse("kurtosis" %in% summary[j] == TRUE, paste("kurtosis = ", round(De.stats[i,12], 2), "\n", sep = ""), ""), ifelse("in.2s" %in% summary[j] == TRUE, paste("in 2 sigma = ", round(sum(data[[i]][,7] > -2 & data[[i]][,7] < 2) / nrow(data[[i]]) * 100 , 1), " %", sep = ""), ""), sep = "")) } summary.text <- paste(summary.text, collapse = "") label.text[[length(label.text) + 1]] <- paste(stops, summary.text, stops, sep = "") } } else { for(i in 1:length(data)) { summary.text <- character(0) for(j in 1:length(summary)) { summary.text <- c(summary.text, ifelse("n" %in% summary[j] == TRUE, paste("n = ", De.stats[i,1], " | ", sep = ""), ""), ifelse("mean" %in% summary[j] == TRUE, paste("mean = ", round(De.stats[i,2], 2), " | ", sep = ""), ""), ifelse("median" %in% summary[j] == TRUE, paste("median = ", round(De.stats[i,3], 2), " | ", sep = ""), ""), ifelse("kde.max" %in% summary[j] == TRUE, paste("kdemax = ", round(De.stats[i,4], 2), " | ", sep = ""), ""), ifelse("sd.abs" %in% summary[j] == TRUE, paste("abs. sd = ", round(De.stats[i,5], 2), " | ", sep = ""), ""), ifelse("sd.rel" %in% summary[j] == TRUE, paste("rel. sd = ", round(De.stats[i,6], 2), " %", " | ", sep = ""), ""), ifelse("se.abs" %in% summary[j] == TRUE, paste("abs. se = ", round(De.stats[i,7], 2), " | ", sep = ""), ""), ifelse("se.rel" %in% summary[j] == TRUE, paste("rel. se = ", round(De.stats[i,8], 2), " %", " | ", sep = ""), ""), ifelse("skewness" %in% summary[j] == TRUE, paste("skewness = ", round(De.stats[i,11], 2), " | ", sep = ""), ""), ifelse("kurtosis" %in% summary[j] == TRUE, paste("kurtosis = ", round(De.stats[i,12], 2), " | ", sep = ""), ""), ifelse("in.2s" %in% summary[j] == TRUE, paste("in 2 sigma = ", round(sum(data[[i]][,7] > -2 & data[[i]][,7] < 2) / nrow(data[[i]]) * 100 , 1), " % | ", sep = ""), "") ) } summary.text <- paste(summary.text, collapse = "") label.text[[length(label.text) + 1]] <- paste( " ", summary.text, sep = "") } ## remove outer vertical lines from string for(i in 2:length(label.text)) { label.text[[i]] <- substr(x = label.text[[i]], start = 3, stop = nchar(label.text[[i]]) - 3) } } ## remove dummy list element label.text[[1]] <- NULL if(rotate == FALSE) { ## convert keywords into summary placement coordinates if(missing(summary.pos) == TRUE) { summary.pos <- c(limits.x[1], limits.y[2]) summary.adj <- c(0, 1) } else if(length(summary.pos) == 2) { summary.pos <- summary.pos summary.adj <- c(0, 1) } else if(summary.pos[1] == "topleft") { summary.pos <- c(limits.x[1], limits.y[2] - par()$cxy[2] * 1) summary.adj <- c(0, 1) } else if(summary.pos[1] == "top") { summary.pos <- c(mean(limits.x), limits.y[2] - par()$cxy[2] * 1) summary.adj <- c(0.5, 1) } else if(summary.pos[1] == "topright") { summary.pos <- c(limits.x[2], limits.y[2] - par()$cxy[2] * 1) summary.adj <- c(1, 1) } else if(summary.pos[1] == "left") { summary.pos <- c(limits.x[1], mean(limits.y)) summary.adj <- c(0, 0.5) } else if(summary.pos[1] == "center") { summary.pos <- c(mean(limits.x), mean(limits.y)) summary.adj <- c(0.5, 0.5) } else if(summary.pos[1] == "right") { summary.pos <- c(limits.x[2], mean(limits.y)) summary.adj <- c(1, 0.5) }else if(summary.pos[1] == "bottomleft") { summary.pos <- c(limits.x[1], limits.y[1] + par()$cxy[2] * 3.5) summary.adj <- c(0, 0) } else if(summary.pos[1] == "bottom") { summary.pos <- c(mean(limits.x), limits.y[1] + par()$cxy[2] * 3.5) summary.adj <- c(0.5, 0) } else if(summary.pos[1] == "bottomright") { summary.pos <- c(limits.x[2], limits.y[1] + par()$cxy[2] * 3.5) summary.adj <- c(1, 0) } ## convert keywords into legend placement coordinates if(missing(legend.pos) == TRUE) { legend.pos <- c(limits.x[1], limits.y[2]) legend.adj <- c(0, 1) } else if(length(legend.pos) == 2) { legend.pos <- legend.pos legend.adj <- c(0, 1) } else if(legend.pos[1] == "topleft") { legend.pos <- c(limits.x[1], limits.y[2]) legend.adj <- c(0, 1) } else if(legend.pos[1] == "top") { legend.pos <- c(mean(limits.x), limits.y[2]) legend.adj <- c(0.5, 1) } else if(legend.pos[1] == "topright") { legend.pos <- c(limits.x[2], limits.y[2]) legend.adj <- c(1, 1) } else if(legend.pos[1] == "left") { legend.pos <- c(limits.x[1], mean(limits.y)) legend.adj <- c(0, 0.5) } else if(legend.pos[1] == "center") { legend.pos <- c(mean(limits.x), mean(limits.y)) legend.adj <- c(0.5, 0.5) } else if(legend.pos[1] == "right") { legend.pos <- c(limits.x[2], mean(limits.y)) legend.adj <- c(1, 0.5) } else if(legend.pos[1] == "bottomleft") { legend.pos <- c(limits.x[1], limits.y[1]) legend.adj <- c(0, 0) } else if(legend.pos[1] == "bottom") { legend.pos <- c(mean(limits.x), limits.y[1]) legend.adj <- c(0.5, 0) } else if(legend.pos[1] == "bottomright") { legend.pos <- c(limits.x[2], limits.y[1]) legend.adj <- c(1, 0) } } else { ## convert keywords into summary placement coordinates if(missing(summary.pos) == TRUE) { summary.pos <- c(limits.y[1] + par()$cxy[1] * 7.5, limits.x[1]) summary.adj <- c(0, 0) } else if(length(summary.pos) == 2) { summary.pos <- summary.pos summary.adj <- c(0, 1) } else if(summary.pos[1] == "topleft") { summary.pos <- c(limits.y[1] + par()$cxy[1] * 7.5, limits.x[2]) summary.adj <- c(0, 1) } else if(summary.pos[1] == "top") { summary.pos <- c(mean(limits.y), limits.x[2]) summary.adj <- c(0.5, 1) } else if(summary.pos[1] == "topright") { summary.pos <- c(limits.y[2], limits.x[2]) summary.adj <- c(1, 1) } else if(summary.pos[1] == "left") { summary.pos <- c(limits.y[1] + par()$cxy[1] * 7.5, mean(limits.x)) summary.adj <- c(0, 0.5) } else if(summary.pos[1] == "center") { summary.pos <- c(mean(limits.y), mean(limits.x)) summary.adj <- c(0.5, 0.5) } else if(summary.pos[1] == "right") { summary.pos <- c(limits.y[2], mean(limits.x)) summary.adj <- c(1, 0.5) }else if(summary.pos[1] == "bottomleft") { summary.pos <- c(limits.y[1] + par()$cxy[1] * 7.5, limits.x[1]) summary.adj <- c(0, 0) } else if(summary.pos[1] == "bottom") { summary.pos <- c(mean(limits.y), limits.x[1]) summary.adj <- c(0.5, 0) } else if(summary.pos[1] == "bottomright") { summary.pos <- c(limits.y[2], limits.x[1]) summary.adj <- c(1, 0) } ## convert keywords into legend placement coordinates if(missing(legend.pos) == TRUE) { legend.pos <- c(limits.y[1] + par()$cxy[1] * 7.5, limits.x[1]) legend.adj <- c(0, 0) } else if(length(legend.pos) == 2) { legend.pos <- legend.pos legend.adj <- c(1, 0) } else if(legend.pos[1] == "topleft") { legend.pos <- c(limits.y[1] + par()$cxy[1] * 11, limits.x[2]) legend.adj <- c(1, 0) } else if(legend.pos[1] == "top") { legend.pos <- c(mean(limits.y), limits.x[2]) legend.adj <- c(1, 0.5) } else if(legend.pos[1] == "topright") { legend.pos <- c(limits.y[2], limits.x[2]) legend.adj <- c(1, 1) } else if(legend.pos[1] == "left") { legend.pos <- c(limits.y[1] + par()$cxy[1] * 7.5, mean(limits.x)) legend.adj <- c(0.5, 0) } else if(legend.pos[1] == "center") { legend.pos <- c(mean(limits.y), mean(limits.x)) legend.adj <- c(0.5, 0.5) } else if(legend.pos[1] == "right") { legend.pos <- c(limits.y[2], mean(limits.x)) legend.adj <- c(0.5, 1) } else if(legend.pos[1] == "bottomleft") { legend.pos <- c(limits.y[1] + par()$cxy[1] * 7.5, limits.x[1]) legend.adj <- c(0, 0) } else if(legend.pos[1] == "bottom") { legend.pos <- c(mean(limits.y), limits.x[1]) legend.adj <- c(0, 0.5) } else if(legend.pos[1] == "bottomright") { legend.pos <- c(limits.y[2], limits.x[1]) legend.adj <- c(0, 1) } } ## define cartesian plot origins if(rotate == FALSE) { xy.0 <- c(min(ellipse[,1]) * lostintranslation, min(ellipse[,2])) } else { xy.0 <- c(min(ellipse[,1]), min(ellipse[,2]) * lostintranslation) } ## calculate coordinates for dispersion polygon overlay y.max.x <- 2 * limits.x[2] / max(data.global[6]) polygons <- matrix(nrow = length(data), ncol = 14) for(i in 1:length(data)) { if(dispersion == "qr") { ci.lower <- quantile(data[[i]][,1], 0.25) ci.upper <- quantile(data[[i]][,1], 0.75) } else if(grepl(x = dispersion, pattern = "p") == TRUE) { ci.plot <- as.numeric(strsplit(x = dispersion, split = "p")[[1]][2]) ci.plot <- (100 - ci.plot) / 100 ci.lower <- quantile(data[[i]][,1], ci.plot) ci.upper <- quantile(data[[i]][,1], 1 - ci.plot) } else if(dispersion == "sd") { if(log.z == TRUE) { ci.lower <- exp(mean(log(data[[i]][,1])) - sd(log(data[[i]][,1]))) ci.upper <- exp(mean(log(data[[i]][,1])) + sd(log(data[[i]][,1]))) } else { ci.lower <- mean(data[[i]][,1]) - sd(data[[i]][,1]) ci.upper <- mean(data[[i]][,1]) + sd(data[[i]][,1]) } } else if(dispersion == "2sd") { if(log.z == TRUE) { ci.lower <- exp(mean(log(data[[i]][,1])) - 2 * sd(log(data[[i]][,1]))) ci.upper <- exp(mean(log(data[[i]][,1])) + 2 * sd(log(data[[i]][,1]))) } else { ci.lower <- mean(data[[i]][,1]) - 2 * sd(data[[i]][,1]) ci.upper <- mean(data[[i]][,1]) + 2 * sd(data[[i]][,1]) } } else { stop("Measure of dispersion not supported.") } if(log.z == TRUE) { ci.lower[which(ci.lower < 0)] <- 1 y.lower <- log(ci.lower) y.upper <- log(ci.upper) } else { y.lower <- ci.lower y.upper <- ci.upper } if(rotate == FALSE) { polygons[i,1:7] <- c(limits.x[1], limits.x[2], xy.0[1], par()$usr[2], par()$usr[2], xy.0[1], limits.x[2]) polygons[i,8:14] <- c(0, (y.upper - z.central.global) * limits.x[2], (y.upper - z.central.global) * xy.0[1], (y.upper - z.central.global) * xy.0[1], (y.lower - z.central.global) * xy.0[1], (y.lower - z.central.global) * xy.0[1], (y.lower - z.central.global) * limits.x[2] ) } else { y.max <- par()$usr[4] polygons[i,1:7] <- c(limits.x[1], limits.x[2], xy.0[2], y.max, y.max, xy.0[2], limits.x[2]) polygons[i,8:14] <- c(0, (y.upper - z.central.global) * limits.x[2], (y.upper - z.central.global) * xy.0[2], (y.upper - z.central.global) * xy.0[2], (y.lower - z.central.global) * xy.0[2], (y.lower - z.central.global) * xy.0[2], (y.lower - z.central.global) * limits.x[2] ) } } ## append information about data in confidence interval for(i in 1:length(data)) { data.in.2s <- rep(x = FALSE, times = nrow(data[[i]])) data.in.2s[data[[i]][,8] > -2 & data[[i]][,8] < 2] <- TRUE data[[i]] <- cbind(data[[i]], data.in.2s) } ## calculate coordinates for 2-sigma bar overlay if(bar[1] == TRUE) { bars <- matrix(nrow = length(data), ncol = 8) for(i in 1:length(data)) { bars[i,1:4] <- c(limits.x[1], limits.x[1], ifelse("xlim" %in% names(extraArgs), extraArgs$xlim[2] * 0.95, max(data.global$precision)), ifelse("xlim" %in% names(extraArgs), extraArgs$xlim[2] * 0.95, max(data.global$precision))) bars[i,5:8] <- c(-2, 2, (data[[i]][1,5] - z.central.global) * bars[i,3] + 2, (data[[i]][1,5] - z.central.global) * bars[i,3] - 2) } } else { bars <- matrix(nrow = length(bar), ncol = 8) if(is.numeric(bar) == TRUE & log.z == TRUE) { bar <- log(bar) } for(i in 1:length(bar)) { bars[i,1:4] <- c(limits.x[1], limits.x[1], ifelse("xlim" %in% names(extraArgs), extraArgs$xlim[2] * 0.95, max(data.global$precision)), ifelse("xlim" %in% names(extraArgs), extraArgs$xlim[2] * 0.95, max(data.global$precision))) bars[i,5:8] <- c(-2, 2, (bar[i] - z.central.global) * bars[i,3] + 2, (bar[i] - z.central.global) * bars[i,3] - 2) } } if (rotate == TRUE) { bars <- matrix(bars[, rev(seq_len(ncol(bars)))], ncol = 8) } ## calculate error bar coordinates if(error.bars == TRUE) { arrow.coords <- list(NA) for(i in 1:length(data)) { arrow.x1 <- data[[i]][,6] arrow.x2 <- data[[i]][,6] arrow.y1 <- data[[i]][,1] - data[[i]][,2] arrow.y2 <- data[[i]][,1] + data[[i]][,2] if(log.z == TRUE) { arrow.y1 <- log(arrow.y1) arrow.y2 <- log(arrow.y2) } arrow.coords[[length(arrow.coords) + 1]] <- cbind( arrow.x1, arrow.x2, (arrow.y1 - z.central.global) * arrow.x1, (arrow.y2 - z.central.global) * arrow.x1) } arrow.coords[[1]] <- NULL } ## calculate KDE KDE <- list(NA) KDE.ext <- 0 KDE.bw <- numeric(0) for(i in 1:length(data)) { KDE.i <- density(x = data[[i]][,3], kernel = "gaussian", bw = bw, from = ellipse.values[1], to = ellipse.values[2], weights = data[[i]]$weights) KDE.xy <- cbind(KDE.i$x, KDE.i$y) KDE.bw <- c(KDE.bw, KDE.i$bw) KDE.ext <- ifelse(max(KDE.xy[,2]) < KDE.ext, KDE.ext, max(KDE.xy[,2])) KDE.xy <- rbind(c(min(KDE.xy[,1]), 0), KDE.xy, c(max(KDE.xy[,1]), 0)) KDE[[length(KDE) + 1]] <- cbind(KDE.xy[,1], KDE.xy[,2]) } KDE[1] <- NULL ## calculate mean KDE bandwidth KDE.bw <- mean(KDE.bw, na.rm = TRUE) ## calculate max KDE value for labelling KDE.max.plot <- numeric(length(data)) for(i in 1:length(data)) { KDE.plot <- density(x = data[[i]][,1], kernel = "gaussian", bw = bw, from = limits.z[1], to = limits.z[2]) KDE.max.plot[i] <- max(KDE.plot$y) } KDE.max.plot <- max(KDE.max.plot, na.rm = TRUE) ## calculate histogram data without plotting ## create dummy list hist.data <- list(NA) for(i in 1:length(data)) { hist.i <- hist(x = data[[i]][,3], plot = FALSE, breaks = breaks) hist.data[[length(hist.data) + 1]] <- hist.i } ## remove dummy list object hist.data[[1]] <- NULL ## calculate maximum histogram bar height for normalisation hist.max.plot <- numeric(length(data)) for(i in 1:length(data)) { hist.max.plot <- ifelse(max(hist.data[[i]]$counts, na.rm = TRUE) > hist.max.plot, max(hist.data[[i]]$counts, na.rm = TRUE), hist.max.plot) } hist.max.plot <- max(hist.max.plot, na.rm = TRUE) ## normalise histogram bar height to KDE dimensions for(i in 1:length(data)) { hist.data[[i]]$density <- hist.data[[i]]$counts / hist.max.plot * KDE.max.plot } ## calculate boxplot data without plotting ## create dummy list boxplot.data <- list(NA) for(i in 1:length(data)) { boxplot.i <- boxplot(x = data[[i]][,3], plot = FALSE) boxplot.data[[length(boxplot.data) + 1]] <- boxplot.i } ## remove dummy list object boxplot.data[[1]] <- NULL ## calculate line coordinates and further parameters if(missing(line) == FALSE) { ## check if line parameters are R.Lum-objects for(i in 1:length(line)) { if(is.list(line) == TRUE) { if(is(line[[i]], "RLum.Results")) { line[[i]] <- as.numeric(get_RLum(object = line[[i]], data.object = "summary")$de) } } else if(is(object = line, class2 = "RLum.Results")) { line <- as.numeric(get_RLum(object = line, data.object = "summary")$de) } } ## convert list to vector if(is.list(line) == TRUE) { line <- unlist(line) } if(log.z == TRUE) { line <- log(line) } line.coords <- list(NA) if(rotate == FALSE) { for(i in 1:length(line)) { line.x <- c(limits.x[1], min(ellipse[,1]), par()$usr[2]) line.y <- c(0, (line[i] - z.central.global) * min(ellipse[,1]), (line[i] - z.central.global) * min(ellipse[,1])) line.coords[[length(line.coords) + 1]] <- rbind(line.x, line.y) } } else { for(i in 1:length(line)) { line.x <- c(limits.x[1], min(ellipse[,2]),y.max) line.y <- c(0, (line[i] - z.central.global) * min(ellipse[,2]), (line[i] - z.central.global) * min(ellipse[,2])) line.coords[[length(line.coords) + 1]] <- rbind(line.x, line.y) } } line.coords[1] <- NULL if(missing(line.col) == TRUE) { line.col <- seq(from = 1, to = length(line.coords)) } if(missing(line.lty) == TRUE) { line.lty <- rep(1, length(line.coords)) } if(missing(line.label) == TRUE) { line.label <- rep("", length(line.coords)) } } ## calculate rug coordinates if(missing(rug) == FALSE) { if(log.z == TRUE) { rug.values <- log(De.global) } else { rug.values <- De.global } rug.coords <- list(NA) if(rotate == FALSE) { for(i in 1:length(rug.values)) { rug.x <- c(xy.0[1] * (1 - 0.013 * (layout$abanico$dimension$rugl / 100)), xy.0[1]) rug.y <- c((rug.values[i] - z.central.global) * min(ellipse[,1]), (rug.values[i] - z.central.global) * min(ellipse[,1])) rug.coords[[length(rug.coords) + 1]] <- rbind(rug.x, rug.y) } } else { for(i in 1:length(rug.values)) { rug.x <- c(xy.0[2] * (1 - 0.013 * (layout$abanico$dimension$rugl / 100)), xy.0[2]) rug.y <- c((rug.values[i] - z.central.global) * min(ellipse[,2]), (rug.values[i] - z.central.global) * min(ellipse[,2])) rug.coords[[length(rug.coords) + 1]] <- rbind(rug.x, rug.y) } } rug.coords[1] <- NULL } ## Generate plot ------------------------------------------------------------ ## determine number of subheader lines to shift the plot if(length(summary) > 0 & summary.pos[1] == "sub") { shift.lines <- (length(data) + 1) * layout$abanico$dimension$summary.line/100 } else {shift.lines <- 1} ## extract original plot parameters bg.original <- par()$bg on.exit(par(bg = bg.original), add = TRUE) par(bg = layout$abanico$colour$background) if(rotate == FALSE) { ## setup plot area par(mar = c(4.5, 4.5, shift.lines + 1.5, 7), xpd = TRUE, cex = cex) if(layout$abanico$dimension$figure.width != "auto" | layout$abanico$dimension$figure.height != "auto") { par(mai = layout$abanico$dimension$margin / 25.4, pin = c(layout$abanico$dimension$figure.width / 25.4 - layout$abanico$dimension$margin[2] / 25.4 - layout$abanico$dimension$margin[4] / 25.4, layout$abanico$dimension$figure.height / 25.4 - layout$abanico$dimension$margin[1] / 25.4 - layout$abanico$dimension$margin[3]/25.4)) } ## create empty plot par(new = TRUE) plot(NA, xlim = c(limits.x[1], limits.x[2] * (1 / plot.ratio)), ylim = limits.y, main = "", sub = sub, xlab = "", ylab = "", xaxs = "i", yaxs = "i", frame.plot = FALSE, axes = FALSE) ## add y-axis label mtext(text = ylab, at = mean(x = c(min(ellipse[,2]), max(ellipse[,2])), na.rm = TRUE), # at = 0, ## BUG FROM VERSION 0.4.0, maybe removed in future adj = 0.5, side = 2, line = 3 * layout$abanico$dimension$ylab.line / 100, col = layout$abanico$colour$ylab, family = layout$abanico$font.type$ylab, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$ylab)[1], cex = cex * layout$abanico$font.size$ylab/12) ## calculate upper x-axis label values label.x.upper <- if(log.z == TRUE) { as.character(round(1/axTicks(side = 1)[-1] * 100, 1)) } else { as.character(round(1/axTicks(side = 1)[-1], 1)) } # optionally, plot 2-sigma-bar if(bar[1] != FALSE) { for(i in 1:length(bar)) { polygon(x = bars[i,1:4], y = bars[i,5:8], col = bar.fill[i], border = bar.line[i]) } } ## remove unwanted parts polygon(x = c(par()$usr[2], par()$usr[2], par()$usr[2] * 2, par()$usr[2] * 2), y = c(min(ellipse[,2]) * 2, max(ellipse[,2]) * 2, max(ellipse[,2]) * 2, min(ellipse[,2]) * 2), col = bg.original, lty = 0) ## optionally, plot dispersion polygon if(polygon.fill[1] != "none") { for(i in 1:length(data)) { polygon(x = polygons[i,1:7], y = polygons[i,8:14], col = polygon.fill[i], border = polygon.line[i]) } } ## optionally, add minor grid lines if(grid.minor != "none") { for(i in 1:length(tick.values.minor)) { lines(x = c(limits.x[1], min(ellipse[,1])), y = c(0, (tick.values.minor[i] - z.central.global) * min(ellipse[,1])), col = grid.minor, lwd = 1) } for(i in 1:length(tick.values.minor)) { lines(x = c(xy.0[1], par()$usr[2]), y = c((tick.values.minor[i] - z.central.global) * min(ellipse[,1]), (tick.values.minor[i] - z.central.global) * min(ellipse[,1])), col = grid.minor, lwd = 1) } } ## optionally, add major grid lines if(grid.major != "none") { for(i in 1:length(tick.values.major)) { lines(x = c(limits.x[1], min(ellipse[,1])), y = c(0, (tick.values.major[i] - z.central.global) * min(ellipse[,1])), col = grid.major, lwd = 1) } for(i in 1:length(tick.values.major)) { lines(x = c(xy.0[1], par()$usr[2]), y = c((tick.values.major[i] - z.central.global) * min(ellipse[,1]), (tick.values.major[i] - z.central.global) * min(ellipse[,1])), col = grid.major, lwd = 1) } } ## optionally, plot lines for each bar if(lwd[1] > 0 & lty[1] > 0 & bar[1] != FALSE & length(data) == 1) { if(bar[1] == TRUE & length(bar) == 1) { bar[1] <- z.central.global } for(i in 1:length(bar)) { x2 <- r / sqrt(1 + f^2 * ( bar[i] - z.central.global)^2) y2 <- (bar[i] - z.central.global) * x2 lines(x = c(limits.x[1], x2, xy.0[1], par()$usr[2]), y = c(0, y2, y2, y2), lty = lty[i], lwd = lwd[i], col = centrality.col[i]) } } else if(lwd[1] > 0 & lty[1] > 0 & bar[1] != FALSE) { for(i in 1:length(data)) { z.line <- ifelse(test = is.numeric(bar[i]) == TRUE, yes = bar[i], no = data[[i]][1,5]) x2 <- r / sqrt(1 + f^2 * ( z.line - z.central.global)^2) y2 <- (z.line - z.central.global) * x2 lines(x = c(limits.x[1], x2, xy.0[1], par()$usr[2]), y = c(0, y2, y2, y2), lty = lty[i], lwd = lwd[i], col = centrality.col[i]) } } ## optionally add further lines if(missing(line) == FALSE) { for(i in 1:length(line)) { lines(x = line.coords[[i]][1,1:3], y = line.coords[[i]][2,1:3], col = line.col[i], lty = line.lty[i] ) text(x = line.coords[[i]][1,3], y = line.coords[[i]][2,3] + par()$cxy[2] * 0.3, labels = line.label[i], pos = 2, col = line.col[i], cex = cex * 0.9) } } ## add plot title cex.old <- par()$cex par(cex = layout$abanico$font.size$main / 12) title(main = main, family = layout$abanico$font.type$main, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$main)[1], col.main = layout$abanico$colour$main, line = shift.lines * layout$abanico$dimension$main / 100) par(cex = cex.old) ## calculate lower x-axis (precision) x.axis.ticks <- axTicks(side = 1) x.axis.ticks <- x.axis.ticks[c(TRUE, x.axis.ticks <= limits.x[2])] x.axis.ticks <- x.axis.ticks[x.axis.ticks <= max(ellipse[,1])] ## x-axis with lables and ticks axis(side = 1, at = x.axis.ticks, col = layout$abanico$colour$xtck1, col.axis = layout$abanico$colour$xtck1, labels = NA, tcl = -layout$abanico$dimension$xtcl1 / 200, cex = cex) axis(side = 1, at = x.axis.ticks, line = 2 * layout$abanico$dimension$xtck1.line / 100 - 2, lwd = 0, col = layout$abanico$colour$xtck1, family = layout$abanico$font.type$xtck1, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$xtck1)[1], col.axis = layout$abanico$colour$xtck1, cex.axis = layout$abanico$font.size$xlab1/12) ## extend axis line to right side of the plot lines(x = c(max(x.axis.ticks), max(ellipse[,1])), y = c(limits.y[1], limits.y[1]), col = layout$abanico$colour$xtck1) ## draw closing tick on right hand side axis(side = 1, tcl = -layout$abanico$dimension$xtcl1 / 200, lwd = 0, lwd.ticks = 1, at = limits.x[2], labels = FALSE, col = layout$abanico$colour$xtck1) axis(side = 1, tcl = layout$abanico$dimension$xtcl2 / 200, lwd = 0, lwd.ticks = 1, at = limits.x[2], labels = FALSE, col = layout$abanico$colour$xtck2) ## add lower axis label mtext(xlab[2], at = (limits.x[1] + max(ellipse[,1])) / 2, side = 1, line = 2.5 * layout$abanico$dimension$xlab1.line / 100, col = layout$abanico$colour$xlab1, family = layout$abanico$font.type$xlab1, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$xlab1)[1], cex = cex * layout$abanico$font.size$xlab1/12) ## add upper axis label mtext(xlab[1], at = (limits.x[1] + max(ellipse[,1])) / 2, side = 1, line = -3.5 * layout$abanico$dimension$xlab2.line / 100, col = layout$abanico$colour$xlab2, family = layout$abanico$font.type$xlab2, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$xlab2)[1], cex = cex * layout$abanico$font.size$xlab2/12) ## plot upper x-axis axis(side = 1, at = x.axis.ticks[-1], col = layout$abanico$colour$xtck2, col.axis = layout$abanico$colour$xtck2, labels = NA, tcl = layout$abanico$dimension$xtcl2 / 200, cex = cex) ## remove first tick label (infinity) label.x.upper <- label.x.upper[1:(length(x.axis.ticks) - 1)] axis(side = 1, at = x.axis.ticks[-1], labels = label.x.upper, line = -1 * layout$abanico$dimension$xtck2.line / 100 - 2, lwd = 0, col = layout$abanico$colour$xtck2, family = layout$abanico$font.type$xtck2, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$xtck2)[1], col.axis = layout$abanico$colour$xtck2, cex.axis = layout$abanico$font.size$xlab2/12) ## plot y-axis if(is.null(extraArgs$yaxt) || extraArgs$yaxt != "n"){ if(y.axis) { char.height <- par()$cxy[2] tick.space <- axisTicks(usr = limits.y, log = FALSE) tick.space <- (max(tick.space) - min(tick.space)) / length(tick.space) if(tick.space < char.height * 1.7) { axis(side = 2, tcl = -layout$abanico$dimension$ytcl / 200, lwd = 1, lwd.ticks = 1, at = c(-2, 2), labels = c("", ""), las = 1, col = layout$abanico$colour$ytck) axis(side = 2, at = 0, tcl = 0, line = 2 * layout$abanico$dimension$ytck.line / 100 - 2, labels = paste("\u00B1", "2"), las = 1, family = layout$abanico$font.type$ytck, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$ytck)[1], col.axis = layout$abanico$colour$ytck, cex.axis = layout$abanico$font.size$ylab/12) } else { axis(side = 2, at = seq(-2, 2, by = 2), col = layout$abanico$colour$ytck, col.axis = layout$abanico$colour$ytck, labels = NA, las = 1, tcl = -layout$abanico$dimension$ytcl / 200, cex = cex) axis(side = 2, at = seq(-2, 2, by = 2), line = 2 * layout$abanico$dimension$ytck.line / 100 - 2, lwd = 0, las = 1, col = layout$abanico$colour$ytck, family = layout$abanico$font.type$ytck, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$ytck)[1], col.axis = layout$abanico$colour$ytck, cex.axis = layout$abanico$font.size$ylab/12) } } else { axis(side = 2, at = 0, col = layout$abanico$colour$ytck, col.axis = layout$abanico$colour$ytck, labels = NA, las = 1, tcl = -layout$abanico$dimension$ytcl / 200, cex = cex) axis(side = 2, at = 0, line = 2 * layout$abanico$dimension$ytck.line / 100 - 2, lwd = 0, las = 1, col = layout$abanico$colour$ytck, family = layout$abanico$font.type$ytck, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$ytck)[1], col.axis = layout$abanico$colour$ytck, cex.axis = layout$abanico$font.size$ylab/12) } } ## plot minor z-ticks for(i in 1:length(tick.values.minor)) { lines(x = c(par()$usr[2], (1 + 0.007 * cex * layout$abanico$dimension$ztcl / 100) * par()$usr[2]), y = c((tick.values.minor[i] - z.central.global) * min(ellipse[,1]), (tick.values.minor[i] - z.central.global) * min(ellipse[,1])), col = layout$abanico$colour$ztck) } ## plot major z-ticks for(i in 1:length(tick.values.major)) { lines(x = c(par()$usr[2], (1 + 0.015 * cex * layout$abanico$dimension$ztcl / 100) * par()$usr[2]), y = c((tick.values.major[i] - z.central.global) * min(ellipse[,1]), (tick.values.major[i] - z.central.global) * min(ellipse[,1])), col = layout$abanico$colour$ztck) } ## plot z-axes lines(ellipse, col = layout$abanico$colour$border) lines(rep(par()$usr[2], nrow(ellipse)), ellipse[,2], col = layout$abanico$colour$ztck) ## plot z-axis text text(x = (1 + 0.04 * cex * layout$abanico$dimension$ztcl / 100) * par()$usr[2], y = (tick.values.major - z.central.global) * min(ellipse[,1]), labels = label.z.text, adj = 0, family = layout$abanico$font.type$ztck, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$ztck)[1], cex = cex * layout$abanico$font.size$ztck/12) ## plot z-label mtext(text = zlab, at = mean(x = c(min(ellipse[,2]), max(ellipse[,2])), na.rm = TRUE), # at = 0, ## BUG from version 0.4.0, maybe removed in future side = 4, las = 3, adj = 0.5, line = 5 * layout$abanico$dimension$zlab.line / 100, col = layout$abanico$colour$zlab, family = layout$abanico$font.type$zlab, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$zlab)[1], cex = cex * layout$abanico$font.size$zlab/12) ## plot values and optionally error bars if(error.bars == TRUE) { for(i in 1:length(data)) { arrows(x0 = arrow.coords[[i]][,1], x1 = arrow.coords[[i]][,2], y0 = arrow.coords[[i]][,3], y1 = arrow.coords[[i]][,4], length = 0, angle = 90, code = 3, col = value.bar[i]) } } for(i in 1:length(data)) { points(data[[i]][,6][data[[i]][,6] <= limits.x[2]], data[[i]][,8][data[[i]][,6] <= limits.x[2]], col = value.dot[i], pch = pch[i], cex = layout$abanico$dimension$pch / 100) } ## calculate KDE width KDE.max <- 0 for(i in 1:length(data)) { KDE.max <- ifelse(test = KDE.max < max(KDE[[i]][,2]), yes = max(KDE[[i]][,2]), no = KDE.max) } ## optionally adjust KDE width for boxplot option if(boxplot == TRUE) { KDE.max <- 1.25 * KDE.max } KDE.scale <- (par()$usr[2] - xy.0[1]) / (KDE.max * 1.05) ## optionally add KDE plot if(kde == TRUE) { ## plot KDE lines for(i in 1:length(data)) { polygon(x = xy.0[1] + KDE[[i]][,2] * KDE.scale, y = (KDE[[i]][,1] - z.central.global) * min(ellipse[,1]), col = kde.fill[i], border = kde.line[i], lwd = 1.7) } ## plot KDE x-axis axis(side = 1, at = c(xy.0[1], par()$usr[2]), col = layout$abanico$colour$xtck3, col.axis = layout$abanico$colour$xtck3, labels = NA, tcl = -layout$abanico$dimension$xtcl3 / 200, cex = cex) axis(side = 1, at = c(xy.0[1], par()$usr[2]), labels = as.character(round(c(0, KDE.max.plot), 3)), line = 2 * layout$abanico$dimension$xtck3.line / 100 - 2, lwd = 0, col = layout$abanico$colour$xtck3, family = layout$abanico$font.type$xtck3, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$xtck3)[1], col.axis = layout$abanico$colour$xtck3, cex.axis = layout$abanico$font.size$xtck3/12) mtext(text = paste(xlab[3], " (bw ", round(x = KDE.bw, digits = 3), ")", sep = ""), at = (xy.0[1] + par()$usr[2]) / 2, side = 1, line = 2.5 * layout$abanico$dimension$xlab3.line / 100, col = layout$abanico$colour$xlab3, family = layout$abanico$font.type$xlab3, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$xlab3)[1], cex = cex * layout$abanico$font.size$xlab3/12) } ## optionally add histogram or dot plot axis if(hist == TRUE) { axis(side = 1, at = c(xy.0[1], par()$usr[2]), labels = as.character(c(0, hist.max.plot)), line = -1 * layout$abanico$dimension$xtck3.line / 100 - 2, lwd = 0, col = layout$abanico$colour$xtck3, family = layout$abanico$font.type$xtck3, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$xtck3)[1], col.axis = layout$abanico$colour$xtck3, cex.axis = layout$abanico$font.size$xtck3/12) ## add label mtext(text = "n", at = (xy.0[1] + par()$usr[2]) / 2, side = 1, line = -3.5 * layout$abanico$dimension$xlab2.line / 100, col = layout$abanico$colour$xlab2, family = layout$abanico$font.type$xlab2, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$xlab2)[1], cex = cex * layout$abanico$font.size$xlab2/12) ## plot ticks axis(side = 1, at = c(xy.0[1], par()$usr[2]), col = layout$abanico$colour$xtck2, col.axis = layout$abanico$colour$xtck2, labels = NA, tcl = layout$abanico$dimension$xtcl2 / 200, cex = cex) ## calculate scaling factor for histogram bar heights hist.scale <- (par()$usr[2] - xy.0[1]) / (KDE.max.plot * 1.05) ## draw each bar for each data set for(i in 1:length(data)) { for(j in 1:length(hist.data[[i]]$density)) { ## calculate x-coordinates hist.x.i <- c(xy.0[1], xy.0[1], xy.0[1] + hist.data[[i]]$density[j] * hist.scale, xy.0[1] + hist.data[[i]]$density[j] * hist.scale) ## calculate y-coordinates hist.y.i <- c((hist.data[[i]]$breaks[j] - z.central.global) * min(ellipse[,1]), (hist.data[[i]]$breaks[j + 1] - z.central.global) * min(ellipse[,1]), (hist.data[[i]]$breaks[j + 1] - z.central.global) * min(ellipse[,1]), (hist.data[[i]]$breaks[j] - z.central.global) * min(ellipse[,1])) ## remove data out of z-axis range hist.y.i <- ifelse(hist.y.i < min(ellipse[,2]), min(ellipse[,2]), hist.y.i) hist.y.i <- ifelse(hist.y.i > max(ellipse[,2]), max(ellipse[,2]), hist.y.i) ## draw the bars polygon(x = hist.x.i, y = hist.y.i, col = kde.fill[i], border = kde.line[i]) } } } ## optionally add dot plot if(dots == TRUE) { for(i in 1:length(data)) { for(j in 1:length(hist.data[[i]]$counts)) { ## calculate scaling factor for histogram bar heights dots.distance <- (par()$usr[2] - (xy.0[1] + par()$cxy[1] * 0.4)) / hist.max.plot dots.x.i <- seq(from = xy.0[1] + par()$cxy[1] * 0.4, by = dots.distance, length.out = hist.data[[i]]$counts[j]) dots.y.i <- rep((hist.data[[i]]$mids[j] - z.central.global) * min(ellipse[,1]), length(dots.x.i)) ## remove data out of z-axis range dots.x.i <- dots.x.i[dots.y.i >= min(ellipse[,2]) & dots.y.i <= max(ellipse[,2])] dots.y.i <- dots.y.i[dots.y.i >= min(ellipse[,2]) & dots.y.i <= max(ellipse[,2])] if(max(c(0, dots.x.i), na.rm = TRUE) >= (par()$usr[2] - par()$cxy[1] * 0.4)) { dots.y.i <- dots.y.i[dots.x.i < (par()$usr[2] - par()$cxy[1] * 0.4)] dots.x.i <- dots.x.i[dots.x.i < (par()$usr[2] - par()$cxy[1] * 0.4)] pch.dots <- c(rep(20, max(length(dots.x.i) - 1),1), 15) } else { pch.dots <- rep(20, length(dots.x.i)) } ## plot points points(x = dots.x.i, y = dots.y.i, pch = "|", cex = 0.7 * cex, col = kde.line[i]) } } } ## optionally add box plot if(boxplot == TRUE) { for(i in 1:length(data)) { ## draw median line lines(x = c(xy.0[1] + KDE.max * 0.85, xy.0[1] + KDE.max * 0.95), y = c((boxplot.data[[i]]$stats[3,1] - z.central.global) * min(ellipse[,1]), (boxplot.data[[i]]$stats[3,1] - z.central.global) * min(ellipse[,1])), lwd = 2, col = kde.line[i]) ## draw p25-p75-polygon polygon(x = c(xy.0[1] + KDE.max * 0.85, xy.0[1] + KDE.max * 0.85, xy.0[1] + KDE.max * 0.95, xy.0[1] + KDE.max * 0.95), y = c((boxplot.data[[i]]$stats[2,1] - z.central.global) * min(ellipse[,1]), (boxplot.data[[i]]$stats[4,1] - z.central.global) * min(ellipse[,1]), (boxplot.data[[i]]$stats[4,1] - z.central.global) * min(ellipse[,1]), (boxplot.data[[i]]$stats[2,1] - z.central.global) * min(ellipse[,1])), border = kde.line[i]) ## draw whiskers lines(x = c(xy.0[1] + KDE.max * 0.9, xy.0[1] + KDE.max * 0.9), y = c((boxplot.data[[i]]$stats[2,1] - z.central.global) * min(ellipse[,1]), (boxplot.data[[i]]$stats[1,1] - z.central.global) * min(ellipse[,1])), col = kde.line[i]) lines(x = c(xy.0[1] + KDE.max * 0.87, xy.0[1] + KDE.max * 0.93), y = rep((boxplot.data[[i]]$stats[1,1] - z.central.global) * min(ellipse[,1]), 2), col = kde.line[i]) lines(x = c(xy.0[1] + KDE.max * 0.9, xy.0[1] + KDE.max * 0.9), y = c((boxplot.data[[i]]$stats[4,1] - z.central.global) * min(ellipse[,1]), (boxplot.data[[i]]$stats[5,1] - z.central.global) * min(ellipse[,1])), col = kde.line[i]) lines(x = c(xy.0[1] + KDE.max * 0.87, xy.0[1] + KDE.max * 0.93), y = rep((boxplot.data[[i]]$stats[5,1] - z.central.global) * min(ellipse[,1]), 2), col = kde.line[i]) ## draw outlier points points(x = rep(xy.0[1] + KDE.max * 0.9, length(boxplot.data[[i]]$out)), y = (boxplot.data[[i]]$out - z.central.global) * min(ellipse[,1]), cex = cex * 0.8, col = kde.line[i]) } } ## optionally add stats, i.e. min, max, median sample text if(length(stats) > 0) { text(x = stats.data[,1], y = stats.data[,2], pos = 2, labels = round(stats.data[,3], 1), family = layout$abanico$font.type$stats, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$stats)[1], cex = cex * layout$abanico$font.size$stats/12, col = layout$abanico$colour$stats) } ## optionally add rug if(rug == TRUE) { for(i in 1:length(rug.coords)) { lines(x = rug.coords[[i]][1,], y = rug.coords[[i]][2,], col = value.rug[data.global[i,10]]) } } ## plot KDE base line lines(x = c(xy.0[1], xy.0[1]), y = c(min(ellipse[,2]), max(ellipse[,2])), col = layout$abanico$colour$border) ## draw border around plot if(frame == 1) { polygon(x = c(limits.x[1], min(ellipse[,1]), par()$usr[2], par()$usr[2], min(ellipse[,1])), y = c(0, max(ellipse[,2]), max(ellipse[,2]), min(ellipse[,2]), min(ellipse[,2])), border = layout$abanico$colour$border, lwd = 0.8) } else if(frame == 2) { polygon(x = c(limits.x[1], min(ellipse[,1]), par()$usr[2], par()$usr[2], min(ellipse[,1]), limits.x[1]), y = c(2, max(ellipse[,2]), max(ellipse[,2]), min(ellipse[,2]), min(ellipse[,2]), -2), border = layout$abanico$colour$border, lwd = 0.8) } else if(frame == 3) { polygon(x = c(limits.x[1], par()$usr[2], par()$usr[2], limits.x[1]), y = c(max(ellipse[,2]), max(ellipse[,2]), min(ellipse[,2]), min(ellipse[,2])), border = layout$abanico$colour$border, lwd = 0.8) } ## optionally add legend content if(!missing(legend)) { ## store and change font family par.family <- par()$family par(family = layout$abanico$font.type$legend) legend(x = legend.pos[1], y = 0.8 * legend.pos[2], xjust = legend.adj[1], yjust = legend.adj[2], legend = legend, pch = pch, col = value.dot, text.col = value.dot, text.font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$legend)[1], cex = cex * layout$abanico$font.size$legend/12, bty = "n") ## restore font family par(family = par.family) } ## optionally add subheader text mtext(text = mtext, side = 3, line = (shift.lines - 2) * layout$abanico$dimension$mtext / 100, col = layout$abanico$colour$mtext, family = layout$abanico$font.type$mtext, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$mtext)[1], cex = cex * layout$abanico$font.size$mtext / 12) ## add summary content for(i in 1:length(data)) { if(summary.pos[1] != "sub") { text(x = summary.pos[1], y = summary.pos[2], adj = summary.adj, labels = label.text[[i]], col = summary.col[i], family = layout$abanico$font.type$summary, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$summary)[1], cex = cex * layout$abanico$font.size$summary / 12) } else { if(mtext == "") { mtext(side = 3, line = (shift.lines- 1 - i) * layout$abanico$dimension$summary / 100 , text = label.text[[i]], col = summary.col[i], family = layout$abanico$font.type$summary, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$summary)[1], cex = cex * layout$abanico$font.size$summary / 12) } } } } else { ## setup plot area par(mar = c(4, 4, shift.lines + 5, 4), xpd = TRUE, cex = cex) if(layout$abanico$dimension$figure.width != "auto" | layout$abanico$dimension$figure.height != "auto") { par(mai = layout$abanico$dimension$margin / 25.4, pin = c(layout$abanico$dimension$figure.width / 25.4 - layout$abanico$dimension$margin[2] / 25.4 - layout$abanico$dimension$margin[4] / 25.4, layout$abanico$dimension$figure.height / 25.4 - layout$abanico$dimension$margin[1] / 25.4 - layout$abanico$dimension$margin[3]/25.4)) } ## create empty plot par(new = TRUE) plot(NA, xlim = limits.y, ylim = c(limits.x[1], limits.x[2] * (1 / plot.ratio)), main = "", sub = sub, xlab = "", ylab = "", xaxs = "i", yaxs = "i", frame.plot = FALSE, axes = FALSE) ## add y-axis label mtext(text = ylab, at = 0, adj = 0.5, side = 1, line = 3 * layout$abanico$dimension$ylab.line / 100, col = layout$abanico$colour$ylab, family = layout$abanico$font.type$ylab, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$ylab)[1], cex = cex * layout$abanico$font.size$ylab/12) ## calculate upper x-axis label values label.x.upper <- if(log.z == TRUE) { as.character(round(1/axTicks(side = 2)[-1] * 100, 1)) } else { as.character(round(1/axTicks(side = 2)[-1], 1)) } # optionally, plot 2-sigma-bar if(bar[1] != FALSE) { for(i in 1:length(bar)) { polygon(x = bars[i,1:4], y = bars[i,5:8], col = bar.fill[i], border = bar.line[i]) } } ## remove unwanted parts polygon(y = c(par()$usr[2], par()$usr[2], par()$usr[2] * 2, par()$usr[2] * 2), x = c(min(ellipse[,2]) * 2, max(ellipse[,2]) * 2, max(ellipse[,2]) * 2, min(ellipse[,2]) * 2), col = bg.original, lty = 0) ## optionally, plot dispersion polygon if(polygon.fill[1] != "none") { for(i in 1:length(data)) { polygon(x = polygons[i,8:14], y = polygons[i,1:7], col = polygon.fill[i], border = polygon.line[i]) } } ## optionally, add minor grid lines if(grid.minor != "none") { for(i in 1:length(tick.values.minor)) { lines(y = c(limits.x[1], min(ellipse[,1])), x = c(0, (tick.values.minor[i] - z.central.global) * min(ellipse[,1])), col = grid.minor, lwd = 1) } for(i in 1:length(tick.values.minor)) { lines(y = c(xy.0[2], par()$usr[2]), x = c((tick.values.minor[i] - z.central.global) * min(ellipse[,1]), (tick.values.minor[i] - z.central.global) * min(ellipse[,1])), col = grid.minor, lwd = 1) } } ## optionally, add major grid lines if(grid.major != "none") { for(i in 1:length(tick.values.major)) { lines(y = c(limits.x[1], min(ellipse[,2])), x = c(0, (tick.values.major[i] - z.central.global) * min(ellipse[,2])), col = grid.major, lwd = 1) } for(i in 1:length(tick.values.major)) { lines(y = c(xy.0[2],y.max), x = c((tick.values.major[i] - z.central.global) * min(ellipse[,2]), (tick.values.major[i] - z.central.global) * min(ellipse[,2])), col = grid.major, lwd = 1) } } ## optionally, plot lines for each bar if(lwd[1] > 0 & lty[1] > 0 & bar[1] != FALSE & length(data) == 1) { if(bar[1] == TRUE & length(bar) == 1) { bar[1] <- z.central.global } for(i in 1:length(bar)) { x2 <- r / sqrt(1 + f^2 * ( bar[i] - z.central.global)^2) y2 <- (bar[i] - z.central.global) * x2 lines(x = c(0, y2, y2, y2), y = c(limits.x[1], x2, xy.0[2], par()$usr[4]), lty = lty[i], lwd = lwd[i], col = centrality.col[i]) } } ## optionally add further lines if(missing(line) == FALSE) { for(i in 1:length(line)) { lines(y = line.coords[[i]][1,1:3], x = line.coords[[i]][2,1:3], col = line.col[i], lty = line.lty[i] ) text(y = line.coords[[i]][1,3], x = line.coords[[i]][2,3] + par()$cxy[2] * 0.3, labels = line.label[i], pos = 2, col = line.col[i], cex = cex * 0.9) } } ## add plot title cex.old <- par()$cex par(cex = layout$abanico$font.size$main / 12) title(main = main, family = layout$abanico$font.type$main, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$main)[1], col.main = layout$abanico$colour$main, line = (shift.lines + 3.5) * layout$abanico$dimension$main / 100) par(cex = cex.old) ## calculate lower x-axis (precision) x.axis.ticks <- axTicks(side = 2) x.axis.ticks <- x.axis.ticks[c(TRUE, x.axis.ticks <= limits.x[2])] x.axis.ticks <- x.axis.ticks[x.axis.ticks <= max(ellipse[,2])] ## x-axis with lables and ticks axis(side = 2, at = x.axis.ticks, col = layout$abanico$colour$xtck1, col.axis = layout$abanico$colour$xtck1, labels = NA, tcl = -layout$abanico$dimension$xtcl1 / 200, cex = cex) axis(side = 2, at = x.axis.ticks, line = 2 * layout$abanico$dimension$xtck1.line / 100 - 2, lwd = 0, col = layout$abanico$colour$xtck1, family = layout$abanico$font.type$xtck1, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$xtck1)[1], col.axis = layout$abanico$colour$xtck1, cex.axis = layout$abanico$font.size$xlab1/12) ## extend axis line to right side of the plot lines(y = c(max(x.axis.ticks), max(ellipse[,2])), x = c(limits.y[1], limits.y[1]), col = layout$abanico$colour$xtck1) ## draw closing tick on right hand side axis(side = 2, tcl = -layout$abanico$dimension$xtcl1 / 200, lwd = 0, lwd.ticks = 1, at = limits.x[2], labels = FALSE, col = layout$abanico$colour$xtck1) axis(side = 2, tcl = layout$abanico$dimension$xtcl2 / 200, lwd = 0, lwd.ticks = 1, at = limits.x[2], labels = FALSE, col = layout$abanico$colour$xtck2) ## add lower axis label mtext(xlab[2], at = (limits.x[1] + max(ellipse[,2])) / 2, side = 2, line = 2.5 * layout$abanico$dimension$xlab1.line / 100, col = layout$abanico$colour$xlab1, family = layout$abanico$font.type$xlab1, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$xlab1)[1], cex = cex * layout$abanico$font.size$xlab1/12) ## add upper axis label mtext(xlab[1], at = (limits.x[1] + max(ellipse[,2])) / 2, side = 2, line = -3.5 * layout$abanico$dimension$xlab2.line / 100, col = layout$abanico$colour$xlab2, family = layout$abanico$font.type$xlab2, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$xlab2)[1], cex = cex * layout$abanico$font.size$xlab2/12) ## plot upper x-axis axis(side = 2, at = x.axis.ticks[-1], col = layout$abanico$colour$xtck2, col.axis = layout$abanico$colour$xtck2, labels = NA, tcl = layout$abanico$dimension$xtcl2 / 200, cex = cex) ## remove first tick label (infinity) label.x.upper <- label.x.upper[1:(length(x.axis.ticks) - 1)] axis(side = 2, at = x.axis.ticks[-1], labels = label.x.upper, line = -1 * layout$abanico$dimension$xtck2.line / 100 - 2, lwd = 0, col = layout$abanico$colour$xtck2, family = layout$abanico$font.type$xtck2, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$xtck2)[1], col.axis = layout$abanico$colour$xtck2, cex.axis = layout$abanico$font.size$xlab2/12) ## plot y-axis if(y.axis == TRUE) { char.height <- par()$cxy[2] tick.space <- axisTicks(usr = limits.y, log = FALSE) tick.space <- (max(tick.space) - min(tick.space)) / length(tick.space) if(tick.space < char.height * 1.7) { axis(side = 1, tcl = -layout$abanico$dimension$ytcl / 200, lwd = 1, lwd.ticks = 1, at = c(-2, 2), labels = c("", ""), las = 1, col = layout$abanico$colour$ytck) axis(side = 1, at = 0, tcl = 0, line = 2 * layout$abanico$dimension$ytck.line / 100 - 2, labels = paste("\u00B1", "2"), las = 1, family = layout$abanico$font.type$ytck, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$ytck)[1], col.axis = layout$abanico$colour$ytck, cex.axis = layout$abanico$font.size$ylab/12) } else { axis(side = 1, at = seq(-2, 2, by = 2), col = layout$abanico$colour$ytck, col.axis = layout$abanico$colour$ytck, labels = NA, las = 1, tcl = -layout$abanico$dimension$ytcl / 200, cex = cex) axis(side = 1, at = seq(-2, 2, by = 2), line = 2 * layout$abanico$dimension$ytck.line / 100 - 2, lwd = 0, las = 1, col = layout$abanico$colour$ytck, family = layout$abanico$font.type$ytck, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$ytck)[1], col.axis = layout$abanico$colour$ytck, cex.axis = layout$abanico$font.size$ylab/12) } } else { axis(side = 1, at = 0, col = layout$abanico$colour$ytck, col.axis = layout$abanico$colour$ytck, labels = NA, las = 1, tcl = -layout$abanico$dimension$ytcl / 200, cex = cex) axis(side = 1, at = 0, line = 2 * layout$abanico$dimension$ytck.line / 100 - 2, lwd = 0, las = 1, col = layout$abanico$colour$ytck, family = layout$abanico$font.type$ytck, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$ytck)[1], col.axis = layout$abanico$colour$ytck, cex.axis = layout$abanico$font.size$ylab/12) } ## plot minor z-ticks for(i in 1:length(tick.values.minor)) { lines(y = c(par()$usr[4], (1 + 0.015 * cex * layout$abanico$dimension$ztcl / 100) * y.max), x = c((tick.values.minor[i] - z.central.global) * min(ellipse[,2]), (tick.values.minor[i] - z.central.global) * min(ellipse[,2])), col = layout$abanico$colour$ztck) } ## plot major z-ticks for(i in 1:length(tick.values.major)) { lines(y = c(par()$usr[4], (1 + 0.03 * cex * layout$abanico$dimension$ztcl / 100) * y.max), x = c((tick.values.major[i] - z.central.global) * min(ellipse[,2]), (tick.values.major[i] - z.central.global) * min(ellipse[,2])), col = layout$abanico$colour$ztck) } ## plot z-axes lines(ellipse, col = layout$abanico$colour$border) lines(y = rep(par()$usr[4], nrow(ellipse)), x = ellipse[,1], col = layout$abanico$colour$ztck) ## plot z-axis text text(y = (1 + 0.06 * cex * layout$abanico$dimension$ztcl / 100) * y.max, x = (tick.values.major - z.central.global) * min(ellipse[,2]), labels = label.z.text, adj = 0.5, family = layout$abanico$font.type$ztck, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$ztck)[1], cex = cex * layout$abanico$font.size$ztck/12) ## plot z-label mtext(text = zlab, at = 0, side = 3, las = 1, adj = 0.5, line = 2.5 * layout$abanico$dimension$zlab.line / 100, col = layout$abanico$colour$zlab, family = layout$abanico$font.type$zlab, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$zlab)[1], cex = cex * layout$abanico$font.size$zlab/12) ## plot values and optionally error bars if(error.bars == TRUE) { for(i in 1:length(data)) { arrows(y0 = arrow.coords[[i]][,1], y1 = arrow.coords[[i]][,2], x0 = arrow.coords[[i]][,3], x1 = arrow.coords[[i]][,4], length = 0, angle = 90, code = 3, col = value.bar[i]) } } for(i in 1:length(data)) { points(y = data[[i]][,6][data[[i]][,6] <= limits.x[2]], x = data[[i]][,8][data[[i]][,6] <= limits.x[2]], col = value.dot[i], pch = pch[i], cex = layout$abanico$dimension$pch / 100) } ## calculate KDE width KDE.max <- 0 for(i in 1:length(data)) { KDE.max <- ifelse(test = KDE.max < max(KDE[[i]][,2]), yes = max(KDE[[i]][,2]), no = KDE.max) } ## optionally adjust KDE width for boxplot option if(boxplot == TRUE) { KDE.max <- 1.3 * KDE.max } KDE.scale <- (par()$usr[4] - xy.0[2]) / (KDE.max * 1.05) ## optionally add KDE plot if(kde == TRUE) { ## plot KDE lines for(i in 1:length(data)) { polygon(y = xy.0[2] + KDE[[i]][,2] * KDE.scale, x = (KDE[[i]][,1] - z.central.global) * min(ellipse[,2]), col = kde.fill[i], border = kde.line[i], lwd = 1.7) } ## plot KDE x-axis axis(side = 2, at = c(xy.0[2], y.max), col = layout$abanico$colour$xtck3, col.axis = layout$abanico$colour$xtck3, labels = NA, tcl = -layout$abanico$dimension$xtcl3 / 200, cex = cex) axis(side = 2, at = c(xy.0[2], y.max), labels = as.character(round(c(0, KDE.max.plot), 3)), line = 2 * layout$abanico$dimension$xtck3.line / 100 - 2, lwd = 0, col = layout$abanico$colour$xtck3, family = layout$abanico$font.type$xtck3, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$xtck3)[1], col.axis = layout$abanico$colour$xtck3, cex.axis = layout$abanico$font.size$xtck3/12) mtext(text = paste(xlab[3], " (bw ", round(x = KDE.bw, digits = 3), ")", sep = ""), at = (xy.0[2] + y.max) / 2, side = 2, line = 2.5 * layout$abanico$dimension$xlab3.line / 100, col = layout$abanico$colour$xlab3, family = layout$abanico$font.type$xlab3, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$xlab3)[1], cex = cex * layout$abanico$font.size$xlab3/12) } ## optionally add histogram or dot plot axis if(hist == TRUE) { axis(side = 2, at = c(xy.0[2], y.max), labels = as.character(c(0, hist.max.plot)), line = -1 * layout$abanico$dimension$xtck3.line / 100 - 2, lwd = 0, col = layout$abanico$colour$xtck3, family = layout$abanico$font.type$xtck3, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$xtck3)[1], col.axis = layout$abanico$colour$xtck3, cex.axis = layout$abanico$font.size$xtck3/12) ## add label mtext(text = "n", at = (xy.0[2] + y.max) / 2, side = 2, line = -3.5 * layout$abanico$dimension$xlab2.line / 100, col = layout$abanico$colour$xlab2, family = layout$abanico$font.type$xlab2, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$xlab2)[1], cex = cex * layout$abanico$font.size$xlab2/12) ## plot ticks axis(side = 2, at = c(xy.0[2], y.max), col = layout$abanico$colour$xtck2, col.axis = layout$abanico$colour$xtck2, labels = NA, tcl = layout$abanico$dimension$xtcl2 / 200, cex = cex) ## calculate scaling factor for histogram bar heights hist.scale <- (par()$usr[4] - xy.0[2]) / (KDE.max.plot * 1.05) ## draw each bar for each data set for(i in 1:length(data)) { for(j in 1:length(hist.data[[i]]$density)) { ## calculate x-coordinates hist.x.i <- c(xy.0[2], xy.0[2], xy.0[2] + hist.data[[i]]$density[j] * hist.scale, xy.0[2] + hist.data[[i]]$density[j] * hist.scale) ## calculate y-coordinates hist.y.i <- c((hist.data[[i]]$breaks[j] - z.central.global) * min(ellipse[,2]), (hist.data[[i]]$breaks[j + 1] - z.central.global) * min(ellipse[,2]), (hist.data[[i]]$breaks[j + 1] - z.central.global) * min(ellipse[,2]), (hist.data[[i]]$breaks[j] - z.central.global) * min(ellipse[,2])) ## remove data out of z-axis range hist.y.i <- ifelse(hist.y.i < min(ellipse[,1]), min(ellipse[,1]), hist.y.i) hist.y.i <- ifelse(hist.y.i > max(ellipse[,1]), max(ellipse[,1]), hist.y.i) ## draw the bars polygon(y = hist.x.i, x = hist.y.i, col = kde.fill[i], border = kde.line[i]) } } } ## optionally add dot plot if(dots == TRUE) { for(i in 1:length(data)) { for(j in 1:length(hist.data[[i]]$counts)) { ## calculate scaling factor for histogram bar heights dots.distance <- (par()$usr[4] - (xy.0[2] + par()$cxy[1] * 0.4)) / hist.max.plot dots.x.i <- seq(from = xy.0[2] + par()$cxy[2] * 0.4, by = dots.distance, length.out = hist.data[[i]]$counts[j]) dots.y.i <- rep((hist.data[[i]]$mids[j] - z.central.global) * min(ellipse[,2]), length(dots.x.i)) ## remove data out of z-axis range dots.x.i <- dots.x.i[dots.y.i >= min(ellipse[,1]) & dots.y.i <= max(ellipse[,1])] dots.y.i <- dots.y.i[dots.y.i >= min(ellipse[,1]) & dots.y.i <= max(ellipse[,1])] if(max(c(0, dots.x.i), na.rm = TRUE) >= (par()$usr[4] - par()$cxy[2] * 0.4)) { dots.y.i <- dots.y.i[dots.x.i < (par()$usr[4] - par()$cxy[2] * 0.4)] dots.x.i <- dots.x.i[dots.x.i < (par()$usr[4] - par()$cxy[2] * 0.4)] pch.dots <- c(rep(20, length(dots.x.i) - 1), 15) } else { pch.dots <- rep(20, length(dots.x.i)) } ## plot points points(y = dots.x.i, x = dots.y.i, pch = "-", cex = 0.7 * cex, col = kde.line[i]) } } } ## optionally add box plot if(boxplot == TRUE) { for(i in 1:length(data)) { ## draw median line lines(x = c((boxplot.data[[i]]$stats[3,1] - z.central.global) * min(ellipse[,2]), (boxplot.data[[i]]$stats[3,1] - z.central.global) * min(ellipse[,2])), y = c(min(ellipse[,2]) + KDE.max * 0.91, xy.0[2] + KDE.max * 0.96), lwd = 2, col = kde.line[i]) ## draw p25-p75-polygon polygon(y = c(min(ellipse[,2]) + KDE.max * 0.91, min(ellipse[,2]) + KDE.max * 0.91, xy.0[2] + KDE.max * 0.96, xy.0[2] + KDE.max * 0.96), x = c((boxplot.data[[i]]$stats[2,1] - z.central.global) * min(ellipse[,2]), (boxplot.data[[i]]$stats[4,1] - z.central.global) * min(ellipse[,2]), (boxplot.data[[i]]$stats[4,1] - z.central.global) * min(ellipse[,2]), (boxplot.data[[i]]$stats[2,1] - z.central.global) * min(ellipse[,2])), border = kde.line[i]) ## draw whiskers lines(y = rep(mean(c(min(ellipse[,2]) + KDE.max * 0.91, xy.0[2] + KDE.max * 0.96)), 2), x = c((boxplot.data[[i]]$stats[2,1] - z.central.global) * min(ellipse[,2]), (boxplot.data[[i]]$stats[1,1] - z.central.global) * min(ellipse[,2])), col = kde.line[i]) lines(y = c(min(ellipse[,2]) + KDE.max * 0.91, xy.0[2] + KDE.max * 0.96), x = rep((boxplot.data[[i]]$stats[1,1] - z.central.global) * min(ellipse[,2]), 2), col = kde.line[i]) lines(y = rep(mean(c(min(ellipse[,2]) + KDE.max * 0.91, xy.0[2] + KDE.max * 0.96)), 2), x = c((boxplot.data[[i]]$stats[4,1] - z.central.global) * min(ellipse[,2]), (boxplot.data[[i]]$stats[5,1] - z.central.global) * min(ellipse[,2])), col = kde.line[i]) lines(y = c(min(ellipse[,2]) + KDE.max * 0.91, xy.0[2] + KDE.max * 0.96), x = rep((boxplot.data[[i]]$stats[5,1] - z.central.global) * min(ellipse[,2]), 2), col = kde.line[i]) ## draw outlier points points(y = rep(mean(c(min(ellipse[,2]) + KDE.max * 0.91, xy.0[2] + KDE.max * 0.96)), length(boxplot.data[[i]]$out)), x = (boxplot.data[[i]]$out - z.central.global) * min(ellipse[,2]), cex = cex * 0.8, col = kde.line[i]) } } ## optionally add stats, i.e. min, max, median sample text if(length(stats) > 0) { text(y = stats.data[,1], x = stats.data[,2], pos = 2, labels = round(stats.data[,3], 1), family = layout$abanico$font.type$stats, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$stats)[1], cex = cex * layout$abanico$font.size$stats/12, col = layout$abanico$colour$stats) } ## optionally add rug if(rug == TRUE) { for(i in 1:length(rug.coords)) { lines(y = rug.coords[[i]][1,], x = rug.coords[[i]][2,], col = value.rug[data.global[i,10]]) } } ## plot KDE base line lines(y = c(xy.0[2], xy.0[2]), x = c(min(ellipse[,1]), max(ellipse[,1])), col = layout$abanico$colour$border) ## draw border around plot polygon(y = c(limits.x[1], min(ellipse[,2]), y.max, y.max, min(ellipse[,2])), x = c(0, max(ellipse[,1]), max(ellipse[,1]), min(ellipse[,1]), min(ellipse[,1])), border = layout$abanico$colour$border, lwd = 0.8) ## optionally add legend content if(missing(legend) == FALSE) { ## store and change font familiy par.family <- par()$family par(family = layout$abanico$font.type$legend) legend(y = legend.pos[2], x = 0.8 * legend.pos[1], xjust = legend.adj[2], yjust = legend.adj[1], legend = legend, pch = pch, col = value.dot, text.col = value.dot, text.font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$legend)[1], cex = cex * layout$abanico$font.size$legend/12, bty = "n") ## restore font family par(family = par.family) } ## optionally add subheader text mtext(text = mtext, side = 3, line = (shift.lines - 2 + 3.5) * layout$abanico$dimension$mtext / 100, col = layout$abanico$colour$mtext, family = layout$abanico$font.type$mtext, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$mtext)[1], cex = cex * layout$abanico$font.size$mtext / 12) ## add summary content for(i in 1:length(data)) { if(summary.pos[1] != "sub") { text(x = summary.pos[1], y = summary.pos[2], adj = summary.adj, labels = label.text[[i]], col = summary.col[i], family = layout$abanico$font.type$summary, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$summary)[1], cex = cex * layout$abanico$font.size$summary / 12) } else { if(mtext == "") { mtext(side = 3, line = (shift.lines - 1 + 3.5 - i) * layout$abanico$dimension$summary / 100 , text = label.text[[i]], col = summary.col[i], family = layout$abanico$font.type$summary, font = which(c("normal", "bold", "italic", "bold italic") == layout$abanico$font.deco$summary)[1], cex = cex * layout$abanico$font.size$summary / 12) } } } } ##sTeve if(fun & !interactive){sTeve()} ## create numeric output plot.output <- list(xlim = limits.x, ylim = limits.y, zlim = limits.z, polar.box = c(limits.x[1], limits.x[2], min(ellipse[,2]), max(ellipse[,2])), cartesian.box = c(xy.0[1], par()$usr[2], xy.0[2], max(ellipse[,2])), plot.ratio = plot.ratio, data = data, data.global = data.global, KDE = KDE, par = par(no.readonly = TRUE)) ## INTERACTIVE PLOT ---------------------------------------------------------- if (interactive) { if (!requireNamespace("plotly", quietly = TRUE)) stop("The interactive abanico plot requires the 'plotly' package. To install", " this package run 'install.packages('plotly')' in your R console.", call. = FALSE) ##cheat R check (global visible binding error) x <- NA y <- NA ## tidy data ---- data <- plot.output kde <- data.frame(x = data$KDE[[1]][ ,2], y = data$KDE[[1]][ ,1]) # radial scatter plot ---- point.text <- paste0("Measured value:</br>", data$data.global$De, " &plusmn; ", data$data.global$error,"</br>", "P(",format(data$data.global$precision, digits = 2, nsmall = 1),", ", format(data$data.global$std.estimate, digits = 2, nsmall = 1),")") IAP <- plotly::plot_ly(data = data$data.global, x = precision, y = std.estimate, type = "scatter", mode = "markers", hoverinfo = "text", text = point.text, name = "Points", yaxis = "y") ellipse <- as.data.frame(ellipse) IAP <- plotly::add_trace(IAP, data = ellipse, x = ellipse.x, y = ellipse.y, hoverinfo = "none", name = "z-axis (left)", type = "scatter", mode = "lines", line = list(color = "black", width = 1), yaxis = "y") ellipse.right <- ellipse ellipse.right$ellipse.x <- ellipse.right$ellipse.x * 1/0.75 IAP <- plotly::add_trace(IAP, data = ellipse.right, x = ellipse.x, y = ellipse.y, hoverinfo = "none", name = "z-axis (right)", type = "scatter", mode = "lines", line = list(color = "black", width = 1), yaxis = "y") # z-axis ticks major.ticks.x <- c(data$xlim[2] * 1/0.75, (1 + 0.015 * layout$abanico$dimension$ztcl / 100) * data$xlim[2] * 1/0.75) minor.ticks.x <- c(data$xlim[2] * 1/0.75, (1 + 0.01 * layout$abanico$dimension$ztcl / 100) * data$xlim[2] * 1/0.75) major.ticks.y <- (tick.values.major - z.central.global) * min(ellipse[ ,1]) minor.ticks.y <- (tick.values.minor - z.central.global) * min(ellipse[ ,1]) # major z-tick lines for (i in 1:length(major.ticks.y)) { major.tick <- data.frame(x = major.ticks.x, y = rep(major.ticks.y[i], 2)) IAP <- plotly::add_trace(IAP, data = major.tick, x = x, y = y, showlegend = FALSE, hoverinfo = "none", type = "scatter", mode = "lines", line = list(color = "black", width = 1), yaxis = "y") } # minor z-tick lines for (i in 1:length(minor.ticks.y)) { minor.tick <- data.frame(x = minor.ticks.x, y = rep(minor.ticks.y[i], 2)) IAP <- plotly::add_trace(IAP, data = minor.tick, hoverinfo = "none", x = x, y = y, showlegend = FALSE, type = "scatter", mode = "lines", line = list(color = "black", width = 1), yaxis = "y") } # z-tick label tick.text <- paste(" ", exp(tick.values.major)) tick.pos <- data.frame(x = major.ticks.x[2], y = major.ticks.y) IAP <- plotly::add_trace(IAP, data = tick.pos, x = x, y = y, showlegend = FALSE, text = tick.text, textposition = "right", hoverinfo = "none", type = "scatter", mode = "text", yaxis = "y") # Central Line ---- central.line <- data.frame(x = c(-100, data$xlim[2]*1/0.75), y = c(0, 0)) central.line.text <- paste0("Central value: ", format(exp(z.central.global), digits = 2, nsmall = 1)) IAP <- plotly::add_trace(IAP, data = central.line, x = x, y = y, name = "Central line", type = "scatter", mode = "lines", hoverinfo = "text", text = central.line.text, yaxis = "y", line = list(color = "black", width = 0.5, dash = 2)) # KDE plot ---- KDE.x <- xy.0[1] + KDE[[1]][ ,2] * KDE.scale KDE.y <- (KDE[[1]][ ,1] - z.central.global) * min(ellipse[,1]) KDE.curve <- data.frame(x = KDE.x, y = KDE.y) KDE.curve <- KDE.curve[KDE.curve$x != xy.0[1], ] KDE.text <- paste0("Value:", format(exp(KDE[[1]][ ,1]), digits = 2, nsmall = 1), "</br>", "Density:", format(KDE[[1]][ ,2], digits = 2, nsmall = 1)) IAP <- plotly::add_trace(IAP, data = KDE.curve, hoverinfo = "text", text = KDE.text, x = x, y = y, name = "KDE", type = "scatter", mode = "lines", line = list(color = "red"), yaxis = "y") # set layout ---- IAP <- plotly::layout(IAP, hovermode = "closest", dragmode = "pan", xaxis = list(range = c(data$xlim[1], data$xlim[2] * 1/0.65), zeroline = FALSE, showgrid = FALSE, tickmode = "array", tickvals = x.axis.ticks), yaxis = list(range = data$ylim, zeroline = FALSE, showline = FALSE, showgrid = FALSE, tickmode = "array", tickvals = c(-2, 0, 2)), shapes = list(list(type = "rect", # 2 sigma bar x0 = 0, y0 = -2, x1 = bars[1,3], y1 = 2, xref = "x", yref = "y", fillcolor = "grey", opacity = 0.2)) ) # show and return interactive plot ---- #print(plotly::subplot(IAP, IAP.kde)) print(IAP) return(IAP) } ## restore initial cex par(cex = cex_old) ## create and return numeric output invisible(plot.output) }
133,270
gpl-3.0
99012a25ea6e6fa64c18b8b9fbec753c7a5186e9
paul4forest/forestproductsdemand
docs/all_products/draft with brew/knit_reports with brew.R
# # Generate Reports for the different forest products using brew # # Inspired by # http://botthoughts.wordpress.com/2012/05/17/generating-reports-for-different-data-sets-using-brew-and-knitr/ # I first used brew, but then used knitr only library(knitr) opts_knit$set(base.dir = './docs/all_products/') # Change the base dir where to save figures ############# # Load data # ############# load("enddata/EU27 sawnwood demand.rdata") load("enddata/EU27 paper products demand.rdata") load("enddata/EU27 roundwood demand.rdata") # A function that create aggregate reports based on the agg dataframe and template create.report <- function(dtf, dtfagg, report.name, path="./docs/all_products/"){ dtf <- dtf dtfagg <- dtfagg knit2html(paste0(path,"template.Rmd"), paste0(path, report.name, ".html"), options = c(markdownHTMLOptions(defaults=TRUE), "toc") } create.report(roundwood, rwdagg, "rwd") create.report(sawnwood, swdagg, "swd") create.report(paperProducts, ppagg, "pp") ### Content lost, # See maybe in git history february 2014 or before
1,106
gpl-2.0
0d51cfbd8ec08ad2220a91b12fc8bc52d4d6fd99
jonathandfitzgerald/Viral-Texts-R
Wright Data.R
#Working with Wright Data #make a list of all files WRIGHT = list.files("data/wright-txt",full.names = TRUE) #function to read them in readWRIGHT = function(file) { message(file) text = paste(scan(file, sep="\n",what="raw",strip.white = TRUE),collapse = "/n") WRIGHT = data.frame(filename=file,text=text,stringsAsFactors = FALSE) return(WRIGHT) } #run the function allWRIGHT = data.frame(filename=WRIGHT,stringsAsFactors=FALSE) %>% group_by(filename) %>% do(readWRIGHT(.$filename)) #remove everything above Full Text allWRIGHT$text = gsub("/n", "", allWRIGHT$text) #this removes line breaks allWRIGHT$text = gsub("\r?\n|\r", "\\s", allWRIGHT$text) allWRIGHT$text = gsub(".*?----FULL TEXT----", " ", allWRIGHT$text) #sample 8 in an effort to get a smaller corpus #allWRIGHT <- allWRIGHT[sample(1:nrow(allWRIGHT), 8,replace=FALSE),] #convert text to string and chunk by character count. Convert to df allWRIGHT_string = paste(unlist(allWRIGHT$text), collapse =" ") allWRIGHT_string = substring(allWRIGHT_string,seq(1,nchar(allWRIGHT_string),2000),seq(2000,nchar(allWRIGHT_string),2000)) allWRIGHT2 = allWRIGHT_string %>% as.data.frame() # Use Lincoln's update of tokenizers to chunk text allWRIGHT2 = chunk_text(allWRIGHT$text, chunk_size = 300, doc_id = allWRIGHT$filename) %>% as_data_frame() allWRIGHT2 = allWRIGHT2 %>% gather(id, text) allWRIGHT2 = allWRIGHT2 %>% as.data.frame() allWRIGHT2 = allWRIGHT2 %>% mutate(genre="fiction") allWRIGHT2 = allWRIGHT2 %>% mutate(cluster=paste("wright",1:nrow(allWRIGHT2), sep = "_")) names(allWRIGHT2)[names(allWRIGHT2)=="."] <- "text" allWRIGHT2 = allWRIGHT2[,c("cluster","text","genre")] allWRIGHT2 <- allWRIGHT2[sample(1:nrow(allWRIGHT2), 200,replace=FALSE),] allWRIGHT2$text = allWRIGHT2$text %>% as.character() #add genre column and convert filename to cluster allWRIGHT = allWRIGHT %>% mutate(genre="fiction") names(allWRIGHT)[names(allWRIGHT)=="filename"] <- "cluster" allWRIGHT = allWRIGHT %>% as.data.frame() #allWRIGHT <- allWRIGHT[sample(1:nrow(allWRIGHT), 8,replace=FALSE),] #read in fiction found with "by" allFiction = read.csv("data/fiction-with-by.csv", header=TRUE, fill = TRUE, sep = ",", row.names = NULL, stringsAsFactors = FALSE) allFiction = allFiction %>% mutate(genre = "fiction") allFiction = allFiction[,c("cluster","text","genre")] #read in news allNews = read.csv("output/genres/news.csv", header=TRUE, fill = TRUE, sep = ",", row.names = NULL, stringsAsFactors = FALSE) names(allNews)[names(allNews)=="classified_genre"] <- "genre" names(allNews)[names(allNews)=="Text"] <- "text" allNews = allNews[,c("cluster","text","genre")] allNews <- allNews[sample(1:nrow(allNews), 200,replace=FALSE),] allNews$text = gsub("\r?\n|\r", "\\s", allNews$text) #read in vignettes allVignettes = read.csv("data/200vignettes.csv", header=TRUE, fill = TRUE, sep = ",", row.names = NULL, stringsAsFactors = FALSE) allVignettes = allVignettes[,c("cluster","text","genre")] allVignettes = allVignettes %>% mutate(genre="unknown") #allVignettes <- allVignettes[sample(1:nrow(allNews), 75,replace=FALSE),] allVignettes$text = gsub("\r?\n|\r", "\\s", allVignettes$text) #combine above allData = rbind(allWRIGHT2,allNews,allVignettes) # What about vignettes classified against the general population of genres allData <- rbind(allVignettes, newGenres_slim) allData <- allData %>% mutate(cluster = as.character(cluster)) # LET'S COMPARE THE RESULTS WITH OTHER GENRES (ads, poetry) #poetry allPoetry = read.csv("data/genreClass-4-13-16.csv", header=TRUE, fill = TRUE, sep = ",", row.names = NULL, stringsAsFactors = FALSE) allPoetry = allPoetry %>% filter(classified_genre == "poetry") names(allPoetry)[names(allPoetry)=="classified_genre"] <- "genre" names(allPoetry)[names(allPoetry)=="Text"] <- "text" allPoetry = allPoetry[,c("cluster","text","genre")] allPoetry = allPoetry %>% mutate(genre="unknown") allPoetry <- allPoetry[sample(1:nrow(allNews), 200,replace=FALSE),] #combine above allData = rbind(allWRIGHT2,allNews,allPoetry) #ads allAds = read.csv("output/justAds-5-23-16.csv", header=TRUE, fill = TRUE, sep = ",", row.names = NULL, stringsAsFactors = FALSE) allAds = allAds[,c("cluster","text","genre")] allAds = allAds %>% mutate(genre="unknown") allAds <- allAds[sample(1:nrow(allNews), 200,replace=FALSE),] #combine above allData = rbind(allWRIGHT2,allNews,allAds) #Trying to find other fiction. Instead of reading in vignettes, read in everything newData = beginData #from ClusterAnalysis.R newData$cluster <- as.character(newData$cluster) newData = newData %>% group_by(cluster) %>% slice(1) newData = newData %>% mutate(genre="unknown") newData = newData[,c("cluster","text","genre")] newData = newData %>% as.data.frame() #Sample data down to 5000 #newData <- newData[sample(1:nrow(newData), 5000,replace=FALSE),] #combine above allData = rbind(allWRIGHT2,allNews,allVignettes)
4,888
gpl-2.0
ccad15eb5a562b0d98e7d7d0a5a2eed595fc9f78
coolbutuseless/AuCensus2011
R/abs_files.R
#============================================================================= # Code for general file pathnames, manipulation etc #============================================================================= #' Path to ABS DataPack CSV file #' #' \code{create_abs_filename} creates the path to a given ABS datapack file. #' #' MFC TODO: Describe exactly the file layout. #' For now, root_dir = place where DataPack zip files were uncompressed to. #' #' @export #' @param profile The short code for the profile. e.g. 'BCP' for Basic Community Profile. #' @param table Table number including and suffix. e.g. 'B01', 'B08A' #' @param level The level of the statistcal area: [AUS, CED, GCCSA, IARE, ILOC, IREG, LGA, POA, RA, SA1, SA2, SA3, SA4, SED, SLA, SOS, SOSR, SSC, STE, SUA, UCL] #' @return Returns the full path to the CSV file containing the nominated data. #' @examples #' create_abs_filename('BCP', 'B46', 'AUS') #' create_abs_filename <- function(profile, table, level) { root_dir <- file.path(Sys.getenv('HOME'), "projectsdata/ABS2011/DataPacks/") if (level == 'AUS') { abs_filename <- paste0(root_dir, "2011_", profile, "_ALL_for_AUST_long-header/", "2011 Census ", profile, " All Geographies for AUST/", "/AUST/2011Census_", table, "_AUST_long.csv") } else { abs_filename <- paste0(root_dir, "2011_", profile, "_ALL_for_AUST_long-header/", "2011 Census ", profile, " All Geographies for AUST/", level, "/AUST/2011Census_", table, "_AUST_", level, "_long.csv") } abs_filename } #' Load an ABS DataPack file #' #' Given a profile, table & level, read the relevant ABS data into a data.frame #' #' Because of the size of the data, many tables are split over multiple files and numbered #' BxxA, BxxB, BxxC etc. Once a DataPack has over 200 columns (excluding the region_id column), #' further columns are spilled into the next file. #' \code{read_abs} will automatically read these multiple files and #' merge the data into one really really wide data.frame #' #' @importFrom dplyr "%>%" #' @export #' @param profile The short code for the profile. e.g. 'BCP' for Basic Community Profile. #' @param table Table number excluding suffix. e.g. 'B01', 'B08' #' @param level The level of the statistcal area: [AUS, CED, GCCSA, IARE, ILOC, IREG, LGA, POA, RA, SA1, SA2, SA3, SA4, SED, SLA, SOS, SOSR, SSC, STE, SUA, UCL] #' @param long If long==TRUE, then convert to long format, otherwise leave in wide format (default) #' @return Returns a data.frame of the data. #' @examples #' read_abs('BCP', 'B46', 'AUS') #' read_abs <- function(profile, table, level, long=FALSE) { # Find all the files that match the table name + wildcard filename.glob <- create_abs_filename(profile, paste0(table, "*"), level) filenames <- Sys.glob(filename.glob) message(paste("Reading", length(filenames), "file(s) which make up Table", table)) # Read all those files dfs <- lapply(filenames, readr::read_csv) # inner_join them all by region_id suppressMessages({ df <- Reduce(dplyr::inner_join, dfs) }) if (long) { # Convert from wide to long format. df <- df %>% tidyr::gather(colname, count, -region_id) %>% dplyr::mutate(colname = as.factor(as.character(colname))) } # Some codes redundantly have the level name as prefix, but nobody else does! So remove... code_replacer <- c('CED', 'LGA', 'POA', 'RA', 'SED', 'SOS', 'SOSR', 'SSC', 'UCL') if (level %in% code_replacer) { df$region_id <- as.integer(stringr::str_replace(df$region_id, as.character(level), '')) } if (level %in% asgs.info$level) { # Then we'll recode the region_id column to match the level name in the # ASGS Shapefiles so that we can do datamerges without losing information code_name <- asgs.info$code_name[asgs.info$level == level] colnames(df)[1] <- code_name } df }
4,101
mit
d58e7178a3b49ed65740a293c993e4e0fc8ad488
sbfnk/flusurvey
analysis/analysis_201112.R
library(data.table) library(ggplot2) library(reshape) symptoms <- c("fever","chills","blocked.runny.nose","sneezing","sore.throat","cough","shortness.breath","headache","muscle.and.or.joint.pain","chest.pain","tired","loss.appetite","phlegm","watery.eyes","nausea","vomiting","diarrhoea","stomach.ache","other") # compute the age in years from a birthdate (from) and the current date (to) age_years <- function(from, to) { if (is.na(from) || is.na(to)) { NA } else { lt <- as.POSIXlt(c(from, to)) age <- lt$year[2] - lt$year[1] mons <- lt$mon + lt$mday/50 if(mons[2] < mons[1]) age <- age -1 age } } logistic.regression.or.ci <- function(regress.out, level=0.95) { ################################################################ # # # This function takes the output from a glm # # (logistic model) command in R and provides not # # only the usual output from the summary command, but # # adds confidence intervals for all coefficients and OR’s. # # # # This version accommodates multiple regression parameters # # # ################################################################ usual.output <- summary(regress.out) z.quantile <- qnorm(1-(1-level)/2) number.vars <- length(regress.out$coefficients) OR <- exp(regress.out$coefficients[-1]) temp.store.result <- matrix(rep(NA, number.vars*2), nrow=number.vars) for(i in 1:number.vars) { temp.store.result[i,] <- summary(regress.out)$coefficients[i] + c(-1, 1) * z.quantile * summary(regress.out)$coefficients[i+number.vars] } intercept.ci <- temp.store.result[1,] slopes.ci <- temp.store.result[-1,] OR.ci <- exp(slopes.ci) output <- list(regression.table = usual.output, intercept.ci = intercept.ci, slopes.ci = slopes.ci, OR=OR, OR.ci = OR.ci) return(output) } # read tables sf <- read.csv('epidb_weekly.csv', sep=',', header=T) bf <- read.csv('epidb_intake.csv', sep=',', header=T) # create translation table so that every participant gets a unique ID number # (called global.id.number) translation <- data.frame(global_id = unique(bf$global_id)) translation$number <- seq(1,nrow(translation)) # assign global id numbers bf$global.id.number <- translation$number[match(bf$global_id, translation$global_id)] sf$global.id.number <- translation$number[match(sf$global_id, translation$global_id)] # put data in data tables (for the rolling join to be used later) st <- data.table(sf) bt <- data.table(bf) bt$bid <- seq(1:nrow(bt)) rm(sf) rm(bf) setnames(bt, 2, "global_id.bg") st$date <- as.Date(st$timestamp) bt$date <- as.Date(bt$timestamp) # rolling join of symptoms and background, by id number (first) and date # (second) setkey(st, global.id.number, date) setkey(bt, global.id.number, date) dt <- bt[st, roll=TRUE] #cleanup (some participants have only a weekly survey, no background one) dt <- dt[!is.na(country)] rm(bt) rm(st) # set convenient names setnames(dt, "Q0", "self") setnames(dt, "Q1", "gender") setnames(dt, "Q2", "birthmonth") setnames(dt, "Q3", "postcode") setnames(dt, "Q4", "occupation") setnames(dt, "Q4b_0_open", "work.postcode") setnames(dt, "Q4d_0", "no.education") setnames(dt, "Q4d_1", "education.gcse") setnames(dt, "Q4d_2", "education.alevels") setnames(dt, "Q4d_3", "education.bsc") setnames(dt, "Q4d_4", "education.msc") setnames(dt, "Q4d_5", "education.stillin") setnames(dt, "Q5_0", "frequent.contact.children") setnames(dt, "Q5_1", "frequent.contact.elderly") setnames(dt, "Q5_2", "frequent.contact.patients") setnames(dt, "Q5_3", "frequent.contact.people") setnames(dt, "Q6_0", "household.0.4") setnames(dt, "Q6_0_open", "nb.household.0.4") setnames(dt, "Q6_1", "household.5.18") setnames(dt, "Q6_1_open", "nb.household.5.18") setnames(dt, "Q6_2", "household.19.44") setnames(dt, "Q6_2_open", "nb.household.19.44") setnames(dt, "Q6_3", "household.45.64") setnames(dt, "Q6_3_open", "nb.household.45.64") setnames(dt, "Q6_4", "household.65+") setnames(dt, "Q6_4_open", "nb.household.65+") setnames(dt, "Q7", "transport") setnames(dt, "Q7b", "howlong.transport") setnames(dt, "Q9", "vaccine.last.year") setnames(dt, "Q10", "vaccine.this.year") setnames(dt, "Q10b_1_open", "date.vaccine") setnames(dt, "Q10c_0", "why.vaccine.riskgroup") setnames(dt, "Q10c_1", "why.vaccine.protected") setnames(dt, "Q10c_2", "why.vaccine.protect.others") setnames(dt, "Q10c_3", "why.vaccine.doctor") setnames(dt, "Q10c_4", "why.vaccine.work.recommended") setnames(dt, "Q10c_5", "why.vaccine.convenient") setnames(dt, "Q10c_6", "why.vaccine.free") setnames(dt, "Q10c_7", "why.vaccine.nomiss.work") setnames(dt, "Q10c_8", "why.vaccine.always") setnames(dt, "Q10c_9", "why.vaccine.other") setnames(dt, "Q10d_0", "why.not.vaccine.notyet") setnames(dt, "Q10d_1", "why.not.vaccine.notoffered") setnames(dt, "Q10d_2", "why.not.vaccine.norisk") setnames(dt, "Q10d_3", "why.not.vaccine.natural") setnames(dt, "Q10d_4", "why.not.vaccine.noteffective") setnames(dt, "Q10d_5", "why.not.vaccine.minor") setnames(dt, "Q10d_6", "why.not.vaccine.unlikely") setnames(dt, "Q10d_7", "why.not.vaccine.cause") setnames(dt, "Q10d_8", "why.not.vaccine.side.effects") setnames(dt, "Q10d_9", "why.not.vaccine.dont.like") setnames(dt, "Q10d_10", "why.not.vaccine.unavailable") setnames(dt, "Q10d_11", "why.not.vaccine.not.free") setnames(dt, "Q10d_12", "why.not.vaccine.no.reason") setnames(dt, "Q10d_13", "why.not.vaccine.doctor") setnames(dt, "Q10d_14", "why.not.vaccine.other") setnames(dt, "Q11_0", "norisk") setnames(dt, "Q11_1", "risk.asthma") setnames(dt, "Q11_2", "risk.diabetes") setnames(dt, "Q11_3", "risk.lung") setnames(dt, "Q11_4", "risk.heart") setnames(dt, "Q11_5", "risk.kidney") setnames(dt, "Q11_6", "risk.immune") setnames(dt, "Q12", "pregnant") setnames(dt, "Q13", "smoke") setnames(dt, "Q14_1", "allergy.hayfever") setnames(dt, "Q14_2", "allergy.dust") setnames(dt, "Q14_3", "allergy.animals") setnames(dt, "Q14_4", "allergy.other") setnames(dt, "Q14_5", "allergy.none") setnames(dt, "Q1_0", "no.symptoms") setnames(dt, "Q1_1", "fever") setnames(dt, "Q1_2", "chills") setnames(dt, "Q1_3", "blocked.runny.nose") setnames(dt, "Q1_4", "sneezing") setnames(dt, "Q1_5", "sore.throat") setnames(dt, "Q1_6", "cough") setnames(dt, "Q1_7", "shortness.breath") setnames(dt, "Q1_8", "headache") setnames(dt, "Q1_9", "muscle.and.or.joint.pain") setnames(dt, "Q1_10", "chest.pain") setnames(dt, "Q1_11", "tired") setnames(dt, "Q1_12", "loss.appetite") setnames(dt, "Q1_13", "phlegm") setnames(dt, "Q1_14", "watery.eyes") setnames(dt, "Q1_15", "nausea") setnames(dt, "Q1_16", "vomiting") setnames(dt, "Q1_17", "diarrhoea") setnames(dt, "Q1_18", "stomach.ache") setnames(dt, "Q1_19", "other") setnames(dt, "Q2.1", "same") setnames(dt, "Q3_0_open", "symptoms.start.date") setnames(dt, "Q4_0_open", "symptoms.end.date") setnames(dt, "Q5", "symptoms.suddenly") setnames(dt, "Q6_1_open.1", "fever.start") setnames(dt, "Q6b.1", "fever.suddenly") setnames(dt, "Q7_0", "visit.medical.service.no") setnames(dt, "Q7_1", "visit.medical.service.gp") setnames(dt, "Q7_2", "visit.medical.service.ae") setnames(dt, "Q7_3", "visit.medical.service.hospital") setnames(dt, "Q7_4", "visit.medical.service.other") setnames(dt, "Q7_5", "visit.medical.service.appointment") setnames(dt, "Q7b.1", "visit.medical.service.howsoon") setnames(dt, "Q8_0", "contact.medical.service.no") setnames(dt, "Q8_1", "contact.medical.service.gp.receptionist") setnames(dt, "Q8_2", "contact.medical.service.gp.doctor") setnames(dt, "Q8_3", "contact.medical.service.nhs") setnames(dt, "Q8_5", "contact.medical.service.other") setnames(dt, "Q9_0", "no.medication") setnames(dt, "Q9_1", "medication.painkillers") setnames(dt, "Q9_2", "medication.cough") setnames(dt, "Q9_3", "medication.antiviral") setnames(dt, "Q9_4", "medication.antibiotic") setnames(dt, "Q9_5", "medication.other") setnames(dt, "Q9_6", "medication.dontknow") setnames(dt, "Q10.1", "alter.routine") setnames(dt, "Q10c", "howlong.altered") setnames(dt, "Q12_multi_row1_col1", "howmany.household.ili") setnames(dt, "Q13_multi_row1_col1", "howmany.other.ili") # assign some useful variables: ili yes/no, number of reports, symptoms start # (as date), week of report, weight (for histograms later, # i.e. 1/(number of reports that week), and birthdate dt$ili <- ((dt$symptoms.suddenly == 0) & (dt$fever == "t" | dt$tired == "t" | dt$headache == "t" | dt$muscle.and.or.joint.pain =="t") & (dt$sore.throat == "t" | dt$cough =="t" | dt$shortness.breath =="t")) dt$ili <- as.numeric(dt$ili) dt$ili.notired <- ((dt$symptoms.suddenly == 0) & (dt$fever == "t" | dt$headache == "t" | dt$muscle.and.or.joint.pain =="t") & (dt$sore.throat == "t" | dt$cough =="t" | dt$shortness.breath =="t")) dt$ili.notired <- as.numeric(dt$ili.notired) dt$ili.fever <- ((dt$symptoms.suddenly == 0) & (dt$fever == "t") & (dt$sore.throat == "t" | dt$cough =="t" | dt$shortness.breath =="t")) dt$ili.fever <- as.numeric(dt$ili.fever) freq <- data.table(aggregate(dt$global.id.number, by=list(dt$global.id.number), length)) setkey(freq, Group.1) dt <- dt[freq] setnames(dt, "x", "nReports") mindate <- data.table(aggregate(dt$date, by=list(dt$global.id.number), min)) setkey(mindate, Group.1) dt <- dt[mindate] setnames(dt, "x", "mindate") maxdate <- data.table(aggregate(dt$date, by=list(dt$global.id.number), max)) setkey(maxdate, Group.1) dt <- dt[maxdate] setnames(dt, "x", "maxdate") dt$symptoms.start <- as.Date(dt$symptoms.start, "%Y-%m-%d") dt$week <- format(dt$date, format="%G-%W") dt[dt$week=="2011-00"]$week <- "2011-52" dt$weekweight <- 1/table(dt$week)[dt$week] dt$birthdate <- as.Date(dt$birthmonth, "%Y/%M/%d") # more variables to be used later dt$norisk <- factor(dt$norisk) dt$atrisk <- dt$norisk levels(dt$atrisk) <- c(1,0) dt$atrisk <- as.numeric(paste(dt$atrisk)) dt$age <- 0 dt$age <- apply(dt, 1, function(x) { age_years(as.Date(x["birthdate"]), as.Date(x["date"]))}) dt$agegroup <- cut(dt$age, breaks=c(0,18,45,65, max(dt$age, na.rm=T)), include.lowest=T, right=F) dt$vaccine.date <- as.Date(dt$date.vaccine, "%Y/%m/%d") dt$vaccine <- as.numeric(dt$vaccine.this.year==0 & (is.na(dt$vaccine.date) | dt$vaccine.date <= dt$date)) dt$children <- as.numeric((dt$household.0.4 == "t" | dt$household.5.18 == "t")) dt$symptoms.start.date <- as.Date(dt$symptoms.start.date, "%Y-%m-%d") dt$symptoms.end.date <- as.Date(dt$symptoms.end.date, "%Y-%m-%d") dt$symptoms.start.week <- format(dt$symptoms.start.date, format="%G-%W") dt[dt$symptoms.start.week=="2011-00"]$symptoms.start.week <- "2011-52" dt$ili.self <- (dt$Q11 == 0) dt[is.na(ili.self)]$ili.self <- FALSE dt$using.transport <- (dt$transport > 0) # one-per-user table # ds <- dt[!duplicated(dt$global.id.number)] # one-per-background-survey table ds <- dt[!duplicated(dt$bid)] ds$ili <- FALSE ds$nbili <- with(dt, aggregate(ili, ## list(global.id.number=global.id.number), list(bid=bid), sum))$x ds$ili <- (ds$nbili > 0) ds$vaccinated <- with(dt, aggregate(vaccine, ## list(global.id.number=global.id.number), list(bid=bid), sum))$x > 0 ds$nonili <- 1-ds$ili ds$smoking <- ds$smoke %in% c(1,2,3) ds$weight <- 0 for (i in 1:length(levels(factor(ds$country)))) { ds[country==levels(factor(ds$country))[i]]$weight <- 1/nrow(ds[country==levels(factor(ds$country))[i]]) } png("attack_rate.png") ggplot(ds[ili==T], aes(x=country, fill=country, weight=weight))+ geom_bar(color="black")+ theme_bw(20)+ opts(panel.grid.major=theme_blank(), panel.grid.minor=theme_blank(), title)+ scale_fill_brewer(palette="Set1")+ scale_y_continuous("attack rate", limits=c(0,1.01))+ opts(legend.position="none") dev.off() png("vaccination_coverage.png") ggplot(ds[vaccinated==T], aes(x=country, fill=country, weight=weight))+ geom_bar(color="black")+ theme_bw(20)+ opts(panel.grid.major=theme_blank(), panel.grid.minor=theme_blank(), title)+ scale_fill_brewer(palette="Set1")+ scale_y_continuous("vaccination coverage", limits=c(0,1.01))+ opts(legend.position="none") dev.off() ds$reweight <- 0 for (i in levels(factor(ds$country))) { for (j in levels(factor(ds$agegroup))) { ds[country==i & agegroup == j]$reweight <- 1/nrow(ds[country==i & agegroup==j]) } } png("vaccination_coverage_by_age.png") ggplot(ds[vaccinated==T], aes(x=agegroup, fill=agegroup, weight=reweight))+ geom_bar()+ geom_bar(color="black", show_guide=F)+ facet_grid(.~country)+ theme_bw(20)+ opts(panel.grid.major=theme_blank(), panel.grid.minor=theme_blank(), axis.ticks = theme_blank(), axis.text.x = theme_blank(), axis.title.x = theme_blank())+ scale_fill_brewer(name="age group", palette="Set1")+ scale_y_continuous("vaccination coverage", limits=c(0,1.01)) dev.off() ds$reweight <- 0 for (i in levels(factor(ds$country))) { for (j in levels(factor(ds$atrisk))) { ds[country==i & atrisk == j & agegroup %in% levels(agegroup)[1:3]]$reweight <- 1/nrow(ds[country==i & atrisk == j & agegroup %in% levels(agegroup)[1:3]]) } } png("vaccination_coverage_by_risk.png") ggplot(ds[vaccinated==T & agegroup %in% levels(agegroup)[1:3]], aes(x=factor(atrisk), fill=factor(atrisk), weight=reweight))+ geom_bar()+ geom_bar(color="black", show_guide=F)+ facet_grid(.~country)+ theme_bw(20)+ opts(panel.grid.major=theme_blank(), panel.grid.minor=theme_blank(), axis.ticks = theme_blank(), axis.text.x = theme_blank(), axis.title.x = theme_blank())+ scale_fill_brewer(name="Risk group", palette="Set1", labels=c("no", "yes"))+ scale_y_continuous("vaccination coverage", limits=c(0,1.01)) dev.off() png("age_dist.png") ggplot(ds, aes(x=country, fill=agegroup, weight=weight))+ geom_bar()+ geom_bar(color="black", show_guide=F)+ theme_bw(20)+ opts(panel.grid.major=theme_blank(), panel.grid.minor=theme_blank(), title)+ scale_fill_brewer(name="age group", palette="Set1")+ scale_y_continuous("age distribution", limits=c(0,1.01)) dev.off() vaccine_time <- data.frame() for (country in levels(factor(ds$country))) { vaccine_country <- data.frame(week=as.character(levels(factor(compare$week))), elderly=0, risk=0, all=0, country=country) for (i in 1:nrow(vaccine_country)) { vaccine_week <- compare[week <= vaccine_country[i,]$week] vaccine_country[i,]$all <- nrow(compare[week == vaccine_country[i,]$week & country == country & vaccine.this.year == 0]) / nrow(compare[week == vaccine_country[i,]$week & country == country]) vaccine_country[i,]$elderly <- nrow(compare[week == vaccine_country[i,]$week & country == country & vaccine.this.year == 0 & agegroup == levels(compare$agegroup)[4]]) / nrow(compare[week == vaccine_country[i,]$week & country == country & agegroup == levels(compare$agegroup)[4]]) vaccine_country[i,]$risk <- nrow(compare[week == vaccine_country[i,]$week & country == country & vaccine.this.year == 0 & atrisk == 1]) / nrow(compare[week == vaccine_country[i,]$week & country == country & atrisk == 1]) } vaccine_time <- rbind(vaccine_time, vaccine_country) } ds$education <- "" ds[no.education=="t"]$education <- "None" ds[education.gcse=="t"]$education <- "Intermediate" ds[education.alevels=="t"]$education <- "High school" ds[education.bsc=="t"]$education <- "Bachelor" ds[education.msc=="t"]$education <- "Higher" ds[education.stillin=="t"]$education <- "Student" ds$education <- factor(ds$education, levels=levels(factor(ds$education))[c(1,3,2,4,5,6,7)]) ds$reweight <- 0 for (i in levels(factor(ds$country))) { ds[country==i]$reweight <- 1/nrow(ds[education!="" & country==i]) } png("education_dist.png") ggplot(ds[education!=""], aes(x=country, fill=education, weight=reweight))+ geom_bar()+ geom_bar(color="black", show_guide=F)+ theme_bw(20)+ opts(panel.grid.major=theme_blank(), panel.grid.minor=theme_blank(), title)+ scale_fill_brewer(palette="Set1")+ scale_y_continuous("education distribution") dev.off() countries <- data.frame(country=levels(factor(ds$country)), aru = 0, arv = 0, ar = 0, efficacy = 0) for (i in 1:nrow(countries)) { countries[i,]$ar <- nrow(ds[country == countries[i,]$country & ili == T]) / nrow(ds[country == countries[i,]$country]) countries[i,]$aru <- nrow(ds[country == countries[i,]$country & ili == T & vaccinated == F]) / nrow(ds[country == countries[i,]$country & vaccinated == F]) countries[i,]$arv <- nrow(ds[country == countries[i,]$country & ili == T & vaccinated == T]) / nrow(ds[country == countries[i,]$country & vaccinated == T]) countries[i,]$efficacy <- (countries[i,]$aru - countries[i,]$arv) / countries[i,]$aru * 100 } # HPA stuff peak <- dt[country=="uk" & date > "2012-02-25" & date < "2012-04-09" & age > 17] peak <- peak[postcode!=""] peak$postcode <- toupper(peak$postcode) #peak$area <- toupper(sub("^([A-Za-z]+).+$", "\\1", peak$postcode)) postcodes <- data.table(read.csv("../postcodes.csv", header=F, sep=",")) setnames(postcodes, "V1", "postcode") setnames(postcodes, "V2", "region") postcodes[region=="W99999999"]$region <- "Wales" postcodes[region=="E12000001"]$region <- "North East England" postcodes[region=="E12000002"]$region <- "North West England" postcodes[region=="E12000003"]$region <- "Yorkshire and the Humber" postcodes[region=="E12000004"]$region <- "East Midlands" postcodes[region=="E12000005"]$region <- "West Midlands" postcodes[region=="E12000006"]$region <- "East of England" postcodes[region=="E12000007"]$region <- "London" postcodes[region=="E12000008"]$region <- "South East England" postcodes[region=="E12000009"]$region <- "South West England" postcodes[region=="L99999999"]$region <- "Channel Islands" postcodes[region=="N99999999"]$region <- "Northern Ireland" postcodes[region=="S99999999"]$region <- "Scotland" postcodes$postcode <- as.character(postcodes$postcode) peak <- join(peak,postcodes, by='postcode') peak$region <- factor(peak$region) peak <- peak[!(region %in% c("Scotland", "Channel Islands", "Northern Ireland"))] setkey(peak, global.id.number) nb.users.noclean <- nrow(peak[!duplicated(peak$global.id.number)]) # need to have reported in 3 intervals peak1 <- peak[date < "2012-03-12"] peak2 <- peak[date > "2012-03-10" & date < "2012-03-26"] peak3 <- peak[date > "2012-03-25"] max1date <- data.table(aggregate(peak1$date, by=list(peak1$global.id.number), max)) setkey(max1date, Group.1) peak <- peak[max1date] setnames(peak, "x", "max1date") min2date <- data.table(aggregate(peak2$date, by=list(peak2$global.id.number), min)) setkey(min2date, Group.1) peak <- peak[min2date] setnames(peak, "x", "min2date") max2date <- data.table(aggregate(peak2$date, by=list(peak2$global.id.number), max)) setkey(max2date, Group.1) peak <- peak[max2date] setnames(peak, "x", "max2date") min3date <- data.table(aggregate(peak3$date, by=list(peak3$global.id.number), min)) setkey(min3date, Group.1) peak <- peak[min3date] setnames(peak, "x", "min3date") maxdate <- data.table(aggregate(peak$date, by=list(peak$global.id.number), min)) setkey(maxdate, Group.1) peak <- peak[maxdate] setnames(peak, "x", "maxdate") peak$diff1 <- difftime(peak$min2date, peak$max1date, units='days') peak$diff2 <- difftime(peak$min3date, peak$max2date, units='days') peak <- peak[global.id.number %in% intersect( intersect( peak[date < "2012-03-12"]$global.id.number, peak[date > "2012-03-10" & date < "2012-03-26"]$global.id.number), peak[date > "2012-03-24"]$global.id.number)] peak <- peak[diff1<16 & diff2 < 16] peak.users <- peak[!duplicated(peak$global.id.number)] nb.users.clean <- nrow(peak.users) nb.users.noclean nb.users.clean nb.users.clean/nb.users.noclean # 0.5874409 # HPA definition peak.users[is.na(fever.suddenly)]$fever.suddenly <- 1 peak$ili.hpa <- as.numeric(peak$fever.suddenly == 0 & peak$cough =="t") peak[is.na(ili.hpa)]$ili.hpa <- 0 # remove the ones that were reported to have ended earlier or started later peak[symptoms.start.date > "2012-04-08"]$ili <- 0 peak[symptoms.start.date > "2012-04-08"]$ili.hpa <- 0 peak[symptoms.end.date < "2012-02-26"]$ili <- 0 peak[symptoms.end.date < "2012-02-26"]$ili.hpa <- 0 nrow(peak.users[gender==0])/nrow(peak.users[gender==1]) # 0.7365269 nrow(peak.users[age < 25])/nrow(peak.users) # 0.02988506 nrow(peak.users[age > 24 & age < 45])/nrow(peak.users) # 0.3436782 nrow(peak.users[age > 44 & age < 65])/nrow(peak.users) # 0.4551724 nrow(peak.users[age > 64])/nrow(peak.users) # 0.1712644 table(peak.users$region) / nrow(peak.users) table(peak.users$education.msc) / nrow(peak.users) table(peak.users$education.bsc) / nrow(peak.users) table(peak.users$education.alevels) / nrow(peak.users) table(peak.users$education.gcse) / nrow(peak.users) table(peak.users$no.education) / nrow(peak.users) table(peak.users$occupation) / nrow(peak.users) t <- rowSums(peak.users[,c(27,29,31,33,35),with=F], na.rm=T) table(t[t>0])/length(t[t>0]) nrow(peak.users[age<65]) table(dt[(dt$global.id.number %in% peak.users$global.id.number) & (!duplicated(dt$global.id.number)) & (norisk == "f") & (age < 65) ]$vaccine) / nrow(dt[(dt$global.id.number %in% peak.users$global.id.number) & (!duplicated(dt$global.id.number)) & (norisk == "f") & (age < 65) ]) table(dt[(dt$global.id.number %in% peak.users$global.id.number) & (!duplicated(dt$global.id.number)) & (age >= 65) ]$vaccine) / nrow(dt[(dt$global.id.number %in% peak.users$global.id.number) & (!duplicated(dt$global.id.number)) & (age >= 65) ]) table(dt[(dt$global.id.number %in% peak.users$global.id.number) & (!duplicated(dt$global.id.number)) & (pregnant == 0) ]$vaccine) / nrow(dt[(dt$global.id.number %in% peak.users$global.id.number) & (!duplicated(dt$global.id.number)) & (pregnant == 0) ]) table(peak.users[ (norisk == "f") & (age < 65) ]$vaccine) / nrow(peak.users[ (norisk == "f") & (age < 65) ]) table(peak.users[ (age >= 65) ]$vaccine) / nrow(peak.users[ (age >= 65) ]) table(peak.users[ (pregnant == 0) ]$vaccine) / nrow(peak.users[ (pregnant == 0) ]) for (symptom in c("fever", "chills", "blocked.runny.nose", "sneezing", "sore.throat", "cough", "shortness.breath", "headache", "muscle.and.or.joint.pain", "chest.pain", "tired", "loss.appetite", "phlegm", "watery.eyes", "nausea", "vomiting", "diarrhoea", "stomach.ache", "other")) { peak.users$nb <- with(peak, aggregate((get(symptom) == "t"), list(global.id.number=global.id.number), sum))$x peak.users <- peak.users[, which(!grepl(symptom, colnames(peak.users))), with=FALSE] peak.users <- peak.users[,symptom:=(nb>0), with=F] } for (symptom in c("fever.suddenly")) { peak <- peak[is.na(get(symptom)), symptom := -1, with=F] peak.users$nb <- with(peak, aggregate((get(symptom) == 0), list(global.id.number=global.id.number), sum))$x peak.users <- peak.users[, which(!grepl(symptom, colnames(peak.users))), with=FALSE] peak.users <- peak.users[,symptom:=(nb>0), with=F] } for (change in c("visit.medical.service.no", "contact.medical.service.no", "no.medication")) { peak.users$nb <- with(peak, aggregate((get(change) == "t"), list(global.id.number=global.id.number), sum))$x peak.users <- peak.users[, which(!grepl(change, colnames(peak.users))), with=FALSE] peak.users <- peak.users[,change:=(nb>0), with=F] } for (change in c("alter.routine")) { peak <- peak[is.na(get(change)), change := -1, with=F] peak.users$nb <- with(peak, aggregate((get(change) > 0), list(global.id.number=global.id.number), sum))$x peak.users <- peak.users[, which(!grepl(change, colnames(peak.users))), with=FALSE] peak.users <- peak.users[,change:=(nb>0), with=F] } for (change in c("absent")) { peak.users$nb <- with(peak, aggregate((get("alter.routine") == 1), list(global.id.number=global.id.number), sum))$x peak.users <- peak.users[, which(!grepl(change, colnames(peak.users))), with=FALSE] peak.users <- peak.users[,change:=(nb>0), with=F] } peak.users <- peak.users[, which(!grepl("nb", colnames(peak.users))), with=FALSE] peak.users$ili <- FALSE peak.users$nbili <- with(peak, aggregate(ili, list(global.id.number=global.id.number), sum))$x peak.users$ili <- (peak.users$nbili > 0) peak.users$ili.hpa <- FALSE peak.users$nbili.hpa <- with(peak, aggregate(ili.hpa, list(global.id.number=global.id.number), sum))$x peak.users$ili.hpa <- (peak.users$nbili.hpa > 0) peak.users$ili.fever <- FALSE peak.users$nbili.fever <- with(peak, aggregate(ili.fever, list(global.id.number=global.id.number), sum))$x peak.users$ili.fever <- (peak.users$nbili.fever > 0) peak$ili.self <- (peak$Q11 == 0) peak[is.na(ili.self)]$ili.self <- FALSE peak.users$ili.self <- FALSE peak.users$nbili.self <- with(peak, aggregate(ili.self, list(global.id.number=global.id.number), sum))$x peak.users$ili.self <- (peak.users$nbili.self > 0) # self-reported ILI table(peak.users$ili.self) table(peak.users$ili.self)/nrow(peak.users) table(peak.users[(norisk == "f") & (age < 65)]$ili.self) table(peak.users[(norisk == "f") & (age < 65)]$ili.self) / nrow(peak.users[(norisk == "f") & (age < 65)]) table(peak.users[(norisk == "f") & (age < 65) & (vaccine == 1)]$ili.self) table(peak.users[(norisk == "f") & (age < 65) & (vaccine == 1)]$ili.self) / nrow(peak.users[(norisk == "f") & (age < 65) & (vaccine == 1)]) table(peak.users[(norisk == "f") & (age < 65) & (vaccine == 0)]$ili.self) table(peak.users[(norisk == "f") & (age < 65) & (vaccine == 0)]$ili.self) / nrow(peak.users[(norisk == "f") & (age < 65) & (vaccine == 0)]) table(peak.users[(norisk == "f") & (age >= 65)]$ili.self) table(peak.users[(norisk == "f") & (age >= 65)]$ili.self) / nrow(peak.users[(norisk == "f") & (age >= 65)]) table(peak.users[(norisk == "f") & (age >= 65) & (vaccine == 1)]$ili.self) table(peak.users[(norisk == "f") & (age >= 65) & (vaccine == 1)]$ili.self) / nrow(peak.users[(norisk == "f") & (age >= 65) & (vaccine == 1)]) table(peak.users[(norisk == "f") & (age >= 65) & (vaccine == 0)]$ili.self) table(peak.users[(norisk == "f") & (age >= 65) & (vaccine == 0)]$ili.self) / nrow(peak.users[(norisk == "f") & (age >= 65) & (vaccine == 0)]) table(peak.users[pregnant == 0]$ili.self) table(peak.users[pregnant == 0]$ili.self) / nrow(peak.users[pregnant == 0]) table(peak.users[pregnant == 0 & (vaccine == 1)]$ili.self) table(peak.users[pregnant == 0 & (vaccine == 1)]$ili.self) / nrow(peak.users[pregnant == 0 & (vaccine == 1)]) table(peak.users[pregnant == 0 & (vaccine == 0)]$ili.self) table(peak.users[pregnant == 0 & (vaccine == 0)]$ili.self) / nrow(peak.users[pregnant == 0 & (vaccine == 0)]) peak.users$agegroup <- cut(peak.users$age, breaks=c(0,18,25,35,45,55,65,75, max(dt$age, na.rm=T)), include.lowest=T, right=F) table(peak.users[ili.self==1]$agegroup) table(peak.users[ili.self==1]$agegroup) / table(peak.users$agegroup) table(peak.users[ili.self==1]$gender) table(peak.users[ili.self==1]$gender) / table(peak.users$gender) table(peak.users[ili.self==1]$cough) table(peak.users[ili.self==1]$cough) / nrow(peak.users[ili.self==1]) table(peak.users[ili.self==1]$sore.throat) table(peak.users[ili.self==1]$sore.throat) / nrow(peak.users[ili.self==1]) table(peak.users[ili.self==1]$muscle.and.or.joint.pain) table(peak.users[ili.self==1]$muscle.and.or.joint.pain) / nrow(peak.users[ili.self==1]) table(peak.users[ili.self==1]$fever.suddenly) table(peak.users[ili.self==1]$fever.suddenly) / nrow(peak.users[ili.self==1]) table(peak.users[ili.self==1]$shortness.breath) table(peak.users[ili.self==1]$shortness.breath) / nrow(peak.users[ili.self==1]) table((peak.users[ili.self==1]$chills == TRUE | peak.users[ili.self==1]$blocked.runny.nose == TRUE | peak.users[ili.self==1]$sneezing == TRUE | peak.users[ili.self==1]$headache == TRUE | peak.users[ili.self==1]$chest.pain == TRUE | peak.users[ili.self==1]$tired == TRUE | peak.users[ili.self==1]$loss.appetite == TRUE | peak.users[ili.self==1]$phlegm == TRUE | peak.users[ili.self==1]$watery.eyes == TRUE | peak.users[ili.self==1]$nausea == TRUE | peak.users[ili.self==1]$vomiting == TRUE | peak.users[ili.self==1]$diarrhoea == TRUE | peak.users[ili.self==1]$stomach.ache == TRUE | peak.users[ili.self==1]$other == TRUE | (peak.users[ili.self==1]$fever == TRUE & peak.users[ili.self==1]$fever.suddenly == FALSE))) table((peak.users[ili.self==1]$chills == TRUE | peak.users[ili.self==1]$blocked.runny.nose == TRUE | peak.users[ili.self==1]$sneezing == TRUE | peak.users[ili.self==1]$headache == TRUE | peak.users[ili.self==1]$chest.pain == TRUE | peak.users[ili.self==1]$tired == TRUE | peak.users[ili.self==1]$loss.appetite == TRUE | peak.users[ili.self==1]$phlegm == TRUE | peak.users[ili.self==1]$watery.eyes == TRUE | peak.users[ili.self==1]$nausea == TRUE | peak.users[ili.self==1]$vomiting == TRUE | peak.users[ili.self==1]$diarrhoea == TRUE | peak.users[ili.self==1]$stomach.ache == TRUE | peak.users[ili.self==1]$other == TRUE | (peak.users[ili.self==1]$fever == TRUE & peak.users[ili.self==1]$fever.suddenly == FALSE))) / nrow(peak.users[ili.self==1]) table(peak.users[ili.self==1]$no.medication) table(peak.users[ili.self==1]$no.medication) / nrow(peak.users[ili.self==1]) table(peak.users[ili.self==1]$visit.medical.service.no) table(peak.users[ili.self==1]$visit.medical.service.no) / nrow(peak.users[ili.self==1]) table(peak.users[ili.self==1]$contact.medical.service.no) table(peak.users[ili.self==1]$contact.medical.service.no) / nrow(peak.users[ili.self==1]) table(peak.users[ili.self==1]$absent) table(peak.users[ili.self==1]$absent) / nrow(peak.users[ili.self==1]) # HPA definition table(peak.users$ili.hpa) table(peak.users$ili.hpa)/nrow(peak.users) table(peak.users[(norisk == "f") & (age < 65)]$ili.hpa) table(peak.users[(norisk == "f") & (age < 65)]$ili.hpa) / nrow(peak.users[(norisk == "f") & (age < 65)]) table(peak.users[(norisk == "f") & (age < 65) & (vaccine == 1)]$ili.hpa) table(peak.users[(norisk == "f") & (age < 65) & (vaccine == 1)]$ili.hpa) / nrow(peak.users[(norisk == "f") & (age < 65) & (vaccine == 1)]) table(peak.users[(norisk == "f") & (age < 65) & (vaccine == 0)]$ili.hpa) table(peak.users[(norisk == "f") & (age < 65) & (vaccine == 0)]$ili.hpa) / nrow(peak.users[(norisk == "f") & (age < 65) & (vaccine == 0)]) table(peak.users[(norisk == "f") & (age >= 65)]$ili.hpa) table(peak.users[(norisk == "f") & (age >= 65)]$ili.hpa) / nrow(peak.users[(norisk == "f") & (age >= 65)]) table(peak.users[(norisk == "f") & (age >= 65) & (vaccine == 1)]$ili.hpa) table(peak.users[(norisk == "f") & (age >= 65) & (vaccine == 1)]$ili.hpa) / nrow(peak.users[(norisk == "f") & (age >= 65) & (vaccine == 1)]) table(peak.users[(norisk == "f") & (age >= 65) & (vaccine == 0)]$ili.hpa) table(peak.users[(norisk == "f") & (age >= 65) & (vaccine == 0)]$ili.hpa) / nrow(peak.users[(norisk == "f") & (age >= 65) & (vaccine == 0)]) table(peak.users[pregnant == 0]$ili.hpa) table(peak.users[pregnant == 0]$ili.hpa) / nrow(peak.users[pregnant == 0]) table(peak.users[pregnant == 0 & (vaccine == 1)]$ili.hpa) table(peak.users[pregnant == 0 & (vaccine == 1)]$ili.hpa) / nrow(peak.users[pregnant == 0 & (vaccine == 1)]) table(peak.users[pregnant == 0 & (vaccine == 0)]$ili.hpa) table(peak.users[pregnant == 0 & (vaccine == 0)]$ili.hpa) / nrow(peak.users[pregnant == 0 & (vaccine == 0)]) peak.users$agegroup <- cut(peak.users$age, breaks=c(0,18,25,35,45,55,65,75, max(dt$age, na.rm=T)), include.lowest=T, right=F) table(peak.users[ili.hpa==1]$agegroup) table(peak.users[ili.hpa==1]$agegroup) / table(peak.users$agegroup) table(peak.users[ili.hpa==1]$gender) table(peak.users[ili.hpa==1]$gender) / table(peak.users$gender) table(peak.users[ili.hpa==1]$cough) table(peak.users[ili.hpa==1]$cough) / nrow(peak.users[ili.hpa==1]) table(peak.users[ili.hpa==1]$sore.throat) table(peak.users[ili.hpa==1]$sore.throat) / nrow(peak.users[ili.hpa==1]) table(peak.users[ili.hpa==1]$muscle.and.or.joint.pain) table(peak.users[ili.hpa==1]$muscle.and.or.joint.pain) / nrow(peak.users[ili.hpa==1]) table(peak.users[ili.hpa==1]$fever.suddenly) table(peak.users[ili.hpa==1]$fever.suddenly) / nrow(peak.users[ili.hpa==1]) table(peak.users[ili.hpa==1]$shortness.breath) table(peak.users[ili.hpa==1]$shortness.breath) / nrow(peak.users[ili.hpa==1]) table((peak.users[ili.hpa==1]$chills == TRUE | peak.users[ili.hpa==1]$blocked.runny.nose == TRUE | peak.users[ili.hpa==1]$sneezing == TRUE | peak.users[ili.hpa==1]$headache == TRUE | peak.users[ili.hpa==1]$chest.pain == TRUE | peak.users[ili.hpa==1]$tired == TRUE | peak.users[ili.hpa==1]$loss.appetite == TRUE | peak.users[ili.hpa==1]$phlegm == TRUE | peak.users[ili.hpa==1]$watery.eyes == TRUE | peak.users[ili.hpa==1]$nausea == TRUE | peak.users[ili.hpa==1]$vomiting == TRUE | peak.users[ili.hpa==1]$diarrhoea == TRUE | peak.users[ili.hpa==1]$stomach.ache == TRUE | peak.users[ili.hpa==1]$other == TRUE | (peak.users[ili.hpa==1]$fever == TRUE & peak.users[ili.hpa==1]$fever.suddenly == FALSE))) table((peak.users[ili.hpa==1]$chills == TRUE | peak.users[ili.hpa==1]$blocked.runny.nose == TRUE | peak.users[ili.hpa==1]$sneezing == TRUE | peak.users[ili.hpa==1]$headache == TRUE | peak.users[ili.hpa==1]$chest.pain == TRUE | peak.users[ili.hpa==1]$tired == TRUE | peak.users[ili.hpa==1]$loss.appetite == TRUE | peak.users[ili.hpa==1]$phlegm == TRUE | peak.users[ili.hpa==1]$watery.eyes == TRUE | peak.users[ili.hpa==1]$nausea == TRUE | peak.users[ili.hpa==1]$vomiting == TRUE | peak.users[ili.hpa==1]$diarrhoea == TRUE | peak.users[ili.hpa==1]$stomach.ache == TRUE | peak.users[ili.hpa==1]$other == TRUE | (peak.users[ili.hpa==1]$fever == TRUE & peak.users[ili.hpa==1]$fever.suddenly == FALSE))) / nrow(peak.users[ili.hpa==1]) table(peak.users[ili.hpa==1]$no.medication) table(peak.users[ili.hpa==1]$no.medication) / nrow(peak.users[ili.hpa==1]) table(peak.users[ili.hpa==1]$visit.medical.service.no) table(peak.users[ili.hpa==1]$visit.medical.service.no) / nrow(peak.users[ili.hpa==1]) table(peak.users[ili.hpa==1]$contact.medical.service.no) table(peak.users[ili.hpa==1]$contact.medical.service.no) / nrow(peak.users[ili.hpa==1]) table(peak.users[ili.hpa==1]$absent) table(peak.users[ili.hpa==1]$absent) / nrow(peak.users[ili.hpa==1]) # ECDC table(peak.users$ili) table(peak.users$ili)/nrow(peak.users) table(peak.users[(norisk == "f") & (age < 65)]$ili) table(peak.users[(norisk == "f") & (age < 65)]$ili) / nrow(peak.users[(norisk == "f") & (age < 65)]) table(peak.users[(norisk == "f") & (age < 65) & (vaccine == 1)]$ili) table(peak.users[(norisk == "f") & (age < 65) & (vaccine == 1)]$ili) / nrow(peak.users[(norisk == "f") & (age < 65) & (vaccine == 1)]) table(peak.users[(norisk == "f") & (age < 65) & (vaccine == 0)]$ili) table(peak.users[(norisk == "f") & (age < 65) & (vaccine == 0)]$ili) / nrow(peak.users[(norisk == "f") & (age < 65) & (vaccine == 0)]) table(peak.users[(norisk == "f") & (age >= 65)]$ili) table(peak.users[(norisk == "f") & (age >= 65)]$ili) / nrow(peak.users[(norisk == "f") & (age >= 65)]) table(peak.users[(norisk == "f") & (age >= 65) & (vaccine == 1)]$ili) table(peak.users[(norisk == "f") & (age >= 65) & (vaccine == 1)]$ili) / nrow(peak.users[(norisk == "f") & (age >= 65) & (vaccine == 1)]) table(peak.users[(norisk == "f") & (age >= 65) & (vaccine == 0)]$ili) table(peak.users[(norisk == "f") & (age >= 65) & (vaccine == 0)]$ili) / nrow(peak.users[(norisk == "f") & (age >= 65) & (vaccine == 0)]) table(peak.users[pregnant == 0]$ili) table(peak.users[pregnant == 0]$ili) / nrow(peak.users[pregnant == 0]) table(peak.users[pregnant == 0 & (vaccine == 1)]$ili) table(peak.users[pregnant == 0 & (vaccine == 1)]$ili) / nrow(peak.users[pregnant == 0 & (vaccine == 1)]) table(peak.users[pregnant == 0 & (vaccine == 0)]$ili) table(peak.users[pregnant == 0 & (vaccine == 0)]$ili) / nrow(peak.users[pregnant == 0 & (vaccine == 0)]) peak.users$agegroup <- cut(peak.users$age, breaks=c(0,18,25,35,45,55,65,75, max(dt$age, na.rm=T)), include.lowest=T, right=F) table(peak.users[ili==1]$agegroup) table(peak.users[ili==1]$agegroup) / table(peak.users$agegroup) table(peak.users[ili==1]$gender) table(peak.users[ili==1]$gender) / table(peak.users$gender) table(peak.users[ili==1]$cough) table(peak.users[ili==1]$cough) / nrow(peak.users[ili==1]) table(peak.users[ili==1]$sore.throat) table(peak.users[ili==1]$sore.throat) / nrow(peak.users[ili==1]) table(peak.users[ili==1]$muscle.and.or.joint.pain) table(peak.users[ili==1]$muscle.and.or.joint.pain) / nrow(peak.users[ili==1]) table(peak.users[ili==1]$fever.suddenly) table(peak.users[ili==1]$fever.suddenly) / nrow(peak.users[ili==1]) table(peak.users[ili==1]$shortness.breath) table(peak.users[ili==1]$shortness.breath) / nrow(peak.users[ili==1]) table((peak.users[ili==1]$chills == TRUE | peak.users[ili==1]$blocked.runny.nose == TRUE | peak.users[ili==1]$sneezing == TRUE | peak.users[ili==1]$headache == TRUE | peak.users[ili==1]$chest.pain == TRUE | peak.users[ili==1]$tired == TRUE | peak.users[ili==1]$loss.appetite == TRUE | peak.users[ili==1]$phlegm == TRUE | peak.users[ili==1]$watery.eyes == TRUE | peak.users[ili==1]$nausea == TRUE | peak.users[ili==1]$vomiting == TRUE | peak.users[ili==1]$diarrhoea == TRUE | peak.users[ili==1]$stomach.ache == TRUE | peak.users[ili==1]$other == TRUE | (peak.users[ili==1]$fever == TRUE & peak.users[ili==1]$fever.suddenly == FALSE))) table((peak.users[ili==1]$chills == TRUE | peak.users[ili==1]$blocked.runny.nose == TRUE | peak.users[ili==1]$sneezing == TRUE | peak.users[ili==1]$headache == TRUE | peak.users[ili==1]$chest.pain == TRUE | peak.users[ili==1]$tired == TRUE | peak.users[ili==1]$loss.appetite == TRUE | peak.users[ili==1]$phlegm == TRUE | peak.users[ili==1]$watery.eyes == TRUE | peak.users[ili==1]$nausea == TRUE | peak.users[ili==1]$vomiting == TRUE | peak.users[ili==1]$diarrhoea == TRUE | peak.users[ili==1]$stomach.ache == TRUE | peak.users[ili==1]$other == TRUE | (peak.users[ili==1]$fever == TRUE & peak.users[ili==1]$fever.suddenly == FALSE))) / nrow(peak.users[ili==1]) table(peak.users[ili==1]$no.medication) table(peak.users[ili==1]$no.medication) / nrow(peak.users[ili==1]) table(peak.users[ili==1]$visit.medical.service.no) table(peak.users[ili==1]$visit.medical.service.no) / nrow(peak.users[ili==1]) table(peak.users[ili==1]$contact.medical.service.no) table(peak.users[ili==1]$contact.medical.service.no) / nrow(peak.users[ili==1]) table(peak.users[ili==1]$absent) table(peak.users[ili==1]$absent) / nrow(peak.users[ili==1]) # ECDC + fever table(peak.users$ili.fever) table(peak.users$ili.fever)/nrow(peak.users) table(peak.users[(norisk == "f") & (age < 65)]$ili.fever) table(peak.users[(norisk == "f") & (age < 65)]$ili.fever) / nrow(peak.users[(norisk == "f") & (age < 65)]) table(peak.users[(norisk == "f") & (age < 65) & (vaccine == 1)]$ili.fever) table(peak.users[(norisk == "f") & (age < 65) & (vaccine == 1)]$ili.fever) / nrow(peak.users[(norisk == "f") & (age < 65) & (vaccine == 1)]) table(peak.users[(norisk == "f") & (age < 65) & (vaccine == 0)]$ili.fever) table(peak.users[(norisk == "f") & (age < 65) & (vaccine == 0)]$ili.fever) / nrow(peak.users[(norisk == "f") & (age < 65) & (vaccine == 0)]) table(peak.users[(norisk == "f") & (age >= 65)]$ili.fever) table(peak.users[(norisk == "f") & (age >= 65)]$ili.fever) / nrow(peak.users[(norisk == "f") & (age >= 65)]) table(peak.users[(norisk == "f") & (age >= 65) & (vaccine == 1)]$ili.fever) table(peak.users[(norisk == "f") & (age >= 65) & (vaccine == 1)]$ili.fever) / nrow(peak.users[(norisk == "f") & (age >= 65) & (vaccine == 1)]) table(peak.users[(norisk == "f") & (age >= 65) & (vaccine == 0)]$ili.fever) table(peak.users[(norisk == "f") & (age >= 65) & (vaccine == 0)]$ili.fever) / nrow(peak.users[(norisk == "f") & (age >= 65) & (vaccine == 0)]) table(peak.users[pregnant == 0]$ili.fever) table(peak.users[pregnant == 0]$ili.fever) / nrow(peak.users[pregnant == 0]) table(peak.users[pregnant == 0 & (vaccine == 1)]$ili.fever) table(peak.users[pregnant == 0 & (vaccine == 1)]$ili.fever) / nrow(peak.users[pregnant == 0 & (vaccine == 1)]) table(peak.users[pregnant == 0 & (vaccine == 0)]$ili.fever) table(peak.users[pregnant == 0 & (vaccine == 0)]$ili.fever) / nrow(peak.users[pregnant == 0 & (vaccine == 0)]) peak.users$agegroup <- cut(peak.users$age, breaks=c(0,18,25,35,45,55,65,75, max(dt$age, na.rm=T)), include.lowest=T, right=F) table(peak.users[ili.fever==1]$agegroup) table(peak.users[ili.fever==1]$agegroup) / table(peak.users$agegroup) table(peak.users[ili.fever==1]$gender) table(peak.users[ili.fever==1]$gender) / table(peak.users$gender) table(peak.users[ili.fever==1]$cough) table(peak.users[ili.fever==1]$cough) / nrow(peak.users[ili.fever==1]) table(peak.users[ili.fever==1]$sore.throat) table(peak.users[ili.fever==1]$sore.throat) / nrow(peak.users[ili.fever==1]) table(peak.users[ili.fever==1]$muscle.and.or.joint.pain) table(peak.users[ili.fever==1]$muscle.and.or.joint.pain) / nrow(peak.users[ili.fever==1]) table(peak.users[ili.fever==1]$fever.suddenly) table(peak.users[ili.fever==1]$fever.suddenly) / nrow(peak.users[ili.fever==1]) table(peak.users[ili.fever==1]$shortness.breath) table(peak.users[ili.fever==1]$shortness.breath) / nrow(peak.users[ili.fever==1]) table((peak.users[ili.fever==1]$chills == TRUE | peak.users[ili.fever==1]$blocked.runny.nose == TRUE | peak.users[ili.fever==1]$sneezing == TRUE | peak.users[ili.fever==1]$headache == TRUE | peak.users[ili.fever==1]$chest.pain == TRUE | peak.users[ili.fever==1]$tired == TRUE | peak.users[ili.fever==1]$loss.appetite == TRUE | peak.users[ili.fever==1]$phlegm == TRUE | peak.users[ili.fever==1]$watery.eyes == TRUE | peak.users[ili.fever==1]$nausea == TRUE | peak.users[ili.fever==1]$vomiting == TRUE | peak.users[ili.fever==1]$diarrhoea == TRUE | peak.users[ili.fever==1]$stomach.ache == TRUE | peak.users[ili.fever==1]$other == TRUE | (peak.users[ili.fever==1]$fever == TRUE & peak.users[ili.fever==1]$fever.suddenly == FALSE))) table((peak.users[ili.fever==1]$chills == TRUE | peak.users[ili.fever==1]$blocked.runny.nose == TRUE | peak.users[ili.fever==1]$sneezing == TRUE | peak.users[ili.fever==1]$headache == TRUE | peak.users[ili.fever==1]$chest.pain == TRUE | peak.users[ili.fever==1]$tired == TRUE | peak.users[ili.fever==1]$loss.appetite == TRUE | peak.users[ili.fever==1]$phlegm == TRUE | peak.users[ili.fever==1]$watery.eyes == TRUE | peak.users[ili.fever==1]$nausea == TRUE | peak.users[ili.fever==1]$vomiting == TRUE | peak.users[ili.fever==1]$diarrhoea == TRUE | peak.users[ili.fever==1]$stomach.ache == TRUE | peak.users[ili.fever==1]$other == TRUE | (peak.users[ili.fever==1]$fever == TRUE & peak.users[ili.fever==1]$fever.suddenly == FALSE))) / nrow(peak.users[ili.fever==1]) table(peak.users[ili.fever==1]$no.medication) table(peak.users[ili.fever==1]$no.medication) / nrow(peak.users[ili.fever==1]) table(peak.users[ili.fever==1]$visit.medical.service.no) table(peak.users[ili.fever==1]$visit.medical.service.no) / nrow(peak.users[ili.fever==1]) table(peak.users[ili.fever==1]$contact.medical.service.no) table(peak.users[ili.fever==1]$contact.medical.service.no) / nrow(peak.users[ili.fever==1]) table(peak.users[ili.fever==1]$absent) table(peak.users[ili.fever==1]$absent) / nrow(peak.users[ili.fever==1]) peak.users$agegroup2 <- cut(peak.users$age, breaks=c(0,20,30,40,50,60,70,80, max(dt$age, na.rm=T)), include.lowest=T, right=F) # table(peak.users[ili.self==1 & # absent==T]$agegroup2)/table(peak.users[ili.self==1]$agegroup2) absent.age <- as.vector(table(peak.users[ili.self==1 & absent==T]$agegroup2)/ table(peak.users[ili.self==1]$agegroup2)) absent.age[is.nan(absent.age)] <- 0 agegroup.absent <- data.table(age=levels(peak.users$agegroup2), absent=absent.age) png("absenteeism.png", width=640) ggplot(agegroup.absent[-1], aes(x=age, y=absent*100, group=1))+ geom_line()+ theme_bw(20)+ opts(panel.grid.major=theme_blank(), panel.grid.minor=theme_blank())+ scale_y_continuous("%", limits=c(0,80)) dev.off() table(peak.users[vaccine==0]$ili.self) table(peak.users[vaccine==1]$ili.self) table(peak.users[vaccine==0]$ili.hpa) table(peak.users[vaccine==1]$ili.hpa) m <- data.table(melt(peak, measure.vars=c("ili.self", "ili.hpa"))) png("ili_date.png", width=640) ggplot(m[value == 1 & symptoms.start.date>"2012-02-23"], aes(x=symptoms.start.date, fill=variable))+ geom_histogram(binwidth=2, position="dodge")+ scale_fill_brewer("ILI", labels=c("Self-reported", "HPA definition"), palette="Set1")+ theme_bw(20)+ opts(panel.grid.major=theme_blank(), panel.grid.minor=theme_blank())+ scale_y_continuous("Count")+ scale_x_date("Date") dev.off() png("ili_week.png", width=640) ggplot(m[value == 1 & symptoms.start.date>"2012-02-23"], aes(x=symptoms.start.date, fill=variable))+ geom_histogram(binwidth=7, position="dodge")+ scale_fill_brewer("ILI", labels=c("Self-reported", "HPA definition"), palette="Set1")+ theme_bw(20)+ opts(panel.grid.major=theme_blank(), panel.grid.minor=theme_blank())+ scale_y_continuous("Count")+ scale_x_date("Week", labels=c("",8,9,10,11,12,"")) dev.off() # whole season whole.users <- dt[!duplicated(dt$bid)] whole.users$vaccinated <- with(dt, aggregate(vaccine, ## list(global.id.number=global.id.number), list(bid=bid), sum))$x > 0 for (symptom in c("fever", "chills", "blocked.runny.nose", "sneezing", "sore.throat", "cough", "shortness.breath", "headache", "muscle.and.or.joint.pain", "chest.pain", "tired", "loss.appetite", "phlegm", "watery.eyes", "nausea", "vomiting", "diarrhoea", "stomach.ache", "other")) { whole.users$nb <- with(dt, aggregate((get(symptom) == "t"), list(bid=bid), sum))$x whole.users <- whole.users[, which(!grepl(symptom, colnames(whole.users))), with=FALSE] whole.users <- whole.users[,symptom:=(nb>0), with=F] } for (symptom in c("fever.suddenly")) { dt <- dt[is.na(get(symptom)), symptom := -1, with=F] whole.users$nb <- with(dt, aggregate((get(symptom) == 0), list(bid=bid), sum))$x whole.users <- whole.users[, which(!grepl(symptom, colnames(whole.users))), with=FALSE] whole.users <- whole.users[,symptom:=(nb>0), with=F] } for (change in c("visit.medical.service.no", "contact.medical.service.no", "no.medication")) { whole.users$nb <- with(dt, aggregate((get(change) == "t"), list(bid=bid), sum))$x whole.users <- whole.users[, which(!grepl(change, colnames(whole.users))), with=FALSE] whole.users <- whole.users[,change:=(nb>0), with=F] } for (change in c("alter.routine")) { dt <- dt[is.na(get(change)), change := -1, with=F] whole.users$nb <- with(dt, aggregate((get(change) > 0), list(bid=bid), sum))$x whole.users <- whole.users[, which(!grepl(change, colnames(whole.users))), with=FALSE] whole.users <- whole.users[,change:=(nb>0), with=F] } for (change in c("absent")) { whole.users$nb <- with(dt, aggregate((get("alter.routine") == 1), list(bid=bid), sum))$x whole.users <- whole.users[, which(!grepl(change, colnames(whole.users))), with=FALSE] whole.users <- whole.users[,change:=(nb>0), with=F] } whole.users <- whole.users[, which(!grepl("nb", colnames(whole.users))), with=FALSE] whole.users$ili <- FALSE whole.users$nbili <- with(dt, aggregate(ili, list(bid=bid), sum))$x whole.users$ili <- (whole.users$nbili > 0) whole.users$ili.fever <- FALSE whole.users$nbili.fever <- with(dt, aggregate(ili.fever, list(bid=bid), sum))$x whole.users$ili.fever <- (whole.users$nbili.fever > 0) whole.users[is.na(ili.fever)]$ili.fever <- F whole.users$ili.self <- FALSE whole.users$nbili.self <- with(dt, aggregate(ili.self, list(bid=bid), sum))$x whole.users$ili.self <- (whole.users$nbili.self > 0) whole.users$agegroup2 <- cut(whole.users$age, breaks=c(0,20,30,40,50,60,70,80, max(dt$age, na.rm=T)), include.lowest=T, right=F) whole.users$daycare <- (whole.users$Q6b>0) whole.users[is.na(daycare)]$daycare <- F whole.users$frequent.contact <- (whole.users$frequent.contact.children == "t" | whole.users$frequent.contact.elderly == "t" | whole.users$frequent.contact.people == "t") whole.users$smoking <- whole.users$smoke %in% c(1,2,3) # higher education etc nrow(ds[country=="uk" & ili==T])/nrow(ds[country=="uk"])*100 nrow(ds[country=="uk" & ili==T & age < 20])/nrow(ds[country=="uk" & age < 20])*100 nrow(ds[country=="uk" & ili==T & age >= 20 & age < 45])/nrow(ds[country=="uk" & age >=20 & age < 45])*100 nrow(ds[country=="uk" & ili==T & age >= 45])/nrow(ds[country=="uk" & age >= 45])*100 nrow(ds[country=="uk" & ili==T & atrisk == 1])/nrow(ds[country=="uk" & atrisk == 1])*100 ds$vmsg <- with(dt2, aggregate(vmsg, list(global.id.number=global.id.number), sum))$x ds$vm <- (ds$vmsg > 0) nrow(ds[country=="uk" & ili==T & vm == 1])/nrow(ds[country=="uk"])*100 # active users #dt$active <- (dt$nReports > 4 & # cohorts # exclude users with bad age temp.data <- dt[!is.na(age)] temp.data$agegroup <- factor(temp.data$agegroup) temp.data <- temp.data[duplicated(dt$global.id.number)] temp.data$newili <- temp.data$ili temp.data$newili.notired <- temp.data$ili.notired temp.data$newili.fever <- temp.data$ili.fever temp.data[same==0, newili := 0] temp.data[same==0, newili.notired := 0] temp.data[same==0, newili.fever := 0] levels(temp.data$agegroup) <- c("<18","18-44","45-64","65+") r <- ftable(temp.data$vaccine, temp.data$atrisk, temp.data$children, temp.data$agegroup, temp.data$week, temp.data$country, temp.data$newili, row.vars=rev(1:6)) vaccination.raw.data <- data.frame(expand.grid(rev(attr(r, "row.vars"))), unclass(r)) names(vaccination.raw.data) <- c("vaccinated","risk","children","agegroup","year-week","country","non_ili","ili") write.csv(vaccination.raw.data, "cohorts_201112.raw", quote=F, row.names=F) r <- ftable(temp.data$vaccine, temp.data$atrisk, temp.data$children, temp.data$agegroup, temp.data$week, temp.data$country, temp.data$newili.notired, row.vars=rev(1:6)) vaccination.raw.data <- data.frame(expand.grid(rev(attr(r, "row.vars"))), unclass(r)) names(vaccination.raw.data) <- c("vaccinated","risk","children","agegroup","year-week","country","non_ili","ili") write.csv(vaccination.raw.data, "cohorts_notired_201112.raw", quote=F, row.names=F) r <- ftable(temp.data$vaccine, temp.data$atrisk, temp.data$children, temp.data$agegroup, temp.data$week, temp.data$country, temp.data$newili.fever, row.vars=rev(1:6)) vaccination.raw.data <- data.frame(expand.grid(rev(attr(r, "row.vars"))), unclass(r)) names(vaccination.raw.data) <- c("vaccinated","risk","children","agegroup","year-week","country","non_ili","ili") write.csv(vaccination.raw.data, "cohorts_fever_201112.raw", quote=F, row.names=F) # GI stuff dt$gi.or <- as.numeric(dt$diarrhoea == "t" | dt$vomiting == "t" | dt$nausea == "t") dt$gi.and <- as.numeric(dt$diarrhoea == "t" & dt$vomiting == "t" & dt$nausea == "t") dt$gi.or.novom <- as.numeric(dt$diarrhoea == "t" | dt$nausea == "t") dt$gi.and.novom <- as.numeric(dt$diarrhoea == "t" & dt$nausea == "t") dt$newgi.or <- dt$gi.or dt$newgi.and <- dt$gi.and dt$newgi.or.novom <- dt$gi.or.novom dt$newgi.and.novom <- dt$gi.and.novom dt[same==0, newgi.or := 0] dt[same==0, newgi.and := 0] dt[same==0, newgi.or.novom := 0] dt[same==0, newgi.and.novom := 0] r.or <- ftable(dt[country == "uk"]$week, dt[country=="uk"]$newgi.or, row.vars=1) r.and <- ftable(dt[country == "uk"]$week, dt[country=="uk"]$newgi.and, row.vars=1) r.or.novom <- ftable(dt[country == "uk"]$week, dt[country=="uk"]$newgi.or.novom, row.vars=1) r.and.novom <- ftable(dt[country == "uk"]$week, dt[country=="uk"]$newgi.and.novom, row.vars=1) gi.or.raw.data <- data.frame(expand.grid(rev(attr(r.or, "row.vars"))), unclass(r.or)) gi.and.raw.data <- data.frame(expand.grid(rev(attr(r.and, "row.vars"))), unclass(r.and)) gi.or.novom.raw.data <- data.frame(expand.grid(rev(attr(r.or.novom, "row.vars"))), unclass(r.or.novom)) gi.and.novom.raw.data <- data.frame(expand.grid(rev(attr(r.and.novom, "row.vars"))), unclass(r.and.novom)) names(gi.or.raw.data) <- c("Week", "nongi", "gi") names(gi.and.raw.data) <- c("Week", "nongi", "gi") names(gi.or.novom.raw.data) <- c("Week", "nongi", "gi") names(gi.and.novom.raw.data) <- c("Week", "nongi", "gi") gi.or.raw.data$gi.incidence <- gi.or.raw.data$gi / (gi.or.raw.data$nongi + gi.or.raw.data$nongi) gi.and.raw.data$gi.incidence <- gi.and.raw.data$gi / (gi.and.raw.data$nongi + gi.and.raw.data$nongi) gi.or.novom.raw.data$gi.incidence <- gi.or.novom.raw.data$gi / (gi.or.novom.raw.data$nongi + gi.or.novom.raw.data$nongi) gi.and.novom.raw.data$gi.incidence <- gi.and.novom.raw.data$gi / (gi.and.novom.raw.data$nongi + gi.and.novom.raw.data$nongi) gi.or.12 <- gi.or.raw.data[-c(1:3, 22:26),] gi.and.12 <- gi.and.raw.data[-c(1:3, 22:26),] gi.or.novom.12 <- gi.or.novom.raw.data[-c(1:3, 22:26),] gi.and.novom.12 <- gi.and.novom.raw.data[-c(1:3, 22:26),] write.csv(gi.or.12, "gi_or_201112.csv", quote=F, row.names=F) write.csv(gi.and.12, "gi_and_201112.csv", quote=F, row.names=F) write.csv(gi.or.novom.12, "gi_or_novom_201112.csv", quote=F, row.names=F) write.csv(gi.and.novom.12, "gi_and_novom_201112.csv", quote=F, row.names=F) # logistic regressions whole.users$notvaccinated <- !(whole.users$vaccinated) season <- logistic.regression.or.ci(glm(ili ~ notvaccinated + children + agegroup + country + frequent.contact + atrisk + gender, data=whole.users, family=binomial)) regressions <- data.table(yearweek=levels(factor(dt$week))) setkey(regressions, yearweek) for (variable in names(season$OR)) { regressions <- regressions[,variable := 0.0,with=F] regressions <- regressions[,paste(variable, ".ci.low", sep="") := 0.0,with=F] regressions <- regressions[,paste(variable, ".ci.high", sep="") := 0.0,with=F] } for (thisweek in levels(factor(dt$week))) { week.all <- dt[week == thisweek] week.users <- week.all[!duplicated(week.all$bid)] week.users$vaccinated <- with(week.all, aggregate(vaccine, ## list(global.id.number=global.id.number), list(bid=bid), sum))$x > 0 for (symptom in c("fever", "chills", "blocked.runny.nose", "sneezing", "sore.throat", "cough", "shortness.breath", "headache", "muscle.and.or.joint.pain", "chest.pain", "tired", "loss.appetite", "phlegm", "watery.eyes", "nausea", "vomiting", "diarrhoea", "stomach.ache", "other")) { week.users$nb <- with(week.all, aggregate((get(symptom) == "t"), list(bid=bid), sum))$x week.users <- week.users[, which(!grepl(symptom, colnames(week.users))), with=FALSE] week.users <- week.users[,symptom:=(nb>0), with=F] } for (symptom in c("fever.suddenly")) { week.all <- week.all[is.na(get(symptom)), symptom := -1, with=F] week.users$nb <- with(week.all, aggregate((get(symptom) == 0), list(bid=bid), sum))$x week.users <- week.users[, which(!grepl(symptom, colnames(week.users))), with=FALSE] week.users <- week.users[,symptom:=(nb>0), with=F] } for (change in c("visit.medical.service.no", "contact.medical.service.no", "no.medication")) { week.users$nb <- with(week.all, aggregate((get(change) == "t"), list(bid=bid), sum))$x week.users <- week.users[, which(!grepl(change, colnames(week.users))), with=FALSE] week.users <- week.users[,change:=(nb>0), with=F] } for (change in c("alter.routine")) { week.all <- week.all[is.na(get(change)), change := -1, with=F] week.users$nb <- with(week.all, aggregate((get(change) > 0), list(bid=bid), sum))$x week.users <- week.users[, which(!grepl(change, colnames(week.users))), with=FALSE] week.users <- week.users[,change:=(nb>0), with=F] } for (change in c("absent")) { week.users$nb <- with(week.all, aggregate((get("alter.routine") == 1), list(bid=bid), sum))$x week.users <- week.users[, which(!grepl(change, colnames(week.users))), with=FALSE] week.users <- week.users[,change:=(nb>0), with=F] } week.users <- week.users[, which(!grepl("nb", colnames(week.users))), with=FALSE] week.users$ili <- FALSE week.users$nbili <- with(week.all, aggregate(ili, list(bid=bid), sum))$x week.users$ili <- (week.users$nbili > 0) week.users$ili.fever <- FALSE week.users$nbili.fever <- with(week.all, aggregate(ili.fever, list(bid=bid), sum))$x week.users$ili.fever <- (week.users$nbili.fever > 0) week.users <- week.users[is.na(ili.fever), "ili.fever" := F, with=F] week.all$ili.self <- (week.all$Q11 == 0) week.all[is.na(ili.self)]$ili.self <- FALSE week.users$ili.self <- FALSE week.users$nbili.self <- with(week.all, aggregate(ili.self, list(bid=bid), sum))$x week.users$ili.self <- (week.users$nbili.self > 0) week.users$agegroup2 <- cut(week.users$age, breaks=c(0,20,30,40,50,60,70,80, max(dt$age, na.rm=T)), include.lowest=T, right=F) week.users$daycare <- (week.users$Q6b>0) week.users[is.na(daycare)]$daycare <- F week.users$frequent.contact <- (week.users$frequent.contact.children == "t" | week.users$frequent.contact.elderly == "t" | week.users$frequent.contact.people == "t") week.users$smoking <- week.users$smoke %in% c(1,2,3) week.users$notvaccinated <- !(week.users$vaccinated) week.regression <- logistic.regression.or.ci(glm(ili ~ notvaccinated + children + agegroup + country + frequent.contact + atrisk + gender, data=week.users, family=binomial)) for (i in 1:length(names(week.regression$OR))) { # for (variable in names(week.regression$OR)) { ## regressions <- regressions[thisweek, variable := ## week.regression$OR[[variable]], with=F] regressions <- regressions[thisweek, names(week.regression$OR[i]) := week.regression$OR[[i]], with=F] regressions <- regressions[thisweek, paste(names(week.regression$OR[i]), ".ci.low", sep="") := week.regression$OR.ci[i,1], with=F] regressions <- regressions[thisweek, paste(names(week.regression$OR[i]), ".ci.high", sep="") := week.regression$OR.ci[i,2], with=F] } } regressions$year <- as.numeric(substr(regressions$yearweek, 1, 4)) regressions$week <- as.numeric(substr(regressions$yearweek, 6, 7)) regressions$date <- as.Date(strptime(paste(regressions$year, regressions$week*7,sep=" "),format="%Y %j"))+5 for (variable in names(season$OR)) { # filename <- gsub("[,\\[)]", "", gsub("\\]", "", names(season$OR)[1])) pdf(paste(variable, "3.pdf", sep="")) print( ggplot(regressions[yearweek > "2011-45" & yearweek < "2012-14"], aes(x=date, y=get(variable)))+ geom_line()+ geom_errorbar(aes(ymin = get(paste(variable, ".ci.low", sep="")), ymax = get(paste(variable, ".ci.high", sep=""))))+ geom_point(size=3, shape=21, fill="white")+ scale_y_continuous(name="Weekly odds ratio")+ theme_bw(30)+ scale_x_date(name="")+ theme(panel.grid.major=element_blank(), panel.grid.minor=element_blank())+ geom_abline(intercept=1, slope=0) ) dev.off() png(paste(variable, "3.png", sep="")) print( ggplot(regressions[yearweek > "2011-45" & yearweek < "2012-14"], aes(x=date, y=get(variable)))+ geom_line()+ geom_errorbar(aes(ymin = get(paste(variable, ".ci.low", sep="")), ymax = get(paste(variable, ".ci.high", sep=""))))+ geom_point(size=3, shape=21, fill="white")+ scale_y_continuous(name="Weekly odds ratio")+ theme_bw(30)+ scale_x_date(name="")+ theme(panel.grid.major=element_blank(), panel.grid.minor=element_blank())+ geom_abline(intercept=1, slope=0) ) dev.off() } # cumulative regressions cregressions <- data.table(yearweek=levels(factor(dt$week))) setkey(cregressions, yearweek) for (variable in names(season$OR)) { cregressions <- cregressions[,variable := 0.0,with=F] } for (thisweek in levels(factor(dt$week))) { week.all <- dt[week <= thisweek] week.users <- week.all[!duplicated(week.all$bid)] week.users$vaccinated <- with(week.all, aggregate(vaccine, ## list(global.id.number=global.id.number), list(bid=bid), sum))$x > 0 for (symptom in c("fever", "chills", "blocked.runny.nose", "sneezing", "sore.throat", "cough", "shortness.breath", "headache", "muscle.and.or.joint.pain", "chest.pain", "tired", "loss.appetite", "phlegm", "watery.eyes", "nausea", "vomiting", "diarrhoea", "stomach.ache", "other")) { week.users$nb <- with(week.all, aggregate((get(symptom) == "t"), list(bid=bid), sum))$x week.users <- week.users[, which(!grepl(symptom, colnames(week.users))), with=FALSE] week.users <- week.users[,symptom:=(nb>0), with=F] } for (symptom in c("fever.suddenly")) { week.all <- week.all[is.na(get(symptom)), symptom := -1, with=F] week.users$nb <- with(week.all, aggregate((get(symptom) == 0), list(bid=bid), sum))$x week.users <- week.users[, which(!grepl(symptom, colnames(week.users))), with=FALSE] week.users <- week.users[,symptom:=(nb>0), with=F] } for (change in c("visit.medical.service.no", "contact.medical.service.no", "no.medication")) { week.users$nb <- with(week.all, aggregate((get(change) == "t"), list(bid=bid), sum))$x week.users <- week.users[, which(!grepl(change, colnames(week.users))), with=FALSE] week.users <- week.users[,change:=(nb>0), with=F] } for (change in c("alter.routine")) { week.all <- week.all[is.na(get(change)), change := -1, with=F] week.users$nb <- with(week.all, aggregate((get(change) > 0), list(bid=bid), sum))$x week.users <- week.users[, which(!grepl(change, colnames(week.users))), with=FALSE] week.users <- week.users[,change:=(nb>0), with=F] } for (change in c("absent")) { week.users$nb <- with(week.all, aggregate((get("alter.routine") == 1), list(bid=bid), sum))$x week.users <- week.users[, which(!grepl(change, colnames(week.users))), with=FALSE] week.users <- week.users[,change:=(nb>0), with=F] } week.users <- week.users[, which(!grepl("nb", colnames(week.users))), with=FALSE] week.users$ili <- FALSE week.users$nbili <- with(week.all, aggregate(ili, list(bid=bid), sum))$x week.users$ili <- (week.users$nbili > 0) week.users$ili.fever <- FALSE week.users$nbili.fever <- with(week.all, aggregate(ili.fever, list(bid=bid), sum))$x week.users$ili.fever <- (week.users$nbili.fever > 0) week.users[is.na(ili.fever)]$ili.fever <- F week.all$ili.self <- (week.all$Q11 == 0) week.all[is.na(ili.self)]$ili.self <- FALSE week.users$ili.self <- FALSE week.users$nbili.self <- with(week.all, aggregate(ili.self, list(bid=bid), sum))$x week.users$ili.self <- (week.users$nbili.self > 0) week.users$agegroup2 <- cut(week.users$age, breaks=c(0,20,30,40,50,60,70,80, max(dt$age, na.rm=T)), include.lowest=T, right=F) week.users$daycare <- (week.users$Q6b>0) week.users[is.na(daycare)]$daycare <- F week.users$frequent.contact <- (week.users$frequent.contact.children == "t" | week.users$frequent.contact.elderly == "t" | week.users$frequent.contact.people == "t") week.users$smoking <- week.users$smoke %in% c(1,2,3) week.users$notvaccinated <- !(week.users$vaccinated) week.regression <- logistic.regression.or.ci(glm(ili ~ notvaccinated + children + agegroup + country + frequent.contact + atrisk + gender, data=week.users, family=binomial)) for (i in 1:length(names(week.regression$OR))) { ## for (variable in names(week.regression$OR)) { ## cregressions <- cregressions[thisweek, variable := ## week.regression$OR[[variable]], with=F] cregressions <- cregressions[thisweek, names(week.regression$OR[i]) := week.regression$OR[[i]], with=F] cregressions <- cregressions[thisweek, paste(names(week.regression$OR[i]), ".ci.low", sep="") := week.regression$OR.ci[i,1], with=F] cregressions <- cregressions[thisweek, paste(names(week.regression$OR[i]), ".ci.high", sep="") := week.regression$OR.ci[i,2], with=F] } } cregressions$year <- as.numeric(substr(cregressions$yearweek, 1, 4)) cregressions$week <- as.numeric(substr(cregressions$yearweek, 6, 7)) cregressions$date <- as.Date(strptime(paste(cregressions$year, cregressions$week*7,sep=" "),format="%Y %j"))+5 for (variable in names(season$OR)) { ## filename <- gsub("[,\\[)]", "", gsub("\\]", "", variable)) ## cat(filename, "\n") pdf(paste("c_", variable, "3.pdf", sep="")) print( ggplot(cregressions[yearweek > "2011-45" & yearweek < "2012-14"], aes(x=date, y=get(variable)))+ geom_line()+ geom_errorbar(aes(ymin = get(paste(variable, ".ci.low", sep="")), ymax = get(paste(variable, ".ci.high", sep=""))))+ geom_point(size=3, shape=21, fill="white")+ scale_y_continuous(name="Cumulative odds ratio")+ theme_bw(30)+ scale_x_date(name="")+ theme(panel.grid.major=element_blank(), panel.grid.minor=element_blank())+ geom_abline(intercept=1, slope=0) ) dev.off() png(paste("c_", variable, "3.png", sep="")) print( ggplot(cregressions[yearweek > "2011-45" & yearweek < "2012-14"], aes(x=date, y=get(variable)))+ geom_line()+ geom_errorbar(aes(ymin = get(paste(variable, ".ci.low", sep="")), ymax = get(paste(variable, ".ci.high", sep=""))))+ geom_point(size=3, shape=21, fill="white")+ scale_y_continuous(name="Cumulative odds ratio")+ theme_bw(30)+ scale_x_date(name="")+ theme(panel.grid.major=element_blank(), panel.grid.minor=element_blank())+ geom_abline(intercept=1, slope=0) ) dev.off() } # reporting delay distributions dt$diffdays.onset <- as.numeric(as.Date(dt$timestamp.1)-as.Date(dt$symptoms.start.date)) pdf("onset_all_symptoms.pdf") ggplot(dt[same != 0 & diffdays.onset>=0 & diffdays.onset < 57], aes(x = diffdays.onset, y=..density..)) + geom_histogram(binwidth=1) + scale_x_continuous("days between symptom onset and report")+ scale_y_continuous("proportion of all symptom reports")+ theme_bw() dev.off() pdf("onset_ili.pdf") ggplot(dt[diffdays.onset>=0 & diffdays.onset < 57 & ili==T], aes(x = diffdays.onset, y=..density..)) + geom_histogram(binwidth=1) + scale_x_continuous("days between symptom onset and report")+ scale_y_continuous("proportion of symptom reports with ILI")+ theme_bw() dev.off() nrow(dt[diffdays.onset>7])/nrow(dt[diffdays.onset>=0]) nrow(dt[diffdays.onset>14])/nrow(dt[diffdays.onset>=0]) nrow(dt[diffdays.onset>21])/nrow(dt[diffdays.onset>=0]) nrow(dt[diffdays.onset>28])/nrow(dt[diffdays.onset>=0]) nrow(dt[diffdays.onset<0])/nrow(dt[!is.na(diffdays.onset)]) nrow(dt[same != 0 & diffdays.onset>7])/nrow(dt[same != 0 & diffdays.onset>=0]) nrow(dt[same != 0 & diffdays.onset>14])/nrow(dt[same != 0 & diffdays.onset>=0]) nrow(dt[same != 0 & diffdays.onset>21])/nrow(dt[same != 0 & diffdays.onset>=0]) nrow(dt[same != 0 & diffdays.onset>28])/nrow(dt[same != 0 & diffdays.onset>=0]) nrow(dt[same != 0 & diffdays.onset<0])/nrow(dt[same != 0 & !is.na(diffdays.onset)]) nrow(dt[ili==T & diffdays.onset>7])/nrow(dt[ili==T & diffdays.onset>=0]) nrow(dt[ili==T & diffdays.onset>14])/nrow(dt[ili==T & diffdays.onset>=0]) nrow(dt[ili==T & diffdays.onset>21])/nrow(dt[ili==T & diffdays.onset>=0]) nrow(dt[ili==T & diffdays.onset>28])/nrow(dt[ili==T & diffdays.onset>=0]) nrow(dt[ili==T & diffdays.onset<0])/nrow(dt[ili==T & !is.na(diffdays.onset)]) nrow(dt[ili.fever==T & diffdays.onset>7])/nrow(dt[ili.fever==T & diffdays.onset>=0]) nrow(dt[ili.fever==T & diffdays.onset>14])/nrow(dt[ili.fever==T & diffdays.onset>=0]) nrow(dt[ili.fever==T & diffdays.onset>21])/nrow(dt[ili.fever==T & diffdays.onset>=0]) nrow(dt[ili.fever==T & diffdays.onset>28])/nrow(dt[ili.fever==T & diffdays.onset>=0]) nrow(dt[ili.fever==T & diffdays.onset<0])/nrow(dt[ili.fever==T & !is.na(diffdays.onset)]) dt$diffdays.end <- as.numeric(as.Date(dt$timestamp.1)-as.Date(dt$symptoms.end.date)) pdf("end_all_symptoms.pdf") ggplot(dt[diffdays.end>=0 & diffdays.end < 57], aes(x = diffdays.end, y=..density..)) + geom_histogram(binwidth=1) + scale_x_continuous("days between symptom end and report")+ scale_y_continuous("proportion of all symptom reports")+ theme_bw() dev.off() pdf("end_ili.pdf") ggplot(dt[diffdays.end>=0 & diffdays.end < 57 & ili==T], aes(x = diffdays.end, y=..density..)) + geom_histogram(binwidth=1) + scale_x_continuous("days between symptom end and report")+ scale_y_continuous("proportion of symptom reports with ILI")+ theme_bw() dev.off() nrow(dt[diffdays.end>7])/nrow(dt[diffdays.end>=0]) nrow(dt[diffdays.end>14])/nrow(dt[diffdays.end>=0]) nrow(dt[diffdays.end>21])/nrow(dt[diffdays.end>=0]) nrow(dt[diffdays.end>28])/nrow(dt[diffdays.end>=0]) nrow(dt[diffdays.end<0])/nrow(dt[!is.na(diffdays.end)]) nrow(dt[ili==T & diffdays.end>7])/nrow(dt[ili==T & diffdays.end>=0]) nrow(dt[ili==T & diffdays.end>14])/nrow(dt[ili==T & diffdays.end>=0]) nrow(dt[ili==T & diffdays.end>21])/nrow(dt[ili==T & diffdays.end>=0]) nrow(dt[ili==T & diffdays.end>28])/nrow(dt[ili==T & diffdays.end>=0]) nrow(dt[ili==T & diffdays.end<0])/nrow(dt[ili==T & !is.na(diffdays.end)]) nrow(dt[ili.fever==T & diffdays.end>7])/nrow(dt[ili.fever==T & diffdays.end>=0]) nrow(dt[ili.fever==T & diffdays.end>14])/nrow(dt[ili.fever==T & diffdays.end>=0]) nrow(dt[ili.fever==T & diffdays.end>21])/nrow(dt[ili.fever==T & diffdays.end>=0]) nrow(dt[ili.fever==T & diffdays.end>28])/nrow(dt[ili.fever==T & diffdays.end>=0]) nrow(dt[ili.fever==T & diffdays.end<0])/nrow(dt[ili.fever==T & !is.na(diffdays.end)]) # add active user stuff dt.short <- dt[,c("week", "bid", "vaccine", "fever", "chills", "blocked.runny.nose", "sneezing", "sore.throat", "cough", "shortness.breath", "headache", "muscle.and.or.joint.pain", "chest.pain", "tired", "loss.appetite", "phlegm", "watery.eyes", "nausea", "vomiting", "diarrhoea", "stomach.ache", "other", "fever.suddenly", "visit.medical.service.no", "contact.medical.service.no", "no.medication", "alter.routine", "ili", "ili.fever", "ili.self", "age", "agegroup", "Q6b", "frequent.contact.children", "frequent.contact.elderly", "frequent.contact.people", "smoke", "atrisk", "date", "symptoms.start.week", "same", "no.symptoms"),with=F] dt.short$added.2week <- F dt.short$added.3week <- F lastrow <- nrow(dt.short) dt2 <- dt.short dt3 <- dt.short counter <- 1 ## dt2$date <- dt$date - 7 ## dt2$week <- format(dt2$date, format="%G-%W") for (i in 1:lastrow) { ## if (nrow(dt[bid == dt2[i]$bid & week == dt2[i]$week]) == 0) { ## if (is.na(dt[i]$symptoms.start.week) | ## dt[i]$symptoms.start.week != dt2[i]$week) { ## ## dt <- rbind(dt, dt[i]) ## dt2 <- dt2[i, same:=0] ## dt2 <- dt2[i, date := dt[i]$date] ## dt2[newrow]$date <- as.Date(date.before) ## dt2[newrow]$week <- week.before ## dt2[newrow]$added.2week <- T ## counter <- counter + 1 ## } date.before <- dt.short[i]$date - 7 week.before <- format(date.before, format="%G-%W") date.before.before <- dt.short[i]$date - 14 week.before.before <- format(date.before.before, format="%G-%W") if (nrow(dt.short[bid == dt.short[i]$bid & week == week.before]) == 0) { if (is.na(dt.short[i]$symptoms.start.week) | dt.short[i]$symptoms.start.week != week.before) { ## dt <- rbind(dt, dt.short[i]) newrow <- counter dt2[newrow] <- dt.short[i] dt2 <- dt2[newrow, same := as.integer(0)] dt2 <- dt2[newrow, date := as.integer(date.before)] dt2 <- dt2[newrow, week := week.before] dt2 <- dt2[newrow, added.2week := T] counter <- counter + 1 } if (nrow(dt.short[bid == dt.short[i]$bid & week == week.before.before]) == 0) { if (is.na(dt.short[i]$symptoms.start.week) | dt.short[i]$symptoms.start.week != week.before.before) { if (is.na(dt.short[i]$symptoms.start.week) | dt.short[i]$symptoms.start.week != week.before) { ## dt <- rbind(dt, dt.short[i]) ## newrow <- nrow(dt) newrow <- counter dt2[newrow] <- dt.short[i] dt2 <- dt2[newrow, same := as.integer(0)] dt2 <- dt2[newrow, date := as.integer(date.before.before)] dt2 <- dt2[newrow, week := week.before.before] dt2 <- dt2[newrow, added.3week := T] counter <- counter + 1 } else { ## dt <- rbind(dt, dt.short[i]) ## newrow <- nrow(dt) newrow <- counter dt2[newrow] <- dt.short[i] dt2 <- dt2[newrow, same := as.integer(0)] dt2 <- dt2[newrow, date := as.integer(date.before.before)] dt2 <- dt2[newrow, week := week.before.before] dt2 <- dt2[newrow, no.symptoms := "t"] dt2 <- dt2[newrow, symptoms := "f", with=F] dt2 <- dt2[newrow, added.3week := T] counter <- counter + 1 } } } } } dt.added <- rbind(dt.short, dt2[1:(counter-1),]) dt.added[dt.added$week=="2011-00"]$week <- "2011-52" incidence <- data.table(expand.grid( yearweek = levels(factor(dt.added$week)), measure = c("realtime.report", "realtime.symptoms", "retrospective.symptoms"), weeks = as.factor(seq(0, 3)), def = c("ili", "self", "fever"), value = 0.0 )) for (thisweek in levels(factor(dt.added$week))) { week.all <- dt.added[week == thisweek] week.all <- week.all[added.3week == F & added.2week == F] week.users <- week.all[!duplicated(week.all$bid)] incidence[yearweek == thisweek & weeks == 0 & def == "ili" & measure == "realtime.report"]$value <- nrow(week.users[ili==1 & same != 0])/nrow(week.users) incidence[yearweek == thisweek & weeks == 0 & def == "self" & measure == "realtime.report"]$value <- nrow(week.users[ili.self==1 & same!=0])/nrow(week.users) incidence[yearweek == thisweek & weeks == 0 & def == "fever" & measure == "realtime.report"]$value <- nrow(week.users[ili.fever==1 & same!=0])/nrow(week.users) incidence[yearweek == thisweek & weeks == 1 & def == "ili" & measure == "realtime.symptoms"]$value <- nrow(week.users[ili==1 & same != 0 & symptoms.start.week == thisweek])/nrow(week.users) incidence[yearweek == thisweek & weeks == 1 & def == "self" & measure == "realtime.symptoms"]$value <- nrow(week.users[ili.self==1 & same != 0 & symptoms.start.week == thisweek])/nrow(week.users) incidence[yearweek == thisweek & weeks == 1 & def == "fever" & measure == "realtime.symptoms"]$value <- nrow(week.users[ili.fever==1 & same != 0 & symptoms.start.week == thisweek])/nrow(week.users) week.all <- dt.added[(week == thisweek & (is.na(symptoms.start.week) | same == 0)) | (symptoms.start.week == thisweek & same != 0)] week.all <- week.all[added.3week == F & added.2week == F] week.users <- week.all[!duplicated(week.all$bid)] incidence[yearweek == thisweek & weeks == 1 & def == "ili" & measure == "retrospective.symptoms"]$value <- nrow(week.users[ili==1 & same != 0 & symptoms.start.week == thisweek])/nrow(week.users) incidence[yearweek == thisweek & weeks == 1 & def == "self" & measure == "retrospective.symptoms"]$value <- nrow(week.users[ili.self==1 & same != 0 & symptoms.start.week == thisweek])/nrow(week.users) incidence[yearweek == thisweek & weeks == 1 & def == "fever" & measure == "retrospective.symptoms"]$value <- nrow(week.users[ili.fever==1 & same != 0 & symptoms.start.week == thisweek])/nrow(week.users) week.all <- dt.added[(week == thisweek & is.na(symptoms.start.week)) | symptoms.start.week == thisweek] week.all <- week.all[added.3week==F] week.users <- week.all[!duplicated(week.all$bid)] incidence[yearweek == thisweek & weeks == 2 & def == "ili" & measure == "retrospective.symptoms"]$value <- nrow(week.users[ili==1 & same != 0 & symptoms.start.week == thisweek])/nrow(week.users) incidence[yearweek == thisweek & weeks == 2 & def == "self" & measure == "retrospective.symptoms"]$value <- nrow(week.users[ili.self==1 & same != 0 & symptoms.start.week == thisweek])/nrow(week.users) incidence[yearweek == thisweek & weeks == 2 & def == "fever" & measure == "retrospective.symptoms"]$value <- nrow(week.users[ili.fever==1 & same != 0 & symptoms.start.week == thisweek])/nrow(week.users) week.all <- dt.added[(week == thisweek & is.na(symptoms.start.week)) | symptoms.start.week == thisweek] week.users <- week.all[!duplicated(week.all$bid)] incidence[yearweek == thisweek & weeks == 3 & def == "ili" & measure == "retrospective.symptoms"]$value <- nrow(week.users[ili==1 & same != 0 & symptoms.start.week == thisweek])/nrow(week.users) incidence[yearweek == thisweek & weeks == 3 & def == "self" & measure == "retrospective.symptoms"]$value <- nrow(week.users[ili.self==1 & same != 0 & symptoms.start.week == thisweek])/nrow(week.users) incidence[yearweek == thisweek & weeks == 3 & def == "fever" & measure == "retrospective.symptoms"]$value <- nrow(week.users[ili.fever==1 & same != 0 & symptoms.start.week == thisweek])/nrow(week.users) } incidence <- incidence[as.character(yearweek) > "2011-45" & as.character(yearweek) < "2012-19"] incidence$year <- as.numeric(substr(incidence$yearweek, 1, 4)) incidence$week <- as.numeric(substr(incidence$yearweek, 6, 7)) incidence$date <- as.Date(strptime(paste(incidence$year, incidence$week*7,sep=" "),format="%Y %j"))+5 incidence <- incidence[value > 0] for (definition in unique(incidence$def)) { pdf(paste("memory_", definition, ".pdf", sep=""), width=10) print( ggplot(droplevels(incidence[as.numeric(weeks) > 1 & measure == "retrospective.symptoms" & def==definition]), aes(x=date, y=value, group=weeks, color=weeks))+ geom_line()+ geom_point(size=3, shape=21, fill="white")+ scale_y_continuous(name="Weekly incidence")+ theme_bw(30)+ scale_x_date(name="")+ scale_color_brewer(palette="Set1") ) dev.off() pdf(paste("realtime_", definition, ".pdf", sep=""), width=10) print( ggplot(incidence[as.numeric(weeks) < 3 & def==definition], aes(x=date, y=value, group=measure, color=measure))+ geom_line()+ geom_point(size=3, shape=21, fill="white")+ scale_y_continuous(name="Weekly incidence")+ theme_bw(30)+ scale_x_date(name="")+ scale_color_brewer(palette="Set1") ) dev.off() }
85,926
gpl-2.0
b269d07226017fb21ef663ef82d19f0b6a74c0fb
arank/mxnet
R-package/R/rnn_model.R
is.param.name <- function(name) { return (grepl('weight$', name) || grepl('bias$', name) || grepl('gamma$', name) || grepl('beta$', name) ) } # Initialize parameters mx.model.init.params.rnn <- function(symbol, input.shape, initializer, ctx) { if (!is.mx.symbol(symbol)) stop("symbol need to be MXSymbol") slist <- symbol$infer.shape(input.shape) if (is.null(slist)) stop("Not enough information to get shapes") arg.params <- mx.init.create(initializer, slist$arg.shapes, ctx, skip.unknown=TRUE) aux.params <- mx.init.create(initializer, slist$aux.shapes, ctx, skip.unknown=FALSE) return(list(arg.params=arg.params, aux.params=aux.params)) } # Initialize the data iter mx.model.init.iter.rnn <- function(X, y, batch.size, is.train) { if (is.MXDataIter(X)) return(X) shape <- dim(X) if (is.null(shape)) { num.data <- length(X) } else { ndim <- length(shape) num.data <- shape[[ndim]] } if (is.null(y)) { if (is.train) stop("Need to provide parameter y for training with R arrays.") y <- c(1:num.data) * 0 } batch.size <- min(num.data, batch.size) return(mx.io.arrayiter(X, y, batch.size=batch.size, shuffle=is.train)) } # set up rnn model with rnn cells setup.rnn.model <- function(rnn.sym, ctx, num.rnn.layer, seq.len, num.hidden, num.embed, num.label, batch.size, input.size, init.states.name, initializer=mx.init.uniform(0.01), dropout=0) { arg.names <- rnn.sym$arguments input.shapes <- list() for (name in arg.names) { if (name %in% init.states.name) { input.shapes[[name]] <- c(num.hidden, batch.size) } else if (grepl('data$', name) || grepl('label$', name) ) { if (seq.len == 1) { input.shapes[[name]] <- c(batch.size) } else { input.shapes[[name]] <- c(seq.len, batch.size) } } } params <- mx.model.init.params.rnn(rnn.sym, input.shapes, initializer, mx.cpu()) args <- input.shapes args$symbol <- rnn.sym args$ctx <- ctx args$grad.req <- "add" rnn.exec <- do.call(mx.simple.bind, args) mx.exec.update.arg.arrays(rnn.exec, params$arg.params, match.name=TRUE) mx.exec.update.aux.arrays(rnn.exec, params$aux.params, match.name=TRUE) grad.arrays <- list() for (name in names(rnn.exec$ref.grad.arrays)) { if (is.param.name(name)) grad.arrays[[name]] <- rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.grad.arrays(rnn.exec, grad.arrays, match.name=TRUE) return (list(rnn.exec=rnn.exec, symbol=rnn.sym, num.rnn.layer=num.rnn.layer, num.hidden=num.hidden, seq.len=seq.len, batch.size=batch.size, num.embed=num.embed)) } calc.nll <- function(seq.label.probs, batch.size) { nll = - sum(log(seq.label.probs)) / batch.size return (nll) } get.label <- function(label, ctx) { label <- as.array(label) seq.len <- dim(label)[[1]] batch.size <- dim(label)[[2]] sm.label <- array(0, dim=c(seq.len*batch.size)) for (seqidx in 1:seq.len) { sm.label[((seqidx-1)*batch.size+1) : (seqidx*batch.size)] <- label[seqidx,] } return (mx.nd.array(sm.label, ctx)) } # training rnn model train.rnn <- function (model, train.data, eval.data, num.round, update.period, init.states.name, optimizer='sgd', ctx=mx.ctx.default(), epoch.end.callback, batch.end.callback, verbose=TRUE, ...) { m <- model model <- list(symbol=model$symbol, arg.params=model$rnn.exec$ref.arg.arrays, aux.params=model$rnn.exec$ref.aux.arrays) seq.len <- m$seq.len batch.size <- m$batch.size num.rnn.layer <- m$num.rnn.layer num.hidden <- m$num.hidden opt <- mx.opt.create(optimizer, rescale.grad=(1/batch.size), ...) updater <- mx.opt.get.updater(opt, m$rnn.exec$ref.arg.arrays) epoch.counter <- 0 log.period <- max(as.integer(1000 / seq.len), 1) last.perp <- 10000000.0 for (iteration in 1:num.round) { nbatch <- 0 train.nll <- 0 # reset states init.states <- list() for (name in init.states.name) { init.states[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.arg.arrays(m$rnn.exec, init.states, match.name=TRUE) tic <- Sys.time() train.data$reset() while (train.data$iter.next()) { # set rnn input rnn.input <- train.data$value() mx.exec.update.arg.arrays(m$rnn.exec, rnn.input, match.name=TRUE) mx.exec.forward(m$rnn.exec, is.train=TRUE) seq.label.probs <- mx.nd.choose.element.0index(m$rnn.exec$ref.outputs[["sm_output"]], get.label(m$rnn.exec$ref.arg.arrays[["label"]], ctx)) mx.exec.backward(m$rnn.exec) init.states <- list() for (name in init.states.name) { init.states[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.arg.arrays(m$rnn.exec, init.states, match.name=TRUE) # update epoch counter epoch.counter <- epoch.counter + 1 if (epoch.counter %% update.period == 0) { # the gradient of initial c and inital h should be zero init.grad <- list() for (name in init.states.name) { init.grad[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.grad.arrays(m$rnn.exec, init.grad, match.name=TRUE) arg.blocks <- updater(m$rnn.exec$ref.arg.arrays, m$rnn.exec$ref.grad.arrays) mx.exec.update.arg.arrays(m$rnn.exec, arg.blocks, skip.null=TRUE) grad.arrays <- list() for (name in names(m$rnn.exec$ref.grad.arrays)) { if (is.param.name(name)) grad.arrays[[name]] <- m$rnn.exec$ref.grad.arrays[[name]]*0 } mx.exec.update.grad.arrays(m$rnn.exec, grad.arrays, match.name=TRUE) } train.nll <- train.nll + calc.nll(as.array(seq.label.probs), batch.size) nbatch <- nbatch + seq.len if (!is.null(batch.end.callback)) { batch.end.callback(iteration, nbatch, environment()) } if ((epoch.counter %% log.period) == 0) { message(paste0("Epoch [", epoch.counter, "] Train: NLL=", train.nll / nbatch, ", Perp=", exp(train.nll / nbatch))) } } train.data$reset() # end of training loop toc <- Sys.time() message(paste0("Iter [", iteration, "] Train: Time: ", as.numeric(toc - tic, units="secs"), " sec, NLL=", train.nll / nbatch, ", Perp=", exp(train.nll / nbatch))) if (!is.null(eval.data)) { val.nll <- 0.0 # validation set, reset states init.states <- list() for (name in init.states.name) { init.states[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.arg.arrays(m$rnn.exec, init.states, match.name=TRUE) eval.data$reset() nbatch <- 0 while (eval.data$iter.next()) { # set rnn input rnn.input <- eval.data$value() mx.exec.update.arg.arrays(m$rnn.exec, rnn.input, match.name=TRUE) mx.exec.forward(m$rnn.exec, is.train=FALSE) # probability of each label class, used to evaluate nll seq.label.probs <- mx.nd.choose.element.0index(m$rnn.exec$ref.outputs[["sm_output"]], get.label(m$rnn.exec$ref.arg.arrays[["label"]], ctx)) # transfer the states init.states <- list() for (name in init.states.name) { init.states[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.arg.arrays(m$rnn.exec, init.states, match.name=TRUE) val.nll <- val.nll + calc.nll(as.array(seq.label.probs), batch.size) nbatch <- nbatch + seq.len } eval.data$reset() perp <- exp(val.nll / nbatch) message(paste0("Iter [", iteration, "] Val: NLL=", val.nll / nbatch, ", Perp=", exp(val.nll / nbatch))) } # get the model out epoch_continue <- TRUE if (!is.null(epoch.end.callback)) { epoch_continue <- epoch.end.callback(iteration, 0, environment(), verbose = verbose) } if (!epoch_continue) { break } } return (m) } # check data and translate data into iterator if data is array/matrix check.data <- function(data, batch.size, is.train) { if (!is.null(data) && !is.list(data) && !is.mx.dataiter(data)) { stop("The dataset should be either a mx.io.DataIter or a R list") } if (is.list(data)) { if (is.null(data$data) || is.null(data$label)){ stop("Please provide dataset as list(data=R.array, label=R.array)") } data <- mx.model.init.iter.rnn(data$data, data$label, batch.size=batch.size, is.train = is.train) } if (!is.null(data) && !data$iter.next()) { data$reset() if (!data$iter.next()) stop("Empty input") } return (data) }
9,826
apache-2.0
b269d07226017fb21ef663ef82d19f0b6a74c0fb
EvanzzzZ/mxnet
R-package/R/rnn_model.R
is.param.name <- function(name) { return (grepl('weight$', name) || grepl('bias$', name) || grepl('gamma$', name) || grepl('beta$', name) ) } # Initialize parameters mx.model.init.params.rnn <- function(symbol, input.shape, initializer, ctx) { if (!is.mx.symbol(symbol)) stop("symbol need to be MXSymbol") slist <- symbol$infer.shape(input.shape) if (is.null(slist)) stop("Not enough information to get shapes") arg.params <- mx.init.create(initializer, slist$arg.shapes, ctx, skip.unknown=TRUE) aux.params <- mx.init.create(initializer, slist$aux.shapes, ctx, skip.unknown=FALSE) return(list(arg.params=arg.params, aux.params=aux.params)) } # Initialize the data iter mx.model.init.iter.rnn <- function(X, y, batch.size, is.train) { if (is.MXDataIter(X)) return(X) shape <- dim(X) if (is.null(shape)) { num.data <- length(X) } else { ndim <- length(shape) num.data <- shape[[ndim]] } if (is.null(y)) { if (is.train) stop("Need to provide parameter y for training with R arrays.") y <- c(1:num.data) * 0 } batch.size <- min(num.data, batch.size) return(mx.io.arrayiter(X, y, batch.size=batch.size, shuffle=is.train)) } # set up rnn model with rnn cells setup.rnn.model <- function(rnn.sym, ctx, num.rnn.layer, seq.len, num.hidden, num.embed, num.label, batch.size, input.size, init.states.name, initializer=mx.init.uniform(0.01), dropout=0) { arg.names <- rnn.sym$arguments input.shapes <- list() for (name in arg.names) { if (name %in% init.states.name) { input.shapes[[name]] <- c(num.hidden, batch.size) } else if (grepl('data$', name) || grepl('label$', name) ) { if (seq.len == 1) { input.shapes[[name]] <- c(batch.size) } else { input.shapes[[name]] <- c(seq.len, batch.size) } } } params <- mx.model.init.params.rnn(rnn.sym, input.shapes, initializer, mx.cpu()) args <- input.shapes args$symbol <- rnn.sym args$ctx <- ctx args$grad.req <- "add" rnn.exec <- do.call(mx.simple.bind, args) mx.exec.update.arg.arrays(rnn.exec, params$arg.params, match.name=TRUE) mx.exec.update.aux.arrays(rnn.exec, params$aux.params, match.name=TRUE) grad.arrays <- list() for (name in names(rnn.exec$ref.grad.arrays)) { if (is.param.name(name)) grad.arrays[[name]] <- rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.grad.arrays(rnn.exec, grad.arrays, match.name=TRUE) return (list(rnn.exec=rnn.exec, symbol=rnn.sym, num.rnn.layer=num.rnn.layer, num.hidden=num.hidden, seq.len=seq.len, batch.size=batch.size, num.embed=num.embed)) } calc.nll <- function(seq.label.probs, batch.size) { nll = - sum(log(seq.label.probs)) / batch.size return (nll) } get.label <- function(label, ctx) { label <- as.array(label) seq.len <- dim(label)[[1]] batch.size <- dim(label)[[2]] sm.label <- array(0, dim=c(seq.len*batch.size)) for (seqidx in 1:seq.len) { sm.label[((seqidx-1)*batch.size+1) : (seqidx*batch.size)] <- label[seqidx,] } return (mx.nd.array(sm.label, ctx)) } # training rnn model train.rnn <- function (model, train.data, eval.data, num.round, update.period, init.states.name, optimizer='sgd', ctx=mx.ctx.default(), epoch.end.callback, batch.end.callback, verbose=TRUE, ...) { m <- model model <- list(symbol=model$symbol, arg.params=model$rnn.exec$ref.arg.arrays, aux.params=model$rnn.exec$ref.aux.arrays) seq.len <- m$seq.len batch.size <- m$batch.size num.rnn.layer <- m$num.rnn.layer num.hidden <- m$num.hidden opt <- mx.opt.create(optimizer, rescale.grad=(1/batch.size), ...) updater <- mx.opt.get.updater(opt, m$rnn.exec$ref.arg.arrays) epoch.counter <- 0 log.period <- max(as.integer(1000 / seq.len), 1) last.perp <- 10000000.0 for (iteration in 1:num.round) { nbatch <- 0 train.nll <- 0 # reset states init.states <- list() for (name in init.states.name) { init.states[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.arg.arrays(m$rnn.exec, init.states, match.name=TRUE) tic <- Sys.time() train.data$reset() while (train.data$iter.next()) { # set rnn input rnn.input <- train.data$value() mx.exec.update.arg.arrays(m$rnn.exec, rnn.input, match.name=TRUE) mx.exec.forward(m$rnn.exec, is.train=TRUE) seq.label.probs <- mx.nd.choose.element.0index(m$rnn.exec$ref.outputs[["sm_output"]], get.label(m$rnn.exec$ref.arg.arrays[["label"]], ctx)) mx.exec.backward(m$rnn.exec) init.states <- list() for (name in init.states.name) { init.states[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.arg.arrays(m$rnn.exec, init.states, match.name=TRUE) # update epoch counter epoch.counter <- epoch.counter + 1 if (epoch.counter %% update.period == 0) { # the gradient of initial c and inital h should be zero init.grad <- list() for (name in init.states.name) { init.grad[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.grad.arrays(m$rnn.exec, init.grad, match.name=TRUE) arg.blocks <- updater(m$rnn.exec$ref.arg.arrays, m$rnn.exec$ref.grad.arrays) mx.exec.update.arg.arrays(m$rnn.exec, arg.blocks, skip.null=TRUE) grad.arrays <- list() for (name in names(m$rnn.exec$ref.grad.arrays)) { if (is.param.name(name)) grad.arrays[[name]] <- m$rnn.exec$ref.grad.arrays[[name]]*0 } mx.exec.update.grad.arrays(m$rnn.exec, grad.arrays, match.name=TRUE) } train.nll <- train.nll + calc.nll(as.array(seq.label.probs), batch.size) nbatch <- nbatch + seq.len if (!is.null(batch.end.callback)) { batch.end.callback(iteration, nbatch, environment()) } if ((epoch.counter %% log.period) == 0) { message(paste0("Epoch [", epoch.counter, "] Train: NLL=", train.nll / nbatch, ", Perp=", exp(train.nll / nbatch))) } } train.data$reset() # end of training loop toc <- Sys.time() message(paste0("Iter [", iteration, "] Train: Time: ", as.numeric(toc - tic, units="secs"), " sec, NLL=", train.nll / nbatch, ", Perp=", exp(train.nll / nbatch))) if (!is.null(eval.data)) { val.nll <- 0.0 # validation set, reset states init.states <- list() for (name in init.states.name) { init.states[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.arg.arrays(m$rnn.exec, init.states, match.name=TRUE) eval.data$reset() nbatch <- 0 while (eval.data$iter.next()) { # set rnn input rnn.input <- eval.data$value() mx.exec.update.arg.arrays(m$rnn.exec, rnn.input, match.name=TRUE) mx.exec.forward(m$rnn.exec, is.train=FALSE) # probability of each label class, used to evaluate nll seq.label.probs <- mx.nd.choose.element.0index(m$rnn.exec$ref.outputs[["sm_output"]], get.label(m$rnn.exec$ref.arg.arrays[["label"]], ctx)) # transfer the states init.states <- list() for (name in init.states.name) { init.states[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.arg.arrays(m$rnn.exec, init.states, match.name=TRUE) val.nll <- val.nll + calc.nll(as.array(seq.label.probs), batch.size) nbatch <- nbatch + seq.len } eval.data$reset() perp <- exp(val.nll / nbatch) message(paste0("Iter [", iteration, "] Val: NLL=", val.nll / nbatch, ", Perp=", exp(val.nll / nbatch))) } # get the model out epoch_continue <- TRUE if (!is.null(epoch.end.callback)) { epoch_continue <- epoch.end.callback(iteration, 0, environment(), verbose = verbose) } if (!epoch_continue) { break } } return (m) } # check data and translate data into iterator if data is array/matrix check.data <- function(data, batch.size, is.train) { if (!is.null(data) && !is.list(data) && !is.mx.dataiter(data)) { stop("The dataset should be either a mx.io.DataIter or a R list") } if (is.list(data)) { if (is.null(data$data) || is.null(data$label)){ stop("Please provide dataset as list(data=R.array, label=R.array)") } data <- mx.model.init.iter.rnn(data$data, data$label, batch.size=batch.size, is.train = is.train) } if (!is.null(data) && !data$iter.next()) { data$reset() if (!data$iter.next()) stop("Empty input") } return (data) }
9,826
apache-2.0
2e37573308cf9e18ec830699b4cd866cbb53debe
NickSalkowski/HALICON_2015_Reporting_Presentation
run_rmarkdown_html.R
iris_split <- split( x = iris[-5], f = iris$Species) system.time({ for (i in names(iris_split)) { rmarkdown::render( "iris_markdown.Rmd", output_file = paste0(i, ".html"), output_dir = "rmarkdown_html", params = list(species = i), quiet = TRUE) } }) list.files("rmarkdown_html")
322
mit
b269d07226017fb21ef663ef82d19f0b6a74c0fb
lxn2/mxnet
R-package/R/rnn_model.R
is.param.name <- function(name) { return (grepl('weight$', name) || grepl('bias$', name) || grepl('gamma$', name) || grepl('beta$', name) ) } # Initialize parameters mx.model.init.params.rnn <- function(symbol, input.shape, initializer, ctx) { if (!is.mx.symbol(symbol)) stop("symbol need to be MXSymbol") slist <- symbol$infer.shape(input.shape) if (is.null(slist)) stop("Not enough information to get shapes") arg.params <- mx.init.create(initializer, slist$arg.shapes, ctx, skip.unknown=TRUE) aux.params <- mx.init.create(initializer, slist$aux.shapes, ctx, skip.unknown=FALSE) return(list(arg.params=arg.params, aux.params=aux.params)) } # Initialize the data iter mx.model.init.iter.rnn <- function(X, y, batch.size, is.train) { if (is.MXDataIter(X)) return(X) shape <- dim(X) if (is.null(shape)) { num.data <- length(X) } else { ndim <- length(shape) num.data <- shape[[ndim]] } if (is.null(y)) { if (is.train) stop("Need to provide parameter y for training with R arrays.") y <- c(1:num.data) * 0 } batch.size <- min(num.data, batch.size) return(mx.io.arrayiter(X, y, batch.size=batch.size, shuffle=is.train)) } # set up rnn model with rnn cells setup.rnn.model <- function(rnn.sym, ctx, num.rnn.layer, seq.len, num.hidden, num.embed, num.label, batch.size, input.size, init.states.name, initializer=mx.init.uniform(0.01), dropout=0) { arg.names <- rnn.sym$arguments input.shapes <- list() for (name in arg.names) { if (name %in% init.states.name) { input.shapes[[name]] <- c(num.hidden, batch.size) } else if (grepl('data$', name) || grepl('label$', name) ) { if (seq.len == 1) { input.shapes[[name]] <- c(batch.size) } else { input.shapes[[name]] <- c(seq.len, batch.size) } } } params <- mx.model.init.params.rnn(rnn.sym, input.shapes, initializer, mx.cpu()) args <- input.shapes args$symbol <- rnn.sym args$ctx <- ctx args$grad.req <- "add" rnn.exec <- do.call(mx.simple.bind, args) mx.exec.update.arg.arrays(rnn.exec, params$arg.params, match.name=TRUE) mx.exec.update.aux.arrays(rnn.exec, params$aux.params, match.name=TRUE) grad.arrays <- list() for (name in names(rnn.exec$ref.grad.arrays)) { if (is.param.name(name)) grad.arrays[[name]] <- rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.grad.arrays(rnn.exec, grad.arrays, match.name=TRUE) return (list(rnn.exec=rnn.exec, symbol=rnn.sym, num.rnn.layer=num.rnn.layer, num.hidden=num.hidden, seq.len=seq.len, batch.size=batch.size, num.embed=num.embed)) } calc.nll <- function(seq.label.probs, batch.size) { nll = - sum(log(seq.label.probs)) / batch.size return (nll) } get.label <- function(label, ctx) { label <- as.array(label) seq.len <- dim(label)[[1]] batch.size <- dim(label)[[2]] sm.label <- array(0, dim=c(seq.len*batch.size)) for (seqidx in 1:seq.len) { sm.label[((seqidx-1)*batch.size+1) : (seqidx*batch.size)] <- label[seqidx,] } return (mx.nd.array(sm.label, ctx)) } # training rnn model train.rnn <- function (model, train.data, eval.data, num.round, update.period, init.states.name, optimizer='sgd', ctx=mx.ctx.default(), epoch.end.callback, batch.end.callback, verbose=TRUE, ...) { m <- model model <- list(symbol=model$symbol, arg.params=model$rnn.exec$ref.arg.arrays, aux.params=model$rnn.exec$ref.aux.arrays) seq.len <- m$seq.len batch.size <- m$batch.size num.rnn.layer <- m$num.rnn.layer num.hidden <- m$num.hidden opt <- mx.opt.create(optimizer, rescale.grad=(1/batch.size), ...) updater <- mx.opt.get.updater(opt, m$rnn.exec$ref.arg.arrays) epoch.counter <- 0 log.period <- max(as.integer(1000 / seq.len), 1) last.perp <- 10000000.0 for (iteration in 1:num.round) { nbatch <- 0 train.nll <- 0 # reset states init.states <- list() for (name in init.states.name) { init.states[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.arg.arrays(m$rnn.exec, init.states, match.name=TRUE) tic <- Sys.time() train.data$reset() while (train.data$iter.next()) { # set rnn input rnn.input <- train.data$value() mx.exec.update.arg.arrays(m$rnn.exec, rnn.input, match.name=TRUE) mx.exec.forward(m$rnn.exec, is.train=TRUE) seq.label.probs <- mx.nd.choose.element.0index(m$rnn.exec$ref.outputs[["sm_output"]], get.label(m$rnn.exec$ref.arg.arrays[["label"]], ctx)) mx.exec.backward(m$rnn.exec) init.states <- list() for (name in init.states.name) { init.states[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.arg.arrays(m$rnn.exec, init.states, match.name=TRUE) # update epoch counter epoch.counter <- epoch.counter + 1 if (epoch.counter %% update.period == 0) { # the gradient of initial c and inital h should be zero init.grad <- list() for (name in init.states.name) { init.grad[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.grad.arrays(m$rnn.exec, init.grad, match.name=TRUE) arg.blocks <- updater(m$rnn.exec$ref.arg.arrays, m$rnn.exec$ref.grad.arrays) mx.exec.update.arg.arrays(m$rnn.exec, arg.blocks, skip.null=TRUE) grad.arrays <- list() for (name in names(m$rnn.exec$ref.grad.arrays)) { if (is.param.name(name)) grad.arrays[[name]] <- m$rnn.exec$ref.grad.arrays[[name]]*0 } mx.exec.update.grad.arrays(m$rnn.exec, grad.arrays, match.name=TRUE) } train.nll <- train.nll + calc.nll(as.array(seq.label.probs), batch.size) nbatch <- nbatch + seq.len if (!is.null(batch.end.callback)) { batch.end.callback(iteration, nbatch, environment()) } if ((epoch.counter %% log.period) == 0) { message(paste0("Epoch [", epoch.counter, "] Train: NLL=", train.nll / nbatch, ", Perp=", exp(train.nll / nbatch))) } } train.data$reset() # end of training loop toc <- Sys.time() message(paste0("Iter [", iteration, "] Train: Time: ", as.numeric(toc - tic, units="secs"), " sec, NLL=", train.nll / nbatch, ", Perp=", exp(train.nll / nbatch))) if (!is.null(eval.data)) { val.nll <- 0.0 # validation set, reset states init.states <- list() for (name in init.states.name) { init.states[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.arg.arrays(m$rnn.exec, init.states, match.name=TRUE) eval.data$reset() nbatch <- 0 while (eval.data$iter.next()) { # set rnn input rnn.input <- eval.data$value() mx.exec.update.arg.arrays(m$rnn.exec, rnn.input, match.name=TRUE) mx.exec.forward(m$rnn.exec, is.train=FALSE) # probability of each label class, used to evaluate nll seq.label.probs <- mx.nd.choose.element.0index(m$rnn.exec$ref.outputs[["sm_output"]], get.label(m$rnn.exec$ref.arg.arrays[["label"]], ctx)) # transfer the states init.states <- list() for (name in init.states.name) { init.states[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.arg.arrays(m$rnn.exec, init.states, match.name=TRUE) val.nll <- val.nll + calc.nll(as.array(seq.label.probs), batch.size) nbatch <- nbatch + seq.len } eval.data$reset() perp <- exp(val.nll / nbatch) message(paste0("Iter [", iteration, "] Val: NLL=", val.nll / nbatch, ", Perp=", exp(val.nll / nbatch))) } # get the model out epoch_continue <- TRUE if (!is.null(epoch.end.callback)) { epoch_continue <- epoch.end.callback(iteration, 0, environment(), verbose = verbose) } if (!epoch_continue) { break } } return (m) } # check data and translate data into iterator if data is array/matrix check.data <- function(data, batch.size, is.train) { if (!is.null(data) && !is.list(data) && !is.mx.dataiter(data)) { stop("The dataset should be either a mx.io.DataIter or a R list") } if (is.list(data)) { if (is.null(data$data) || is.null(data$label)){ stop("Please provide dataset as list(data=R.array, label=R.array)") } data <- mx.model.init.iter.rnn(data$data, data$label, batch.size=batch.size, is.train = is.train) } if (!is.null(data) && !data$iter.next()) { data$reset() if (!data$iter.next()) stop("Empty input") } return (data) }
9,826
apache-2.0
b269d07226017fb21ef663ef82d19f0b6a74c0fb
Ldpe2G/mxnet
R-package/R/rnn_model.R
is.param.name <- function(name) { return (grepl('weight$', name) || grepl('bias$', name) || grepl('gamma$', name) || grepl('beta$', name) ) } # Initialize parameters mx.model.init.params.rnn <- function(symbol, input.shape, initializer, ctx) { if (!is.mx.symbol(symbol)) stop("symbol need to be MXSymbol") slist <- symbol$infer.shape(input.shape) if (is.null(slist)) stop("Not enough information to get shapes") arg.params <- mx.init.create(initializer, slist$arg.shapes, ctx, skip.unknown=TRUE) aux.params <- mx.init.create(initializer, slist$aux.shapes, ctx, skip.unknown=FALSE) return(list(arg.params=arg.params, aux.params=aux.params)) } # Initialize the data iter mx.model.init.iter.rnn <- function(X, y, batch.size, is.train) { if (is.MXDataIter(X)) return(X) shape <- dim(X) if (is.null(shape)) { num.data <- length(X) } else { ndim <- length(shape) num.data <- shape[[ndim]] } if (is.null(y)) { if (is.train) stop("Need to provide parameter y for training with R arrays.") y <- c(1:num.data) * 0 } batch.size <- min(num.data, batch.size) return(mx.io.arrayiter(X, y, batch.size=batch.size, shuffle=is.train)) } # set up rnn model with rnn cells setup.rnn.model <- function(rnn.sym, ctx, num.rnn.layer, seq.len, num.hidden, num.embed, num.label, batch.size, input.size, init.states.name, initializer=mx.init.uniform(0.01), dropout=0) { arg.names <- rnn.sym$arguments input.shapes <- list() for (name in arg.names) { if (name %in% init.states.name) { input.shapes[[name]] <- c(num.hidden, batch.size) } else if (grepl('data$', name) || grepl('label$', name) ) { if (seq.len == 1) { input.shapes[[name]] <- c(batch.size) } else { input.shapes[[name]] <- c(seq.len, batch.size) } } } params <- mx.model.init.params.rnn(rnn.sym, input.shapes, initializer, mx.cpu()) args <- input.shapes args$symbol <- rnn.sym args$ctx <- ctx args$grad.req <- "add" rnn.exec <- do.call(mx.simple.bind, args) mx.exec.update.arg.arrays(rnn.exec, params$arg.params, match.name=TRUE) mx.exec.update.aux.arrays(rnn.exec, params$aux.params, match.name=TRUE) grad.arrays <- list() for (name in names(rnn.exec$ref.grad.arrays)) { if (is.param.name(name)) grad.arrays[[name]] <- rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.grad.arrays(rnn.exec, grad.arrays, match.name=TRUE) return (list(rnn.exec=rnn.exec, symbol=rnn.sym, num.rnn.layer=num.rnn.layer, num.hidden=num.hidden, seq.len=seq.len, batch.size=batch.size, num.embed=num.embed)) } calc.nll <- function(seq.label.probs, batch.size) { nll = - sum(log(seq.label.probs)) / batch.size return (nll) } get.label <- function(label, ctx) { label <- as.array(label) seq.len <- dim(label)[[1]] batch.size <- dim(label)[[2]] sm.label <- array(0, dim=c(seq.len*batch.size)) for (seqidx in 1:seq.len) { sm.label[((seqidx-1)*batch.size+1) : (seqidx*batch.size)] <- label[seqidx,] } return (mx.nd.array(sm.label, ctx)) } # training rnn model train.rnn <- function (model, train.data, eval.data, num.round, update.period, init.states.name, optimizer='sgd', ctx=mx.ctx.default(), epoch.end.callback, batch.end.callback, verbose=TRUE, ...) { m <- model model <- list(symbol=model$symbol, arg.params=model$rnn.exec$ref.arg.arrays, aux.params=model$rnn.exec$ref.aux.arrays) seq.len <- m$seq.len batch.size <- m$batch.size num.rnn.layer <- m$num.rnn.layer num.hidden <- m$num.hidden opt <- mx.opt.create(optimizer, rescale.grad=(1/batch.size), ...) updater <- mx.opt.get.updater(opt, m$rnn.exec$ref.arg.arrays) epoch.counter <- 0 log.period <- max(as.integer(1000 / seq.len), 1) last.perp <- 10000000.0 for (iteration in 1:num.round) { nbatch <- 0 train.nll <- 0 # reset states init.states <- list() for (name in init.states.name) { init.states[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.arg.arrays(m$rnn.exec, init.states, match.name=TRUE) tic <- Sys.time() train.data$reset() while (train.data$iter.next()) { # set rnn input rnn.input <- train.data$value() mx.exec.update.arg.arrays(m$rnn.exec, rnn.input, match.name=TRUE) mx.exec.forward(m$rnn.exec, is.train=TRUE) seq.label.probs <- mx.nd.choose.element.0index(m$rnn.exec$ref.outputs[["sm_output"]], get.label(m$rnn.exec$ref.arg.arrays[["label"]], ctx)) mx.exec.backward(m$rnn.exec) init.states <- list() for (name in init.states.name) { init.states[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.arg.arrays(m$rnn.exec, init.states, match.name=TRUE) # update epoch counter epoch.counter <- epoch.counter + 1 if (epoch.counter %% update.period == 0) { # the gradient of initial c and inital h should be zero init.grad <- list() for (name in init.states.name) { init.grad[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.grad.arrays(m$rnn.exec, init.grad, match.name=TRUE) arg.blocks <- updater(m$rnn.exec$ref.arg.arrays, m$rnn.exec$ref.grad.arrays) mx.exec.update.arg.arrays(m$rnn.exec, arg.blocks, skip.null=TRUE) grad.arrays <- list() for (name in names(m$rnn.exec$ref.grad.arrays)) { if (is.param.name(name)) grad.arrays[[name]] <- m$rnn.exec$ref.grad.arrays[[name]]*0 } mx.exec.update.grad.arrays(m$rnn.exec, grad.arrays, match.name=TRUE) } train.nll <- train.nll + calc.nll(as.array(seq.label.probs), batch.size) nbatch <- nbatch + seq.len if (!is.null(batch.end.callback)) { batch.end.callback(iteration, nbatch, environment()) } if ((epoch.counter %% log.period) == 0) { message(paste0("Epoch [", epoch.counter, "] Train: NLL=", train.nll / nbatch, ", Perp=", exp(train.nll / nbatch))) } } train.data$reset() # end of training loop toc <- Sys.time() message(paste0("Iter [", iteration, "] Train: Time: ", as.numeric(toc - tic, units="secs"), " sec, NLL=", train.nll / nbatch, ", Perp=", exp(train.nll / nbatch))) if (!is.null(eval.data)) { val.nll <- 0.0 # validation set, reset states init.states <- list() for (name in init.states.name) { init.states[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.arg.arrays(m$rnn.exec, init.states, match.name=TRUE) eval.data$reset() nbatch <- 0 while (eval.data$iter.next()) { # set rnn input rnn.input <- eval.data$value() mx.exec.update.arg.arrays(m$rnn.exec, rnn.input, match.name=TRUE) mx.exec.forward(m$rnn.exec, is.train=FALSE) # probability of each label class, used to evaluate nll seq.label.probs <- mx.nd.choose.element.0index(m$rnn.exec$ref.outputs[["sm_output"]], get.label(m$rnn.exec$ref.arg.arrays[["label"]], ctx)) # transfer the states init.states <- list() for (name in init.states.name) { init.states[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.arg.arrays(m$rnn.exec, init.states, match.name=TRUE) val.nll <- val.nll + calc.nll(as.array(seq.label.probs), batch.size) nbatch <- nbatch + seq.len } eval.data$reset() perp <- exp(val.nll / nbatch) message(paste0("Iter [", iteration, "] Val: NLL=", val.nll / nbatch, ", Perp=", exp(val.nll / nbatch))) } # get the model out epoch_continue <- TRUE if (!is.null(epoch.end.callback)) { epoch_continue <- epoch.end.callback(iteration, 0, environment(), verbose = verbose) } if (!epoch_continue) { break } } return (m) } # check data and translate data into iterator if data is array/matrix check.data <- function(data, batch.size, is.train) { if (!is.null(data) && !is.list(data) && !is.mx.dataiter(data)) { stop("The dataset should be either a mx.io.DataIter or a R list") } if (is.list(data)) { if (is.null(data$data) || is.null(data$label)){ stop("Please provide dataset as list(data=R.array, label=R.array)") } data <- mx.model.init.iter.rnn(data$data, data$label, batch.size=batch.size, is.train = is.train) } if (!is.null(data) && !data$iter.next()) { data$reset() if (!data$iter.next()) stop("Empty input") } return (data) }
9,826
apache-2.0
b269d07226017fb21ef663ef82d19f0b6a74c0fb
coder-james/mxnet
R-package/R/rnn_model.R
is.param.name <- function(name) { return (grepl('weight$', name) || grepl('bias$', name) || grepl('gamma$', name) || grepl('beta$', name) ) } # Initialize parameters mx.model.init.params.rnn <- function(symbol, input.shape, initializer, ctx) { if (!is.mx.symbol(symbol)) stop("symbol need to be MXSymbol") slist <- symbol$infer.shape(input.shape) if (is.null(slist)) stop("Not enough information to get shapes") arg.params <- mx.init.create(initializer, slist$arg.shapes, ctx, skip.unknown=TRUE) aux.params <- mx.init.create(initializer, slist$aux.shapes, ctx, skip.unknown=FALSE) return(list(arg.params=arg.params, aux.params=aux.params)) } # Initialize the data iter mx.model.init.iter.rnn <- function(X, y, batch.size, is.train) { if (is.MXDataIter(X)) return(X) shape <- dim(X) if (is.null(shape)) { num.data <- length(X) } else { ndim <- length(shape) num.data <- shape[[ndim]] } if (is.null(y)) { if (is.train) stop("Need to provide parameter y for training with R arrays.") y <- c(1:num.data) * 0 } batch.size <- min(num.data, batch.size) return(mx.io.arrayiter(X, y, batch.size=batch.size, shuffle=is.train)) } # set up rnn model with rnn cells setup.rnn.model <- function(rnn.sym, ctx, num.rnn.layer, seq.len, num.hidden, num.embed, num.label, batch.size, input.size, init.states.name, initializer=mx.init.uniform(0.01), dropout=0) { arg.names <- rnn.sym$arguments input.shapes <- list() for (name in arg.names) { if (name %in% init.states.name) { input.shapes[[name]] <- c(num.hidden, batch.size) } else if (grepl('data$', name) || grepl('label$', name) ) { if (seq.len == 1) { input.shapes[[name]] <- c(batch.size) } else { input.shapes[[name]] <- c(seq.len, batch.size) } } } params <- mx.model.init.params.rnn(rnn.sym, input.shapes, initializer, mx.cpu()) args <- input.shapes args$symbol <- rnn.sym args$ctx <- ctx args$grad.req <- "add" rnn.exec <- do.call(mx.simple.bind, args) mx.exec.update.arg.arrays(rnn.exec, params$arg.params, match.name=TRUE) mx.exec.update.aux.arrays(rnn.exec, params$aux.params, match.name=TRUE) grad.arrays <- list() for (name in names(rnn.exec$ref.grad.arrays)) { if (is.param.name(name)) grad.arrays[[name]] <- rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.grad.arrays(rnn.exec, grad.arrays, match.name=TRUE) return (list(rnn.exec=rnn.exec, symbol=rnn.sym, num.rnn.layer=num.rnn.layer, num.hidden=num.hidden, seq.len=seq.len, batch.size=batch.size, num.embed=num.embed)) } calc.nll <- function(seq.label.probs, batch.size) { nll = - sum(log(seq.label.probs)) / batch.size return (nll) } get.label <- function(label, ctx) { label <- as.array(label) seq.len <- dim(label)[[1]] batch.size <- dim(label)[[2]] sm.label <- array(0, dim=c(seq.len*batch.size)) for (seqidx in 1:seq.len) { sm.label[((seqidx-1)*batch.size+1) : (seqidx*batch.size)] <- label[seqidx,] } return (mx.nd.array(sm.label, ctx)) } # training rnn model train.rnn <- function (model, train.data, eval.data, num.round, update.period, init.states.name, optimizer='sgd', ctx=mx.ctx.default(), epoch.end.callback, batch.end.callback, verbose=TRUE, ...) { m <- model model <- list(symbol=model$symbol, arg.params=model$rnn.exec$ref.arg.arrays, aux.params=model$rnn.exec$ref.aux.arrays) seq.len <- m$seq.len batch.size <- m$batch.size num.rnn.layer <- m$num.rnn.layer num.hidden <- m$num.hidden opt <- mx.opt.create(optimizer, rescale.grad=(1/batch.size), ...) updater <- mx.opt.get.updater(opt, m$rnn.exec$ref.arg.arrays) epoch.counter <- 0 log.period <- max(as.integer(1000 / seq.len), 1) last.perp <- 10000000.0 for (iteration in 1:num.round) { nbatch <- 0 train.nll <- 0 # reset states init.states <- list() for (name in init.states.name) { init.states[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.arg.arrays(m$rnn.exec, init.states, match.name=TRUE) tic <- Sys.time() train.data$reset() while (train.data$iter.next()) { # set rnn input rnn.input <- train.data$value() mx.exec.update.arg.arrays(m$rnn.exec, rnn.input, match.name=TRUE) mx.exec.forward(m$rnn.exec, is.train=TRUE) seq.label.probs <- mx.nd.choose.element.0index(m$rnn.exec$ref.outputs[["sm_output"]], get.label(m$rnn.exec$ref.arg.arrays[["label"]], ctx)) mx.exec.backward(m$rnn.exec) init.states <- list() for (name in init.states.name) { init.states[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.arg.arrays(m$rnn.exec, init.states, match.name=TRUE) # update epoch counter epoch.counter <- epoch.counter + 1 if (epoch.counter %% update.period == 0) { # the gradient of initial c and inital h should be zero init.grad <- list() for (name in init.states.name) { init.grad[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.grad.arrays(m$rnn.exec, init.grad, match.name=TRUE) arg.blocks <- updater(m$rnn.exec$ref.arg.arrays, m$rnn.exec$ref.grad.arrays) mx.exec.update.arg.arrays(m$rnn.exec, arg.blocks, skip.null=TRUE) grad.arrays <- list() for (name in names(m$rnn.exec$ref.grad.arrays)) { if (is.param.name(name)) grad.arrays[[name]] <- m$rnn.exec$ref.grad.arrays[[name]]*0 } mx.exec.update.grad.arrays(m$rnn.exec, grad.arrays, match.name=TRUE) } train.nll <- train.nll + calc.nll(as.array(seq.label.probs), batch.size) nbatch <- nbatch + seq.len if (!is.null(batch.end.callback)) { batch.end.callback(iteration, nbatch, environment()) } if ((epoch.counter %% log.period) == 0) { message(paste0("Epoch [", epoch.counter, "] Train: NLL=", train.nll / nbatch, ", Perp=", exp(train.nll / nbatch))) } } train.data$reset() # end of training loop toc <- Sys.time() message(paste0("Iter [", iteration, "] Train: Time: ", as.numeric(toc - tic, units="secs"), " sec, NLL=", train.nll / nbatch, ", Perp=", exp(train.nll / nbatch))) if (!is.null(eval.data)) { val.nll <- 0.0 # validation set, reset states init.states <- list() for (name in init.states.name) { init.states[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.arg.arrays(m$rnn.exec, init.states, match.name=TRUE) eval.data$reset() nbatch <- 0 while (eval.data$iter.next()) { # set rnn input rnn.input <- eval.data$value() mx.exec.update.arg.arrays(m$rnn.exec, rnn.input, match.name=TRUE) mx.exec.forward(m$rnn.exec, is.train=FALSE) # probability of each label class, used to evaluate nll seq.label.probs <- mx.nd.choose.element.0index(m$rnn.exec$ref.outputs[["sm_output"]], get.label(m$rnn.exec$ref.arg.arrays[["label"]], ctx)) # transfer the states init.states <- list() for (name in init.states.name) { init.states[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.arg.arrays(m$rnn.exec, init.states, match.name=TRUE) val.nll <- val.nll + calc.nll(as.array(seq.label.probs), batch.size) nbatch <- nbatch + seq.len } eval.data$reset() perp <- exp(val.nll / nbatch) message(paste0("Iter [", iteration, "] Val: NLL=", val.nll / nbatch, ", Perp=", exp(val.nll / nbatch))) } # get the model out epoch_continue <- TRUE if (!is.null(epoch.end.callback)) { epoch_continue <- epoch.end.callback(iteration, 0, environment(), verbose = verbose) } if (!epoch_continue) { break } } return (m) } # check data and translate data into iterator if data is array/matrix check.data <- function(data, batch.size, is.train) { if (!is.null(data) && !is.list(data) && !is.mx.dataiter(data)) { stop("The dataset should be either a mx.io.DataIter or a R list") } if (is.list(data)) { if (is.null(data$data) || is.null(data$label)){ stop("Please provide dataset as list(data=R.array, label=R.array)") } data <- mx.model.init.iter.rnn(data$data, data$label, batch.size=batch.size, is.train = is.train) } if (!is.null(data) && !data$iter.next()) { data$reset() if (!data$iter.next()) stop("Empty input") } return (data) }
9,826
apache-2.0
b269d07226017fb21ef663ef82d19f0b6a74c0fb
apaleyes/mxnet
R-package/R/rnn_model.R
is.param.name <- function(name) { return (grepl('weight$', name) || grepl('bias$', name) || grepl('gamma$', name) || grepl('beta$', name) ) } # Initialize parameters mx.model.init.params.rnn <- function(symbol, input.shape, initializer, ctx) { if (!is.mx.symbol(symbol)) stop("symbol need to be MXSymbol") slist <- symbol$infer.shape(input.shape) if (is.null(slist)) stop("Not enough information to get shapes") arg.params <- mx.init.create(initializer, slist$arg.shapes, ctx, skip.unknown=TRUE) aux.params <- mx.init.create(initializer, slist$aux.shapes, ctx, skip.unknown=FALSE) return(list(arg.params=arg.params, aux.params=aux.params)) } # Initialize the data iter mx.model.init.iter.rnn <- function(X, y, batch.size, is.train) { if (is.MXDataIter(X)) return(X) shape <- dim(X) if (is.null(shape)) { num.data <- length(X) } else { ndim <- length(shape) num.data <- shape[[ndim]] } if (is.null(y)) { if (is.train) stop("Need to provide parameter y for training with R arrays.") y <- c(1:num.data) * 0 } batch.size <- min(num.data, batch.size) return(mx.io.arrayiter(X, y, batch.size=batch.size, shuffle=is.train)) } # set up rnn model with rnn cells setup.rnn.model <- function(rnn.sym, ctx, num.rnn.layer, seq.len, num.hidden, num.embed, num.label, batch.size, input.size, init.states.name, initializer=mx.init.uniform(0.01), dropout=0) { arg.names <- rnn.sym$arguments input.shapes <- list() for (name in arg.names) { if (name %in% init.states.name) { input.shapes[[name]] <- c(num.hidden, batch.size) } else if (grepl('data$', name) || grepl('label$', name) ) { if (seq.len == 1) { input.shapes[[name]] <- c(batch.size) } else { input.shapes[[name]] <- c(seq.len, batch.size) } } } params <- mx.model.init.params.rnn(rnn.sym, input.shapes, initializer, mx.cpu()) args <- input.shapes args$symbol <- rnn.sym args$ctx <- ctx args$grad.req <- "add" rnn.exec <- do.call(mx.simple.bind, args) mx.exec.update.arg.arrays(rnn.exec, params$arg.params, match.name=TRUE) mx.exec.update.aux.arrays(rnn.exec, params$aux.params, match.name=TRUE) grad.arrays <- list() for (name in names(rnn.exec$ref.grad.arrays)) { if (is.param.name(name)) grad.arrays[[name]] <- rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.grad.arrays(rnn.exec, grad.arrays, match.name=TRUE) return (list(rnn.exec=rnn.exec, symbol=rnn.sym, num.rnn.layer=num.rnn.layer, num.hidden=num.hidden, seq.len=seq.len, batch.size=batch.size, num.embed=num.embed)) } calc.nll <- function(seq.label.probs, batch.size) { nll = - sum(log(seq.label.probs)) / batch.size return (nll) } get.label <- function(label, ctx) { label <- as.array(label) seq.len <- dim(label)[[1]] batch.size <- dim(label)[[2]] sm.label <- array(0, dim=c(seq.len*batch.size)) for (seqidx in 1:seq.len) { sm.label[((seqidx-1)*batch.size+1) : (seqidx*batch.size)] <- label[seqidx,] } return (mx.nd.array(sm.label, ctx)) } # training rnn model train.rnn <- function (model, train.data, eval.data, num.round, update.period, init.states.name, optimizer='sgd', ctx=mx.ctx.default(), epoch.end.callback, batch.end.callback, verbose=TRUE, ...) { m <- model model <- list(symbol=model$symbol, arg.params=model$rnn.exec$ref.arg.arrays, aux.params=model$rnn.exec$ref.aux.arrays) seq.len <- m$seq.len batch.size <- m$batch.size num.rnn.layer <- m$num.rnn.layer num.hidden <- m$num.hidden opt <- mx.opt.create(optimizer, rescale.grad=(1/batch.size), ...) updater <- mx.opt.get.updater(opt, m$rnn.exec$ref.arg.arrays) epoch.counter <- 0 log.period <- max(as.integer(1000 / seq.len), 1) last.perp <- 10000000.0 for (iteration in 1:num.round) { nbatch <- 0 train.nll <- 0 # reset states init.states <- list() for (name in init.states.name) { init.states[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.arg.arrays(m$rnn.exec, init.states, match.name=TRUE) tic <- Sys.time() train.data$reset() while (train.data$iter.next()) { # set rnn input rnn.input <- train.data$value() mx.exec.update.arg.arrays(m$rnn.exec, rnn.input, match.name=TRUE) mx.exec.forward(m$rnn.exec, is.train=TRUE) seq.label.probs <- mx.nd.choose.element.0index(m$rnn.exec$ref.outputs[["sm_output"]], get.label(m$rnn.exec$ref.arg.arrays[["label"]], ctx)) mx.exec.backward(m$rnn.exec) init.states <- list() for (name in init.states.name) { init.states[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.arg.arrays(m$rnn.exec, init.states, match.name=TRUE) # update epoch counter epoch.counter <- epoch.counter + 1 if (epoch.counter %% update.period == 0) { # the gradient of initial c and inital h should be zero init.grad <- list() for (name in init.states.name) { init.grad[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.grad.arrays(m$rnn.exec, init.grad, match.name=TRUE) arg.blocks <- updater(m$rnn.exec$ref.arg.arrays, m$rnn.exec$ref.grad.arrays) mx.exec.update.arg.arrays(m$rnn.exec, arg.blocks, skip.null=TRUE) grad.arrays <- list() for (name in names(m$rnn.exec$ref.grad.arrays)) { if (is.param.name(name)) grad.arrays[[name]] <- m$rnn.exec$ref.grad.arrays[[name]]*0 } mx.exec.update.grad.arrays(m$rnn.exec, grad.arrays, match.name=TRUE) } train.nll <- train.nll + calc.nll(as.array(seq.label.probs), batch.size) nbatch <- nbatch + seq.len if (!is.null(batch.end.callback)) { batch.end.callback(iteration, nbatch, environment()) } if ((epoch.counter %% log.period) == 0) { message(paste0("Epoch [", epoch.counter, "] Train: NLL=", train.nll / nbatch, ", Perp=", exp(train.nll / nbatch))) } } train.data$reset() # end of training loop toc <- Sys.time() message(paste0("Iter [", iteration, "] Train: Time: ", as.numeric(toc - tic, units="secs"), " sec, NLL=", train.nll / nbatch, ", Perp=", exp(train.nll / nbatch))) if (!is.null(eval.data)) { val.nll <- 0.0 # validation set, reset states init.states <- list() for (name in init.states.name) { init.states[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.arg.arrays(m$rnn.exec, init.states, match.name=TRUE) eval.data$reset() nbatch <- 0 while (eval.data$iter.next()) { # set rnn input rnn.input <- eval.data$value() mx.exec.update.arg.arrays(m$rnn.exec, rnn.input, match.name=TRUE) mx.exec.forward(m$rnn.exec, is.train=FALSE) # probability of each label class, used to evaluate nll seq.label.probs <- mx.nd.choose.element.0index(m$rnn.exec$ref.outputs[["sm_output"]], get.label(m$rnn.exec$ref.arg.arrays[["label"]], ctx)) # transfer the states init.states <- list() for (name in init.states.name) { init.states[[name]] <- m$rnn.exec$ref.arg.arrays[[name]]*0 } mx.exec.update.arg.arrays(m$rnn.exec, init.states, match.name=TRUE) val.nll <- val.nll + calc.nll(as.array(seq.label.probs), batch.size) nbatch <- nbatch + seq.len } eval.data$reset() perp <- exp(val.nll / nbatch) message(paste0("Iter [", iteration, "] Val: NLL=", val.nll / nbatch, ", Perp=", exp(val.nll / nbatch))) } # get the model out epoch_continue <- TRUE if (!is.null(epoch.end.callback)) { epoch_continue <- epoch.end.callback(iteration, 0, environment(), verbose = verbose) } if (!epoch_continue) { break } } return (m) } # check data and translate data into iterator if data is array/matrix check.data <- function(data, batch.size, is.train) { if (!is.null(data) && !is.list(data) && !is.mx.dataiter(data)) { stop("The dataset should be either a mx.io.DataIter or a R list") } if (is.list(data)) { if (is.null(data$data) || is.null(data$label)){ stop("Please provide dataset as list(data=R.array, label=R.array)") } data <- mx.model.init.iter.rnn(data$data, data$label, batch.size=batch.size, is.train = is.train) } if (!is.null(data) && !data$iter.next()) { data$reset() if (!data$iter.next()) stop("Empty input") } return (data) }
9,826
apache-2.0
ae1f8e9efef828088fee8eee45ea07a4d32b1902
ccwang002/2014-China-RConf-Interactive-Vis
R_proj/play_grid.R
library(grid) grid.newpage() pushViewport(plotViewport(c(5, 4, 2, 2))) pushViewport(dataViewport( pressure$temperature, pressure$pressure, name="plotRegion" )) grid.points(pressure$temperature, pressure$pressure, name="dataSymbols") grid.rect(gp=gpar(fill=0)) grid.xaxis() grid.yaxis() grid.edit("dataSymbols", pch=10) upViewport(1) grid.rect(gp=gpar(lty="dashed", fill=0, lwd=4)) upViewport(1) grid.rect(gp=gpar(lty="dotted", fill=0, lwd=4)) downViewport("plotRegion") grid.text( "Pressure (mm Hg)\nversus\nTemperature (Celsius)", just="right", x=unit(250, "native"), y=unit(600, "native") )
633
mit
16b957f66af5a09820a39dcf89e49bbc0008cbff
kingaa/pomp
tests/R_v_C.R
options(digits=3) png(filename="R_v_C-%02d.png",res=100) ## ----packages------------------------------------------------------------ library(pomp) library(ggplot2) ## ----seed,echo=FALSE----------------------------------------------------- set.seed(56300069) ## ----R1------------------------------------------------------------------ simulate(times=1:100,t0=0, params=c(K=1,r=0.1,sigma=0.1,tau=0.1,X.0=1), rprocess=discrete_time( step.fun=function (X,r,K,sigma,...,delta.t) { eps <- exp(rnorm(n=1,mean=0,sd=sigma)) S <- exp(-r*delta.t) c(X=K^(1-S)*X^S*eps) }, delta.t=1 ), rmeasure=function (X, tau, ...) { c(Y=rlnorm(n=1,meanlog=log(X),sdlog=tau)) }, dmeasure=function (tau, X, Y, ..., log) { dlnorm(x=Y,meanlog=log(X),sdlog=tau,log=log) }, partrans=parameter_trans( toEst=function(r,K,sigma,tau,X.0,...){ log(c(r=r,K=K,sigma=sigma,tau=tau,X.0=X.0)) }, fromEst=function(r,K,sigma,tau,X.0,...){ exp(c(r=r,K=K,sigma=sigma,tau=tau,X.0=X.0)) } ) ) -> gompertz ## ----R2------------------------------------------------------------------ gompertz %>% as.data.frame() %>% melt(id="time") %>% ggplot(aes(x=time,y=value,color=variable))+ geom_line()+ labs(y="X, Y")+ theme_bw() ## ----C1------------------------------------------------------------------ simulate(times=0:100,t0=0, params=c(K=1,r=0.1,sigma=0.1,tau=0.1,X.0=1), dmeasure=Csnippet(" lik = dlnorm(Y,log(X),tau,give_log);" ), rmeasure=Csnippet(" Y = rlnorm(log(X),tau);" ), rprocess=discrete_time( step.fun=Csnippet(" double S = exp(-r*dt); double logeps = (sigma > 0.0) ? rnorm(0,sigma) : 0.0; X = pow(K,(1-S))*pow(X,S)*exp(logeps);" ), delta.t=1 ), partrans=parameter_trans(log=c("r","K","sigma","tau","X.0")), paramnames=c("r","K","sigma","X.0","tau"), obsnames="Y", statenames="X" ) -> Gompertz ## ----params-------------------------------------------------------------- p <- parmat(coef(Gompertz),4) p["X.0",] <- c(0.5,0.9,1.1,1.5) ## ----sim1---------------------------------------------------------------- simulate(Gompertz,params=p,format="data.frame") %>% ggplot(aes(x=time,y=X,group=.id,color=.id))+ geom_line()+ guides(color="none")+ theme_bw()+ labs(title="Gompertz model",subtitle="stochastic simulations") ## ----pf1----------------------------------------------------------------- pf <- replicate(n=10,pfilter(Gompertz,Np=500)) logmeanexp(sapply(pf,logLik),se=TRUE) ## ----comparison---------------------------------------------------------- system.time(simulate(gompertz,nsim=10000,format="arrays")) system.time(simulate(Gompertz,nsim=10000,format="arrays")) system.time(pfilter(gompertz,Np=1000)) system.time(pfilter(Gompertz,Np=1000)) dev.off()
2,788
gpl-3.0
6a7a22d0fcbd272672d047acea67ac1955d7e81f
ReproducibleQM/sapsuckRz
prism_weather_data_pull.R
##Download weather data from PRISM and pull weather data for individual sites #created on:5/17/2017 #created by: Chad Zirbel #pull in coordinates for all sites location<-read.csv("counties+coordinates2.csv") #install and load packages #install.packages("prism") library(prism) #pull max and min temp and precipitation type=c("tmax","tmin","ppt") #download daily prism data from 2003-2016 for(i in 1:3){ var <- paste("weather", i, sep = "") assign(var, get_prism_dailys(type=type[i], minDate = "2003-01-01", maxDate = "2016-01-01", keepZip=T)) } #function to pull data from specific locations prism_cut <- function(location,prismfile){ meta_d <- unlist(prism_md(prism_data[,1],returnDate=T)) meta_names <- as.matrix(unlist(prism_md(prism_data[,1]))) param_name <- do.call(rbind,strsplit(meta_names,"-"))[,3] pstack <- prism_stack(prism_data[,1]) data <- unlist(extract(pstack,cbind(location$LONG,location$LAT),nrow=1,buffer=10)) data <- as.data.frame(data) data$date <- as.Date(meta_d) data$param<-param_name data$siteid<-location$SITEID return(data)} #load in the prism data files prism_data<-ls_prism_data(absPath=T) #pull the data weather_data<-prism_cut(location,prism_data[,1])
1,230
mpl-2.0
702aa7237898dd8dd41030edb2676f609f8e0332
mem48/glider
Gavin/forGavin.R
# Simple File to get Gavin Started # Step 1: Get R set up correctly library(igraph) # Load in the igraph library if it is not available use install.packages("igraph") # Step 2: Read in the data graph = readRDS("twitterNetwork.Rds") #Read the file called twitterNetwork and make it a variaible called graph # Step 3: Let’s find out some basics about this graph gorder(graph) # How many verticies does it have? ecount(graph) # How many edges does it have? # Step 4: Make a smaller graph by removing some of the low degree vertices graph.trim = delete.vertices(graph, which(degree(graph)<=10)) # Notice that we have created a new graph called graph.trim gorder(graph.trim) # Reduced the oerde by about a factor of 10 # Step 5: Calculate some statistics for each vertex, this will take a minute or two V(graph.trim)$degree.total <- degree(graph.trim, mode = "total") # Total Degree V(graph.trim)$degree.in <- degree(graph.trim, mode = "in") # Degree In V(graph.trim)$degree.out <- degree(graph.trim, mode = "out") # Degree Out V(graph.trim)$strength.total <- strength(graph.trim, mode = "total") # Total Strength V(graph.trim)$strength.in <- strength(graph.trim, mode = "in") # Strength in V(graph.trim)$strength.out <- strength(graph.trim, mode = "out") # strength out V(graph.trim)$between <- betweenness(graph.trim) # betweeness centrality V(graph.trim)$closeness <- closeness(graph.trim) # closeness centrality V(graph.trim)$eigenvector <- eigen_centrality(graph.trim, directed = TRUE, scale = FALSE, weights = E(graph.trim)$weight)$vector #eigenvector centrality V(graph.trim)$PageRank <- page_rank(graph.trim, directed = TRUE, damping = 0.85, weights = E(graph.trim)$weight)$vector #page rank centrality # Step 6: Let’s export those results as a table so we can see them vert = as_data_frame(graph.trim, what="vertices") # Now click on the table icon next to vertices in the environment tab # on the right side of the screen to view the table # Notice that you can sort using the arrows on each column # This is where the excel spreadsheets come from # We can also save the results and view them in excel write.csv(vert,"verticies.csv", row.names = FALSE) # A CSV file will be saved in the same folder as the Rproj file # CSV files can be opened in Excel # Step 7: Let’s draw a graph to look at # Step 7a: First, we need a much smaller graph with only a few hundred vertices graph.toDraw = delete.vertices(graph.trim, which(V(graph.trim)$strength.in <= 800)) # Notice the different syntax for accessing the variables that we created # whereas before we had to calculate the degree within the delete.verticies function # We have already calculated the strenght.in and can access it via V(graph.trim)$strength.in gorder(graph.toDraw) # Now only have a few hundred vertices # Step 7b: We can plot graphs witin R plot(graph.toDraw) # But the defaults are often not very clear and it is slow to draw large complex graphs # SO let make a pretty graph #Step 7c: Let colour the vertices based on one of the variables we have calculated # to do this we define a colour scale and the add a new colour variable to the graph c_scale = colorRamp(c('blue','cyan','yellow','red')) #Define a colour scale from blue to red # Now for each vertex assing a colour V(graph.toDraw)$color = apply(c_scale(V(graph.toDraw)$between / max(V(graph.toDraw)$between, na.rm = T)), 1, function(x) rgb(x[1]/255,x[2]/255,x[3]/255) ) # Not that we have normaised the betweeness centralisty score on a 0-1 scale by dividing by the max(imum) value #Step 7d: Draw the graph and export it as a SVG File #SVG file can be opened in web browsers and graphic programmes # I found Microsoft Edge on windows 10 to be very quick at opening SVG files #Create High Resolution Plots svg(filename="gavindemo.svg", # Set the name of the file width=25, # Set width and height of the graph height=25, pointsize=10) # Set the font size of the text labels par(mar = c(1,1,1,1)) # Defines the bounds for the graph, don't change plot(graph.toDraw, edge.width = E(graph.toDraw)$weight/ 20, # Set the widths of the edges vertex.size = V(graph.toDraw)$strength.total / 1000 , # Set the size of the vertex edge.arrow.size = 0.2, # set the size of the arrows on the edges edge.curved=0.2, # Set how curved the edges are vertex.color = V(graph.toDraw)$color, #Use the colour schemes defined above vertex.frame.color = V(graph.toDraw)$color, vertex.label.family= "Helvetica", #Label font vertex.label.color = "black", # Label font colour layout = layout_nicely, #Which layout algorithm to use see http://igraph.org/r/doc/layout_.html rescale = TRUE, #Scale graph to fit axes = FALSE); dev.off() # Don't show XY axis
4,758
gpl-3.0
c83e9d2bc29c7eda47c2a4c5301493fb74c9bac2
leomaranhao/dataScience9week4
ui.R
library(shiny) library(leaflet) shinyUI(pageWithSidebar( headerPanel("Insurance Direct Premium in Brazil"), sidebarPanel( selectInput("Segment", "Choose the Segment:", choices = c("Auto" = "Auto", "Multiple Peril" = "Compreensivos", "DPVAT - Mandatory Personal Injury caused by Motor Vehicle" = "DPVAT", "Financial" = "Financeiros", "Extended Guarantee" = "Garantia Estendida", "Major Risks" = "Grandes Riscos", "Housing" = "Habitacional", "Maritime/Aircraft" = "Maritmos/Aeronauticos", "Microinsurance" = "Microsseguros", "Equity - Other" = "Patrimoniais - Outros", "Life" = "Pessoas", "Civil Liability" = "RC", "Crop/Cattle/Florest/Fish" = "Rural", "Transportation" = "Transporte", "Redeemable Life Insurance" = "VGBL")), selectInput("Year", "Choose the year:", choices = as.character(c(2005 : 2015))), h4("Instructions"), tags$ul( tags$li("Direct premiums are the total premiums received by an insurance company before taking into account reinsurance ceded. The growth of direct premiums represent the growth of a company’s insurance business."), tags$li("Here we have the direct premiums of brazilian companies by brazilian states from 2005 up to 2015. The different lines of business were aggregated into what we called \"Segments\". The premiums are billions of brazilian Reais (R$), roughly 1 US$ = 3.37 R$ in 12-09-2016."), tags$li("Just select a segment and a year and the application will generate the percentage distribution of premiums per brazilian states and a table with the values themselves.") ), h4("Links"), a(href="https://github.com/leomaranhao/dataScience9week4", "server.R and ui.R ") ), mainPanel( h3("Percentage distribuition of Direct Premium in Brazil"), leafletOutput("plotSaida"), h3("Direct Premiums per State"), htmlOutput("tabela") ) ))
2,456
apache-2.0
b573359b4ff774c67a6621af5c5d11e9efd5b8b2
oursu/Gem_code
data_processing/RNAseq/scripts/DEgenes_fromCufflinks.R
#==== args=commandArgs(trailingOnly=TRUE) DE_FILE=args[1] SIG=as.numeric(args[2]) FPKMmin=as.numeric(args[3]) out=args[4] EXPRESSED=args[5] #Produce a set of upregulated genes, and a set of downregulated genes #Get data de_data=read.table(DE_FILE,header=TRUE) #Function for picking DE genes pick_DE_genes=function(qvalueThresh,foldChange,FPKMmin,FPKMdiff,data){ OKFoldChange=which(abs(data$log2.fold_change.)>=log(foldChange,2)) OKFPKMmin=union(which(data$value_1>=FPKMmin),which(data$value_2>=FPKMmin)) OKFPKMdiff=which(abs(data$value_1-data$value_2)>=FPKMdiff) OKqvalue=which(data$q_value<=qvalueThresh) #For DE, keep only OK genes OKtestgenes=which(as.character(data$status)=='OK') DEidx=intersect(OKqvalue,intersect(OKFPKMdiff,intersect(OKFPKMmin,OKFoldChange))) #Hits: DEgene_data=data[DEidx,] #split into up and downreg columns_of_interest=c('gene','log2.fold_change.', 'value_1','value_2') deGenes=list() deGenes[['up']]=DEgene_data[which(as.numeric(as.character(DEgene_data[,'log2.fold_change.']))>0),columns_of_interest] deGenes[['down']]=DEgene_data[which(as.numeric(as.character(DEgene_data[,'log2.fold_change.']))<0),columns_of_interest] return(deGenes) } #Get DE genes DE_genes=pick_DE_genes(SIG,1.5,FPKMmin,1,de_data) print(DE_genes) write.table(DE_genes[['up']],file=paste(out,'.UpReg.txt',sep=''),quote=F,row.names=F,col.names=T,sep='\t') write.table(DE_genes[['down']],file=paste(out,'.DownReg.txt',sep=''),quote=F,row.names=F,col.names=T,sep='\t') write.table(rbind(DE_genes[['down']],DE_genes[['up']]),file=paste(out,'.UpAndDownReg.txt',sep=''),quote=F,row.names=F,col.names=T,sep='\t') #also write the genes that are expressed OKFPKMmin=union(which(de_data$value_1>=FPKMmin),which(de_data$value_2>=FPKMmin)) write.table(de_data[OKFPKMmin,'gene'],file=EXPRESSED,quote=F,row.names=F,col.names=T,sep='\t')
1,896
bsd-3-clause
c7b44baf51c184796a12eb6a1b668f4510f006e2
advnturecaptlst/kaggle_archive
avito/avito.R
# coding: utf-8 #__author__ = 'IPM' # Required Libraries library(data.table) library(readr) library(caret) library(stringdist) # Read in data location <- fread("~/Documents/kaggle/avito/input/Location.csv") itemPairsTest <- fread("~/Documents/kaggle/avito/input/ItemPairs_test.csv") itemPairsTrain <- fread("~/Documents/kaggle/avito/input/ItemPairs_train.csv") itemInfoTest <- read_csv("~/Documents/kaggle/avito/input/ItemInfo_test.csv") itemInfoTrain <- read_csv("~/Documents/kaggle/avito/input/ItemInfo_train.csv") itemInfoTest <- data.table(itemInfoTest) itemInfoTrain <- data.table(itemInfoTrain) setkey(location, locationID) setkey(itemInfoTrain, itemID) setkey(itemInfoTest, itemID) # Drop unused factors dropAndNumChar <- function(itemInfo){ itemInfo[, ':=' (ncharTitle = nchar(title), ncharDescription = nchar(description), description = NULL, images_array = NULL, attrsJSON = NULL)] } dropAndNumChar(itemInfoTest) dropAndNumChar(itemInfoTrain) # Merge mergeInfo <- function(itemPairs, itemInfo){ # merge on itemID_1 setkey(itemPairs, itemID_1) itemPairs <- itemInfo[itemPairs] setnames(itemPairs, names(itemInfo), paste0(names(itemInfo), "_1")) # merge on itemID_2 setkey(itemPairs, itemID_2) itemPairs <- itemInfo[itemPairs] setnames(itemPairs, names(itemInfo), paste0(names(itemInfo), "_2")) # merge on locationID_1 setkey(itemPairs, locationID_1) itemPairs <- location[itemPairs] setnames(itemPairs, names(location), paste0(names(location), "_1")) # merge on locationID_2 setkey(itemPairs, locationID_2) itemPairs <- location[itemPairs] setnames(itemPairs, names(location), paste0(names(location), "_2")) return(itemPairs) } itemPairsTrain <- mergeInfo(itemPairsTrain, itemInfoTrain) itemPairsTest <- mergeInfo(itemPairsTest, itemInfoTest) rm(list=c("itemInfoTest", "itemInfoTrain", "location")) # Create features matchPair <- function(x, y){ ifelse(is.na(x), ifelse(is.na(y), 3, 2), ifelse(is.na(y), 2, ifelse(x==y, 1, 4))) } createFeatures <- function(itemPairs){ itemPairs[, ':=' (locationMatch = matchPair(locationID_1, locationID_2), locationID_1 = NULL, locationID_2 = NULL, regionMatch = matchPair(regionID_1, regionID_2), regionID_1 = NULL, regionID_2 = NULL, metroMatch = matchPair(metroID_1, metroID_2), metroID_1 = NULL, metroID_2 = NULL, categoryID_1 = NULL, categoryID_2 = NULL, priceMatch = matchPair(price_1, price_2), priceDiff = pmax(price_1/price_2, price_2/price_1), priceMin = pmin(price_1, price_2, na.rm=TRUE), priceMax = pmax(price_1, price_2, na.rm=TRUE), price_1 = NULL, price_2 = NULL, titleStringDist = stringdist(title_1, title_2, method = "jw"), titleStringDist2 = (stringdist(title_1, title_2, method = "lcs") / pmax(ncharTitle_1, ncharTitle_2, na.rm=TRUE)), title_1 = NULL, title_2 = NULL, titleCharDiff = pmax(ncharTitle_1/ncharTitle_2, ncharTitle_2/ncharTitle_1), titleCharMin = pmin(ncharTitle_1, ncharTitle_2, na.rm=TRUE), titleCharMax = pmax(ncharTitle_1, ncharTitle_2, na.rm=TRUE), ncharTitle_1 = NULL, ncharTitle_2 = NULL, descriptionCharDiff = pmax(ncharDescription_1/ncharDescription_2, ncharDescription_2/ncharDescription_1), descriptionCharMin = pmin(ncharDescription_1, ncharDescription_2, na.rm=TRUE), descriptionCharMax = pmax(ncharDescription_1, ncharDescription_2, na.rm=TRUE), ncharDescription_1 = NULL, ncharDescription_2 = NULL, distance = sqrt((lat_1-lat_2)^2+(lon_1-lon_2)^2), lat_1 = NULL, lat_2 = NULL, lon_1 = NULL, lon_2 = NULL, itemID_1 = NULL, itemID_2 = NULL)] itemPairs[, ':=' (priceDiff = ifelse(is.na(priceDiff), 0, priceDiff), priceMin = ifelse(is.na(priceMin), 0, priceMin), priceMax = ifelse(is.na(priceMax), 0, priceMax), titleStringDist = ifelse(is.na(titleStringDist), 0, titleStringDist), titleStringDist2 = ifelse(is.na(titleStringDist2) | titleStringDist2 == Inf, 0, titleStringDist2))] } createFeatures(itemPairsTest) createFeatures(itemPairsTrain) library(xgboost) maxTrees <- 500 shrinkage <- 0.1 gamma <- 2 depth <- 8 minChildWeight <- 49 colSample <- 0.85 subSample <- 0.85 earlyStopRound <- 10 modelVars <- names(itemPairsTrain)[which(!(names(itemPairsTrain) %in% c("isDuplicate", "generationMethod", "foldId")))] itemPairsTest <- data.frame(itemPairsTest) itemPairsTrain <- data.frame(itemPairsTrain) set.seed(13) #cat(dim(itemPairsTrain)) #itemPairsTrain <- itemPairsTrain[sample(nrow(itemPairsTrain), 500000), ] # Matrix dtrain <- xgb.DMatrix(as.matrix(itemPairsTrain[, modelVars]), label=itemPairsTrain$isDuplicate) dtest <- xgb.DMatrix(as.matrix(itemPairsTest[, modelVars])) # xgboost cross-validated set.seed(13) #xgbCV <- xgb.cv(params=list(max_depth=depth, # eta=shrinkage, # gamma=gamma, # colsample_bytree=colSample, # min_child_weight=minChildWeight, # subsample=subSample, # objective="binary:logistic"), # data=dtrain, # nrounds=maxTrees, # eval_metric ="auc", # nfold=4, # stratified=TRUE, # early.stop.round=earlyStopRound) #numTrees <- min(which(xgbCV$test.auc.mean==max(xgbCV$test.auc.mean))) xgbResult <- xgboost(params=list(max_depth=depth, eta=shrinkage, gamma=gamma, colsample_bytree=colSample, min_child_weight=minChildWeight), data=dtrain, nrounds=maxTrees, objective="binary:logistic", eval_metric="auc") testPreds <- predict(xgbResult, dtest) submission <- data.frame(id=itemPairsTest$id, probability=testPreds) write.csv(submission, file="submission_r_v2.csv",row.names=FALSE)
6,768
apache-2.0
01064a6146e8eb6672cb3c97eacc5bcc4efbe052
javierluraschi/sparkworker
R/worker_apply.R
spark_worker_apply <- function(sc) { hostContextId <- invoke_method(sc, FALSE, "Handler", "getHostContext") log("retrieved worker context id ", hostContextId) context <- structure( class = c("spark_jobj", "worker_jobj"), list( id = hostContextId, connection = sc ) ) log("retrieved worker context") length <- worker_invoke(context, "getSourceArrayLength") log("found ", length, " rows") data <- worker_invoke(context, "getSourceArraySeq") log("retrieved ", length(data), " rows") closureRaw <- worker_invoke(context, "getClosure") closure <- unserialize(closureRaw) columnNames <- worker_invoke(context, "getColumns") data <- lapply(data, function(e) { names(e) <- columnNames e }) data <- if (length(formals(closure)) > 0) lapply(data, closure) else lapply(data, function(e) { closure() }) if (!identical(typeof(data[[1]]), "list")) { data <- lapply(data, function(e) list(e)) } worker_invoke(context, "setResultArraySeq", data) log("updated ", length(data), " rows") spark_split <- worker_invoke(context, "finish") log("finished apply") } spark_worker_collect <- function(sc) { collected <- invoke_static(sc, "sparklyr.Utils", "collect", sdf, separator$regexp) transformed <- lapply(collected, function(e) { sdf_deserialize_column(e, sc) }) }
1,366
apache-2.0
e6b4137c27603998b86d43e3751a211436cdf420
nstauffer/aim.analysis
R/benchmarking.R
#' Apply benchmarks to data #' @description Using data that has unique identifier and indicator value variables, apply benchmarks. The benchmarks are applied to the data based on the benchmark group(s) that the data belong to, which may already be assigned in the data or may be added with a benchmark group lookup table. #' @param data Data frame or spatial * data frame. The data to be benchmarked. Must contain the variable(s) in \code{idvars} as unique identifiers. May be "wide" or "long" data. If wide, then each indicator name should be a variable name. If long, then the indicator names and values should be in variables named \code{"indicator_var"} and \code{"value"}. #' @param idvars Character string or vecor of character strings. The names of the variable(s) in \code{data} which serve as unique identifiers. #' @param benchmark_group_var Optional character string. The name of the variable that holds the benchmark group memberships. If \code{NULL} then it defaults to the variable in \code{benchmark_group_lut} that is not in \code{idvars}. Defaults to \code{NULL}. #' @param benchmark_group_lut Optional data frame. The lookup table used to assign benchmark group membership to \code{data}. Must contain all of the variables in \code{idvar} and one additional variable with the benchmark group memberships. #' @param benchmarks Data frame. The benchmarks in the format produced by \code{read.benchmarks()}. If the benchmark group membership variable in other data frames is not \code{"Benchmark.Group"} then it must be renamed here. #' @param verbose Logical. If \code{TRUE} then the function will generate additional messages as it executes. #' @return A long data frame of each point/benchmarked indicator combination with the assigned condition category. #' @export apply_benchmarks <- function(data, idvars, benchmark_group_var = NULL, benchmark_group_lut = NULL, benchmarks, verbose = FALSE) { if (grepl(class(data)[1], pattern = "^Spatial.*DataFrame$")) { data <- data@data } else if (class(data) != "data.frame") { stop("data must either be a data frame or a spatial data frame.") } idvars <- c(idvars, benchmark_group_var) missing_idvars <- idvars[!(idvars %in% names(data))] if (length(missing_idvars) > 0) { stop(paste0("The following variables are missing from data: ", paste(missing_idvars, collapse = ", "))) } if (class(benchmarks) != "data.frame") { stop("Benchmarks must be a data frame.") } if (!is.null(benchmark_group_var)) { if (!(benchmark_group_var %in% names(benchmarks)) & !("Benchmark.Group" %in% names(benchmarks))) { stop(paste0("The variable ", benchmark_group_var, "does not appear in the data frame benchmarks")) } else { if (verbose) { message(paste0("Adding the contents of benchmarks[['Benchmark.Group']] to benchmarks[['", benchmark_group_var, "']]")) } benchmarks[[benchmark_group_var]] <- benchmarks[["Benchmark.Group"]] } } if (is.null(benchmark_group_var) & is.null(benchmark_group_lut)) { stop("Either benchmark_group_var or benchmark_group_lut must not be NULL") } else if (!is.null(benchmark_group_var) & !is.null(benchmark_group_lut)) { if (verbose) { message("Both a benchmark variable and a benchmark group lookup table have been provided. Assuming that the benchmark_group_var is in the lookup table and will be applied to the data from there.") } if (!(benchmark_group_var) %in% names(benchmark_group_lut)) { stop(paste0("The variable ", benchmark_group_var, " does not appear in the names of benchmark_group_lut")) } } else if (!is.null(benchmark_group_var) & is.null(benchmark_group_lut)) { if (!(benchmark_group_var) %in% names(data)) { stop(paste0("The variable ", benchmark_group_var, " does not appear in the names of data. Did you mean to supply a lookup table as well?")) } } if (!is.null(benchmark_group_lut)) { common_vars_benchmarks <- names(table(c(names(benchmarks), names(benchmark_group_lut))))[table(c(names(benchmarks), names(benchmark_group_lut))) > 1] if (length(common_vars_benchmarks) < 1) { stop("There are no variables in common between benchmark_group_lut and benchmarks") } if (!is.null(benchmark_group_var)) { if (verbose) { message("Removing existing benchmark group variable from data to replace with values from lookup table.") } data <- data[, names(data)[!(names(data %in% benchmark_group_var))]] } common_vars <- names(table(c(names(data), names(benchmark_group_lut))))[table(c(names(data), names(benchmark_group_lut))) > 1] if (verbose) { message(paste0("Joining data and benchmark group lut by the variable(s): ", paste(common_vars, collapse = ", "))) } data_grouped <- merge(x = data, y = benchmark_group_lut, by = common_vars) } else { data_grouped <- data } if (verbose) { message("Applying benchmarks") } # Get the benchmarks merged to the points indicator_lut <- indicator.lookup() names(indicator_lut) <- c("indicator_var", "indicator_name") benchmarks <- merge(x = benchmarks, y = indicator_lut, by.x = "Indicator", by.y = "indicator_name") eval_vars <- names(benchmarks)[grepl(names(benchmarks), pattern = "^evalstring\\d+$")] idvars <- c(idvars, "Benchmark.Group") # Make the data tall if (!all(c("indicator", "value") %in% names(data_grouped))) { indicator_vars_present <- names(data_grouped)[names(data_grouped) %in% indicator_lut[["indicator_var"]]] data_tall <- tidyr::pivot_longer(data = data_grouped[, c(idvars, indicator_vars_present)], cols = tidyselect::one_of(indicator_vars_present), names_to = "indicator", values_to = "value") } else { data_tall <- data } data_benchmarked <- merge(x = data_tall, y = benchmarks, by.x = c("indicator", "Benchmark.Group", "Reporting.Unit"), by.y = c("indicator_var", "Benchmark.Group", "Reporting.Unit")) benchmark_vector <- sapply(X = 1:nrow(data_benchmarked), data = data_benchmarked, eval_vars = eval_vars, FUN = function(X, data, eval_vars){ all(sapply(X = eval_vars, data = data[X, ], FUN = function(X, data){ evalstring <- gsub(data[[X]][1], pattern = "(x){1}", replacement = data[["value"]]) eval(parse(text = evalstring)) })) }) output <- data_benchmarked[benchmark_vector, c(idvars, "indicator", "Condition.Category")] return(output) } #' Apply benchmarks to data #' @description Using data that has unique identifier and indicator value variables, apply benchmarks. The benchmarks are applied to the data based on the benchmark group(s) that the data belong to, which may already be assigned in the data or may be added with a benchmark group lookup table. #' @param data Data frame or spatial * data frame. The data to be benchmarked. Must contain the variable(s) in \code{idvars} as unique identifiers. May be "wide" or "long" data. If wide, then each indicator name should be a variable name. If long, then the indicator names and values should be in variables named \code{"indicator_var"} and \code{"value"}. #' @param idvars Character string or vecor of character strings. The names of the variable(s) in \code{data} which serve as unique identifiers. #' @param benchmark_group_var Optional character string. The name of the variable that holds the benchmark group memberships. If \code{NULL} then it defaults to the variable in \code{benchmark_group_lut} that is not in \code{idvars}. Defaults to \code{NULL}. #' @param benchmark_group_lut Optional data frame. The lookup table used to assign benchmark group membership to \code{data}. Must contain all of the variables in \code{idvar} and one additional variable with the benchmark group memberships. #' @param benchmarks Data frame. The benchmarks in the format produced by \code{read.benchmarks()}. If the benchmark group membership variable in other data frames is not \code{"Benchmark.Group"} then it must be renamed here. #' @param verbose Logical. If \code{TRUE} then the function will generate additional messages as it executes. #' @param tdat_version Version of TerrADat used in the analysis for use in \code{indicator lookup()}. Defaults to \code{"2"}. #' @return A long data frame of each point/benchmarked indicator combination with the assigned condition category. #' @export apply_benchmarks <- function(data, idvars, benchmark_group_var = NULL, benchmark_group_lut = NULL, benchmarks, verbose = FALSE, tdat_version = "2") { if (grepl(class(data)[1], pattern = "^Spatial.*DataFrame$")) { data <- data@data } else if (class(data) != "data.frame") { stop("data must either be a data frame or a spatial data frame.") } idvars <- c(idvars, benchmark_group_var) missing_idvars <- idvars[!(idvars %in% names(data))] if (length(missing_idvars) > 0) { stop(paste0("The following variables are missing from data: ", paste(missing_idvars, collapse = ", "))) } if (class(benchmarks) != "data.frame") { stop("Benchmarks must be a data frame.") } if (!is.null(benchmark_group_var)) { if (!(benchmark_group_var %in% names(benchmarks)) & !("Benchmark.Group" %in% names(benchmarks))) { stop(paste0("The variable ", benchmark_group_var, "does not appear in the data frame benchmarks")) } else { if (verbose) { message(paste0("Adding the contents of benchmarks[['Benchmark.Group']] to benchmarks[['", benchmark_group_var, "']]")) } benchmarks[[benchmark_group_var]] <- benchmarks[["Benchmark.Group"]] } } if (is.null(benchmark_group_var) & is.null(benchmark_group_lut)) { stop("Either benchmark_group_var or benchmark_group_lut must not be NULL") } else if (!is.null(benchmark_group_var) & !is.null(benchmark_group_lut)) { if (verbose) { message("Both a banchmark variable and a benchmark group lookup table have been provided. Assuming that the benchmark_group_var is in the lookup table and will be applied to the data from there.") } if (!(benchmark_group_var) %in% names(benchmark_group_lut)) { stop(paste0("The variable ", benchmark_group_var, " does not appear in the names of benchmark_group_lut")) } } else if (!is.null(benchmark_group_var) & is.null(benchmark_group_lut)) { if (!(benchmark_group_var) %in% names(data)) { stop(paste0("The variable ", benchmark_group_var, " does not appear in the names of data. Did you mean to supply a lookup table as well?")) } } if (!is.null(benchmark_group_lut)) { common_vars_benchmarks <- names(table(c(names(benchmarks), names(benchmark_group_lut))))[table(c(names(benchmarks), names(benchmark_group_lut))) > 1] if (length(common_vars_benchmarks) < 1) { stop("There are no variables in common between benchmark_group_lut and benchmarks") } if (!is.null(benchmark_group_var)) { if (verbose) { message("Removing existing benchmark group variable from data to replace with values from lookup table.") } data <- data[, names(data)[!(names(data %in% benchmark_group_var))]] } common_vars <- names(table(c(names(data), names(benchmark_group_lut))))[table(c(names(data), names(benchmark_group_lut))) > 1] if (verbose) { message(paste0("Joining data and benchmark group lut by the variable(s): ", paste(common_vars, collapse = ", "))) } data_grouped <- merge(x = data, y = benchmark_group_lut, by = common_vars) } else { data_grouped <- data } if (verbose) { message("Applying benchmarks") } # Get the benchmarks merged to the points indicator_lut <- indicator.lookup(tdat_version) names(indicator_lut) <- c("indicator_var", "indicator_name") benchmarks <- merge(x = benchmarks, y = indicator_lut, by.x = "Indicator", by.y = "indicator_name") eval_vars <- names(benchmarks)[grepl(names(benchmarks), pattern = "^evalstring\\d+$")] idvars <- c(idvars, "Benchmark.Group") # Make the data tall if (!all(c("indicator", "value") %in% names(data_grouped))) { indicator_vars_present <- names(data_grouped)[names(data_grouped) %in% indicator_lut[["indicator_var"]]] data_tall <- tidyr::pivot_longer(data = data_grouped[, c(idvars, indicator_vars_present)], cols = tidyselect::one_of(indicator_vars_present), names_to = "indicator", values_to = "value") } else { data_tall <- data } data_benchmarked <- merge(x = data_tall, y = benchmarks, by.x = c("indicator", "Benchmark.Group", "Reporting.Unit"), by.y = c("indicator_var", "Benchmark.Group", "Reporting.Unit")) benchmark_vector <- sapply(X = 1:nrow(data_benchmarked), data = data_benchmarked, eval_vars = eval_vars, FUN = function(X, data, eval_vars){ all(sapply(X = eval_vars, data = data[X, ], FUN = function(X, data){ evalstring <- gsub(data[[X]][1], pattern = "(x){1}", replacement = data[["value"]]) eval(parse(text = evalstring)) })) }) output <- data_benchmarked[benchmark_vector, c(idvars, "indicator", "Condition.Category")] return(output) }
14,838
mit
704c733d011782b8795068569284f0400ecc1e5b
aknight1-uva/jasp-desktop
JASP-Engine/JASP/R/ttestpairedsamples.R
# # Copyright (C) 2013-2015 University of Amsterdam # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # TTestPairedSamples <- function(dataset = NULL, options, perform = "run", callback = function(...) 0, ...) { state <- .retrieveState() ## call the common initialization function init <- .initializeTTest(dataset, options, perform, type = 'paired') results <- init[["results"]] dataset <- init[["dataset"]] ## call the specific paired T-Test functions results[["ttest"]] <- .ttestPairedSamples(dataset, options, perform) descriptivesTable <- .ttestPairedSamplesDescriptives(dataset, options, perform) shapiroWilk <- .ttestPairedNormalityTest(dataset, options, perform) results[["assumptionChecks"]] <- list(shapiroWilk = shapiroWilk, title = "Assumption Checks") keep <- NULL ## if the user wants descriptive plots, s/he shall get them! if (options$descriptivesPlots) { plotTitle <- ifelse(length(options$pairs) > 1, "Descriptives Plots", "Descriptives Plot") descriptivesPlots <- .pairedSamplesTTestDescriptivesPlot(dataset, options, perform) if (!is.null(descriptivesPlots[[1]][["obj"]])){ keep <- unlist(lapply(descriptivesPlots, function(x) x[["data"]]),NULL) } results[["descriptives"]] <- list(descriptivesTable = descriptivesTable, title = "Descriptives", descriptivesPlots = list(collection = descriptivesPlots, title = plotTitle)) } else { results[["descriptives"]] <- list(descriptivesTable = descriptivesTable, title = "Descriptives") } ## return the results object if (perform == "init") { return(list(results=results, status="inited")) } else { return(list(results=results, status="complete", state = list(options = options, results = results), keep = keep)) } } .ttestPairedSamples <- function(dataset, options, perform) { ttest <- list() ## what does the user want? what does s/he really want?? wantsEffect <- options$effectSize wantsDifference <- options$meanDifference wantsConfidenceMeanDiff <- (options$meanDiffConfidenceIntervalCheckbox && options$meanDifference) wantsConfidenceEffSize <- (options$effSizeConfidenceIntervalCheckbox && options$effectSize) percentConfidenceMeanDiff <- options$meanDiffConfidenceIntervalPercent percentConfidenceEffSize <- options$effSizeConfidenceIntervalPercent wantsStudents <- options$students wantsWilcox <- options$wilcoxonSignedRank allTests <- c(wantsStudents, wantsWilcox) onlyTest <- sum(allTests) == 1 ## setup table for paired t-test results fields <- list(list(name = "v1", type = "string", title = ""), list(name = "sep", type = "separator", title = ""), list(name = "v2", type = "string", title = ""), list(name = "df", type = "integer"), list(name = "p", type = "number", format = "dp:3;p:.001")) footnotes <- .newFootnotes() title <- "Paired Samples T-Test" ## get the right statistics for the table and, if only one test type, add footnote if (wantsWilcox && onlyTest) { testname <- "Wilcoxon signed-rank test" testTypeFootnote <- paste0(testname, ".") .addFootnote(footnotes, symbol = "<em>Note.</em>", text = testTypeFootnote) testStat <- "W" ## additionally, Wilcoxon's test doesn't have degrees of freedoms fields <- fields[-4] nameOfLocationParameter <- "Hodges-Lehmann Estimate" nameOfEffectSize <- "Rank-Biserial Correlation" } else if (wantsStudents && onlyTest) { testname <- "Student's t-test" testTypeFootnote <- paste0(testname, ".") .addFootnote(footnotes, symbol = "<em>Note.</em>", text = testTypeFootnote) testStat <- "t" nameOfLocationParameter <- "Mean Difference" nameOfEffectSize <- "Cohen's d" } else { testStat <- "Statistic" nameOfLocationParameter <- "Location Parameter" nameOfEffectSize <- "Effect Size" } ttest[["title"]] <- title ## if only conducting Student's, the table should have "t" as column name ## for the test statistic when doing only Wilcoxon's, the name should be "V"; ## when doing both, it should be "statistic" fields <- append(fields, list(list(name = testStat, type = "number", format = "sf:4;dp:3")), 3) ## if the user wants all tests, add a column called "Test" if (sum(allTests) == 2) { fields <- append(fields, list(list(name = "test", type = "string", title = "Test")), 3) } if (options$VovkSellkeMPR) { .addFootnote(footnotes, symbol = "\u002A", text = "Vovk-Sellke Maximum <em>p</em>-Ratio: Based on the <em>p</em>-value, the maximum possible odds in favor of H\u2081 over H\u2080 equals 1/(-e <em>p</em> log(<em>p</em>)) for <em>p</em> \u2264 .37 (Sellke, Bayarri, & Berger, 2001).") fields[[length(fields) + 1]] <- list(name = "VovkSellkeMPR", title = "VS-MPR\u002A", type = "number", format = "sf:4;dp:3") } if (wantsDifference) { fields[[length(fields) + 1]] <- list(name = "md", title = nameOfLocationParameter, type = "number", format = "sf:4;dp:3") if(wantsStudents) { fields[[length(fields) + 1]] <- list(name = "sed", title = "SE Difference", type = "number", format = "sf:4;dp:3") } if (wantsWilcox && wantsStudents) { .addFootnote(footnotes, symbol = "<em>Note.</em>", text = "For the Student t-test, location parameter is given by mean difference <em>d</em>; for the Wilcoxon test, effect size is given by the Hodges-Lehmann estimate.") } } if (wantsConfidenceMeanDiff) { interval <- 100 * percentConfidenceMeanDiff title <- paste0(interval, "% CI for ", nameOfLocationParameter) fields[[length(fields) + 1]] <- list(name = "lowerCIlocationParameter", type = "number", format = "sf:4;dp:3", title = "Lower", overTitle = title) fields[[length(fields) + 1]] <- list(name = "upperCIlocationParameter", type = "number", format = "sf:4;dp:3", title = "Upper", overTitle = title) } if (wantsEffect) { fields[[length(fields) + 1]] <- list(name = "d", title = nameOfEffectSize, type = "number", format = "sf:4;dp:3") if (wantsWilcox && wantsStudents) { .addFootnote(footnotes, symbol = "<em>Note.</em>", text = "For the Student t-test, effect size is given by Cohen's <em>d</em>; for the Wilcoxon test, effect size is given by the matched rank biserial correlation.") } } if (wantsConfidenceEffSize) { interval <- 100 * percentConfidenceEffSize title <- paste0(interval, "% CI for ", nameOfEffectSize) fields[[length(fields) + 1]] <- list(name = "lowerCIeffectSize", type = "number", format = "sf:4;dp:3", title = "Lower", overTitle = title) fields[[length(fields) + 1]] <- list(name = "upperCIeffectSize", type = "number", format = "sf:4;dp:3", title = "Upper", overTitle = title) } ttest[["schema"]] <- list(fields = fields) ######################### ## check the directionality if (options$hypothesis == "groupOneGreater") { direction <- "greater" message <- "All tests, hypothesis is measurement one greater than measurement two." .addFootnote(footnotes, symbol = "<em>Note.</em>", text = message) } else if (options$hypothesis == "groupTwoGreater") { direction <- "less" message <- "All tests, hypothesis is measurement one less than measurement two." .addFootnote(footnotes, symbol = "<em>Note.</em>", text = message) } else { direction <- "two.sided" } rowNo <- 1 ttest.rows <- list() # for each pair and each test, save stuff in there whichTests <- list("1" = wantsStudents, "2" = wantsWilcox) ## add a row for each variable, even before we are conducting tests for (pair in options$pairs) { ttest.rows[[length(ttest.rows) + 1]] <- list(v1 = pair[[1]], sep = '-', v2 = pair[[2]]) } ## for each pair, run the checked tests and update the table for (pair in options$pairs) { p1 <- pair[[1]] p2 <- pair[[2]] errors <- .hasErrors(dataset, perform, message = 'short', type = c('observations', 'variance', 'infinity'), all.target = c(p1, p2), observations.amount = '< 2') row <- list(v1 = "", sep = "", v2 = "") ## test is a number, indicating which tests should be run for (test in seq_len(length(whichTests))) { currentTest <- whichTests[[test]] ## don't run a test the user doesn't want if (!currentTest) { next } if (!identical(errors, FALSE)) { errorMessage <- errors$message } else { errorMessage <- NULL } if (perform == "run") { row.footnotes <- NULL if (p1 != "" && p2 != "") { c1 <- dataset[[ .v(p1) ]] c2 <- dataset[[ .v(p2) ]] df <- na.omit(data.frame(c1 = c1, c2 = c2)) c1 <- df$c1 c2 <- df$c2 n <- length(c1) if(is.null(errorMessage)){ result <- try(silent = FALSE, expr = { ## if Wilcox box is ticked, run a paired wilcoxon signed rank test if (test == 2) { res <- stats::wilcox.test(c1, c2, paired = TRUE, conf.level = percentConfidenceMeanDiff, conf.int = TRUE, alternative = direction) maxw <- (n*(n+1))/2 d <- as.numeric((res$statistic/maxw) * 2 - 1) wSE <- sqrt((n*(n+1)*(2*n+1))/6) /2 mrSE <- sqrt(wSE^2 * 4 * (1/maxw^2)) # zSign <- (ww$statistic - ((n*(n+1))/4))/wSE zmbiss <- atanh(d) d <- .clean(d) if(direction == "two.sided") { confIntEffSize <- sort(c(tanh(zmbiss + qnorm((1-percentConfidenceEffSize)/2)*mrSE), tanh(zmbiss + qnorm((1+percentConfidenceEffSize)/2)*mrSE))) }else if (direction == "less") { confIntEffSize <- sort(c(-Inf, tanh(zmbiss + qnorm(percentConfidenceEffSize)*mrSE))) }else if (direction == "greater") { confIntEffSize <- sort(c(tanh(zmbiss + qnorm((1-percentConfidenceEffSize))*mrSE), Inf)) } ## else run a simple paired t-test } else { res <- stats::t.test(c1, c2, paired = TRUE, conf.level = percentConfidenceMeanDiff, alternative = direction) df <- ifelse(is.null(res$parameter), "", as.numeric(res$parameter)) d <- .clean(mean(c1 - c2) / sd(c1 - c2)) t <- as.numeric(res$statistic) confIntEffSize <- c(0,0) if (wantsConfidenceEffSize) { signT <- sign(t) t <- abs(t) if(direction == "two.sided") { end1 <- t while( pt(q=t,df=df,ncp=end1) > (1-percentConfidenceEffSize)/2 ) { end1 <- end1 + abs(end1) } ncp1 <- uniroot(function(x) (1-percentConfidenceEffSize)/2-pt(q=t,df=df,ncp=x), c(2*t-end1,end1))$root end2 <- t while( pt(q=t,df=df,ncp=end2) < (1+percentConfidenceEffSize)/2 ) { end2 <- end2 - abs(t) } ncp2 <- uniroot(function(x) (1+percentConfidenceEffSize)/2-pt(q=t,df=df,ncp=x), c(end2,2*t-end2))$root confIntEffSize <- sort(c(ncp1/sqrt(df)* signT,ncp2/sqrt(df)* signT)) } else if (direction == "greater") { end1 <- t while( pt(q=t,df=df,ncp=end1) > (1-percentConfidenceEffSize) ) { end1 <- end1 + abs(end1) } ncp1 <- uniroot(function(x) (1-percentConfidenceEffSize)-pt(q=t,df=df,ncp=x), c(2*t-end1,end1))$root confIntEffSize <- sort(c(ncp1/sqrt(df)* signT, Inf)) }else if(direction == "less") { end2 <- t while( pt(q=t,df=df,ncp=end2) < percentConfidenceEffSize ) { end2 <- end2 - abs(t) } ncp2 <- uniroot(function(x) percentConfidenceEffSize-pt(q=t,df=df,ncp=x), c(end2,2*t-end2))$root confIntEffSize <- sort(c(ncp2/sqrt(df)* signT, -Inf)) } t <- t * signT } } ## don't use a return statement in expressions ## ... it will take ages to debug :) res }) ## if testing raised an error, we extract information from it if (class(result) != "try-error") { ## same for all tests p <- as.numeric(result$p.value) stat <- .clean(as.numeric(result$statistic)) sed <- .clean(sd(c1 - c2) / sqrt(length(c1))) # num <- sqrt(sd(c1)^2 + sd(c2)^2 - 2 * cov(c1, c2)) # d <- .clean(mean(c1) - mean(c2) / num) m <- as.numeric(result$estimate) ciLow <- ifelse(direction == "less", .clean(-Inf), as.numeric(result$conf.int[1])) ciUp <- ifelse(direction == "greater", .clean(Inf), as.numeric(result$conf.int[2])) ciLowEffSize = .clean(as.numeric(confIntEffSize[1])) ciUpEffSize = .clean(as.numeric(confIntEffSize[2])) ## paired t-test has it, wilcox doesn't! df <- ifelse(is.null(result$parameter), "", as.numeric(result$parameter)) sed <- ifelse(is.null(result$parameter), "", sed) # add things to the intermediate results object row <- list(df = df, p = p, md = m, d = d, lowerCIlocationParameter = ciLow, upperCIlocationParameter = ciUp, lowerCIeffectSize = ciLowEffSize, upperCIeffectSize = ciUpEffSize, sed = sed, .footnotes = row.footnotes) if (options$VovkSellkeMPR){ row[["VovkSellkeMPR"]] <- .VovkSellkeMPR(p) } row[[testStat]] <- stat ## however, if there has been an error ## find out which and log it as a footnote } else if (isTryError(result)) { errorMessage <- .extractErrorMessage(result) } } if (!is.null(errorMessage)){ index <- .addFootnote(footnotes, errorMessage) row.footnotes <- list(t = list(index)) ## since an error occured, we could not extract information row <- list(df = "", p = "", md = "", d = "", lowerCI = "", upperCI = "", sed = "", .footnotes = row.footnotes) row[[testStat]] <- .clean(NaN) } } else { ## if p1 or p2 are undefined (empty string), also show an empty table row <- list(df = "", p = "", md = "", d = "", lowerCI = "", upperCI = "", sed = "") row[[testStat]] <- "" } } ## if this is the first test / row for specific variables, add variable names ## since we have only two tests, the first test always will be an odd number isFirst <- (rowNo %% 2 == 1 && sum(allTests) == 2) || (sum(allTests) == 1) row[["v1"]] <- ifelse(isFirst, p1, "") row[["sep"]] <- ifelse(isFirst, "-", "") row[["v2"]] <- ifelse(isFirst, p2, "") ## if the user wants both tests, change the columns such that there is ## one called "Test" and "statistic" to differentiate Student's from Wilcoxon if (!isFirst) { row[["test"]] <- "Wilcoxon" ttest.rows[[rowNo - 1]][["test"]] <- "Student" } ttest.rows[[rowNo]] <- row rowNo <- rowNo + 1 } } ## if no test was conducted if (length(ttest.rows) == 0) { ttest.rows[[1]] <- list() } ttest[["data"]] <- ttest.rows ttest[["footnotes"]] <- as.list(footnotes) ttest } .ttestPairedSamplesDescriptives <- function(dataset, options, perform) { if (!options$descriptives) return(NULL) descriptives <- list(title = "Descriptives") fields <- list( list(name = "v", title = "", type = "string"), list(name = "N", type = "integer"), list(name = "mean", title = "Mean", type = "number", format = "sf:4;dp:3"), list(name = "sd", title = "SD", type = "number", format = "sf:4;dp:3"), list(name = "se", title = "SE", type = "number", format = "sf:4;dp:3") ) descriptives[["schema"]] <- list(fields = fields) descriptives.results <- list() desc.vars <- unique(unlist(options$pairs)) desc.vars <- desc.vars[desc.vars != ""] for (var in desc.vars) { row <- list(v = var) if (perform == "run") { dat <- na.omit(dataset[[ .v(var) ]]) n <- .clean(as.numeric(length(dat))) m <- .clean(as.numeric(mean(dat, na.rm = TRUE))) std <- .clean(as.numeric(sd(dat, na.rm = TRUE))) if (is.numeric(std)) { se <- .clean(as.numeric(std/sqrt(n))) } else { se <- .clean(NaN) } row[["N"]] <- n row[["mean"]] <- m row[["sd"]] <- std row[["se"]] <- se } descriptives.results[[length(descriptives.results) + 1]] <- row } descriptives[["data"]] <- descriptives.results descriptives } .ttestPairedNormalityTest <- function(dataset, options, perform) { if (!options$normalityTests) return(NULL) normalityTests <- list(title = "Test of Normality (Shapiro-Wilk)") normalityTests[["cases"]] <- I(options$variables) fields <- list( list(name = "v1", type = "string", title = ""), list(name = "sep", type = "separator", title = ""), list(name = "v2", type = "string", title = ""), list(name = "W", title = "W", type = "number", format = "sf:4;dp:3"), list(name = "p", title = "p", type = "number", format = "dp:3;p:.001") ) normalityTests[["schema"]] <- list(fields = fields) footnotes <- .newFootnotes() normalityTests.results <- list() .addFootnote(footnotes, symbol = "<em>Note.</em>", text = "Significant results suggest a deviation from normality.") pairs <- options$pairs if (length(pairs) == 0) { pairs[[1]] <- list(".", ".") } for (pair in pairs) { p1 <- pair[[1]] p2 <- pair[[2]] if (perform == "run" && length(options$pairs) > 0 && p1 != p2) { c1 <- dataset[[ .v(p1) ]] c2 <- dataset[[ .v(p2) ]] data <- na.omit(c1 - c2) row.footnotes <- NULL error <- FALSE errors <- .hasErrors(dataset, perform, message = 'short', type = c('observations', 'variance', 'infinity'), all.target = c(p1, p2), observations.amount = c('< 3', '> 5000')) if (!identical(errors, FALSE)) { errorMessage <- errors$message foot.index <- .addFootnote(footnotes, errorMessage) row.footnotes <- list(W = list(foot.index), p = list(foot.index)) error <- TRUE } if (!error) { r <- stats::shapiro.test(data) W <- .clean(as.numeric(r$statistic)) p <- .clean(r$p.value) newGroup <- length(normalityTests.results) == 0 result <- list(v1 = p1, sep = "-", v2 = p2, W = W, p = p, .isNewGroup = newGroup) } else { newGroup <- length(normalityTests.results) == 0 result <- list(v1 = p1, sep = "-", v2 = p2, W = "NaN", p = "NaN", .isNewGroup = newGroup, .footnotes = row.footnotes) } } else { newGroup <- length(normalityTests.results) == 0 result <- list(v1 = p1, sep = "-", v2 = p2, W = ".", p = ".", .isNewGroup = newGroup) } normalityTests.results[[length(normalityTests.results) + 1]] <- result } normalityTests[["data"]] <- normalityTests.results normalityTests[["footnotes"]] <- as.list(footnotes) normalityTests } .pairedSamplesTTestDescriptivesPlot <- function(dataset, options, perform) { if (!options$descriptivesPlots) return(NULL) descriptivesPlotList <- list() base_breaks_x <- function(x) { b <- unique(as.numeric(x)) d <- data.frame(y = -Inf, yend = -Inf, x = min(b), xend = max(b)) list(ggplot2::geom_segment(data = d, ggplot2::aes(x = x, y = y, xend = xend, yend = yend), inherit.aes = FALSE, size = 1)) } base_breaks_y <- function(x) { ci.pos <- c(x[, "dependent"] - x[, "ci"], x[, "dependent"] + x[, "ci"]) b <- pretty(ci.pos) d <- data.frame(x = -Inf, xend = -Inf, y = min(b), yend = max(b)) list(ggplot2::geom_segment(data = d, ggplot2::aes(x = x, y = y, xend = xend, yend = yend), inherit.aes = FALSE, size = 1), ggplot2::scale_y_continuous(breaks = c(min(b), max(b)))) } for (i in .indices(options$pairs)) { pair <- options$pairs[[i]] descriptivesPlot <- list(title = paste(pair, collapse=" - ")) descriptivesPlot[["width"]] <- options$plotWidth descriptivesPlot[["height"]] <- options$plotHeight descriptivesPlot[["custom"]] <- list(width = "plotWidth", height = "plotHeight") if (perform == "run" && pair[[1]] != "" && pair[[2]] != "") { c1 <- dataset[[ .v(pair[[1]]) ]] c2 <- dataset[[ .v(pair[[2]]) ]] ### errors <- .hasErrors(dataset, perform, message = 'short', type = c('observations', 'variance', 'infinity'), all.target = c(pair[[1]], pair[[2]]), observations.amount = '< 2') if (!identical(errors, FALSE)) { errorMessage <- errors$message descriptivesPlot[["data"]] <- "" descriptivesPlot[["error"]] <- list(error="badData", errorMessage=errorMessage) } else { #### data <- data.frame(id = rep(1:length(c1), 2), dependent = c(c1, c2), groupingVariable = c(rep(paste("1.", pair[[1]], sep = ""), length(c1)), rep(paste("2.", pair[[2]], sep = ""), length(c2)))) summaryStat <- .summarySEwithin(data, measurevar = "dependent", withinvars = "groupingVariable", idvar = "id", conf.interval = options$descriptivesPlotsConfidenceInterval, na.rm = TRUE, .drop = FALSE) pd <- ggplot2::position_dodge(0.2) p <- ggplot2::ggplot(summaryStat, ggplot2::aes(x = groupingVariable, y = dependent, group = 1)) + ggplot2::geom_errorbar(ggplot2::aes(ymin = ciLower, ymax = ciUpper), colour = "black", width = 0.2, position = pd) + ggplot2::geom_line(position = pd, size = 0.7) + ggplot2::geom_point(position = pd, size = 4) + ggplot2::ylab(NULL) + ggplot2::xlab(NULL) + ggplot2::theme_bw() + ggplot2::theme(panel.grid.minor = ggplot2::element_blank(), plot.title = ggplot2::element_text(size = 18), panel.grid.major = ggplot2::element_blank(), axis.title.x = ggplot2::element_text(size = 18, vjust = -0.2), axis.title.y = ggplot2::element_text(size = 18, vjust = -1), axis.text.x = ggplot2::element_text(size = 15), axis.text.y = ggplot2::element_text(size = 15), panel.background = ggplot2::element_rect(fill = "transparent", colour = NA), plot.background = ggplot2::element_rect(fill = "transparent", colour = NA), legend.background = ggplot2::element_rect(fill = "transparent", colour = NA), panel.border = ggplot2::element_blank(), axis.line = ggplot2::element_blank(), legend.key = ggplot2::element_blank(), legend.title = ggplot2::element_text(size = 12), legend.text = ggplot2::element_text(size = 12), axis.ticks = ggplot2::element_line(size = 0.5), axis.ticks.margin = grid::unit(1, "mm"), axis.ticks.length = grid::unit(3, "mm"), plot.margin = grid::unit(c(0.5, 0, 0.5, 0.5), "cm")) + base_breaks_y(summaryStat) + base_breaks_x(summaryStat$groupingVariable) + ggplot2::scale_x_discrete(labels = c(pair[[1]], pair[[2]])) imgObj <- .writeImage(width = options$plotWidth, height = options$plotHeight, plot = p) descriptivesPlot[["data"]] <- imgObj[["png"]] descriptivesPlot[["obj"]] <- imgObj[["obj"]] } descriptivesPlot[["convertible"]] <- TRUE descriptivesPlot[["status"]] <- "complete" } descriptivesPlotList[[i]] <- descriptivesPlot } descriptivesPlotList }
23,983
agpl-3.0
14b18753e84ef8cd9c34e7260ca947fed24fcb54
gxa/gxa
atlas-loader/src/main/resources/R/htsProcessPipeline.R
esetToTextFile = function(infname, outfname) { require(Biobase) objnames = load(infname); expressions = exprs(get(objnames[1])); dimensionnames = dimnames(expressions); write(c("scanref", dimensionnames$sample), file = outfname, ncolumns = length(dimensionnames$sample) + 1, sep = "\t"); write.table(expressions, file = outfname, sep = "\t", quote = FALSE, row.names = TRUE, col.names = FALSE, append = TRUE) }
456
apache-2.0
e0041886b136b25aa50aa3b65c921f6b1f188d06
cran/TIMP
R/calcD.R
"calcD" <- function (kincoeffs, times, cstart, rsmatrix, smatrix) { ## contributed by David Nicolaides <dnicolaides@accelrys.com> ## in modified form, along with other options for 2nd order modeling ns <- length(cstart) np <- length(kincoeffs) ## we need to pass our kinetic model the stoichiometry matrices, ## as well as the kinetic coefficients parms <- c(rsmatrix, smatrix, kincoeffs, ns, np) Model <- function(times, conc, parms) { ## get s-matrices as matrices first rsm <- rsmatrix dim(rsm) <- c(ns, np) rsm <- t(rsm) sm <- smatrix dim(sm) <- c(ns, np) sm <- t(sm) ## now calculate the nu vectors nu <- rep(0,np) ## Note: R correctly handles 0^0 (= 1) for (j in 1:np) { nu[j] <- kincoeffs[j]*prod(conc^rsm[j,]) } ## then calculate the sums over the nu variables to get the derivatives result <- rep(0,ns) for (j in 1:np) { result <- result + sm[j,]*nu[j] } list(result) } c.temp <- lsoda(y=cstart,times=times,func=Model,parms=parms) c.temp <- c.temp[,-1] colnames(c.temp) <- vector() c.temp }
1,159
gpl-2.0
4bd8d8dcd35daf0c16b9ce1329f6dddf4897c75e
princelab/metriculator
r_install.R
#!/usr/bin/env Rscript install.packages('Rserve') install.packages('beanplot')
79
mit
0e2fdf2b6c3198ad5c9e73d1ee388bb1af073aa4
lmweber/cytometry-clustering-comparison
run_methods/run_SWIFT.R
# How to run SWIFT # Not available in R, so follow steps below instead: # Requires: Matlab, Statistics Toolbox, Parallel Computing Toolbox # 1. Copy FCS file into a temporary directory; results files will be saved in the same # directory. # 2. Run SWIFT graphical interface from Matlab by typing "swift_main" in command window. # 3. After graphical interface opens, select FCS file to import data. Note that SWIFT # will automatically perform an arcsinh transform, so the FCS file should not be # transformed already. # 4. Enter parameters and click to continue. # 5. After SWIFT completes, cluster labels will be saved in the file # "<original_filename>.Cluster_Output.txt" in the input directory. Cluster labels are in # the "MergeCluster" column. ################### ### SUBSAMPLING ### ################### # SWIFT requires subsampling for some data sets due to runtime. Use code below to # subsample and save true population labels. # note: use non-transformed data files library(flowCore) # load data DATA_DIR <- "../../../benchmark_data_sets" files <- list( Levine_32dim = file.path(DATA_DIR, "Levine_32dim/data/Levine_32dim_notransform.fcs"), Levine_13dim = file.path(DATA_DIR, "Levine_13dim/data/Levine_13dim_notransform.fcs"), Samusik_01 = file.path(DATA_DIR, "Samusik/data/Samusik_01_notransform.fcs"), Samusik_all = file.path(DATA_DIR, "Samusik/data/Samusik_all_notransform.fcs"), Nilsson_rare = file.path(DATA_DIR, "Nilsson_rare/data/Nilsson_rare_notransform.fcs"), Mosmann_rare = file.path(DATA_DIR, "Mosmann_rare/data/Mosmann_rare_notransform.fcs"), FlowCAP_ND = file.path(DATA_DIR, "FlowCAP_ND/data/FlowCAP_ND.fcs"), FlowCAP_WNV = file.path(DATA_DIR, "FlowCAP_WNV/data/FlowCAP_WNV.fcs") ) is_FlowCAP <- c(FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE) data <- vector("list", length(files)) names(data) <- names(files) for (i in 1:length(data)) { f <- files[[i]] if (!is_FlowCAP[i]) { data[[i]] <- flowCore::exprs(flowCore::read.FCS(f, transformation = FALSE, truncate_max_range = FALSE)) } else { smp <- flowCore::exprs(flowCore::read.FCS(f, transformation = FALSE, truncate_max_range = FALSE)) smp <- smp[, "sample"] d <- flowCore::read.FCS(f, transformation = FALSE, truncate_max_range = FALSE) d <- flowCore::split(d, smp) data[[i]] <- lapply(d, function(s) flowCore::exprs(s)) } } # subsampling for data sets with excessive runtime (> 6 hrs on laptop) ix_subsample <- c(1, 4) n_sub <- c(100000, NA, NA, 100000, NA, NA) for (i in ix_subsample) { if (!is_FlowCAP[i]) { set.seed(123) data[[i]] <- data[[i]][sample(1:nrow(data[[i]]), n_sub[i]), ] # save subsampled data sets in FCS format with population labels files_sub_i <- paste0("../../results/auto/SWIFT/", names(data)[i], "_notransform_subsampled.fcs") flowCore::write.FCS(flowCore::flowFrame(data[[i]]), filename = files_sub_i) } } ############################################## ### FIX ERROR FOR FLOW CYTOMETRY DATA SETS ### ############################################## # Some of the non-marker columns (forward scatter etc) included in the flow cytometry # data sets (Nilsson_rare, Mosmann_rare) appear to cause an error while trying to load # the data into SWIFT. To fix this, save data sets containing marker columns only. # indices of protein marker columns marker_cols <- list( Levine_32dim = 5:36, Levine_13dim = 1:13, Samusik_01 = 9:47, Samusik_all = 9:47, Nilsson_rare = c(5:7, 9:18), Mosmann_rare = c(7:9, 11:21), FlowCAP_ND = 3:12, FlowCAP_WNV = 3:8 ) sapply(marker_cols, length) # subset and save data files: protein marker columns only for (i in c(5, 6)) { data[[i]] <- data[[i]][, marker_cols[[i]]] files_i <- paste0("../../results/auto/SWIFT/", names(data)[i], "_notransform_markers_only.fcs") flowCore::write.FCS(flowCore::flowFrame(data[[i]]), filename = files_i) }
3,932
mit
9fcb746f0e3e27fef594eb7ac1fee2254d8d5f0e
nxdao2000/pis2
tests/ou2-is2.R
library(pis2) library(coda) library(lattice) pompExample(ou2) Nmcmc<-100 NP<-1000 dprior.ou2 <- function (params, log, ...) { f <- sum(dunif(params,min=coef(ou2)-1,max=coef(ou2)+1,log=TRUE)) if (log) f else exp(f) } p.truth <- coef(ou2) guess2 <- guess1 <- p.truth guess1[c('x1.0','x2.0','alpha.2','alpha.3')] <- 0.8*guess1[c('x1.0','x2.0','alpha.2','alpha.3')] set.seed(123) f1 <- pmcmc( pomp(ou2,dprior=dprior.ou2), start=guess1, Nmcmc=Nmcmc, rw.sd=c(alpha.2=0.02,alpha.3=0.02), Np=NP, max.fail=100, verbose=FALSE ) set.seed(123) f2 <- pmif( pomp(ou2,dprior=dprior.ou2), start=guess1, Nmcmc=Nmcmc, rw.sd=c(alpha.2=0.02,alpha.3=0.02), Np=NP, cooling.type="geometric", cooling.factor=1, method="pmif", lag=0, max.fail=100, verbose=FALSE ) set.seed(123) f3 <- pmif2( pomp(ou2,dprior=dprior.ou2), start=guess1, Nmcmc=Nmcmc, rw.sd=c(alpha.2=0.02,alpha.3=0.02), Np=NP, cooling.type="geometric", cooling.factor=1, method="pmif2", ic.lag=100, var.factor=1, lag=0, max.fail=100, verbose=FALSE ) set.seed(123) f4 <- pmif3( pomp(ou2,dprior=dprior.ou2), start=guess1, Nmcmc=Nmcmc, rw.sd=c(alpha.2=0.02,alpha.3=0.02), Np=NP, cooling.type="geometric", cooling.factor=1, method="pmif3", ic.lag=100, var.factor=1, lag=1, max.fail=100, verbose=FALSE ) set.seed(123) f5 <- pmif4( pomp(ou2,dprior=dprior.ou2), start=guess1, Nmcmc=Nmcmc, rw.sd=c(alpha.2=0.02,alpha.3=0.02), Np=NP, cooling.type="geometric", cooling.factor=1, method="pmif4", ic.lag=100, var.factor=1, lag=1, max.fail=100, verbose=FALSE ) pdf(file="ou2-pmcmc.pdf") result<-mcmc.list(coda::mcmc(conv.rec(f1))[,c("alpha.3","alpha.2","loglik")],coda::mcmc(conv.rec(f2))[,c("alpha.3","alpha.2","loglik")],coda::mcmc(conv.rec(f3))[,c("alpha.3","alpha.2","loglik")],coda::mcmc(conv.rec(f4))[,c("alpha.3","alpha.2","loglik")],coda::mcmc(conv.rec(f5))[,c("alpha.3","alpha.2","loglik")]) save( result, file="ou2-10000.rda",compress='xz') plot(conv.rec(f1,c("alpha.2","alpha.3","loglik"))) plot(conv.rec(f2,c("alpha.2","alpha.3","loglik"))) plot(conv.rec(f3,c("alpha.2","alpha.3","loglik"))) plot(conv.rec(f4,c("alpha.2","alpha.3","loglik"))) plot(conv.rec(f5,c("alpha.2","alpha.3","loglik"))) dev.off() pdf(file="ou2-pmcmc1.pdf") result<-mcmc.list(coda::mcmc(conv.rec(f1))[,c("alpha.3","alpha.2","loglik")],coda::mcmc(conv.rec(f2))[,c("alpha.3","alpha.2","loglik")],coda::mcmc(conv.rec(f3))[,c("alpha.3","alpha.2","loglik")],coda::mcmc(conv.rec(f4))[,c("alpha.3","alpha.2","loglik")],coda::mcmc(conv.rec(f5))[,c("alpha.3","alpha.2","loglik")]) xyplot(result) densityplot(result) qqmath(result, start = (Nmcmc/2)) acfplot(result) plot(result, trace = TRUE, density = TRUE, smooth = FALSE, auto.layout = TRUE) dev.off()
2,890
gpl-2.0
008c415357f23b8897440b22f687b7b9f4a92d57
michathoma/flywalkr
R/response_per_pulse.R
#' Calculate mean net displacement per odor pulse. #' #' Calculate mean response per odor pulse in a given experiment. Can be used to check data for adaptation/habituation effects. #' Response is defined as the net displacement within 4s after odor encounter. #' #' @param object a \code{data.frame} as produced by \code{read.esm} #' @return a \code{data.frame} #' @export response_per_pulse<-function(object){ data.short <- data.frame(cbind(object[, 1:3], object[, 104:144])) data.clean <- data.short[!apply(is.na(data.short), 1, any),] after <- apply(data.clean[, 4:44], 1, sum, na.rm = T) after <- (-0.1 * after) resp.frame <- data.frame(cbind(data.clean[, 1:3], after)) testframe <- data.frame() for (i in 1:dim(resp.frame)[1]){ flypulse <- subset(resp.frame, pulse == resp.frame$pulse[i] & odour == resp.frame$odour[i]) n <- dim(flypulse)[1] test.frame <- data.frame(flypulse[1, 2], flypulse[1, 3], n, mean(flypulse$after)) testframe <- rbind(testframe, test.frame) testframe <- unique(testframe) } colnames(testframe) <- c("odor", "pulse", "n", "response") write.table(testframe, file = "responses", sep = ",", row.names = F) return(testframe) }
1,199
mit
77665e3c0fabf04e9bf97bb0925b498a6272ed26
aWhereAPI/aWhere-R-Library
R/grid-functions.R
#' Get aWhere GridX from longitude coordinate(s) #' #' #' @param longitude one more more longitude coordinates #' #' @return A vector of GridX values #' #' @examples getGridX(-90) #' getGridX <- function(longitude) { MaxLon <- 180 MinLon <- -180 MaxGridX <- 2160 MinGridX <- -2160 gridX <- (longitude / ((MaxLon - MinLon) / 2)) * ((MaxGridX - MinGridX) / 2) gridX[which(gridX > 0)] <- ceiling(gridX[which(gridX > 0)]) gridX[which(gridX < 0)] <- floor(gridX[which(gridX < 0)]) return (gridX) } #' Get aWhere GridY from latitude coordinate(s) #' #' #' @param latitude one or more latitudes coordinates #' #' @return A vector of GridY values #' #' @examples getGridY(-90) #' getGridY <- function(latitude) { MaxLat <- 90 MinLat <- -90 MaxGridY <- 1080 MinGridY <- -1080 gridY <- (latitude / ((MaxLat - MinLat) / 2)) * ((MaxGridY - MinGridY) / 2) gridY[which(gridY > 0)] <- ceiling(gridY[which(gridY > 0)]) gridY[which(gridY < 0)] <- floor(gridY[which(gridY < 0)]) return (gridY) } getLongitude <- function(gridX) { MaxLon = 180 MinLon = -180 MaxGridX = 2160 MinGridX = -2160 differenceLon <- (MaxLon - MinLon)/2 gridX[which(gridX < 0)] <- ((differenceLon/MaxGridX) * gridX[which(gridX < 0)]) + (differenceLon/(MaxGridX*2)) gridX[which(gridX > 0)] <- ((differenceLon/MaxGridX) * gridX[which(gridX > 0)]) - (differenceLon/(MaxGridX*2)) return (gridX) } getLatitude <- function(gridY) { MaxLat = 90 MinLat = -90 MaxGridY = 1080 MinGridY = -1080 differenceLat <- (MaxLat - MinLat)/2 gridY[which(gridY < 0)] <- ((differenceLat/MaxGridY) * gridY[which(gridY < 0)]) + (differenceLat/(MaxGridY*2)) gridY[which(gridY > 0)] <- ((differenceLat/MaxGridY) * gridY[which(gridY > 0)]) - (differenceLat/(MaxGridY*2)) return (gridY) }
1,807
mit