content
stringlengths
0
14.9M
filename
stringlengths
44
136
library(tseries) library(urca) data(Raotbl3) attach(Raotbl3) lc <- ts(lc, start=c(1966,4), end=c(1991,2), frequency=4) li <- ts(li, start=c(1966,4), end=c(1991,2), frequency=4) lw <- ts(lw, start=c(1966,4), end=c(1991,2), frequency=4) ukcons <- window(cbind(lc, li, lw), start=c(1967, 2), end=c(1991,2)) lc.eq <- summary(lm(lc ~ li + lw, data=ukcons)) li.eq <- summary(lm(li ~ lc + lw, data=ukcons)) lw.eq <- summary(lm(lw ~ li + lc, data=ukcons)) error.lc <- ts(resid(lc.eq), start=c(1967,2), end=c(1991,2), frequency=4) error.li <- ts(resid(li.eq), start=c(1967,2), end=c(1991,2), frequency=4) error.lw <- ts(resid(lw.eq), start=c(1967,2), end=c(1991,2), frequency=4) ci.lc <- ur.df(error.lc, lags=1, type='none') ci.li <- ur.df(error.li, lags=1, type='none') ci.lw <- ur.df(error.lw, lags=1, type='none') jb.lc <- jarque.bera.test(error.lc) jb.li <- jarque.bera.test(error.li) jb.lw <- jarque.bera.test(error.lw)
/scratch/gouwar.j/cran-all/cranData/urca/inst/book-ex/Rcode-7-1.R
ukcons2 <- ts(embed(diff(ukcons), dim=2), start=c(1967,4), freq=4) colnames(ukcons2) <- c('lc.d', 'li.d', 'lw.d', 'lc.d1', 'li.d1', 'lw.d1') error.ecm1 <- window(lag(error.lc, k=-1), start=c(1967,4), end=c(1991, 2)) error.ecm2 <- window(lag(error.li, k=-1), start=c(1967,4), end=c(1991, 2)) ecm.eq1 <- lm(lc.d ~ error.ecm1 + lc.d1 + li.d1 + lw.d1, data=ukcons2) ecm.eq2 <- lm(li.d ~ error.ecm2 + lc.d1 + li.d1 + lw.d1, data=ukcons2)
/scratch/gouwar.j/cran-all/cranData/urca/inst/book-ex/Rcode-7-2.R
library(urca) data(Raotbl3) attach(Raotbl3) lc <- ts(lc, start=c(1966,4), end=c(1991,2), frequency=4) li <- ts(li, start=c(1966,4), end=c(1991,2), frequency=4) lw <- ts(lw, start=c(1966,4), end=c(1991,2), frequency=4) ukcons <- window(cbind(lc, li, lw), start=c(1967, 2), end=c(1991,2)) pu.test <- summary(ca.po(ukcons, demean='const', type='Pu')) pz.test <- summary(ca.po(ukcons, demean='const', type='Pz'))
/scratch/gouwar.j/cran-all/cranData/urca/inst/book-ex/Rcode-7-3.R
library(urca) data(UKpppuip) names(UKpppuip) attach(UKpppuip) dat1 <- cbind(p1, p2, e12, i1, i2) dat2 <- cbind(doilp0, doilp1) args('ca.jo') H1 <- ca.jo(dat1, type = 'trace', K = 2, season = 4, dumvar = dat2) H1.trace <- summary(ca.jo(dat1, type = 'trace', K = 2, season = 4, dumvar = dat2)) H1.eigen <- summary(ca.jo(dat1, type = 'eigen', K = 2, season = 4, dumvar = dat2))
/scratch/gouwar.j/cran-all/cranData/urca/inst/book-ex/Rcode-8-1.R
VARselect(Canada, lag.max = 8, type = "both")
/scratch/gouwar.j/cran-all/cranData/urca/inst/book-ex/Rcode-8-10.R
Canada <- Canada[, c("prod", "e", "U", "rw")] p1ct <- VAR(Canada, p = 1, type = "both") p2ct <- VAR(Canada, p = 2, type = "both") p3ct <- VAR(Canada, p = 3, type = "both") ## Serial serial.test(p3ct, lags.pt = 16, type = "PT.asymptotic") serial.test(p2ct, lags.pt = 16, type = "PT.asymptotic") serial.test(p1ct, lags.pt = 16, type = "PT.asymptotic") serial.test(p3ct, lags.pt = 16, type = "PT.adjusted") serial.test(p2ct, lags.pt = 16, type = "PT.adjusted") serial.test(p1ct, lags.pt = 16, type = "PT.adjusted") ## JB normality.test(p3ct) normality.test(p2ct) normality.test(p1ct) ## ARCH arch.test(p3ct, lags.multi = 5) arch.test(p2ct, lags.multi = 5) arch.test(p1ct, lags.multi = 5) ## Stability (Recursive CUSUM) plot(stability(p3ct), nc = 2) plot(stability(p2ct), nc = 2) plot(stability(p1ct), nc = 2)
/scratch/gouwar.j/cran-all/cranData/urca/inst/book-ex/Rcode-8-11.R
summary(ca.jo(Canada, type = "trace", ecdet = "trend", K = 3, spec = "transitory")) summary(ca.jo(Canada, type = "trace", ecdet = "trend", K = 2, spec = "transitory"))
/scratch/gouwar.j/cran-all/cranData/urca/inst/book-ex/Rcode-8-12.R
vecm <- ca.jo(Canada[, c("rw", "prod", "e", "U")], type = "trace", ecdet = "trend", K = 3, spec = "transitory") vecm.r1 <- cajorls(vecm, r = 1) alpha <- coef(vecm.r1$rlm)[1, ] beta <- vecm.r1$beta resids <- resid(vecm.r1$rlm) N <- nrow(resids) sigma <- crossprod(resids) / N ## t-stats for alpha alpha.se <- sqrt(solve(crossprod( cbind(vecm@ZK %*% beta, vecm@Z1))) [1, 1]* diag(sigma)) alpha.t <- alpha / alpha.se ## t-stats for beta beta.se <- sqrt(diag(kronecker(solve( crossprod(vecm@RK[, -1])), solve(t(alpha) %*% solve(sigma) %*% alpha)))) beta.t <- c(NA, beta[-1] / beta.se)
/scratch/gouwar.j/cran-all/cranData/urca/inst/book-ex/Rcode-8-13.R
vecm <- ca.jo(Canada[, c("prod", "e", "U", "rw")], type = "trace", ecdet = "trend", K = 3, spec = "transitory") SR <- matrix(NA, nrow = 4, ncol = 4) SR[4, 2] <- 0 SR LR <- matrix(NA, nrow = 4, ncol = 4) LR[1, 2:4] <- 0 LR[2:4, 4] <- 0 LR svec <- SVEC(vecm, LR = LR, SR = SR, r = 1, lrtest = FALSE, boot = TRUE, runs = 100) svec svec$SR / svec$SRse svec$LR / svec$LRse
/scratch/gouwar.j/cran-all/cranData/urca/inst/book-ex/Rcode-8-14.R
LR[3, 3] <- 0 LR svec.oi <- SVEC(vecm, LR = LR, SR = SR, r = 1, lrtest = TRUE, boot = FALSE) svec.oi <- update(svec, LR = LR, lrtest = TRUE, boot = FALSE) svec.oi$LRover
/scratch/gouwar.j/cran-all/cranData/urca/inst/book-ex/Rcode-8-15.R
svec.irf <- irf(svec, response = "U", n.ahead = 48, boot = TRUE) svec.irf plot(svec.irf)
/scratch/gouwar.j/cran-all/cranData/urca/inst/book-ex/Rcode-8-16.R
fevd.U <- fevd(svec, n.ahead = 48)$U
/scratch/gouwar.j/cran-all/cranData/urca/inst/book-ex/Rcode-8-17.R
beta <- H1@V beta[,2] <- beta[,2]/beta[4,2] beta[,3] <- beta[,3]/beta[4,3] alpha <- H1@PI%*%solve(t(beta)) beta1 <- cbind(beta[,1:2], H1@V[,3:5]) ci.1 <- ts((H1@x%*%beta1)[-c(1,2),], start=c(1972, 3), end=c(1987, 2), frequency=4) ci.2 <- ts(H1@RK%*%beta1, start=c(1972, 3), end=c(1987, 2), frequency=4)
/scratch/gouwar.j/cran-all/cranData/urca/inst/book-ex/Rcode-8-2.R
A1 <- matrix(c(1,0,0,0,0, 0,0,1,0,0, 0,0,0,1,0, 0,0,0,0,1), nrow=5, ncol=4) A2 <- matrix(c(1,0,0,0,0, 0,1,0,0,0, 0,0,1,0,0, 0,0,0,1,0), nrow=5, ncol=4) H41 <- summary(alrtest(z = H1, A = A1, r = 2)) H42 <- summary(alrtest(z = H1, A = A2, r = 2))
/scratch/gouwar.j/cran-all/cranData/urca/inst/book-ex/Rcode-8-3.R
H.31 <- matrix(c(1,-1,-1,0,0, 0,0,0,1,0, 0,0,0,0,1), c(5,3)) H.32 <- matrix(c(1,0,0,0,0, 0,1,0,0,0, 0,0,1,0,0, 0,0,0,1,-1), c(5,4)) H31 <- summary(blrtest(z = H1, H = H.31, r = 2)) H32 <- summary(blrtest(z = H1, H = H.32, r = 2))
/scratch/gouwar.j/cran-all/cranData/urca/inst/book-ex/Rcode-8-4.R
H.51 <- c(1, -1, -1, 0, 0) H.52 <- c(0, 0, 0, 1, -1) H51 <- summary(bh5lrtest(z = H1, H = H.51, r = 2)) H52 <- summary(bh5lrtest(z = H1, H = H.52, r = 2))
/scratch/gouwar.j/cran-all/cranData/urca/inst/book-ex/Rcode-8-5.R
H.6 <- matrix(rbind(diag(3), c(0, 0, 0), c(0, 0, 0)), nrow=5, ncol=3) H6 <- summary(bh6lrtest(z = H1, H = H.6, r = 2, r1 = 1))
/scratch/gouwar.j/cran-all/cranData/urca/inst/book-ex/Rcode-8-6.R
data(denmark) sjd <- denmark[, c("LRM", "LRY", "IBO", "IDE")] sjd.vecm <- summary(ca.jo(sjd, ecdet = "const", type = "eigen", K = 2, spec = "longrun", season = 4)) lue.vecm <- summary(cajolst(sjd, season=4))
/scratch/gouwar.j/cran-all/cranData/urca/inst/book-ex/Rcode-8-7.R
library(vars) data(Canada) summary(Canada) plot(Canada, nc = 2)
/scratch/gouwar.j/cran-all/cranData/urca/inst/book-ex/Rcode-8-8.R
summary(ur.df(Canada[, "prod"], type = "trend", lags = 2)) summary(ur.df(diff(Canada[, "prod"]), type = "drift", lags = 1)) summary(ur.df(Canada[, "e"], type = "trend", lags = 2)) summary(ur.df(diff(Canada[, "e"]), type = "drift", lags = 1)) summary(ur.df(Canada[, "U"], type = "drift", lags = 1)) summary(ur.df(diff(Canada[, "U"]), type = "none", lags = 0)) summary(ur.df(Canada[, "rw"], type = "trend", lags = 4)) summary(ur.df(diff(Canada[, "rw"]), type = "drift", lags = 3)) summary(ur.df(diff(Canada[, "rw"]), type = "drift", lags = 0))
/scratch/gouwar.j/cran-all/cranData/urca/inst/book-ex/Rcode-8-9.R
curl_fetch_headers <- function(urls, pool = curl::new_pool(), progress = FALSE) { hs <- vector("list", length(urls)) bar <- progress_bar(if (progress) length(urls), msg = "fetching ") for (i in seq_along(hs)) { u <- urls[[i]] h <- curl::new_handle(url = u) curl::handle_setopt(h, nobody = TRUE, cookiesession = 1L, followlocation = 1L, http_version = 2L, ssl_enable_alpn = 0L) if (grepl("^https?://github[.]com", u) && nzchar(a <- Sys.getenv("GITHUB_PAT", ""))) { curl::handle_setheaders(h, "Authorization" = paste("token", a)) } handle_result <- local({ i <- i function(x) { hs[[i]] <<- x bar$update() } }) handle_error <- local({ i <- i function(x) { hs[[i]] <<- structure(list(message = x), class = c("curl_error", "error", "condition")) bar$update() } }) curl::multi_add(h, done = handle_result, fail = handle_error, pool = pool) } curl::multi_run(pool = pool) out <- vector("list", length(hs)) for (i in seq_along(out)) { if (inherits(hs[[i]], "error")) { out[[i]] <- hs[[i]] } else { out[[i]] <- strsplit(rawToChar(hs[[i]]$headers), "(?<=\r\n)", perl = TRUE)[[1]] attr(out[[i]], "status") <- hs[[i]]$status_code } } out } utils::globalVariables(c("done", "fmt")) progress_bar <- function(length, msg = "") { bar <- new.env(parent = baseenv()) if (is.null(length)) { length <- 0L } bar$length <- length bar$done <- -1L digits <- trunc(log10(length)) + 1L bar$fmt <- paste0("\r", msg, "[ %", digits, "i / %", digits, "i ]") bar$update <- function() { assign("done", inherits = TRUE, done + 1L) if (length <= 0L) { return() } if (done >= length) { cat("\r", strrep(" ", nchar(fmt)), "\r", sep = "") } else { cat(sprintf(fmt, done, length), sep = "") } } environment(bar$update) <- bar bar$update() bar }
/scratch/gouwar.j/cran-all/cranData/urlchecker/R/parallel.R
url_db_from_package_rmd_vignettes <- function(dir) { urls <- path <- character() rfiles <- Filter(file.exists, tools::pkgVignettes(dir = dir)$docs) for (rfile in rfiles) { if(!is.na(rfile) && nzchar(Sys.which("pandoc"))) { rpath <- asNamespace("tools")$.file_path_relative_to_dir(rfile, dir) tfile <- tempfile(fileext = ".html") on.exit(unlink(tfile), add = TRUE) out <- .pandoc_md_for_CRAN2(rfile, tfile) if(!out$status) { rurls <- tools$.get_urls_from_HTML_file(tfile) urls <- c(urls, rurls) path <- c(path, rep.int(rpath, length(rurls))) } } } tools$url_db(urls, path) } # adapted from https://github.com/wch/r-source/blob/58d223cf3eaa50ff8cfc2caf591d67350e549e4a/src/library/tools/R/utils.R#L1847-L1857 # Adding the autolink_bare_uris extension .pandoc_md_for_CRAN2 <- function(ifile, ofile) { asNamespace("tools")$.system_with_capture("pandoc", paste(shQuote(normalizePath(ifile)), "-s", "--mathjax", "--email-obfuscation=references", "-f", "markdown+autolink_bare_uris", "-o", shQuote(ofile))) }
/scratch/gouwar.j/cran-all/cranData/urlchecker/R/rmd.R
#' Check urls in a package #' #' Runs the `url_db_from_package_source` function in the tools package along #' with a function to check URLs in un-rendered Rmarkdown vignettes. #' #' @param path Path to the package #' @param db A url database #' @param parallel If `TRUE`, check the URLs in parallel #' @param pool A multi handle created by [curl::new_pool()]. If `NULL` use a global pool. #' @param progress Whether to show the progress bar for parallel checks #' @return A `url_checker_db` object (invisibly). This is a `check_url_db` object #' with an added class with a custom print method. #' @examples #' \dontrun{ #' url_check("my_pkg") #' } #' @export url_check <- function(path = ".", db = NULL, parallel = TRUE, pool = curl::new_pool(), progress = TRUE) { if (is.null(db)) { db <- with_pandoc_available( rbind( tools$url_db_from_package_sources(normalizePath(path)), url_db_from_package_rmd_vignettes(normalizePath(path)) ) ) } res <- tools$check_url_db(db, parallel = parallel, pool = pool, verbose = progress) if (NROW(res) > 0) { res$root <- normalizePath(path) } class(res) <- c("urlchecker_db", class(res)) res } #' @export print.urlchecker_db <- function(x, ...) { if (NROW(x) == 0) { cli::cli_alert_success("All URLs are correct!") return(invisible(x)) } for (row in seq_len(NROW(x))) { cran <- x[["CRAN"]][[row]] if (nzchar(cran)) { status <- "Error" message <- "CRAN URL not in canonical form" url <- cran new <- "" } else { status <- x[["Status"]][[row]] message <- x[["Message"]][[row]] url <- x[["URL"]][[row]] new <- x[["New"]][[row]] } root <- x[["root"]][[row]] from <- x[["From"]][[row]] for (file in from) { file_path <- file.path(root, file) data <- readLines(file_path) match <- regexpr(url, data, fixed = TRUE) lines <- which(match != -1) starts <- match[match != -1] ends <- starts + attr(match, "match.length")[match != -1] for (i in seq_along(lines)) { pointer <- paste0(strrep(" ", starts[[i]] - 1), "^", strrep("~", ends[[i]] - starts[[i]] - 1)) if (nzchar(new)) { fix_it <- paste0(strrep(" ", starts[[i]] - 1), new) cli::cli_alert_warning(" {.strong Warning:} {file}:{lines[[i]]}:{starts[[i]]} {.emph Moved} {data[lines[[i]]]} {pointer} {fix_it} ") } else { cli::cli_alert_danger(" {.strong Error:} {file}:{lines[[i]]}:{starts[[i]]} {.emph {status}: {message}} {data[lines[[i]]]} {pointer} ") } } } } invisible(x) }
/scratch/gouwar.j/cran-all/cranData/urlchecker/R/url_check.R
#' Update URLs in a package #' #' First uses [url_check] to check and then updates any URLs which are permanent (301) #' redirects. #' #' @param path Path to the package #' @param results results from [url_check]. #' @return The results from `url_check(path)`, invisibly. #' @examples #' \dontrun{ #' url_update("my_pkg") #' } #' @export url_update <- function(path = ".", results = url_check(path)) { can_update <- vlapply(results[["New"]], nzchar) to_update <- results[can_update, ] for (row in seq_len(NROW(to_update))) { old <- to_update[["URL"]][[row]] new <- to_update[["New"]][[row]] root <- to_update[["root"]][[row]] if (nzchar(new)) { from <- to_update[["From"]][[row]] if (("README.md" %in% from) && file.exists("README.Rmd")) { from <- c(from, "README.Rmd") } for (file in from) { file_path <- file.path(root, file) data <- readLines(file_path) data <- gsub(old, new, data, fixed = TRUE) writeLines(data, file_path) cli::cli_alert_success("{.strong Updated:} {.url {old}} to {.url {new}} in {.file {file}}") } } } print(results[!can_update, ]) invisible(results) }
/scratch/gouwar.j/cran-all/cranData/urlchecker/R/url_update.R
vlapply <- function(x, f, ...) vapply(x, f, logical(1)) # makes sure that pandoc is available # puts RStudio's pandoc on the PATH if it is the only one available with_pandoc_available <- function(code) { pandoc_location <- Sys.which("pandoc") if (!nzchar(pandoc_location)) { pandoc_path <- Sys.getenv("RSTUDIO_PANDOC") if (!nzchar(pandoc_path)) { stop("pandoc is not installed and on the PATH") } else { sys_path <- Sys.getenv("PATH") on.exit(Sys.setenv("PATH" = sys_path)) Sys.setenv("PATH" = paste(pandoc_path, sys_path, sep = .Platform$path.sep)) } } force(code) }
/scratch/gouwar.j/cran-all/cranData/urlchecker/R/utils.R
tools <- new.env(parent = asNamespace("tools")) .onLoad <- function(...) { source(file = system.file(file.path("tools", "urltools.R"), package = "urlchecker"), local = tools) if (getRversion() < "4.0.0") { source(file = system.file(file.path("tools", "utils.R"), package = "urlchecker"), local = tools) } }
/scratch/gouwar.j/cran-all/cranData/urlchecker/R/zzz.R
# File src/library/tools/R/urltools.R # Part of the R package, https://www.R-project.org # # Copyright (C) 2015-2021 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/ get_IANA_URI_scheme_db <- function() { ## See ## <https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml>. baseurl <- "https://www.iana.org/assignments/uri-schemes/" db <- utils::read.csv(url(paste0(baseurl, "uri-schemes-1.csv")), stringsAsFactors = FALSE, encoding = "UTF-8") names(db) <- chartr(".", "_", names(db)) db } parse_URI_reference <- function(x) { ## See RFC_3986 <http://www.ietf.org/rfc/rfc3986.txt>. re <- "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?" if(length(x)) { y <- do.call(rbind, regmatches(x, regexec(re, x))) y <- y[, c(3, 5, 6, 8, 10), drop = FALSE] } else { y <- matrix(character(), 0L, 5L) } colnames(y) <- c("scheme", "authority", "path", "query", "fragment") y } .get_urls_from_Rd <- function(x, href = TRUE, ifdef = FALSE) { urls <- character() recurse <- function(e) { tag <- attr(e, "Rd_tag") ## Rd2HTML and Rd2latex remove whitespace and \n from URLs. if(identical(tag, "\\url")) { urls <<- c(urls, lines2str(.Rd_deparse(e, tag = FALSE))) } else if(href && identical(tag, "\\href")) { ## One could also record the \href text argument in the ## names, but then one would need to process named and ## unnamed extracted URLs separately. urls <<- c(urls, lines2str(.Rd_deparse(e[[1L]], tag = FALSE))) } else if(ifdef && length(tag) && (tag %in% c("\\if", "\\ifelse"))) { ## cf. testRdConditional() condition <- e[[1L]] if(all(RdTags(condition) == "TEXT")) { if(any(c("TRUE", "html") %in% trimws(strsplit(paste(condition, collapse = ""), ",")[[1L]]))) recurse(e[[2L]]) else if(tag == "\\ifelse") recurse(e[[3L]]) } } else if(is.list(e)) lapply(e, recurse) } lapply(x, recurse) unique(trimws(urls)) } .get_urls_from_HTML_file <- function(f) { doc <- xml2::read_html(f) if(!inherits(doc, "xml_node")) return(character()) nodes <- xml2::xml_find_all(doc, "//a") hrefs <- xml2::xml_attr(nodes, "href") unique(hrefs[!is.na(hrefs) & !startsWith(hrefs, "#")]) } .get_urls_from_PDF_file <- function(f) { ## Seems there is no straightforward way to extract hyperrefs from a ## PDF, hence first convert to HTML. ## Note that pdftohtml always outputs in cwd ... owd <- getwd() dir.create(d <- tempfile()) on.exit({ unlink(d, recursive = TRUE); setwd(owd) }) file.copy(normalizePath(f), d) setwd(d) g <- tempfile(tmpdir = d, fileext = ".xml") system2("pdftohtml", c("-s -q -i -c -xml", shQuote(basename(f)), shQuote(basename(g)))) ## Oh dear: seems that pdftohtml can fail without a non-zero exit ## status. if(file.exists(g)) .get_urls_from_HTML_file(g) else character() } url_db <- function(urls, parents) { ## Some people get leading LFs in URLs, so trim before checking. db <- data.frame(URL = trimws(as.character(urls)), Parent = as.character(parents), stringsAsFactors = FALSE) class(db) <- c("url_db", "data.frame") db } url_db_from_HTML_files <- function(dir, recursive = FALSE, files = NULL, verbose = FALSE) { urls <- parents <- character() if(is.null(files)) files <- list.files(dir, pattern = "[.]html$", full.names = TRUE, recursive = recursive) urls <- lapply(files, function(f) { if(verbose) message(sprintf("processing %s", .file_path_relative_to_dir(f, dir))) .get_urls_from_HTML_file(f) }) names(urls) <- files urls <- Filter(length, urls) if(length(urls)) { parents <- rep.int(.file_path_relative_to_dir(names(urls), dir), lengths(urls)) urls <- unlist(urls, use.names = FALSE) } url_db(urls, parents) } url_db_from_PDF_files <- function(dir, recursive = FALSE, files = NULL, verbose = FALSE) { urls <- parents <- character() if(is.null(files)) files <- list.files(dir, pattern = "[.]pdf$", full.names = TRUE, recursive = recursive) ## FIXME: this is simpler to do with full.names = FALSE and without ## tools:::.file_path_relative_to_dir(). urls <- lapply(files, function(f) { if(verbose) message(sprintf("processing %s", .file_path_relative_to_dir(f, dir))) .get_urls_from_PDF_file(f) }) names(urls) <- files urls <- Filter(length, urls) if(length(urls)) { parents <- rep.int(.file_path_relative_to_dir(names(urls), dir), lengths(urls)) urls <- unlist(urls, use.names = FALSE) } url_db(urls, parents) } url_db_from_package_Rd_db <- function(db) { urls <- Filter(length, lapply(db, .get_urls_from_Rd)) url_db(unlist(urls, use.names = FALSE), rep.int(file.path("man", names(urls)), lengths(urls))) } url_db_from_package_metadata <- function(meta) { urls <- character() fields <- c("URL", "BugReports") for(v in meta[fields]) { if(is.na(v)) next pattern <- "<(URL: *)?((https?|ftp)://[^[:space:],]*)[[:space:]]*>" m <- gregexpr(pattern, v) urls <- c(urls, .gregexec_at_pos(pattern, v, m, 3L)) regmatches(v, m) <- "" pattern <- "(^|[^>\"])((https?|ftp)://[^[:space:],]*)" m <- gregexpr(pattern, v) urls <- c(urls, .gregexec_at_pos(pattern, v, m, 3L)) } if(!is.na(v <- meta["Description"])) { pattern <- "<(URL: *)?((https?|ftp)://[^[:space:]]+)[[:space:]]*>" m <- gregexpr(pattern, v) urls <- c(urls, .gregexec_at_pos(pattern, v, m, 3L)) regmatches(v, m) <- "" pattern <- "([^>\"])((https?|ftp)://[[:alnum:]/.:@+\\_~%#?=&;,-]+[[:alnum:]/])" m <- gregexpr(pattern, v) urls <- c(urls, .gregexec_at_pos(pattern, v, m, 3L)) } url_db(urls, rep.int("DESCRIPTION", length(urls))) } url_db_from_package_citation <- function(dir, meta, installed = FALSE) { urls <- character() path <- if(installed) "CITATION" else file.path("inst", "CITATION") cfile <- file.path(dir, path) if(file.exists(cfile)) { cinfo <- .read_citation_quietly(cfile, meta) if(!inherits(cinfo, "error")) urls <- trimws(unique(unlist(cinfo$url, use.names = FALSE))) } url_db(urls, rep.int(path, length(urls))) } url_db_from_package_news <- function(dir, installed = FALSE) { path <- if(installed) "NEWS.Rd" else file.path("inst", "NEWS.Rd") nfile <- file.path(dir, path) urls <- if(file.exists(nfile)) { macros <- initialRdMacros() .get_urls_from_Rd(prepare_Rd(parse_Rd(nfile, macros = macros), stages = "install")) } else character() url_db(urls, rep.int(path, length(urls))) } url_db_from_package_HTML_files <- function(dir, installed = FALSE) { path <- if(installed) "doc" else file.path("inst", "doc") files <- Sys.glob(file.path(dir, path, "*.html")) if(installed && file.exists(rfile <- file.path(dir, "README.html"))) files <- c(files, rfile) url_db_from_HTML_files(dir, files = files) } url_db_from_package_README_md <- function(dir, installed = FALSE) { urls <- path <- character() rfile <- Filter(file.exists, c(if(!installed) file.path(dir, "inst", "README.md"), file.path(dir, "README.md")))[1L] if(!is.na(rfile) && nzchar(Sys.which("pandoc"))) { path <- .file_path_relative_to_dir(rfile, dir) tfile <- tempfile("README", fileext = ".html") on.exit(unlink(tfile)) out <- .pandoc_md_for_CRAN(rfile, tfile) if(!out$status) { urls <- .get_urls_from_HTML_file(tfile) } } url_db(urls, rep.int(path, length(urls))) } url_db_from_package_NEWS_md <- function(dir, installed = FALSE) { urls <- path <- character() nfile <- Filter(file.exists, c(if(!installed) file.path(dir, "inst", "NEWS.md"), file.path(dir, "NEWS.md")))[1L] if(!is.na(nfile) && nzchar(Sys.which("pandoc"))) { path <- .file_path_relative_to_dir(nfile, dir) tfile <- tempfile("NEWS", fileext = ".html") on.exit(unlink(tfile)) out <- .pandoc_md_for_CRAN(nfile, tfile) if(!out$status) { urls <- .get_urls_from_HTML_file(tfile) } } url_db(urls, rep.int(path, length(urls))) } url_db_from_package_sources <- function(dir, add = FALSE) { meta <- .read_description(file.path(dir, "DESCRIPTION")) db <- rbind(url_db_from_package_metadata(meta), url_db_from_package_Rd_db(Rd_db(dir = dir)), url_db_from_package_citation(dir, meta), url_db_from_package_news(dir)) if(requireNamespace("xml2", quietly = TRUE)) { db <- rbind(db, url_db_from_package_HTML_files(dir), url_db_from_package_README_md(dir), url_db_from_package_NEWS_md(dir) ) } if(add) db$Parent <- file.path(basename(dir), db$Parent) db } url_db_from_installed_packages <- function(packages, lib.loc = NULL, verbose = FALSE) { if(!length(packages)) return() one <- function(p) { if(verbose) message(sprintf("processing %s", p)) dir <- system.file(package = p, lib.loc = lib.loc) if(dir == "") return() meta <- .read_description(file.path(dir, "DESCRIPTION")) rddb <- Rd_db(p, lib.loc = dirname(dir)) db <- rbind(url_db_from_package_metadata(meta), url_db_from_package_Rd_db(rddb), url_db_from_package_citation(dir, meta, installed = TRUE), url_db_from_package_news(dir, installed = TRUE)) if(requireNamespace("xml2", quietly = TRUE)) { db <- rbind(db, url_db_from_package_HTML_files(dir, installed = TRUE), url_db_from_package_README_md(dir, installed = TRUE), url_db_from_package_NEWS_md(dir, installed = TRUE) ) } db$Parent <- file.path(p, db$Parent) db } do.call(rbind, c(lapply(packages, one), list(make.row.names = FALSE))) } get_IANA_HTTP_status_code_db <- function() { ## See ## <https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml> baseurl <- "https://www.iana.org/assignments/http-status-codes/" db <- utils::read.csv(url(paste0(baseurl, "http-status-codes-1.csv")), stringsAsFactors = FALSE) ## Drop "Unassigned". db[db$Description != "Unassigned", ] } ## See <https://en.wikipedia.org/wiki/List_of_FTP_server_return_codes> ## and <http://tools.ietf.org/html/rfc959>, ## Section 4.2.2 "Numeric Order List of Reply Codes", ## and <https://tools.ietf.org/html/rfc2228>, ## Section 5 "New FTP Replies". ## Only need those >= 400. table_of_FTP_server_return_codes <- c("421" = "Service not available, closing control connection.", "425" = "Can't open data connection.", "426" = "Connection closed; transfer aborted.", "430" = "Invalid username or password", "431" = "Need some unavailable resource to process security.", "434" = "Requested host unavailable.", "450" = "Requested file action not taken.", "451" = "Requested action aborted: local error in processing.", "452" = "Requested action not taken. Insufficient storage space in system.", "500" = "Syntax error, command unrecognized.", "501" = "Syntax error in parameters or arguments.", "502" = "Command not implemented.", "503" = "Bad sequence of commands.", "504" = "Command not implemented for that parameter.", "530" = "Not logged in.", "532" = "Need account for storing files.", "533" = "Command protection level denied for policy reasons.", "534" = "Request denied for policy reasons.", "535" = "Failed security check (hash, sequence, etc).", "536" = "Requested PROT level not supported by mechanism.", "537" = "Command protection level not supported by security mechanism.", "550" = "Requested action not taken. File unavailable", "551" = "Requested action aborted: page type unknown.", "552" = "Requested file action aborted. Exceeded storage allocation (for current directory or dataset).", "553" = "Requested action not taken. File name not allowed.", "631" = "Integrity protected reply.", "632" = "Confidentiality and integrity protected reply.", "633" = "Confidentiality protected reply." ) check_url_db <- function(db, remote = TRUE, verbose = FALSE, parallel = FALSE, pool = NULL) { use_curl <- !parallel && config_val_to_logical(Sys.getenv("_R_CHECK_URLS_USE_CURL_", "TRUE")) && requireNamespace("curl", quietly = TRUE) if(parallel && is.null(pool)) pool <- curl::new_pool() .gather <- function(u = character(), p = list(), s = rep.int("", length(u)), m = rep.int("", length(u)), new = rep.int("", length(u)), cran = rep.int("", length(u)), spaces = rep.int("", length(u)), R = rep.int("", length(u))) { y <- data.frame(URL = u, From = I(p), Status = s, Message = m, New = new, CRAN = cran, Spaces = spaces, R = R, row.names = NULL, stringsAsFactors = FALSE) y$From <- p class(y) <- c("check_url_db", "data.frame") y } .fetch_headers <- if(parallel) function(urls) .fetch_headers_via_curl(urls, verbose, pool) else function(urls) .fetch_headers_via_base(urls, verbose) .check_ftp <- function(u, h) { if(inherits(h, "error")) { s <- "-1" msg <- sub("[[:space:]]*$", "", conditionMessage(h)) } else { s <- as.character(attr(h, "status")) msg <- table_of_FTP_server_return_codes[s] } c(s, msg, "", "") } .check_http <- if(remote) function(u, h) c(.check_http_A(u, h), .check_http_B(u)) else function(u, h) c(rep.int("", 3L), .check_http_B(u)) .check_http_A <- function(u, h) { newLoc <- "" if(inherits(h, "error")) { s <- "-1" msg <- sub("[[:space:]]*$", "", conditionMessage(h)) if(grepl(paste(c("server certificate verification failed", "failed to get server cert", "libcurl error code (51|60)"), collapse = "|"), msg)) { h2 <- tryCatch(curlGetHeaders(u, verify = FALSE), error = identity) s2 <- as.character(attr(h2, "status")) msg <- paste0(msg, "\n\t(Status without verification: ", table_of_HTTP_status_codes[s2], ")") } } else { s <- as.character(attr(h, "status")) msg <- table_of_HTTP_status_codes[s] } ## Look for redirected URLs ## According to ## <https://tools.ietf.org/html/rfc7230#section-3.1.2> the first ## line of a response is the status-line, with "a possibly empty ## textual phrase describing the status code", so only look for ## a 301 status code in the first line. if(grepl(" 301 ", h[1L], useBytes = TRUE) && !startsWith(u, "https://doi.org/") && !startsWith(u, "http://dx.doi.org/")) { ## Get the new location from the last consecutive 301 ## obtained. h <- split(h, c(0L, cumsum(h == "\r\n")[-length(h)])) i <- vapply(h, function(e) grepl(" 301 ", e[1L], useBytes = TRUE), NA) h <- h[[which(!i)[1L] - 1L]] pos <- grep("^[Ll]ocation: ", h, useBytes = TRUE) if(length(pos)) { loc <- sub("^[Ll]ocation: ([^\r]*)\r\n", "\\1", h[pos[1L]]) ## Ouch. According to RFC 7231, the location is a URI ## reference, and may be relative in which case it needs ## resolving against the effect request URI. ## <https://tools.ietf.org/html/rfc7231#section-7.1.2>. ## Not quite straightforward, hence do not report such ## 301s. ## (Alternatively, could try reporting the 301 but no ## new location.) if(nzchar(parse_URI_reference(loc)[1L, "scheme"])) newLoc <- loc ## (Note also that fragments would need extra care.) } } ## if((s != "200") && use_curl) { g <- .curl_GET_status(u) if(g == "200") { s <- g msg <- "OK" } } ## A mis-configured site if (s == "503" && any(grepl("www.sciencedirect.com", c(u, newLoc)))) s <- "405" c(s, msg, newLoc) } .check_http_B <- function(u) { ul <- tolower(u) cran <- ((grepl("^https?://cran.r-project.org/web/packages", ul) && !grepl("^https?://cran.r-project.org/web/packages/[.[:alnum:]_]+(html|pdf|rds)$", ul)) || (grepl("^https?://cran.r-project.org/web/views/[[:alnum:]]+[.]html$", ul)) || startsWith(ul, "http://cran.r-project.org") || any(startsWith(ul, mirrors))) R <- grepl("^http://(www|bugs|journal).r-project.org", ul) spaces <- grepl(" ", u) c(if(cran) u else "", if(spaces) u else "", if(R) u else "") } bad <- .gather() if(!NROW(db)) return(bad) ## Could also use utils::getCRANmirrors(local.only = TRUE). mirrors <- c(utils::read.csv(file.path(R.home("doc"), "CRAN_mirrors.csv"), as.is = TRUE, encoding = "UTF-8")$URL, "http://cran.rstudio.com/", "https://cran.rstudio.com/") mirrors <- tolower(sub("/$", "", mirrors)) if(inherits(db, "check_url_db")) { ## Allow re-checking check results. parents <- db$From urls <- db$URL } else { parents <- split(db$Parent, db$URL) urls <- names(parents) } parts <- parse_URI_reference(urls) ## Empty URLs. ind <- apply(parts == "", 1L, all) if(any(ind)) { len <- sum(ind) bad <- rbind(bad, .gather(urls[ind], parents[ind], m = rep.int("Empty URL", len))) } ## Invalid URI schemes. schemes <- parts[, 1L] ind <- is.na(match(schemes, c("", IANA_URI_scheme_db$URI_Scheme, ## Also allow 'javascript' scheme, see ## <https://tools.ietf.org/html/draft-hoehrmann-javascript-scheme-03> ## (but apparently never registered with IANA). "javascript"))) if(any(ind)) { len <- sum(ind) msg <- rep.int("Invalid URI scheme", len) doi <- schemes[ind] == "doi" if(any(doi)) msg[doi] <- paste(msg[doi], "(use \\doi for DOIs in Rd markup)") bad <- rbind(bad, .gather(urls[ind], parents[ind], m = msg)) } ## ftp. pos <- which(schemes == "ftp") if(length(pos) && remote) { urlspos <- urls[pos] headers <- .fetch_headers(urlspos) results <- do.call(rbind, Map(.check_ftp, urlspos, headers)) status <- as.numeric(results[, 1L]) ind <- (status < 0L) | (status >= 400L) if(any(ind)) { pos <- pos[ind] s <- as.character(status[ind]) s[s == "-1"] <- "Error" m <- results[ind, 2L] m[is.na(m)] <- "" bad <- rbind(bad, .gather(urls[pos], parents[pos], s, m)) } } ## http/https. pos <- which(schemes == "http" | schemes == "https") if(length(pos)) { urlspos <- urls[pos] headers <- .fetch_headers(urlspos) results <- do.call(rbind, Map(.check_http, urlspos, headers)) status <- as.numeric(results[, 1L]) ## 405 is HTTP not allowing HEAD requests ## maybe also skip 500, 503, 504 as likely to be temporary issues ind <- is.na(match(status, c(200L, 405L, NA))) | nzchar(results[, 3L]) | nzchar(results[, 4L]) | nzchar(results[, 5L]) | nzchar(results[, 6L]) if(any(ind)) { pos <- pos[ind] s <- as.character(status[ind]) s[is.na(s)] <- "" s[s == "-1"] <- "Error" m <- results[ind, 2L] m[is.na(m)] <- "" bad <- rbind(bad, .gather(urls[pos], parents[pos], s, m, results[ind, 3L], results[ind, 4L], results[ind, 5L], results[ind, 6L])) } } bad } format.check_url_db <- function(x, ...) { if(!NROW(x)) return(character()) u <- x$URL new <- x$New ind <- nzchar(new) if(any(ind)) { u[ind] <- sprintf("%s (moved to %s)", u[ind], new[ind]) if(config_val_to_logical(Sys.getenv("_R_CHECK_URLS_SHOW_301_STATUS_", "FALSE"))) { x$Message[ind] <- "Moved Permanently" x$Status[ind] <- "301" } } paste0(sprintf("URL: %s", u), sprintf("\nFrom: %s", vapply(x$From, paste, "", collapse = "\n ")), ifelse((s <- x$Status) == "", "", sprintf("\nStatus: %s", s)), ifelse((m <- x$Message) == "", "", sprintf("\nMessage: %s", gsub("\n", "\n ", m, fixed=TRUE))), ifelse((m <- x$Spaces) == "", "", "\nURL contains spaces"), ifelse((m <- x$CRAN) == "", "", "\nCRAN URL not in canonical form"), ifelse((m <- x$R) == "", "", "\nR-project URL not in canonical form") ) } print.check_url_db <- function(x, ...) { if(NROW(x)) writeLines(paste(format(x), collapse = "\n\n")) invisible(x) } as.matrix.check_url_db <- function(x, ...) { n <- lengths(x[["From"]]) y <- do.call(cbind, c(list(URL = rep.int(x[["URL"]], n), Parent = unlist(x[["From"]])), lapply(x[-c(1L, 2L)], rep.int, n))) rownames(y) <- NULL y } .fetch_headers_via_base <- function(urls, verbose = FALSE, ids = urls) Map(function(u, verbose, i) { if(verbose) message(sprintf("processing %s", i)) tryCatch(curlGetHeaders(u), error = identity) }, urls, verbose, ids) .fetch_headers_via_curl <- function(urls, verbose = FALSE, pool = NULL) { .progress_bar <- function(length, msg = "") { bar <- new.env(parent = baseenv()) if(is.null(length)) { length <- 0L } ## <FIXME> ## make codetools happy done <- fmt <- NULL ## </FIXME> bar$length <- length bar$done <- -1L digits <- trunc(log10(length)) + 1L bar$fmt <- paste0("\r", msg, "[ %", digits, "i / %", digits, "i ]") bar$update <- function() { assign("done", inherits = TRUE, done + 1L) if (length <= 0L) { return() } if (done >= length) { cat("\r", strrep(" ", nchar(fmt)), "\r", sep = "") } else { cat(sprintf(fmt, done, length), sep = "") } } environment(bar$update) <- bar bar$update() bar } if(is.null(pool)) pool <- curl::new_pool() hs <- vector("list", length(urls)) bar <- .progress_bar(if (verbose) length(urls), msg = "fetching ") for(i in seq_along(hs)) { u <- urls[[i]] h <- curl::new_handle(url = u) curl::handle_setopt(h, nobody = TRUE, cookiesession = 1L, followlocation = 1L, http_version = 2L, ssl_enable_alpn = 0L) timeout <- as.integer(getOption("timeout")) if(!is.na(timeout) && (timeout > 0L)) curl::handle_setopt(h, connecttimeout = timeout, timeout = timeout) if(grepl("^https?://github[.]com", u) && nzchar(a <- Sys.getenv("GITHUB_PAT", ""))) { curl::handle_setheaders(h, "Authorization" = paste("token", a)) } handle_result <- local({ i <- i function(x) { hs[[i]] <<- x bar$update() } }) handle_error <- local({ i <- i function(x) { hs[[i]] <<- structure(list(message = x), class = c("curl_error", "error", "condition")) bar$update() } }) curl::multi_add(h, done = handle_result, fail = handle_error, pool = pool) } curl::multi_run(pool = pool) out <- vector("list", length(hs)) for(i in seq_along(out)) { if(inherits(hs[[i]], "error")) { out[[i]] <- hs[[i]] } else { out[[i]] <- strsplit(rawToChar(hs[[i]]$headers), "(?<=\r\n)", perl = TRUE)[[1L]] attr(out[[i]], "status") <- hs[[i]]$status_code } } out } .curl_GET_status <- function(u, verbose = FALSE) { if(verbose) message(sprintf("processing %s", u)) ## Configure curl handle for better luck with JSTOR URLs/DOIs. ## Alternatively, special-case requests to ## https?://doi.org/10.2307 ## https?://www.jstor.org h <- curl::new_handle() curl::handle_setopt(h, cookiesession = 1, followlocation = 1, http_version = 2L, ssl_enable_alpn = 0) timeout <- as.integer(getOption("timeout")) if(!is.na(timeout) && (timeout > 0L)) curl::handle_setopt(h, connecttimeout = timeout, timeout = timeout) if(startsWith(u, "https://github.com") && nzchar(a <- Sys.getenv("GITHUB_PAT", ""))) curl::handle_setheaders(h, "Authorization" = paste("token", a)) g <- tryCatch(curl::curl_fetch_memory(u, handle = h), error = identity) if(inherits(g, "error")) -1L else g$status_code }
/scratch/gouwar.j/cran-all/cranData/urlchecker/inst/tools/urltools.R
### ** lines2str lines2str <- function(txt, sep = "") trimws(gsub("\n", sep, paste(txt, collapse = sep), fixed = TRUE, useBytes = TRUE))
/scratch/gouwar.j/cran-all/cranData/urlchecker/inst/tools/utils.R
# Bitly_api_version <- "v4" # Isgd_api_version <- "v2019" .urlshorteneREnv <- new.env(parent = emptyenv()) #' @title is_token #' @description is the object a token #' @noRd #' @keywords Internal is_token <- function(x) inherits(x, "Token") #' @title Assign bit.ly API tokens using OAuth2.0 #' #' @param debug - whether to print additional debug messages #' #' @description #' There are 2 ways of how you can authenticate using this package. #' #' 1. The recommended practise for the end-user of this package is to use default API keys which #' are provided using this method. #' #' 2. Alternatively, you can register your own application via the web in order to get Client ID #' and Client Secret code. #' #' For that go first to \url{https://app.bitly.com/settings/integrations/}. Click \code{REGISTERED OAUTH APPLICATIONS}, #' then \code{REGISTER NEW APPLICATION} followed by \code{GET REGISTRATION CODE}. #' Open your email that you will receive and click \code{COMPLETE REGISTRATION}. #' Make up an \code{APPLICATION NAME} that is unique. Unless you know to do otherwise, #' type "http://localhost:1410/" (slash at the end is important) in \code{REDIRECT URIs}. For #' \code{APPLICATION LINK} and \code{APPLICATION DESCRIPTION} you can type whatever you like. #' #' @section However Important Information: #' Before choosing registering new application yourself, you can try using my API keys (the default option). No #' worries, no information is exposed to me at all: neither what you shorten nor who does it, etc. #' In fact, quote: "If you are shortening URLs on behalf of end-users, we ask that you use our OAuth 2 #' implementation to authenticate end-users before shortening. URLs shortened in this manner #' will be added to the specified end-user's history, allowing the end-user to manage and #' track the shortened URLs". #' #' @section WARNING: #' If using RStudio in the browsers via RStudio Server, then authentication may not work well. In #' such case, use desktop RStudio application. Look for help at <https://support.rstudio.com/>. #' #' @param key - Client ID #' @param secret - Client Secret #' @param token - a \code{Token} object or a file path to an rds file containing a token. #' #' @seealso See \url{https://dev.bitly.com/api-reference} #' #' @examples #' \dontrun{ #' # overwrite keys - Variant 2 #' bitly_token <- #' bitly_auth( #' key = "be03aead58f23bc1aee6e1d7b7a1d99d62f0ede8", #' secret = "f9c6a3b18968e991e35f466e90c7d883cc176073" #' ) #' #' # default variant #' bitly_token <- bitly_auth() #' saveRDS(bitly_token, "bitly_token.rds") #' # for non-interactive use: #' bitly_auth(token = "bitly_token.rds") #' } #' #' @import httr #' @export bitly_auth <- function(key = "be03aead58f23bc1aee6e1d7b7a1d99d62f0ede8", secret = "f9c6a3b18968e991e35f466e90c7d883cc176073", debug = F, token) { if (!missing(token)) { if (!is_token(token)) { token <- readRDS(token) if (!is_token(token)) stop("Invalid token") } } else if (interactive()) { token <- httr::oauth2.0_token( httr::oauth_endpoint( authorize = "https://bitly.com/oauth/authorize", access = "https://api-ssl.bitly.com/oauth/access_token" ), httr::oauth_app("bitly", key = key, secret = secret), cache = TRUE ) } else { stop("Save bit.ly token as rds and pass to token to run non-interactively.") } if (isTRUE(debug)) { message(paste0("urlshorteneR: You have been authorized as ", token$credentials$login, " with access token ", token$credentials$access_token)) } .urlshorteneREnv$access_token <- token$credentials$access_token .urlshorteneREnv$token <- token invisible(token) } #' Get Bitly access token #' #' Extract token from \code{bitly_auth} method #' #' @noRd #' @keywords internal bitly_auth_access <- function() { if (is.null(.urlshorteneREnv$token) && interactive()) { .urlshorteneREnv$token <- bitly_auth() } else if (is.null(.urlshorteneREnv$token)) { .urlshorteneREnv$token <- readRDS("../bitly_local_token.rds") } .urlshorteneREnv$acc_token <- .urlshorteneREnv$token$credentials$access_token return(.urlshorteneREnv$acc_token) } #' @title Generalized function for executing REST requests #' #' @param verb - REST verb #' @param url - which is used for the request #' @param queryParameters - parameters that are used for building a URL #' @param showURL - for debugging purposes only: it shows what URL has been called #' #' @import httr #' @import jsonlite #' #' @return json data #' #' @noRd #' @keywords internal doRequest <- function(verb = "", url = NULL, queryParameters = NULL, patch_body = NULL, showURL = NULL) { switch(verb, "PATCH" = { return_request <- suppressMessages(httr::PATCH(url, query = queryParameters, body = patch_body, encode = "json", content_type_json(), httr::config(token = .urlshorteneREnv$token) )) }, "GET" = { return_request <- httr::GET(url, query = queryParameters, httr::config(token = .urlshorteneREnv$token)) }, "POST" = { return_request <- suppressMessages(httr::POST(url, body = queryParameters, encode = "json", httr::content_type_json(), httr::config(token = .urlshorteneREnv$token) )) } ) if (http_error(return_request) == FALSE) { stop_for_status(return_request, "you are not a premium account holder, or internet connection does not work properly") text_response <- content(return_request, as = "text", encoding = "utf-8") json_response <- fromJSON(text_response) if (is.null(return_request$status_code) == FALSE && return_request$status_code >= 400) { message(sprintf("Code: %s - %s", json_response$message, json_response$description)) } if (identical(showURL, TRUE)) { cat("The requested URL has been this: ", return_request$request$url, "\n") } } else { text_response <- content(return_request, as = "text", encoding = "utf-8") json_response <- fromJSON(text_response) message(sprintf("Code: %s - %s", json_response$message, json_response$description)) cat("The requested URL has been this: ", return_request$request$url, "\n") stop_for_status(return_request) } return(json_response) }
/scratch/gouwar.j/cran-all/cranData/urlshorteneR/R/ApiKey.R
#' Shorten an URL #' #' @description Call this function as an addin to prompt a url shortener. #' bit.ly accepts a custom domain, see \code{\link[urlshorteneR]{bitly_shorten_link}}. #' #' @export shortenerAddin <- function() { ui <- miniUI::miniPage( miniUI::gadgetTitleBar("Shorten/Expand URL"), miniUI::miniContentPanel( padding = 10, shiny::textInput("url", label = "Long URL", value = "", width = "100%"), shiny::selectInput( "provider", label = "Provider", choices = c("bit.ly", "is.gd", "v.gd"), selected = "bit.ly", width = "100%" ), shiny::uiOutput("bitly_domain"), shiny::actionButton("shorten", label = "Shorten"), shiny::actionButton("expand", label = "Expand") ) ) server <- function(input, output, session) { shortener_provider <- shiny::reactive({ shiny::req(input$provider) input$provider }) # bit.ly supports custom domains output$bitly_domain <- shiny::renderUI({ if (shortener_provider() == "bit.ly") { shiny::tagList( shiny::textInput("domain", label = "Bit.ly domain", value = "bit.ly", width = "100%") ) } else { return(NULL) } }) # Shorten links shiny::observeEvent(input$shorten, { shiny::req(input$url) shortener <- get_shortener(provider_name = input$provider) # Conditionally pass custom bit.ly custom domain if (input$provider == "bit.ly") { res <- shortener(longUrl = input$url, domain = input$domain) } else { res <- shortener(longUrl = input$url) } tryCatch({ parse_response(res) %>% copy_and_notify() }, error = function(e) { cli::cli_alert_danger(e) shiny::showNotification( ui = paste("Something went wrong:", e, sep = " "), duration = 3L, closeButton = TRUE, type = "message" ) }) }) # Expand links shiny::observeEvent(input$expand, { shiny::req(input$url) expander <- get_expander(provider_name = input$provider) # bitly_expand_link uses bitly_id instead of a short URL - strip protocol accordingly if (input$provider == "bit.ly") { short_url <- gsub(pattern = "https://", x = input$url, replacement = "") } else { short_url <- input$url } tryCatch({ expander(shorturl = short_url) %>% parse_response(expand = TRUE) %>% copy_and_notify() }, error = function(e) { cli::cli_alert_danger(e) shiny::showNotification( ui = paste("Something went wrong:", e, sep = " "), duration = 3L, closeButton = TRUE, type = "warning" ) }) }) shiny::observeEvent(input$done, { invisible(shiny::stopApp()) }) } viewer <- shiny::dialogViewer(dialogName = "URL shortener", width = 600, height = 400) shiny::runGadget(ui, server, viewer = viewer) } #' Shorten an URL from clipboard #' #' @export clipShortenerAddin <- function() { long_url <- clipr::read_clip() tryCatch({ short_url <- bitly_shorten_link(long_url = long_url) %>% parse_response() clipr::write_clip(short_url) cli::cli_alert_success(paste(short_url, "copied to clipboard", sep = " ")) }, error = function(err) { cli::cli_alert_danger(err) }) } #' Expand an URL from clipboard #' #' @export clipExpanderAddin <- function() { bitly_id <- clipr::read_clip() %>% gsub(pattern = "https://", replacement = "") tryCatch({ long_url <- bitly_expand_link(bitlink_id = bitly_id) %>% parse_response(expand = TRUE) clipr::write_clip(long_url) cli::cli_alert_success(paste(long_url, "copied to clipboard", sep = " ")) }, error = function(e) { cli::cli_alert_danger(e) }) } #' Select shortener function #' #' @param provider_name (str) url shortener provider #' @return A function #' #' @noRd get_shortener <- function(provider_name) { switch (provider_name, "bit.ly" = bitly_shorten_link_, "is.gd" = isgd_LinksShorten, "v.gd" = vgd_LinksShorten ) } #' Select expander function #' #' @inheritParams get_shortener #' @noRd get_expander <- function(provider_name) { switch (provider_name, "bit.ly" = bitly_expand_link_, "is.gd" = isgd_LinksExpand, "v.gd" = vgd_LinksExpand ) } #' Copy result to clipboard and fire notifications #' #' @noRd copy_and_notify <- function(url) { clipr::write_clip(url) shiny::showNotification( ui = paste(url, "copied to clipboard", sep = " "), duration = 3L, closeButton = TRUE, type = "message", ) cli::cli_alert_success(paste(url, "copied to clipboard", sep = " ")) } #' Parse response #' #' @description url shortener functions return results in different formats, #' this helper checks for length and grabs values accordingly. #' For example, \code{bitly_shorten_link} returns a \code{data.frame}. #' #' @noRd parse_response <- function(res, expand = FALSE) { if (length(res) > 1 && expand == FALSE) { res$link[[1]] } else if (length(res) > 1 && expand == TRUE) { res$long_url[[1]] } else { res } }
/scratch/gouwar.j/cran-all/cranData/urlshorteneR/R/addins.R
#' Fetch all Branded Short Domains #' #' BSDs is an acronym for branded short domains. This is a custom 15 #' character or less domain for bitlinks. This allows you to customize the domain to your brand. #' #' @seealso \url{https://dev.bitly.com/api-reference/#getBSDs} #' #' @inheritParams bitly_retrieve_links_grouped #' #' @import httr jsonlite #' @export bitly_bsds <- function(showRequestURL = F) { url_bsds <- "https://api-ssl.bitly.com/v4/bsds" query <- list(access_token = bitly_auth_access()) df_bsds <- doRequest("GET", url = url_bsds, queryParameters = query, showURL = showRequestURL) if (length(df_bsds$bsds) == 0) { warning("There are no branded domains. First create some in Bitly.com") } else { df_bsds <- data.frame(df_bsds, stringsAsFactors = FALSE) return(df_bsds) } } #' Branded Short Domains Group Overrides (Premium) #' #' @description #' Retrieves all account overrides matching specified group_guid and bsd query filters. #' #' @seealso \url{https://dev.bitly.com/api-reference/#getOverridesForGroups} #' #' @inheritParams bitly_user_info #' @inheritParams bitly_retrieve_links_grouped #' #' @examples #' \dontrun{ #' ui <- bitly_user_info(showRequestURL = TRUE) #' bsds_over <- bitly_bsds_overrides(group_id = ui$default_group_guid[1]) #' } #' #' @import httr jsonlite #' @export bitly_bsds_overrides <- function(group_id = NA, showRequestURL = F) { if (is.string(group_id)) { url_bsds_overrides <- paste0("https://api-ssl.bitly.com/v4/groups", group_id, "/overrides") } else { stop("group_id must not be empty string, NA or NULL") } query <- list(access_token = bitly_auth_access()) df_bsds_overrides <- doRequest("GET", url = url_bsds_overrides, queryParameters = query, showURL = showRequestURL) return(df_bsds_overrides) }
/scratch/gouwar.j/cran-all/cranData/urlshorteneR/R/bitly_bsd.R
#' Create Campaign (Premium) #' #' @description #' Create a new campaign #' #' @section Campaigns: #' Bitly Campaigns allows you to build and manage omnichannel campaigns. #' #' @param group_guid - a GUID for a Bitly group #' @param channel_guids - a list of strings #' @param description - description of campaign #' @param name - its name #' #' @inheritParams bitly_user_info #' @inheritParams bitly_retrieve_group #' @inheritParams bitly_retrieve_bitlinks_by_groups #' #' @seealso \url{https://dev.bitly.com/api-reference/#createCampaign} #' #' @examples #' \dontrun{ #' cc <- bitly_create_campaigns( #' group_guid = "testing", showRequestURL = TRUE, channel_guids = list("1", "2", "3"), #' description = "description", name = "name" #' ) #' } #' #' @import httr jsonlite lubridate #' #' @export bitly_create_campaigns <- function(group_guid = NULL, channel_guids = NULL, description = NULL, name = NULL, showRequestURL = T) { create_camp <- "https://api-ssl.bitly.com/v4/campaigns" body_req_query <- list(access_token = bitly_auth_access(), group_guid = group_guid, channel_guids = channel_guids, description = description, name = name ) df_create_camps <- doRequest("POST", create_camp, queryParameters = body_req_query, showURL = showRequestURL) df_create_camps <- data.frame(df_create_camps, stringsAsFactors = FALSE) df_create_camps$created <- ymd_hms(df_create_camps$created, tz = "UTC") df_create_camps$modified <- ymd_hms(df_create_camps$modified, tz = "UTC") return(df_create_camps) } #' Retrieve campaigns (Premium) #' #' @description #' Retrieve the campaigns for the current user #' #' @inheritParams bitly_create_campaigns #' @inheritParams bitly_user_info #' @inheritParams bitly_retrieve_group #' @inheritSection bitly_create_campaigns Campaigns #' #' @seealso \url{https://dev.bitly.com/api-reference/#getCampaigns} #' #' @examples #' \dontrun{ #' gc <- bitly_retrieve_campaigns(group_guid = "testing") #' } #' #' @import httr jsonlite lubridate #' @export bitly_retrieve_campaigns <- function(group_guid = NULL, showRequestURL = T) { get_camp <- "https://api-ssl.bitly.com/v4/campaigns" query <- list(access_token = bitly_auth_access(), group_guid = group_guid) df_get_camps <- doRequest("GET", get_camp, queryParameters = query, showURL = showRequestURL) df_get_camps <- data.frame(df_get_camps$campaigns, stringsAsFactors = FALSE) df_get_camps$created <- ymd_hms(df_get_camps$created, tz = "UTC") df_get_camps$modified <- ymd_hms(df_get_camps$modified, tz = "UTC") return(df_get_camps) } #' Create channel (Premium) #' #' @description #' Create a new channel #' #' @inheritParams bitly_retrieve_campaigns #' @inheritParams bitly_user_info #' @inheritParams bitly_retrieve_group #' @inheritParams bitly_create_campaigns #' @inheritParams bitly_add_cust_bitlink #' @inheritSection bitly_create_campaigns Campaigns #' #' @param modified - string | ISO_TIMESTAMP #' @param created - string | ISO TIMESTAMP #' @param campaign_guid - string | A GUID for a Bitly campaign #' @param guid - ID for a channel #' @seealso \url{https://dev.bitly.com/api-reference/#createChannel} #' #' @examples #' \dontrun{ #' gc <- bitly_create_channel(group_guid = "testing", ...) #' } #' #' @import httr jsonlite lubridate #' @export bitly_create_channel <- function(group_guid = NULL, guid = NULL, name = NULL, modified = NULL, created = NULL, campaign_guid = NULL, bitlink_id = NULL, showRequestURL = T) { create_channel <- "https://api-ssl.bitly.com/v4/channels" bitlinks <- list(bitlink_id = bitlink_id, campaign_guid = campaign_guid) body_req_query <- list(access_token = bitly_auth_access(), group_guid = group_guid, created = created, bitlinks = bitlinks, guid = guid, modified = modified, name = name ) df_create_channel <- doRequest("POST", create_channel, queryParameters = body_req_query, showURL = showRequestURL) df_create_channel <- data.frame(df_create_channel, stringsAsFactors = FALSE) df_create_channel$created <- ymd_hms(df_create_channel$created, tz = "UTC") df_create_channel$modified <- ymd_hms(df_create_channel$modified, tz = "UTC") return(df_create_channel) } #' Retrieve channels (Premium) #' #' @description #' Retrieve the channels available to a user #' #' @inheritParams bitly_create_channel #' @inheritParams bitly_create_campaigns #' @inheritParams bitly_user_info #' @inheritParams bitly_retrieve_group #' @inheritSection bitly_create_campaigns Campaigns #' #' @seealso \url{https://dev.bitly.com/api-reference/#getChannels} #' #' @examples #' \dontrun{ #' gc <- bitly_retrieve_channels(group_guid = "testing", campaign_guid = "test") #' } #' #' @import httr jsonlite lubridate #' @export bitly_retrieve_channels <- function(group_guid = NULL, campaign_guid = NULL, showRequestURL = T) { get_channels <- "https://api-ssl.bitly.com/v4/channels" query <- list(access_token = bitly_auth_access(), group_guid = group_guid, campaign_guid = campaign_guid) df_get_channels <- doRequest("GET", get_channels, queryParameters = query, showURL = showRequestURL) df_get_channels <- data.frame(df_get_channels$channels, stringsAsFactors = FALSE) df_get_channels$created <- ymd_hms(df_get_channels$created, tz = "UTC") df_get_channels$modified <- ymd_hms(df_get_channels$modified, tz = "UTC") return(df_get_channels) } #' Retrieve a Campaign #' #' @description #' Retrive details for a campaign #' #' @inheritParams bitly_create_channel #' @inheritParams bitly_create_campaigns #' @inheritParams bitly_user_info #' @inheritParams bitly_retrieve_group #' @inheritSection bitly_create_campaigns Campaigns #' #' @seealso \url{https://dev.bitly.com/api-reference/#getCampaign} #' #' @examples #' \dontrun{ #' gc <- bitly_retrieve_campaign(campaign_guid = "testing") #' } #' #' @import httr jsonlite lubridate #' @export bitly_retrieve_campaign <- function(campaign_guid = NULL, showRequestURL = T) { get_camp <- paste0("https://api-ssl.bitly.com/v4/campaigns/", campaign_guid) query <- list(access_token = bitly_auth_access(), campaign_guid = campaign_guid) df_get_camp <- doRequest("GET", get_camp, queryParameters = query, showURL = showRequestURL) df_get_camp <- data.frame(df_get_camp, stringsAsFactors = FALSE) df_get_camp$created <- ymd_hms(df_get_camp$created, tz = "UTC") df_get_camp$modified <- ymd_hms(df_get_camp$modified, tz = "UTC") return(df_get_camp) } #' Get a Channel (Premium) #' #' @description #' Get a channel's details #' #' @inheritParams bitly_create_channel #' @inheritParams bitly_create_campaigns #' @inheritParams bitly_user_info #' @inheritParams bitly_retrieve_group #' @inheritSection bitly_create_campaigns Campaigns #' @inheritParams bitly_retrieve_bitlinks_by_groups #' @param channel_guid - GUID of a target channel #' @seealso \url{https://dev.bitly.com/api-reference/#getChannel} #' #' @examples #' \dontrun{ #' gc <- bitly_retrieve_channel(channel_guid = "testing") #' } #' #' @import httr jsonlite lubridate #' @export bitly_retrieve_channel <- function(channel_guid = NULL, showRequestURL = T) { get_channel <- paste0("https://api-ssl.bitly.com/v4/channels/", channel_guid) query <- list(access_token = bitly_auth_access(), channel_guid = channel_guid) df_get_channel <- doRequest("GET", get_channel, queryParameters = query, showURL = showRequestURL) df_get_channel <- data.frame(df_get_channel, stringsAsFactors = FALSE) df_get_channel$created <- ymd_hms(df_get_channel$created, tz = "UTC") df_get_channel$modified <- ymd_hms(df_get_channel$modified, tz = "UTC") return(df_get_channel) } #' Update A Channel (Premium) #' #' @description #' Update an existing Channel #' #' @inheritSection bitly_create_campaigns Campaigns #' #' @inheritParams bitly_create_channel #' @inheritParams bitly_create_campaigns #' @inheritParams bitly_user_info #' @inheritParams bitly_retrieve_group #' @inheritParams bitly_create_channel #' #' @seealso \url{https://dev.bitly.com/api-reference/#updateCampaign} #' #' @examples #' \dontrun{ #' cc <- bitly_update_campaign( #' group_guid = "", channel_guids = list("1", "2", "3"), #' description = "description", name = "name" #' ) #' } #' #' @import httr jsonlite lubridate #' #' @export bitly_update_campaign <- function(campaign_guid = NULL, group_guid = NULL, channel_guids = NULL, description = NULL, name = NULL, showRequestURL = T) { update_campaign <- paste0("https://api-ssl.bitly.com/v4/campaigns", campaign_guid) query <- list(access_token = bitly_auth_access()) body_req_query <- list(group_guid = group_guid, channel_guids = channel_guids, description = description, name = name ) df_update_camps <- doRequest("PATCH", update_campaign, queryParameters = query, patch_body = body_req_query, showURL = showRequestURL) df_update_camps <- data.frame(df_update_camps, stringsAsFactors = FALSE) df_update_camps$created <- ymd_hms(df_update_camps$created, tz = "UTC") df_update_camps$modified <- ymd_hms(df_update_camps$modified, tz = "UTC") return(df_update_camps) } #' Update A Channel (Premium) #' #' @description #' Update an existing Channel #' #' @inheritSection bitly_create_campaigns Campaigns #' #' @inheritParams bitly_create_channel #' @inheritParams bitly_create_campaigns #' @inheritParams bitly_user_info #' @inheritParams bitly_retrieve_group #' @inheritParams bitly_retrieve_bitlinks_by_groups #' @inheritParams bitly_retrieve_channel #' @seealso \url{https://dev.bitly.com/api-reference/#updateChannel} #' #' @examples #' \dontrun{ #' uc <- bitly_update_channel(channel_guid = "testing", group_guid = "", name = "name") #' } #' #' @import httr jsonlite lubridate #' #' @export bitly_update_channel <- function(channel_guid = NULL, group_guid = NULL, guid = NULL, name = NULL, modified = NULL, created = NULL, campaign_guid = NULL, bitlink_id = NULL, showRequestURL = T) { update_channels <- paste0("https://api-ssl.bitly.com/v4/channels", channel_guid) query <- list(access_token = bitly_auth_access()) body_req_query <- list(group_guid = group_guid, guid = guid, modified = modified, name = name, created = created, bitlinks = list(bitlink_id = bitlink_id, campaign_guid = campaign_guid) ) df_update_camp <- doRequest("PATCH", update_channels, queryParameters = query, patch_body = body_req_query, showURL = showRequestURL) df_update_camp <- data.frame(df_update_camp, stringsAsFactors = FALSE) df_update_camp$created <- ymd_hms(df_update_camp$created, tz = "UTC") df_update_camp$modified <- ymd_hms(df_update_camp$modified, tz = "UTC") return(df_update_camp) }
/scratch/gouwar.j/cran-all/cranData/urlshorteneR/R/bitly_camp.R
#' @title Add Custom Bitlink (Premium) #' #' @description #' Add a Keyword to a Bitlink #' #' @seealso \url{https://dev.bitly.com/api-reference/#addCustomBitlink} #' @inheritParams bitly_add_cust_bitlink #' #' @param bitlink_id - string #' @inheritParams bitly_retrieve_destination_metrics #' @inheritParams bitly_retrieve_metrics_by_referrers #' #' @section Custom Bitlinks: #' Custom Bitlinks have both a branded short domain (BSD) AND a customized backend. #' For example, bit.ly/bitlinks would not be considered a Custom Bitlink because it #' does not have a branded short domain. es.pn/2yxklu would not be considered a custom #' Bitlink because while it has a branded short domain, it doesn't have a customized #' backhalf. An example of a link that would live in this section is es.pn/SuperBowl #' #' @examples #' \dontrun{ #' bitly_add_cust_bitlink(custom_bitlink = "es.pn/SuperBowl", bitlink_id = "") #' } #' #' @import httr jsonlite lubridate #' #' @export bitly_add_cust_bitlink <- function(bitlink_id = NULL, custom_bitlink = NULL, showRequestURL = FALSE) { cust_post_url <- "https://api-ssl.bitly.com/v4/custom_bitlinks" body_req_query <- list(access_token = bitly_auth_access(), bitlink_id = bitlink_id, custom_bitlink = custom_bitlink ) df_add_keywords <- doRequest("POST", cust_post_url, queryParameters = body_req_query, showURL = showRequestURL) return(df_add_keywords) } #' Get Metrics for a Custom Bitlink by destination (Premium) #' @seealso \url{https://dev.bitly.com/api-reference/#getCustomBitlinkMetricsByDestination} #' #' @description #' Get Click Metrics for a Custom Bitlink by historical Bitlink destinations #' #' @param custom_bitlink - A Custom Bitlink made of the domain and keyword #' #' @inheritParams bitly_retrieve_group_pref #' #' @examples #' \dontrun{ #' bitly_retrieve_destination_metrics(custom_bitlink = "es.pn/SuperBowl") #' } #' #' @import httr jsonlite lubridate #' #' @export bitly_retrieve_destination_metrics <- function(custom_bitlink = NULL, showRequestURL = FALSE) { if (is.string(custom_bitlink)) { metrics_url <- paste0("https://api-ssl.bitly.com/v4/custom_bitlinks/", custom_bitlink, "/clicks_by_destination") } else { stop("custom_bitlink must not be empty string, NA or NULL") } query <- list(access_token = bitly_auth_access(), custom_bitlink = custom_bitlink) df_cust_metrics <- doRequest("GET", url = metrics_url, queryParameters = query, showURL = showRequestURL) df_cust_metrics <- data.frame(df_cust_metrics, stringsAsFactors = FALSE) return(df_cust_metrics) } #' Update Custom Bitlink (Premium) #' #' @description #' Move a Keyword to a different Bitlink #' #' @inheritParams bitly_add_cust_bitlink #' #' @seealso \url{https://dev.bitly.com/api-reference/#updateCustomBitlink} #' #' @examples #' \dontrun{ #' bitly_update_cust_bitlink(custom_bitlink = "es.pn/SuperBowl", bitlink_id = "") #' } #' #' @import httr jsonlite lubridate #' #' @export bitly_update_cust_bitlink <- function(custom_bitlink = NULL, bitlink_id = NULL, showRequestURL = FALSE) { if (is.string(custom_bitlink)) { patch_url <- paste0("https://api-ssl.bitly.com/v4/custom_bitlinks/", custom_bitlink) } else { stop("custom_bitlink must not be empty string, NA or NULL") } query <- list(access_token = bitly_auth_access()) body_req_query <- list(bitlink_id = bitlink_id) df_update_cost_link <- doRequest("PATCH", patch_url, queryParameters = query, patch_body = body_req_query, showURL = showRequestURL) return(df_update_cost_link) } #' Retrieve Custom Bitlink (Premium) #' #' @description #' Retrieve the details and history of a Custom Bitlink #' #' @inheritParams bitly_add_cust_bitlink #' #' @seealso \url{https://dev.bitly.com/api-reference/#getCustomBitlink} #' #' @examples #' \dontrun{ #' bitly_retrieve_cust_bitlink(custom_bitlink = "es.pn/SuperBowl") #' } #' #' @import httr jsonlite lubridate #' #' @export bitly_retrieve_cust_bitlink <- function(custom_bitlink = NULL, showRequestURL = FALSE) { if (is.string(custom_bitlink)) { get_url <- paste0("https://api-ssl.bitly.com/v4/custom_bitlinks/", custom_bitlink) } else { stop("custom_bitlink must not be empty string, NA or NULL") } query <- list(access_token = bitly_auth_access(), custom_bitlink = custom_bitlink) df_cust_metrics <- doRequest("GET", url = get_url, queryParameters = query, showURL = showRequestURL) return(df_cust_metrics) } #' Get Clicks for a Custom Bitlink's Entire History (Premium) #' #' @description #' Returns the click counts for the specified link. This returns an array with clicks based on a date. #' #' @inheritParams bitly_add_cust_bitlink #' #' @seealso \url{https://dev.bitly.com/api-reference/#getClicksForCustomBitlink} #' #' @examples #' \dontrun{ #' bitly_retrieve_cust_bitlink_clicks_history(custom_bitlink = "es.pn/SuperBowl") #' } #' #' @import httr jsonlite lubridate #' #' @export bitly_retrieve_cust_bitlink_clicks_history <- function(custom_bitlink = NULL, showRequestURL = FALSE) { if (is.string(custom_bitlink)) { get_url <- paste0("https://api-ssl.bitly.com/v4/custom_bitlinks/", custom_bitlink, "/clicks") } else { stop("custom_bitlink must not be empty string, NA or NULL") } query <- list(access_token = bitly_auth_access(), custom_bitlink = custom_bitlink) df_cust_metrics_history <- doRequest("GET", url = get_url, queryParameters = query, showURL = showRequestURL) return(df_cust_metrics_history) } #' Get Metrics for a Custom Bitlink by Destination (Premium) #' #' @description #' Returns click metrics for the specified link by its historical destinations. #' #' @inheritParams bitly_add_cust_bitlink #' #' @seealso \url{https://dev.bitly.com/api-reference/#getCustomBitlinkMetricsByDestination} #' #' @examples #' \dontrun{ #' bitly_retrieve_cust_bitlink_metrics_destination(custom_bitlink = "es.pn/SuperBowl") #' } #' #' @import httr jsonlite lubridate #' #' @export bitly_retrieve_cust_bitlink_metrics_destination <- function(custom_bitlink = NULL, showRequestURL = FALSE) { if (is.string(custom_bitlink)) { get_url <- paste0("https://api-ssl.bitly.com/v4/custom_bitlinks/", custom_bitlink, "/clicks_by_destination") } else { stop("custom_bitlink must not be empty string, NA or NULL") } query <- list(access_token = bitly_auth_access(), custom_bitlink = custom_bitlink) df_cust_metrics_dest <- doRequest("GET", url = get_url, queryParameters = query, showURL = showRequestURL) return(df_cust_metrics_dest) }
/scratch/gouwar.j/cran-all/cranData/urlshorteneR/R/bitly_custom_links.R
#' Retrieve Group Preferences #' #' Retrieve preferences for a specific group #' #' @seealso \url{https://dev.bitly.com/api-reference#getGroupPreferences} #' #' @inheritSection bitly_retrieve_group Group #' @inheritParams bitly_retrieve_sorted_links #' @param group_id - the group id the user belongs to #' #' @examples #' \dontrun{ #' ui <- bitly_user_info(showRequestURL = TRUE) #' group_pref <- bitly_retrieve_group_pref(group_id = ui$default_group_guid[1]) #' } #' @import httr jsonlite assertthat #' #' @export bitly_retrieve_group_pref <- function(group_id = NA, showRequestURL = F) { if (is.string(group_id)) { gr_pref_url <- paste0("https://api-ssl.bitly.com/v4/groups/", group_id, "/preferences") } else { stop("group_id must not be empty string, NA or NULL") } query <- list(access_token = bitly_auth_access()) df_group_prefs <- doRequest("GET", url = gr_pref_url, queryParameters = query, showURL = showRequestURL) df_group_prefs <- data.frame(df_group_prefs, stringsAsFactors = FALSE) return(df_group_prefs) } #' Update Group Preferences #' #' Update preferences for a specific group #' #' @seealso \url{https://dev.bitly.com/api-reference#updateGroupPreferences} #' #' @inheritSection bitly_retrieve_group Group #' #' @inheritParams bitly_retrieve_sorted_links #' @inheritParams bitly_retrieve_group_pref #' #' @param domain_pref - string #' #' @examples #' \dontrun{ #' ui <- bitly_user_info(showRequestURL = TRUE) #' group_pref <- bitly_update_group_pref(group_id = ui$default_group_guid[1]) #' } #' @import httr jsonlite assertthat #' #' @export bitly_update_group_pref <- function(group_id = NA, domain_pref = NA, showRequestURL = F) { if (is.string(group_id)) { gr_pref_url_up <- paste0("https://api-ssl.bitly.com/v4/groups/", group_id, "/preferences") } else { stop("group_id must not be empty string, NA or NULL") } query <- list(access_token = bitly_auth_access()) body_upd <- list(group_guid = group_id, domain_preference = domain_pref) df_update_pref <- doRequest("PATCH", url = gr_pref_url_up, queryParameters = query, patch_body = body_upd, showURL = showRequestURL) df_update_pref <- data.frame(df_update_pref, stringsAsFactors = FALSE) return(df_update_pref) } #' Retrieve Bitlinks by Group #' #' @description #' Retrieve a paginated collection of Bitlinks for a Group #' #' @param page - Default: 1 | Integer specifying the numbered result at which to start #' @param keyword - Custom keyword to filter on history entries #' @param modified_after - Timestamp as an integer unix epoch, #' see \code{\link[lubridate]{as_datetime}} or \code{anytime}'s \code{as_datetime} #' @param created_after - Timestamp as an integer unix epoch #' @param created_before - Timestamp as an integer unix epoch #' @param search_query - string | the value that you would like to search #' @param archived - string | Default: "off" | Enum:"on" "off" "both" | Whether or not to include archived bitlinks #' @param deeplinks - string | Default: "both" | Enum:"on" "off" "both" | Filter to only Bitlinks that contain deeplinks #' @param domain_deeplinks - string | Default: "both" | Enum:"on" "off" "both" | Filter to only Bitlinks #' that contain deeplinks configured with a custom domain #' @param campaign_guid - Filter to return only links for the given campaign GUID, can be provided #' @param channel_guid - Filter to return only links for the given channel GUID, #' can be provided, overrides all other parameters #' @param custom_bitlink - string | Default: "both" | Enum:"on" "off" "both" #' @param tags - Array of string | filter by given tags #' @param encoding_login - Array of string | Filter by the login of the authenticated user that created the Bitlink #' #' @inheritSection bitly_retrieve_group Group #' @inheritParams bitly_user_info #' @inheritParams bitly_retrieve_group #' @inheritParams bitly_retrieve_sorted_links #' @inheritParams bitly_update_group_pref #' @seealso \url{https://dev.bitly.com/api-reference#getBitlinksByGroup} #' #' @import httr jsonlite assertthat lubridate #' #' @examples #' \dontrun{ #' ui <- bitly_user_info(showRequestURL = TRUE) #' rg <- bitly_retrieve_links_grouped(group_id = ui$default_group_guid[1]) #' } #' #' @export bitly_retrieve_links_grouped <- function(group_id = NA, keyword = NULL, search_query = NULL, created_before = NULL, created_after = NULL, modified_after = NULL, archived = "off", deeplinks = "both", domain_deeplinks = "both", campaign_guid = NULL, channel_guid = NULL, custom_bitlink = "both", tags = NULL, encoding_login = NULL, page = 1, size = 50, showRequestURL = F) { if (is.string(group_id)) { grouped_links_url <- paste0("https://api-ssl.bitly.com/v4/groups/", group_id, "/bitlinks") } else { stop("group_id must not be empty string, NA or NULL") } query <- list(access_token = bitly_auth_access(), size = size, page = page, keyword = keyword, query = search_query, created_before = created_before, created_after = created_after, modified_after = modified_after, archived = archived) df_grouped_links <- doRequest("GET", url = grouped_links_url, queryParameters = query, showURL = showRequestURL) return(df_grouped_links) } #' @title Retrieve Tags by Group #' #' @description #' Retrieve the currently used tags for a group #' #' @seealso \url{https://dev.bitly.com/api-reference#getGroupTags} #' #' @import httr jsonlite assertthat #' #' @inheritSection bitly_retrieve_group Group #' @inheritParams bitly_retrieve_links_grouped #' @inheritParams bitly_user_info #' #' @examples #' \dontrun{ #' ui <- bitly_user_info(showRequestURL = TRUE) #' rg <- bitly_retrieve_tags(group_id = ui$default_group_guid[1]) #' } #' @export bitly_retrieve_tags <- function(group_id = NA, showRequestURL = F) { if (is.string(group_id)) { tags_url <- paste0("https://api-ssl.bitly.com/v4/groups/", group_id, "/tags") } else { stop("group_id must not be empty string, NA or NULL") } query <- list(access_token = bitly_auth_access()) df_groups_details <- doRequest("GET", tags_url, query, showURL = showRequestURL) df_groups_details <- data.frame(df_groups_details, stringsAsFactors = FALSE) return(df_groups_details) } #' Get Click Metrics for a Group by countries #' #' This endpoint will return metrics about the countries referring click traffic rolled up to a Group #' #' @seealso \url{https://dev.bitly.com/api-reference#getGroupMetricsByCountries} #' #' @inheritSection bitly_retrieve_group Group #' #' @inheritParams bitly_user_info #' @inheritParams bitly_retrieve_links_grouped #' @import httr jsonlite assertthat lubridate #' #' @examples #' \dontrun{ #' ui <- bitly_user_info(showRequestURL = TRUE) #' rg <- bitly_retrieve_group_click_metrics_by_countries(group_id = ui$default_group_guid[1]) #' } #' @export bitly_retrieve_group_click_metrics_by_countries <- function(group_id = NA, showRequestURL = F) { if (is.string(group_id)) { metrics_url <- paste0("https://api-ssl.bitly.com/v4/groups/", group_id, "/countries") } else { stop("group_id must not be empty string, NA or NULL") } query <- list(access_token = bitly_auth_access()) df_click_metrics <- doRequest("GET", metrics_url, query, showURL = showRequestURL) df_click_metrics <- data.frame(df_click_metrics, stringsAsFactors = FALSE) df_click_metrics$unit_reference <- ymd_hms(df_click_metrics$unit_reference, tz = "UTC") return(df_click_metrics) } #' Get Click Metrics for a specified group by devices (Premium) #' #' Returns the device types generating click traffic to the specified group's links. #' Requires a premium account. #' #' @seealso \url{https://dev.bitly.com/api-reference/#getGroupMetricsByDevices} #' #' @inheritSection bitly_retrieve_group Group #' #' @inheritParams bitly_user_info #' @inheritParams bitly_retrieve_links_grouped #' @import httr jsonlite assertthat lubridate #' #' @examples #' \dontrun{ #' ui <- bitly_user_info(showRequestURL = TRUE) #' rg <- bitly_retrieve_group_click_metrics_by_devices(group_id = ui$default_group_guid[1]) #' } #' @export bitly_retrieve_group_click_metrics_by_devices <- function(group_id = NA, showRequestURL = F) { if (is.string(group_id)) { metrics_devices_url <- paste0("https://api-ssl.bitly.com/v4/groups/", group_id, "/cities") } else { stop("group_id must not be empty string, NA or NULL") } query <- list(access_token = bitly_auth_access()) df_click_metrics_devices <- doRequest("GET", metrics_devices_url, query, showURL = showRequestURL) df_click_metrics_devices <- data.frame(df_click_metrics_devices, stringsAsFactors = FALSE) df_click_metrics_devices$unit_reference <- ymd_hms(df_click_metrics_devices$unit_reference, tz = "UTC") return(df_click_metrics_devices) } #' Get Click Metrics for a specified group by city (Premium) #' #' Returns the geographic origins of click traffic by city for the specified group. #' Requires a premium account. #' #' @seealso \url{https://dev.bitly.com/api-reference/#getGroupMetricsByCities} #' #' @inheritSection bitly_retrieve_group Group #' #' @inheritParams bitly_user_info #' @inheritParams bitly_retrieve_links_grouped #' @import httr jsonlite assertthat lubridate #' #' @examples #' \dontrun{ #' ui <- bitly_user_info(showRequestURL = TRUE) #' rg <- bitly_retrieve_group_click_metrics_by_cities(group_id = ui$default_group_guid[1]) #' } #' @export bitly_retrieve_group_click_metrics_by_cities <- function(group_id = NA, showRequestURL = F) { if (is.string(group_id)) { metrics_cities_url <- paste0("https://api-ssl.bitly.com/v4/groups/", group_id, "/cities") } else { stop("group_id must not be empty string, NA or NULL") } query <- list(access_token = bitly_auth_access()) df_click_metrics_cities <- doRequest("GET", metrics_cities_url, query, showURL = showRequestURL) df_click_metrics_cities <- data.frame(df_click_metrics_cities, stringsAsFactors = FALSE) df_click_metrics_cities$unit_reference <- ymd_hms(df_click_metrics_cities$unit_reference, tz = "UTC") return(df_click_metrics_cities) } #' Get Click Metrics for a Group by referring networks #' #' This endpoint will return metrics about the referring network click traffic rolled up to a Group #' #' @seealso \url{https://dev.bitly.com/api-reference#GetGroupMetricsByReferringNetworks} #' #' @inheritSection bitly_retrieve_group Group #' #' @inheritParams bitly_user_info #' @inheritParams bitly_retrieve_links_grouped #' @import httr jsonlite assertthat lubridate #' #' @examples #' \dontrun{ #' ui <- bitly_user_info(showRequestURL = TRUE) #' rg <- bitly_retrieve_group_click_metrics_by_ref_networks(group_id = ui$default_group_guid[1]) #' } #' @export bitly_retrieve_group_click_metrics_by_ref_networks <- function(group_id = NA, showRequestURL = F) { if (is.string(group_id)) { metrics_ref_net_url <- paste0("https://api-ssl.bitly.com/v4/groups/", group_id, "/referring_networks") } else { stop("group_id must not be empty string, NA or NULL") } query <- list(access_token = bitly_auth_access()) df_click_metrics_net <- doRequest("GET", metrics_ref_net_url, query, showURL = showRequestURL) if(length(df_click_metrics_net$metrics) == 0) { stop("Metrics are empty.") } df_click_metrics_net <- data.frame(df_click_metrics_net, stringsAsFactors = FALSE) df_click_metrics_net$unit_reference <- ymd_hms(df_click_metrics_net$unit_reference, tz = "UTC") return(df_click_metrics_net) } #' Retrieve Group Shorten Counts #' #' Get all the shorten counts for a specific group #' #' @seealso \url{https://dev.bitly.com/api-reference#getGroupShortenCounts} #' #' @inheritSection bitly_retrieve_group Group #' #' @inheritParams bitly_user_info #' @inheritParams bitly_retrieve_links_grouped #' @import httr jsonlite assertthat lubridate #' #' @examples #' \dontrun{ #' ui <- bitly_user_info(showRequestURL = TRUE) #' rg <- bitly_retrieve_group_shorten_counts(group_id = ui$default_group_guid[1]) #' } #' @export bitly_retrieve_group_shorten_counts <- function(group_id = NA, showRequestURL = F) { if (is.string(group_id)) { gr_short_counts_url <- paste0("https://api-ssl.bitly.com/v4/groups/", group_id, "/shorten_counts") } else { stop("group_id must not be empty string, NA or NULL") } query <- list(access_token = bitly_auth_access()) df_short_co <- doRequest("GET", gr_short_counts_url, query, showURL = showRequestURL) df_short_co <- data.frame(df_short_co, stringsAsFactors = FALSE) df_short_co$unit_reference <- ymd_hms(df_short_co$unit_reference, tz = "UTC") return(df_short_co) } #' @title Retrieve a list of all groups #' #' @description #' Retrive details for all groups that a user belongs to. #' #' @param organization_id - an optional string parameter | A GUID for a Bitly organization #' #' @seealso \url{https://dev.bitly.com/api-reference#getGroups} #' #' @import httr jsonlite assertthat #' #' @inheritSection bitly_retrieve_group Group #' #' @inheritParams bitly_user_info #' @inheritParams bitly_retrieve_links_grouped #' @examples #' \dontrun{ #' rg <- bitly_retrieve_groups("") # will still work ok #' } #' @export bitly_retrieve_groups <- function(organization_id = NULL, showRequestURL = F) { groups_url <- "https://api-ssl.bitly.com/v4/groups/" query <- list(access_token = bitly_auth_access(), organization_guid = organization_id) df_groups_details <- doRequest("GET", groups_url, query, showURL = showRequestURL) df_groups_details <- data.frame(df_groups_details, stringsAsFactors = FALSE) return(df_groups_details) } #' Retrieve Sorted Bitlinks for Group #' #' @description #' This will retrieve a paginated response for Bitlinks that are sorted for the Group. #' This method returns a combined object which end-user (you) have to further process for your needs. #' #' @param to_sort_by - a required string | Enum: "clicks" | The type of sorting that you would like to do #' @param unit - string | Default: "day", Enum: "minute" "hour" "day" "week" "month" | A unit of time #' @param units - integer | Default: -1 | An integer representing the time units to #' query data for. pass -1 to return all units of time. #' @param unit_reference - string | An ISO-8601 timestamp, indicating the most recent time for #' which to pull metrics. Will default to current time. #' @param size - string | Default: 50 | The quantity of items to be be returned #' #' @inheritSection bitly_retrieve_group Group #' @inheritParams bitly_user_info #' @inheritParams bitly_retrieve_group #' @inheritParams bitly_retrieve_links_grouped #' @seealso \url{https://dev.bitly.com/api-reference#getSortedBitlinks} #' #' @import httr jsonlite lubridate #' #' @examples #' \dontrun{ #' ui <- bitly_user_info(showRequestURL = TRUE) #' rg <- bitly_retrieve_sorted_links(group_id = ui$default_group_guid[1]) #' } #' #' @export bitly_retrieve_sorted_links <- function(group_id = NA, to_sort_by = "clicks", unit = "day", units = -1, unit_reference = NULL, size = 50, showRequestURL = F) { if (is.string(group_id) && is.string(to_sort_by)) { sorted_links_group_url <- paste0("https://api-ssl.bitly.com/v4/groups/", group_id, "/bitlinks/", to_sort_by) } else { stop("group_id and to_sort_by must not be empty string, NA or NULL") } query <- list(access_token = bitly_auth_access(), unit = unit, units = units, unit_reference = unit_reference, size = size) df_sorted_links <- doRequest("GET", url = sorted_links_group_url, queryParameters = query, showURL = showRequestURL) df_sorted_links2 <- cbind( data.frame(df_sorted_links$links, stringsAsFactors = FALSE), data.frame(df_sorted_links$sorted_links, stringsAsFactors = FALSE)) return(df_sorted_links2) } #' Update a Group #' #' Update the details of a group #' #' @seealso \url{https://dev.bitly.com/api-reference#updateGroup} #' #' @inheritSection bitly_retrieve_group Group #' #' @seealso [bitly_update_user()] #' #' @inheritParams bitly_retrieve_sorted_links #' @inheritParams bitly_update_user #' @inheritParams bitly_retrieve_groups #' @inheritParams bitly_retrieve_links_grouped #' @examples #' \dontrun{ #' ui <- bitly_user_info(showRequestURL = TRUE) #' up_group <- bitly_update_group(group_id = ui$default_group_guid[1], name = "New Group Name", #' organization_id = "asd") #' } #' @import httr jsonlite assertthat lubridate #' #' @export bitly_update_group <- function(group_id = NA, name = NA, organization_id = NA, showRequestURL = F) { if (is.string(group_id)) { upd_group_url <- paste0("https://api-ssl.bitly.com/v4/groups/", group_id) } else { stop("group_id must not be empty string, NA or NULL") } query <- list(access_token = bitly_auth_access()) update_body <- list(name = name, organization_guid = organization_id) df_update_pref <- doRequest("PATCH", url = upd_group_url, queryParameters = query, patch_body = update_body, showURL = showRequestURL) df_update_pref <- data.frame(t(unlist(df_update_pref)), stringsAsFactors = FALSE) df_update_pref$created <- ymd_hms(df_update_pref$created, tz = "UTC") df_update_pref$modified <- ymd_hms(df_update_pref$modified, tz = "UTC") return(df_update_pref) } #' @title Retrieve a single group #' #' @description #' Retrive details for a specific group that a user belongs to. #' #' @section Group: #' Groups are a subdivision within an organization. A user will belong to a group within an organization. #' Most actions on our API will be on behalf of a group. For example, when you #' shorten a link, it will be on behalf of a user and a group. #' #' @seealso \url{https://dev.bitly.com/api-reference#getGroup} #' #' @param group_id - a required string | A GUID for a Bitly group #' #' @inheritParams bitly_user_info #' @inheritParams bitly_retrieve_links_grouped #' @import httr jsonlite assertthat #' #' @examples #' \dontrun{ #' ui <- bitly_user_info(showRequestURL = TRUE) #' rg <- bitly_retrieve_group(group_guid = ui$default_group_guid) #' } #' #' @export bitly_retrieve_group <- function(group_id = NA, showRequestURL = F) { if (is.string(group_id)) { group_url <- paste0("https://api-ssl.bitly.com/v4/groups/", group_id) } else { stop("group_id must not be empty string, NA or NULL") } query <- list(access_token = bitly_auth_access(), group_guid = group_id) df_group_details <- doRequest("GET", url = group_url, queryParameters = query, showURL = showRequestURL) df_group_details <- data.frame(t(unlist(df_group_details)), stringsAsFactors = FALSE) return(df_group_details) }
/scratch/gouwar.j/cran-all/cranData/urlshorteneR/R/bitly_groups.R
#' @title Create a short Bitlink #' #' @description See \url{https://dev.bitly.com/docs/getting-started/rate-limits} and #' \url{https://dev.bitly.com/api-reference/#createFullBitlink} #' Convert a long url to a Bitlink and set additional parameters. #' #' @param long_url - required, a long URL to be shortened (example: https://www.idnes.cz). #' Must contain http/https #' @param domain - (optional) the short domain to use; either bit.ly, j.mp, or bitly.com or #' a custom short domain. The default for this parameter is the short domain selected by each #' user in their bitly account settings. Passing a specific domain via this parameter will override #' the default settings. #' @param title - title of the bitlink #' @param tags - Array of string, use e.g. \code{c("test1", "test2")} #' @param showRequestURL - show URL which has been build and requested from server. For debug #' purposes. #' @param deeplinks_list - a list containing parameters below #' @param app_uri_path - app_uri_path #' @param install_type - install_type #' @param install_url - install_url #' @param app_id - app_id #' #' @inheritParams bitly_create_campaigns #' #' @note Look in the vignette for bulk shortening of URLs. Each call of this function == 1 API call. #' Take that into consideration due to limits etc. #' @note The bitly API does not support shortening more than one long URL with a single API call. #' Meaning 1 Long URL = 1 Function call. #' @note Long URLs should be URL-encoded. You can not include a longUrl in the request #' that has &, ?, #, or other reserved parameters without first encoding it. #' @note The default value for the domain parameter is selected by each user from within their bitly #' account settings at <https://app.bitly.com/settings/api/>. #' @note Long URLs should not contain spaces: any longUrl with spaces will be rejected. All spaces #' should be either percent encoded %20 or plus encoded +. Note that tabs, newlines and trailing #' spaces are all indications of errors. Please remember to strip leading and trailing whitespace #' from any user input before shortening. #' #' @return id - a short bitly identifier for long_url which is unique to the given account. #' @return long_url - This may not always be equal to the URL requested, as some URL normalization #' may occur (e.g., due to encoding differences, or case #' differences in the domain). This long_url will always be functionally identical the the request #' parameter. #' @return link - an bitly id with http(s) prefix #' @import httr jsonlite lubridate #' #' @examples #' \dontrun{ #' bitly_create_bitlink(long_url = "http://slovnik.seznam.cz/") #' } #' #' @export bitly_create_bitlink <- function(long_url = NULL, domain = "bit.ly", title = NULL, tags = NULL, group_guid = NULL, deeplinks_list = list(app_uri_path = NULL, install_type = NULL, install_url = NULL, app_id = NULL), showRequestURL = FALSE) { links_shorten_url <- "https://api-ssl.bitly.com/v4/bitlinks" body_req_query <- list(access_token = bitly_auth_access(), domain = domain, long_url = long_url) if (!length(deeplinks_list$app_uri_path) == 0 || !length(deeplinks_list$install_type) == 0 || !length(deeplinks_list$install_url) == 0 || !length(deeplinks_list$app_id) == 0) { body_req_query$deeplinks <- deeplinks_list } if (length(title) >= 1) { body_req_query$title <- title } if (length(tags) >= 1) { body_req_query$tags <- tags } if (length(group_guid) >= 1) { body_req_query$group_guid <- group_guid } body_req_query_cleaned <- toJSON(body_req_query, auto_unbox = T) df_link_shorten <- doRequest("POST", links_shorten_url, queryParameters = body_req_query_cleaned, showURL = showRequestURL) df_link_shorten <- data.frame(t(do.call(rbind, df_link_shorten)), stringsAsFactors = F) df_link_shorten$created_at <- now("UTC") return(df_link_shorten) } #' @title Get Metrics for a Bitlink by referring domains #' #' @description This endpoint will rollup the click counts to a referrer about a single Bitlink. #' #' @seealso See \url{https://dev.bitly.com/api-reference/#getMetricsForBitlinkByReferringDomains} #' #' @inheritParams bitly_retrieve_sorted_links #' #' @return facet - string | One of "countries" "referrers" "referrers_by_domain" #' "referring_domains" "referring_networks" "shorten_counts" #' #' @param bitlink - required, a Bitlink made of the domain and hash #' #' @import httr jsonlite lubridate #' #' @examples #' \dontrun{ #' bitly_user_metrics_referring_domains(bitlink = "cnn.it/2HomWGB", unit = "month", units = -1, #' size = 100) #' } #' #' @export bitly_user_metrics_referring_domains <- function(bitlink = NULL, unit = "day", units = -1, size = 50, unit_reference = NULL, showRequestURL = FALSE) { user_metrics_referring_domains_url <- paste0("https://api-ssl.bitly.com/v4/bitlinks/", bitlink, "/referring_domains") query <- list(access_token = bitly_auth_access(), bitlink = bitlink, unit = unit, units = units, size = size, unit_reference = unit_reference) df_user_metrics_referring_domains <- doRequest("GET", user_metrics_referring_domains_url, query, showURL = showRequestURL) df_user_metrics_referring_domains$unit_reference <- ymd_hms(df_user_metrics_referring_domains$unit_reference, tz = "UTC") if (length(df_user_metrics_referring_domains$metrics) == 0) { df_user_metrics_referring_domains <- NULL message("The domain has no metrics available. Has it been shared ?") } return(df_user_metrics_referring_domains) } #' @title Expand a Bitlink #' #' @description See \url{https://dev.bitly.com/api-reference/#expandBitlink} #' This endpoint returns public information for a Bitlink. #' #' @inheritParams bitly_user_metrics_referring_domains #' @inheritParams bitly_create_channel #' @return long_url - a full URL to which bitlink points to #' #' @examples #' \dontrun{ #' bitly_expand_link(bitlink_id = "bit.ly/DPetrov") #' bitly_expand_link(bitlink_id = "on.natgeo.com/1bEVhwE") #' #' ## manyHashes <- list("bit.ly/DPetrov", "bit.ly/1QU8CFm", "bit.ly/1R1LPSE", "bit.ly/1LNqqva") #' ## for (u in 1:length(manyHashes)) { #' ## print(bitly_expand_link(bitlink_id = manyHashes[[u]], showRequestURL = TRUE)) #' ## } #' } #' @import httr jsonlite lubridate #' @export bitly_expand_link <- function(bitlink_id = NULL, showRequestURL = FALSE) { links_expand_url <- "https://api-ssl.bitly.com/v4/expand" if (!is.null(bitlink_id)) { body_req_query <- list(access_token = bitly_auth_access(), bitlink_id = bitlink_id) } df_link_expand <- doRequest("POST", links_expand_url, queryParameters = body_req_query, showURL = showRequestURL) df_link_expand <- data.frame(df_link_expand, stringsAsFactors = FALSE) df_link_expand$created_at <- ymd_hms(df_link_expand$created_at, tz = "UTC") return(df_link_expand) } #' Wrapper url expander #' #' @description url expander functions have different argnames to pass short URLs #' therefore a wrapper is needed to avoid changing argnames to main functions. #' #' @noRd bitly_expand_link_ <- function(shorturl, ...) { bitly_expand_link(bitlink_id = shorturl, ...) } #' @title Shorten a Link #' #' @description See \url{https://dev.bitly.com/api-reference/#createBitlink} #' Convert a long url to a Bitlink #' #' @inheritParams bitly_create_bitlink #' #' @examples #' \dontrun{ #' bitly_shorten_link(url = "http://www.seznam.cz/") #' bitly_shorten_link(url = "http://www.seznam.cz/", showRequestURL = TRUE) #' #' manyUrls <- list( #' "http://www.seznam.cz/", "http://www.seznamasdas.cz/", #' "http://www.seznam.cz/asadasd", "http://www.seznam.cz/adqwrewtregt" #' ) #' for (u in 1:length(manyUrls)) { #' print(bitly_shorten_link(long_url = manyUrls[[u]], showRequestURL = TRUE)) #' } #' } #' @import httr jsonlite lubridate #' @export bitly_shorten_link <- function(domain = "bit.ly", group_guid = NULL, long_url = NULL, showRequestURL = FALSE) { links_shorten_url <- "https://api-ssl.bitly.com/v4/shorten" if (!is.null(long_url)) { body_req_query <- list(access_token = bitly_auth_access(), group_guid = group_guid, long_url = long_url, domain = domain) } df_link_shorten <- doRequest("POST", links_shorten_url, queryParameters = body_req_query, showURL = showRequestURL) df_link_shorten <- data.frame(t(do.call(rbind, df_link_shorten)), stringsAsFactors = F) df_link_shorten$created_at <- now("UTC") return(df_link_shorten) } #' Wrapper url shortener #' #' @description url shortener function have different argnames to pass long URLS #' theefore a wrapper is needed to avoid changing argnames to main functions. #' #' @noRd bitly_shorten_link_ <- function(longUrl, ...) { bitly_shorten_link(long_url = longUrl, ...) } #' @title Update a Bitlink #' #' @description See \url{https://dev.bitly.com/api-reference/#updateBitlink} #' Update fields in the Bitlink #' #' @inheritParams bitly_create_bitlink #' @inheritParams bitly_retrieve_bitlinks_by_groups #' @inheritParams bitly_create_channel #' @inheritParams bitly_retrieve_links_grouped #' @inheritParams bitly_user_metrics_referring_domains #' @inheritParams bitly_add_cust_bitlink #' @inheritParams bitly_update_cust_bitlink #' @inheritParams bitly_update_channel #' @inheritParams bitly_retrieve_sorted_links #' @inheritParams bitly_app_details #' @param created_at - update created at parameter #' @param created_by - update user #' @param custom_bitlinks - update custom_bitlinks #' @param link - link #' @param id - id #' @examples #' \dontrun{ #' bitly_update_bitlink(bitlink = "bit.ly/DPetrov", title = "novy titulek") #' #' ## hash is the one which is only returned. Dont use #' bitly_update_bitlink(bitlink = "on.natgeo.com/1bEVhwE") #' #' ## manyHashes <- list("bit.ly/DPetrov", "bit.ly/1QU8CFm", "bit.ly/1R1LPSE", "bit.ly/1LNqqva") #' ## for (u in 1:length(manyHashes)) { #' ## print(bitly_update_bitlink(bitlink = manyHashes[[u]], #' ## title = stri_rand_strings(1, 8, pattern = "[A-Za-z0-9]"))) #' ## } #' } #' @import httr jsonlite lubridate #' @export bitly_update_bitlink <- function(bitlink = NULL, archived = NULL, tags = NULL, showRequestURL = FALSE, created_at = NULL, title = NULL, created_by = NULL, long_url = NULL, client_id = NULL, custom_bitlinks = NULL, link = NULL, id = NULL, deeplinks = list(bitlink = NULL, install_url = NULL, created = NULL, modified = NULL, app_uri_path = NULL, install_type = NULL, app_guid = NULL, guid = NULL, os = NULL)) { link_update <- paste0("https://api-ssl.bitly.com/v4/bitlinks/", bitlink) query <- list(access_token = bitly_auth_access()) body_upd = list() if (!length(deeplinks$bitlink) == 0 || !length(deeplinks$created) == 0 || !length(deeplinks$install_url) == 0 || !length(deeplinks$app_uri_path) == 0 || !length(deeplinks$modified) == 0 || !length(deeplinks$install_type) == 0 || !length(deeplinks$app_guid) == 0 || !length(deeplinks$guid) == 0 || !length(deeplinks$os) == 0) { body_upd$deeplinks <- deeplinks } if (length(tags) >= 1) { body_upd$tags <- tags } if (length(archived) >= 1) { body_upd$archived <- archived } if (length(created_at) >= 1) { body_upd$created_at <- created_at } if (length(created_by) >= 1) { body_upd$created_by <- created_by } if (length(title) >= 1) { body_upd$title <- title } if (length(long_url) >= 1) { body_upd$long_url <- long_url } if (length(client_id) >= 1) { body_upd$client_id <- client_id } if (length(custom_bitlinks) >= 1) { body_upd$custom_bitlinks <- custom_bitlinks } if (length(link) >= 1) { body_upd$link <- link } if (length(id) >= 1) { body_upd$id <- id } body_req_query_cleaned <- toJSON(body_upd, auto_unbox = T) df_update_pref <- doRequest("PATCH", url = link_update, queryParameters = query, patch_body = body_req_query_cleaned, showURL = showRequestURL) df_update_pref <- data.frame(t(do.call(rbind, df_update_pref)), stringsAsFactors = F) df_update_pref$created_at <- ymd_hms(df_update_pref$created_at, tz = "UTC") return(df_update_pref) } #' @title Retrieve a Bitlink #' #' @description This endpoint returns information for a Bitlink. #' #' @seealso See \url{https://dev.bitly.com/api-reference/#getBitlink} #' #' @inheritParams bitly_retrieve_sorted_links #' @inheritParams bitly_update_bitlink #' @inheritParams bitly_create_bitlink #' @inheritParams bitly_retrieve_bitlinks_by_groups #' @inheritParams bitly_create_channel #' @inheritParams bitly_retrieve_links_grouped #' @inheritParams bitly_user_metrics_referring_domains #' @import httr jsonlite lubridate #' #' @examples #' \dontrun{ #' bitly_retrieve_bitlink(bitlink = "cnn.it/2HomWGB") #' } #' #' @export bitly_retrieve_bitlink <- function(bitlink = NULL, showRequestURL = FALSE) { get_bitlink_url <- paste0("https://api-ssl.bitly.com/v4/bitlinks/", bitlink) query <- list(access_token = bitly_auth_access(), bitlink = bitlink) df_bitlink <- doRequest("GET", get_bitlink_url, queryParameters = query, showURL = showRequestURL) df_bitlink <- data.frame(t(do.call(rbind, df_bitlink)), stringsAsFactors = F) df_bitlink$created_at <- ymd_hms(df_bitlink$created_at, tz = "UTC") return(df_bitlink) } #' @title Get Metrics for a Bitlink by referrers by domain #' #' @description This endpoint will group referrers metrics about a single Bitlink. #' #' @seealso \url{https://dev.bitly.com/api-reference/#getMetricsForBitlinkByReferrersByDomains} #' #' @inheritParams bitly_user_metrics_referring_domains #' #' @import httr jsonlite lubridate #' #' @examples #' \dontrun{ #' bitly_retrieve_metrics_by_referrers_by_domain(bitlink = "bit.ly/DPetrov", unit = "day", #' units = -1, size = 100) #' } #' #' @export bitly_retrieve_metrics_by_referrers_by_domain <- function(bitlink = NULL, size = 50, unit_reference = NULL, unit = NULL, units = -1, showRequestURL = FALSE) { metrics_referrers_by_domain_url <- paste0("https://api-ssl.bitly.com/v4/bitlinks/", bitlink, "/referrers_by_domains") query <- list(access_token = bitly_auth_access(), bitlink = bitlink, size = size, units = units, unit = unit, unit_reference = unit_reference) df_metrics_referrers_by_domain <- doRequest("GET", metrics_referrers_by_domain_url, query, showURL = showRequestURL) return(df_metrics_referrers_by_domain) } #' @title Get Clicks for a Bitlink #' #' @description See \url{https://dev.bitly.com/api-reference/#getClicksForBitlink} #' This will return the click counts for a specified Bitlink. This returns an array with clicks based on a date. #' #' @param size - The quantity of items to be be returned #' @param units - An integer representing the time units to query data for. pass -1 to return all units of time. #' @param unit - A unit of time #' @param showRequestURL - show URL which has been build and requested from server. For debug #' purposes. #' @inheritParams bitly_retrieve_metrics_by_referrers_by_domain #' #' @examples #' \dontrun{ #' bitly_retrieve_clicks(bitlink = "cnn.it/2HomWGB", unit = "day", units = -1, size = 100) #' } #' @import httr jsonlite lubridate #' @export bitly_retrieve_clicks <- function(bitlink = NULL, size = 50, unit_reference = NULL, unit = NULL, units = -1, showRequestURL = FALSE) { user_metrics_clicks_url <- paste0("https://api-ssl.bitly.com/v4/bitlinks/", bitlink, "/clicks") query <- list(access_token = bitly_auth_access(), bitlink = bitlink, unit_reference = unit_reference, unit = unit, units = units) df_user_metrics_clicks <- doRequest("GET", user_metrics_clicks_url, query, showURL = showRequestURL) df_user_metrics_clicks$link_clicks$date <- ymd_hms(df_user_metrics_clicks$link_clicks$date, tz = "UTC") df_user_metrics_clicks$unit_reference <- ymd_hms(df_user_metrics_clicks$unit_reference, tz = "UTC") return(df_user_metrics_clicks) } #' @title Get Clicks Summary for a Bitlink #' #' @description See \url{https://dev.bitly.com/api-reference/#getClicksSummaryForBitlink} #' This will return the click counts for a specified Bitlink. This rolls up all the data into a #' single field of clicks. #' #' @inheritParams bitly_retrieve_clicks #' @examples #' \dontrun{ #' bitly_retrieve_clicks_summary(bitlink = "cnn.it/2HomWGB", unit = "day", units = -1, size = 100) #' } #' @import httr jsonlite lubridate #' @export bitly_retrieve_clicks_summary <- function(bitlink = NULL, size = 50, unit_reference = NULL, unit = NULL, units = -1, showRequestURL = FALSE) { user_metrics_clicks_url_sum <- paste0("https://api-ssl.bitly.com/v4/bitlinks/", bitlink, "/clicks/summary") query <- list(access_token = bitly_auth_access(), bitlink = bitlink, unit_reference = unit_reference, unit = unit, units = units, size = size) df_user_metrics_clicks_sum <- doRequest("GET", user_metrics_clicks_url_sum, query, showURL = showRequestURL) df_user_metrics_clicks_sum$unit_reference <- ymd_hms(df_user_metrics_clicks_sum$unit_reference, tz = "UTC") return(df_user_metrics_clicks_sum) } #' @title Get Metrics for a Bitlink by countries #' #' @description This endpoint will return metrics about the countries referring click traffic to #' a single Bitlink. #' #' @seealso \url{https://dev.bitly.com/api-reference/#getMetricsForBitlinkByCountries} #' #' @inheritParams bitly_retrieve_clicks_summary #' #' @import httr jsonlite lubridate #' #' @examples #' \dontrun{ #' bitly_retrieve_metrics_by_countries(bitlink = "bit.ly/DPetrov", unit = "day", units = -1, #' size = 100) #' } #' #' @export bitly_retrieve_metrics_by_countries <- function(bitlink = NULL, size = 100, unit = NULL, unit_reference = NULL, units = -1, showRequestURL = FALSE) { link_metrics_countries_url <- paste0("https://api-ssl.bitly.com/v4/bitlinks/", bitlink, "/countries") query <- list(access_token = bitly_auth_access(), bitlink = bitlink, unit_reference = unit_reference, unit = unit, units = units, size = size) df_link_metrics_countries <- doRequest("GET", link_metrics_countries_url, query, showURL = showRequestURL) df_link_metrics_countries$unit_reference <- ymd_hms(df_link_metrics_countries$unit_reference, tz = "UTC") return(df_link_metrics_countries) } #' @title Get Metrics for a Bitlink by referrers #' #' @description This endpoint will return metrics about the referrers referring click traffic to #' a single Bitlink. #' #' @seealso \url{https://dev.bitly.com/api-reference/#getMetricsForBitlinkByReferrers} #' #' @inheritParams bitly_retrieve_metrics_by_countries #' #' @import httr jsonlite lubridate #' #' @examples #' \dontrun{ #' bitly_retrieve_metrics_by_referrers(bitlink = "bit.ly/DPetrov", unit = "day", #' units = -1, size = 100) #' } #' #' @export bitly_retrieve_metrics_by_referrers <- function(bitlink = NULL, size = 100, unit = NULL, unit_reference = NULL, units = -1, showRequestURL = FALSE) { link_metrics_countries_url <- paste0("https://api-ssl.bitly.com/v4/bitlinks/", bitlink, "/referrers") query <- list(access_token = bitly_auth_access(), bitlink = bitlink, unit_reference = unit_reference, unit = unit, units = units, size = size) df_link_metrics_countries <- doRequest("GET", link_metrics_countries_url, query, showURL = showRequestURL) df_link_metrics_countries$unit_reference <- ymd_hms(df_link_metrics_countries$unit_reference, tz = "UTC") return(df_link_metrics_countries) } #' @title Retrieve Bitlinks by Group #' #' @description See \url{https://dev.bitly.com/api-reference/#getBitlinksByGroup} #' Retrieve a paginated collection of Bitlinks for a Group #' @param query_q - a query to look for in bitlinks; acts a filter #' @inheritParams bitly_retrieve_metrics_by_referrers #' @inheritParams bitly_update_bitlink #' @inheritParams bitly_retrieve_sorted_links #' @inheritParams bitly_create_bitlink #' @inheritParams bitly_create_channel #' @inheritParams bitly_retrieve_links_grouped #' #' @examples #' \dontrun{ #' bitly_retrieve_bitlinks_by_groups(group_guid = "bit.ly/DPetrov", keyword = "novy titulek") #' } #' @import httr jsonlite #' @export bitly_retrieve_bitlinks_by_groups <- function(group_guid = NULL, size = 50, page = 1, showRequestURL = FALSE, keyword = NULL, query_q = NULL, created_before = NULL, created_after = NULL, modified_after = NULL, archived = "both", deeplinks = "both", campaign_guid = NULL, channel_guid = NULL, custom_bitlink = "both", tags = NULL, encoding_login = NULL, domain_deeplinks = "both") { link_by_groups <- paste0("https://api-ssl.bitly.com/v4/groups/", group_guid, "/bitlinks") query <- list(access_token = bitly_auth_access(), size = size, page = page, archived = archived, domain_deeplinks = domain_deeplinks, deeplinks = deeplinks, custom_bitlink = custom_bitlink) if (!length(tags) >= 1) { query$tags <- tags } if (!length(keyword) >= 1) { query$keyword <- keyword } if (!length(query_q) >= 1) { query$query_q <- query_q } if (!length(created_before) >= 1) { query$created_before <- created_before } if (!length(created_after) >= 1) { query$created_after <- created_after } if (!length(modified_after) >= 1) { query$modified_after <- modified_after } if (!length(campaign_guid) >= 1) { query$campaign_guid <- campaign_guid } if (!length(channel_guid) >= 1) { query$channel_guid <- channel_guid } if (!length(encoding_login) >= 1) { query$encoding_login <- encoding_login } df_bitlinks_byGroup <- doRequest("GET", url = link_by_groups, queryParameters = query, showURL = showRequestURL) return(df_bitlinks_byGroup) } #' @title Retrieve Sorted Bitlinks for Group #' #' @description See \url{https://dev.bitly.com/api-reference/#getSortedBitlinks} #' This will retrieve a paginated response for Bitlinks that are sorted for the Group #' #' @inheritParams bitly_retrieve_metrics_by_referrers #' @inheritParams bitly_update_bitlink #' @inheritParams bitly_retrieve_bitlinks_by_groups #' @inheritParams bitly_retrieve_groups #' @param sort - required, Enum:"clicks" - The type of sorting that you would like to do #' #' @examples #' \dontrun{ #' bitly_retrieve_sorted_bitlinks_by_groups(group_guid = "", sort = "clicks") #' } #' @import httr jsonlite lubridate #' @export bitly_retrieve_sorted_bitlinks_by_groups <- function(group_guid = NULL, unit = "day", units = -1, sort = "clicks", size = 50, unit_reference = NULL, showRequestURL = FALSE) { link_by_sorted_groups <- paste0("https://api-ssl.bitly.com/v4/groups/", group_guid, "/bitlinks/", sort) query <- list(access_token = bitly_auth_access(), unit_reference = unit_reference, unit = unit, units = units, size = size) df_bitlinks_byGroup <- doRequest("GET", url = link_by_sorted_groups, queryParameters = query, showURL = showRequestURL) return(df_bitlinks_byGroup) }
/scratch/gouwar.j/cran-all/cranData/urlshorteneR/R/bitly_links.R
#' @title Retrieve a single Organization #' #' @description #' Retrive details for the specified organization. #' #' @section Organizations: #' Organizations are part of our hierarchy. This is the top level where a group and user will belong. #' #' @seealso \url{https://dev.bitly.com/api-reference/#getOrganization} #' #' @param organization_id - a required string | A GUID for a Bitly organization. #' You may also simply pass "" (double quotes), but this should be avoided at all costs. #' #' @import httr jsonlite assertthat #' #' @examples #' \dontrun{ #' all_orgs <- bitly_retrieve_orgs() #' ro <- bitly_retrieve_org(organization_id = all_orgs$guid) #' } #' #' @export bitly_retrieve_org <- function(organization_id = NULL) { org_url <- paste0("https://api-ssl.bitly.com/v4/organizations/", organization_id) if (!is.string(organization_id)) { stop("organization_id must not be empty string, NA or NULL") } query <- list(access_token = bitly_auth_access(), organization_guid = organization_id) df_org_details <- doRequest("GET", url = org_url, queryParameters = query) df_org_details <- data.frame(df_org_details, stringsAsFactors = FALSE) return(df_org_details) } #' @title Retrieve all Organizations #' #' @description #' Retrieve a list of organizations #' #' @inheritSection bitly_retrieve_org Organizations #' #' @seealso \url{https://dev.bitly.com/api-reference/#getOrganizations} #' #' @import httr jsonlite #' #' @examples #' \dontrun{ #' ros <- bitly_retrieve_orgs() #' } #' @import httr jsonlite #' @export bitly_retrieve_orgs <- function() { orgs_url <- "https://api-ssl.bitly.com/v4/organizations" query <- list(access_token = bitly_auth_access()) df_orgs_details <- doRequest(verb = "GET", url = orgs_url, queryParameters = query) df_orgs_details <- data.frame(df_orgs_details$organizations, stringsAsFactors = FALSE) return(df_orgs_details) } #' Retrieve Organization Shorten Counts #' #' Retrieve all the shorten counts for a specific organization #' #' @seealso \url{https://dev.bitly.com/api-reference/#getOrganizationShortenCounts} #' #' @inheritSection bitly_retrieve_org Organizations #' #' @inheritParams bitly_retrieve_org #' #' @return facet - Enum: "countries" "referrers" "referrers_by_domain" "referring_domains" "referring_networks" "shorten_counts" #' #' @examples #' \dontrun{ #' all_orgs <- bitly_retrieve_orgs() #' osc <- bitly_org_shorten_counts(organization_id = all_orgs$guid) #' df_org_short_counts <- data.frame(osc, stringsAsFactors = FALSE) #' } #' #' @import httr jsonlite assertthat #' @export bitly_retrieve_org_shorten_counts <- function(organization_id = NULL) { org_short_counts <- paste0("https://api-ssl.bitly.com/v4/organizations/", organization_id, "/shorten_counts") if (!is.string(organization_id)) { stop("organization_id must not be empty string, NA or NULL") } query <- list(access_token = bitly_auth_access(), organization_guid = organization_id) df_org_short_counts <- doRequest("GET", org_short_counts, queryParameters = query) # df_org_short_counts <- data.frame(df_org_short_counts, stringsAsFactors = FALSE) return(df_org_short_counts) } #' Get Plan Limits #' #' Returns all plan limits and counts available for an organization. #' #' @seealso \url{https://dev.bitly.com/api-reference/#getPlanLimits} #' #' @inheritSection bitly_retrieve_org Organizations #' #' @inheritParams bitly_retrieve_org #' #' @examples #' \dontrun{ #' all_orgs <- bitly_retrieve_orgs() #' plan <- bitly_retrieve_org_plan_limits(organization_id = all_orgs$guid) #' } #' #' @import httr jsonlite assertthat #' @export bitly_retrieve_org_plan_limits <- function(organization_id = NULL) { org_plan_limits <- paste0("https://api-ssl.bitly.com/v4/organizations/", organization_id, "/plan_limits") if (!is.string(organization_id)) { stop("organization_id must not be empty string, NA or NULL") } query <- list(access_token = bitly_auth_access(), organization_guid = organization_id) df_plan_limits <- doRequest("GET", org_plan_limits, queryParameters = query) df_org_plan_limits <- data.frame(df_plan_limits$plan_limits, stringsAsFactors = FALSE) return(df_org_plan_limits) }
/scratch/gouwar.j/cran-all/cranData/urlshorteneR/R/bitly_orgs.R
#' @title Retrieve information for the current authenticated user #' #' @param showRequestURL - an optional T/F value to whether show URL which has been #' build and requested from server. For debug purposes, default FALSE. #' #' @section User: #' User operations such as changing your name or fetching basic user information apply only to the authenticated user. #' #' @seealso \url{https://dev.bitly.com/api-reference/#getUser} #' #' @return login - the specified bitly login or the login of the authenticated user #' @return name - the user's full/display name #' @return default_group_guid - a group to which user belongs #' @return created - Timestamp for the moment the user signed up (uses \code{\link[lubridate]{ymd_hms}}) #' @return is_active - whether a user profile is active #' @return modified - Timestamp of the last modification to the user profile (uses \code{\link[lubridate]{ymd_hms}}) #' @return is_sso_user - is Single-Sign-On enabled for the user (PREMIUM FEATURE) #' @return is_2fa_enabled - is 2 Step verification enabled ? #' @return email - user's emails #' #' @examples #' \dontrun{ #' ui <- bitly_user_info(showRequestURL = TRUE) #' } #' #' @import httr stringr lubridate #' @export bitly_user_info <- function(showRequestURL = FALSE) { user_info_url <- "https://api-ssl.bitly.com/v4/user" create_query <- list(access_token = bitly_auth_access()) df_user_info <- doRequest(verb = "GET", url = user_info_url, queryParameters = create_query, showURL = showRequestURL) df_user_info_data <- data.frame(df_user_info, stringsAsFactors = FALSE) # convert to readable format - use lubridate parse_date_time df_user_info_data$created <- ymd_hms(df_user_info_data$created, tz = "UTC") df_user_info_data$modified <- ymd_hms(df_user_info_data$modified, tz = "UTC") return(df_user_info_data) } #' @title Update your name and/or default group ID #' #' @description #' This will overwrite your (display) username and/or group ID you belong to. #' #' @note Applies only to the authenticated user: #' Changing group/org ID is only permitted to premium users. Thus, if you are a "free" user and will try to change your #' default group id to something else, you will get an error. In that case, only changing display name is permitted. #' #' @param default_group_guid - group id to change, see NOTE #' @param name - username to change #' #' @inheritParams bitly_user_info #' @inheritSection bitly_user_info User #' #' @seealso \url{https://dev.bitly.com/api-reference/#updateUser} #' #' @examples #' \dontrun{ #' # this applies only for "free" users #' uu <- bitly_update_user(name = "Malc") #' #' # if you are premium user, you can additionally adjust your group id #' uug <- bitly_update_user(name = "Malc", default_group_guid = "TestGroupID") #' } #' #' @import httr jsonlite lubridate #' #' @export bitly_update_user <- function(default_group_guid = NULL, name = "", showRequestURL = FALSE) { user_info_url <- "https://api-ssl.bitly.com/v4/user" if (!is_bitly_user_premium_holder()) { default_group_guid <- NULL warning("Your account is not premium. Please report bugs in GitHub if this is not true.", "We will now skip changing group guid.") } query <- list(access_token = bitly_auth_access()) body <- list(name = name, default_group_guid = default_group_guid) df_user_info <- doRequest("PATCH", url = user_info_url, queryParameters = query, patch_body = body, showURL = showRequestURL ) df_user_info$created <- ymd_hms(df_user_info$created, tz = "UTC") df_user_info$modified <- ymd_hms(df_user_info$modified, tz = "UTC") return(df_user_info) } #' Check if authenticated user holds premium account #' #' @seealso [bitly_user_info()] #' #' @export is_bitly_user_premium_holder <- function() { user_profile <- bitly_user_info() return(user_profile$is_sso_user[[1]]) } #' Retrieve OAuth App #' #' Retrieve details for the provided OAuth App client ID #' #' @param client_id - The client ID of an OAuth app #' #' @inheritParams bitly_user_info #' #' @export bitly_app_details <- function(client_id = "be03aead58f23bc1aee6e1d7b7a1d99d62f0ede8", showRequestURL = F) { oauth_app_details <- paste0("https://api-ssl.bitly.com/v4/apps/", client_id) query <- list(access_token = bitly_auth_access(), client_id = client_id) df_app_details <- doRequest("GET", url = oauth_app_details, queryParameters = query, showURL = showRequestURL) df_app_details <- data.frame(df_app_details, stringsAsFactors = FALSE) return(df_app_details) } #' @title bitly_rate_limits #' @description Provides bit.ly rate limits by endpoint. See \url{https://dev.bitly.com/api-reference/#getPlatformLimitss} #' @inheritParams bitly_user_info #' @return \code{data.frame} of end points and their rate limits by action #' @export bitly_rate_limits <- function(showRequestURL = F) { query <- list(access_token = bitly_auth_access()) .url <- "https://api-ssl.bitly.com/v4/user/platform_limits" limits <- doRequest("GET", url = .url, queryParameters = query, showURL = showRequestURL) return(limits[[1]]) }
/scratch/gouwar.j/cran-all/cranData/urlshorteneR/R/bitly_user_app_info.R
#' @title Given a long URL, returns a short is.gd link. #' #' @description See \url{https://is.gd/apishorteningreference.php} #' #' @param longUrl - The url parameter is the address that you want to shorten. #' #' @param shorturl - (optional) You can specify the shorturl parameter if you'd like to pick a #' shortened URL instead of having is.gd randomly generate one. These must be between #' 5 and 30 characters long and can only contain alphanumeric characters and underscores. #' Shortened URLs are case sensitive. Bear in mind that a desired short URL might already #' be taken (this is very often the case with common words) so if you're using this option #' be prepared to respond to an error and get an alternative choice from your app's user. #' #' @param logstats - (optional) Adding the parameter logstats=1 turns on logging of detailed #' statistics when the shortened URL you create is accessed. This allows you to see how many #' times the link was accessed on a given day, what pages referred people to the link, what #' browser visitors were using etc. You can access these stats via the link preview page for #' your shortened URL (add a hyphen/dash to the end of the shortened URL to get to it). Creating #' links with statistics turned on has twice the "cost" towards our rate limit of other shortened #' links, so leave this parameter out of your API call if you don't require statistics on usage. See #' our usage limits page for more information on this \url{https://is.gd/usagelimits.php}. #' #' @param showRequestURL - show URL which has been build and requested from server. #' For debug purposes. #' #' @examples #' \dontrun{ #' short_lin <- isgd_LinksShorten(longUrl = "https://novinky.cz/",showRequestURL = TRUE) #' } #' @export isgd_LinksShorten <- function(longUrl = "", logstats = "0", shorturl = NULL, showRequestURL = FALSE) { links_shorten_url <- "https://is.gd/create.php?format=json" query <- list(url = longUrl, logstats = logstats, shorturl = shorturl) df_link_shorten <- doRequest("GET", links_shorten_url, queryParameters = query, showURL = showRequestURL) return(df_link_shorten$shorturl) } #' @title Expand a short URL to a longer one #' #' @inheritParams isgd_LinksShorten #' #' @description See \url{https://is.gd/apilookupreference.php} #' #' @examples #' \dontrun{ #' isgd_LinksExpand(shorturl = "https://is.gd/4oIAXJ", showRequestURL = TRUE) #' } #' @export isgd_LinksExpand <- function(shorturl = "", showRequestURL = FALSE) { links_expand_url <- "https://is.gd/forward.php?format=json" query <- list(shorturl = shorturl) df_link_expand <- doRequest("GET", links_expand_url, queryParameters = query, showURL = showRequestURL) return(df_link_expand$url) }
/scratch/gouwar.j/cran-all/cranData/urlshorteneR/R/isgd_links.R
#' @title Given a long URL, returns a short v.gd link. #' #' @description See \url{https://v.gd/apishorteningreference.php} #' #' @param longUrl - The url parameter is the address that you want to shorten. #' #' @param shorturl - (optional) You can specify the shorturl parameter if you'd like to pick a #' shortened URL instead of having v.gd randomly generate one. These must be between #' 5 and 30 characters long and can only contain alphanumeric characters and underscores. #' Shortened URLs are case sensitive. Bear in mind that a desired short URL might already #' be taken (this is very often the case with common words) so if you're using this option #' be prepared to respond to an error and get an alternative choice from your app's user. #' #' @param logstats - (optional) Adding the parameter logstats=1 turns on logging of detailed #' statistics when the shortened URL you create is accessed. This allows you to see how many #' times the link was accessed on a given day, what pages referred people to the link, what #' browser visitors were using etc. You can access these stats via the link preview page for #' your shortened URL (add a hyphen/dash to the end of the shortened URL to get to it). Creating #' links with statistics turned on has twice the "cost" towards our rate limit of other shortened #' links, so leave this parameter out of your API call if you don't require statistics on usage. See #' our usage limits page for more information on this \url{https://v.gd/usagelimits.php}. #' #' @param showRequestURL - show URL which has been build and requested from server. #' For debug purposes. #' #' @examples #' \dontrun{ #' assd <- vgd_LinksShorten(longUrl = "https://novinky.cz/",showRequestURL = TRUE) #' } #' #' @export vgd_LinksShorten <- function(longUrl = "", logstats = "0", shorturl = NULL, showRequestURL = FALSE) { links_shorten_url <- "https://v.gd/create.php?format=json" query <- list(url = longUrl, logstats = logstats, shorturl = shorturl) df_link_shorten <- doRequest("GET", links_shorten_url, queryParameters = query, showURL = showRequestURL) return(df_link_shorten$shorturl) } #' @title Expand a short URL to a longer one #' #' @inheritParams vgd_LinksShorten #' #' @description See \url{https://v.gd/apilookupreference.php} #' #' @examples #' \dontrun{ #' isgd_LinksExpand(shorturl = "https://v.gd/4oIAXJ", showRequestURL = TRUE) #' } #' #' @export vgd_LinksExpand <- function(shorturl = "", showRequestURL = FALSE) { links_expand_url <- "https://v.gd/forward.php?format=json" query <- list(shorturl = shorturl) df_link_expand <- doRequest("GET", links_expand_url, queryParameters = query, showURL = showRequestURL) return(df_link_expand$url) }
/scratch/gouwar.j/cran-all/cranData/urlshorteneR/R/vgd_links.R
.onAttach <- function(libname, pkgname) { packageStartupMessage("In order to use bitly functions, you first need to authenticate. For that execute 'bitly_auth()' in R console.") }
/scratch/gouwar.j/cran-all/cranData/urlshorteneR/R/zzz.R
## ----------------------------------------------------------------------------- library("knitr") library(urlshorteneR) if(interactive()) { # You must register a new pair of keys yourself # bitly_token <- bitly_auth(key = "xxx", secret = "xxx") # bitly_token <- bitly_auth() ui <- bitly_user_info(showRequestURL = TRUE) is_bitly_user_premium_holder() } ## ----------------------------------------------------------------------------- if (interactive()) { bitly_update_user(name = "John Malc", showRequestURL = TRUE) } ## ----------------------------------------------------------------------------- if (interactive()) { bitly_app_details() } ## ----------------------------------------------------------------------------- if (interactive()) { bitly_retrieve_group(ui$default_group_guid) bitly_retrieve_groups() } ## ----------------------------------------------------------------------------- if (interactive()) { bitly_user_info() } ## ----------------------------------------------------------------------------- if (interactive()) { df <- data.frame(pubDate = rep("2016-02-10", 4), link = c("https://www.google.com", "https://www.apple.com"), stringsAsFactors = FALSE) df fin = NULL for (p in 1:length(df$link)) { fin[[p]] <- bitly_create_bitlink(long_url = df$link[p]) } } ## ----------------------------------------------------------------------------- isgd_LinksShorten(longUrl = "https://us.cnn.com", showRequestURL = TRUE) ## ----------------------------------------------------------------------------- vgd_LinksShorten(longUrl = "https://www.cbs.com", showRequestURL = TRUE)
/scratch/gouwar.j/cran-all/cranData/urlshorteneR/inst/doc/Tutorial.R
--- title: "Tutorial for urlshorteneR -- v4" author: "dmpe @ github" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Tutorial for urlshorteneR -- v4} %\VignetteEncoding{UTF-8} %\VignetteEngine{knitr::rmarkdown} editor_options: chunk_output_type: console --- `urlshorteneR` wraps 2 URL services `Bit.ly` and its 2 friends `is.gd` as well as `v.gd`. For Bit.ly, in order to shorten URLs and downloading useful statistics about them, you have to authenticate using OAuth2.0 protocol, for which you need user account and API keys.. For 2 other services `is.gd` & `v.gd`, there is no authentication needed. Just create desired short links, see below. # Bit.ly ## User/App Information & Authentication for Bit.ly Return some basic information about my user on Bit.ly. Additionally, is my account a "premium" one? ```{r} library("knitr") library(urlshorteneR) if(interactive()) { # You must register a new pair of keys yourself # bitly_token <- bitly_auth(key = "xxx", secret = "xxx") # bitly_token <- bitly_auth() ui <- bitly_user_info(showRequestURL = TRUE) is_bitly_user_premium_holder() } ``` We can also decide to update my username with a different one. ```{r} if (interactive()) { bitly_update_user(name = "John Malc", showRequestURL = TRUE) } ``` And what about the metadata about our OAUTH application? ```{r} if (interactive()) { bitly_app_details() } ``` ## Group Information This retrieves information about a single group that user belongs to and and then about all groups that user are associated with. ```{r} if (interactive()) { bitly_retrieve_group(ui$default_group_guid) bitly_retrieve_groups() } ``` ## Information about Organizations Official API documentation <https://dev.bitly.com/api-reference>. The first method returns an information about myself. ```{r} if (interactive()) { bitly_user_info() } ``` ### Custom Bitlinks ```{r} if (interactive()) { df <- data.frame(pubDate = rep("2016-02-10", 4), link = c("https://www.google.com", "https://www.apple.com"), stringsAsFactors = FALSE) df fin = NULL for (p in 1:length(df$link)) { fin[[p]] <- bitly_create_bitlink(long_url = df$link[p]) } } ``` **BEWARE:** This will proceed only with the two real links, not with the NA, NULL or an empty strings. These, however, will stop the flow of the code (i.e. are errors). # Is.gd & V.gd ## Is.gd ```{r} isgd_LinksShorten(longUrl = "https://us.cnn.com", showRequestURL = TRUE) ``` ## V.gd ```{r} vgd_LinksShorten(longUrl = "https://www.cbs.com", showRequestURL = TRUE) ```
/scratch/gouwar.j/cran-all/cranData/urlshorteneR/inst/doc/Tutorial.Rmd
--- title: "Tutorial for urlshorteneR -- v4" author: "dmpe @ github" date: "`r Sys.Date()`" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Tutorial for urlshorteneR -- v4} %\VignetteEncoding{UTF-8} %\VignetteEngine{knitr::rmarkdown} editor_options: chunk_output_type: console --- `urlshorteneR` wraps 2 URL services `Bit.ly` and its 2 friends `is.gd` as well as `v.gd`. For Bit.ly, in order to shorten URLs and downloading useful statistics about them, you have to authenticate using OAuth2.0 protocol, for which you need user account and API keys.. For 2 other services `is.gd` & `v.gd`, there is no authentication needed. Just create desired short links, see below. # Bit.ly ## User/App Information & Authentication for Bit.ly Return some basic information about my user on Bit.ly. Additionally, is my account a "premium" one? ```{r} library("knitr") library(urlshorteneR) if(interactive()) { # You must register a new pair of keys yourself # bitly_token <- bitly_auth(key = "xxx", secret = "xxx") # bitly_token <- bitly_auth() ui <- bitly_user_info(showRequestURL = TRUE) is_bitly_user_premium_holder() } ``` We can also decide to update my username with a different one. ```{r} if (interactive()) { bitly_update_user(name = "John Malc", showRequestURL = TRUE) } ``` And what about the metadata about our OAUTH application? ```{r} if (interactive()) { bitly_app_details() } ``` ## Group Information This retrieves information about a single group that user belongs to and and then about all groups that user are associated with. ```{r} if (interactive()) { bitly_retrieve_group(ui$default_group_guid) bitly_retrieve_groups() } ``` ## Information about Organizations Official API documentation <https://dev.bitly.com/api-reference>. The first method returns an information about myself. ```{r} if (interactive()) { bitly_user_info() } ``` ### Custom Bitlinks ```{r} if (interactive()) { df <- data.frame(pubDate = rep("2016-02-10", 4), link = c("https://www.google.com", "https://www.apple.com"), stringsAsFactors = FALSE) df fin = NULL for (p in 1:length(df$link)) { fin[[p]] <- bitly_create_bitlink(long_url = df$link[p]) } } ``` **BEWARE:** This will proceed only with the two real links, not with the NA, NULL or an empty strings. These, however, will stop the flow of the code (i.e. are errors). # Is.gd & V.gd ## Is.gd ```{r} isgd_LinksShorten(longUrl = "https://us.cnn.com", showRequestURL = TRUE) ``` ## V.gd ```{r} vgd_LinksShorten(longUrl = "https://www.cbs.com", showRequestURL = TRUE) ```
/scratch/gouwar.j/cran-all/cranData/urlshorteneR/vignettes/Tutorial.Rmd
# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #'@title Recompose Parsed URLs #' #'@description Sometimes you want to take a vector of URLs, parse them, perform #'some operations and then rebuild them. \code{url_compose} takes a data.frame produced #'by \code{\link{url_parse}} and rebuilds it into a vector of full URLs (or: URLs as full #'as the vector initially thrown into url_parse). #' #'This is currently a `beta` feature; please do report bugs if you find them. #' #'@param parsed_urls a data.frame sourced from \code{\link{url_parse}} #' #'@seealso \code{\link{scheme}} and other accessors, which you may want to #'run URLs through before composing them to modify individual values. #' #'@examples #'#Parse a URL and compose it #'url <- "http://en.wikipedia.org" #'url_compose(url_parse(url)) #' #'@export url_compose <- function(parsed_urls) { .Call(`_urltools_url_compose`, parsed_urls) } #'@title Get or remove user authentication credentials #'@description authentication credentials appear before the domain #'name and look like \emph{user:password}. Sometimes you want the removed, #'or retrieved; \code{strip_credentials} and \code{get_credentials} do #'precisely that #' #'@aliases creds #'@rdname creds #' #'@param urls a URL, or vector of URLs #' #'@examples #'# Remove credentials #'strip_credentials("http://foo:[email protected]:3128") #' #'# Get credentials #'get_credentials("http://foo:[email protected]:3128") #'@export strip_credentials <- function(urls) { .Call(`_urltools_strip_credentials`, urls) } #'@rdname creds #'@export get_credentials <- function(urls) { .Call(`_urltools_get_credentials`, urls) } #'@title Encode or decode a URI #'@description encodes or decodes a URI/URL #' #'@param urls a vector of URLs to decode or encode. #' #'@details #'URL encoding and decoding is an essential prerequisite to proper web interaction #'and data analysis around things like server-side logs. The #'\href{http://tools.ietf.org/html/rfc3986}{relevant IETF RfC} mandates the percentage-encoding #'of non-Latin characters, including things like slashes, unless those are reserved. #' #'Base R provides \code{\link{URLdecode}} and \code{\link{URLencode}}, which handle #'URL encoding - in theory. In practise, they have a set of substantial problems #'that the urltools implementation solves:: #' #'\itemize{ #' \item{No vectorisation: }{Both base R functions operate on single URLs, not vectors of URLs. #' This means that, when confronted with a vector of URLs that need encoding or #' decoding, your only option is to loop from within R. This can be incredibly #' computationally costly with large datasets. url_encode and url_decode are #' implemented in C++ and entirely vectorised, allowing for a substantial #' performance improvement.} #' \item{No scheme recognition: }{encoding the slashes in, say, http://, is a good way #' of making sure your URL no longer works. Because of this, the only thing #' you can encode in URLencode (unless you refuse to encode reserved characters) #' is a partial URL, lacking the initial scheme, which requires additional operations #' to set up and increases the complexity of encoding or decoding. url_encode #' detects the protocol and silently splits it off, leaving it unencoded to ensure #' that the resulting URL is valid.} #' \item{ASCII NULs: }{Server side data can get very messy and sometimes include out-of-range #' characters. Unfortunately, URLdecode's response to these characters is to convert #' them to NULs, which R can't handle, at which point your URLdecode call breaks. #' \code{url_decode} simply ignores them.} #'} #' #'@return a character vector containing the encoded (or decoded) versions of "urls". #' #'@seealso \code{\link{puny_decode}} and \code{\link{puny_encode}}, for punycode decoding #'and encoding. #' #'@examples #' #'url_decode("https://en.wikipedia.org/wiki/File:Vice_City_Public_Radio_%28logo%29.jpg") #'url_encode("https://en.wikipedia.org/wiki/File:Vice_City_Public_Radio_(logo).jpg") #' #'\dontrun{ #'#A demonstrator of the contrasting behaviours around out-of-range characters #'URLdecode("%gIL") #'url_decode("%gIL") #'} #'@rdname encoder #'@export url_decode <- function(urls) { .Call(`_urltools_url_decode`, urls) } #'@rdname encoder #'@export url_encode <- function(urls) { .Call(`_urltools_url_encode`, urls) } #'@title get the values of a URL's parameters #'@description URLs can have parameters, taking the form of \code{name=value}, chained together #'with \code{&} symbols. \code{param_get}, when provided with a vector of URLs and a vector #'of parameter names, will generate a data.frame consisting of the values of each parameter #'for each URL. #' #'@param urls a vector of URLs #' #'@param parameter_names a vector of parameter names. If \code{NULL} (default), will extract #'all parameters that are present. #' #'@return a data.frame containing one column for each provided parameter name. Values that #'cannot be found within a particular URL are represented by an NA. #' #'@examples #'#A very simple example #'url <- "https://google.com:80/foo.php?this_parameter=selfreferencing&hiphop=awesome" #'parameter_values <- param_get(url, c("this_parameter","hiphop")) #' #'@seealso \code{\link{url_parse}} for decomposing URLs into their constituent parts and #'\code{\link{param_set}} for inserting or modifying key/value pairs within a query string. #' #'@aliases param_get url_parameter #'@rdname param_get #'@export param_get <- function(urls, parameter_names = NULL) { .Call(`_urltools_param_get`, urls, parameter_names) } #'@title Set the value associated with a parameter in a URL's query. #'@description URLs often have queries associated with them, particularly URLs for #'APIs, that look like \code{?key=value&key=value&key=value}. \code{param_set} #'allows you to modify key/value pairs within query strings, or even add new ones #'if they don't exist within the URL. #' #'@param urls a vector of URLs. These should be decoded (with \code{url_decode}) #'but do not have to have been otherwise manipulated. #' #'@param key a string representing the key to modify the value of (or insert wholesale #'if it doesn't exist within the URL). #' #'@param value a value to associate with the key. This can be a single string, #'or a vector the same length as \code{urls} #' #'@return the original vector of URLs, but with modified/inserted key-value pairs. If the #'URL is \code{NA}, the returned value will be - if the key or value are, no insertion #'will be made. #' #'@examples #'# Set a URL parameter where there's already a key for that #'param_set("https://en.wikipedia.org/api.php?action=query", "action", "pageinfo") #' #'# Set a URL parameter where there isn't. #'param_set("https://en.wikipedia.org/api.php?list=props", "action", "pageinfo") #' #'@seealso \code{\link{param_get}} to retrieve the values associated with multiple keys in #'a vector of URLs, and \code{\link{param_remove}} to strip key/value pairs from a URL entirely. #' #'@export param_set <- function(urls, key, value) { .Call(`_urltools_param_set`, urls, key, value) } #'@title Remove key-value pairs from query strings #'@description URLs often have queries associated with them, particularly URLs for #'APIs, that look like \code{?key=value&key=value&key=value}. \code{param_remove} #'allows you to remove key/value pairs while leaving the rest of the URL intact. #' #'@param urls a vector of URLs. These should be decoded with \code{url_decode} but don't #'have to have been otherwise processed. #' #'@param keys a vector of parameter keys to remove. #' #'@return the original URLs but with the key/value pairs specified by \code{keys} removed. #'If the original URL is \code{NA}, \code{NA} will be returned; if a specified key is \code{NA}, #'nothing will be done with it. #' #'@seealso \code{\link{param_set}} to modify values associated with keys, or \code{\link{param_get}} #'to retrieve those values. #' #'@examples #'# Remove multiple parameters from a URL #'param_remove(urls = "https://en.wikipedia.org/wiki/api.php?action=list&type=query&format=json", #' keys = c("action","format")) #'@export param_remove <- function(urls, keys) { .Call(`_urltools_param_remove`, urls, keys) } #'@title split URLs into their component parts #'@description \code{url_parse} takes a vector of URLs and splits each one into its component #'parts, as recognised by RfC 3986. #' #'@param urls a vector of URLs #' #'@details It's useful to be able to take a URL and split it out into its component parts - #'for the purpose of hostname extraction, for example, or analysing API calls. This functionality #'is not provided in base R, although it is provided in \code{\link[httr]{parse_url}}; that #'implementation is entirely in R, uses regular expressions, and is not vectorised. It's #'perfectly suitable for the intended purpose (decomposition in the context of automated #'HTTP requests from R), but not for large-scale analysis. #' #'Note that user authentication/identification information is not extracted; #'this can be found with \code{\link{get_credentials}}. #' #'@return a data.frame consisting of the columns scheme, domain, port, path, query #'and fragment. See the '\href{http://tools.ietf.org/html/rfc3986}{relevant IETF RfC} for #'definitions. If an element cannot be identified, it is represented by an empty string. #' #'@examples #'url_parse("https://en.wikipedia.org/wiki/Article") #' #'@seealso \code{\link{param_get}} for extracting values associated with particular keys in a URL's #'query string, and \code{\link{url_compose}}, which is \code{url_parse} in reverse. #' #'@export url_parse <- function(urls) { .Call(`_urltools_url_parse`, urls) } get_component_ <- function(urls, component) { .Call(`_urltools_get_component_`, urls, component) } set_component_ <- function(urls, component, new_value) { .Call(`_urltools_set_component_`, urls, component, new_value) } set_component_r <- function(urls, component, new_value, comparator) { .Call(`_urltools_set_component_r`, urls, component, new_value, comparator) } set_component_f <- function(urls, component, new_value, comparator) { .Call(`_urltools_set_component_f`, urls, component, new_value, comparator) } rm_component_ <- function(urls, component) { .Call(`_urltools_rm_component_`, urls, component) } #'@title Encode or Decode Internationalised Domains #'@description \code{puny_encode} and \code{puny_decode} implement #'the encoding standard for internationalised (non-ASCII) domains and #'subdomains. You can use them to encode UTF-8 domain names, or decode #'encoded names (which start "xn--"), or both. #' #'@param x a vector of URLs. These should be URL decoded using \code{\link{url_decode}}. #' #'@return a CharacterVector containing encoded or decoded versions of the entries in \code{x}. #'Invalid URLs (ones that are \code{NA}, or ones that do not successfully map to an actual #'decoded or encoded version) will be returned as \code{NA}. #' #'@examples #'# Encode a URL #'puny_encode("https://www.bücher.com/foo") #' #'# Decode the result, back to the original #'puny_decode("https://www.xn--bcher-kva.com/foo") #' #'@seealso \code{\link{url_decode}} and \code{\link{url_encode}} for percent-encoding. #' #'@rdname puny #'@export puny_encode <- function(x) { .Call(`_urltools_puny_encode`, x) } #'@rdname puny #'@export puny_decode <- function(x) { .Call(`_urltools_puny_decode`, x) } reverse_strings <- function(strings) { .Call(`_urltools_reverse_strings`, strings) } finalise_suffixes <- function(full_domains, suffixes, wildcard, is_suffix) { .Call(`_urltools_finalise_suffixes`, full_domains, suffixes, wildcard, is_suffix) } tld_extract_ <- function(domains) { .Call(`_urltools_tld_extract_`, domains) } host_extract_ <- function(domains) { .Call(`_urltools_host_extract_`, domains) }
/scratch/gouwar.j/cran-all/cranData/urltools/R/RcppExports.R
#'@title Get or set a URL's scheme #'@description as in the lubridate package, individual components of a URL #'can be both extracted or set using the relevant function call - see the #'examples. #'@aliases scheme #'@rdname scheme #' #'@param x a URL, or vector of URLs #' #'@param value a replacement value (or vector of replacement values) #'for x's scheme. #' #'@seealso \code{\link{domain}}, \code{\link{port}}, \code{\link{path}}, #'\code{\link{parameters}} and \code{\link{fragment}} for other accessors. #' #'@examples #'#Get a component #'example_url <- "http://cran.r-project.org/submit.html" #'scheme(example_url) #' #'#Set a component #'scheme(example_url) <- "https" #' #'# NA out the URL #'scheme(example_url) <- NA_character_ #'@import methods #'@export scheme <- function(x){ return(get_component_(x,0)) } "scheme<-" <- function(x, value) standardGeneric("scheme<-") #'@rdname scheme #'@export setGeneric("scheme<-", useAsDefault = function(x, value){ if(length(value) == 0 && is.null(value)){ return(rm_component_(x, 0)) } return(set_component_r(x, 0, value, "://")) }) #'@title Get or set a URL's domain #'@description as in the lubridate package, individual components of a URL #'can be both extracted or set using the relevant function call - see the #'examples. #'@aliases domain #'@rdname domain #' #'@param x a URL, or vector of URLs #' #'@param value a replacement value (or vector of replacement values) #'for x's scheme. #' #'@seealso \code{\link{scheme}}, \code{\link{port}}, \code{\link{path}}, #'\code{\link{parameters}} and \code{\link{fragment}} for other accessors. #' #'@examples #'#Get a component #'example_url <- "http://cran.r-project.org/submit.html" #'domain(example_url) #' #'#Set a component #'domain(example_url) <- "en.wikipedia.org" #'@export domain <- function(x){ return(get_component_(x,1)) } "domain<-" <- function(x, value) standardGeneric("domain<-") #'@rdname domain #'@export setGeneric("domain<-", useAsDefault = function(x, value){ if(length(value) == 0 && is.null(value)){ return(rm_component_(x, 1)) } return(set_component_(x, 1, value)) }) #'@title Get or set a URL's port #'@description as in the lubridate package, individual components of a URL #'can be both extracted or set using the relevant function call - see the #'examples. #' #'@aliases port #'@rdname port #' #'@param x a URL, or vector of URLs #' #'@param value a replacement value (or vector of replacement values) #'for x's port. If NULL, the port will be entirely removed. #' #'@seealso \code{\link{scheme}}, \code{\link{domain}}, \code{\link{path}}, #'\code{\link{parameters}} and \code{\link{fragment}} for other accessors. #' #'@examples #'# Get the port #'example_url <- "http://cran.r-project.org:80/submit.html" #'port(example_url) #' #'# Set the port #'port(example_url) <- "12" #' #'# Remove the port #'port(example_url) <- NULL #'@export port <- function(x){ return(get_component_(x,2)) } "port<-" <- function(x, value) standardGeneric("port<-") #'@rdname port #'@export setGeneric("port<-", useAsDefault = function(x, value){ if(length(value) == 0 && is.null(value)){ return(rm_component_(x, 2)) } return(set_component_f(x, 2, value, ":")) }) #'@title Get or set a URL's path #'@description as in the lubridate package, individual components of a URL #'can be both extracted or set using the relevant function call - see the #'examples. #'@aliases path #'@rdname path #' #'@param x a URL, or vector of URLs #' #'@param value a replacement value (or vector of replacement values) #'for x's path. If NULL, the path will be removed entirely. #' #'@seealso \code{\link{scheme}}, \code{\link{domain}}, \code{\link{port}}, #'\code{\link{parameters}} and \code{\link{fragment}} for other accessors. #' #'@examples #'# Get the path #'example_url <- "http://cran.r-project.org:80/submit.html" #'path(example_url) #' #'# Set the path #'path(example_url) <- "bin/windows/" #' #'# Remove the path #'path(example_url) <- NULL #'@export path <- function(x){ return(get_component_(x,3)) } "path<-" <- function(x, value) standardGeneric("path<-") #'@rdname path #'@export setGeneric("path<-", useAsDefault = function(x, value){ if(length(value) == 0 && is.null(value)){ return(rm_component_(x, 3)) } return(set_component_f(x, 3, value, "/")) }) #'@title Get or set a URL's parameters #'@description as in the lubridate package, individual components of a URL #'can be both extracted or set using the relevant function call - see the #'examples. #' #'@aliases parameters #'@rdname parameters #' #'@param x a URL, or vector of URLs #' #'@param value a replacement value (or vector of replacement values) #'for x's parameters. If NULL, the parameters will be removed entirely. #' #'@seealso \code{\link{scheme}}, \code{\link{domain}}, \code{\link{port}}, #'\code{\link{path}} and \code{\link{fragment}} for other accessors. #' #'@examples #'# Get the parameters #'example_url <- "http://en.wikipedia.org/wiki/Aaron_Halfaker?debug=true" #'parameters(example_url) #' #'# Set the parameters #'parameters(example_url) <- "debug=false" #' #'# Remove the parameters #'parameters(example_url) <- NULL #'@export parameters <- function(x){ return(get_component_(x,4)) } "parameters<-" <- function(x, value) standardGeneric("parameters<-") #'@rdname parameters #'@export setGeneric("parameters<-", useAsDefault = function(x, value){ if(length(value) == 0 && is.null(value)){ return(rm_component_(x, 4)) } return(set_component_f(x, 4, value, "?")) }) #'@title Get or set a URL's fragment #'@description as in the lubridate package, individual components of a URL #'can be both extracted or set using the relevant function call - see the #'examples. #'@aliases fragment #'@rdname fragment #' #'@param x a URL, or vector of URLs #' #'@param value a replacement value (or vector of replacement values) #'for x's fragment. If NULL, the fragment will be removed entirely. #' #'@seealso \code{\link{scheme}}, \code{\link{domain}}, \code{\link{port}}, #'\code{\link{path}} and \code{\link{parameters}} for other accessors. #' #'@examples #'#Get a component #'example_url <- "http://en.wikipedia.org/wiki/Aaron_Halfaker?debug=true#test" #'fragment(example_url) #' #'#Set a component #'fragment(example_url) <- "production" #' #'#Remove a component #'fragment(example_url) <- NULL #'@export #'@rdname fragment #'@export fragment <- function(x){ return(get_component_(x,5)) } "fragment<-" <- function(x, value) standardGeneric("fragment<-") #'@rdname fragment #'@export setGeneric("fragment<-", useAsDefault = function(x, value){ if(length(value) == 0 && is.null(value)){ return(rm_component_(x, 5)) } return(set_component_f(x, 5, value, "#")) })
/scratch/gouwar.j/cran-all/cranData/urltools/R/accessors.R
#' @title Dataset of public suffixes #' @description This dataset contains a registry of public suffixes, as retrieved from #' and defined by the \href{https://publicsuffix.org/}{public suffix list}. It is #' sorted by how many periods(".") appear in the suffix, to optimise it for #' \code{\link{suffix_extract}}. It is a data.frame with two columns, the first is #' the list of suffixes and the second is our best guess at the comment or owner #' associated with the particular suffix. #' #' @docType data #' @keywords datasets #' @name suffix_dataset #' #' @seealso \code{\link{suffix_extract}} for extracting suffixes from domain names, #' and \code{\link{suffix_refresh}} for getting a new, totally-up-to-date dataset #' version. #' #' @usage data(suffix_dataset) #' @note Last updated 2016-07-31. #' @format A data.frame of 8030 rows and 2 columns "suffix_dataset" #'@title Retrieve a public suffix dataset #' #'@description \code{urltools} comes with an inbuilt #'dataset of public suffixes, \code{\link{suffix_dataset}}. #'This is used in \code{\link{suffix_extract}} to identify the top-level domain #'within a particular domain name. #' #'While updates to the dataset will be included in each new package release, #'there's going to be a gap between changes to the suffixes list and changes to the package. #'Accordingly, the package also includes \code{suffix_refresh}, which generates #'and returns a \emph{fresh} version of the dataset. This can then be passed through #'to \code{\link{suffix_extract}}. #' #'@return a dataset equivalent in format to \code{\link{suffix_dataset}}. #' #'@seealso \code{\link{suffix_extract}} to extract suffixes from domain names, #'or \code{\link{suffix_dataset}} for the inbuilt, default version of the data. #' #'@examples #'\dontrun{ #'new_suffixes <- suffix_refresh() #'} #' #'@export suffix_refresh <- function(){ has_libcurl <- capabilities("libcurl") if(length(has_libcurl) == 0 || has_libcurl == FALSE){ stop("libcurl support is needed for this function") } #Read in and filter connection <- url("https://www.publicsuffix.org/list/effective_tld_names.dat", method = "libcurl") results <- readLines(connection, encoding = "UTF-8") close(connection) # making an assumption that sections are broken by blank lines blank <- which(results == "") # and gotta know where the comments are comments <- grep(pattern = "^//", x=results) # if the file doesn't end on a blank line, stick an ending on there. if (blank[length(blank)] < length(results)) { blank <- c(blank, length(results)+1) } # now break up each section into a list # grab right after the blank line and right before the next blank line. suffix_dataset <- do.call(rbind, lapply(seq(length(blank) - 1), function(i) { # these are the lines in the current block lines <- seq(blank[i] + 1, blank[i + 1] - 1) # assume there is nothing in the block rez <- NULL # the lines of text in this block suff <- results[lines] # of which these are the comments iscomment <- lines %in% comments # and check if we have any results # append the first comment at the top of the block only. if(length(suff[!iscomment])) { rez <- data.frame(suffixes = suff[!iscomment], comments = suff[which(iscomment)[1]], stringsAsFactors = FALSE) } return(rez) })) ## this is the old way #suffix_dataset <- results[!grepl(x = results, pattern = "//", fixed = TRUE) & !results == ""] #Return the user-friendly version return(suffix_dataset) } #' @title extract the suffix from domain names #' @description domain names have suffixes - common endings that people #' can or could register domains under. This includes things like ".org", but #' also things like ".edu.co". A simple Top Level Domain list, as a #' result, probably won't cut it. #' #' \code{\link{suffix_extract}} takes the list of public suffixes, #' as maintained by Mozilla (see \code{\link{suffix_dataset}}) and #' a vector of domain names, and produces a data.frame containing the #' suffix that each domain uses, and the remaining fragment. #' #' @param domains a vector of damains, from \code{\link{domain}} #' or \code{\link{url_parse}}. Alternately, full URLs can be provided #' and will then be run through \code{\link{domain}} internally. #' #' @param suffixes a dataset of suffixes. By default, this is NULL and the function #' relies on \code{\link{suffix_dataset}}. Optionally, if you want more updated #' suffix data, you can provide the result of \code{\link{suffix_refresh}} for #' this parameter. #' #' @return a data.frame of four columns, "host" "subdomain", "domain" & "suffix". #' "host" is what was passed in. "subdomain" is the subdomain of the suffix. #' "domain" contains the part of the domain name that came before the matched suffix. #' "suffix" is, well, the suffix. #' #' @seealso \code{\link{suffix_dataset}} for the dataset of suffixes. #' #' @examples #' #' # Using url_parse #' domain_name <- url_parse("http://en.wikipedia.org")$domain #' suffix_extract(domain_name) #' #' # Using domain() #' domain_name <- domain("http://en.wikipedia.org") #' suffix_extract(domain_name) #' #' \dontrun{ #' #Relying on a fresh version of the suffix dataset #' suffix_extract(domain("http://en.wikipedia.org"), suffix_refresh()) #' } #' #' @importFrom triebeard trie longest_match #' @export suffix_extract <- function(domains, suffixes = NULL){ if(!is.null(suffixes)){ # check if suffixes is a data.frame, and stop if column not found if(is.data.frame(suffixes)) { if ("suffixes" %in% colnames(suffixes)) { suffixes <- suffixes$suffixes } else { stop("Expected column named \"suffixes\" in suffixes data.frame") } } holding <- suffix_load(suffixes) } else { holding <- list(suff_trie = urltools_env$suff_trie, is_wildcard = urltools_env$is_wildcard, cleaned_suffixes = urltools_env$cleaned_suffixes) } rev_domains <- reverse_strings(tolower(domains)) matched_suffixes <- triebeard::longest_match(holding$suff_trie, rev_domains) has_wildcard <- matched_suffixes %in% holding$is_wildcard is_suffix <- domains %in% holding$cleaned_suffixes return(finalise_suffixes(domains, matched_suffixes, has_wildcard, is_suffix)) } #' @title Dataset of top-level domains (TLDs) #' @description This dataset contains a registry of top-level domains, as retrieved from #' and defined by the \href{http://data.iana.org/TLD/tlds-alpha-by-domain.txt}{IANA}. #' #' @docType data #' @keywords datasets #' @name tld_dataset #' #' @seealso \code{\link{tld_extract}} for extracting TLDs from domain names, #' and \code{\link{tld_refresh}} to get an updated version of this dataset. #' #' @usage data(tld_dataset) #' @note Last updated 2016-07-20. #' @format A vector of 1275 elements. "tld_dataset" #'@title Retrieve a TLD dataset #' #'@description \code{urltools} comes with an inbuilt #'dataset of top level domains (TLDs), \code{\link{tld_dataset}}. #'This is used in \code{\link{tld_extract}} to identify the top-level domain #'within a particular domain name. #' #'While updates to the dataset will be included in each new package release, #'there's going to be a gap between changes to TLDs and changes to the package. #'Accordingly, the package also includes \code{tld_refresh}, which generates #'and returns a \emph{fresh} version of the dataset. This can then be passed through #'to \code{\link{tld_extract}}. #' #'@return a dataset equivalent in format to \code{\link{tld_dataset}}. #' #'@seealso \code{\link{tld_extract}} to extract suffixes from domain names, #'or \code{\link{tld_dataset}} for the inbuilt, default version of the data. #' #'@examples #'\dontrun{ #'new_tlds <- tld_refresh() #'} #' #'@export tld_refresh <- function(){ raw_tlds <- readLines("http://data.iana.org/TLD/tlds-alpha-by-domain.txt", warn = FALSE) raw_tlds <- tolower(raw_tlds[!grepl(x = raw_tlds, pattern = "#", fixed = TRUE)]) return(raw_tlds) } #'@title Extract TLDs #'@description \code{tld_extract} extracts the top-level domain (TLD) from #'a vector of domain names. This is distinct from the suffixes, extracted with #'\code{\link{suffix_extract}}; TLDs are \emph{top} level, while suffixes are just #'domains through which internet users can publicly register domains (the difference #'between \code{.org.uk} and \code{.uk}). #' #'@param domains a vector of domains, retrieved through \code{\link{url_parse}} or #'\code{\link{domain}}. #' #'@param tlds a dataset of TLDs. If NULL (the default), \code{tld_extract} relies #'on urltools' \code{\link{tld_dataset}}; otherwise, you can pass in the result of #'\code{\link{tld_refresh}}. #' #'@return a data.frame of two columns: \code{domain}, with the original domain names, #'and \code{tld}, the identified TLD from the domain. #' #'@examples #'# Using the inbuilt dataset #'domains <- domain("https://en.wikipedia.org/wiki/Main_Page") #'tld_extract(domains) #' #'# Using a refreshed one #'tld_extract(domains, tld_refresh()) #' #'@seealso \code{\link{suffix_extract}} for retrieving suffixes (distinct from TLDs). #' #'@export tld_extract <- function(domains, tlds = NULL){ if(is.null(tlds)){ tlds <- urltools::tld_dataset } guessed_tlds <- tld_extract_(tolower(domains)) guessed_tlds[!guessed_tlds %in% tlds] <- NA return(data.frame(domain = domains, tld = guessed_tlds, stringsAsFactors = FALSE)) } #'@title Extract hosts #'@description \code{host_extract} extracts the host from #'a vector of domain names. A host isn't the same as a domain - it could be #'the subdomain, if there are one or more subdomains. The host of \code{en.wikipedia.org} #'is \code{en}, while the host of \code{wikipedia.org} is \code{wikipedia}. #' #'@param domains a vector of domains, retrieved through \code{\link{url_parse}} or #'\code{\link{domain}}. #' #'@return a data.frame of two columns: \code{domain}, with the original domain names, #'and \code{host}, the identified host from the domain. #' #'@examples #'# With subdomains #'has_subdomain <- domain("https://en.wikipedia.org/wiki/Main_Page") #'host_extract(has_subdomain) #' #'# Without #'no_subdomain <- domain("https://ironholds.org/projects/r_shiny/") #'host_extract(no_subdomain) #'@export host_extract <- function(domains){ return(data.frame(domain = domains, host = host_extract_(domains), stringsAsFactors = FALSE)) }
/scratch/gouwar.j/cran-all/cranData/urltools/R/suffix.R
#' @title Tools for handling URLs #' @name urltools #' @description This package provides functions for URL encoding and decoding, #' parsing, and parameter extraction, designed to be both fast and #' entirely vectorised. It is intended to be useful for people dealing with #' web-related datasets, such as server-side logs. #' #' @seealso the \href{https://CRAN.R-project.org/package=urltools/vignettes/urltools.html}{package vignette}. #' @useDynLib urltools, .registration = TRUE #' @importFrom Rcpp sourceCpp #' @docType package #' @aliases urltools urltools-package NULL
/scratch/gouwar.j/cran-all/cranData/urltools/R/urltools.R
urltools_env <- new.env(parent = emptyenv()) suffix_load <- function(suffixes = NULL){ if(is.null(suffixes)){ suffixes <- urltools::suffix_dataset } cleaned_suffixes <- gsub(x = suffixes$suffixes, pattern = "*.", replacement = "", fixed = TRUE) is_wildcard <- cleaned_suffixes[which(grepl(x = suffixes$suffixes, pattern = "*.", fixed = TRUE))] suff_trie <- triebeard::trie(keys = reverse_strings(paste0(".", cleaned_suffixes)), values = cleaned_suffixes) return(list(suff_trie = suff_trie, is_wildcard = is_wildcard, cleaned_suffixes = cleaned_suffixes)) return(invisible()) } .onLoad <- function(...) { holding <- suffix_load() assign("is_wildcard", holding$is_wildcard, envir = urltools_env) assign("cleaned_suffixes", holding$cleaned_suffixes, envir = urltools_env) assign("suff_trie", holding$suff_trie, envir = urltools_env) }
/scratch/gouwar.j/cran-all/cranData/urltools/R/zzz.R
## ---- eval=FALSE--------------------------------------------------------- # URLdecode("test%gIL") # Error in rawToChar(out) : embedded nul in string: '\0L' # In addition: Warning message: # In URLdecode("%gIL") : out-of-range values treated as 0 in coercion to raw ## ---- eval=FALSE--------------------------------------------------------- # URLencode("https://en.wikipedia.org/wiki/Article", reserved = TRUE) # [1] "https%3a%2f%2fen.wikipedia.org%2fwiki%2fArticle" ## ---- eval=FALSE--------------------------------------------------------- # library(urltools) # url_decode("test%gIL") # [1] "test" # url_encode("https://en.wikipedia.org/wiki/Article") # [1] "https://en.wikipedia.org%2fwiki%2fArticle" ## ---- eval=FALSE--------------------------------------------------------- # > parsed_address <- url_parse("https://en.wikipedia.org/wiki/Article") # > str(parsed_address) # 'data.frame': 1 obs. of 6 variables: # $ scheme : chr "https" # $ domain : chr "en.wikipedia.org" # $ port : chr NA # $ path : chr "wiki/Article" # $ parameter: chr NA # $ fragment : chr NA ## ---- eval=FALSE--------------------------------------------------------- # > url_compose(parsed_address) # [1] "https://en.wikipedia.org/wiki/article" ## ---- eval=FALSE--------------------------------------------------------- # url <- "https://en.wikipedia.org/wiki/Article" # scheme(url) # "https" # scheme(url) <- "ftp" # url # "ftp://en.wikipedia.org/wiki/Article" ## ---- eval=FALSE--------------------------------------------------------- # > url <- "https://en.wikipedia.org/wiki/Article" # > domain_name <- domain(url) # > domain_name # [1] "en.wikipedia.org" # > str(suffix_extract(domain_name)) # 'data.frame': 1 obs. of 4 variables: # $ host : chr "en.wikipedia.org" # $ subdomain: chr "en" # $ domain : chr "wikipedia" # $ suffix : chr "org" ## ---- eval=FALSE--------------------------------------------------------- # domain_name <- domain("https://en.wikipedia.org/wiki/Article") # updated_suffixes <- suffix_refresh() # suffix_extract(domain_name, updated_suffixes) ## ---- eval=FALSE--------------------------------------------------------- # domain_name <- domain("https://en.wikipedia.org/wiki/Article") # host_extract(domain_name) ## ---- eval=FALSE--------------------------------------------------------- # > str(param_get(urls = "http://en.wikipedia.org/wiki/api.php?action=parse&pageid=1023&export=json", # parameter_names = c("pageid","export"))) # 'data.frame': 1 obs. of 2 variables: # $ pageid: chr "1023" # $ export: chr "json" ## ---- eval=FALSE--------------------------------------------------------- # url <- "http://en.wikipedia.org/wiki/api.php?action=parse&pageid=1023&export=json" # url <- param_set(url, key = "pageid", value = "12") # url # # [1] "http://en.wikipedia.org/wiki/api.php?action=parse&pageid=12&export=json" ## ---- eval=FALSE--------------------------------------------------------- # url <- "http://en.wikipedia.org/wiki/api.php" # url <- param_set(url, key = "pageid", value = "12") # url # # [1] "http://en.wikipedia.org/wiki/api.php?pageid=12" ## ---- eval=FALSE--------------------------------------------------------- # url <- "http://en.wikipedia.org/wiki/api.php?action=parse&pageid=1023&export=json" # url <- param_remove(url, keys = c("action","export")) # url # # [1] "http://en.wikipedia.org/wiki/api.php?pageid=1023"
/scratch/gouwar.j/cran-all/cranData/urltools/inst/doc/urltools.R
<!-- %\VignetteEngine{knitr::knitr} %\VignetteIndexEntry{urltools} --> ## Elegant URL handling with urltools URLs are treated, by base R, as nothing more than components of a data retrieval process: they exist to create connections to retrieve datasets. This is an essential feature for the language to have, but it also means that URL handlers are designed for situations where URLs *get* you to the data - not situations where URLs *are* the data. There is no support for encoding or decoding URLs en-masse, and no support for parsing and interpreting them. `urltools` provides this support! ### URL encoding and decoding Base R provides two functions - <code>URLdecode</code> and <code>URLencode</code> - for taking percentage-encoded URLs and turning them into regular strings, or vice versa. As discussed, these are primarily designed to enable connections, and so they have several inherent limitations, including a lack of vectorisation, that make them unsuitable for large datasets. Not only are they not vectorised, they also have several particularly idiosyncratic bugs and limitations: <code>URLdecode</code>, for example, breaks if the decoded value is out of range: ```{r, eval=FALSE} URLdecode("test%gIL") Error in rawToChar(out) : embedded nul in string: '\0L' In addition: Warning message: In URLdecode("%gIL") : out-of-range values treated as 0 in coercion to raw ``` URLencode, on the other hand, encodes slashes on its most strict setting - without paying attention to where those slashes *are*: if we attempt to URLencode an entire URL, we get: ```{r, eval=FALSE} URLencode("https://en.wikipedia.org/wiki/Article", reserved = TRUE) [1] "https%3a%2f%2fen.wikipedia.org%2fwiki%2fArticle" ``` That's a completely unusable URL (or ewRL, if you will). urltools replaces both functions with <code>url\_decode</code> and <code>url\_encode</code> respectively: ```{r, eval=FALSE} library(urltools) url_decode("test%gIL") [1] "test" url_encode("https://en.wikipedia.org/wiki/Article") [1] "https://en.wikipedia.org%2fwiki%2fArticle" ``` As you can see, <code>url\_decode</code> simply excludes out-of-range characters from consideration, while <code>url\_encode</code> detects characters that make up part of the URLs scheme, and leaves them unencoded. Both are extremely fast; with `urltools`, you can decode a vector of 1,000,000 URLs in 0.9 seconds. Alongside these, we have functions for encoding and decoding the 'punycode' format of URLs - ones that are designed to be internationalised and have unicode characters in them. These also take one argument, a vector of URLs, and can be found at `puny_encode` and `puny_decode` respectively. ### URL parsing Once you've got your nicely decoded (or encoded) URLs, it's time to do something with them - and, most of the time, you won't actually care about most of the URL. You'll want to look at the scheme, or the domain, or the path, but not the entire thing as one string. The solution is <code>url_parse</code>, which takes a URL and breaks it out into its [RfC 3986](http://www.ietf.org/rfc/rfc3986.txt) components: scheme, domain, port, path, query string and fragment identifier. This is, again, fully vectorised, and can happily be run over hundreds of thousands of URLs, rapidly processing them. The results are provided as a data.frame, since most people use data.frames to store data. ```{r, eval=FALSE} > parsed_address <- url_parse("https://en.wikipedia.org/wiki/Article") > str(parsed_address) 'data.frame': 1 obs. of 6 variables: $ scheme : chr "https" $ domain : chr "en.wikipedia.org" $ port : chr NA $ path : chr "wiki/Article" $ parameter: chr NA $ fragment : chr NA ``` We can also perform the opposite of this operation with `url_compose`: ```{r, eval=FALSE} > url_compose(parsed_address) [1] "https://en.wikipedia.org/wiki/article" ``` ### Getting/setting URL components With the inclusion of a URL parser, we suddenly have the opportunity for lubridate-style component getting and setting. Syntax is identical to that of `lubridate`, but uses URL components as function names. ```{r, eval=FALSE} url <- "https://en.wikipedia.org/wiki/Article" scheme(url) "https" scheme(url) <- "ftp" url "ftp://en.wikipedia.org/wiki/Article" ``` Fields that can be extracted or set are <code>scheme</code>, <code>domain</code>, <code>port</code>, <code>path</code>, <code>parameters</code> and <code>fragment</code>. ### Suffix and TLD extraction Once we've extracted a domain from a URL with `domain` or `url_parse`, we can identify which bit is the domain name, and which bit is the suffix: ```{r, eval=FALSE} > url <- "https://en.wikipedia.org/wiki/Article" > domain_name <- domain(url) > domain_name [1] "en.wikipedia.org" > str(suffix_extract(domain_name)) 'data.frame': 1 obs. of 4 variables: $ host : chr "en.wikipedia.org" $ subdomain: chr "en" $ domain : chr "wikipedia" $ suffix : chr "org" ``` This relies on an internal database of public suffixes, accessible at `suffix_dataset` - we recognise, though, that this dataset may get a bit out of date, so you can also pass the results of the `suffix_refresh` function, which retrieves an updated dataset, to `suffix_extract`: ```{r, eval=FALSE} domain_name <- domain("https://en.wikipedia.org/wiki/Article") updated_suffixes <- suffix_refresh() suffix_extract(domain_name, updated_suffixes) ``` We can do the same thing with top-level domains, with precisely the same setup, except the functions and datasets are `tld_refresh`, `tld_extract` and `tld_dataset`. In the other direction we have `host_extract`, which retrieves, well, the host! If the URL has subdomains, it'll be the lowest-level subdomain. If it doesn't, it'll be the actual domain name, without the suffixes: ```{r, eval=FALSE} domain_name <- domain("https://en.wikipedia.org/wiki/Article") host_extract(domain_name) ``` ### Query manipulation Once a URL is parsed, it's sometimes useful to get the value associated with a particular query parameter. As an example, take the URL `http://en.wikipedia.org/wiki/api.php?action=parse&pageid=1023&export=json`. What pageID is being used? What is the export format? We can find out with `param_get`. ```{r, eval=FALSE} > str(param_get(urls = "http://en.wikipedia.org/wiki/api.php?action=parse&pageid=1023&export=json", parameter_names = c("pageid","export"))) 'data.frame': 1 obs. of 2 variables: $ pageid: chr "1023" $ export: chr "json" ``` This isn't the only function for query manipulation; we can also dynamically modify the values a particular parameter might have, or strip them out entirely. To modify the values, we use `param_set`: ```{r, eval=FALSE} url <- "http://en.wikipedia.org/wiki/api.php?action=parse&pageid=1023&export=json" url <- param_set(url, key = "pageid", value = "12") url # [1] "http://en.wikipedia.org/wiki/api.php?action=parse&pageid=12&export=json" ``` As you can see this works pretty well; it even works in situations where the URL doesn't *have* a query yet: ```{r, eval=FALSE} url <- "http://en.wikipedia.org/wiki/api.php" url <- param_set(url, key = "pageid", value = "12") url # [1] "http://en.wikipedia.org/wiki/api.php?pageid=12" ``` On the other hand we might have a parameter we just don't want any more - that can be handled with `param_remove`, which can take multiple parameters as well as multiple URLs: ```{r, eval=FALSE} url <- "http://en.wikipedia.org/wiki/api.php?action=parse&pageid=1023&export=json" url <- param_remove(url, keys = c("action","export")) url # [1] "http://en.wikipedia.org/wiki/api.php?pageid=1023" ``` ### Other URL handlers If you have ideas for other URL handlers that would make your data processing easier, the best approach is to either [request it](https://github.com/Ironholds/urltools/issues) or [add it](https://github.com/Ironholds/urltools/pulls)!
/scratch/gouwar.j/cran-all/cranData/urltools/inst/doc/urltools.Rmd
<!-- %\VignetteEngine{knitr::knitr} %\VignetteIndexEntry{urltools} --> ## Elegant URL handling with urltools URLs are treated, by base R, as nothing more than components of a data retrieval process: they exist to create connections to retrieve datasets. This is an essential feature for the language to have, but it also means that URL handlers are designed for situations where URLs *get* you to the data - not situations where URLs *are* the data. There is no support for encoding or decoding URLs en-masse, and no support for parsing and interpreting them. `urltools` provides this support! ### URL encoding and decoding Base R provides two functions - <code>URLdecode</code> and <code>URLencode</code> - for taking percentage-encoded URLs and turning them into regular strings, or vice versa. As discussed, these are primarily designed to enable connections, and so they have several inherent limitations, including a lack of vectorisation, that make them unsuitable for large datasets. Not only are they not vectorised, they also have several particularly idiosyncratic bugs and limitations: <code>URLdecode</code>, for example, breaks if the decoded value is out of range: ```{r, eval=FALSE} URLdecode("test%gIL") Error in rawToChar(out) : embedded nul in string: '\0L' In addition: Warning message: In URLdecode("%gIL") : out-of-range values treated as 0 in coercion to raw ``` URLencode, on the other hand, encodes slashes on its most strict setting - without paying attention to where those slashes *are*: if we attempt to URLencode an entire URL, we get: ```{r, eval=FALSE} URLencode("https://en.wikipedia.org/wiki/Article", reserved = TRUE) [1] "https%3a%2f%2fen.wikipedia.org%2fwiki%2fArticle" ``` That's a completely unusable URL (or ewRL, if you will). urltools replaces both functions with <code>url\_decode</code> and <code>url\_encode</code> respectively: ```{r, eval=FALSE} library(urltools) url_decode("test%gIL") [1] "test" url_encode("https://en.wikipedia.org/wiki/Article") [1] "https://en.wikipedia.org%2fwiki%2fArticle" ``` As you can see, <code>url\_decode</code> simply excludes out-of-range characters from consideration, while <code>url\_encode</code> detects characters that make up part of the URLs scheme, and leaves them unencoded. Both are extremely fast; with `urltools`, you can decode a vector of 1,000,000 URLs in 0.9 seconds. Alongside these, we have functions for encoding and decoding the 'punycode' format of URLs - ones that are designed to be internationalised and have unicode characters in them. These also take one argument, a vector of URLs, and can be found at `puny_encode` and `puny_decode` respectively. ### URL parsing Once you've got your nicely decoded (or encoded) URLs, it's time to do something with them - and, most of the time, you won't actually care about most of the URL. You'll want to look at the scheme, or the domain, or the path, but not the entire thing as one string. The solution is <code>url_parse</code>, which takes a URL and breaks it out into its [RfC 3986](http://www.ietf.org/rfc/rfc3986.txt) components: scheme, domain, port, path, query string and fragment identifier. This is, again, fully vectorised, and can happily be run over hundreds of thousands of URLs, rapidly processing them. The results are provided as a data.frame, since most people use data.frames to store data. ```{r, eval=FALSE} > parsed_address <- url_parse("https://en.wikipedia.org/wiki/Article") > str(parsed_address) 'data.frame': 1 obs. of 6 variables: $ scheme : chr "https" $ domain : chr "en.wikipedia.org" $ port : chr NA $ path : chr "wiki/Article" $ parameter: chr NA $ fragment : chr NA ``` We can also perform the opposite of this operation with `url_compose`: ```{r, eval=FALSE} > url_compose(parsed_address) [1] "https://en.wikipedia.org/wiki/article" ``` ### Getting/setting URL components With the inclusion of a URL parser, we suddenly have the opportunity for lubridate-style component getting and setting. Syntax is identical to that of `lubridate`, but uses URL components as function names. ```{r, eval=FALSE} url <- "https://en.wikipedia.org/wiki/Article" scheme(url) "https" scheme(url) <- "ftp" url "ftp://en.wikipedia.org/wiki/Article" ``` Fields that can be extracted or set are <code>scheme</code>, <code>domain</code>, <code>port</code>, <code>path</code>, <code>parameters</code> and <code>fragment</code>. ### Suffix and TLD extraction Once we've extracted a domain from a URL with `domain` or `url_parse`, we can identify which bit is the domain name, and which bit is the suffix: ```{r, eval=FALSE} > url <- "https://en.wikipedia.org/wiki/Article" > domain_name <- domain(url) > domain_name [1] "en.wikipedia.org" > str(suffix_extract(domain_name)) 'data.frame': 1 obs. of 4 variables: $ host : chr "en.wikipedia.org" $ subdomain: chr "en" $ domain : chr "wikipedia" $ suffix : chr "org" ``` This relies on an internal database of public suffixes, accessible at `suffix_dataset` - we recognise, though, that this dataset may get a bit out of date, so you can also pass the results of the `suffix_refresh` function, which retrieves an updated dataset, to `suffix_extract`: ```{r, eval=FALSE} domain_name <- domain("https://en.wikipedia.org/wiki/Article") updated_suffixes <- suffix_refresh() suffix_extract(domain_name, updated_suffixes) ``` We can do the same thing with top-level domains, with precisely the same setup, except the functions and datasets are `tld_refresh`, `tld_extract` and `tld_dataset`. In the other direction we have `host_extract`, which retrieves, well, the host! If the URL has subdomains, it'll be the lowest-level subdomain. If it doesn't, it'll be the actual domain name, without the suffixes: ```{r, eval=FALSE} domain_name <- domain("https://en.wikipedia.org/wiki/Article") host_extract(domain_name) ``` ### Query manipulation Once a URL is parsed, it's sometimes useful to get the value associated with a particular query parameter. As an example, take the URL `http://en.wikipedia.org/wiki/api.php?action=parse&pageid=1023&export=json`. What pageID is being used? What is the export format? We can find out with `param_get`. ```{r, eval=FALSE} > str(param_get(urls = "http://en.wikipedia.org/wiki/api.php?action=parse&pageid=1023&export=json", parameter_names = c("pageid","export"))) 'data.frame': 1 obs. of 2 variables: $ pageid: chr "1023" $ export: chr "json" ``` This isn't the only function for query manipulation; we can also dynamically modify the values a particular parameter might have, or strip them out entirely. To modify the values, we use `param_set`: ```{r, eval=FALSE} url <- "http://en.wikipedia.org/wiki/api.php?action=parse&pageid=1023&export=json" url <- param_set(url, key = "pageid", value = "12") url # [1] "http://en.wikipedia.org/wiki/api.php?action=parse&pageid=12&export=json" ``` As you can see this works pretty well; it even works in situations where the URL doesn't *have* a query yet: ```{r, eval=FALSE} url <- "http://en.wikipedia.org/wiki/api.php" url <- param_set(url, key = "pageid", value = "12") url # [1] "http://en.wikipedia.org/wiki/api.php?pageid=12" ``` On the other hand we might have a parameter we just don't want any more - that can be handled with `param_remove`, which can take multiple parameters as well as multiple URLs: ```{r, eval=FALSE} url <- "http://en.wikipedia.org/wiki/api.php?action=parse&pageid=1023&export=json" url <- param_remove(url, keys = c("action","export")) url # [1] "http://en.wikipedia.org/wiki/api.php?pageid=1023" ``` ### Other URL handlers If you have ideas for other URL handlers that would make your data processing easier, the best approach is to either [request it](https://github.com/Ironholds/urltools/issues) or [add it](https://github.com/Ironholds/urltools/pulls)!
/scratch/gouwar.j/cran-all/cranData/urltools/vignettes/urltools.Rmd
# the code for function 'ch.rs.pvalue' below has been # ported from gretl code provided by Ignacio Díaz-Emparanza and M. Paz Moral (2013) # http://www.ehu.eus/ignacio.diaz-emparanza/packages/Canova_Hansen.gfn # "Seasonal Stability Tests in gretl. An Application to International Tourism Data" # Ignacio Díaz-Emparanza and M. Paz Moral, Working Paper Biltoki D.T. 2013.03 # https://addi.ehu.es/handle/10810/10577 ch.rs.pvalue <- function(x, type, lag1, S, n, nobsreg, VMdf) { if (type == "dummy") { CMlabel <- if (isTRUE(lag1)) "1_D_qy" else "1_D_q0" } else { # type == "trigonometric" tmp <- which(c(1, 2, S-1) == VMdf) if (length(tmp) == 0) { stop("unexpected value of ", sQuote("VMdf")) } else CMlabel <- paste0("1_", c("Pi", "Dos", "Ft")[tmp]) tmp <- if (isTRUE(lag1)) "_qy" else "_q0" CMlabel <- paste0(CMlabel, tmp) } CM <- .CH.CM.tabs[[CMlabel]] SdErrs <- CM[,ncol(CM)] Coeffs <- CM[,-ncol(CM)] rq <- c(0.0001, 0.0002, 0.0005, seq(0.001, 0.01, 0.001), seq(0.015, 0.985, 0.005), seq(0.99, 0.999, 0.001), 0.9995, 0.9998, 0.9999) nrq <- length(rq) if (type == "dummy") { xeplc <- c(1, 1/n, 1/n^2, 1/n^3, S/n, S/n^2, S/n^3) } else { # type == "trigonometric" if (VMdf %in% c(1, 2)) { xeplc <- c(1, 1/n, 1/n^2, S/n, S/n^2) } else # VMdf == S-1, all seasonal frequencies xeplc <- c(1, 1/n, 1/n^2, S/n, S/n^2, S-1, (S-1)^2) } Q1 <- sort(Coeffs %*% xeplc) if (x < Q1[1]) { return(1) } else if (x > Q1[nrq]) return(0) Mdif <- cbind(seq_len(nrq), abs(Q1 - x)) Msort <- Mdif[order(Mdif[,2]),] mascer <- Msort[1,1] swindow <- (nobsreg - 1)/2 minq <- if (mascer <= swindow) 1 else mascer - swindow maxq <- if (mascer + swindow >= nrq) nrq else mascer + swindow maxq <- if (maxq == 1) nobsreg else maxq minq <- if (maxq == nrq) maxq - nobsreg + 1 else minq qi <- Q1[seq.int(minq, maxq)] pri <- rq[seq.int(minq, maxq)] si <- SdErrs[seq.int(minq, maxq)] Y <- qchisq(pri, df = 2) X <- cbind(1, qi, qi^2, qi^3) pri1 <- sqrt(pri / (1 - pri)) pri2 <- si / pri1 # Sigma <- matrix(0, nrow = nobsreg, ncol = nobsreg) Sigma <- matrix(0, nrow = length(si), ncol = length(si)) uid <- upper.tri(Sigma, diag = TRUE) Sigma[uid] <- tcrossprod(pri1 * si, pri2)[uid] Sigma <- t(Sigma) + Sigma - diag(si^2) Pinv <- t(solve(chol(Sigma))) PY <- Pinv %*% Y PX <- Pinv %*% X fit <- lm(PY ~ 0 + PX) valorcomp <- abs(sum(coef(fit) * c(1, x, x^2, x^3))) pchisq(q = valorcomp, df = 2, lower.tail = FALSE) }
/scratch/gouwar.j/cran-all/cranData/uroot/R/ch-rs-pvalue.R
print.CHtest <- function(x, digits = max(3L, getOption("digits") - 2L), dig.tst = max(1L, min(5L, digits - 1L)), print.fittedmodel = FALSE, ...) { tab <- cbind(round(cbind(statistic=x$stat, pvalue=x$pval), dig.tst), format(x$pvlabels)) cat("\n") cat(strwrap(x$method, prefix = "\t"), sep = "\n") cat("\n") cat("data: ", x$data.name, "\n\n", sep = "") if (print.fittedmodel) { x$fitted.model$series <- x$data.name cat("Fitted model\n") cat("------------\n") if (x$method.fit == "qr") print(summary(x$fitted.model)) else print(x$fitted.model) if (x$method.fit == "qr") cat("Test statistic\n") else cat("\nTest statistic\n") cat("--------------\n") } print(tab, quote = FALSE, right = TRUE, digits = digits, ...) cat("---\n") cat("Signif. codes:", attributes(x$pvlabels)$legend, "\n") if (!x$isNullxreg) { xregnms <- names(coef(x$fitted.model)) xregnms <- xregnms[-seq_len(tail(grep("ypi.Ypi", xregnms),1))] xregnms <- paste(xregnms,collapse=", ") } else xregnms <- NULL cat("\n") cat(paste("Test type:", switch(x$type, "dummy" = "seasonal dummies", "seasonal cycles"), "\n")) cat(paste("NW covariance matrix lag order:", x$NW.order, "\n")) cat(paste("First order lag:", c("no", "yes")[as.numeric(x$lag1)+1], "\n")) cat(paste("Other regressors:", c("yes, ", "no")[as.numeric(x$isNullxreg)+1], xregnms, "\n")) cat(paste("P-values:", switch(x$type.pvalue, "RS" = "based on response surface regressions", "raw" = "interpolation in original tables"), "\n")) } summary.CHtest <- function(object, ...) { print.CHtest(object, print.fittedmodel = TRUE, ...) }
/scratch/gouwar.j/cran-all/cranData/uroot/R/ch-test-print.R
ch.test <- function(x, type = c("dummy", "trigonometric"), lag1 = FALSE, NW.order = NULL, sid = NULL, xreg = NULL, pvalue = c("RS", "raw"), rs.nobsreg = 13) { ch.test0 <- function(id) { # robust covariance matrix estimator # scaled by the seasonal components # based on function "sandwich::NeweyWest" # (other options used in package "sandwich" could be considered here) # OmegafHat <- crossprod(SD * ehat) / n SDe <- SD[,id,drop=FALSE] * ehat if (NW.order > 0) { weights <- 1 - seq_len(NW.order) / (NW.order + 1) OmegafHat <- 0.5 * crossprod(SDe) for (i in seq_along(weights)) OmegafHat <- OmegafHat + weights[i] * crossprod(SDe[seq_len(n-i),,drop=FALSE], SDe[-seq_len(i),,drop=FALSE]) OmegafHat <- OmegafHat + t(OmegafHat) } else OmegafHat <- crossprod(SDe) OmegafHat <- OmegafHat / n # auxiliary elements # cumulative sum by columns in "SDe" ("SD" multiplied by "ehat" by columns) Fhat <- apply(SDe, MARGIN = 2, FUN = cumsum) # summation of crossproducts of "Fhat" Fhat.cp <- matrix(0, nrow = nrow(OmegafHat), ncol = ncol(OmegafHat)) for (i in seq_len(n)) Fhat.cp <- Fhat.cp + tcrossprod(Fhat[i,]) # test statistic sum(diag(chol2inv(chol(OmegafHat)) %*% Fhat.cp)) / n^2 } data.name <- deparse(substitute(x)) type <- match.arg(type) pvalue <- match.arg(pvalue) isNullxreg <- is.null(xreg) n <- length(x) if (!isNullxreg && NROW(xreg) != n) stop("wrong dimension of argument ", sQuote("xreg")) S <- frequency(x) if (S < 2) stop("the time series is not seasonal") if (is.null(NW.order)) NW.order <- round(S * (n/100)^0.25) # indicator variable for the target seasonal dummies or cycles if (is.null(sid)) { sid <- "all" } else { #if (!identical(sid, "all")) if (is.numeric(sid)) { if (type == "trigonometric") { if (length(sid) != floor(S/2)) stop("wrong length of argument ", sQuote("sid")) tmp <- head(sid, -1) id <- which(c(rbind(tmp, tmp)) == 1) if (tail(sid, 1) == 1) id <- c(id, S-1) } else { if (any(!(sid %in% seq_len(S)))) # assumed that no duplicates are defined stop("wrong definition of argument ", sQuote("sid")) id <- sid } } else if (!(sid %in% c("all", "joint"))) stop("wrong definition of argument ", sQuote("sid")) } # create target regressor variables (seasonal dummies or seasonal cycles) switch(type, "dummy" = { # seasonal dummies #SD <- seasonal.dummies(x) SD <- do.call("rbind", replicate(ceiling(n/S), diag(S), simplify = FALSE)) SD <- ts(SD, frequency = S, start = c(start(x)[1], 1)) # ignore warning "'end' value not changed" SD <- suppressWarnings(window(SD, start = start(x), end = end(x))) }, "trigonometric" = { # seasonal cycles Sh <- floor(S/2) isSeven <- as.numeric(S %% 2 == 0) if (S %in% c(4, 12) && n/S <= 50) { SD <- .SDtrig[[as.character(S)]][seq_len(n),] } else { #SD <- seasonal.cycles(x) tmp <- matrix(seq_len(n), nrow = Sh-isSeven, ncol = n, byrow = TRUE) seqsm1 <- seq_len(nrow(tmp)) tmp <- (2 * seqsm1 * pi / S) * tmp SD <- rbind(cos(tmp), sin(tmp)) SD <- t(SD[c(rbind(seqsm1, seqsm1 + nrow(tmp))),]) if ((S %% 2) == 0) SD <- cbind(SD, rep(c(-1, 1), len = n)) #SD <- ts(SD, frequency = S, start = c(start(x)[1], 1)) } } ) # switch colnames(SD) <- paste0("SD", seq_len(ncol(SD))) # arrange other possible exogenous variables if (lag1) { SD <- SD[-1,] # updating SD is required as well as it will be used by "ch.test0" xreg <- cbind(lag1 = x[-n], SD, xreg[-1,]) x <- x[-1] n <- n - 1 } else xreg <- cbind(SD, xreg) ##NOTE # in principle it is not a good idea to define the intercept in "xreg" and # use lm(x ~ 0 + xreg) because stats::summary.lm uses attr(z$terms, "intercept") # to compute the R-squared, but here the R-squared is not used if (type == "trigonometric") xreg <- cbind(c = 1, xreg) # fit regression model and get residuals fit <- lm(x ~ 0 + xreg) ehat <- residuals(fit) # used with pvalue = "RS" Nc <- n - ncol(xreg) # test statistics if (identical(sid, "all")) { if (type == "dummy") { stat <- matrix(nrow = S+1, ncol = 2) id <- 0 for (i in seq_len(S)) { id <- id + 1 stat[i,1] <- ch.test0(id) stat[i,2] <- switch(pvalue, #"raw" = 1 - .CH.cvals[[1]](stat[i,1]), "raw" = uroot.raw.pvalue(stat[i,1], "CH", 1), "RS" = ch.rs.pvalue(stat[i,1], "dummy", lag1, S, Nc, rs.nobsreg, 1)) } stat[S+1,1] <- ch.test0(seq_len(S)) ##NOTE to mention in documentation #"RS" p-value is not available for the joint test with dummies stat[S+1,2] <- uroot.raw.pvalue(stat[S+1,1], "CH", S) colnames(stat) <- c("statistic", "p-value") rownames(stat) <- c(switch(as.character(S), "4" = paste0("Quarter", seq_len(S)), "12" = month.abb, paste0("Season", seq_len(S))), "joint") } else { #type == "trigonometric" Shp1 <- Sh + 1 stat <- matrix(nrow = Shp1, ncol = 2) id <- c(-1, 0) for (i in seq_len(Sh-isSeven)) { id <- id + 2 stat[i,1] <- ch.test0(id) stat[i,2] <- switch(pvalue, "raw" = uroot.raw.pvalue(stat[i,1], "CH", 2), "RS" = ch.rs.pvalue(stat[i,1], "trigonometric", lag1, S, Nc, rs.nobsreg, 2)) } if (isSeven) { stat[Sh,1] <- ch.test0(S-1) stat[Sh,2] <- switch(pvalue, "raw" = uroot.raw.pvalue(stat[Sh,1], "CH", 1), "RS" = ch.rs.pvalue(stat[Sh,1], "trigonometric", lag1, S, Nc, rs.nobsreg, 1)) } stat[Shp1,1] <- ch.test0(seq_len(S-1)) stat[Shp1,2] <- switch(pvalue, "raw" = uroot.raw.pvalue(stat[Shp1,1], "CH", S-1), "RS" = ch.rs.pvalue(stat[Shp1,1], "trigonometric", lag1, S, Nc, rs.nobsreg, S-1)) colnames(stat) <- c("statistic", "p-value") if (isSeven) { rownames(stat) <- c(paste0("pi/", Sh), if(Sh > 2) paste0(seq.int(2, Sh-1), "pi/", Sh), "pi", "joint") } else rownames(stat) <- c(paste0(seq.int(2, S, 2), "pi/", S), "joint") } } else # sid != "all" if (identical(sid, "joint")) { if (type == "dummy") { stat <- ch.test0(seq_len(S)) stat <- cbind("joint" = stat, "p-value" = uroot.raw.pvalue(stat, "CH", S)) } else { # type trigonometric stat <- ch.test0(seq_len(S-1)) pval <- switch(pvalue, "raw" = uroot.raw.pvalue(stat, "CH", S-1), "RS" = ch.rs.pvalue(stat, type, lag1, S, Nc, rs.nobsreg, S-1)) stat <- cbind("joint" = stat, "p-value" = pval) } } else { # "sid" is a numeric vector indicating the index of the # seasonal dummy(s) or cycle(s) to be tested if (pvalue == "RS") { #it could be checked if a case for which "RS" p-values are available #is requested through "sid", but for that end, simply use default "sid" value pvalue <- "raw" warning("argument ", sQuote("pvalue"), " was changed to ", sQuote("raw")) } #if length(id) > 1, a joint test for those seasons or cycles is obtained stat <- ch.test0(id) pval <- uroot.raw.pvalue(stat, "CH", length(id)) stat <- rbind(c(stat, pval)) colnames(stat) <- c("statistic", "p-value") if (type == "dummy") { rownames(stat) <- switch(as.character(S), "4" = paste("Quarter(s)", paste0(id, collapse = ",")), "12" = paste(month.abb[id], collapse = ","), paste("Season(s)", paste0(id, collapse = ","))) } else { # type trigonometric ##TODO S odd (see how this is arranged above) } } # output res <- list(statistics = stat[,1], pvalues = stat[,2], method = "Canova and Hansen test for seasonal stability", data.name = data.name, type = type, fitted.model = fit, NW.order = NW.order, lag1 = lag1, isNullxreg = isNullxreg, type.pvalue = pvalue, pvlabels = symnum(stat[,"p-value"], corr = FALSE, na = FALSE, cutpoints = c(0, 0.001, 0.01, 0.05, 0.1, 1), symbols = c("***","**","*","."," "))) class(res) <- "CHtest" res }
/scratch/gouwar.j/cran-all/cranData/uroot/R/ch-test.R
hegy.boot.pval <- function(x, model0, stats0, deterministic = c(1,0,0), lag.method = c("fixed", "AIC", "BIC"), maxlag = 0, byseason = FALSE, nb = 500, u = NULL, debug.tid = -1) { lag.method <- match.arg(lag.method) S <- frequency(x) #nx <- length(x) - S e <- residuals(model0) arcoefs <- coef(model0) arcoefs <- arcoefs[grepl("Lag\\d{1,3}$", names(arcoefs))] narcoefs <- length(arcoefs) Spnlags <- S + narcoefs ns <- c(length(x) + S + narcoefs, length(e)) if (!is.null(u)) { if (nrow(u) != ns[1]) stop("not enough rows in argument ", sQuote("u")) if (ncol(u) < nb) stop("not enough columns in argument ", sQuote("u")) } refnms <- names(stats0) bpvals <- rep(0, length(stats0)) for (i in seq_len(nb)) { # generate data # resample residuals and use them as innovations in the model under # the null hypothesis (seasonal random walk possibly with serial correlation) if (byseason) { #e <- ts(e, frequency = S, start = time(x)[S+narcoefs+1]) e <- ts(e, frequency = S, start = time(x)[narcoefs+1]) le <- split(e, cycle(e)) if (is.null(u)) { if ((length(e) %% S) == 0) { tmp <- lapply(le, FUN = function(x) sample(x, size = length(x) + 2, replace = TRUE)) be <- do.call("rbind", tmp) be <- c(be[cycle(x)[seq_len(S)],]) } else { # (length(e) %% S) != 0) tmp <- vector("list", S) nse <- table(cycle(x)) + 1 j <- 0 for (k in cycle(x)[seq_len(S)+narcoefs]) { j <- j + 1 tmp[[j]] <- sample(le[[k]], size = nse[k], replace = TRUE) } be <- suppressWarnings(c(do.call("rbind", tmp))) be <- be[seq_len(length(be) - length(x) %% S)] } } else { #!is.null(u) be <- unlist(le)[u[,i]] } if (narcoefs == 0) { bx <- ts(filter(be[-seq_len(S)], filter = c(rep(0, S-1),1), method = "rec", init = rev(be[seq_len(S)])), frequency = S, start = start(x)) } else { # narcoefs > 0 m <- outer(c(1, -arcoefs), c(1, rep(0, S-1),-1)) pcoefs <- as.vector(tapply(m, row(m) + col(m), sum)) bx <- ts(filter(be[-seq_len(Spnlags)], filter = -pcoefs[-1], method = "rec", init = rev(be[seq_len(Spnlags)])), frequency = S, start = start(x)) } } else # !byseason { if (is.null(u)) { be <- sample(e, size = ns[1], replace = TRUE) } else { be <- e[u[,i]] } if (narcoefs == 0) { bx <- ts(filter(be[-seq_len(S)], filter = c(rep(0, S-1),1), method = "rec", init = rev(be[seq_len(S)])), frequency = S, start = start(x)) } else # narcoefs > 0 { m <- outer(c(1, -arcoefs), c(1, rep(0, S-1),-1)) pcoefs <- as.vector(tapply(m, row(m) + col(m), sum)) bx <- ts(filter(be[-seq_len(Spnlags)], filter = -pcoefs[-1], method = "rec", init = rev(be[seq_len(Spnlags)])), frequency = S, start = start(x)) } } # HEGY statistics for the bootstrap replicate bres <- hegy.test(bx, deterministic = deterministic, lag.method = lag.method, maxlag = maxlag, pvalue = "raw") # counter # increment those statistics that are more extreme (in the right tail) # than the statistics obtained for the original data for (j in seq_along(bpvals)) { if (grepl("t\\_", refnms[j])) { if (bres$stat[j] <= stats0[j]) bpvals[j] <- bpvals[j] + 1 } else if (bres$stat[j] >= stats0[j]) bpvals[j] <- bpvals[j] + 1 } if (debug.tid == i-1) return(bx) } # loop seq_len(nb) names(bpvals) <- refnms bpvals/nb }
/scratch/gouwar.j/cran-all/cranData/uroot/R/hegy-boot-pval.R
hegy.regressors <- function(x) { n <- length(x) S <- frequency(x) isSeven <- (S %% 2) == 0 isSevenp2 <- 2 + isSeven ML <- x for (i in seq_len(S-1)) ML <- cbind(ML, lag(x, -i)) ML <- window(ML, end = end(x)) ML <- sapply(seq.int(0, S-1), function(x, y, n) c(rep(NA,length.out=x), y[seq_len(n-x)]), y=x, n=n) ypi <- matrix(nrow = n, ncol = S) ypi[,1] <- rowSums(ML) if (isSeven) ypi[,2] <- ML %*% rep(c(-1, 1), len = S) seqS <- seq_len(S) j <- 0 sinesign <- -1 id <- seq.int(isSevenp2, S, 2) ref <- ceiling(S) / 4 for (i in id) { j <- j + 1 seqw <- seqS * (2 * pi * j / S) ypi[,i] <- ML %*% cos(seqw) ypi[,i+1] <- sinesign * ML %*% sin(seqw) if (j == ref) sinesign <- -1 * sinesign } ypi <- rbind(NA, ypi[-n,]) colnames(ypi) <- paste("Ypi", seq_len(S), sep="") ypi[-seq_len(S),] }
/scratch/gouwar.j/cran-all/cranData/uroot/R/hegy-regressors.R
# the code for function 'hegy.rs.pvalue' below has been # ported from gretl code provided by Ignacio Díaz-Emparanza (2014) # http://www.ehu.eus/ignacio.diaz-emparanza/packages/GHegy.gfn # "Numerical Distribution Functions for Seasonal Unit Root Tests", # Computational Statistics and Data Analysis, Volume 76, pages 237-247 # The Annals of Computational and Financial Econometrics - 2nd Issue # DOI: http://dx.doi.org/10.1016/j.csda.2013.03.006 hegy.rs.pvalue <- function(x, type = c("zero", "pi", "pair", "seasall", "all"), deterministic = c(1,0,0), lag.method = c("fixed", "AIC", "BIC"), #"HQC" lag.order, S, n, nobsreg) { type <- match.arg(type) if (is.numeric(deterministic)) deterministic <- paste(deterministic, collapse = "") lag.method <- match.arg(lag.method) if (deterministic == "000") stop("the combination of deterministic components ", sQuote(deterministic), " is not available for ", sQuote("pvalue=\"RS\"")) ##NOTE #casedet = "000" is not considered CMlabel <- switch(type, "zero" = "Ct1", "pi" = "Ct2", "pair" = "CF", "seasall" = "CFs", "all" = "CFt") tmp <- switch(deterministic, "100" = "c", "110" = "ct", "101" = "cD", "111" = "cDt") CMlabel <- paste(CMlabel, tmp, sep = "_") tmp <- switch(lag.method, "fixed" = "fijo", "AIC" = "AIC", "BIC" = "BIC", "HQC" = "HQC") CMlabel <- paste(CMlabel, tmp, sep = "_") C <- .HEGY.CM.tabs[[CMlabel]] nc <- ncol(C) C1 <- C[,seq_len(nc-1)] sdC1 <- C[,nc] r1 <- c(0.0001, 0.0002, 0.0005, seq_len(10)/1000) rq <- c(r1, seq.int(15, 985, 5)/1000, 1 - rev(r1)) xeplc <- c(1, 1/n, 1/n^2, 1/n^3, lag.order/n, lag.order/n^2, lag.order/n^3, lag.order^2/n, lag.order^2/n^2, lag.order^2/n^3, lag.order^3/n, lag.order^3/n^2, lag.order^3/n^3, S/n, S/n^2, S/n^3) Q1 <- C1 %*% xeplc nrq <- length(rq) centro <- floor(nobsreg/2) + 1 isFtest <- !(type %in% c("zero", "pi")) if (isFtest) { stopifnot(NCOL(Q1) == 1) Q1 <- rev(Q1) } bin <- rep(0, nrq) bin[Q1 >= 0] <- 1 sbin <- sum(bin) if (isFtest) sdC1 <- rev(sdC1) Q1s <- sort(Q1) if (x < Q1s[1]) { if (isFtest) return(1) else return(0) } else if (x > tail(Q1s, 1)) { if (isFtest) return(0) else return(1) } else { masque <- which(x > Q1) masque <- if (length(masque) > 0) max(masque) else 1 if (masque < nrq) { mascer <- if ((x - Q1[masque]) < (Q1[masque+1] - x)) masque else masque + 1 } else mascer <- nrq centroup <- nrq - centro + 1 mascer <- if (mascer <= centro) centro else mascer mascer <- if (mascer >= centroup) centroup else mascer # local regressions with "nobsreg" observations qi <- pri <- si <- rep(NA, nobsreg) for (i in seq_len(nobsreg)) { j <- mascer - centro + i qi[i] <- Q1[j] pri[i] <- rq[j] si[i] <- sdC1[j] } Y <- if (isFtest) qchisq(pri, df = 2) else qnorm(pri) X <- cbind(1, qi, qi^2, qi^3) co <- lm.fit(X, Y)$coef # substitute by FGLS Sigma <- matrix(0, nrow = nobsreg, ncol = nobsreg) for (i in seq_len(nobsreg)) { for (j in seq_len(nobsreg)) if (i <= j) { Sigma[i,j] <- (si[i]*si[j])*sqrt((pri[i]*(1-pri[j]))/(pri[j]*(1-pri[i]))) } else Sigma[i,j] <- (si[i]*si[j])*sqrt((pri[j]*(1-pri[i]))/(pri[i]*(1-pri[j]))) } Pinv <- t(solve(chol(Sigma))) PY <- Pinv %*% Y PX <- Pinv %*% X co <- lm.fit(PX, PY)$coef valorcomp <- sum(co * c(1, x, x^2, x^3)) if (isFtest) { pval <- pchisq(q = abs(valorcomp), df = 2, lower.tail = FALSE) } else pval <- pnorm(q = valorcomp, lower.tail = TRUE) } pval }
/scratch/gouwar.j/cran-all/cranData/uroot/R/hegy-rs-pvalue.R
residuals.HEGYtest <- function(object, ...) residuals(object$fit) print.HEGYtest <- function(x, digits = max(3L, getOption("digits") - 2L), dig.tst = max(1L, min(5L, digits - 1L)), print.fittedmodel = FALSE, ...) { tab <- cbind(round(cbind(statistic=x$stat, "p-value"=x$pval), dig.tst), format(x$pvlabels)) cat("\n") cat(strwrap(x$method, prefix = "\t"), sep = "\n") cat("\n") cat("data: ", x$data.name, "\n\n", sep = "") if (print.fittedmodel) { x$fitted.model$series <- x$data.name cat("Fitted model\n") cat("------------\n") print(summary(x$fitted.model)) cat("Test statistic\n") cat("--------------\n") } print(tab, quote = FALSE, right = TRUE, digits = digits, ...) cat("---\n") cat("Signif. codes:", attributes(x$pvlabels)$legend, "\n") cat("\n") cat(paste("Deterministic terms:", x$strdet, "\n")) cat(paste("Lag selection criterion and order: ", x$lag.method, ", ", x$lag.order, "\n", sep = "")) cat(paste("P-values:", switch(x$type.pvalue, "RS" = "based on response surface regressions", "bootstrap" = paste0("based on bootstrap (", x$bootstrap$nb, " replicates)"), "raw" = "by interpolation in original tables"), "\n")) } summary.HEGYtest <- function(object, ...) { print.HEGYtest(object, print.fittedmodel = TRUE, ...) }
/scratch/gouwar.j/cran-all/cranData/uroot/R/hegy-test-print.R
hegy.test <- function(x, deterministic = c(1,0,0), lag.method = c("fixed", "AIC", "BIC", "AICc"), maxlag = 0, pvalue = c("RS", "bootstrap", "raw"), #args related to response surface method rs.nobsreg = 15, #args related to bootstrap method boot.args = list(seed = 123, #lag.method = c("fixed", "AIC", "BIC", "AICc"), maxlag = 0, lag.method = lag.method[1], maxlag = maxlag, byseason = FALSE, nb = 1000, BTdim = c(100, 10), debug.tid = -1)) { F.test.stat <- function(id) { if (length(id) == S) { if (is.null(xreg)) { #model with no HEGY regressors and deterministic=c(0,0,0) rss1 <- sum(dx^2) dfs1 <- length(dx) return(((rss1 - rss2) / (dfs1 - dfs2)) / (rss2 / dfs2)) } else fit1 <- lm(dx ~ 0 + xreg) } else fit1 <- lm(dx ~ 0 + cbind(xreg, ypi[,-id])) rss1 <- deviance(fit1) dfs1 <- df.residual(fit1) ((rss1 - rss2) / (dfs1 - dfs2)) / (rss2 / dfs2) } xreg <- NULL stopifnot(is.ts(x)) n <- length(x) S <- frequency(x) if (S < 2) stop("the time series is not seasonal") isSeven <- (S %% 2) == 0 isSevenp2 <- 2 + isSeven dx <- diff(x, S) #xreg <- if (is.matrix(xreg)) xreg[-seq_len(S),] else xreg[-seq_len(S)] if (!is.null(xreg) && NROW(xreg) != length(dx)) stop("the number of rows in argument ", sQuote("xreg"), " does not match the length of ", sQuote("diff(x, frequency(x))")) data.name <- deparse(substitute(x)) lag.method <- match.arg(lag.method) isNullxreg <- is.null(xreg) pvalue <- match.arg(pvalue) if (lag.method == "AICc" && pvalue == "RS") { ##NOTE #response surfaces are not provided by the reference paper DE14 #they are available for the Hannan-Quinn criterion, see add this option here lag.method <- "AIC" warning("argument ", sQuote("lag.method"), " was changed to ", sQuote("AIC")) } if (pvalue == "bootstrap") { #if (!isNullxreg) # warning("argument ", sQuote("xreg"), " was set to NULL") #if (!is.null(boot.args$lag.method)) #boot.args$lag.method <- boot.args$lag.method[1] # default arguments #bargs <- list(seed = 123, lag.method = "fixed", # maxlag = 0, byseason = FALSE, nb = 1000, BTdim = c(100, 10), debug.tid = -1) bargs <- list(seed = 123, lag.method = lag.method[1], maxlag = maxlag, byseason = FALSE, nb = 1000, BTdim = c(100, 10), debug.tid = -1) nms1 <- names(boot.args) notinldef <- !(nms1 %in% names(bargs)) wno <- which(notinldef) if (any(notinldef)) warning("the following elements in ", sQuote("boot.args"), " were omitted: ", paste(sQuote(nms1[wno]), collapse = ", "), ".", call. = FALSE) if (length(boot.args) > 0) { if (any(notinldef)) { bargs[nms1[which(!notinldef)]] <- boot.args[-wno] } else bargs[nms1] <- boot.args } } # storage matrix stats <- matrix(nrow = floor(S/2) + 3, ncol = 2) id <- seq.int(isSevenp2, S, 2) rownames(stats) <- c("t_1", if (isSeven) "t_2" else NULL, paste("F", apply(cbind(id, id + 1), 1, paste, collapse=":"), sep = "_"), paste0("F_2:", S), paste0("F_1:", S)) colnames(stats) <- c("statistic", "p-value") # deterministic terms if (all(deterministic == c(0,0,1))) deterministic <- c(1,0,1) if (deterministic[1] == 1) { strdet <- "constant" xreg <- cbind(xreg, c = rep(1, n - S)) } else strdet <- "" ##NOTE #in principle it is not a good idea to define the intercept in "xreg" and #use lm(x ~ 0 + xreg) because stats::summary.lm uses attr(z$terms, "intercept") #to compute the R-squared and the F statistic includes the intercept (not the usual test), #but here the R-squared and the F-statistic are not used if (deterministic[2] == 1) { xreg <- cbind(xreg, trend = seq_along(dx)) strdet <- paste(strdet, "+ trend") } if (deterministic[3] == 1) { SD <- do.call("rbind", replicate(ceiling(length(dx)/S), diag(S), simplify = FALSE)) SD <- ts(SD, frequency = S, start = start(dx)) # ignore warning "'end' value not changed" SD <- suppressWarnings(window(SD, start = start(dx), end = end(dx))) colnames(SD) <- paste0("SD", seq_len(S)) if (deterministic[1] == 1) SD <- SD[,-1] xreg <- cbind(xreg, SD) strdet <- paste0(strdet, ifelse(deterministic[1] == 1, " + ", ""), "seasonal dummies") } if (strdet == "") strdet <- "none" # lags of the dependent variable if (maxlag > 0) { dxlags <- dx for (i in seq_len(maxlag)) dxlags <- cbind(dxlags, lag(dx, -i)) dxlags <- window(dxlags, end = end(dx))[,-1] if (is.null(dim(dxlags))) dxlags <- as.matrix(dxlags) #NOTE this way would be a bit faster #sapply(seq_len(maxlag), function(x) c(rep(NA,length.out=x), c(1:10)[1:(10-x)])) colnames(dxlags) <- paste("Lag", seq_len(maxlag), sep ="") if (lag.method == "fixed") { #NOTE 'data.frame' keeps column names, 'cbind' doesn't; #'data.matrix' is required in order to be accepted by 'lm' xreg <- data.matrix(data.frame(xreg, dxlags)) } # else, do not add dxlags here since they will be selected below } #else # maxlags == 0 #nlags == 0 #str.lag.order <- lag.order <- 0 # HEGY regressors ypi <- hegy.regressors(x) # lag order selection if (maxlag > 0) { if (lag.method != "fixed") { # information criteria are obtained using the same number of observations # regardless of the number of lags included in a given model tmp <- vector("list", maxlag + 1) # model with no lags id <- seq_len(maxlag) tmp[[1]] <- lm(dx[-id] ~ 0 + ypi[-id,] + xreg[-id,]) dxlags2 <- dxlags[-id,] #http://stackoverflow.com/questions/23154074/writing-a-loop-in-r-that-updates-a-model?rq=1 #the loop does not resolve the "i" and new variables are not distinguished #tmp[[i+1]] <- update(tmp[[i]], . ~ . + dxlags[,i,drop=FALSE]) for (i in seq_len(maxlag)) tmp[[i+1]] <- update(tmp[[i]], as.formula(paste0(". ~ . + dxlags2[,",i,"]"))) icvals <- unlist(switch(lag.method, "AIC" = lapply(tmp, AIC), "BIC" = lapply(tmp, BIC), "AICc" = lapply(tmp, function(x) { k <- x$rank+1; -2*logLik(x) + 2*k + (2*k*(k+1))/(length(residuals(x))-k-1) }))) id <- which.min(icvals) # update lag order (tmp[[1]] contains 0 lags) maxlag <- id - 1 if (maxlag > 0) { xreg <- data.matrix(data.frame(xreg, dxlags[,seq_len(maxlag),drop=FALSE])) } } # else, lag.method=="fixed", dxlags was added to reg above } # fit the model with the chosen lags (if any) # using the entire sample (i.e., including the first 'maxlag' observations) fit2 <- lm(dx ~ 0 + ypi + xreg) # test statistics rss2 <- deviance(fit2) dfs2 <- df.residual(fit2) j <- isSevenp2 for (i in seq.int(isSevenp2, S, 2)) { id <- c(i, i+1) stats[j,1] <- F.test.stat(id) j <- j + 1 } stats[j,1] <- F.test.stat(seq.int(2, ncol(ypi))) # F-test statistic for all HEGY regressors stats[j+1,1] <- F.test.stat(seq_len(S)) # t-test statistics id <- seq_len(1 + isSeven) #+ ncxreg stats[seq_along(id),1] <- coef(fit2)[id] / sqrt(diag(vcov(fit2))[id]) # p-values # used with pvalue equal to "RS" or "raw" ctd <- paste(deterministic, collapse = "") if (pvalue == "RS") { stats[1,2] <- hegy.rs.pvalue(stats[1,1], "zero", ctd, lag.method, maxlag, S, dfs2, rs.nobsreg) if (isSeven) stats[2,2] <- hegy.rs.pvalue(stats[2,1], "pi", ctd, lag.method, maxlag, S, dfs2, rs.nobsreg) for (i in seq.int(isSevenp2, (S+4)/2-1)) stats[i,2] <- hegy.rs.pvalue(stats[i,1], "pair", ctd, lag.method, maxlag, S, dfs2, rs.nobsreg) j <- nrow(stats) - 1 stats[j,2] <- hegy.rs.pvalue(stats[j,1], "seasall", ctd, lag.method, maxlag, S, dfs2, rs.nobsreg) stats[j+1,2] <- hegy.rs.pvalue(stats[j+1,1], "all", ctd, lag.method, maxlag, S, dfs2, rs.nobsreg) } else if (pvalue == "bootstrap") { e <- residuals(fit2) dgp.nlags <- maxlag if (dgp.nlags > 0) { arcoefs <- coef(fit2) arcoefs <- arcoefs[grepl("Lag\\d{1,3}$", names(arcoefs))] if (length(arcoefs) != dgp.nlags) # debug stop("unexpected number of lags") } else arcoefs <- 0 BTdim <- bargs$BTdim nb <- bargs$nb if (is.null(BTdim)) { BTdim <- rep(ceiling(sqrt(nb)), 2) } else if (prod(BTdim) < nb) { stop("the number of threads is lower than the number of bootstrap replicates") } #NOTE n-S is passed as the length of the data, #the length of diff(x,S) is required by hegy_boot_pval if (bargs$byseason) { e <- ts(e, frequency = S) csns <- cumsum(table(cycle(e))) #names(csns) <- cycle(dx)[seq.int(dgp.nlags+1, length.out=S)] e <- unlist(split(e, cycle(e))) } else { csns <- c(0, length(e)) } boot.lag.method <- match.arg(bargs$lag.method, c("fixed", "AIC", "BIC")) chosen.lags <- if (boot.lag.method == "fixed") integer(1) else integer(bargs$nb) ## removed with cuda stuff ## if (@HAS_CUDA@) ## { ## tmp <- .C("hegy_boot_pval", dim = as.integer(c(nb, BTdim)), ## seed = as.integer(bargs$seed), idc = as.integer(deterministic), ## ip = as.integer(c(S, n-S, dgp.nlags, bargs$maxlag, bargs$debug.tid)), ## csns = as.integer(csns), ## eps = as.double(e), arcoefs = as.double(arcoefs), ## stats0 = as.double(stats[,1]), ## ICtype = as.integer(switch(boot.lag.method, ## "fixed" = 0, "AIC" = 1, "BIC" = 2, "AICc" = 3)), ## bpvals = double(nrow(stats)), chosen_lags = chosen.lags, PACKAGE = "uroot") ## stats[,2] <- tmp$bpvals ## chosen.lags <- tmp$chosen_lags ## } else { ## if (grepl("windows", .Platform$OS.type)) { ## stop("GPU parallelization could not be tested on a Windows system,\n", ## "consider using the function ", sQuote("hegy.boot.pval")) ## } else # unix ## stop("CUDA capable GPU was not available when installing the package on this system,\n", ## "consider using the function ", sQuote("hegy.boot.pval")) ## } stop("'pvalue = bootstrap' was only available with CUDA, but\n", "CUDA capablities in package 'uroot' were removed from v. 2.1-0,\n", "consider using the function ", sQuote("hegy.boot.pval")) } else if (pvalue == "raw") { #NOTE documentation deterministic == c(0,0,1) not available #in original tables (use c(1,0,1) instead) stats[1,2] <- uroot.raw.pvalue(stats[1,1], "HEGY", NULL, dfs2, ctd, S, "zero") if (isSeven) stats[2,2] <- uroot.raw.pvalue(stats[2,1], "HEGY", NULL, dfs2, ctd, S, "pi") for (i in seq.int(isSevenp2, (S+4)/2-1)) stats[i,2] <- uroot.raw.pvalue(stats[i,1], "HEGY", NULL, dfs2, ctd, S, "pair") } # output res <- list(statistics = stats[,1], pvalues = stats[,2], method = "HEGY test for unit roots", data.name = data.name, fitted.model = fit2, lag.method = lag.method, lag.order = maxlag, strdet = strdet, type.pvalue = pvalue, bootstrap = if (pvalue == "bootstrap") bargs else NULL, boot.chosen.lags = if (pvalue == "bootstrap") chosen.lags else NULL, pvlabels = symnum(stats[,"p-value"], corr = FALSE, na = FALSE, cutpoints = c(0, 0.001, 0.01, 0.05, 0.1, 1), symbols = c("***","**","*","."," "))) class(res) <- "HEGYtest" res }
/scratch/gouwar.j/cran-all/cranData/uroot/R/hegy-test.R
seasonal.dummies <- function(x) { S <- frequency(x) SD <- do.call("rbind", replicate(ceiling(length(x)/S), diag(S), simplify = FALSE)) SD <- ts(SD, frequency = S, start = c(start(x)[1], 1)) # ignore warning about 'start' or 'end' "value not changed" SD <- suppressWarnings(window(SD, start = start(x), end = end(x))) colnames(SD) <- paste("SD", seq_len(S), sep = "") SD } seasonal.cycles <- function(x) { n <- length(x) S <- frequency(x) tmp <- matrix(seq_len(n), nrow = floor(0.5 * S - 1), ncol = n, byrow = TRUE) seqsm1 <- seq_len(nrow(tmp)) tmp <- (2 * seqsm1 * pi / S) * tmp SD <- rbind(cos(tmp), sin(tmp)) SD <- t(SD[c(rbind(seqsm1, seqsm1 + nrow(tmp))),]) if ((S %% 2) == 0) SD <- cbind(SD, rep(c(-1, 1), len = n)) SD <- ts(SD, frequency = S, start = c(start(x)[1], 1)) colnames(SD) <- paste("SD", seq_len(ncol(SD)), sep = "") SD }
/scratch/gouwar.j/cran-all/cranData/uroot/R/seasonal-dummies-cycles.R
uroot.raw.pvalue <- function(x, type = c("CH", "HEGY"), v, n, ctd, S, Ftpi) { type <- match.arg(type) switch(type, "CH" = { if (v > 12) stop("tabulated values are not available for ", sQuote("v"), " = ", v, " degrees of freedom") pval <- approx(c(0, .CH.orig.cv[v,], Inf), c(1, 0.20, 0.10, 0.075, 0.05, 0.025, 0.01, 0), x)$y return(pval) }, "HEGY" = { if (S == 4) { tab <- .HEGY.orig.cv[ctd,,,Ftpi] nsizes <- c(48, 100, 136, 200) } else if (S == 12) { tab <- .BM.orig.cv[ctd,,,Ftpi] nsizes <- c(240, 480, 10000) } else { return(NA) warning("tabulated values are available only for quarterly and monthly series. ") } #option rule=2 chooses the values tabulated for n=48 and n=200 if "n" is beyond these limits cvals <- rep(NA, 4) for (i in seq_along(cvals)) cvals[i] <- approx(nsizes, c(tab[,i]), n, rule = 2)$y if (Ftpi == "pair") { pval <- approx(c(10000, cvals, 0), c(0, 0.01, 0.025, 0.05, 0.1, 1), x)$y } else pval <- approx(c(-10000, cvals, 3), c(0, 0.01, 0.025, 0.05, 0.1, 1), x)$y return(pval) } ) # end switch }
/scratch/gouwar.j/cran-all/cranData/uroot/R/tables-critical-values.R
'band_mean' <- function(obj) { res <- band_stat(obj)$mean names(res) <- bandname(obj) res } 'band_min' <- function(obj) { res <- band_stat(obj)$min names(res) <- bandname(obj) res } 'band_max' <- function(obj) { res <- band_stat(obj)$max names(res) <- bandname(obj) res } 'band_sum' <- function(obj) { res <- band_stat(obj)$sum names(res) <- bandname(obj) res } 'band_sd' <- function(obj) { res <- band_stat(obj)$sd names(res) <- bandname(obj) res } 'band_n' <- function(obj) { res <- band_stat(obj)$n names(res) <- bandname(obj) res } 'band_nNA' <- function(obj) { res <- band_stat(obj)$nNA names(res) <- bandname(obj) res } 'band_quantile' <- function(obj,...) { res <- apply(ursa_value(obj),2,simplify=FALSE,function(x) quantile(na.omit(x),...)) res <- do.call(rbind,res) rownames(res) <- names(obj) res }
/scratch/gouwar.j/cran-all/cranData/ursa/R/Ops.band_group.R
'band_stat' <- function(x,grid=FALSE,raw=FALSE) { if (!is.ursa(x)) return(NULL) # inMemory <- !is.null(dim(x$value)) if ((!.in.memory(x))||(grid)) return(ursa_info(x)) n <- x$dim[2] # length(x$name) if (.is.con(x$con)) { ind <- x$con$posZ if (anyNA(ind)) ind <- seq(n) else n <- length(ind) } else ind <- seq(n) id <- sprintf(paste0("[%0",nchar(as.character(n)),"d]"),ind) myname <- names(x) if ((length(na.omit(myname))!=n)) myname <- rep("____",n) # n <- dim(x$value)[2] if (n==0) { result <- data.frame(name=character(0),mean=rep(NA,0),sd=rep(NA,0) ,sum=rep(NA,0),min=rep(NA,0),max=rep(NA,0) ,n=rep(NA,0),nNA=rep(NA,0),stringsAsFactors=FALSE) return(result) } else { id0 <- if (length(id)==length(unique(id))) id else make.unique(id,sep=".") result <- data.frame(name=myname,mean=NA,sd=NA,sum=NA ,min=NA,max=NA,n=NA,nNA=NA,row.names=id0 ,stringsAsFactors=FALSE) } if ((TRUE)&&(!sum(nchar(myname)))) { # result <- subset(result,select=-c(name)) # result <- result[,-c("name")] ## -- 20211209 result$name <- rep("____",n) ## ++ 20211209 } for (i in seq(along=myname)) { # str(x$value[,i]) if (raw) tmp <- as.numeric(x$value[,i]) else tmp <- as.numeric(.extract(x)$value[,i]) tmpNA <- length(tmp[is.na(tmp)]) tmp <- tmp[!is.na(tmp)] if (length(tmp)) { result[i,"sum"] <- sum(tmp) result[i,"mean"] <- mean(tmp) result[i,"sd"] <- sd(tmp) result[i,"min"] <- min(tmp) result[i,"max"] <- max(tmp) } result[i,"n"] <- length(tmp) result[i,"nNA"] <- tmpNA rm(tmp) } sparse <- attr(x$value,"sparse") if (is.null(sparse)) ni <- 0L else if (all(sparse<0)) ni <- length(sparse) else if (all(sparse>0)) ni <- with(x$grid,columns*rows)-length(sparse) else ni <- 0L result[,"nNA"] <- result[,"nNA"]+ni result }
/scratch/gouwar.j/cran-all/cranData/ursa/R/Ops.band_stat.R
'focal_min' <- function(x,size=3,cover=1e-6,fillNA=FALSE,saveMargin=TRUE ,verbose=0L) { focal_extrem(x=x,kind="min",size=size,cover=cover,fillNA=fillNA ,saveMargin=saveMargin,verbose=verbose) } 'focal_max' <- function(x,size=3,cover=1e-6,fillNA=FALSE,saveMargin=TRUE ,verbose=0L) { focal_extrem(x=x,kind="max",size=size,cover=cover,fillNA=fillNA ,saveMargin=saveMargin,verbose=verbose) } 'focal_extrem' <- function(x,kind=c("min","max"),size=3,cover=1e-6 ,fillNA=FALSE,saveMargin=TRUE,verbose=0L) { kind <- match.arg(kind) fun <- 'focalExtrem' # as.character(match.call()[1]) if (!is.ursa(x)) return(NULL) sparse <- attr(x$value,"sparse") if ((!is.null(sparse))&&(any(na.omit(sparse)!=0))) stop("TODO: expand compression") if (!is.na(x$con$posZ[1])) nb <- length(x$con$posZ) else nb <- x$dim[2] if (!is.na(x$con$posR[1])) nr <- length(x$con$posR) else nr <- x$grid$rows if (!is.na(x$con$posC[1])) nc <- length(x$con$posC) else nc <- x$grid$columns dimy <- c(nc,nr,nb) dim(x$value) <- dimy x$value <- as.numeric(x$value) if (verbose>2) .elapsedTime(paste0("start:nodata:",fun)) nodata <- x$con$nodata if (is.na(nodata)) nodata <- max(x$value,na.rm=TRUE)+1 x$value[is.na(x$value)] <- nodata if (verbose>2) .elapsedTime(paste0("finish:nodata:",fun)) if (verbose>1) print(summary(x$value)) if (verbose) .elapsedTime(paste0("start:",fun)) x$value <- .Cursa(C_focalExtrem,x=x$value ,kind=switch(kind,min=-1L,max=1L) ,nodata=as.numeric(nodata) ,dim=as.integer(dimy) ,size=as.integer(size) ,cover=as.numeric(cover) ,fillNA=as.integer(fillNA) ,saveMargin=as.integer(saveMargin) ,verbose=as.integer(verbose) ,res=numeric(prod(dimy)),NAOK=FALSE)$res # str(x$value,digits=7) # x$value <- x$value$res if (verbose) .elapsedTime(paste0("finish:",fun)) if (verbose>1) print(summary(x$value)) if (verbose>2) .elapsedTime(paste0("start:nodata:",fun)) if (abs(nodata)<1) x$value[abs(x$value-nodata)<1e-27] <- NA else x$value[abs(x$value/nodata-1)<1e-6] <- NA if (verbose>2) .elapsedTime(paste0("finish:nodata:",fun)) dim(x$value) <- c(dimy[1]*dimy[2],dimy[3])#with(x$grid,c(columns*rows,nb)) class(x$value) <- "ursaNumeric" x }
/scratch/gouwar.j/cran-all/cranData/ursa/R/Ops.focal_extrem.R
'focal_mean' <- function(x,size=3.0,cover=1e-6,fillNA=FALSE,saveMargin=TRUE ,noNA=TRUE,verbose=0L) { fun <- "focalMean" # as.character(match.call())[1] if (!is.ursa(x)) return(NULL) # x$data <- aperm(x$data,c(2,1,3)) sparse <- attr(x$value,"sparse") if ((!is.null(sparse))&&(any(na.omit(sparse)!=0))) stop("TODO: expand compression") if (!is.na(x$con$posZ[1])) nb <- length(x$con$posZ) else nb <- x$dim[2] if (!is.na(x$con$posR[1])) nr <- length(x$con$posR) else nr <- x$grid$rows dimy <- c(x$grid$columns,nr,nb) # dim(x$value) <- dimy x$value <- as.numeric(x$value) if (noNA) { if (verbose>2) .elapsedTime(paste0("start:nodata:",fun)) nodata <- x$con$nodata if (is.na(nodata)) nodata <- max(x$value,na.rm=TRUE)+1 x$value[is.na(x$value)] <- nodata if (verbose>2) .elapsedTime(paste0("finish:nodata:",fun)) } if (verbose>1) print(summary(x$value)) if (verbose) .elapsedTime(paste0("start:",fun)) if (noNA) {# C-code is more quick x$value <- .Cursa(C_focalMean,x=x$value,nodata=as.numeric(nodata) ,dim=as.integer(dimy),size=as.numeric(size) ,cover=as.numeric(cover),fillNA=as.integer(fillNA) ,saveMargin=as.integer(saveMargin) ,verbose=as.integer(verbose) ,res=numeric(prod(dimy)),NAOK=FALSE)$res } else { x$value <- .Cursa(C_focalMeanWithNA,x=x$value ,dim=as.integer(dimy),size=as.numeric(size) ,cover=as.numeric(cover),fillNA=as.integer(fillNA) ,verbose=as.integer(verbose) ,res=numeric(prod(dimy)),NAOK=TRUE)$res } if (verbose) .elapsedTime(paste0("finish:",fun)) if (verbose>1) print(summary(x$value)) if (noNA) { if (verbose>2) .elapsedTime(paste0("start:nodata:",fun)) if (abs(nodata)<1) x$value[abs(x$value-nodata)<1e-27] <- NA else x$value[abs(x$value/nodata-1)<1e-6] <- NA if (verbose>2) .elapsedTime(paste0("finish:nodata:",fun)) } dim(x$value) <- c(dimy[1]*dimy[2],dimy[3])#with(x$grid,c(columns*rows,nb)) class(x$value) <- "ursaNumeric" x } '.focal_mean.big' <- function(x,fname,memory=100,verbose=FALSE,...) { fun <- "focal_mean.big" if (!is.ursa(x)) return(NULL) nr <- x$grid$rows res <- if (missing(fname)) create_envi(x,...) else create_envi(x,fname,...) rel <- as.list(match.call())[-1] ## try mget(names(match.call())[-1]) rel$fname <- NULL size <- rel[[.grep("size",names(rel))]] s1 <- ceiling(size) if (!(s1%%2)) s1 <- s1+1 s2 <- as.integer(floor(s1/2)) chunk <- chunk_line(x,memory) isPb <- verbose & length(chunk)>1 if (isPb) pb <- ursaProgressBar(min=0,max=length(chunk),tail=TRUE) for (i in seq_along(chunk)) { # if (verbose) print(range(i)) r1 <- chunk[[i]] r2 <- c(min(r1)-rev(seq(s2)),r1,max(r1)+seq(s2)) r2 <- r2[r2>=1 & r2<=nr] r3 <- na.omit(match(r1,r2)) rel[["x"]] <- quote(x[,r2]) res[,r1] <- do.call("focal_mean",rel)[,r3] if (isPb) setUrsaProgressBar(pb,i) } if (isPb) close(pb) res }
/scratch/gouwar.j/cran-all/cranData/ursa/R/Ops.focal_mean.R
'focal_median' <- function(x,size=3,cover=1e-6,fillNA=FALSE,saveMargin=TRUE ,verbose=0L) { fun <- 'focalMedian' # as.character(match.call()[1]) # print(fun) if (!is.ursa(x)) return(NULL) sparse <- attr(x$value,"sparse") if ((!is.null(sparse))&&(any(na.omit(sparse)!=0))) stop("TODO: expand compression") if (!is.na(x$con$posZ[1])) nb <- length(x$con$posZ) else nb <- x$dim[2] dimy <- with(x$grid,c(columns,rows,nb)) dim(x$value) <- dimy x$value <- as.numeric(x$value) if (verbose>2) .elapsedTime(paste0("start:nodata:",fun)) nodata <- x$con$nodata if (is.na(nodata)) nodata <- max(x$value,na.rm=TRUE)+1 x$value[is.na(x$value)] <- nodata if (verbose>2) .elapsedTime(paste0("finish:nodata:",fun)) if (verbose>1) print(summary(x$value)) if (verbose) .elapsedTime(paste0("start:",fun)) x$value <- .Cursa(C_focalMedian,x=x$value,nodata=as.numeric(nodata) ,dim=as.integer(dimy),size=as.integer(size) ,fillNA=as.integer(fillNA),saveMargin=as.integer(saveMargin) ,cover=as.numeric(cover),verbose=as.integer(verbose) ,res=numeric(prod(dimy)),NAOK=FALSE)$res if (verbose) .elapsedTime(paste0("finish:",fun)) if (verbose>1) print(summary(x$value)) if (verbose>2) .elapsedTime(paste0("start:nodata:",fun)) if (abs(nodata)<1) x$value[abs(x$value-nodata)<1e-27] <- NA else x$value[abs(x$value/nodata-1)<1e-6] <- NA if (verbose>2) .elapsedTime(paste0("finish:nodata:",fun)) dim(x$value) <- with(x$grid,c(columns*rows,nb)) class(x$value) <- "ursaNumeric" x }
/scratch/gouwar.j/cran-all/cranData/ursa/R/Ops.focal_median.R
'focal_special' <- function(x,type=c("custom","gaussian","laplacian","osisaf" ,"hires","correl","LoG","sobel","sobelG") ,fmask=NULL,size=3,alpha=0.5,sigma=(size-1)/4,cover=1-1e-6 ,fillNA=FALSE,saveMargin=FALSE,verbose=0L) { type <- match.arg(type) if (!is.ursa(x)) return(NULL) sparse <- attr(x$value,"sparse") if ((!is.null(sparse))&&(any(na.omit(sparse)!=0))) stop("TODO: expand compression") if (!any(!is.na(x$value))) return(x) if (!is.na(x$con$posZ[1])) nb <- length(x$con$posZ) else nb <- x$dim[2] if (!is.na(x$con$posR[1])) nr <- length(x$con$posR) else nr <- x$grid$rows if (!is.na(x$con$posC[1])) nc <- length(x$con$posC) else nc <- x$grid$columns dimy <- c(nc,nr,nb) dim(x$value) <- dimy x$value <- as.numeric(x$value) nodata <- x$con$nodata if (is.na(nodata)) nodata <- max(x$value,na.rm=TRUE)+1 x$value[is.na(x$value)] <- nodata if (type!="custom") fmask <- NULL if (!is.null(fmask)) { size <- unique(dim(fmask)) if (length(size)!=1) stop("Only squared filter mask is allowed") } if (type %in% c("custom")) { if (is.null(fmask)) { fmask=1 size=1L } x$value <- .Cursa(C_focalCommon ,x=as.numeric(x$value) ,dim=as.integer(dimy) ,nodata=as.numeric(nodata) ,H=as.numeric(fmask) ,size=as.integer(size) ,cover=as.numeric(cover) ,fillNA=as.integer(fillNA) ,saveMargin=as.integer(saveMargin) ,verbose=as.integer(verbose) ,res=numeric(prod(dimy)),NAOK=FALSE)$res } else { # fun <- gsub("^(\\w)(\\w+)","focal\\U\\1\\E\\2",type,perl=TRUE) #paste0(type,"4") fun <- switch(type,gaussian=C_focalGaussian ,laplacian=C_focalLaplacian ,osisaf=C_focalOsisaf ,hires=C_focalHires ,correl=C_focalCorrel ,LoG=C_focalLoG ,sobel=C_focalSobel ,sobelG=C_focalSobelG ) x$value <- .Cursa(fun ,x=as.numeric(x$value) ,dim=as.integer(dimy) ,nodata=as.numeric(nodata) ,size=as.numeric(size) ,sigma=as.numeric(sigma) ,alpha=as.numeric(alpha) ,cover=as.numeric(cover) ,fillNA=as.integer(fillNA) ,saveMargin=as.integer(saveMargin) ,verbose=as.integer(verbose) ,res=numeric(prod(dimy)),NAOK=FALSE)$res } if (abs(nodata)<1) x$value[abs(x$value-nodata)<1e-27] <- NA else x$value[abs(x$value/nodata-1)<1e-6] <- NA dim(x$value) <- c(dimy[1]*dimy[2],dimy[3])#with(x$grid,c(columns*rows,nb)) class(x$value) <- "ursaNumeric" .gc() x }
/scratch/gouwar.j/cran-all/cranData/ursa/R/Ops.focal_special.R
'global_mean' <- function(x,ursa=FALSE,...) { arglist <- list(...) if (!.lgrep("na\\.rm",names(arglist))) arglist$na.rm <- TRUE res <- try(do.call("mean",c(list(c(x$value)),arglist))) if (inherits(res,"try-error")) res <- NA if (ursa) return(ursa_new(res,bandname="mean")) res } 'global_min' <- function(x,ursa=FALSE,...) { arglist <- list(...) if (!.lgrep("na\\.rm",names(arglist))) arglist$na.rm <- TRUE res <- try(do.call("min",c(list(c(x$value)),arglist))) if (inherits(res,"try-error")) res <- NA if (ursa) return(ursa_new(res,bandname="min")) res } 'global_max' <- function(x,ursa=FALSE,...) { arglist <- list(...) if (!.lgrep("na\\.rm",names(arglist))) arglist$na.rm <- TRUE res <- try(do.call("max",c(list(c(x$value)),arglist))) if (inherits(res,"try-error")) res <- NA if (ursa) return(ursa_new(res,bandname="max")) res } 'global_sd' <- function(x,ursa=FALSE,...) { arglist <- list(...) if (!.lgrep("na\\.rm",names(arglist))) arglist$na.rm <- TRUE res <- try(do.call("sd",c(list(c(x$value)),arglist))) if (inherits(res,"try-error")) res <- NA if (ursa) return(ursa_new(res,bandname="sd")) res } 'global_sum' <- function(x,ursa=FALSE,...) { arglist <- list(...) if (!.lgrep("na\\.rm",names(arglist))) arglist$na.rm <- TRUE res <- try(do.call("sum",c(list(c(x$value)),arglist))) if (inherits(res,"try-error")) res <- NA if (ursa) return(ursa_new(res,bandname="sum")) res } 'global_median' <- function(x,ursa=FALSE,...) { arglist <- list(...) if (!.lgrep("na\\.rm",names(arglist))) arglist$na.rm <- TRUE res <- try(do.call("median",c(list(c(x$value)),arglist))) if (inherits(res,"try-error")) res <- NA if (ursa) return(ursa_new(res,bandname="median")) res } 'global_n' <- function(x,ursa=FALSE,...) { arglist <- list(...) res <- length(na.omit(c(x$value))) if (ursa) return(ursa_new(res,bandname="n")) res } 'global_nNA' <- function(x,ursa=FALSE,...) { arglist <- list(...) res <- length(which(is.na(c(x$value)))) if (ursa) return(ursa_new(res,bandname="n")) res } 'global_quantile' <- function(x,ursa=FALSE,...) { v <- quantile(na.omit(c(ursa_value(x))),...) if (!ursa) return(v) ursa(v,bands=length(v)) } 'global_range' <- function(x,ursa=FALSE,...) c(global_min(x,ursa=ursa,...),global_max(x,ursa=ursa,...)) ## code below is proposal to reduce COPY/PASTE, but doesn't work correctly for 'range' ## try mget(names(match.call())[-1]) instead of as.list(match.call())[-1] '.global_fun1' <- '.global_fun2'<- function(x,ursa=FALSE,...) do.call(".global_common",as.list(match.call())) '.global_common' <- function(...) { rel <- as.list(sys.call())[-1] fun <- .gsub("^global\\.","",as.character(rel[[1]])) rel <- rel[-1] obj <- .getPrm(rel,name="x",class="name",default=NULL) rel <- rel[-1] if (length(rel)) { scalar <- !.getPrm(rel,name="ursa",default=FALSE) if (length(ind <- grep("ursa",names(rel)))) rel <- rel[-ind] if (!.lgrep("na\\.rm",names(rel))) rel$na.rm <- TRUE } else { rel <- list(na.rm=TRUE) scalar <- TRUE } rel <- c(list(ursa_value(eval(obj))),rel) res <- do.call(fun,rel) if (scalar) return(res) ursa_new(res,bandname=fun) }
/scratch/gouwar.j/cran-all/cranData/ursa/R/Ops.global_group.R
'mean.ursaRaster' <- function(x,...) .syn('local_mean',0,x,...) 'median.ursaRaster' <- function(x,...) .syn('local_median',0,x,...) # 'sd.ursaRaster' <- function(x,...) .syn('local_sd',0,x,...) ## (list) object cannot be coerced to type 'double' 'local_mean' <- function(x,cover=0.5-1e-3,weight=NULL,verbose=FALSE,bandname="mean") { a <- .average(x=x,cover=cover,weight=weight,verbose=verbose,sum=FALSE) if (nchar(bandname)) bandname(a) <- bandname a } 'local_sum' <- function(x,cover=0.5-1e-3,weight=NULL,verbose=FALSE,bandname="sum") { a <- .average(x=x,cover=cover,weight=weight,verbose=verbose,sum=TRUE) if (nchar(bandname)) bandname(a) <- bandname a } 'local_median' <- function(x,cover=0.5-1e-3,verbose=FALSE) { res <- .groupSummary(x,generic="median",cover=cover,weight=NULL ,verbose=verbose) res } 'local_min' <- function(x,cover=0.5-1e-3,verbose=FALSE) { res <- .groupSummary(x,generic="min",cover=cover,weight=NULL ,verbose=verbose) res } 'local_max' <- function(x,cover=0.5-1e-3,verbose=FALSE) { res <- .groupSummary(x,generic="max",cover=cover,weight=NULL ,verbose=verbose) res } 'local_sd' <- function(x,cover=0.5-1e-3,verbose=FALSE) { res <- .groupSummary(x,generic="sd",cover=cover,weight=NULL ,verbose=verbose) res } 'local_var' <- function(x,cover=0.5-1e-3,verbose=FALSE) { res <- .groupSummary(x,generic="var",cover=cover,weight=NULL ,verbose=verbose) res } 'local_length' <- function(x,cover=0.5-1e-3,verbose=FALSE) { res <- .groupSummary(x,generic="length",cover=cover,weight=NULL ,verbose=verbose) res } 'local_any' <- function(x,cover=0.5-1e-3,verbose=FALSE) { res <- .groupSummary(x,generic="any",cover=cover,weight=NULL ,verbose=verbose) res } 'local_all' <- function(x,cover=0.5-1e-3,verbose=FALSE) { res <- .groupSummary(x,generic="all",cover=cover,weight=NULL ,verbose=verbose) res } '.average' <- function(x,cover=0.5-1e-3,weight=NULL,sum=FALSE,verbose=FALSE) { fun <- "mapAlgebraLocal" #as.character(match.call())[1] isImage <- is.ursa(x) isArray <- is.array(x) if (cover>1) cover <- cover/length(x) if (cover==0) cover <- 1e-11 if (isImage) { g0 <- session_grid() session_grid(x) if (.is.con(x$con)) nodata <- x$con$nodata else nodata <- NA if (is.na(nodata)) { # nodata <- max(x$value,na.rm=TRUE)+1 nodata <- -1e38 #.optimal.nodata(x$value) ## result and nodata matching } x$value[is.na(x$value)] <- nodata obj <- ursa_new(bandname=fun,nodata=nodata) # print(c(nodata=nodata)) dimx <- dim(x$value) if (is.null(weight)) weight <- rep(1,dimx[2]) if (!sum) weight <- weight/sum(weight) if (verbose) .elapsedTime(paste(fun,"start",sep=":")) a <- .Cursa(C_makemap4 ,x=as.numeric(x$value),bg=as.numeric(nodata) ,dim=as.integer(dimx),cover=as.numeric(cover) ,weight=weight,sum=as.integer(sum) ,res=numeric(dimx[1]*1L),NAOK=FALSE) if (verbose) .elapsedTime(paste(fun,"stop",sep=":")) if (is.na(x$con$posR[1])) { obj$value[] <- a$res class(obj$value) <- "ursaNumeric" } else { obj$con$posR <- x$con$posR obj$value <- a$res dim(obj$value) <- c(dimx[1],1) } if (abs(nodata)<1) obj$value[abs(obj$value-nodata)<1e-27] <- NA else obj$value[abs(obj$value/nodata-1)<1e-6] <- NA session_grid(g0) return(obj) } if (isArray) { dimx <- dim0 <- dim(x) # if (length(dimx)==2) # return(x) if (length(dimx)==3) dimx <- c(dimx[1]*dimx[2],dimx[3]) if (length(dimx)!=2) return(x) if (is.null(weight)) weight <- rep(1,dimx[2]) weight <- weight/sum(weight) a <- .Cursa(C_makemap4 ,x=as.numeric(x),bg=-1e34 ,dim=as.integer(dimx),cover=as.numeric(cover) ,weight=weight,sum=as.integer(sum) ,res=numeric(dimx[1]*1L),NAOK=TRUE)$res # dim(a) <- dim(x)[1:2] dim(a) <- head(dim0,-1) return(a) } stop(paste0(fun,": Non-supported class of data")) } 'quantile.ursaRaster' <- function(x,...) .syn('local_quantile',0,x,...) 'local_quantile' <- function(x,probs=seq(0,1,0.25),type=7,cover=0.5-1e-3,verbose=FALSE) { if (!is.ursa(x)) return(NULL) g0 <- session_grid() nx <- length(x) skip <- rep(NA,length(probs)) if (cover>1) cover <- cover/length(x) if (cover==0) cover <- 1e-11 session_grid(x) # res <- ursa(bandname=as.character(probs)) qv <- apply(ursa_value(x),1,function(v) { if (length(na.omit(v))/nx<cover) return(skip) quantile(v,probs=probs,type=type,name=FALSE,na.rm=TRUE) }) res <- as.ursa(t(qv)) # ursa_value(res) <- t(qv) # display(res) session_grid(g0) res }
/scratch/gouwar.j/cran-all/cranData/ursa/R/Ops.local_group.R
'local_stat' <- function(obj,time=NULL,cover=1e-6,smooth=FALSE,verbose=FALSE) { fun <- 'local_stat' # as.character(match.call())[1] if (!is.ursa(obj)) return(NULL) if (.is.con(obj$con)) nodata <- obj$con$nodata else nodata <- NA res <- ursa_new(bandname=c("mean","sd","sum","min","max","n" ,"slope","slopeS","RSS","ESS") ,nodata=-9999) ## nodata=nodata myname <- bandname(obj) dimy <- dim(obj$value) np <- dimy[1] if (is.null(time)) time <- seq(myname) if (cover>1) cover <- cover/length(myname)-1e-11 if (verbose) .elapsedTime(paste(fun,"start",sep=":")) ret <- .Cursa(C_variability4 ,y=as.numeric(obj$value),x=as.numeric(time),dim=as.integer(dimy) ,cover=as.numeric(cover) ,res=numeric(np*10L),NAOK=TRUE)$res if (verbose) .elapsedTime(paste(fun,"stop",sep=":")) dim(ret) <- c(np,10) if (is.na(obj$con$lines)) obj$con$lines <- obj$grid$rows if (is.na(obj$con$samples)) obj$con$samples <- obj$grid$columns if (FALSE) ## 20180220 -- r <- if (is.na(obj$con$posR[1])) seq(obj$con$lines) else obj$con$posR else { r <- if (is.na(obj$con$indexR[1])) seq(obj$con$lines) else seq_along(obj$con$indexR) if (!is.na(obj$con$posR[1])) r <- obj$con$posR } if ((is.na(obj$con$posR[1]))&&(length(r)!=res$grid$rows)) { if (verbose) message(paste(fun,"warning *** probably incorrect resampling",sep=":")) r <- seq(res$grid$rows) } ##~ # print(str(ret)) b <- 7L for (i in seq(b)) res[i,r] <- ret[,i,drop=FALSE] ##a$ret[(i-1)*np+1:np] res[b+2,r] <- ret[,b+2,drop=FALSE] ## SSR (introduced 20150123) res[b+3,r] <- ret[,b+3,drop=FALSE] ## SSE (introduced 20150123) if (smooth) res["slope"] <- focal_median(res["slope"],verbose=verbose) F <- ret[,b+1] N <- ret[,b-1] ind <- which(!is.na(F) & !is.na(N) & N>2) F[ind] <- pf(abs(F[ind]),1,N[ind]-2)*sign(F[ind]) F[-ind] <- NA r2 <- (c(min(r)-1,max(r)))*obj$con$samples r2[1] <- r2[1]+1 # res$value[r2[1]:r2[2],6] <- F res[b+1,r] <- F res[,r] }
/scratch/gouwar.j/cran-all/cranData/ursa/R/Ops.local_stat.R
# 'choropleth' <- function(...) .syn('zonal_stat',1,...) ## GISTools::choropleth() 'zonal_stat' <- function(x,by,FUN,table=FALSE) { aggregate(x=x,by=by,FUN=FUN,table=table)#,na.rm=TRUE) } 'aggregate.ursaRaster' <- function(x,by,FUN,table=FALSE,...) { if (isList <- .is.ursa_stack(by)) { clname <- sapply(by,function(x) names(ursa(x,"colortable"))) by <- ursa_brick(by) src <- by n <- length(src) bn <- names(src) if (length(bn)!=n) bn <- sapply(by,bandname) by <- ursa_new(bandname=bn) for (i in seq(nband(by))) by[i] <- src[i] rm(src) isCategory <- length(clname) } else { isCategory <- .is.category(by) if (isCategory) clname <- names(ursa(by,"colortable")) n <- nband(by) bn <- bandname(by) } by0 <- vector("list",n) names(by0) <- bn for (i in seq_along(by0)) by0[[i]] <- by[i]$value[,1] x0 <- unclass(x$value) z <- aggregate(x=x0,by=by0,FUN,...,simplify=TRUE) indZ <- grep("V\\d+",colnames(z)) colnames(z)[indZ] <- bandname(x) if ((isList)&&(isCategory)) { for (i in seq_along(clname)) z[,i] <- rep(clname[[i]],length=nrow(z)) } # a <- na.omit(names(ursa_colortable(by))) if (table) { ## 'table' is agrument, is not a function if (!nrow(z)) return(z) nameBy <- names(ursa_colortable(by)) if ((isCategory)&&(!is.null(nameBy))&&(length(na.omit(nameBy)))) { ind <- z[,1]+1 ind2 <- which(is.na(match(seq_along(nameBy),ind))) indc <- 2:ncol(z) z[ind,indc] <- z[seq(nrow(z)),indc] z[ind2,indc] <- rep(NA,length(indc)) z[,1] <- nameBy } return(z) } res <- ursa_new(bandname=bandname(x),ignorevalue=ignorevalue(x)) if (n==1) { ind <- match(by0[[1]],z[,1]) i1 <- which(!is.na(ind)) i2 <- c(na.omit(ind)) for (i in seq_along(indZ)) res$value[i1,i] <- z[i2,indZ[i]] return(res) } else { for (i in seq(nrow(z))) { ind <- rep(0,length(by0[[1]])) for (j in seq_along(by0)) ind <- ind+as.integer(by0[[j]]==z[i,j]) ind <- which(ind==n) for (j in seq(nband(res))) res$value[ind,j] <- z[i,indZ[j]] } return(res) } NULL }
/scratch/gouwar.j/cran-all/cranData/ursa/R/Ops.zonal_stat.R
# for interpoaltion: packages 'interp', 'MBA'. 'akima' is under ACM license # D:\ongoing\CloudMailRu\pdf\R\akima_ACM--alternatives_GPL.pdf 'allocate' <- function(vec,coords=c("x","y"),nodata=NA,attr=".+",fun=c("mean","sum","n") ,cellsize=NA,resetGrid=FALSE,verbose=FALSE) { class(vec) ## initizize evaluation 'vec' before # vec <- list(x=vec$x,y=vec$y,conc=vec$conc,speed=vec$speed) fun <- match.arg(fun) kind <- switch(fun,mean=1L,sum=2L,n=4L,0L) onlyGrid <- FALSE if (resetGrid) session_grid(NULL) if (is.character(vec)) { # vec <- .shp.read(vec) vec <- spatialize(vec,engine="sp") } if (inherits(vec,c("SpatialPointsDataFrame","SpatialPixelsDataFrame"))) { requireNamespace("sp",quietly=.isPackageInUse()) z <- methods::slot(vec,"data") lname <- colnames(z) opW <- options(warn=ifelse(.isPackageInUse(),-1,1)) proj4 <- sp::proj4string(vec) options(opW) vec <- as.data.frame(sp::coordinates(vec),stringsAsFactors=FALSE) colnames(vec) <- c("x","y") } else if ((inherits(vec,c("sf")))&& (.grep("^sfc_.+$",class(vec[[attr(vec,"sf_column")]]),value=TRUE))=="sfc_POINT") { proj4 <- sf::st_crs(vec)$proj4string z <- vec sf::st_geometry(z) <- NULL lname <- colnames(z) vec <- as.data.frame(sf::st_coordinates(vec)) colnames(vec) <- c("x","y") } else if ((inherits(vec,c("sfc")))&&(inherits(vec,"sfc_POINT"))) { spatial_data(vec) <- data.frame(value=1L) z <- spatial_data(vec) proj4 <- spatial_crs(vec) lname <- spatial_colnames(vec) vec <- data.frame(spatial_coordinates(vec)) colnames(vec) <- c("x","y") } else { proj4 <- attr(vec,"proj") if ((!is.data.frame(vec))&&(is.list(vec))) vec <- as.data.frame(do.call("cbind",lapply(vec,I))) if (!is.data.frame(vec)) return(NULL) mname <- colnames(vec) indX <- .grep("^coords.x1$",mname) if (!length(indX)) indX <- .grep("^x$",mname) if (!length(indX)) indX <- .grep("^x1$",mname) if (!length(indX)) indX <- .grep("^lon",mname) if (!length(indX)) indX <- .grep("^east",mname) indY <- .grep("^coords.x2$",mname) if (!length(indY)) indY <- .grep("^y$",mname) if (!length(indY)) indY <- .grep("^x2$",mname) if (!length(indY)) indY <- .grep("^lat",mname) if (!length(indY)) indY <- .grep("^north",mname) if ((!length(indX))&&(!length(indY))) { indX <- .grep("^000x1$",mname) indY <- .grep("^000x2$",mname) } if ((!length(indX))&&(!length(indY))) { indX <- .grep(paste0("^",coords[1],"$"),mname) indY <- .grep(paste0("^",coords[2],"$"),mname) } ind <- c(indX[1],indY[1]) if ((any(is.na(ind)))||(length(ind)!=2)) stop("unable to detect 'x' and 'y' coordinates") lname <- .grep(attr,mname[-ind],value=TRUE) if (!length(lname)) { # lname <- "<location>" # z <- data.frame(z=rep(1,nrow(vec))) z <- data.frame(z=numeric()) onlyGrid <- TRUE } else { # z <- vec[,-ind,drop=FALSE] ## remove 20160505 # z <- subset(vec,select=lname) ## add 20150505 if (inherits(vec,"data.table")) z <- vec[,lname,with=FALSE] else { z <- vec[,lname,drop=FALSE] ## modified 20170128 if (inherits(z,"data.frame")) z <- as.data.frame(lapply(z,c)) } } if (inherits(vec,"data.table")) vec <- vec[,ind,with=FALSE] else vec <- vec[,ind,drop=FALSE] colnames(vec) <- c("x","y") ind <- .grep("^(lon|lat)",mname) if ((length(ind)==2)&&(is.null(proj4))) proj4 <- paste("+proj=longlat +datum=WGS84 +no_defs") } if (is.null(proj4)) proj4 <- "" ind <- which(unname(sapply(z,function(x) any(!(class(x) %in% c("integer","numeric","logical")))))) # ind <- which(sapply(z,class) %in% c("factor","character","POSIXt")) isCategory <- length(ind)>0 isStack <- isCategory & ncol(z)>1 vname <- vector("list",ncol(z)) a <- lapply(z,levels) names(vname) <- colnames(z) if (isCategory) { for (i in ind) { val <- factor(z[,i]) vname[[i]] <- levels(val) z[,i] <- as.numeric(val)-1 } } if (is.na(nodata)) nodata <- .optimal.nodata(z) if (!.is.grid((getOption("ursaSessionGrid")))) { x <- sort(unique(vec$x)) y <- sort(unique(vec$y)) minx <- min(x) maxx <- max(x) miny <- min(y) maxy <- max(y) difx <- diff(x) dify <- diff(y) resx <- unique(difx) resy <- unique(dify) if ((length(resx)!=1)||(length(resy)!=1)) { # print(resx,digits=16) # print(resy,digits=16) if (!is.na(cellsize)) resx <- resy <- cellsize else { # if (sd(diff(x))/mean(difx)<1) mx <- mean(resx) my <- mean(resy) if (FALSE) NULL if ((any(abs(resx-mx)<1e-11))&&(any(abs(resy-my)<1e-11))) { resx <- mx resy <- my } else if ((sd(difx)/mean(difx)<0.01)&&(sd(dify)/mean(dify)<0.01)) { resx <- max(resx) # min(resx) mx resy <- max(resy) # min(resy) mx } else { isU <- FALSE n <- sqrt(2*nrow(z)) if (FALSE) ## coarse res <- min(c(v1=(maxx-minx)/n,v2=(maxy-miny)/n)) else if (FALSE) ## extra quality res <- median(c(difx,dify)) else { if (inherits(vec,"data.table")) vec <- as.data.frame(vec) d <- .dist2(vec,vec,verbose=FALSE)$dist if (verbose) { print(range(d),digits=16) print(summary(d)) } res <- unique(d) if (!(isU <- length(res)==1L)) { # res <- min(d) res <- median(d) if ((res==mean(d))||(res==min(d))) isU <- TRUE else if (max(res)/min(res)-1<.Machine$double.eps) { isU <- TRUE } } } if (!isU) { p <- pretty(res) res <- p[which.min(abs(res-p))] } resx <- resy <- res if (verbose) print(c(x=resx,y=resy)) } } } minx <- min(x)-resx/2 miny <- min(y)-resy/2 maxx <- max(x)+resx/2 maxy <- max(y)+resy/2 # g0 <- regrid(minx=minx,miny=miny,maxx=maxx,maxy=maxy,resx=resx,resy=resy # ,columns=(maxx-minx)/resx,rows=(maxy-miny)/resy,crs=proj4) g0 <- regrid(minx=minx,miny=miny,maxx=maxx,maxy=maxy,resx=resx,resy=resy ,crs=proj4,verbose=verbose) # g0 <- regrid(setbound=) session_grid(g0) } if (onlyGrid) return(session_grid()) res <- ursa_new(bandname=lname,ignorevalue=nodata) z <- as.matrix(z) z[is.na(z)] <- nodata g1 <- res$grid nb <- length(lname) dimx <- dim(res$value) dimy <- with(res$grid,c(columns,rows,nb)) if (verbose) .elapsedTime(paste0(fun,":start")) res$value <- .Cursa(C_rasterize,dat=numeric(prod(dimy)),dim=as.integer(dimy) ,bbox=as.numeric(with(g1,c(minx,miny,maxx,maxy))) ,x=as.numeric(vec$x),y=as.numeric(vec$y),value=as.numeric(z) ,nodata=as.numeric(nodata) ,len=nrow(vec),kind=kind,NAOK=FALSE)$dat if (abs(nodata)<1) res$value[abs(res$value-nodata)<1e-27] <- NA else res$value[abs(res$value/nodata-1)<1e-6] <- NA dim(res$value) <- dimx class(res$value) <- "ursaNumeric" #ifelse(isCategory,"ursaCategory","ursaNumeric") if (isStack) res <- ursa_stack(res) if (isCategory) { for (i in ind) { ct <- rep(NA,length(vname[[i]])) names(ct) <- vname[[i]] class(ct) <- "ursaColorTable" if (isStack) { res[[i]] <- as.integer(round(res[[i]])) res[[i]]$colortable <- ct } else { res[i] <- as.integer(round(res[i])) res$colortable <- ct } } } if (verbose) .elapsedTime(paste0(fun,":finish")) res }
/scratch/gouwar.j/cran-all/cranData/ursa/R/allocate.R
'.chunk' <- function(nr,size=96,name="") { nl <- ceiling(nr/size) res <- vector("list",nl) i1 <- 1 for (i in 1:nr) { i2 <- i1+size-1 if (i2>nr) i2 <- nr res[[i]] <- i1:i2 i1 <- i2+1 if (i1>nr) break } if (nchar(name)) names(res) <- sprintf(sprintf("%s%%0%dd",name,nchar(length(1:i))),1:i) res } 'chunk_line' <- function(obj,mem=100,mul=1) { if (!is.ursa(obj)) return(NULL) y <- obj$con if (any(is.na(with(y,c(samples,lines,bands))))) { nb <- nband(obj) nc <- obj$grid$columns nr <- obj$grid$rows } else { nb <- y$bands nr <- y$lines nc <- y$samples } a <- as.integer(ceiling(1e6*mem*mul/(8*nc*nb))) return(.chunk(nr,a,"line")) } 'chunk_band' <- function(obj,mem=100,mul=1) { if (!is.ursa(obj)) return(NULL) y <- obj$con if (anyNA(with(y,c(samples,lines,bands)))) { nb <- nband(obj) nc <- obj$grid$columns nr <- obj$grid$rows } else { nb <- if (!is.na(y$posZ[1])) length(y$posZ) else y$bands nr <- y$lines nc <- y$samples } a <- as.integer(ceiling(1e6*mem*mul/(8*nc*nr))) return(.chunk(nb,a,"band")) } 'chunk_expand' <- function(ind,size=3) { nr <- session_grid()$rows s1 <- ceiling(size) if (!(s1%%2)) s1 <- s1+1 s2 <- as.integer(floor(s1/2)) sq <- seq(s2) r2 <- c(min(ind)-rev(sq),ind,max(ind)+sq) src <- r2[r2>=1 & r2<=nr] dst <- na.omit(match(ind,src)) list(src=src,dst=dst) }
/scratch/gouwar.j/cran-all/cranData/ursa/R/chunk.R
'ursa_colortable' <- function(x) { verbose <- !.isPackageInUse() if ((TRUE)&&(inherits(x,"ursaColorTable"))) ## was FALSE 20160127 ct <- x else if (is.character(x)) { valid <- all(sapply(unname(x),function(col) { tryCatch(is.matrix(col2rgb(col)),error=function(e) FALSE) })) if (!valid) return(NULL) class(x) <- "ursaColorTable" return(x) } else if (inherits(x,"ursaLegend")) { if (length(x$name)==length(x$pt.bg)) { if (verbose) print("POINT") ret <- x$pt.bg names(ret) <- x$name class(ret) <- "ursaColorTable" return(ret) } if ((all("transparent" %in% x$fill))&&(length(x$name)==length(unique(x$border)))) { if (verbose) print("LINESTRING") if (is.null(names(x$border))) { names(x$border) <- x$name ret <- x$border } else { ind <- match(x$name,names(x$border)) if (inherits(x$border,"ursaColorTable")) return(x$border[ind]) ret <- x$border[ind] names(ret) <- x$name } class(ret) <- "ursaColorTable" return(ret) } if (length(x$name)==length(x$fill)) { if (verbose) print("POLYGON") ret <- x$fill names(ret) <- x$name class(ret) <- "ursaColorTable" return(ret) } if (verbose) print("unreachable") return(NULL) } else if (any(sapply(x,inherits,"ursaLegend"))) { return(lapply(x,ursa_colortable)) ## RECURSIVE!!! } else if (!is.ursa(x)) { ct <- x$colortable if (!inherits(ct,"ursaColorTable")) { if ((is.list(x))&&("name" %in% names(x))&&("fill" %in% names(x))) { ct <- x$fill names(ct) <- x$name class(ct) <- "ursaColorTable" return(ct) } else return(NULL) } } else ct <- x$colortable if (!length(ct)) return(ct) if (is.null(names(ct))) names(ct) <- as.character(seq(length(ct))-1L) ct } '[.ursaColorTable' <- function(x,i) { cl <- class(x) res <- unclass(x)[i] class(res) <- cl res } 'ursa_colortable<-' <- function(x,value) { if (!is.ursa(x)) return(NULL) ## Implement? 'if (is.ursa(value,"colortable)) {x <- colorize(x,value);return(x)' if (is.null(value)) value <- character(0) myname <- names(x$colortable) if ((length(myname)==length(value))&& (is.null(names(value)))&& (!inherits(value,"ursaColorTable"))) names(value) <- myname class(value) <- "ursaColorTable" x$colortable <- value if ((inherits(x$con$handle,"connection"))&&(is.null(dim(x$value)))) .write.hdr(x,clear=FALSE) x } 'print.ursaColorTable' <- function(x,...) { print(unclass(x)) cn <- names(x) cnd <- .deintervale(cn) # if ((!identical(cn,as.character(cnd)))&&(length(cn))) if (length(cn)!=length(cnd)) print(.deintervale(cn),quote=FALSE) } '.is.colortable' <- function(obj) { if (is.ursa(obj)) obj <- obj$colortable else if (is.list(obj)) { if (!is.null(obj$colortable)) obj <- obj$colortable else if (length(obj)==1) obj <- obj[[1]] } ((length(obj)>0)&&(inherits(obj,"ursaColorTable"))) } '.is.nominal' <- function(obj) { if (!.is.colortable(obj)) return (FALSE) ct <- ursa_colortable(obj) val <- .deintervale(ct) length(val)==length(ct) } '.is.interval' <- function(obj) { if (!.is.colortable(obj)) return (FALSE) ct <- ursa_colortable(obj) val <- .deintervale(ct) length(val)!=length(ct) } '.is.category' <- function(obj) { if (is.ursa(obj)) return(inherits(obj$value,"ursaCategory")) inherits(obj,"ursaCategory") } '.be.category' <- function(obj) { (.is.colortable(obj))&&(!.is.category(obj)) } 'names.ursaColorTable' <- function(x) NextMethod("names",x) 'names<-.ursaColorTable' <- function(x,value) { ##~ print("HERE") ##~ str(x) ##~ str(value) ##~ print(c('is numeric?'=.is.numeric(value))) if (!is.null(value)) { if ((.is.numeric(value))&&(length(x)==length(value)+1)) { n0 <- value if (length(n0)>1) value <- paste0("(",n0[-length(n0)],";",n0[-1],"]") value <- c(paste0("<= ",n0[1]),value,paste0("> ",n0[length(n0)])) } } ##~ str(value) if (!FALSE) return(NextMethod("names<-",x)) cl <- class(x) x <- unclass(x) names(x) <- value class(x) <- cl x } 'ursa_colorindex' <- function(ct) { if ((is.list(ct))&&(!is.null(ct$index))&&(inherits(ct$colortable,"ursaColorTable"))) return(ct$index) NULL } 'ursa_color' <- function(ct,...) { x <- colorize(ct,...) as.character(x$colortable[x$index]) }
/scratch/gouwar.j/cran-all/cranData/ursa/R/classColorTable.R
'.con.skeleton' <- function() { obj <- list(driver=NA_character_ ,samples=NA_integer_,lines=NA_integer_,bands=NA_integer_ ,datatype=NA_integer_,interleave=NA_character_,byteorder=NA_integer_ ,endian=NA_character_,swap=NA_integer_,signed=NA ,offset=NA_integer_,wkt=FALSE,nodata=NA_real_,mode="raw" ,sizeof=NA_integer_,indexC=NA_integer_,indexR=NA_integer_,indexZ=NA_integer_ ,posC=NA_integer_,posR=NA_integer_,posZ=NA_integer_ ,fname=NA_character_,connection=NA_character_ ,compress=0L,seek=NA,handle=NA) class(obj) <- c("ursaConnection") obj } '.is.con' <- function(obj) inherits(obj,"ursaConnection") '.ursa_connection'<- function(x) { if (.is.con(x)) return(x) if (is.ursa(x)) return(x$con) return(NULL) } 'print.ursaConnection' <- function(x,...) str(x,...) 'seek.ursaConnection' <- function(con,where=NA,origin="start",rw="",...) { if ((1)||(con$seek)) return(seek(con$handle,where=round(where),origin=origin,rw=rw,...)) stop("Reopenning is needed here, but it seems that connection doesn't support seek") F <- con$handle if (isOpen(F)) { close(F) con$handle <- with(con,do.call(connection,list(fname,"rb"))) } # print(showConnections(TRUE)) readBin(con$handle,raw(),n=as.integer(where)) where }
/scratch/gouwar.j/cran-all/cranData/ursa/R/classConnection.R
'.grid.skeleton' <- function() { g1 <- list(columns=NA_integer_,rows=NA_integer_,resx=NA_real_,resy=NA_real_ ,minx=NA_real_,maxx=NA_real_,miny=NA_real_,maxy=NA_real_ ,seqx=numeric(0),seqy=numeric(0) ,crs="",retina=NA) # class(g1$crs) <- c("character","ursaProjection") class(g1) <- "ursaGrid" g1 } '.is.grid' <- function(obj) inherits(obj,"ursaGrid") 'print.ursaGrid' <- function(x,...) { class(x) <- paste0(".",class(x)) if (!length(x$seqx)) x$seqx <- NULL if (!length(x$seqy)) x$seqy <- NULL if (is.na(x$retina)) x$retina <- NULL str(x,formatNum=function(x) format(x,scientific=FALSE),...) } 'str.ursaGrid' <- function(object,...) { # args <- list(...) # print(str(args)) # q() class(object) <- paste0(".",class(object)) if (FALSE) { y <- list('colunms rows'=c(object$columns,object$rows) ,'resx resy'=c(object$resx,object$resy) ,'minx miny maxx maxy'=c(object$minx,object$miny,object$maxx,object$maxy) ,'crs'=c(object$crs)) class(y) <- class(object) return(y) } if (!length(object$seqx)) object$seqx <- NULL if (!length(object$seqy)) object$seqy <- NULL if ((!is.null(object$retina))&&(is.na(object$retina))) object$retina <- NULL str(object,...)#,formatNum=function(x) format(x,scientific=FALSE),...) # do.call("str",lx,...)#,formatNum=function(x) format(x,scientific=FALSE),...) } 'dim.ursaGrid' <- function(x) structure(c(x$rows,x$columns),names=c("lines","samples")) '.grid.equal' <- function(g1,g2) { (g1$columns==g2$columns)&& (g1$rows==g2$rows)&& (g1$minx==g2$minx)&& (g1$maxx==g2$maxx)&& (g1$miny==g2$miny)&& (g1$maxy==g2$maxy)&& 1L } 'as.data.frame.ursaGrid' <- function(x,row.names=NULL,optional=FALSE,...) { expand.grid(x=seq(x,"x"),y=seq(x,"y"),KEEP.OUT.ATTRS=FALSE) }
/scratch/gouwar.j/cran-all/cranData/ursa/R/classGrid.R
'[.ursaRaster' <- function(x,i,j,...,drop=FALSE) { verbose <- isTRUE(getOption("ursaDevel")) if (verbose) { cat("----------\n") on.exit(cat("==========\n")) print(match.call()) ##~ a <- as.list(match.call())$i ##~ print(class(a)) ##~ print(is.symbol(a)) ##~ print(is.language(a)) ##~ print(is.call(a)) ##~ q() } dimx <- dim(x$value) clValue <- class(x$value) res <- x missingJ <- missing(j) ## read all lines and (selected) bands missingI <- missing(i) ## read all bands and (selected) lines if ((missingJ)&&(missingI)) { if (length(dimx)==2L) return(x) ## return(x$value) identiical(x$value,as.matrix(x))==TRUE } if (!is.null(dimx)) { if ((!missingI)&&(is.ursa(i))) { # return(res*i) ## removed 20160805 if (nband(i)==1) res$value[which(is.na(i$value)),] <- NA else res$value[which(is.na(i$value))] <- NA return(res) ## added 20160805 } if (missingJ) j <- seq(dimx[1]) if (missingI) i <- seq(dimx[2]) if ((is.numeric(i))&&(any(abs(i)>dimx[2]))) i <- as.character(i) if (is.character(i)) { args <- list(...) regexp <- if ("regexp" %in% names(args)) args[["regexp"]] else FALSE i1 <- .getBand(res,i,regexp=regexp) if (is.null(i1)) { ind <- .grep(i,ursa(res,"category")) if (length(ind) == -10000+1) { return(res[res==ind-1L]) } else { if (length(ind)) { res$value[!(x$value %in% (ind-1L))] <- NA return(res) } else return(res[integer()]) } } else i <- i1 j <- seq(dimx[1]) missingJ <- TRUE missingI <- FALSE } # if (is.con(res$con)) # res$con$indexZ <- res$con$indexZ[i] # print(c(j=range(j),i=i)) # res$name <- make.unique(res$name[i],"_") if (all(i<0)) { if (!is.na(res$con$posZ[1])) i <- seq(res$con$posZ)[i] else i <- seq(res$dim[2])[i] } # res$dim[2] <- length(i) if (!missingJ) { if (verbose) .elapsedTime("expandIndex:start") if (is.na(x$con$indexC)[1]) s <- x$grid$columns else s <- length(x$con$indexC) j2 <- j j <- as.integer(c(t(col(array(NA,dim=c(length(j2),s)))+(j2-1)*s))) if (max(j)>x$dim[1]) { opW <- options(warn=0) warning(paste("Expected",length(j),"bytes, but found",max(j),"bytes")) options(opW) j <- j[j<=x$dim[1]] } if (verbose) .elapsedTime("expandIndex:finish") } if (.is.con(res$con)) { if (!missingJ) { if (is.na(res$con$posR[1])) res$con$posR <- j2 else res$con$posR <- res$con$posR[j2] } if (!missingI) { if (is.na(res$con$posZ[1])) { if (is.logical(i)) res$con$posZ <- which(i) else res$con$posZ <- i } else res$con$posZ <- res$con$posZ[i] } } else res$name <- res$name[i] cl <- class(res$value) sp <- attr(res$value,"sparse") res$value <- res$value[j,i,drop=drop] class(res$value) <- cl attr(res$value,"sparse") <- sp res$dim <- dim(res$value) return(res) } res$con$compress <- 0L grid <- res$grid con <- res$con indF <- length(con$fname) opW <- options(warn=-1) intOverflow <- is.na(with(con,samples*lines*bands*sizeof)) options(opW) if (verbose & intOverflow) { print(c(intOverflow=with(con,as.double(samples)*as.double(lines)* as.double(bands)*as.double(sizeof)))) # intOverflow <- FALSE } intOverflow <- FALSE internalReading <- intOverflow | con$connection %in% c("gzfile") externalReading <- !internalReading if ((1)&&(!missingJ)&&(is.character(j))) stop("TODO: is.character(j)") if ((1)&&(!missingI)&&(is.character(i))) { args <- list(...) regexp <- if ("regexp" %in% names(args)) args[["regexp"]] else FALSE i <- .getBand(res,i,regexp=regexp) if (is.null(i)) { op <- options(warn=1) warning(paste("Speciefied name",paste0("'",i,"'"),"is not in bandname")) options(op) return(NULL) } missingJ <- TRUE missingI <- FALSE } if ((!missingI)&&(is.logical(i))) { i <- which(i) } if ((!missingI)&&(all(i<0))) { if (!is.na(res$con$posZ[1])) i <- seq(res$con$posZ)[i] else i <- seq(res$dim[2])[i] } if ((missingJ)&&(missingI)) ## read full { if (con$driver %in% c("ENVI","EGDAL")) { n <- prod(with(con,samples*lines*bands)) xdim <- with(con,c(lines,samples,bands)) if ((con$seek)&&(con$interleave %in% c("bsq","bil"))&& (externalReading)&&(TRUE)) { seek(con,where=0L,origin="start",rw="r") if (con$interleave=="bsq") { if (con$mode=="integer") { res$value <- with(con,.Cursa(C_readBsqBandInteger ,fname=con$fname[indF],dim=xdim,index=seq(bands),n=bands ,datatype=datatype,swap=swap ,res=integer(bands*samples*lines)))$res } else res$value <- with(con,.Cursa(C_readBsqBandDouble ,fname=con$fname[indF],dim=xdim,index=seq(bands),n=bands ,datatype=datatype,swap=swap ,res=double(bands*samples*lines)))$res } else if (con$interleave=="bil") { if (con$mode=="integer") { res$value <- with(con,.Cursa(C_readBilLineInteger2 ,fname=con$fname[indF],dim=xdim,index=seq(lines),n=lines ,datatype=datatype,swap=swap ,res=integer(bands*samples*lines)))$res } else { res$value <- with(con,.Cursa(C_readBilLineDouble2 ,con$fname[indF],dim=xdim ,lines=seq(lines) ,nline=lines,datatype=datatype,swap=swap ,res=double(with(con,lines*samples*bands))))$res } } dim(res$value) <- with(con,c(samples,lines,bands)) } else { res$value <- with(con,.readline(handle,datatype,n,endian)) if (con$interleave=="bil") ##bil[col,band,row] -> R[col,row,band] { dim(res$value) <- with(con,c(samples,bands,lines)) res$value <- aperm(res$value,c(1,3,2)) ##(3,1,2) } else if (con$interleave=="bip") ##bip[band,col,row] -> R[col,row,band] { dim(res$value) <- with(con,c(bands,samples,lines)) res$value <- aperm(res$value,c(2,3,1)) ##c(3,2,1) } else if (con$interleave=="bsq") ##bsq[col,row,band] -> R[col,row,band] { dim(res$value) <- with(con,c(samples,lines,bands)) # res$value <- aperm(res$value,c(1,2,3)) ##c(2,1,3) } else stop("read ENVI: Error in input header file ",con$interleave ," incorrect interleave type") } } else if (con$driver=="RGDAL") { ## read full res$value <- .rgdal_getRasterData(con$handle) dim(res$value) <- with(con,c(samples,lines,bands)) } else if (con$driver=="GDALRASTER") { ## read full if (con$datatype %in% c(4,5)) res$value <- array(NA_real_,dim=res$dim) else res$value <- array(NA_integer_,dim=res$dim) if (verbose) cat("read") for (b2 in seq_len(con$bands)) { if (verbose) cat(".") res$value[,b2] <- con$handle$read(band=b2 ,xoff=0,yoff=0 ,xsize=con$samples,ysize=con$lines ,out_xsize=con$samples,out_ysize=con$lines ) } if (verbose) cat(" done!\n") dim(res$value) <- with(con,c(samples,lines,bands)) } else if (con$driver=="SF") { ## read full if (con$datatype %in% c(4,5)) { res$value <- attr(sf::gdal_read(con$handle$filename,read_data=TRUE),"data") attr(res$value,"units") <- NULL } else { res$value <- as.integer(attr(sf::gdal_read(con$handle$filename ,read_data=TRUE),"data")) } dim(res$value) <- with(con,c(samples,lines,bands)) } else if (con$driver=="NCDF") { ## read full # stop("NCDF -- read full") nc <- ncdf4::nc_open(con$fname[indF]) varName <- con$handle flip <- attr(varName,"flip") permute <- attr(varName,"permute") indT <- attr(varName,"temporal") indS <- attr(varName,"spatial") indV <- c(indS,indT) indL <- seq_along(con$offset)[-indV] w <- attr(varName,"weight") # level <- attr(varName,"level") attributes(varName) <- NULL # print(data.frame(var=varName,flip=flip,permute=permute,time="???")) nc.start <- rep(1,length(con$offset)) nc.count <- con$offset if (length(w)) { ind <- which(w>0) isW <- all(diff(ind))==1 if (isW) { nc.start[indL] <- ind[1] nc.count[indL] <- length(ind) w <- w[ind] } } else isW <- FALSE res$value <- ncdf4::ncvar_get(nc,varName,start=nc.start,count=nc.count ,collapse_degen=!FALSE) if (length(dim(res$value))==1) return(res$value) dim(res$value) <- nc.count if (length(indL)==1) { if (nc.count[indL]>1) { #(con$offset[indL]>1) if (FALSE) res$value <- apply(res$value,indV,function(x) sum(x*w)) else { val <- aperm(res$value,c(indV,indL)) dima <- dim(val) dim(val) <- c(prod(dima[1:3]),dima[4]) val <- .average(val,weight=w) dim(val) <- nc.count[indV] res$value <- val rm(val) } } else dim(res$value) <- con$offset[indV] } if (permute) { dima <- length(dim(res$value)) if (dima==2) res$value <- aperm(res$value,c(2,1)) else if (dima==3) res$value <- aperm(res$value,c(2,1,3)) else if (dima==4) res$value <- aperm(res$value,c(2,1,3,4)) else stop(paste("NCDF: transpose is not implemented for dimension:",dima)) } if (flip) { if (length(dim(res$value))>2) res$value <- res$value[,rev(seq(dim(res$value)[2])),,drop=FALSE] else res$value <- res$value[,rev(seq(dim(res$value)[2])),drop=FALSE] } dim(res$value) <- with(con,c(samples,lines,bands)) ncdf4::nc_close(nc) } else stop(paste("unknown driver:",con$driver)) if ((con$samples!=res$grid$columns)||(con$lines!=res$grid$rows)) res$value <- res$value[con$indexC,con$indexR,,drop=FALSE] dimy <- dim(res$value) dim(res$value) <- c(dimy[1]*dimy[2],dimy[3]) ## t() res$dim <- dim(res$value) if (!is.na(con$nodata)) { if (abs(con$nodata)<1) res$value[abs(res$value-con$nodata)<1e-27] <- NA else res$value[abs(res$value/con$nodata-1)<1e-6] <- NA } class(res$value) <- clValue return(res) } else if ((missingJ)&&(!missingI)) ## read band { if (verbose) cat("read bands ",min(i),":",max(i),"\n") if (is.list(i)) i <- unlist(i) nb <- length(i) i <- as.integer(i) nline <- if (!is.na(con$indexR[1L])) length(con$indexR) else con$lines if (is.na(con$indexR)[1]) minJ <- 0L else minJ <- min(con$indexR)-1L minI <- min(i) toWarp <- with(con,(!is.na(indexR)[1])&&(length(indexR)!=lines)|| (!is.na(indexC)[1])&&(length(indexC)!=samples)) if (con$driver %in% c("ENVI","EGDAL")) { if (con$interleave=="bil") { if (externalReading) { if (con$seek) seek(con,where=0L,origin="start",rw="r") xdim <- with(con,c(lines,samples,bands)) if (con$mode=="integer") val <- .Cursa(C_readBilBandInteger,con$fname[indF],dim=xdim,index=i ,n=nb,datatype=con$datatype,swap=con$swap ,res=integer(with(con,nb*samples*lines)))$res else { val <- .Cursa(C_readBilBandDouble,con$fname[indF],dim=xdim,index=i ,n=nb,datatype=con$datatype,swap=con$swap ,res=double(with(con,nb*samples*lines)))$res } } else { n <- nb*con$samples val <- array(NA,dim=c(n,nline)) conseq <- all(diff(sort(i))==1) if (conseq) { for (r in seq(nline)) { # print(with(con,c(minJ=minJ,rsi=bands*(r-1)+minI-1 # ,samples=samples,sizeof=sizeof))) pos <- with(con,(minJ+bands*(r-1)+minI-1)*samples*sizeof) # print(c(r=r,pos=pos,n=n)) if (con$seek) seek(con,where=pos,origin="start",rw="r") val[,r] <- with(con,.readline(handle,datatype,n,endian)) } } else { for (r in seq(nline)) { for (s in seq_along(i)) { pos <- with(con,(minJ+bands*(r-1)+i[s]-1)*samples*sizeof) if (con$seek) seek(con,where=pos,origin="start",rw="r") s2 <- seq((s-1)*con$samples+1,s*con$samples) val[s2,r] <- with(con,.readline(handle,datatype,con$samples,endian)) } } } } if (toWarp) ## added 2013-06-14 { dim(val) <- with(con,c(samples,nb,lines)) val <- val[,,con$indexR,drop=FALSE] } dim(val) <- with(con,c(samples,nb,nline)) val <- aperm(val,c(1,3,2)) } else if (con$interleave=="bip") { n <- with(con,samples*bands) val <- array(NA,dim=c(nb*con$samples,nline)) ind <- which(with(con,(seq(bands*samples)-1)%%bands+1) %in% i) for (r in seq(nline)) { pos <- with(con,(minJ+(r-1)*samples*bands)*sizeof) if (con$seek) seek(con,where=pos,origin="start",rw="r") val[,r] <- with(con,.readline(handle,datatype,n,endian))[ind] } dim(val) <- with(con,c(nb,samples,nline)) val <- aperm(val,c(2,3,1)) } else if (con$interleave=="bsq") { isSeq <- identical(i,min(i):max(i)) # val <- array(NA,dim=c(con$samples*nline,nb)) if ((externalReading)&&(TRUE)) { if (con$seek) seek(con,where=0L,origin="start",rw="r") xdim <- with(con,c(lines,samples,bands)) # str(list(i=i,dim=xdim,nb=nb,fname=con$fname)) if (con$mode=="integer") { val <- .Cursa(C_readBsqBandInteger,fname=con$fname[indF],dim=xdim,index=i ,n=nb,datatype=con$datatype,swap=con$swap ,res=integer(with(con,nb*samples*lines)))$res } else { val <- .Cursa(C_readBsqBandDouble,fname=con$fname[indF],dim=xdim,index=i ,n=nb,datatype=con$datatype,swap=con$swap ,res=double(with(con,nb*samples*lines)))$res } } else { val <- array(NA,dim=c(con$samples*nline,nb)) if ((1)&&(isSeq)) { n <- with(con,nline*samples*nb) pos <- with(con,(minJ+(minI-1)*lines*samples)*sizeof) if (con$seek) seek(con,where=pos,origin="start",rw="r") val[] <- with(con,.readline(handle,datatype,n,endian)) } else { n <- with(con,nline*samples) for (r in seq(along=i)) { pos <- with(con,(minJ+(i[r]-1)*lines*samples)*sizeof) if (con$seek) seek(con,where=pos,origin="start",rw="r") val[,r] <- with(con,.readline(handle,datatype,n,endian)) } } } if (toWarp) { dim(val) <- with(con,c(samples,lines,nb)) val <- val[,con$indexR,,drop=FALSE] ## before 2012-12-23 } dim(val) <- with(con,c(samples,nline,nb)) # val <- aperm(val,c(1,2,3)) } else stop("Error in input header file ",con$interleave ," incorrect interleave type") } else if (con$driver=="RGDAL") { ## read band val <- .rgdal_getRasterData(con$handle,band=i) dim(val) <- with(con,c(samples,nline,nb)) } else if (con$driver=="GDALRASTER") { ## read band if (con$datatype %in% c(4,5)) val <- array(NA_real_,dim=c(res$dim[1],length(i))) else val <- array(NA_integer_,dim=c(res$dim[1],length(i))) if (verbose) cat("read chunk band") for (b2 in seq_along(i)) { if (verbose) cat(".") val[,b2] <- con$handle$read(band=i[b2] ,xoff=0,yoff=0 ,xsize=con$samples,ysize=con$lines ,out_xsize=con$samples,out_ysize=con$lines ) } if (verbose) cat(" done!\n") dim(val) <- with(con,c(samples,nline,nb)) } else if (con$driver=="SF") { ## read band rasterio <- list(bands=i) if (con$datatype %in% c(4,5)) { val <- attr(sf::gdal_read(con$handle$filename,read_data=TRUE ,RasterIO_parameters=rasterio),"data") attr(val,"units") <- NULL } else { val <- as.integer(attr(sf::gdal_read(con$handle$filename,read_data=TRUE ,RasterIO_parameters=rasterio),"data")) } dim(val) <- with(con,c(samples,nline,nb)) } else if (con$driver=="NCDF") { ## read band # stop("NCDF -- read band") # str(con) # print(c(i=i)) di <- diff(i) isC <- ((!length(di))||(abs(unique(di))==1)) nc <- ncdf4::nc_open(con$fname) varName <- con$handle flip <- attr(varName,"flip") permute <- attr(varName,"permute") indT <- attr(varName,"temporal") indS <- attr(varName,"spatial") indV <- c(indS,indT) indL <- seq_along(con$offset)[-indV] # print(c(indS=indS,indT=indT,indL=indL)) w <- attr(varName,"weight") attributes(varName) <- NULL nc.start <- rep(1,length(con$offset)) nc.count <- con$offset if (length(w)) { ind <- which(w>0) isW <- all(diff(ind))==1 if (isW) { nc.start[indL] <- ind[1] nc.count[indL] <- length(ind) w <- w[ind] } } else isW <- FALSE # level <- attr(varName,"level") # print(data.frame(var=varName,flip=flip,permute=permute,time=time)) if (isC) { #(isC) { nc.start[indT] <- min(i) nc.count[indT] <- length(i) val <- ncdf4::ncvar_get(nc,varName,start=nc.start,count=nc.count ,collapse_degen=FALSE) # if (length(indL)==1) # val <- apply(val,c(1,2,indT),mean) } else { nc.count[indT] <- 1 dima <- con$offset dima[indT] <- length(i) val <- array(NA_real_,dim=dima) for (i2 in seq_along(i)) { nc.start[indT] <- i[i2] if (length(indL)==1) { if (indT==4) val[,,,i2] <- ncdf4::ncvar_get(nc,varName,start=nc.start ,count=nc.count,collapse_degen=FALSE) else stop("NCDF column 'time' index?") } else { if (indT==3) val[,,i2] <- ncdf4::ncvar_get(nc,varName,start=nc.start ,count=nc.count,collapse_degen=FALSE) else if (indT==1) val[i2,,] <- ncdf4::ncvar_get(nc,varName,start=nc.start ,count=nc.count,collapse_degen=FALSE) } } } if (length(indL)==1) { if (nc.count[indL]>1) { ## con$offset[indL]>1 if (FALSE) val <- apply(val,indV,function(x) sum(x*w)) else { val <- aperm(val,c(indV,indL)) dima <- dim(val) dim(val) <- c(prod(dima[1:3]),dima[4]) val <- .average(val,weight=w) dim(val) <- nc.count[indV] } } else { dim(val) <- nc.count[indV] } } if (permute) { dima <- length(dim(val)) if (dima==2) val <- aperm(val,c(2,1)) else if (dima==3) val <- aperm(val,c(2,1,3)) else if (dima==4) val <- aperm(val,c(2,1,3,4)) else stop(paste("NCDF: transpose is not implemented for dimension:",dima)) } if (flip) { if (length(dim(val))>2) val <- val[,rev(seq(dim(val)[2])),,drop=FALSE] else val <- val[,rev(seq(dim(val)[2])),drop=FALSE] } dim(val) <- with(con,c(samples,nline,nb)) ncdf4::nc_close(nc) } if (!is.na(con$indexC[1])) res$value <- val[con$indexC,,,drop=FALSE] else res$value <- val dimy <- dim(res$value) dim(res$value) <- c(dimy[1]*dimy[2],dimy[3]) if (!is.na(con$nodata)) { if (abs(con$nodata)<1) res$value[abs(res$value-con$nodata)<1e-27] <- NA else { # print(abs(res$value/con$nodata-1)) res$value[abs(res$value/con$nodata-1)<1e-6] <- NA } } res$con$posZ <- i class(res$value) <- clValue return(res) } else if ((!missingJ)&&(missingI)) ## read line { if (is.list(j)) j <- unlist(j) j <- as.integer(seq(min(j),max(j))) nline <- length(j) minJ <- (min(j)-1L)+min(con$indexR-1L) if (con$driver %in% c("ENVI","EGDAL")) { if (con$interleave=="bil") ##bil[col,band,row] -> R[col,row,band] { if ((externalReading)&&(TRUE)) { xdim <- with(con,c(lines,samples,bands)) if (con$mode=="integer") val <- .Cursa(C_readBilLineInteger,con$fname[indF],dim=xdim ,lines=j+as.integer(min(con$indexR-1L)) ,nline=nline,datatype=con$datatype,swap=con$swap ,res=integer(with(con,nline*samples*bands)))$res else val <- .Cursa(C_readBilLineDouble,con$fname[indF],dim=xdim ,lines=j+as.integer(min(con$indexR-1L)) ,nline=nline,datatype=con$datatype,swap=con$swap ,res=double(with(con,nline*samples*bands)))$res # print(summary(val)) } else { n <- with(con,nline*bands*samples) # print(sprintf("seek=%d",with(con,minJ*bands*sizeof*samples))) if (con$seek) seek(con,where=with(con,minJ*bands*sizeof*samples) ,origin="start",rw="r") val <- with(con,.readline(handle,datatype,n,endian)) # print(summary(val)) } dim(val) <- with(con,c(samples,bands,nline)) val <- aperm(val,c(1,3,2)) } else if (con$interleave=="bip") ##bip[band,col,row] -> R[col,row,band] { n <- with(con,nline*bands*samples) seek(con,where=with(con,minJ*bands*sizeof*samples),origin="start",rw="r") val <- with(con,.readline(handle,datatype,n,endian)) dim(val) <- with(con,c(bands,samples,nline)) val <- aperm(val,c(2,3,1)) } else if (con$interleave=="bsq") ##bsq[col,row,band] -> R[col,row,band] { if ((externalReading)&&(TRUE)) { xdim <- with(con,c(lines,samples,bands)) if (con$mode=="integer") val <- .Cursa(C_readBsqLineInteger,con$fname[indF],dim=xdim,lines=j ,nline=nline,datatype=con$datatype,swap=con$swap ,res=integer(with(con,nline*samples*bands)))$res else val <- .Cursa(C_readBsqLineDouble,con$fname[indF],dim=xdim,lines=j ,nline=nline,datatype=con$datatype,swap=con$swap ,res=double(with(con,nline*samples*bands)))$res } else { n <- nline*con$samples val <- array(NA,dim=c(n,con$bands)) for (nb in seq(con$bands)) { pos <- minJ+(nb-1)*con$lines if (con$seek) seek(con,where=with(con,pos*sizeof*samples),origin="start",rw="r") val[,nb] <- with(con,.readline(handle,datatype,n,endian)) } } dim(val) <- with(con,c(samples,nline,bands)) # val <- aperm(val,c(1,2,3)) } } else if (con$driver=="RGDAL") { ## read line nline <- length(j) minJ <- (min(j)-1L)+min(con$indexR-1L) val <- .rgdal_getRasterData(con$handle,offset=c(minJ,0) ,region.dim=c(nline,con$samples)) dim(val) <- with(con,c(samples,nline,bands)) } else if (con$driver=="GDALRASTER") { ## read line nline <- length(j) minJ <- (min(j)-1L)+min(con$indexR-1L) if (con$datatype %in% c(4,5)) val <- array(NA_real_,dim=c(con$samples*nline,res$dim[2])) else val <- array(NA_integer_,dim=c(con$samples*nline,res$dim[2])) if (verbose) cat("read chunk line") for (b2 in seq_len(con$bands)) { if (verbose) cat(".") val[,b2] <- con$handle$read(band=b2 ,xoff=0,yoff=minJ ,xsize=con$samples,ysize=nline ,out_xsize=con$samples,out_ysize=nline ) } if (verbose) cat(" done!\n") dim(val) <- with(con,c(samples,nline,bands)) } else if (con$driver=="SF") { ## read line nline <- length(j) minJ <- (min(j)-1L)+min(con$indexR-1L) rasterio <- list(nXOff=1,nYOff=minJ+1L,nXSize=con$samples,nYSize=nline # ,nBufXSize=2,nBufYSize=2 ) if (con$datatype %in% c(4,5)) { val <- attr(sf::gdal_read(con$handle$filename,read_data=TRUE ,RasterIO_parameters=rasterio),"data") attr(val,"units") <- NULL } else { val <- as.integer(attr(sf::gdal_read(con$handle$filename,read_data=TRUE ,RasterIO_parameters=rasterio),"data")) } dim(val) <- with(con,c(samples,nline,bands)) } else if (con$driver=="NCDF") { ## read line nc <- ncdf4::nc_open(con$fname[indF]) varName <- con$handle # str(con$offset) flip <- attr(varName,"flip") permute <- attr(varName,"permute") indT <- attr(varName,"temporal") indS <- attr(varName,"spatial") indV <- c(indS,indT) indL <- seq_along(con$offset)[-indV] indC <- indS[ifelse(permute,2,1)] indR <- indS[ifelse(permute,1,2)] # indR <- ifelse(permute,1L,2L) # indC <- 3L-indR w <- attr(varName,"weight") if (flip) j <- rev(rev(seq(con$offset[[indR]]))[j]) nline <- length(j) dj <- diff(j) isC <- ((!length(dj))||(abs(unique(dj))==1)) # level <- attr(varName,"level") attributes(varName) <- NULL nc.start <- rep(1,length(con$offset)) nc.count <- con$offset ##~ print(nc.start) ##~ print(nc.count) if (isC) { #(isC) { nc.start[indR] <- min(j) nc.count[indR] <- length(j) # print(c(start=nc.start)) # print(c(count=nc.count)) val <- ncdf4::ncvar_get(nc,varName,start=nc.start,count=nc.count ,collapse_degen=FALSE) } else { ## slow! nc.count[indR] <- 1 dima <- con$offset dima[indR] <- length(j) val <- array(NA_real_,dim=dima) for (j2 in seq_along(j)) { nc.start[indR] <- j[j2] # print(nc.start) # print(nc.count) if (length(indL)==1) { if (indR==2) val[,j2,,] <- ncdf4::ncvar_get(nc,varName,start=nc.start ,count=nc.count,collapse_degen=FALSE) else stop("NCDF column 'line' index? (multi-level)") } else { # print(indV) if (indR==2) val[,j2,] <- ncdf4::ncvar_get(nc,varName,start=nc.start ,count=nc.count,collapse_degen=FALSE) else stop("NCDF column 'line' index? (single-level)") } } } if (length(indL)==1) { if (con$offset[indL]>1) { # val <- apply(val,indV,mean) if (FALSE) val <- apply(val,indV,function(x) sum(x*w)) else { val <- aperm(val,c(indV,indL)) dima <- dim(val) dim(val) <- c(prod(dima[1:3]),dima[4]) val <- .average(val,weight=w) dim(val) <- nc.count[indV] } } else { dim(val) <- nc.count[indV] # con$offset[indV] } } if (permute) { dima <- length(dim(val)) if (dima==2) val <- aperm(val,c(2,1)) else if (dima==3) val <- aperm(val,c(2,1,3)) else if (dima==4) val <- aperm(val,c(2,1,3,4)) else stop(paste("NCDF: transpose is not implemented for dimension:",dima)) } if (flip) { if (length(dim(val))>2) val <- val[,rev(seq(dim(val)[2])),,drop=FALSE] else val <- val[,rev(seq(dim(val)[2])),drop=FALSE] } dim(val) <- with(con,c(samples,nline,bands)) ncdf4::nc_close(nc) } else stop("read ENVI: Error in input header file ",con$interleave ," incorrect interleave type") res$value <- val[con$indexC,,,drop=FALSE] dimy <- dim(res$value) dim(res$value) <- c(dimy[1]*dimy[2],dimy[3]) ## t() if (!is.na(con$nodata)) { if (abs(con$nodata)<1) res$value[abs(res$value-con$nodata)<1e-27] <- NA else res$value[abs(res$value/con$nodata-1)<1e-6] <- NA } res$con$posR <- j res$dim <- dim(res$value) class(res$value) <- clValue return(res) } else stop("TODO") stop("UNREACHABLE CODE") } '.readline' <- function(Fin,datatype,size,endian) { if (FALSE) ## benchmark is needed datatype <- datatype+1000L if (datatype==1001) ## data.type==1 -> 1-byte short val <- readBin(Fin,integer(),n=size,size=1,signed=FALSE) else if (datatype==1) ## data.type==1 -> 1-byte short, unsigned val <- readBin(readBin(Fin,raw(),n=size*1) ,integer(),n=size,size=1,signed=FALSE) else if (datatype==1002) ## data.type==2 -> 2-byte short, signed val <- readBin(Fin,integer(),n=size,size=2,endian=endian,signed=TRUE) else if (datatype==2) ## data.type==2 -> 2-byte short, unsigned val <- readBin(readBin(Fin,raw(),n=size*2) ,integer(),n=size,size=2,endian=endian,signed=TRUE) else if (datatype==1003) ## data.type==3 -> 4-byte int val <- readBin(Fin,integer(),n=size,endian=endian,signed=TRUE) else if (datatype==3) ## data.type==3 -> 4-byte int val <- readBin(readBin(Fin,raw(),n=size*4) ,integer(),n=size,endian=endian,signed=TRUE) else if (datatype==1004) ## data.type==4 -> 4-byte float val <- readBin(Fin,double(),n=size,size=4,endian=endian) else if (datatype==4) ## data.type==4 -> 4-byte float val <- readBin(readBin(Fin,raw(),n=size*4) ,double(),n=size,size=4,endian=endian) else if (datatype==5) ## data.type==5 -> 8-byte double val <- readBin(Fin,double(),n=size,endian=endian) else if (datatype %in% c(11,1011)) ## data.type==11 -> 1-byte signed short integer val <- readBin(Fin,integer(),n=size,size=1,endian=endian,signed=TRUE) else if (datatype %in% c(12,1012)) ## data.type==12 -> 2-byte unsigned short integer val <- readBin(Fin,integer(),n=size,size=2,endian=endian,signed=FALSE) else if (datatype %in% c(13,1013)) ## data.type==13 -> 4-byte unsigned integer { val <- readBin(Fin,integer(),n=size,size=4,endian=endian,signed=!FALSE) ## need signed=FALSE! ind <- which(val>(2^31-1)) if (length(ind)) { opW <- options(warn=1) warning("Datatype 'UInt32' is supported with restriction. See '?readBin'.") options(opW) val[ind] <- val[ind]-2^32 } } else stop("Unsupported data data type: ",datatype) gc(reset=TRUE) val }
/scratch/gouwar.j/cran-all/cranData/ursa/R/classRaster.Extract.R
'.raster.skeleton' <- function() { obj <- list(grid=NA,con=NA,value=NA,dim=NA,name=NA,colortable=character(0)) class(obj$value) <- "ursaNumeric" class(obj$colortable) <- "ursaColorTable" class(obj) <- "ursaRaster" obj } 'is_ursa' <- function(obj,ref=NULL) is.ursa(obj=obj,ref=ref) 'is.ursa' <- function(obj,ref=NULL) { if (is.null(ref)) return(inherits(obj,"ursaRaster")) if (.lgrep("(raster|brick|ursa)",ref)>0) return(inherits(obj,"ursaRaster")) if (.lgrep("grid",ref)>0) return(.is.grid(obj)) if (.lgrep("(ct|color|table)",ref)>0) return(.is.colortable(obj)) if (.lgrep("stack",ref)>0) return(.is.ursa_stack(obj)) if (.lgrep("con",ref)>0) return(.is.con(obj)) if (.lgrep("val",ref)>0) return(inherits(obj,"ursaNumeric") || inherits(obj,"ursaCategory")) if (.lgrep("cat",ref)>0) return(.is.category(obj)) FALSE } '.str.ursaRaster' <- function(x,grid=NA,con=NA,...) { NULL } 'str.ursaRaster' <- function(object,...) { arglist <- list(...) Rgrid <- .getPrm(arglist,name="grid",default=NA) con <- .getPrm(arglist,name="con",default=NA) os <- object.size(object) .con <- con if (is.na(con)) con <- FALSE if (is.na(Rgrid)) { if (is.na(.con)) Rgrid <- TRUE else Rgrid <- FALSE } if (!con) { if (!is.na(nodata <- ursa_nodata(object))) object$nodata <- nodata if (identical(dim(object$value),object$dim)) object$dim <- NULL if (!length(object$colortable)) { object$colortable <- NULL # attr(object$value,"category") <- NULL } if (!is.na(object$con$posZ[1])) object$name <- object$name[object$con$posZ] object$con <- NULL } if (!Rgrid) object$grid <- NULL else { # if (is.na(object$grid$retina)) # object$grid$retina <- NULL } if ((!is.null(object$grid$retina))&&(is.na(object$grid$retina))) object$grid$retina <- NULL object$object.size <- format(os,units="MB") metadata <- attr(object,"metadata") if (!is.null(metadata)) attr(object,"metadata") <- TRUE class(object) <- paste0(".",class(object)) NextMethod("str",object,...) } 'print.ursaRaster' <- function(x,digits=NA,grid=FALSE,raw=FALSE,caption=FALSE,...) { ellipsis <- c(">","\u2026")[2] e <- band_stat(x,grid=grid,raw=raw) if (grid) return(format(e,digits=digits,...)) if ((is.null(e))||(!nrow(e))) return(e) if (isTRUE(caption)) { ## try mget(names(match.call())[-1]) caption <- as.character(as.expression(as.list(match.call())[["x"]])) } else if (!(is.character(caption))||(!nchar(caption))) caption <- "" else caption <- "" if (nchar(caption)) cat(paste0(caption,":\n")) if (is.na(digits)) { ln <- e$name lmax <- max(nchar(ln)) cn <- colnames(e) len <- if (lmax>13) seq(lmax,13,by=-1) else lmax nmax <- getOption("width")-max(nchar(rownames(e)))-1 for (i in seq_along(len)) { e$name <- substr(ln,1,len[i]) mn <- ifelse(i==1,2,1) for (d in 6:mn) { f <- format(e,digits=d,scientific=FALSE) f2 <- rbind(cn,as.matrix(f)) f5 <- apply(f2,2,function(x){max(nchar(x))}) n <- length(f5)-1+sum(f5) if (n<nmax) { l <- substr(ln,1,len[i]+nmax-n-1) ind <- which(nchar(ln)!=nchar(l)) if (length(ind)) { b <- nchar(l[ind]) substr(l[ind],b,b) <- ellipsis } f$name <- format(l) return({ if ((FALSE)&&(.isKnitr())) print(knitr::kable(f,format="pandoc")) else { ret <- print(f,quote=FALSE) if (candidate <- TRUE) { ct <- ursa(x,"category") if (!is.null(ct)) { o <- paste(ct,collapse=", ") if (nchar(o)>66) o <- paste0(substr(o,1,65),"\u2026") cat(" Classes: ",o,"\n") } } invisible(ret) } }) } } for (d in 3:mn) { f <- format(e,digits=d,scientific=TRUE) f2 <- rbind(cn,as.matrix(f)) f5 <- apply(f2,2,function(x){max(nchar(x))}) n <- length(f5)-1+sum(f5) if (n<nmax) { l <- substr(ln,1,len[i]+nmax-n-1) ind <- which(nchar(ln)!=nchar(l)) if (length(ind)) { b <- nchar(l[ind]) substr(l[ind],b,b) <- ellipsis } f$name <- format(l) return({ if ((FALSE)&&(.isKnitr())) knitr::kable(f,format="pandoc") else print(f,quote=FALSE) }) } } } digits <- 3 } if ((FALSE)&&(.isKnitr())) knitr::kable(format(e,digits=digits,...)) else print(format(e,digits=digits,...),quote=FALSE) }
/scratch/gouwar.j/cran-all/cranData/ursa/R/classRaster.R
'[<-.ursaRaster' <- function(x,i,j,...,value) { verbose <- isTRUE(getOption("ursaDevel")) if (verbose) { cat("----------\n") on.exit(cat("==========\n")) } # if (verbose) # str(match.call()) dimx <- dim(x$value) con <- x$con if (!.is.con(con)) stop("no connnecton") missingJ <- missing(j) missingI <- missing(i) if (!is.null(dimx)) { if (missingJ) j <- seq(dimx[1]) if (missingI) i <- seq(dimx[2]) if ((is.numeric(i))&&(any(abs(i)>dimx[2]))) i <- as.character(i) if (is.character(i)) { args <- list(...) regexp <- if ("regexp" %in% names(args)) args[["regexp"]] else FALSE i2 <- .getBand(x,i,regexp=regexp) if (is.null(i2)) { names(value) <- i x <- c(x,value) return(x) } i <- i2 j <- seq(dimx[1]) } obj <- x if (is.ursa(i)) { debug <- FALSE if (debug) { print(head(obj)) print(head(i)) print(head(value)) } if (!is.ursa(value)) obj$value[!is.na(i$value)] <- value else { ind <- !is.na(i$value) if (proposed <- TRUE) { if ((length(obj)>1)&&(length(obj)==length(i))) { k <- rep(seq_along(value),length.out=length(obj)) for (m in seq_along(k)) obj$value[ind[,m],m] <- value$value[ind[,m],k[m]] } else ## common obj$value[ind] <- value$value[ind] } else { obj$value[ind] <- value$value[ind] } } if (debug) { print(head(obj)) stop("HERE") } return(obj) } if (is.ursa(value)) { if (FALSE) { print(str(obj)) print(str(value)) print(i) } if (FALSE) ## 2011-08-07 { if (length(obj$name[i])==length(value$name[seq(i)])) obj$name[i] <- value$name[seq(i)] } posR <- value$con$posR posZ <- value$con$posZ value <- value$value ## length(dim(val))==2 should be! isUrsa <- TRUE } else { posR <- NA posZ <- NA isUrsa <- FALSE } if (TRUE) { ## added 20160327 bg <- ignorevalue(x) if (!is.na(bg)) value[.is.eq(value,bg)] <- NA } if (verbose) { str(value) print(is.null(value)) print(dim(value)) print(length(value)) } if (missingJ) { if (is.null(value)) return(obj[-i]) if ((is.null(dim(value)))&&(!length(value))) return(obj[-i]) } if (is.array(value)) { if (!isUrsa) { ## 20170712 ++ d <- prod(obj$dim)/prod(dim(value)) d2 <- prod(dim(value))==prod(c(obj$dim[1],obj$dim[1]/prod(dim(value)))) ## 2013-02-25 added '&&(prod(dim(value))==prod(obj$dim))' ## 2013-10-07 added '&&(d==round(d))' ## 2013-11-07 added '&&(d2)' if ((dim(value)[1]!=obj$dim[1])&&(d==round(d))&&(d2)) dim(value) <- c(obj$dim[1],obj$dim[1]/prod(dim(value))) } j2 <- if (!missingJ) .expandLineIndex(x,j) else j # print(range(j)) # print(range(j2)) # print(i) # str(value) for (m in seq(along=i)) { # obj$data[j,i[m]] <- value[,m] val <- value[,m,drop=FALSE] # val[val==con$nodata] <- NA if (FALSE) { print(c(m=m,j=range(j2),i=i,im=i[m])) print(str(val)) print(str(obj$data[j,])) } obj$value[j2,i[m]] <- val } } else if ((is.numeric(value))||(is.na(value))) { if (!missingJ) j2 <- .expandLineIndex(x,j) if ((!missingJ)&&(length(value)==length(j2))) { for (m in seq_along(i)) { obj$value[j2,i[m]] <- value } } else { dim1 <- obj$dim[1] lenv <- length(value) leni <- length(i) # if (length(value)==1L) # value <- rep(value,length(i)) if (lenv==dim1*leni) obj$value[,i] <- value else if (lenv<=leni) { value <- rep(value,len=leni) for (m in seq(i)) obj$value[,i[m]] <- value[m] } else if (.is.integer(lenv/dim1)) obj$value[,i] <- rep(value,len=dim1*leni) else { str(value) warning("#101 Cannot recognize value structure. Assigning is skipped") } } } else { print(str(value)) warning("#102 Cannot recognize value structure. Assigning is skipped") } # obj$con <- con # print(str(obj));q() return(obj) } if (is.array(value)) { message("**************************** Not debugged *********************************") message("** 'is.array(v)'. Try 'x[] <- ursa_new(value=v)' or 'ursa_value(x) <- v' **") message("**************************** Not debugged *********************************") value <- ursa_new(value=value,flip=FALSE,permute=FALSE) ## introduced 2012-10-14 # val <- value # value <- x # print(str(x)) } else if ((!is.ursa(value))&&((is.numeric(value))||(all(is.na(value))))) { value <- ursa_new(value=value,flip=FALSE,permute=FALSE) } if (is.ursa(value)) { dimy <- dim(value$value) dimx <- x$dim if (length(con$nodata)==1L) value$value[is.na(value$value)] <- con$nodata ## uncomment 2012-05-06 toSeek <- as.integer(con$seek) if (missing(j)) j <- seq(dimy[1]) else if (toSeek) toSeek <- toSeek+1 if (missing(i)) i <- seq(dimy[2]) else if (toSeek) toSeek <- toSeek+2 if (is.list(j)) j <- unlist(j) if (is.list(i)) i <- unlist(i) if (toSeek) toSeek <- toSeek-1 if (is.character(i)) { i <- .getBand(x,i,new=TRUE) j <- seq(dimy[1]) } if (all(i %in% seq(dimx[2]))) NULL else ##if (all(!(i %in% seq(dimx[2])))) { message("append new band(s)") if (x$con$interleave!="bsq") stop("Only BSQ interleave is effective for band rebuild") nb <- x$con$bands nb2 <- max(nb,i) x$con$bands <- nb2 z <- x$con$indexZ x$con$indexZ <- seq(nb2) indZ <- match(z,i) x$dim[2] <- x$dim[2]+nb2-nb myname <- rep("",nb2) myname[z] <- x$name name2 <- value$name if (!is.na(value$con$posZ)[1]) name2 <- name2[value$con$posZ] myname[i] <- name2 ind <- which(!nchar(myname)) if (length(ind)) myname[ind] <- paste0("band",ind) x$name <- myname dimx <- x$dim if (x$con$driver %in% c("ENVI","EGDAL")) { .write.hdr(x) if (TRUE) { ## added 20161226 nb <- ifelse(is.na(x$con$posZ[1]),x$con$bands,length(con$posZ)) if (toSeek) seek(x$con,origin="start" ,where=with(x$con,(lines*samples*nb2-1)*sizeof+offset),rw="w") val <- 0L storage.mode(val) <- con$mode with(x$con,writeBin(val,size=sizeof,endian=endian,handle)) } } con <- x$con } ## else stop("Cannot apply mixed assignment for existing and missing bands") if (!TRUE) ## TRUE before 2012-09-07 { j <- seq(min(j),max(j)) i <- seq(min(i),max(i)) } # isRound <- if (con$datatype %in% c(1,2,3,12)) TRUE else FALSE toRound <- !(is.integer(value$value)) && (con$mode=="integer") bands <- x$dim[2] if (length(i)>bands) { cat(sprintf("writting %d bands into file with %d bands. Truncated\n" ,length(i),bands)) stop("Unpredictive result. Check your code!") i <- i[seq(bands)] } if (verbose) print(c(j=range(j),i=range(i),dim=dimx,toSeek=toSeek)) # print(c(j=all(j %in% seq(dimx[1])),i=all(i %in% seq(dimx[2])))) if ((length(j)<dimx[1])&&(all(j %in% seq(dimx[1])))) ## write lines { if (verbose) print("write lines") toSeek <- toSeek %in% c(1,3) if (any(is.na(value$con$posR))) nl <- as.integer(dimy[1]/con$samples) else nl <- length(value$con$posR) sparse <- attr(value$value,"sparse") if ((!is.null(sparse))&&(any(sparse!=0))) { val <- array(NA,dim=with(con,c(samples*nl,dimy[2]))) cl <- class(value$value) val[sparse,] <- value$value value$value <- val class(value$value) <- cl rm(val) gc(reset=TRUE) } dim(value$value) <- with(con,c(samples,nl,bands)) dimz <- dim(value$value) if (con$driver %in% c("ENVI","EGDAL")) { if (con$interleave=="bil") { if ((0)&&(TRUE)) { stop("HERE") } else { if (toSeek) seek(con,origin="start" ,with(con,(min(j)-1)*samples*bands*sizeof+offset),rw="w") if (toRound) for (r in seq(dimz[2])) writeBin(as.vector(.round(value$value[,r,],0),con$mode) ,size=con$sizeof,endian=con$endian,con$handle) else for (r in seq(dimz[2])) writeBin(as.vector(value$value[,r,],con$mode) ,size=con$sizeof,endian=con$endian,con$handle) } } else if (con$interleave=="bip") { if (toSeek) seek(con,origin="start" ,with(con,(min(j)-1)*samples*bands*sizeof+offset),rw="w") if (toRound) for (r in seq(dimz[2])) writeBin(as.vector(t(.round(value$value[,r,],0)),con$mode) ,size=con$sizeof,endian=con$endian,con$handle) else for (r in seq(dimz[2])) writeBin(as.vector(t(value$value[,r,]),con$mode) ,size=con$sizeof,endian=con$endian,con$handle) } else if (con$interleave=="bsq") { posR <- value$con$posR nl <- length(posR) minI <- min(posR) myoffset <- with(con,(lines-nl)*samples*sizeof) for (r in seq(dimz[3])) { # print(with(con,((r-1)*lines+minI-1)*samples)) if (toSeek) seek(con,origin="start" ,with(con,((r-1)*lines+minI-1)*samples*sizeof+offset) ,rw="w") # print(c(r=r,beg=with(con,seek(handle,w=0,pos="current")))) if (toRound) writeBin(as.vector(.round(value$value[,,r],0),con$mode) ,size=con$sizeof,endian=con$endian,con$handle) else writeBin(as.vector(value$value[,,r],con$mode) ,size=con$sizeof,endian=con$endian,con$handle) # print(c(r=r,end=with(con,seek(handle,w=0,pos="current")))) if ((!toSeek)&&(r<dimz[3])) { seek(con$handle,where=myoffset,origin="current",rw="w") } } if (!toSeek) { seek(con$handle,origin="current" ,where=-with(con,lines*samples*(dimz[3]-1)*sizeof),rw="w") } # print(c(onexit=with(con,seek(handle,w=0,pos="current")))) } } else if (con$driver=="RGDAL") { # write lines minJ <- min(j)-1 if (toRound) { for (b in seq(dimz[3])) { .rgdal_putRasterData(con$handle ,.round(value$value[,,b,drop=TRUE]) ,offset=c(minJ,0),band=b) } } else { for (b in seq(dimz[3])) { .rgdal_putRasterData(con$handle,value$value[,,b,drop=TRUE] ,offset=c(minJ,0),band=b) } } } } else if ((length(i)<dimx[2])&&(all(i %in% seq(dimx[2])))) ## write bands { if (verbose) print("write bands") toSeek <- (toSeek %in% c(1,2)) ## c(2,3) 2012-08-27 sparse <- attr(value$value,"sparse") if ((!is.null(sparse))&&(any(sparse!=0))) { val <- array(NA,dim=with(con,c(samples*lines,dimy[2]))) cl <- class(value$value) val[sparse,] <- value$value value$value <- val class(value$value) <- cl rm(val) gc(reset=TRUE) } else dim(value$value) <- with(con,c(samples,lines,dimy[2])) dimz <- dim(value$value) if (con$driver %in% c("ENVI","EGDAL")) { if (con$interleave=="bil") { posZ <- as.integer(value$con$posZ) # .elapsedTime("write:start") if ((0)&&(TRUE)) { xdim <- with(con,c(lines,samples,bands)) if (toRound) val <- as.vector(.round(value$value),con$mode) else val <- as.vector(value$value,con$mode) if (!is.na(con$nodata)) val[is.na(val)] <- con$nodata if (con$mode=="integer") val <- .Cursa(C_writeBilBandInteger,con$fname,val=val,dim=xdim ,index=posZ,n=length(posZ),datatype=con$datatype ,swap=con$swap) else val <- .Cursa(C_writeBilBandDouble,con$fname,dim=xdim,index=i ,n=bands,datatype=con$datatype,swap=con$swap ,res=double(with(con,bands*samples*lines)))$res } else { if (!toSeek) { if (!is.na(posZ[1])) i <- posZ else if (FALSE) stop("unable define file position. Please specify 'band'") toSeek <- con$seek if (is.na(posZ[1])) nb <- con$bands else { nb <- length(posZ) i <- seq(length(posZ)) } nb <- ifelse(is.na(con$posZ[1]),con$bands,length(con$posZ)) } else nb <- con$bands dj <- which(diff(i)!=1) nj <- 1+length(dj) listJ <- vector("list",nj) j1 <- 1 for (j3 in seq_along(listJ)) { j2 <- ifelse(j3==nj,length(i),dj[j3]) listJ[[j3]] <- i[j1:j2] j1 <- j2+1 } for (j0 in seq_along(listJ)) { j1 <- listJ[[j0]] minJ <- min(j1)-1 j2 <- match(j1,i) for (r in seq(dimz[2])) { if (toSeek) { pos <- with(con,((r-1)*nb+minJ)*samples*sizeof+offset) seek(con$handle,pos,origin="start",rw="w") } if (toRound) writeBin(as.vector(.round(value$value[,r,j2],0),con$mode) ,size=con$sizeof,endian=con$endian,con$handle) else writeBin(as.vector(value$value[,r,j2],con$mode) ,size=con$sizeof,endian=con$endian,con$handle) } } } # .elapsedTime("write:finish") } else if (con$interleave=="bip") { posZ <- value$con$posZ minJ <- min(posZ)-1 for (r in seq(dimz[2])) { val <- t(value$value[,r,]) if (toRound) val <- .round(val,0) for (c in seq(dimz[1])) { pos <- with(con,(((r-1)*samples+c-1)*bands+minJ)*sizeof+offset) seek(con$handle,pos,origin="start",rw="w") writeBin(as.vector(val[,c],con$mode) ,size=con$sizeof,endian=con$endian,con$handle) } } } else if (con$interleave=="bsq") { toSeek <- con$seek ## introdiced 2012-08-27 for (r in seq(along=i)) { if (toSeek) seek(con$handle,origin="start" ,with(con,(i[r]-1)*lines*samples*sizeof+offset),rw="w") if (toRound) writeBin(as.vector(.round(value$value[,,r],0),con$mode) ,size=con$sizeof,endian=con$endian,con$handle) else writeBin(as.vector(value$value[,,r],con$mode) ,size=con$sizeof,endian=con$endian,con$handle) # if ((!toSeek)&&(r<dimy[3])) # seek(con$handle,where=myoffset,origin="current") } if ((0)&&(!toSeek)) seek(con$handle,origin="current" ,where=-with(con,(lines)*samples*(dimy[3]-1)*sizeof),rw="w") } else stop("unknown interleave") } else if (con$driver=="RGDAL") { ## write bands if (toRound) { for (r in seq_along(i)) { .rgdal_putRasterData(con$handle ,.round(value$value[,,r,drop=TRUE]) ,band=i[r]) } } else { for (r in seq_along(i)) { .rgdal_putRasterData(con$handle,value$value[,,r,drop=TRUE] ,band=i[r]) } } } } else if ((length(j)==dimx[1])&&(length(i)==dimx[2])) ## write full { if (verbose) print("write full") # .writeall(data=value$value,con=con,split=TRUE,con$handle) if (!is.na(con$nodata)) { # storage.mode(con$nodata) <- con$mode if (TRUE) { tmp <- value$value tmp[is.na(tmp)] <- con$nodata value$value[] <- tmp } else if (FALSE) value$value[is.na(value$value)] <- con$nodata else if (FALSE) is.na(value$value) <- con$nodata ## don't trust } value <- decompress(value) dim(value$value) <- with(con,c(samples,lines,bands)) if (con$driver %in% c("ENVI","EGDAL")) { Fout <- con$handle if (con$seek) seek(con,origin="start",where=con$offset,rw="w") if (toRound) { if (con$interleave=="bil") ## R's [col,row,band] -> bil [col,band,row] { for (r in seq(dim(value$value)[2])) writeBin(as.vector(.round(value$value[,r,],0),con$mode) ,size=con$sizeof,endian=con$endian,Fout) } else if (con$interleave=="bip") ## R's [col,row,band] -> bip [band,col,row] { for (r in seq(dim(value$value)[2])) writeBin(as.vector(t(.round(value$value[,r,],0)),con$mode) ,size=con$sizeof,endian=con$endian,Fout) } else if (con$interleave=="bsq") ## R's [col,row,band] -> bsq [col,row,band] { for (r in seq(dim(value$value)[3])) writeBin(as.vector(.round(value$value[,,r],0),con$mode) ,size=con$sizeof,endian=con$endian,Fout) } } else { if (con$interleave=="bil") ## R's [col,row,band] -> bil [col,band,row] { for (r in seq(dim(value$value)[2])) writeBin(as.vector(value$value[,r,],con$mode) ,size=con$sizeof,endian=con$endian,Fout) } else if (con$interleave=="bip") ## R's [col,row,band] -> bip [band,col,row] { for (r in seq(dim(value$value)[2])) writeBin(as.vector(t(value$value[,r,]),con$mode) ,size=con$sizeof,endian=con$endian,Fout) } else if (con$interleave=="bsq") ## R's [col,row,band] -> bsq [col,row,band] { for (r in seq(dim(value$value)[3])) writeBin(as.vector(value$value[,,r],con$mode) ,size=con$sizeof,endian=con$endian,Fout) } } } else if (con$driver=="RGDAL") { # write full dimz <- dim(value$value) if (toRound) { for (b in seq(dimz[3])) .rgdal_putRasterData(con$handle ,.round(value$value[,,b,drop=TRUE]) ,band=b) } else { for (b in seq(dimz[3])) { .rgdal_putRasterData(con$handle,value$value[,,b,drop=TRUE] ,band=b) } } } } else { print(dimx) print(length(j)) print(length(i)) stop("TODO#1") } if (x$con$compress==-1) x$con$compress <- -2L else if (x$con$compress==0) x$con$compress <- 3L return(x) } else stop("TODO#2") } '.expandLineIndex' <- function(x,j) ## cadidate for applying in '[.' function { if (!is.ursa(x)) return(NULL) if (is.na(x$con$indexC)[1]) s <- x$grid$columns else s <- length(x$con$indexC) i <- as.integer(c(t(col(array(NA,dim=c(length(j),s)))+(j-1)*s))) if (max(j)>x$dim[1]) { print(c(maxi=max(j),leni=length(j))) i <- i[i<=x$dim[1]] } i }
/scratch/gouwar.j/cran-all/cranData/ursa/R/classRaster.Replace.R
## ?groupGeneric # 'Summary.ursaRaster' <- function(x,cover=0.5-1e-3,weight=NULL,verbose=FALSE) { '.zzz1.Summary.ursaRaster' <- function(x,cover=0.5-1e-3,weight=NULL,verbose=FALSE ,na.rm=FALSE,bandname="") { res <- .groupSummary(x,generic=.Generic,cover=cover,weight=weight ,bandname=bandname,verbose=verbose) res } 'Summary.ursaRaster' <- function(...,na.rm=FALSE) { arglist <- list(...) cover <- .getPrm(arglist[-1],name="(cov|cvr)",default=0.5-1e-3) weight <- .getPrm(arglist[-1],name="w",class="numeric",default=NULL) verbose <- .getPrm(arglist[-1],name="verb(ose)*",default=FALSE) bandname <- .getPrm(arglist[-1],name="name",default="") if (verbose) str(list(generic=.Generic,cover=cover,weight=weight ,bandname=bandname,verbose=verbose)) res <- .groupSummary(arglist[[1]],generic=.Generic,cover=cover,weight=weight ,bandname=bandname,verbose=verbose) res } '.zzz2.Summary.ursaRaster' <- function(x,na.rm=TRUE) { print(.Generic) stop("GLOBAL") ## global do.call(.Generic,list(x$value,na.rm=na.rm)) } 'Math.ursaRaster' <- function(x,...) { # print(.Generic) x <- discolor(x) # opW <- options(warn=ifelse(.isPackageInUse(),-1,1)) x$value[] <- do.call(.Generic,list(x$value,...)) # options(opW) get("x") } 'Complex.ursaRaster' <- function(z) { stop("Unsupported") } 'Ops.ursaRaster' <- function(e1,e2=NULL) { verbose <- FALSE if (is.ursa(e1)) { # e1 <- discolor(e1) ## removed 20160805 if (.is.category(e1)) {## added 20161214 # attr(e1$value,"category") ct1 <- ursa(e1,"colortable") cl1 <- ursa(e1,"category") e1 <- discolor(e1) # e1 <- .extract(e1) } } else { cl1 <- "" } if (is.ursa(e2)) { # e2 <- discolor(e2) ## removed 20160805 if (.is.category(e2)) {## added 20161214 # attr(e2$value,"category") ct2 <- ursa(e1,"category") e2 <- discolor(e2) # e2 <- .extract(e2) } } else cl2 <- "" if (nargs()==11L) { e2 <- e1 e1 <- 0 if (.Generic %in% c("!")) .Generic <- "!=" } if (nargs()==1L) { if (.Generic %in% c("!")) { val <- e1$value val[] <- NA val[is.na(e1$value)] <- 1L e1$value <- val class(e1$value) <- "ursaNumeric" ignorevalue(e1) <- 127L return(e1) } if (.Generic %in% c("-")) { e1$value[] <- -e1$value return(e1) } } FUN <- get(.Generic,envir=parent.frame(),mode="function") f <- quote(FUN(left,right)) ##eval(f) if (FALSE) { if (is.matrix(e1)) dim(e1) <- c(prod(dim(e1)),1) if (is.matrix(e2)) dim(e2) <- c(prod(dim(e2)),1) } if ((is.character(e2))&&(is.ursa(e1))) { if (.lgrep(e2,names(e1))) e2 <- e1[e2] else { ind <- match(e2,cl1) if (is.na(ind)) ind <- .grep(e2,cl1) if (length(ind) == 1) e2 <- ind-1L else { e1$value[!(e1$value %in% (ind-1L))] <- NA e1$value[!is.na(e1$value)] <- 1L # ursa(e1,"colortable") <- ct1 return(e1) # message(paste("multiple categories are detected:" # ,paste(.sQuote(ct1[ind]),collapse=", "))) # stop("conditions with multiple values are not implemented") } } } if ((is.character(e1))&&(is.ursa(e2))) { e1 <- e2[e1] } isImage1 <- is.ursa(e1) isImage2 <- is.ursa(e2) isArray1 <- is.array(e1) isArray2 <- is.array(e2) isNumeric1 <- is.numeric(e1) isNumeric2 <- is.numeric(e2) if (verbose) print(c(isImage1=isImage1,isImage2=isImage2 ,isArray1=isArray1,isArray2=isArray2 ,isNumeric1=isNumeric1,isNumeric2=isNumeric2)) n1 <- if (isImage1) dim(e1$value)[2] else if (isArray1) dim(e1)[2] else if (isNumeric1) length(e1) else stop("e1: unsupported type") n2 <- if (isImage2) dim(e2$value)[2] else if (isArray2) dim(e2)[2] else if (isNumeric2) length(e2) else stop("e2: unsupported type") n3 <- if ((n1>=n2)&&((n2==1)||(n1==n2))) n1 else if ((n2>1)&&(n1==1)) n2 else {message(paste0("n1=",n1," n2=",n2,": unpredictive"));max(n1,n2)} varName <- if ((isImage1)&&(!isImage2)) "e1" else if ((!isImage1)&&(isImage2)) "e2" else if ((isImage1)&&(isImage2)) if (n3==n1) "e1" else "e2" else stop("What else?") if (verbose) print(data.frame(n1=n1,n2=n2,n3=n3,varName=varName)) isNew <- n3!=dim(get(varName)$value)[2] if (isNew) { e3 <- rep(get(varName),n3) varName <- "e3" } seq1 <- rep(seq(n1),len=n3) seq2 <- rep(seq(n2),len=n3) # st1 <- st2 <- st3 <- 0 if ((n1==1)||(n2==1)) seqi <- list(seq(n3)) else seqi <- lapply(seq(n3),function(x) x) for (i in seqi) { # st1 <- system.time({ left <- if (isImage1) e1$value[,seq1[i]] else if (isArray1) e1[,seq1[i]] else e1[seq1[i]] right <- if (isImage2) e2$value[,seq2[i]] else if (isArray2) e2[,seq2[i]] else e2[seq2[i]] # })["elapsed"]+st1 # st2 <- system.time({ if (varName=="e1") e1$value[,i] <- eval(f) else if (varName=="e2") e2$value[,i] <- eval(f) else if (varName=="e3") e3$value[,i] <- eval(f) # })["elapsed"]+st2 # st3 <- system.time({ if ((TRUE)&&(.Generic %in% c(">","<",">=","<=","==","!="))) { if (varName=="e1") { e1$value[,i][!e1$value[,i]] <- NA ignorevalue(e1) <- 127L } else if (varName=="e2") { e2$value[,i][!e2$value[,i]] <- NA ignorevalue(e2) <- 127L } else if (varName=="e3") { e3$value[,i][!e3$value[,i]] <- NA ignorevalue(e3) <- 127L } } # })["elapsed"]+st3 # print(summary(e1$value[,i])) # message("-------------") } # print(c(st1=st1,st2=st2,st3=st3)) return(get(varName)) } '.groupSummary' <- function(obj,generic=c("blank","all","any","sum" ,"prod","min","max","range" ,"mean","median","sd","var","length") ,cover=0.5-1e-3,weight=NULL,bandname="" ,verbose=FALSE) { if (!is.ursa(obj)) return(NULL) generic <- match.arg(generic) fun <- generic if (generic=="range") { # recursive!!! res <- c(.groupSummary(obj,"min",cover=cover,weight=weight,verbose=verbose) ,.groupSummary(obj,"max",cover=cover,weight=weight,verbose=verbose)) return(res) } code <- switch(generic,blank=0L,all=1L,any=2L,sum=3L,prod=4L ,min=5L,max=6L,range=7L,mean=8L,median=9L ,sd=10L,var=11L,length=12L,-1L) g0 <- session_grid() session_grid(obj) if (.is.con(obj$con)) nodata <- obj$con$nodata else nodata <- NA bname <- if (nchar(bandname)) bandname else switch(generic,length="n",generic) res <- ursa_new(len=1,bandname=bname,nodata=nodata) dimx <- dim(obj$value) if (is.null(weight)) weight <- rep(1,dimx[2]) weight <- weight/sum(weight) if (cover>1) cover <- cover/length(obj) if (cover==0) cover <- 1e-6 if (verbose) .elapsedTime(paste(fun,"start",sep=":")) a <- .Cursa(C_groupSummary ,x=as.numeric(obj$value),dim=as.integer(dimx),cover=as.numeric(cover) ,weight=weight,generic=as.integer(code),res=numeric(dimx[1]*1L) ,NAOK=TRUE)$res if (verbose) .elapsedTime(paste(fun,"stop",sep=":")) if (is.na(obj$con$posR[1])) { res$value[] <- a class(res$value) <- "ursaNumeric" } else { res$con$posR <- obj$con$posR res$value <- a class(res$value) <- "ursaNumeric" dim(res$value) <- c(dimx[1],1) } session_grid(g0) return(res) }
/scratch/gouwar.j/cran-all/cranData/ursa/R/classRaster_GroupGeneric.R
'as.array.ursaRaster' <- function(x,...) { arglist <- list(...) drop <- .getPrm(arglist,name="drop",default=FALSE) flip <- .getPrm(arglist,name="flip",default=FALSE) permute <- .getPrm(arglist,name="perm",default=FALSE) dim <- .getPrm(arglist,name="dim",default=FALSE) .as.array(x,drop=drop,flip=flip,permute=permute,dim=dim) } '.as.array' <- function(x,drop=FALSE,flip=FALSE,permute=FALSE,dim=FALSE) { if (!.is.con(x$con)) { nc <- x$grid$columns nr <- x$grid$rows nb <- x$dim[2] } else { con <- x$con if ((length(con$indexC)==1)&&(is.na(con$indexC[1]))) ## 20170525 added len==1 { if (is.na(con$samples)) nc <- x$grid$columns else nc <- con$samples } else nc <- length(con$indexC) if ((length(con$indexR)==1)&&(is.na(con$indexR[1]))) ## 20170525 added len==1 { if (is.na(con$lines)) nr <- x$grid$rows else nr <- con$lines } else if (all(is.na(con$indexR))) nr <- x$grid$rows else nr <- length(con$indexR) if (is.na(con$indexZ[1])) { if (!is.na(con$bands)) nb <- con$bands else nb <- x$dim[2] } else nb <- length(con$indexZ) if (!is.na(con$posC[1])) nc <- length(con$posC) if (!is.na(con$posR[1])) nr <- length(con$posR) if (!is.na(con$posZ[1])) nb <- length(con$posZ) if (is.na(nb)) nb <- 1L } if (dim) { if (!permute) return(c(nc,nr,nb)) else return(c(nr,nc,nb)) } if (is.null(dim(x$value))) return(NULL) sparse <- attr(x$value,"sparse") if (is.null(sparse)) val <- x$value else if (sparse[1]<0) { ind <- 1L:x$dim[1] ind[-sparse] <- 0L val <- array(NA,dim=c(nc*nr,nb)) val[sparse,] <- x$value } else if (sparse[1]>0) { val <- array(NA,dim=c(nc*nr,nb)) val[sparse,] <- x$value } else val <- x$value dim(val) <- c(nc,nr,nb) if (!flip) ## FALSE 20160201, TRUE 20160330, added '!flip' for 'write.idrisi' val[] <- val[,rev(seq(nr)),] if (permute) val <- aperm(val,c(2,1,3)) if ((drop)&&(nb==1)) val <- val[,,1] class(val) <- NULL val }
/scratch/gouwar.j/cran-all/cranData/ursa/R/classRaster_as.array.R
'as.data.frame.ursaRaster' <- function(x,...) # (x,row.names,optional,...) { arglist <- list(...) band <- .getPrm(arglist,name="band",default=FALSE) id <- .getPrm(arglist,name="id",default=FALSE) na.rm <- .getPrm(arglist,name="na\\.rm",default=TRUE) all.na <- .getPrm(arglist,name="all\\.na",default=FALSE) col.names <- .getPrm(arglist,name="col(\\.)*name(s)*" ,class="character",default=NULL) .as.data.frame(obj=x,band=band,id=id,na.rm=na.rm ,all.na=all.na,col.names=col.names) } '.as.data.frame' <- function(obj,band=FALSE,id=FALSE ,na.rm=TRUE,all.na=FALSE,col.names=NULL) { ## TODO: categories should be intepreted as 'factor' or 'character' g1 <- ursa_grid(obj) if (!length(g1$seqx)) x <- with(g1,seq(minx,maxx,by=resx)[-1]-resx/2) else x <- g1$seqx if (!length(g1$seqy)) y <- rev(with(g1,seq(miny,maxy,by=resy)[-1]-resy/2)) else y <- rev(g1$seqy) # xy <- expand.grid(x=x,y=y,KEEP.OUT.ATTRS=FALSE,stringsAsFactors=FALSE) xy <- data.frame(x=rep(x,times=length(y)),y=rep(y,each=length(x))) isList <- .is.ursa_stack(obj) isCT <- .is.colortable(obj) bname <- bandname(obj) if (!is.na(obj$con$posZ[1])) indZ <- obj$con$posZ else indZ <- seq_along(bname) if (na.rm) { if (length(indZ)>1) { if (all.na) indR <- which(apply(obj$value,1,function(x) all(!is.na(x)))) else indR <- which(apply(obj$value,1,function(x) any(!is.na(x)))) } else { indR <- which(!is.na(obj$value[,1])) } } else indR <- seq(obj$dim[1])#*length(indZ)) xy <- xy[indR,] if (!band) { if (TRUE) { # res <- with(xy,data.frame(x=x,y=y)) res <- xy # isCategory <- .is.category(obj) for (i in seq_along(indZ)) { res$z <- c(obj$value[indR,i]) ## 20170202 'i' or 'indZ[i]'? if (isCT) { ct <- ursa_colortable(obj) aname <- names(ct) # acol <- unname(ct) ## TODO new column $amount_col for $amount # res$z <- factor(names(ct)[res$z+1L]) ## -- 20180317 res$z <- ordered(factor(names(ct)[res$z+1L]),levels=names(ct)) ## ++ 20180317 if (T) attr(res$z,"colortable") <- ct } if (length(indZ)>0) ## 20160812 changed '>1' -> '>0' colnames(res)[i+2] <- bname[i] } if (F & isCT) attr(res,"colortable") <- ct } else if (FALSE){ # res <- cbind(xy,as.data.frame(obj$value[indR,indZ])) ## not quick } else { res <- vector("list",length(indZ)) if (length(indZ)) names(res) <- bname for (i in seq_along(indZ)) { res[[i]] <- c(obj$value[indR,i]) } res <- cbind(xy,res) ## not quick } } else { n <- length(indZ) nr <- nrow(xy) res <- data.frame(x=rep(xy$x,n),y=rep(xy$y,n) ,z=NA ,band=rep(bname,each=nrow(xy)) ,id=rep(seq(nr),n) ,stringsAsFactors=TRUE) for (i in seq_along(indZ)) { ind <- (nr*(i-1)+1):(nr*i) res$z[ind] <- c(obj$value[indR,i]) } if (!id) res$id <- NULL } if (is.character(col.names)) colnames(res) <- rep(col.names,length=ncol(res)) attr(res,"crs") <- g1$crs[which.max(nchar(g1$crs))] # attr(res,"colortable") <- ursa_colortable(obj) res } # 'as_data_frame' <- function(obj) UseMethod("as_data_frame",obj) ##~ '.as_data_frame.ursaRaster' <- function(obj,band=FALSE,id=FALSE ##~ ,na.rm=TRUE,all.na=FALSE) ##~ { ##~ res <- as.data.frame(obj,band=band,id=id,na.rm=na.rm,all.na=all.na) ##~ if (!requireNamespace("dplyr",quietly=.isPackageInUse())) ##~ return(res) ##~ dplyr::as_data_frame(res) ##~ } ##~ '.as.data.table.ursaRaster' <- function(obj,band=FALSE,id=FALSE ##~ ,na.rm=TRUE,all.na=FALSE) { ##~ print("HERE data.table") ##~ NULL ##~ }
/scratch/gouwar.j/cran-all/cranData/ursa/R/classRaster_as.data.frame.R
'as.integer.ursaRaster' <- function(x,...) { clname <- class(x$value) dimx <- dim(x$value) x$value <- as.integer(x$value,...) ignorevalue(x) <- .optimal.nodata(x) ## added 20161206 dim(x$value) <- dimx class(x$value) <- clname x } '.is.integer.ursaRaster' <- function(x,...) { print("needs Generic") NA }
/scratch/gouwar.j/cran-all/cranData/ursa/R/classRaster_as.integer.R
'[[.ursaRaster' <- function(x,i) { if (missing(i)) i <- 1L as.matrix(x[i],coords=TRUE) } 'as.matrix.ursaRaster' <- function(x,...) { coords <- .getPrm(list(...),name="(^$|crd|coord)",default=FALSE) if (!coords) return(unclass(ursa_value(x))) g1 <- x$grid if (FALSE) { ## failed due to round of floating point xo <- with(g1,seq(minx,maxx,by=resx)[-1]-resx/2) yo <- with(g1,seq(miny,maxy,by=resy)[-1]-resy/2) } else { xo <- with(g1,seq(minx,maxx,len=columns+1)[-1]-resx/2) yo <- with(g1,seq(miny,maxy,len=rows+1)[-1]-resy/2) } isValue <- !is.null(dim(x$value)[1]) if (isValue) { posR <- x$con$posR if (is.na(posR[1])) { z <- x$value[,1] } else { z <- rep(NA,with(g1,columns*rows)) z2 <- x$value[,1] nc <- g1$columns sc <- seq(nc) for (i in seq_along(posR)) z[(posR[i]-1)*nc+sc] <- z2[(i-1)*nc+sc] } } dim(z) <- with(g1,c(columns,rows)) z <- z[,rev(seq(g1$rows)),drop=FALSE] img <- list(x=xo,y=yo,z=z)#,nodata=ignorevalue(x),crs=proj4[length(proj4)]) attr(img,"crs") <- with(g1,crs[length(crs)]) if (length(x$colortable)) attr(img,"colortable") <- x$colortable img }
/scratch/gouwar.j/cran-all/cranData/ursa/R/classRaster_as.matrix.R
'as.raster.ursaRaster' <- function(x,...) .as.raster2(obj=x,...) '.as.raster1' <- function(obj,max=255) { # slower verbose <- TRUE if (verbose) .elapsedTime("as.raster -- start") nb <- nband(obj) if (nb>4) return(NULL) a <- round(obj*255/max) dimv <- obj$dim if (nb %in% c(1,3)) { v <- sum(a*c(65536,256,1),cover=1) b <- sprintf("#%06X",as.hexmode(ursa_value(v))) } else { if (nb==4) { v1 <- a[1]*256+a[2] v2 <- a[3]*256+a[4] b <- sprintf("#%04X%04X",as.hexmode(ursa_value(v1)) ,as.hexmode(ursa_value(v2))) } else if (nb==2) { v <- sum(a[1]*c(65536,256,1),cover=1) b <- sprintf("#%06X%02X",as.hexmode(ursa_value(v)) ,as.hexmode(ursa_value(a[2]))) } } b[grep("NA",b)] <- NA dim(b) <- unname(dim(obj)[1:2]) class(b) <- "raster" if (verbose) .elapsedTime("as.raster -- finish") return(b) } '.as.raster2' <- function(obj,...) { # faster maxv <- .getPrm(list(...),name=".*",default=255) verbose <- FALSE nb <- nband(obj) if (verbose) .elapsedTime("as.raster -- start") s <- ursa_value(!is.na(sum(obj,cover=1))) if (nb %in% c(3,4)) { a <- ursa_value(obj) } else if (nb==1) a <- ursa_value(obj[rep(1,3)]) else if (nb==2) a <- ursa_value(obj[c(1,1,1,2)]) else { warning("not recognized as RGB(A) or Grayscale") return(NULL) } dim(a) <- c(1,dim(a)) ind <- which(!is.na(c(s))) res <- rep(NA_character_,prod(dim(s))) res[ind] <- c(grDevices::as.raster(a[,ind,,drop=FALSE],max=maxv)) dim(res) <- dim(obj)[c(1,2)] class(res) <- class(as.raster(1)) if (verbose) .elapsedTime("as.raster -- finish") res }
/scratch/gouwar.j/cran-all/cranData/ursa/R/classRaster_as.raster.R
'as.table.ursaRaster' <- 'ursa_table' <- function(x,...) { # print("as.table.ursaRaster") ct <- ursa_colortable(x) isCT <- .is.colortable(x) res <- table(x$value,...) if (!.is.colortable(ct)) { # ## try mget(names(match.call())[2]) # names(dimnames(res)) <- as.character(match.call())[2] names(dimnames(res)) <- NULL return(res) } ind <- match(as.numeric(names(res)),seq(length(ct))-1) if (any(is.na(ind))) { return(res) } freq <- rep(0L,length(ct)) freq[ind] <- res res <- as.table(freq) dimnames(res) <- list(names(ct)) res } #'table' <- function(...) UseMethod("table") #'table.NULL' <- function(...) NULL #'table.default' <- function(x,...) base::table(x,...) #'table.ursaRaster' <- function(x,...) as.table.ursaRaster(x,...)
/scratch/gouwar.j/cran-all/cranData/ursa/R/classRaster_as.table.R
'c.ursaRaster' <- function(...) { args <- list(...) # str(args) # print(names(args)) if (length(args)<2) { myname <- names(args)[1] res <- args[[1]] if ((is.character(myname))&&(nchar(myname))) { bandname(res) <- rep(myname,length(bandname(res))) } return(res) } x <- decompress(args[[1]]) xname <- names(args[1]) z <- x$con$posZ ##~ if (((length(x$name)==1)||(!is.na(z[1]))&&(length(z)==1))&&(!is.null(xname))) if (is.null(xname)) xname <- "" # if ((length(x$name)==1)&&(nchar(xname))) ## before 2015-03-05 'if (!is.null(xname))' # x$name <- xname if (nchar(xname)) { if (is.na(z[1])) { x$name <- rep(xname,nband(x)) ## x$name <- xname } else if (length(z)==1L) x$name[z] <- xname # x$name <- xname } if (!is.na(z[1])) { x$dim[2] <- length(z) x$name <- x$name[z] nz <- length(z) x$con$posZ <- rep(NA,nz) x$con$indexZ <- seq(nz) x$con$bands <- nz } clValue <- class(x$value) isDiskX <- is.null(dim(x$value)) bandInd <- vector("list",length(args)) bandInd[[1]] <- if (is.na(x$con$bands[1])) 1L else seq(x$con$bands) if (!is.na(x$con$posZ[1])) bandInd[[1]] <- x$con$posZ for (i in seq(along=args)) { if (i==1L) next y <- args[[i]] if (!is.ursa(y)){ if (is.na(y)) y <- ursa_new() else if (is.numeric(y)) y <- ursa_new(value=y) } else y <- decompress(y) isDiskY <- is.null(dim(y$value)) if (isDiskY) next n1 <- seq(x$dim[2]) x$dim[2] <- x$dim[2]+y$dim[2] n2 <- seq(x$dim[2]) indy <- which(is.na(match(n2,n1))) bandInd[[i]] <- indy z <- y$con$posZ yname <- names(args[i]) if (is.na(z[1])) { if (is.null(yname)) yname <- "" if (nchar(yname)) { if (length(y$name)==1) ## before 2015-03-05 'if (!is.null(yname))' y$name <- yname else y$name <- rep(yname,nband(y)) } x$name <- c(x$name,y$name) } else { # op <- options(warn=0) # warning("probably incorrect naminig") # options(op) if (length(y$name[z])==1) { if (is.null(yname)) yname <- "" if (nchar(yname)) ## before 2015-03-05 'if (!is.null(yname))' { y$name <- yname z <- 1L } else { # y$name <- y$name[z] } } x$name <- c(x$name,y$name[z]) ## before 2015-03-05 'c(x$name,y$name)' } if (!is.na(x$con$bands)) { if (!is.na(y$con$bands)) x$con$bands <- x$con$bands+y$con$bands else x$con$bands <- x$con$bands+y$dim[2] } if (!is.na(x$con$indexZ[1L])) { x$con$indexZ <- c(x$con$indexZ,indy) } if ((!isDiskX)&&(!isDiskY)) { x$value <- cbind(x$value,y$value) class(x$value) <- clValue ## 'clValue' '"ursaNumeric"' } } if ((!isDiskX)&&(!isDiskY)) { x$dim[2] <- x$con$bands <- ncol(x$value) x$con$indexZ <- seq(x$con$bands) } if (!isDiskX) return(x); stop("TODO (low-level image manipulation)") .write.hdr(x) for (i in seq(along=args)) { if (i==1L) next y <- args[[i]] } x }
/scratch/gouwar.j/cran-all/cranData/ursa/R/classRaster_c.R
'close_envi' <- function(...) close(...) 'close.ursaRaster' <- function(...) { args <- list(...) for (i in seq(along=args)) { con <- args[[i]]$con # print(class(con)) if (!.is.con(con)) next if (inherits(con$handle,"connection")) { if ((F)&&(con$compress %in% c(0L,3L))&&(con$connection=="file")) { str(args[[i]]) str(con) } if (any(con$fname %in% showConnections()[,"description"])) close(con$handle) con$handle <- NA if ((con$driver=="EGDAL")&&(length(con$fname)==2)) { with(con,.envi2gdal(src=fname[2],dst=fname[1],datatype=datatype,bands=bands)) envi_remove(con$fname[2]) con$compress <- 0L } if (con$compress==-1L) file.remove(con$fname) else if (con$compress==-2L) { fname <- .gsub("\\.unpacked(.*)~$",".envi",con$fname) file.rename(con$fname,fname) if (file.exists(ftmp <- paste0(fname,".gz"))) file.remove(ftmp) if (file.exists(ftmp <- paste0(.gsub("\\.bin","",fname),".gz"))) file.remove(ftmp) if (file.exists(ftmp <- paste0(.gsub("\\.envi","",fname),".gz"))) file.remove(ftmp) system(paste("gzip","-f -Sgz",dQuote(fname))) } else if (con$compress==1L) { # .elapsedTime("CLOSE 1") if (file.exists(ftmp <- paste0(con$fname,".gz"))) file.remove(ftmp) if (nchar(Sys.which("gzip"))) { for (i in seq(10)) { break s <- file.size(con$fname) print(c(i=i,s=s)) if (s) break Sys.sleep(7) } a <- system(paste("gzip","-f -Sgz",dQuote(con$fname))) ##keep # str(a) } # .elapsedTime("PASSED") # src <- paste0(con$fname,"gz") # dst <- file.path(dirname(src),.gsub("\\.bin",".gz",basename(con$fname))) # file.rename(src,dst) } else if (con$compress==3L) { ## compress==0 and at least one 'replace' if (dirname(con$fname)==.ursaCacheDir()) { was <- .ursaCacheRead() if (!is.null(was)) { dst <- was$src[match(basename(con$fname),was$dst)] if (file.exists(dst)) { if ((.lgrep("(envi|bin|\\.)gz$",dst))&& (nchar(Sys.which("gzip")))) { system2("gzip",c("-f -9 -c -n",.dQuote(con$fname)) ,stdout=dst,stderr=FALSE) } else if ((.lgrep("\\.bz2$",dst))&& (nchar(Sys.which("bzip2")))) { system2("bzip2",c("-f -9 -c -n",.dQuote(con$fname)) ,stdout=dst,stderr=FALSE) } } } } # print(.ursaCasheLoc()) # a <- .ursaCacheRead() # ind <- match(con$fname,) # str(a) } } else if (inherits(con$handle,"GDALTransientDataset")) { bname <- args[[i]]$name .rgdal_close_Transient(con,bname) } else if (inherits(con$handle,"GDALReadOnlyDataset")) { # print(class(con$handle)) .rgdal_close_ReadOnly(con) con$handle <- NA } } invisible(NULL) } '.reopen' <- function(con) ## not called everywhere { close(con$handle) open(con$handle) if (con$offset) { if (con$seek) seek(con$handle,where=con$offset,origin="start") else readBin(con$handle,raw(),n=con$offset) } }
/scratch/gouwar.j/cran-all/cranData/ursa/R/classRaster_close.R
'diff.ursaRaster' <- function(x,lag=1,differences=1,...) { as.ursa(t(diff(t(x$value),lag=lag,differences=differences,...)) ,nband=nband(x)-1L) } 'duplicated.ursaRaster' <- function(x,incomparables=FALSE,MARGIN=2 ,fromLast=FALSE,...) { duplicated(unclass(x$value),incomparables=incomparables,MARGIN=2 ,fromLast=fromLast,...) }
/scratch/gouwar.j/cran-all/cranData/ursa/R/classRaster_commonGeneric.R
'dim.ursaRaster' <- function(x) { res <- as.array(x,dim=TRUE) names(res) <- c("samples","lines","bands") res[c(2,1,3)] } 'dim<-.ursaRaster' <- function(x,value) x
/scratch/gouwar.j/cran-all/cranData/ursa/R/classRaster_dim.R
'head.ursaRaster' <- function(x,n=3L,...) { if (!is.na(x$con$posZ[1L])) k <- length(x$con$posZ) else k <- x$dim[2] if (FALSE) { m <- if (n>k) k else n if (m==0) m <- 1 x[1:m] } x[head(seq_len(k),n)] } 'tail.ursaRaster' <- function(x,n=3L,...) { if (!is.na(x$con$posZ[1L])) k <- length(x$con$posZ) else k <- x$dim[2] if (FALSE) { m <- if (n>k) k else n if (m==0) m <- 1 # str(x) # print(k-(m:1)+1) x[k-(m:1)+1] } x[tail(seq_len(k),n)] } 'series' <- function(x,n=3L,s=170,...) { if (!is.ursa(x)) { if (is.null(dim(x))) { if (is.list(x)) { ind <- seq_along(x) ind <- unique(c(head(ind,n),tail(ind,n))) return(x[ind]) # return(lapply(x[ind],series,n)) ## RECURSIVE } objAttr <- attributes(x) if ((FALSE)&&(is.null(objAttr))) { dim(x) <- c(length(x),1) rownames(x) <- seq(nrow(x)) colnames(x) <- "<vector>" ind <- seq(dim(x)[1]) ind <- sort(unique(c(head(ind,n),tail(ind,n)))) return(x[ind,,drop=FALSE]) } ret <- c(head(x,n),tail(x,n)) if (length(ret)>length(x)) return(x) if (length(grep("names",names(objAttr)))) { objAttr$names <- c(head(objAttr$names,n),tail(objAttr$names,n)) } attributes(ret) <- objAttr return(ret) } ind <- seq(dim(x)[1]) ind <- sort(unique(c(head(ind,n),tail(ind,n)))) return(x[ind,,drop=FALSE]) } s2 <- with(ursa_grid(x),columns*rows*4) m2 <- floor(s*1024*1024/2/s2) if (m2<n) n <- m2 if (!is.na(x$con$posZ[1L])) k <- length(x$con$posZ) else k <- x$dim[2] m <- if (n>k) k else n if (m==0) m <- 1 m <- sort(unique(c(1L:m,k-(m:1L)+1L))) x[m] }
/scratch/gouwar.j/cran-all/cranData/ursa/R/classRaster_head.R
'hist.ursaRaster' <- function(x,...) { v <- ursa_value(x) class(v) <- paste0(".",class(v)) hist(v,...) } 'histogram' <- function(...) .syn('ursa_hist',0,...) 'ursa_hist' <- function(obj,width=800,height=600,...) { rel <- as.list(match.call()) ## try mget(names(match.call())[-1]) rel <- .evaluate(rel,c("colorize","ursa_hist")[1]) isFactor <- inherits(obj,c("character","factor","Date")) if (F) { if (!is.ursa(obj)) { if ((is.character(obj))&&(!is.matrix(obj))&&(length(obj)==1)) obj <- if (envi_exists(obj)) read_envi(obj,...) else read_gdal(obj,...) if (inherits(obj,c("character","factor","Date"))) { objF <- factor(obj) category <- levels(objF) obj <- as.integer(objF) isFactor <- TRUE if (F & .isPackageInUse()) stop("histogram of categories is not implemented yet") } if ((is.numeric(obj))&&(is.null(dim(obj)))) { g1 <- getOption("ursaSessionGrid") dim(obj) <- c(length(obj),1) } if(!.try(obj <- as.ursa(obj))) return(NULL) # obj <- as.ursa(obj) } if (isFactor) { obj <- obj-1L rel[["name"]] <- category } } rel[["obj"]] <- obj # eval(rel[["obj"]]) failed for 'by <- sample(letters,100,replace=T);ursa_hist(by)' if (length(ind <- (.grep("verbose",names(rel))))) verbose <- eval(rel[[ind]]) else verbose <- FALSE # if (!.lgrep("tail",names(rel))) # rel$tail <- 0.001 # p <- colorize(obj) p <- do.call("colorize",rel[-1],quote=TRUE) # print(ursa(p,"table")) ct <- p$colortable if (FALSE) { str(rel) str(obj) str(p) return(NULL) } if (is.ursa(obj)) ta <- as.table(p) else { ta <- ursa(p,"table") } manual <- which(unname(sapply(names(rel[-1]),function(aname) { !inherits(try(match.arg(aname,"value"),silent=TRUE),"try-error") }))) if (length(manual)) va <- rel[-1][[manual]] else va <- .deintervale(ct) # ind <- match(names(ta),seq_along(va)-1L) # if (any(is.na(ind))) # ct <- rep(NA_character_,) if (is.character(va)) va <- seq(length(ta)) # else # va <- as.numeric(.deintervale(ct)) d <- mean(diff(va)) ##~ if (length(ta)==length(va)+1) { ##~ breaks <- c(min(va)-d,va,max(va)+d) ##~ } ##~ else { ##~ breaks <- c(va-d/2,max(va)+d/2) ##~ } ##~ if (TRUE) ##~ breaks <- c(0,seq(length(ct))) if (!isFactor) { adjy <- va # as.numeric(names(ta)) dify <- diff(adjy) toDensity <- .is.eq(dify) & length(dify)>32 if (toDensity) { rngy <- range(adjy)+c(-1,1)*mean(dify)/2 breaks <- seq(rngy[1],rngy[2],by=mean(dify)) # breaks <- c(0,seq(length(ta))) } else breaks <- c(0,seq(length(ta))) } else { toDensity <- TRUE breaks <- c(0,seq(length(ta))) } mids <- breaks[-1]-d/2 counts <- as.integer(ta) g0 <- session_grid() g1 <- .grid.skeleton() g1$minx <- min(breaks) g1$maxx <- max(breaks) g1$miny <- 0 g1$maxy <- 1 g1$columns <- width g1$rows <- height g1$resx <- with(g1,(maxx-minx)/columns) g1$resy <- with(g1,(maxy-miny)/rows) session_grid(g1) maxy <- 0.95 histValue <- list(breaks=breaks,counts=as.numeric(counts) ,intensities=as.numeric(counts/max(counts)) ,density=maxy*as.numeric(counts/max(counts)) ,mids=mids ,zname="manual histogram" ,equidist=TRUE) class(histValue) <- "histogram" if (patchRemoveZero <- TRUE) { cnt <- histValue$counts ind <- which(cnt>0) d <- diff(ind) ud <- unique(d)/min(d) if (min(ud)>1) { if (all(ud %% min(ud) == 0)) { str(histValue,digits=12) print(min(d)) ind <- seq(min(ind),max(ind),by=min(d)) histValue$counts <- histValue$counts[ind] histValue$intensities <- histValue$intensities[ind] histValue$density <- histValue$density[ind] histValue$mids <- histValue$mids[ind] m <- diff(histValue$mids) histValue$breaks <- with(histValue,c(mids[1]-0.5,mids+0.5)) str(histValue,digits=12) } } } if (verbose) str(histValue,digits=12) options(ursaPngAuto=TRUE) compose_open(legend=list("bottom","left"),...) panel_new(asp=NA,col="white") panel_lines(histValue,col="grey80",lwd=5 ,main=NULL,axes=FALSE,freq=FALSE) # ,xlab=NULL isCT <- .is.colortable(obj) if (isCT) { ct <- obj$colortable val <- .deintervale(ct) isChar <- is.character(val) } if (toDensity) { ## carefully if (!((isCT)&&(!isChar)&&(sd(diff(ct))>0.1))) { if (isCT) z <- try(density(na.omit(reclass(obj)$value),n=2^11,...)) else { if (FALSE) { arglist1 <- as.list(args(density.default)) str(arglist1) arglist2 <- list(...) str(arglist2) q() } opW <- options(warn=-10) if (is.ursa(obj)) z <- try(density(na.omit(c(obj$value)),n=2^11,...)) else if (isFactor) z <- try(density(p$index,n=2^11,...)) else { z <- try(density(va[p$index],n=2^11,...)) } options(opW) } if (!inherits(z,"try-error")) { z$x <- c(min(z$x),z$x,max(z$x)) z$y <- c(-1,z$y,-1) z$y <- maxy*z$y*max(histValue$density)/max(z$y) panel_polygon(z,lwd=3,lty=5,border="grey20") #border=tail(myBrewer("Spectral"),1) } else cat("density was not defined\n") } } arglist <- list(...) ind <- .grep("^las$",names(arglist)) if (!length(ind)) { arglist$las <- if (isCT) 3L else 1L } # str(c(list(p),arglist)) # compose_legend(p,...) xlab <- .getPrm(arglist,name="(^xlab.*|lab.*x$)",default="") ylab <- .getPrm(arglist,name="(^ylab.*|lab.*y$)",default="") if (!nchar(ylab)) { ct <- ursa_colortable(p) # do.call("legend_colorbar",list(ct,units=xlab,las=2)) do.call("legend_colorbar",c(list(ct,units=xlab),arglist)) do.call("legend_mtext",list(ylab)) # leg <- c(list(p),arglist) # do.call("compose_legend",leg) } else { bg <- sum(c(col2rgb(getOption("ursaPngBackground")))*c(0.30,0.59,0.11)) tcol <- ifelse(bg<128,"#FFFFFF","#000000") scol <- paste0(tcol,"7F") las <- 1 adj <- 1 cex <- .getPrm(arglist,name="cex",default=1) if (getOption("ursaPngDevice") %in% c("windows")) toE <- TRUE else { opWE <- options(warn=2) toE1 <- .try(abbreviate(xlab,minlength=2,strict=TRUE),silent=TRUE) toE2 <- .try(abbreviate(ylab,minlength=2,strict=TRUE),silent=TRUE) if (!toE1) message(paste("Note (xlab): unable to make bold caption for",.dQuote(xlab))) if (!toE2) message(paste("Note (ylab): unable to make bold caption for",.dQuote(ylab))) toE <- toE1 & toE2 options(opWE) } if (toE) { xlab <- as.expression(substitute(bold(u),list(u=xlab))) ylab <- as.expression(substitute(bold(u),list(u=ylab))) } family <- getOption("ursaPngFamily") if (nchar(xlab)) { side <- 1 y <- .deintervale(p) mwidth <- max(par()$fin) labels <- 21 repeat({ label <- pretty(y,n=labels) labelW <- label width <- max(strwidth(paste0("Wwwwwii",labelW) ,units="inches",cex=cex,family=family)) if (width*length(label)<mwidth) break labels <- labels-1 }) label <- with(session_grid(),label[label>=minx & label<=maxx]) axis(side=side,col=NA,col.ticks=scol,at=label,tcl=-0.3 ,labels=NA,lty=1,lwd=0.5) mtext(side=side,text=format(label),at=label,las=las ,line=0.3,padj=0.5,adj=0.5 ,cex=cex,col=tcol) mtext(xlab,side=side,padj=1,adj=0.5,las=1,col=tcol,cex=cex ,line=1.2) # da <- .prettyLabel(.deintervale(p),ncol=10) # print(da) } if (nchar(ylab)) { side <- 2 nlab <- c(11,10,12,9,13,8,14,7,15,6,16,5,4,3,2,1) print(table(counts)) for (n in nlab[order(abs(nlab-11))]) { da <- .prettyLabel(counts,ncol=n) if (all(abs(da$at-round(da$at))<1e-11)) break } da$at <- maxy*da$at/max(da$at) width <- max(strwidth(paste0("Ww",da$lab) ,units="inches",cex=cex,family=family)) height <- 1.5*strheight("Mg",units="inches",cex=cex,family=family) axis(side=side,at=da$at,labels=NA,col=NA,col.ticks=scol,tcl=-0.2 ,lty=1,lwd=0.5) # mtext(side=2,at=at,text=lab,padj=0.4,adj=1,line=0.6,cex=2,col=tcol) mtext(text=da$lab,at=da$at,las=las,line=0.5 ,side=side,padj=ifelse(las %in% c(0,3),0.2,0.4) ,adj=ifelse(las %in% c(0,3),0.5,adj),cex=cex,col=tcol) mtext(ylab,side=side,padj=0,adj=0.5,las=3,col=tcol,cex=cex ,line=ifelse(las %in% c(1,2),0.1+width/height,height+1.5)) } } session_grid(g0) compose_close(...) } '.cmd.hist' <- function() { do.call("histogram",.args2list()) }
/scratch/gouwar.j/cran-all/cranData/ursa/R/classRaster_hist.R
'is.na.ursaRaster' <- function(x) { if (is.na(x$con$posZ[1])) val <- rep(NA,prod(x$dim)) else val <- rep(NA,x$dim[1]*length(x$con$posZ)) val[which(is.na(c(x$value)))] <- 1L x$value[] <- val if (!is.na(ignorevalue(x))) ignorevalue(x) <- 127L rm(val) .gc() x } 'is.infinite.ursaRaster' <- function(x) { if (is.na(x$con$posZ[1])) val <- rep(NA,prod(x$dim)) else val <- rep(NA,x$dim[1]*length(x$con$posZ)) val[which(is.infinite(c(x$value)))] <- 1L x$value[] <- val if (!is.na(ignorevalue(x))) ignorevalue(x) <- 127L rm(val) .gc() x } 'is.nan.ursaRaster' <- function(x) { if (is.na(x$con$posZ[1])) val <- rep(NA,prod(x$dim)) else val <- rep(NA,x$dim[1]*length(x$con$posZ)) val[which(is.nan(c(x$value)))] <- 1L x$value[] <- val if (!is.na(ignorevalue(x))) ignorevalue(x) <- 127L rm(val) .gc() x } 'is.na<-.ursaRaster' <- function(x,value) { x$value[is.na(x$value)] <- value x }
/scratch/gouwar.j/cran-all/cranData/ursa/R/classRaster_is.na.R
'length.ursaRaster' <- function(x) .syn('nband',0,x) #'band_length' <- function(...) .syn('nband',0,...) 'nband' <- function(x) { if (is.null(x)) return(0L) if (!is.ursa(x)) return(NULL) z <- x$con$posZ if (!length(z)) ret <- 0L else if (all(is.na(z))) ret <- x$dim[2] else ret <- length(z) ret }
/scratch/gouwar.j/cran-all/cranData/ursa/R/classRaster_length.R
'na.omit.ursaRaster' <- function(object,...) object[!band_blank(object)]
/scratch/gouwar.j/cran-all/cranData/ursa/R/classRaster_na.omit.R
'names.ursaRaster' <- function(x) .syn('bandname',0,x) 'names<-.ursaRaster' <- function(x,value) .syn('bandname<-',0,x,value) #'band_names' <- function(x) .syn('bandname',0,x) #'band_names<-' <- function(x,value) .syn('bandname<-',0,x,value) 'bandname' <- function(x) { if (is.ursa(x)) { z <- x$con$posZ if (all(is.na(z))) return(x$name) return(x$name[z]) } if ((is.character(x))&&(envi_exists(x))) { envi <- open_envi(x,decompress=FALSE) res <- envi$name if (!is.na(envi$con$posZ)) res <- res[envi$con$posZ] close(envi) return(res) } NULL } 'bandname<-' <- function(x,value) { if (!is.ursa(x)) return(NULL) if (is.null(value)) value <- character() z <- x$con$posZ if (all(is.na(z))) { # n1 <- length(x$name) n2 <- x$dim[3] x$name <- rep(value,length=n2) } else x$name[z] <- rep(value,length=length(z)) x }
/scratch/gouwar.j/cran-all/cranData/ursa/R/classRaster_names.R
## graphics::image ## graphics::filled.contour ## fields::image.plot ## lattice::levelplot 'plot.ursaRaster' <- function(x,...) { ct <- ursa_colortable(x) if (!.is.colortable(ct)) return(filled.contour(as.matrix(x,coords=TRUE),...)) a1 <- as.numeric(.deintervale(ct)) da <- max(diff(a1)) if (length(ct)==length(a1)) { ## categoral a2 <- a1[-1]-diff(a1)/2 lev <- c(min(a2)-da,a2,max(a2)+da) } else { ## interval lev <- c(min(a1)-da,a1,max(a1)+da) } filled.contour(as.matrix(reclass(x),coords=TRUE),col=ct ,zlim=range(seq(length(ct))-1),levels=lev,...) } 'image.ursaRaster' <- function(x,...) { ct <- ursa_colortable(x) if (!.is.colortable(ct)) return(image(as.matrix(x,coords=TRUE),...)) image(as.matrix(x,coords=TRUE),col=ct,zlim=range(seq(length(ct))-1),...) } '.plot.ursaRaster.example' <- function() { a <- colorize(pixelsize(),byvalue=10,interval=TRUE) plot(a,asp=TRUE) }
/scratch/gouwar.j/cran-all/cranData/ursa/R/classRaster_plot.R
'.rep.ursaRaster.hide' <- function(x,...) { args <- list(...) if (is.null(names(args))) n <- args[[1]] else n <- args[[match("times",names(args))]] if ((!is.numeric(n))||(n<0)) { op <- options(warn=0) warning("incorrect parameter for 'rep()' function. Return arg#1") options(op) return(x) } res <- ursa_new(bandname=rep(bandname(x),n),nodata=ignorevalue(x)) ind <- match(bandname(res),bandname(x)) for (i in seq(res)) res[i] <- x[ind[i]] res } 'rep.ursaRaster' <- function(x,...) { arglist <- list(...) # a <- c(list(bandname(x)),arglist) # str(a) res <- ursa_new(bandname=do.call("rep",c(list(bandname(x)),arglist)) ,nodata=ignorevalue(x)) ind <- match(bandname(res),bandname(x)) for (i in seq(res)) res[i] <- x[ind[i]] class(res$value) <- class(x$value) ursa_colortable(res) <- ursa_colortable(x) res }
/scratch/gouwar.j/cran-all/cranData/ursa/R/classRaster_rep.R
'.seq.ursaRaster' <- function(obj,axis=c("z","x","y","c","r","lines","samples")) { fun <- match.arg(axis) NULL } '.seq.ursaGrid' <- function(obj,axis=c("z","x","y","c","r")) { fun <- match.arg(axis) NULL } 'seq.ursaRaster' <- function(...) { arglist <- list(...) obj <- arglist[[1]] fun <- .getPrm(arglist[-1],valid=c("z","x","y","c","r","lines","samples")) if (fun=="z") return(seq(nband(obj))) g <- ursa_grid(obj) if (fun=="x") { # return(with(g,seq(minx,maxx,by=resx)[-1]+resx/2)) return(with(g,seq(minx,maxx,len=columns+1L)[-1]-resx/2)) } if (fun=="y") { # return(with(g,seq(miny,maxy,by=resy)[-1]+resy/2)) return(with(g,seq(miny,maxy,len=rows+1L)[-1]-resy/2)) } if (fun %in% c("c","samples")) { # return(with(g,seq_along(seq(minx,maxx,by=resx)[-1]+resx/2))) return(with(g,seq_along(seq(minx,maxx,len=columns+1L)[-1]-resx/2))) } if (fun %in% c("r","lines")) { # return(with(g,seq_along(seq(miny,maxy,by=resy)[-1]+resy/2))) return(with(g,seq_along(seq(miny,maxy,len=rows+1L)[-1]-resy/2))) } } 'seq.ursaGrid' <- function(...) { arglist <- list(...) obj <- arglist[[1]] fun <- .getPrm(arglist[-1],valid=c("z","x","y","c","r","lines","samples")) if (fun=="z") return(1L) if (fun=="x") { # return(with(obj,seq(minx,maxx,by=resx)[-1]+resx/2)) return(with(obj,seq(minx,maxx,len=columns+1L)[-1]-resx/2)) } if (fun=="y") { # return(with(obj,seq(miny,maxy,by=resy)[-1]+resy/2)) return(with(obj,seq(miny,maxy,len=rows+1L)[-1]-resy/2)) } if (fun %in% c("c","samples")) { # return(with(g,seq_along(seq(minx,maxx,by=resx)[-1]+resx/2))) return(with(obj,seq_along(seq(minx,maxx,len=columns+1L)[-1]-resx/2))) } if (fun %in% c("r","lines")) { # return(with(g,seq_along(seq(miny,maxy,by=resy)[-1]+resy/2))) return(with(obj,seq_along(seq(miny,maxy,len=rows+1L)[-1]-resy/2))) } } 'ursa_seqx' <- function(obj) { if (missing(obj)) obj <- session_grid() if (is.ursa(obj)) obj <- ursa_grid(obj) if (!.is.grid(obj)) return(NULL) # with(obj,seq(minx,maxx,by=resx)[-1]+resx/2) with(obj,seq(minx,maxx,len=columns+1L)[-1]-resx/2) } 'ursa_seqy' <- function(obj) { if (missing(obj)) obj <- session_grid() if (is.ursa(obj)) obj <- ursa_grid(obj) if (!.is.grid(obj)) return(NULL) # with(obj,seq(miny,maxy,by=resy)[-1]+resy/2) with(obj,seq(miny,maxy,len=rows+1L)[-1]-resy/2) } 'ursa_seqc' <- function(obj) { if (missing(obj)) obj <- session_grid() if (is.ursa(obj)) obj <- ursa_grid(obj) if (!.is.grid(obj)) return(NULL) # with(obj,seq_along(seq(minx,maxx,by=resx)[-1]+resx/2)) with(obj,seq_along(seq(minx,maxx,len=columns+1L)[-1]-resx/2)) } 'ursa_seqr' <- function(obj) { if (missing(obj)) obj <- session_grid() if (is.ursa(obj)) obj <- ursa_grid(obj) if (!.is.grid(obj)) return(NULL) # with(obj,seq_along(seq(miny,maxy,by=resy)[-1]+resy/2)) with(obj,seq_along(seq(miny,maxy,len=rows+1L)[-1]-resy/2)) }
/scratch/gouwar.j/cran-all/cranData/ursa/R/classRaster_seq.R
'sort.ursaRaster' <- function(x,decreasing=FALSE,...) { x[sort(names(x),decreasing=decreasing,...)] }
/scratch/gouwar.j/cran-all/cranData/ursa/R/classRaster_sort.R