content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
#' Time zone
#'
#' Change the time zone, and restore it afterwards.
#'
#' `with_timezone()` runs the code with the specified time zone and
#' resets it afterwards.
#'
#' `local_timezone()` changes the time zone for the caller
#' execution environment.
#'
#' @template with
#' @param tz `[character(1)]` a valid time zone specification, note that
#' time zone names might be platform dependent.
#'
#' @seealso [Sys.timezone()].
#' @export
#' @examples
#' Sys.time()
#' with_timezone("Europe/Paris", print(Sys.time()))
#' with_timezone("America/Los_Angeles", print(Sys.time()))
#'
with_timezone <- function(tz, code) {
reset_timezone()
with_envvar(c(TZ = tz), code)
}
#' @rdname with_timezone
#' @param .local_envir The environment to apply the change to.
#' @export
#' @examples
#' fun1 <- function() {
#' local_timezone("CET")
#' print(Sys.time())
#' }
#'
#' fun2 <- function() {
#' local_timezone("America/Los_Angeles")
#' print(Sys.time())
#' }
#' Sys.time()
#' fun1()
#' fun2()
#' Sys.time()
local_timezone <- function(tz, .local_envir = parent.frame()) {
reset_timezone(envir = .local_envir)
local_envvar(c(TZ = tz), .local_envir = .local_envir)
}
reset_timezone <- function(envir = parent.frame()) {
base_env <- baseenv()
old <- get0(".sys.timezone", base_env, mode = "character",
inherits = FALSE, ifnotfound = NA_character_)
is_locked <- bindingIsLocked(".sys.timezone", env = base_env)
if (is_locked) {
base_env$unlockBinding(".sys.timezone", env = base_env)
}
defer({
assign(".sys.timezone", old, envir = base_env)
if (is_locked) {
lockBinding(".sys.timezone", env = base_env)
}
}, envir = envir)
assign(".sys.timezone", NA_character_, envir = base_env)
}
|
/scratch/gouwar.j/cran-all/cranData/withr/R/timezone.R
|
#' Torture Garbage Collector
#'
#' Temporarily turn gctorture2 on.
#'
#' @template with
#' @param new `[integer]`\cr run GC every 'step' allocations.
#' @inheritParams base::gctorture
#' @inheritParams local_
with_gctorture2 <- with_(gctorture2)
formals(with_gctorture2)[[3]] <- quote(new)
local_gctorture2 <- local_(gctorture2)
formals(local_gctorture2)[[2]] <- quote(new)
|
/scratch/gouwar.j/cran-all/cranData/withr/R/torture.R
|
make_call <- function(...) {
as.call(list(...))
}
vlapply <- function(X, FUN, ..., FUN.VALUE = logical(1)) {
vapply(X, FUN, ..., FUN.VALUE = FUN.VALUE)
}
names2 <- function(x) {
nms <- names(x)
if (is.null(nms)) {
rep("", length(x))
} else {
nms[is.na(nms)] <- ""
nms
}
}
#' Shim for tools::makevars_user()
#' @keywords internal
#' @export
makevars_user <- function() {
if (getRversion() >= "3.3") {
return(tools::makevars_user())
}
# Below is tools::makevars_user() from R 3.6.2
m <- character()
if (.Platform$OS.type == "windows") {
if (!is.na(f <- Sys.getenv("R_MAKEVARS_USER", NA_character_))) {
if (file.exists(f))
m <- f
}
else if ((Sys.getenv("R_ARCH") == "/x64") && file.exists(f <- path.expand("~/.R/Makevars.win64")))
m <- f
else if (file.exists(f <- path.expand("~/.R/Makevars.win")))
m <- f
else if (file.exists(f <- path.expand("~/.R/Makevars")))
m <- f
}
else {
if (!is.na(f <- Sys.getenv("R_MAKEVARS_USER", NA_character_))) {
if (file.exists(f))
m <- f
}
else if (file.exists(f <- path.expand(paste0("~/.R/Makevars-",
Sys.getenv("R_PLATFORM")))))
m <- f
else if (file.exists(f <- path.expand("~/.R/Makevars")))
m <- f
}
m
}
as_character <- function(x) {
nms <- names(x)
res <- as.character(x)
names(res) <- nms
res
}
list_combine <- function(rhs, lhs) {
for (nme in names(lhs)) {
rhs[nme] <- lhs[nme]
}
rhs
}
# Helper to implement `options()`-like splicing
auto_splice <- function(x) {
if (length(x) == 1 && is.null(names(x)) && is.list(x[[1]])) {
x[[1]]
} else {
x
}
}
setNames <- function(x = nm, nm) {
names(x) <- nm
x
}
# base implementation of rlang::is_interactive()
is_interactive <- function() {
opt <- getOption("rlang_interactive")
if (!is.null(opt)) {
return(opt)
}
if (knitr_in_progress()) {
return(FALSE)
}
if (identical(Sys.getenv("TESTTHAT"), "true")) {
return(FALSE)
}
interactive()
}
`%||%` <- function(x, y) {
if (is.null(x)) y else x
}
|
/scratch/gouwar.j/cran-all/cranData/withr/R/utils.R
|
#' Execute code in temporarily altered environment
#'
#' All functions prefixed by `with_` work as follows. First, a particular
#' aspect of the global environment is modified (see below for a list).
#' Then, custom code (passed via the `code` argument) is executed.
#' Upon completion or error, the global environment is restored to the previous
#' state. Each `with_` function has a `local_` variant, which instead resets
#' the state when the current evaluation context ends (such as the end of a
#' function).
#'
#' @section Arguments pattern:
#' \tabular{lll}{
#' `new` \tab `[various]` \tab Values for setting \cr
#' `code` \tab `[any]` \tab Code to execute in the temporary environment \cr
#' `...` \tab \tab Further arguments \cr
#' }
#' @section Usage pattern:
#' `with_...(new, code, ...)`
#' @name withr
#' @docType package
#' @section withr functions:
#' \itemize{
#' \item [with_collate()]: collation order
#' \item [with_dir()]: working directory
#' \item [with_envvar()]: environment variables
#' \item [with_libpaths()]: library paths, replacing current libpaths
#' \item [with_locale()]: any locale setting
#' \item [with_makevars()]: Makevars variables
#' \item [with_options()]: options
#' \item [with_par()]: graphics parameters
#' \item [with_path()]: `PATH` environment variable
#' \item [with_sink()]: output redirection
#' }
#' @section Creating new "with" functions:
#' All `with_` functions are created by a helper function,
#' [with_()]. This functions accepts two arguments:
#' a setter function and an optional resetter function. The setter function is
#' expected to change the global state and return an "undo instruction".
#' This undo instruction is then passed to the resetter function, which changes
#' back the global state. In many cases, the setter function can be used
#' naturally as resetter.
#' @examples
#' getwd()
#' with_dir(tempdir(), getwd())
#' getwd()
#'
#' Sys.getenv("WITHR")
#' with_envvar(c("WITHR" = 2), Sys.getenv("WITHR"))
#' Sys.getenv("WITHR")
#'
#' with_envvar(c("A" = 1),
#' with_envvar(c("A" = 2), action = "suffix", Sys.getenv("A"))
#' )
#'
#' # local variants are best used within other functions
#' f <- function(x) {
#' local_envvar(c("WITHR" = 2))
#' Sys.getenv("WITHR")
#' }
#' Sys.getenv("WITHR")
"_PACKAGE"
|
/scratch/gouwar.j/cran-all/cranData/withr/R/with.R
|
#' @include local_.R
NULL
#' Create a new "with" or "local" function
#'
#' These are constructors for `with_...` or `local_...` functions.
#' They are only needed if you want to alter some global state which is not
#' covered by the existing `with_...` functions, see \link{withr}
#' for an overview.
#'
#' The `with_...` functions reset the state immediately after the
#' `code` argument has been evaluated. The `local_...` functions
#' reset their arguments after they go out of scope, usually at the end of the
#' function body.
#'
#' @inheritParams rlang::args_dots_empty
#'
#' @param set `[function(...)]`\cr Function used to set the state.
#' The return value from this function should be the old state, which will
#' then be passed back into the `reset()` function to clean up the state.
#' The function can have arbitrarily many arguments, they will be replicated
#' in the formals of the returned function.
#' @param reset `[function(x)]`\cr Function used to reset the state.
#' The first argument can be named arbitrarily, further arguments with default
#' values, or a "dots" argument, are supported but not used: The function will
#' be called as `reset(old)`.
#' @param get `[function(...)]`\cr Optionally, a getter function. If
#' supplied, the `on.exit()` restoration is set up _before_ calling
#' `set`. This is more robust in edge cases.
#'
#' For technical reasons, this getter function must have the same
#' interface as `set`, which means it is passed the new values as
#' well. These can be safely ignored.
#' @param envir `[environment]`\cr Environment of the returned function.
#' @param new `[logical(1)]`\cr Replace the first argument of the `set` function
#' by `new`? Set to `FALSE` if the `set` function only has optional arguments.
#' @return `[function(new, code, ...)]` A function with at least two arguments,
#' \itemize{
#' \item `new`: New state to use
#' \item `code`: Code to run in that state.
#' }
#' If there are more arguments to the function passed in `set` they are
#' added to the returned function. If `set` does not have arguments,
#' or `new` is `FALSE`, the returned function does not have a `code` argument.
#' @keywords internal
#' @examples
#' with_(setwd)
#'
#' global_stack <- list()
#' set_global_state <- function(state, msg = "Changing global state.") {
#' global_stack <- c(list(state), global_stack)
#' message(msg)
#' state
#' }
#' reset_global_state <- function(state) {
#' old_state <- global_stack[[1]]
#' global_stack <- global_stack[-1]
#' stopifnot(identical(state, old_state))
#' }
#' with_(set_global_state, reset_global_state)
#' @export
with_ <- function(set,
reset = set,
get = NULL,
...,
envir = parent.frame(),
new = TRUE) {
if (!missing(...)) {
stop("`...` must be empty.")
}
fmls <- formals(set)
if (length(fmls) > 0L) {
# Called pass all extra formals on
called_fmls <- setNames(lapply(names(fmls), as.symbol), names(fmls))
# Special case for dots. If `set()` and/or `get()` take dots, it
# is assumed they implement `options()`-like semantic: a list
# passed as first argument is automatically spliced in the dots.
names(called_fmls)[names(called_fmls) == "..."] <- ""
if (new) {
# rename first formal to new
called_fmls[[1]] <- as.symbol("new")
fun_args <- c(alist(new =, code =), fmls[-1L])
} else {
fun_args <- c(alist(code =), fmls)
}
} else {
# no formals -- only have code
called_fmls <- NULL
fun_args <- alist(code =)
}
set_call <- as.call(c(substitute(set), called_fmls))
reset <- if (missing(reset)) substitute(set) else substitute(reset)
if (is.null(get)) {
fun <- eval(bquote(function(args) {
old <- .(set_call)
on.exit(.(reset)(old))
force(code)
}))
} else {
get_call <- as.call(c(substitute(get), called_fmls))
fun <- eval(bquote(function(args) {
old <- .(get_call)
on.exit(.(reset)(old))
.(set_call)
force(code)
}))
}
# substitute does not work on arguments, so we need to fix them manually
formals(fun) <- fun_args
environment(fun) <- envir
fun
}
merge_new <- function(old, new, action, merge_fun = c) {
action <- match.arg(action, c("replace", "prefix", "suffix"))
if (action == "suffix") {
new <- merge_fun(old, new)
} else if (action == "prefix") {
new <- merge_fun(new, old)
}
new
}
is.named <- function(x) {
!is.null(names(x)) && all(names(x) != "")
}
|
/scratch/gouwar.j/cran-all/cranData/withr/R/with_.R
|
wrap <- function(f, pre, post, envir = parent.frame()) {
fmls <- formals(f)
# called pass all extra formals on
called_fmls <- setNames(lapply(names(fmls), as.symbol), names(fmls))
f_call <- as.call(c(substitute(f), called_fmls))
pre <- substitute(pre)
post <- substitute(post)
fun <- eval(bquote(function(args) {
.(pre)
.retval <- .(f_call)
.(post)
}, as.environment(list(f_call = f_call, pre = pre, post = post))))
# substitute does not work on arguments, so we need to fix them manually
formals(fun) <- fmls
environment(fun) <- envir
fun
}
|
/scratch/gouwar.j/cran-all/cranData/withr/R/wrap.R
|
## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
## ----setup--------------------------------------------------------------------
library(withr)
## ----include = FALSE----------------------------------------------------------
op <- options()
## -----------------------------------------------------------------------------
sloppy <- function(x, sig_digits) {
options(digits = sig_digits)
print(x)
}
pi
sloppy(pi, 2)
pi
## ----include = FALSE----------------------------------------------------------
options(op)
## -----------------------------------------------------------------------------
neat <- function(x, sig_digits) {
op <- options(digits = sig_digits)
on.exit(options(op), add = TRUE)
print(x)
}
pi
neat(pi, 2)
pi
## -----------------------------------------------------------------------------
neater <- function(x, sig_digits) {
op <- options(digits = sig_digits)
defer(options(op))
print(x)
}
pi
neater(pi, 2)
pi
## -----------------------------------------------------------------------------
defer_stack <- function() {
cat("put on socks\n")
defer(cat("take off socks\n"))
cat("put on shoes\n")
defer(cat("take off shoes\n"))
}
defer_stack()
## -----------------------------------------------------------------------------
on_exit_last_one_wins <- function() {
cat("put on socks\n")
on.exit(cat("take off socks\n"))
cat("put on shoes\n")
on.exit(cat("take off shoes\n"))
}
on_exit_last_one_wins()
## ----eval = getRversion() >= "3.5.0"------------------------------------------
on_exit_stack <- function() {
cat("put on socks\n")
on.exit(cat("take off socks\n"), add = TRUE, after = FALSE)
cat("put on shoes\n")
on.exit(cat("take off shoes\n"), add = TRUE, after = FALSE)
}
on_exit_stack()
## -----------------------------------------------------------------------------
defer_queue <- function() {
cat("Adam gets in line for ice cream\n")
defer(cat("Adam gets ice cream\n"), priority = "last")
cat("Beth gets in line for ice cream\n")
defer(cat("Beth gets ice cream\n"), priority = "last")
}
defer_queue()
## -----------------------------------------------------------------------------
neater <- function(x, sig_digits) {
op <- options(digits = sig_digits) # record orig. "digits" & change "digits"
defer(options(op)) # schedule restoration of "digits"
print(x)
}
## -----------------------------------------------------------------------------
local_digits <- function(sig_digits, envir = parent.frame()) {
op <- options(digits = sig_digits)
defer(options(op), envir = envir)
}
## -----------------------------------------------------------------------------
neato <- function(x, digits) {
local_digits(digits)
print(x)
}
pi
neato(pi, 2)
neato(pi, 4)
## -----------------------------------------------------------------------------
neatful <- function(x) {
local_digits(1)
print(x)
local_digits(3)
print(x)
local_digits(5)
print(x)
}
neatful(pi)
## -----------------------------------------------------------------------------
neatest <- function(x, sig_digits) {
local_options(list(digits = sig_digits))
print(x)
}
pi
neatest(pi, 2)
neatest(pi, 4)
## ----eval = FALSE-------------------------------------------------------------
# neat_with <- function(x, sig_digits) {
# # imagine lots of code here
# withr::with_options(
# list(digits = sig_digits),
# print(x)
# )
# # ... and a lot more code here
# }
## ----eval = FALSE-------------------------------------------------------------
# neat_local <- function(x, sig_digits) {
# withr::local_options(list(digits = sig_digits))
# print(x)
# # imagine lots of code here
# }
## -----------------------------------------------------------------------------
library(withr)
defer(print("hi"))
pi
# this adds another deferred event, but does not re-message
local_digits(3)
pi
deferred_run()
pi
|
/scratch/gouwar.j/cran-all/cranData/withr/inst/doc/changing-and-restoring-state.R
|
---
title: "Changing and restoring state"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Changing and restoring state}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
```{r setup}
library(withr)
```
<!-- This vignette uses a git-diff-friendly convention of ONE LINE PER SENTENCE. -->
This article explains the type of problem withr solves and shows typical patterns of usage.
It also compares withr's functionality to the `on.exit()` function from base R.
## It's dangerous to change state
Whenever possible, it is desirable to write so-called **pure** functions.
The property we focus on here is that the function should not change the surrounding R landscape, i.e. it should not change things like the search path, global options, or the working directory.
If the behaviour of *other* functions differs before and after running your function, you've modified the landscape.
Changing the landscape is bad because it makes code much harder to understand.
Here's a `sloppy()` function that prints a number with a specific number of significant digits, by adjusting R's global "digits" option.
```{r include = FALSE}
op <- options()
```
```{r}
sloppy <- function(x, sig_digits) {
options(digits = sig_digits)
print(x)
}
pi
sloppy(pi, 2)
pi
```
```{r include = FALSE}
options(op)
```
Notice how `pi` prints differently before and after the call to `sloppy()`?
Calling `sloppy()` has a side effect: it changes the "digits" option globally, not just within its own scope of operations.
This is what we want to avoid.
*Don't worry, we're restoring global state (specifically, the "digits" option) behind the scenes here.*
Sometimes you cannot avoid modifying the state of the world, in which case you just have to make sure that you put things back the way you found them.
This is what the withr package is for.
## The base solution: `on.exit()`
The first function to know about is base R's `on.exit()`.
Inside your function body, every time you do something that should be undone **on exit**, you immediately register the cleanup code with `on.exit(expr, add = TRUE)`[^on-exit-add].
[^on-exit-add]: It's too bad `add = TRUE` isn't the default, because you almost always want this. Without it, each call to `on.exit()` clobbers the effect of previous calls.
`neat()` is an improvement over `sloppy()`, because it uses `on.exit()` to ensure that the "digits" option is restored to its original value.
```{r}
neat <- function(x, sig_digits) {
op <- options(digits = sig_digits)
on.exit(options(op), add = TRUE)
print(x)
}
pi
neat(pi, 2)
pi
```
`on.exit()` also works when you exit the function abnormally, i.e. due to error.
This is why official tools, like `on.exit()`, are a better choice than any do-it-yourself solution to this problem.
`on.exit()` is a very useful function, but it's not very flexible.
The withr package provides an extensible `on.exit()`-inspired toolkit.
## `defer()` is the foundation of withr
`defer()` is the core function of withr and is very much like `on.exit()`, i.e. it schedules the execution of arbitrary code when the current function exits:
```{r}
neater <- function(x, sig_digits) {
op <- options(digits = sig_digits)
defer(options(op))
print(x)
}
pi
neater(pi, 2)
pi
```
`withr::defer()` is basically a drop-in substitute for `on.exit()`, but with three key differences we explore below:
1. Different default behaviour around the effect of a series of two or more
calls
1. Control over the environment the deferred events are associated with
1. Ability to work with the global environment
Here we focus on using withr inside your functions.
See the blog post [Self-cleaning test fixtures](https://www.tidyverse.org/blog/2020/04/self-cleaning-test-fixtures/) or the testthat vignette [Test fixtures](https://testthat.r-lib.org/articles/test-fixtures.html) for how to use withr inside tests.
## Last-in, first-out
If you make more than one call to `defer()`, by default, it **adds** expressions to the **top** of the stack of deferred actions.
```{r}
defer_stack <- function() {
cat("put on socks\n")
defer(cat("take off socks\n"))
cat("put on shoes\n")
defer(cat("take off shoes\n"))
}
defer_stack()
```
In contrast, by default, a subsequent call to `on.exit()` **overwrites** the deferred actions registered in the previous call.
```{r}
on_exit_last_one_wins <- function() {
cat("put on socks\n")
on.exit(cat("take off socks\n"))
cat("put on shoes\n")
on.exit(cat("take off shoes\n"))
}
on_exit_last_one_wins()
```
Oops, we still have our socks on!
The last-in, first-out, stack-like behaviour of `defer()` tends to be what you want in most applications.
To get such behaviour with `on.exit()`, remember to call it with `add = TRUE, after = FALSE`[^on-exit-after].
[^on-exit-after]: Note: the `after` argument of `on.exit()` first appeared in R 3.5.0.
```{r, eval = getRversion() >= "3.5.0"}
on_exit_stack <- function() {
cat("put on socks\n")
on.exit(cat("take off socks\n"), add = TRUE, after = FALSE)
cat("put on shoes\n")
on.exit(cat("take off shoes\n"), add = TRUE, after = FALSE)
}
on_exit_stack()
```
Conversely, if you want `defer()` to have first-in, first-out behaviour, specify `priority = "last"`.
```{r}
defer_queue <- function() {
cat("Adam gets in line for ice cream\n")
defer(cat("Adam gets ice cream\n"), priority = "last")
cat("Beth gets in line for ice cream\n")
defer(cat("Beth gets ice cream\n"), priority = "last")
}
defer_queue()
```
## "Local" functions (and "with" functions)
Both `on.exit()` and `withr::defer()` schedule actions to be executed when a certain environment goes out of scope, most typically the execution environment of a function.
But the `envir` argument of `withr::defer()` lets you specify a *different* environment, which makes it possible to create customised `on.exit()` extensions.
Let's look at the `neater()` function again.
```{r}
neater <- function(x, sig_digits) {
op <- options(digits = sig_digits) # record orig. "digits" & change "digits"
defer(options(op)) # schedule restoration of "digits"
print(x)
}
```
The first two lines are typical `on.exit()` maneuvers where, in some order, you record an original state, arrange for its eventual restoration, and
change it.
In real life, this can be much more involved and you might want to wrap this logic up into a helper function.
You can't wrap `on.exit()` in this way, because there's no way to reach back up into the correct parent frame and schedule cleanup there.
But with `defer()`, we can!
Here is such a custom helper, called `local_digits()`.
```{r}
local_digits <- function(sig_digits, envir = parent.frame()) {
op <- options(digits = sig_digits)
defer(options(op), envir = envir)
}
```
We can use `local_digits()` to keep any manipulation of `digits` local to a function.
```{r}
neato <- function(x, digits) {
local_digits(digits)
print(x)
}
pi
neato(pi, 2)
neato(pi, 4)
```
You can even call `local_digits()` multiple times inside a function.
Each call to `local_digits()` is in effect until the next or until the function exits, which ever comes first.
```{r}
neatful <- function(x) {
local_digits(1)
print(x)
local_digits(3)
print(x)
local_digits(5)
print(x)
}
neatful(pi)
```
Certain state changes, such as modifying global options, come up so often that withr offers pre-made helpers.
These helpers come in two forms: `local_*()` functions, like the one we just made, and `with_*()` functions, which we explain below.
Here are the state change helpers in withr that you are most likely to find useful:
| Do / undo this | withr functions |
|-----------------------------|-------------------------------------|
| Set an R option | `local_options()`,`with_options()` |
| Set an environment variable | `local_envvar()`, `with_envvar()` |
| Change working directory | `local_dir()`, `with_dir()` |
| Set a graphics parameter | `local_par()`, `with_par()` |
We didn't really need to write our own `local_digits()` helper, because the built-in `withr::local_options()` also gets the job done:
```{r}
neatest <- function(x, sig_digits) {
local_options(list(digits = sig_digits))
print(x)
}
pi
neatest(pi, 2)
neatest(pi, 4)
```
The `local_*()` functions target a slightly different use case from the `with_*()` functions, which are inspired by base R's `with()` function:
* `with_*()` functions are best for executing a small snippet of code with a
modified state
```{r eval = FALSE}
neat_with <- function(x, sig_digits) {
# imagine lots of code here
withr::with_options(
list(digits = sig_digits),
print(x)
)
# ... and a lot more code here
}
```
* `local_*()` functions are best for modifying state "from now until the
function exits"
```{r eval = FALSE}
neat_local <- function(x, sig_digits) {
withr::local_options(list(digits = sig_digits))
print(x)
# imagine lots of code here
}
```
It's best to minimize the footprint of your state modifications.
Therefore, use `with_*()` functions where you can.
But when this forces you to put lots of (indented) code inside `with_*()`, e.g. most of your function's body, then it's better to use `local_*()`.
## Deferring events on the global environment
Here is one last difference between `withr::defer()` and `on.exit()`: the ability to defer events on the global environment[^withr-2-2-0].
[^withr-2-2-0]: This feature first appeared in withr v2.2.0.
At first, it sounds pretty weird to propose scheduling deferred actions on the global environment.
It's not ephemeral, the way function execution environments are.
It goes out of scope very rarely, i.e. when you exit R.
Why would you want this?
The answer is: for development purposes.
If you are developing functions or tests that use withr, it's very useful to be able to execute that code interactively, without error, and with the ability to trigger the deferred events.
It's hard to develop with functions that work one way inside a function, but another way in the global environment (or, worse, throw an error).
Here's how `defer()` (and all functions based on it) works in an interactive session.
```{r}
library(withr)
defer(print("hi"))
pi
# this adds another deferred event, but does not re-message
local_digits(3)
pi
deferred_run()
pi
```
When you defer events on the global environment, you get a message that alerts you to the situation.
If you add subsequent events, the message is *not* repeated.
Since the global environment isn't perishable, like a test environment is, you have to call `deferred_run()` explicitly to execute the deferred events. You can also clear them, without running, with `deferred_clear()`.
|
/scratch/gouwar.j/cran-all/cranData/withr/inst/doc/changing-and-restoring-state.Rmd
|
---
title: "Changing and restoring state"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Changing and restoring state}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
```{r setup}
library(withr)
```
<!-- This vignette uses a git-diff-friendly convention of ONE LINE PER SENTENCE. -->
This article explains the type of problem withr solves and shows typical patterns of usage.
It also compares withr's functionality to the `on.exit()` function from base R.
## It's dangerous to change state
Whenever possible, it is desirable to write so-called **pure** functions.
The property we focus on here is that the function should not change the surrounding R landscape, i.e. it should not change things like the search path, global options, or the working directory.
If the behaviour of *other* functions differs before and after running your function, you've modified the landscape.
Changing the landscape is bad because it makes code much harder to understand.
Here's a `sloppy()` function that prints a number with a specific number of significant digits, by adjusting R's global "digits" option.
```{r include = FALSE}
op <- options()
```
```{r}
sloppy <- function(x, sig_digits) {
options(digits = sig_digits)
print(x)
}
pi
sloppy(pi, 2)
pi
```
```{r include = FALSE}
options(op)
```
Notice how `pi` prints differently before and after the call to `sloppy()`?
Calling `sloppy()` has a side effect: it changes the "digits" option globally, not just within its own scope of operations.
This is what we want to avoid.
*Don't worry, we're restoring global state (specifically, the "digits" option) behind the scenes here.*
Sometimes you cannot avoid modifying the state of the world, in which case you just have to make sure that you put things back the way you found them.
This is what the withr package is for.
## The base solution: `on.exit()`
The first function to know about is base R's `on.exit()`.
Inside your function body, every time you do something that should be undone **on exit**, you immediately register the cleanup code with `on.exit(expr, add = TRUE)`[^on-exit-add].
[^on-exit-add]: It's too bad `add = TRUE` isn't the default, because you almost always want this. Without it, each call to `on.exit()` clobbers the effect of previous calls.
`neat()` is an improvement over `sloppy()`, because it uses `on.exit()` to ensure that the "digits" option is restored to its original value.
```{r}
neat <- function(x, sig_digits) {
op <- options(digits = sig_digits)
on.exit(options(op), add = TRUE)
print(x)
}
pi
neat(pi, 2)
pi
```
`on.exit()` also works when you exit the function abnormally, i.e. due to error.
This is why official tools, like `on.exit()`, are a better choice than any do-it-yourself solution to this problem.
`on.exit()` is a very useful function, but it's not very flexible.
The withr package provides an extensible `on.exit()`-inspired toolkit.
## `defer()` is the foundation of withr
`defer()` is the core function of withr and is very much like `on.exit()`, i.e. it schedules the execution of arbitrary code when the current function exits:
```{r}
neater <- function(x, sig_digits) {
op <- options(digits = sig_digits)
defer(options(op))
print(x)
}
pi
neater(pi, 2)
pi
```
`withr::defer()` is basically a drop-in substitute for `on.exit()`, but with three key differences we explore below:
1. Different default behaviour around the effect of a series of two or more
calls
1. Control over the environment the deferred events are associated with
1. Ability to work with the global environment
Here we focus on using withr inside your functions.
See the blog post [Self-cleaning test fixtures](https://www.tidyverse.org/blog/2020/04/self-cleaning-test-fixtures/) or the testthat vignette [Test fixtures](https://testthat.r-lib.org/articles/test-fixtures.html) for how to use withr inside tests.
## Last-in, first-out
If you make more than one call to `defer()`, by default, it **adds** expressions to the **top** of the stack of deferred actions.
```{r}
defer_stack <- function() {
cat("put on socks\n")
defer(cat("take off socks\n"))
cat("put on shoes\n")
defer(cat("take off shoes\n"))
}
defer_stack()
```
In contrast, by default, a subsequent call to `on.exit()` **overwrites** the deferred actions registered in the previous call.
```{r}
on_exit_last_one_wins <- function() {
cat("put on socks\n")
on.exit(cat("take off socks\n"))
cat("put on shoes\n")
on.exit(cat("take off shoes\n"))
}
on_exit_last_one_wins()
```
Oops, we still have our socks on!
The last-in, first-out, stack-like behaviour of `defer()` tends to be what you want in most applications.
To get such behaviour with `on.exit()`, remember to call it with `add = TRUE, after = FALSE`[^on-exit-after].
[^on-exit-after]: Note: the `after` argument of `on.exit()` first appeared in R 3.5.0.
```{r, eval = getRversion() >= "3.5.0"}
on_exit_stack <- function() {
cat("put on socks\n")
on.exit(cat("take off socks\n"), add = TRUE, after = FALSE)
cat("put on shoes\n")
on.exit(cat("take off shoes\n"), add = TRUE, after = FALSE)
}
on_exit_stack()
```
Conversely, if you want `defer()` to have first-in, first-out behaviour, specify `priority = "last"`.
```{r}
defer_queue <- function() {
cat("Adam gets in line for ice cream\n")
defer(cat("Adam gets ice cream\n"), priority = "last")
cat("Beth gets in line for ice cream\n")
defer(cat("Beth gets ice cream\n"), priority = "last")
}
defer_queue()
```
## "Local" functions (and "with" functions)
Both `on.exit()` and `withr::defer()` schedule actions to be executed when a certain environment goes out of scope, most typically the execution environment of a function.
But the `envir` argument of `withr::defer()` lets you specify a *different* environment, which makes it possible to create customised `on.exit()` extensions.
Let's look at the `neater()` function again.
```{r}
neater <- function(x, sig_digits) {
op <- options(digits = sig_digits) # record orig. "digits" & change "digits"
defer(options(op)) # schedule restoration of "digits"
print(x)
}
```
The first two lines are typical `on.exit()` maneuvers where, in some order, you record an original state, arrange for its eventual restoration, and
change it.
In real life, this can be much more involved and you might want to wrap this logic up into a helper function.
You can't wrap `on.exit()` in this way, because there's no way to reach back up into the correct parent frame and schedule cleanup there.
But with `defer()`, we can!
Here is such a custom helper, called `local_digits()`.
```{r}
local_digits <- function(sig_digits, envir = parent.frame()) {
op <- options(digits = sig_digits)
defer(options(op), envir = envir)
}
```
We can use `local_digits()` to keep any manipulation of `digits` local to a function.
```{r}
neato <- function(x, digits) {
local_digits(digits)
print(x)
}
pi
neato(pi, 2)
neato(pi, 4)
```
You can even call `local_digits()` multiple times inside a function.
Each call to `local_digits()` is in effect until the next or until the function exits, which ever comes first.
```{r}
neatful <- function(x) {
local_digits(1)
print(x)
local_digits(3)
print(x)
local_digits(5)
print(x)
}
neatful(pi)
```
Certain state changes, such as modifying global options, come up so often that withr offers pre-made helpers.
These helpers come in two forms: `local_*()` functions, like the one we just made, and `with_*()` functions, which we explain below.
Here are the state change helpers in withr that you are most likely to find useful:
| Do / undo this | withr functions |
|-----------------------------|-------------------------------------|
| Set an R option | `local_options()`,`with_options()` |
| Set an environment variable | `local_envvar()`, `with_envvar()` |
| Change working directory | `local_dir()`, `with_dir()` |
| Set a graphics parameter | `local_par()`, `with_par()` |
We didn't really need to write our own `local_digits()` helper, because the built-in `withr::local_options()` also gets the job done:
```{r}
neatest <- function(x, sig_digits) {
local_options(list(digits = sig_digits))
print(x)
}
pi
neatest(pi, 2)
neatest(pi, 4)
```
The `local_*()` functions target a slightly different use case from the `with_*()` functions, which are inspired by base R's `with()` function:
* `with_*()` functions are best for executing a small snippet of code with a
modified state
```{r eval = FALSE}
neat_with <- function(x, sig_digits) {
# imagine lots of code here
withr::with_options(
list(digits = sig_digits),
print(x)
)
# ... and a lot more code here
}
```
* `local_*()` functions are best for modifying state "from now until the
function exits"
```{r eval = FALSE}
neat_local <- function(x, sig_digits) {
withr::local_options(list(digits = sig_digits))
print(x)
# imagine lots of code here
}
```
It's best to minimize the footprint of your state modifications.
Therefore, use `with_*()` functions where you can.
But when this forces you to put lots of (indented) code inside `with_*()`, e.g. most of your function's body, then it's better to use `local_*()`.
## Deferring events on the global environment
Here is one last difference between `withr::defer()` and `on.exit()`: the ability to defer events on the global environment[^withr-2-2-0].
[^withr-2-2-0]: This feature first appeared in withr v2.2.0.
At first, it sounds pretty weird to propose scheduling deferred actions on the global environment.
It's not ephemeral, the way function execution environments are.
It goes out of scope very rarely, i.e. when you exit R.
Why would you want this?
The answer is: for development purposes.
If you are developing functions or tests that use withr, it's very useful to be able to execute that code interactively, without error, and with the ability to trigger the deferred events.
It's hard to develop with functions that work one way inside a function, but another way in the global environment (or, worse, throw an error).
Here's how `defer()` (and all functions based on it) works in an interactive session.
```{r}
library(withr)
defer(print("hi"))
pi
# this adds another deferred event, but does not re-message
local_digits(3)
pi
deferred_run()
pi
```
When you defer events on the global environment, you get a message that alerts you to the situation.
If you add subsequent events, the message is *not* repeated.
Since the global environment isn't perishable, like a test environment is, you have to call `deferred_run()` explicitly to execute the deferred events. You can also clear them, without running, with `deferred_clear()`.
|
/scratch/gouwar.j/cran-all/cranData/withr/vignettes/changing-and-restoring-state.Rmd
|
#' Affine transformer
#'
#' @param trans_matrix A 3x3 transformation matrix
#' @param x A [wk_trans_affine()]
#' @param dx,dy Coordinate offsets in the x and y direction
#' @param scale_x,scale_y Scale factor to apply in the x and y directions, respectively
#' @param rct_in,rct_out The input and output bounds
#' @param rotation_deg A rotation to apply in degrees counterclockwise.
#' @param src,dst Point vectors of control points used to estimate the affine mapping
#' (using [base::qr.solve()]).
#' @param ... Zero or more transforms in the order they should be applied.
#'
#' @export
#'
wk_trans_affine <- function(trans_matrix) {
new_wk_trans(.Call(wk_c_trans_affine_new, trans_matrix), "wk_trans_affine")
}
#' @export
wk_trans_inverse.wk_trans_affine <- function(trans, ...) {
wk_affine_invert(trans)
}
#' @rdname wk_trans_affine
#' @export
wk_affine_identity <- function() {
wk_affine_translate(0, 0)
}
#' @rdname wk_trans_affine
#' @export
wk_affine_rotate <- function(rotation_deg) {
theta <- -rotation_deg * pi / 180
trans_matrix <- matrix(
c(
cos(theta), +sin(theta), 0,
-sin(theta), cos(theta), 0,
0, 0, 1
),
nrow = 3,
byrow = TRUE
)
wk_trans_affine(trans_matrix)
}
#' @rdname wk_trans_affine
#' @export
wk_affine_scale <- function(scale_x = 1, scale_y = 1) {
wk_trans_affine(matrix(c(scale_x, 0, 0, 0, scale_y, 0, 0, 0, 1), ncol = 3))
}
#' @rdname wk_trans_affine
#' @export
wk_affine_translate <- function(dx = 0, dy = 0) {
wk_trans_affine(matrix(c(1, 0, 0, 0, 1, 0, dx, dy, 1), ncol = 3))
}
#' @rdname wk_trans_affine
#' @export
wk_affine_fit <- function(src, dst) {
src <- as_xy(src)
dst <- as_xy(dst)
n <- length(src)
stopifnot(length(src) == length(dst))
src <- unclass(src)
dst <- unclass(dst)
src_mat <- cbind(src$x, src$y, rep_len(1, n))
dst_mat <- cbind(dst$x, dst$y, rep_len(1, n))
wk_trans_affine(t(qr.solve(src_mat, dst_mat)))
}
#' @rdname wk_trans_affine
#' @export
wk_affine_rescale <- function(rct_in, rct_out) {
# use bbox to sanitize input as rct of length 1
rct_in <- unclass(wk_bbox(rct_in))
rct_out <- unclass(wk_bbox(rct_out))
width_in <- rct_in$xmax - rct_in$xmin
height_in <- rct_in$ymax - rct_in$ymin
width_out <- rct_out$xmax - rct_out$xmin
height_out <- rct_out$ymax - rct_out$ymin
dx <- rct_out$xmin - rct_in$xmin
dy <- rct_out$ymin - rct_in$ymin
wk_affine_compose(
wk_affine_scale(width_out / width_in, height_out / height_in),
wk_affine_translate(dx, dy)
)
}
#' @rdname wk_trans_affine
#' @export
wk_affine_compose <- function(...) {
trans_matrix <- Reduce(
`%*%`,
lapply(rev(list(...)), as.matrix),
init = as.matrix(wk_affine_identity())
)
wk_trans_affine(trans_matrix)
}
#' @rdname wk_trans_affine
#' @export
wk_affine_invert <- function(x) {
wk_trans_affine(solve(as.matrix(x)))
}
#' @export
as.matrix.wk_trans_affine <- function(x, ...) {
.Call(wk_c_trans_affine_as_matrix, x)
}
#' @export
format.wk_trans_affine <- function(x, ...) {
format(as.matrix(x), ...)
}
#' @export
print.wk_trans_affine <- function(x, ...) {
cat("<wk_trans_affine>\n")
print(as.matrix(x), ...)
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/affine.R
|
#' 2D bounding rectangles
#'
#' @inheritParams wk_handle
#'
#' @return A [rct()] of length 1.
#' @export
#'
#' @examples
#' wk_bbox(wkt("LINESTRING (1 2, 3 5)"))
#'
wk_bbox <- function(handleable, ...) {
UseMethod("wk_bbox")
}
#' @rdname wk_bbox
#' @export
wk_envelope <- function(handleable, ...) {
UseMethod("wk_envelope")
}
#' @rdname wk_bbox
#' @export
wk_bbox.default <- function(handleable, ...) {
if (wk_is_geodesic(handleable)) {
stop("Can't compute bbox for geodesic object", call. = FALSE)
}
result <- wk_handle(handleable, wk_bbox_handler(), ...)
wk_crs(result) <- wk_crs(handleable)
result
}
#' @rdname wk_bbox
#' @export
wk_envelope.default <- function(handleable, ...) {
if (wk_is_geodesic(handleable)) {
stop("Can't compute envelope for geodesic object", call. = FALSE)
}
result <- wk_handle(handleable, wk_envelope_handler(), ...)
wk_crs(result) <- wk_crs(handleable)
result
}
#' @rdname wk_bbox
#' @export
wk_envelope.wk_rct <- function(handleable, ...) {
handleable
}
#' @rdname wk_bbox
#' @export
wk_envelope.wk_crc <- function(handleable, ...) {
unclassed <- unclass(handleable)
rct_data <- list(
xmin = unclassed$x - unclassed$r,
ymin = unclassed$y - unclassed$r,
xmax = unclassed$x + unclassed$r,
ymax = unclassed$y + unclassed$r
)
new_wk_rct(rct_data, crs = attr(handleable, "crs", exact = TRUE))
}
#' @rdname wk_bbox
#' @export
wk_envelope.wk_xy <- function(handleable, ...) {
unclassed <- unclass(handleable)
rct_data <- c(unclassed[1:2], unclassed[1:2])
names(rct_data) <- c("xmin", "ymin", "xmax", "ymax")
new_wk_rct(rct_data, crs = attr(handleable, "crs", exact = TRUE))
}
# Note to future self: re-implementing wk_bbox() using range()
# for record-style vectors is not faster than the default method
#' @rdname wk_bbox
#' @export
wk_bbox_handler <- function() {
new_wk_handler(.Call(wk_c_bbox_handler_new), "wk_bbox_handler")
}
#' @rdname wk_bbox
#' @export
wk_envelope_handler <- function() {
new_wk_handler(.Call(wk_c_envelope_handler_new), "wk_envelope_handler")
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/bbox.R
|
#' Chunking strategies
#'
#' It is often impractical, inefficient, or impossible to perform
#' an operation on a vector of geometries with all the geometries loaded
#' into memory at the same time. These functions help generalize the
#' pattern of split-apply-combine to one or more handlers recycled along a
#' common length. These functions are designed for developers rather than users
#' and should be considered experimental.
#'
#' @param reduce For [wk_chunk_strategy_coordinates()] this refers to
#' the function used with [Reduce()] to combine coordinate counts
#' from more than one handleable.
#' @param n_chunks,chunk_size Exactly one of the number of
#' chunks or the chunk size. For [wk_chunk_strategy_feature()]
#' the chunk size refers to the number of features; for
#' [wk_chunk_strategy_coordinates()] this refers to the number
#' of coordinates as calculated from multiple handleables
#' using `reduce`.
#'
#' @return A function that returns a `data.frame` with columns `from` and `to`
#' when called with a `handleable` and the feature count.
#' @export
#'
#' @examples
#' feat <- c(as_wkt(xy(1:4, 1:4)), wkt("LINESTRING (1 1, 2 2)"))
#' wk_chunk_strategy_single()(list(feat), 5)
#' wk_chunk_strategy_feature(chunk_size = 2)(list(feat), 5)
#' wk_chunk_strategy_coordinates(chunk_size = 2)(list(feat), 5)
#'
wk_chunk_strategy_single <- function() {
function(handleables, n_features) {
new_data_frame(list(from = 1, to = n_features))
}
}
#' @rdname wk_chunk_strategy_single
#' @export
wk_chunk_strategy_feature <- function(n_chunks = NULL, chunk_size = NULL) {
force(n_chunks)
force(chunk_size)
function(handleables, n_features) {
chunk_info <- chunk_info(n_features, n_chunks = n_chunks, chunk_size = chunk_size)
from <- (chunk_info$chunk_size * (seq_len(chunk_info$n_chunks) - 1L)) + 1L
to <- chunk_info$chunk_size * seq_len(chunk_info$n_chunks)
to[chunk_info$n_chunks] <- n_features
new_data_frame(list(from = from, to = to))
}
}
#' @rdname wk_chunk_strategy_single
#' @export
wk_chunk_strategy_coordinates <- function(n_chunks = NULL, chunk_size = NULL, reduce = "*") {
force(n_chunks)
force(reduce)
function(handleables, n_features) {
coord_count <- lapply(handleables, function(handleable) {
vm <- wk_vector_meta(handleable)
if (identical(vm$geometry_type, 1L)) {
1L
} else {
wk_count(handleable)$n_coord
}
})
coord_count <- Reduce(reduce, coord_count)
if (identical(coord_count, 1L)) {
return(wk_chunk_strategy_feature(n_chunks, chunk_size)(handleables, n_features))
}
coord_count <- rep_len(coord_count, n_features)
coord_count_total <- sum(coord_count)
chunk_info <- chunk_info(coord_count_total, n_chunks, chunk_size)
from <- rep(NA_integer_, chunk_info$n_chunks)
to <- rep(NA_integer_, chunk_info$n_chunks)
from[1] <- 1L
coord_count_chunk <- (coord_count_total / chunk_info$n_chunks)
coord_count_feat <- cumsum(coord_count)
for (chunk_id in seq_len(chunk_info$n_chunks - 1L)) {
next_coord_gt <- coord_count_feat >= coord_count_chunk
if (!any(next_coord_gt)) {
to[chunk_id] <- n_features
break
}
i <- max(min(which(next_coord_gt)), from[chunk_id] + 1L)
to[chunk_id] <- i
from[chunk_id + 1L] <- i + 1L
coord_count[1:i] <- 0L
coord_count_feat <- cumsum(coord_count)
}
valid <- !is.na(from)
from <- from[valid]
to <- to[valid]
if (is.na(to[length(to)])) {
to[length(to)] <- n_features
}
new_data_frame(list(from = from, to = to))
}
}
chunk_info <- function(n_features, n_chunks = NULL, chunk_size = NULL) {
if (is.null(n_chunks) && is.null(chunk_size)) {
stop("Must specify exactly one of `n_chunks` or `chunk_size`", call. = FALSE)
} else if (is.null(n_chunks)) {
n_chunks <- ((n_features - 1L) %/% chunk_size) + 1L
} else if (is.null(chunk_size)) {
if (n_features == 0) {
n_chunks <- 0L
chunk_size <- 1L
} else {
chunk_size <- ((n_features - 1L) %/% n_chunks) + 1L
}
} else {
stop("Must specify exactly one of `n_chunks` or `chunk_size`", call. = FALSE)
}
list(n_chunks = n_chunks, chunk_size = chunk_size)
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/chunk.R
|
#' Use data.frame with wk
#'
#' @inheritParams wk_handle
#' @inheritParams wk_crs
#' @inheritParams wk_translate
#' @inheritParams wk_identity
#' @inheritParams wk_is_geodesic
#'
#' @export
#'
#' @examples
#' wk_handle(data.frame(a = wkt("POINT (0 1)")), wkb_writer())
#' wk_translate(wkt("POINT (0 1)"), data.frame(col_name = wkb()))
#' wk_translate(data.frame(a = wkt("POINT (0 1)")), data.frame(wkb()))
#'
wk_handle.data.frame <- function(handleable, handler, ...) {
col <- handleable_column_name(handleable)
wk_handle(handleable[[col]], handler, ...)
}
#' @export
wk_writer.data.frame <- function(handleable, ...) {
col <- handleable_column_name(handleable)
wk_writer(handleable[[col]], ...)
}
#' @export
wk_crs.data.frame <- function(x) {
col <- handleable_column_name(x)
wk_crs(x[[col]])
}
#' @export
wk_set_crs.data.frame <- function(x, crs) {
col <- handleable_column_name(x)
x[[col]] <- wk_set_crs(x[[col]], crs)
x
}
#' @export
wk_is_geodesic.data.frame <- function(x) {
col <- handleable_column_name(x)
wk_is_geodesic(x[[col]])
}
#' @export
wk_set_geodesic.data.frame <- function(x, geodesic) {
col <- handleable_column_name(x)
x[[col]] <- wk_set_geodesic(x[[col]], geodesic)
x
}
#' @rdname wk_handle.data.frame
#' @export
wk_restore.data.frame <- function(handleable, result, ...) {
col <- handleable_column_name(handleable)
if(nrow(handleable) == length(result)) {
handleable[[col]] <- result
handleable
} else if (nrow(handleable) == 1) {
handleable <- handleable[rep(1L, length(result)), , drop = FALSE]
handleable[[col]] <- result
handleable
} else {
stop(
sprintf(
"Can't assign result of length %d to data frame with %d rows",
length(result), nrow(handleable)
),
call. = FALSE
)
}
}
#' @rdname wk_handle.data.frame
#' @export
wk_restore.tbl_df <- function(handleable, result, ...) {
tibble::as_tibble(wk_restore.data.frame(handleable, result, ...))
}
#' @rdname wk_handle.data.frame
#' @export
wk_translate.data.frame <- function(handleable, to, ...) {
col <- handleable_column_name(to)
col_value <- wk_translate(handleable, to[[col]], ...)
if (inherits(handleable, "data.frame")) {
handleable_col <- handleable_column_name(handleable)
attributes(handleable) <- list(names = names(handleable))
handleable[handleable_col] <- list(col_value)
new_data_frame(handleable)
} else {
df_raw <- list(col_value)
names(df_raw) <- col
new_data_frame(df_raw)
}
}
#' @rdname wk_handle.data.frame
#' @export
wk_translate.tbl_df <- function(handleable, to, ...) {
tibble::as_tibble(wk_translate.data.frame(handleable, to, ...))
}
#' @rdname wk_handle_slice
#' @export
wk_handle_slice.data.frame <- function(handleable, handler,
from = NULL, to = NULL, ...) {
handleable_col <- handleable_column_name(handleable)
wk_handle_slice(
handleable[[handleable_col]], handler,
from = from,
to = to,
...
)
}
handleable_column_name <- function(df) {
has_method <- vapply(df, is_handleable, FUN.VALUE = logical(1))
if (!any(has_method)) {
stop(
"To be used with wk_handle(), a data.frame must have at least one handleable column.",
call. = FALSE
)
}
names(df)[which(has_method)[1L]]
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/class-data-frame.R
|
#' Count geometry components
#'
#' Counts the number of geometries, rings, and coordinates found within
#' each feature. As opposed to [wk_meta()], this handler will iterate
#' over the entire geometry.
#'
#' @inheritParams wk_handle
#'
#' @return A data.frame with one row for every feature encountered and
#' columns:
#' - `n_geom`: The number of geometries encountered, including the
#' root geometry. Will be zero for a null feature.
#' - `n_ring`: The number of rings encountered. Will be zero for a
#' null feature.
#' - `n_coord`: The number of coordinates encountered. Will be zero
#' for a null feature.
#' @export
#'
#' @examples
#' wk_count(as_wkt("LINESTRING (0 0, 1 1)"))
#' wk_count(as_wkb("LINESTRING (0 0, 1 1)"))
#'
wk_count <- function(handleable, ...) {
UseMethod("wk_count")
}
#' @rdname wk_count
#' @export
wk_count.default <- function(handleable, ...) {
new_data_frame(wk_handle(handleable, wk_count_handler(), ...))
}
#' @rdname wk_count
#' @export
wk_count_handler <- function() {
new_wk_handler(.Call(wk_c_count_handler_new), "wk_count_handler")
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/count.R
|
#' 2D Circle Vectors
#'
#' @param x,y Coordinates of the center
#' @param r Circle radius
#' @param ... Extra arguments passed to `as_crc()`.
#' @inheritParams new_wk_wkb
#'
#' @return A vector along the recycled length of bounds.
#' @export
#'
#' @examples
#' crc(1, 2, 3)
#'
crc <- function(x = double(), y = double(), r = double(), crs = wk_crs_auto()) {
vec <- new_wk_crc(
recycle_common(
x = as.double(x),
y = as.double(y),
r = as.double(r)
),
crs = wk_crs_auto_value(x, crs)
)
validate_wk_crc(vec)
vec
}
#' @rdname crc
#' @export
as_crc <- function(x, ...) {
UseMethod("as_crc")
}
#' @rdname crc
#' @export
as_crc.wk_crc <- function(x, ...) {
x
}
#' @rdname crc
#' @export
as_crc.matrix <- function(x, ..., crs = NULL) {
if (ncol(x) == 3) {
colnames(x) <- c("x", "y", "r")
}
as_crc(as.data.frame(x), ..., crs = crs)
}
#' @rdname crc
#' @export
as_crc.data.frame <- function(x, ..., crs = NULL) {
stopifnot(all(c("x", "y", "r") %in% names(x)))
new_wk_crc(lapply(x[c("x", "y", "r")], as.double), crs = crs)
}
validate_wk_crc <- function(x) {
validate_wk_rcrd(x)
stopifnot(
identical(names(unclass(x)), c("x", "y", "r"))
)
invisible(x)
}
#' S3 details for crc objects
#'
#' @param x A [crc()]
#' @inheritParams new_wk_wkb
#'
#' @export
#'
new_wk_crc <- function(x = list(x = double(), y = double(), r = double()),
crs = NULL) {
structure(x, class = c("wk_crc", "wk_rcrd"), crs = crs)
}
#' @export
format.wk_crc <- function(x, ...) {
x <- unclass(x)
sprintf(
"[%s %s, r = %s]",
format(x$x, ...), format(x$y, ...),
format(x$r, ...)
)
}
#' @export
`[<-.wk_crc` <- function(x, i, value) {
replacement <- as_crc(value)
result <- Map("[<-", unclass(x), i, unclass(replacement))
names(result) <- c("x", "y", "r")
new_wk_crc(result, crs = wk_crs_output(x, replacement))
}
#' Circle accessors
#'
#' @param x A [crc()] vector
#'
#' @return Components of the [crc()] vector
#' @export
#'
#' @examples
#' x <- crc(1, 2, r = 3)
#' crc_x(x)
#' crc_y(x)
#' crc_r(x)
#' crc_center(x)
#'
crc_x <- function(x) {
unclass(as_crc(x))$x
}
#' @rdname crc_x
#' @export
crc_y <- function(x) {
unclass(as_crc(x))$y
}
#' @rdname crc_x
#' @export
crc_center <- function(x) {
x <- as_crc(x)
crs <- wk_crs(x)
x <- unclass(x)
xy(x$x, x$y, crs = crs)
}
#' @rdname crc_x
#' @export
crc_r <- function(x) {
unclass(as_crc(x))$r
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/crc.R
|
#' Common CRS Representations
#'
#' These fixtures are calculated from PROJ version 9.1.0 and the database
#' built from its source. They are used internally to transform and inspect
#' coordinate reference systems.
#'
#' @examples
#' head(wk_proj_crs_view)
#' colnames(wk_proj_crs_json)
#'
"wk_proj_crs_view"
#' @rdname wk_proj_crs_view
"wk_proj_crs_json"
#' Create example geometry objects
#'
#' @param which An example name. Valid example names are
#' - "nc" (data derived from the sf package)
#' - "point", "linestring", "polygon", "multipoint",
#' "multilinestring", "multipolygon", "geometrycollection"
#' - One of the above with the "_z", "_m", or "_zm" suffix.
#' @inheritParams wk_crs
#' @inheritParams wk_is_geodesic
#'
#' @return A [wkt()] with the specified example.
#' @export
#'
#' @examples
#' wk_example("polygon")
#'
wk_example <- function(which = "nc",
crs = NA,
geodesic = FALSE) {
all_examples <- wk::wk_example_wkt
match.arg(which, names(all_examples))
handleable <- all_examples[[which]]
if (!identical(crs, NA)) {
wk::wk_crs(handleable) <- crs
}
wk::wk_is_geodesic(handleable) <- geodesic
handleable
}
#' @rdname wk_example
"wk_example_wkt"
|
/scratch/gouwar.j/cran-all/cranData/wk/R/data.R
|
#' Debug filters and handlers
#'
#' @inheritParams wk_handle
#'
#' @return The result of the `handler`.
#' @export
#'
#' @examples
#' wk_debug(wkt("POINT (1 1)"))
#' wk_handle(wkt("POINT (1 1)"), wk_debug_filter())
#'
wk_debug <- function(handleable, handler = wk_void_handler(), ...) {
wk_handle(handleable, wk_debug_filter(handler))
}
#' @rdname wk_debug
#' @export
wk_debug_filter <- function(handler = wk_void_handler()) {
new_wk_handler(.Call(wk_c_debug_filter_new, handler), "wk_debug_filter")
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/debug.R
|
#' Deprecated functions
#'
#' These functions are deprecated and will be removed in a future version.
#'
#' @param wkb A `list()` of [raw()] vectors, such as that
#' returned by `sf::st_as_binary()`.
#' @param wkt A character vector containing well-known text.
#' @param trim Trim unnecessary zeroes in the output?
#' @param precision The rounding precision to use when writing
#' (number of decimal places).
#' @param endian Force the endian of the resulting WKB.
#' @param ... Used to keep backward compatibility with previous
#' versions of these functions.
#'
#' @export
#' @rdname deprecated
#'
wkb_translate_wkt <- function(wkb, ..., precision = 16, trim = TRUE) {
unclass(wk_handle.wk_wkb(wkb, wkt_writer(precision, trim)))
}
#' @rdname deprecated
#' @export
wkb_translate_wkb <- function(wkb, ..., endian = NA_integer_) {
unclass(wk_handle.wk_wkb(wkb, wkb_writer(endian = endian)))
}
#' @rdname deprecated
#' @export
wkt_translate_wkt <- function(wkt, ..., precision = 16, trim = TRUE) {
unclass(wk_handle.wk_wkt(wkt, wkt_writer(precision, trim)))
}
#' @rdname deprecated
#' @export
wkt_translate_wkb <- function(wkt, ..., endian = NA_integer_) {
unclass(wk_handle.wk_wkt(wkt, wkb_writer(endian = endian)))
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/deprecated.R
|
#' Copy a geometry vector
#'
#' @inheritParams wk_handle
#' @param result The result of a filter operation intended to be a
#' transformation.
#'
#' @return A copy of `handleable`.
#' @export
#'
#' @examples
#' wk_identity(wkt("POINT (1 2)"))
#'
wk_identity <- function(handleable, ...) {
result <- wk_handle(handleable, wk_identity_filter(wk_writer(handleable)), ...)
result <- wk_restore(handleable, result, ...)
result <- wk_set_crs(result, wk_crs(handleable))
wk_set_geodesic(result, wk_is_geodesic(handleable))
}
#' @rdname wk_identity
#' @export
wk_identity_filter <- function(handler) {
new_wk_handler(.Call("wk_c_identity_filter_new", as_wk_handler(handler)), "wk_identity_filter")
}
#' @rdname wk_identity
#' @export
wk_restore <- function(handleable, result, ...) {
UseMethod("wk_restore")
}
#' @rdname wk_identity
#' @export
wk_restore.default <- function(handleable, result, ...) {
result
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/filter.R
|
#' Extract simple geometries
#'
#' @inheritParams wk_handle
#' @param max_depth The maximum (outer) depth to remove.
#' @param add_details Use `TRUE` to add a "wk_details" attribute, which
#' contains columns `feature_id`, `part_id`, and `ring_id`.
#'
#' @return `handleable` transformed such that collections have been
#' expanded and only simple geometries (point, linestring, polygon)
#' remain.
#' @export
#'
#' @examples
#' wk_flatten(wkt("MULTIPOINT (1 1, 2 2, 3 3)"))
#' wk_flatten(
#' wkt("GEOMETRYCOLLECTION (GEOMETRYCOLLECTION (GEOMETRYCOLLECTION (POINT (0 1))))"),
#' max_depth = 2
#' )
#'
wk_flatten <- function(handleable, ..., max_depth = 1) {
if (is.data.frame(handleable)) {
result <- wk_handle(
handleable,
wk_flatten_filter(wk_writer(handleable), max_depth, add_details = TRUE),
...
)
feature_id <- attr(result, "wk_details", exact = TRUE)$feature_id
attr(result, "wk_details") <- NULL
result <- wk_restore(handleable[feature_id, , drop = FALSE], result, ...)
} else {
result <- wk_handle(handleable, wk_flatten_filter(wk_writer(handleable, generic = TRUE), max_depth), ...)
result <- wk_restore(handleable, result, ...)
}
result <- wk_set_crs(result, wk_crs(handleable))
wk_set_geodesic(result, wk_is_geodesic(handleable))
}
#' @rdname wk_flatten
#' @export
wk_flatten_filter <- function(handler, max_depth = 1L, add_details = FALSE) {
new_wk_handler(
.Call(
"wk_c_flatten_filter_new",
as_wk_handler(handler),
as.integer(max_depth)[1],
as.logical(add_details)[1]
),
"wk_flatten_filter"
)
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/flatten.R
|
#' Format well-known geometry for printing
#'
#' Provides an abbreviated version of the well-known text
#' representation of a geometry. This returns a constant
#' number of coordinates for each geometry, so is safe to
#' use for geometry vectors with many (potentially large)
#' features. Parse errors are passed on to the format string
#' and do not cause this handler to error.
#'
#' @inheritParams wk_handle
#' @inheritParams wk_writer
#' @param max_coords The maximum number of coordinates to include
#' in the output.
#'
#' @return A character vector of abbreviated well-known text.
#' @export
#'
#' @examples
#' wk_format(wkt("MULTIPOLYGON (((0 0, 10 0, 0 10, 0 0)))"))
#' wk_format(new_wk_wkt("POINT ENTPY"))
#' wk_handle(
#' wkt("MULTIPOLYGON (((0 0, 10 0, 0 10, 0 0)))"),
#' wkt_format_handler()
#' )
#'
wk_format <- function(handleable, precision = 7, trim = TRUE, max_coords = 6, ...) {
wk_handle(
handleable,
wkt_format_handler(precision = precision, trim = trim, max_coords = max_coords),
...
)
}
#' @rdname wk_format
#' @export
wkt_format_handler <- function(precision = 7, trim = TRUE, max_coords = 6) {
new_wk_handler(
.Call(
wk_c_wkt_formatter,
as.integer(precision)[1],
as.logical(trim)[1],
as.integer(max_coords)[1]
),
"wk_wkt_formatter"
)
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/format.R
|
#' Extract values from a grid
#'
#' Unlike [grd_subset()], which subsets like a matrix, [grd_extract()] returns
#' values.
#'
#' @inheritParams grd_summary
#' @inheritParams grd_subset
#' @inheritParams grd_cell
#' @param i,j Index values as in [grd_subset()] except recycled to a common
#' size.
#'
#' @return A matrix or vector with two fewer dimensions than the input.
#' @export
#'
grd_extract <- function(grid, i = NULL, j = NULL) {
grd_data_extract(grid$data, i, j)
}
#' @rdname grd_extract
#' @export
grd_extract_nearest <- function(grid, point, out_of_bounds = c("censor", "squish")) {
out_of_bounds <- match.arg(out_of_bounds)
s <- grd_summary(grid)
ij <- grd_cell(grid, point)
ij <- ij_handle_out_of_bounds2(ij, list(s$ny, s$nx), out_of_bounds)
grd_data_extract(grid$data, ij)
}
#' @rdname grd_extract
#' @export
grd_data_extract <- function(grid_data, i = NULL, j = NULL) {
ij <- ij_from_args(i, j)
# This doesn't make sense in this context where ij is more like a data.frame
stopifnot(!is.null(ij$i), !is.null(ij$j))
ij <- recycle_common(i = ij$i, j = ij$j)
# Again, the nativeRaster is silently row-major
if (inherits(grid_data, "nativeRaster")) {
flat_index <- (ij$i - 1L) * dim(grid_data)[2] + (ij$j - 1L) + 1L
return(array(grid_data[flat_index]))
}
# Only implemented for the first two dimensions right now
if (length(dim(grid_data)) == 2L ||
prod(dim(grid_data)) == prod(dim(grid_data)[1:2])) {
flat_index <- (ij$j - 1L) * dim(grid_data)[1] + (ij$i - 1L) + 1L
result <- array(grid_data[flat_index])
# Restore missing dimensions
dim(result) <- c(length(flat_index), dim(grid_data)[-c(1L, 2L)])
result
} else {
stop("grd_data_extract() not implemented for non-matrix-like data")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/grd-extract.R
|
#' Handler interface for grid objects
#'
#' @inheritParams wk_handle
#' @param data_order A vector of length 2 describing the order in which
#' values should appear. The default, `c("y", "x")`, will output values
#' in the same order as the default matrix storage in R (column-major).
#' You can prefix a dimension with `-` to reverse the order of a
#' dimension (e.g., `c("-y", "x")`).
#'
#' @return The result of the `handler`.
#' @export
#'
#' @examples
#' wk_handle(grd(nx = 3, ny = 3), wkt_writer())
#' wk_handle(grd(nx = 3, ny = 3, type = "centers"), wkt_writer())
#'
wk_handle.wk_grd_xy <- function(handleable, handler, ..., data_order = c("y", "x")) {
# eventually these will be more efficient and not resolve every cell
wk_handle(as_xy(handleable, data_order = data_order), handler, ...)
}
#' @rdname wk_handle.wk_grd_xy
#' @export
wk_handle.wk_grd_rct <- function(handleable, handler, ..., data_order = c("y", "x")) {
# eventually these will be more efficient and not resolve every cell
wk_handle(as_rct(handleable, data_order = data_order), handler, ...)
}
#' @export
as_xy.wk_grd_xy <- function(x, ..., data_order = c("y", "x")) {
rct <- unclass(x$bbox)
nx <- dim(x$data)[2]
ny <- dim(x$data)[1]
width <- rct$xmax - rct$xmin
height <- rct$ymax - rct$ymin
if (identical(width, -Inf) || identical(height, -Inf)) {
return(xy(crs = wk_crs(x)))
}
if (nx == 1L) {
xs <- rct$xmin
} else {
xs <- seq(rct$xmin, rct$xmax, by = width / (nx - 1))
}
if (ny == 1L) {
ys <- rct$ymin
} else {
ys <- seq(rct$ymax, rct$ymin, by = -height / (ny - 1))
}
# Custom ordering such that coordinates can match up to data
dim_order <- gsub("^[+-]", "", data_order)
if (identical(dim_order, c("y", "x"))) {
if (startsWith(data_order[1], "-")) {
ys <- rev(ys)
}
if (startsWith(data_order[2], "-")) {
xs <- rev(xs)
}
xy(
rep(xs, each = length(ys)),
rep(ys, length(xs)),
crs = wk_crs(x$bbox)
)
} else {
if (startsWith(data_order[2], "-")) {
ys <- rev(ys)
}
if (startsWith(data_order[1], "-")) {
xs <- rev(xs)
}
xy(
rep(xs, length(ys)),
rep(ys, each = length(xs)),
crs = wk_crs(x$bbox)
)
}
}
#' @export
as_rct.wk_grd_rct <- function(x, ..., data_order = c("y", "x")) {
rct <- unclass(x$bbox)
nx <- dim(x$data)[2]
ny <- dim(x$data)[1]
width <- rct$xmax - rct$xmin
height <- rct$ymax - rct$ymin
if (identical(width, -Inf) || identical(height, -Inf)) {
return(rct(crs = wk_crs(x)))
}
# Custom ordering such that coordinates can match up to data
xs <- seq(rct$xmin, rct$xmax, by = width / nx)
ys <- seq(rct$ymax, rct$ymin, by = -height / ny)
dim_order <- gsub("^[+-]", "", data_order)
if (identical(dim_order, c("y", "x"))) {
if (startsWith(data_order[1], "-")) {
ys <- rev(ys)
ymax <- rep(ys[-1], nx)
ymin <- rep(ys[-length(ys)], nx)
} else {
ymin <- rep(ys[-1], nx)
ymax <- rep(ys[-length(ys)], nx)
}
if (startsWith(data_order[2], "-")) {
xs <- rev(xs)
xmax <- rep(xs[-length(xs)], each = ny)
xmin <- rep(xs[-1], each = ny)
} else {
xmin <- rep(xs[-length(xs)], each = ny)
xmax <- rep(xs[-1], each = ny)
}
rct(xmin, ymin, xmax, ymax, crs = wk_crs(x$bbox))
} else {
if (startsWith(data_order[2], "-")) {
ys <- rev(ys)
ymax <- rep(ys[-1], each = nx)
ymin <- rep(ys[-length(ys)], each = nx)
} else {
ymin <- rep(ys[-1], each = nx)
ymax <- rep(ys[-length(ys)], each = nx)
}
if (startsWith(data_order[1], "-")) {
xs <- rev(xs)
xmax <- rep(xs[-length(xs)], ny)
xmin <- rep(xs[-1], ny)
} else {
xmin <- rep(xs[-length(xs)], ny)
xmax <- rep(xs[-1], ny)
}
}
rct(xmin, ymin, xmax, ymax, crs = wk_crs(x$bbox))
}
#' @export
as_xy.wk_grd_rct <- function(x, ...) {
as_xy(as_grd_xy(x))
}
#' @export
as_rct.wk_grd_xy <- function(x, ...) {
as_rct(as_grd_rct(x))
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/grd-handle.R
|
#' Plot grid objects
#'
#' @inheritParams wk_plot
#' @param image A raster or nativeRaster to pass to [graphics::rasterImage()].
#' use `NULL` to do a quick-and-dirty rescale of the data such that the low
#' value is black and the high value is white.
#' @param oversample A scale on the number of pixels on the device to use for
#' sampling estimation of large raster values. Use `Inf` to disable.
#' @param border Color to use for polygon borders. Use `NULL` for the default
#' and `NA` to skip plotting borders.
#' @param interpolate Use `TRUE` to perform interpolation between color values.
#'
#' @return `x`, invisibly.
#' @export
#' @importFrom graphics plot
#'
#' @examples
#' plot(grd_rct(volcano))
#' plot(grd_xy(volcano))
#'
plot.wk_grd_xy <- function(x, ...) {
plot(as_xy(x), ...)
invisible(x)
}
#' @rdname plot.wk_grd_xy
#' @export
plot.wk_grd_rct <- function(x, ...,
image = NULL,
interpolate = FALSE,
oversample = 4,
border = NA,
asp = 1, bbox = NULL, xlab = "", ylab = "",
add = FALSE) {
if (!add) {
bbox <- unclass(bbox)
bbox <- bbox %||% unclass(wk_bbox(x))
xlim <- c(bbox$xmin, bbox$xmax)
ylim <- c(bbox$ymin, bbox$ymax)
graphics::plot(
numeric(0),
numeric(0),
xlim = xlim,
ylim = ylim,
xlab = xlab,
ylab = ylab,
asp = asp
)
}
# empty raster can skip plotting
rct <- unclass(x$bbox)
if (identical(rct$xmax - rct$xmin, -Inf) || identical(rct$ymax - rct$ymin, -Inf)) {
return(invisible(x))
}
# as.raster() takes care of the default details here
# call with native = TRUE, but realize this isn't implemented
# everywhere (so we may get a regular raster back)
if (is.null(image)) {
# calculate an image based on a potential downsampling of the original
usr <- graphics::par("usr")
x_downsample_step <- grd_calculate_plot_step(x, oversample = oversample, usr = usr)
# if we're so zoomed out that nothing should be plotted, we are done
if (any(is.na(x_downsample_step))) {
return(invisible(x))
}
x_downsample <- grd_crop(
x,
rct(usr[1], usr[3], usr[2], usr[4], crs = wk_crs(x)),
step = x_downsample_step
)
# update bbox with cropped version and check for empty result
rct <- unclass(x_downsample$bbox)
if (identical(rct$xmax - rct$xmin, -Inf) || identical(rct$ymax - rct$ymin, -Inf)) {
return(invisible(x))
}
image <- as.raster(x_downsample, native = TRUE)
}
if (!inherits(image, "nativeRaster")) {
image <- as.raster(image, native = TRUE)
}
graphics::rasterImage(
image,
rct$xmin, rct$ymin, rct$xmax, rct$ymax,
interpolate = interpolate
)
if (!identical(border, NA)) {
if (is.null(border)) {
border <- graphics::par("fg")
}
# simplify borders by drawing segments
nx <- dim(x$data)[2]
ny <- dim(x$data)[1]
width <- rct$xmax - rct$xmin
height <- rct$ymax - rct$ymin
xs <- seq(rct$xmin, rct$xmax, by = width / nx)
ys <- seq(rct$ymin, rct$ymax, by = height / ny)
graphics::segments(xs, rct$ymin, xs, rct$ymax, col = border)
graphics::segments(rct$xmin, ys, rct$xmax, ys, col = border)
}
invisible(x)
}
grd_calculate_plot_step <- function(grid, oversample = c(2, 2),
usr = graphics::par("usr"),
device = NULL) {
# estimate resolution
usr <- graphics::par("usr")
usr_x <- usr[1:2]
usr_y <- usr[3:4]
device_x <- graphics::grconvertX(usr_x, to = "device")
device_y <- graphics::grconvertY(usr_y, to = "device")
# Use resolution of 1 at the device level, scale to usr coords.
# this is sort of like pixels but not always; an oversample of
# about 4 is needed for the operation to be invisible to the user
scale_x <- abs(diff(device_x) / diff(usr_x))
scale_y <- abs(diff(device_y) / diff(usr_y))
resolution_x <- 1 / scale_x
resolution_y <- 1 / scale_y
# we need to know how many cells are going to be resolved by a crop
# to see how many fewer of them we need to sample
ranges <- grd_cell_range(grid, rct(usr_x[1], usr_y[1], usr_x[2], usr_y[2]))
nx <- ranges$j["stop"] - ranges$j["start"]
ny <- ranges$i["stop"] - ranges$i["start"]
dx <- abs(diff(usr_x) / nx)
dy <- abs(diff(usr_y) / ny)
# calculate which step value is closest (rounding down, clamping to valid limits)
step <- (c(resolution_y, resolution_x) / oversample) %/% c(dy, dx)
step <- pmax(1L, step)
# if the step is more than the number of pixels, it really shouldn't be
# displayed at all
if (any(step > c(ny, nx))) {
return(c(NA_integer_, NA_integer_))
}
step
}
#' @export
#' @importFrom grDevices as.raster
as.raster.wk_grd_rct <- function(x, ..., i = NULL, j = NULL, native = NA) {
# as.raster() works when values are [0..1]. We can emulate
# this default by rescaling the image data if it's not already
# a raster or nativeRaster.
if (inherits(x$data, "nativeRaster") || grDevices::is.raster(x$data)) {
grd_data_subset(x$data, i = i, j = j)
} else if (prod(dim(x)) == 0) {
as.raster(matrix(nrow = dim(x)[1], ncol = dim(x)[2]))
} else if (length(dim(x)) == 2L || all(dim(x)[c(-1L, -2L)] == 1L)) {
# try to interpret character() as hex colours, else
# try to resolve x$data as a double() array
if (is.character(x$data)) {
return(as.raster(grd_data_subset(x$data, i = i, j = j)))
}
data <- grd_data_subset(x$data, i = i, j = j)
storage.mode(data) <- "double"
# we've checked that it's safe to drop the non-xy dimensions and
# collected the data so that we know the axis order is R-native
dim(data) <- dim(data)[1:2]
range <- suppressWarnings(range(data, finite = TRUE))
if (all(is.finite(range)) && (diff(range) > .Machine$double.eps)) {
image <- (data - range[1]) / diff(range)
} else if (all(is.finite(range))) {
# constant value
image <- data
image[] <- 0.5
} else {
# all NA values
image <- matrix(nrow = dim(data)[1], ncol = dim(data)[2])
}
as.raster(image)
} else {
stop(
"Can't convert non-numeric or non-matrix grid to raster image",
call. = FALSE
)
}
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/grd-plot.R
|
#' Subset grid objects
#'
#' The [grd_subset()] method handles the subsetting of a [grd()]
#' in x-y space. Ordering of indices is not considered and logical
#' indies are recycled silently along dimensions. The result of
#' a [grd_subset()] is always a [grd()] of the same type whose
#' relationship to x-y space has not changed.
#'
#' @inheritParams grd_cell
#' @inheritParams grd_summary
#' @param grid_data The `data` member of a [grd()]. This is typically an
#' array but can also be an S3 object with an array-like subset method.
#' The [native raster][grDevices::as.raster] is special-cased as its
#' subset method requires non-standard handling.
#' @param i,j 1-based index values. `i` indices correspond to decreasing
#' `y` values; `j` indices correspond to increasing `x` values.
#' Values outside the range `1:nrow|ncol(data)` will be censored to
#' `NA` including 0 and negative values.
#' @param ... Passed to subset methods
#'
#' @return A modified `grid` whose cell centres have not changed location
#' as a result of the subset.
#' @export
#'
#' @examples
#' grid <- grd_rct(volcano)
#' grd_subset(grid, 1:20, 1:30)
#' grd_crop(grid, rct(-10, -10, 10, 10))
#' grd_extend(grid, rct(-10, -10, 10, 10))
#'
grd_subset <- function(grid, i = NULL, j = NULL, ...) {
UseMethod("grd_subset")
}
#' @rdname grd_subset
#' @export
grd_crop <- function(grid, bbox, ..., step = 1L, snap = NULL) {
UseMethod("grd_crop")
}
#' @rdname grd_subset
#' @export
grd_extend <- function(grid, bbox, ..., step = 1L, snap = NULL) {
UseMethod("grd_extend")
}
#' @export
grd_subset.wk_grd_rct <- function(grid, i = NULL, j = NULL, ...) {
grd_subset_grd_internal(grid, i, j)
}
#' @export
grd_subset.wk_grd_xy <- function(grid, i = NULL, j = NULL, ...) {
grd_subset_grd_internal(grid, i, j)
}
grd_subset_grd_internal <- function(grid, i = NULL, j = NULL) {
ij <- ij_from_args(i, j)
# convert i and j into start, stop, step
i <- ij_to_slice_one(ij$i, dim(grid)[1])
j <- ij_to_slice_one(ij$j, dim(grid)[2])
# calculate bbox
s <- grd_summary(grid)
dx <- unname(j["step"] * s$dx)
dy <- unname(i["step"] * s$dy)
center_min <- unclass(grd_cell_xy(grid, i["stop"], j["start"] + 1L))
center_max <- unclass(grd_cell_xy(grid, i["start"] + 1L, j["stop"]))
rct_new <- list(
xmin = center_min$x, ymin = center_min$y,
xmax = center_max$x, ymax = center_max$y
)
# check for empty subsets in both directions
if (!is.finite(rct_new$xmax - rct_new$xmin)) {
rct_new$xmin <- Inf
rct_new$xmax <- -Inf
} else if (inherits(grid, "wk_grd_rct")) {
rct_new$xmin <- rct_new$xmin - dx / 2
rct_new$xmax <- rct_new$xmax + dx / 2
}
if (!is.finite(rct_new$ymax - rct_new$ymin)) {
rct_new$ymin <- Inf
rct_new$ymax <- -Inf
} else if (inherits(grid, "wk_grd_rct")) {
rct_new$ymin <- rct_new$ymin - dy / 2
rct_new$ymax <- rct_new$ymax + dy / 2
}
grid$data <- grd_data_subset(grid$data, i, j)
grid$bbox <- new_wk_rct(rct_new, crs = wk_crs(grid))
grid
}
#' @rdname grd_subset
#' @export
grd_crop.wk_grd_rct <- function(grid, bbox, ..., step = 1L, snap = NULL) {
snap <- snap %||% list(grd_snap_next, grd_snap_previous)
ij <- grd_cell_range(grid, bbox, step = step, snap = snap)
ij$i["start"] <- max(ij$i["start"], 0L)
ij$i["stop"] <- min(ij$i["stop"], dim(grid)[1])
ij$j["start"] <- max(ij$j["start"], 0L)
ij$j["stop"] <- min(ij$j["stop"], dim(grid)[2])
grd_subset(grid, ij)
}
#' @rdname grd_subset
#' @export
grd_crop.wk_grd_xy <- function(grid, bbox, ..., step = 1L, snap = NULL) {
snap <- snap %||% list(ceiling, floor)
ij <- grd_cell_range(grid, bbox, step = step, snap = snap)
ij$i["start"] <- max(ij$i["start"], 0L)
ij$i["stop"] <- min(ij$i["stop"], dim(grid)[1])
ij$j["start"] <- max(ij$j["start"], 0L)
ij$j["stop"] <- min(ij$j["stop"], dim(grid)[2])
grd_subset(grid, ij)
}
#' @rdname grd_subset
#' @export
grd_extend.wk_grd_rct <- function(grid, bbox, ..., step = 1L, snap = NULL) {
snap <- snap %||% list(grd_snap_next, grd_snap_previous)
grd_subset(grid, grd_cell_range(grid, bbox, step = step, snap = snap))
}
#' @rdname grd_subset
#' @export
grd_extend.wk_grd_xy <- function(grid, bbox, ..., step = 1L, snap = NULL) {
snap <- snap %||% list(ceiling, floor)
grd_subset(grid, grd_cell_range(grid, bbox, step = step, snap = snap))
}
#' @rdname grd_subset
#' @export
grd_data_subset <- function(grid_data, i = NULL, j = NULL) {
ij <- ij_from_args(i, j)
ij$i <- ij_expand_one(ij$i, dim(grid_data)[1], out_of_bounds = "censor")
ij$j <- ij_expand_one(ij$j, dim(grid_data)[2], out_of_bounds = "censor")
if (inherits(grid_data, "nativeRaster")) {
# special case the nativeRaster, whose dims are lying about
# the ordering needed to index it
attrs <- attributes(grid_data)
dim(grid_data) <- rev(dim(grid_data))
grid_data <- grid_data[ij$j, ij$i, drop = FALSE]
attrs$dim <- rev(dim(grid_data))
attributes(grid_data) <- attrs
grid_data
} else {
# we want to keep everything for existing dimensions
# this means generating a list of missings to fill
# the correct number of additional dimensions
n_more_dims <- length(dim(grid_data)) - 2L
more_dims <- alist(1, )[rep(2, n_more_dims)]
do.call("[", c(list(grid_data, ij$i, ij$j), more_dims, list(drop = FALSE)))
}
}
#' Grid cell operators
#'
#' @inheritParams grd_summary
#' @inheritParams grd_subset
#' @param bbox An [rct()] object.
#' @param out_of_bounds One of 'keep', 'censor', 'discard', or 'squish'
#' @param step The difference between adjascent indices in the output
#' @param point A [handleable][wk_handle] of points.
#' @param snap A function that transforms real-valued indices to integer
#' indices (e.g., [floor()], [ceiling()], or [round()]).
#' For [grd_cell_range()], a `list()` with exactly two elements to be called
#' for the minimum and maximum index values, respectively.
#' @param ... Unused
#'
#' @return
#' - `grd_cell()`: returns a `list(i, j)` of index values corresponding
#' to the input points and adjusted according to `snap`. Index values
#' will be outside `dim(grid)` for points outside `wk_bbox(grid)` including
#' negative values.
#' - `grd_cell_range()` returns a slice describing the range of indices
#' in the `i` and `j` directions.
#' - `grd_cell_rct()` returns a [rct()] of the cell extent at `i, j`.
#' - `grd_cell_xy()` returns a [xy()] of the cell center at `i, j`.
#' @export
#'
#' @examples
#' grid <- grd(nx = 3, ny = 2)
#' grd_cell(grid, xy(0.5, 0.5))
#' grd_cell_range(grid, grid$bbox)
#' grd_cell_rct(grid, 1, 1)
#' grd_cell_xy(grid, 1, 1)
#'
grd_cell <- function(grid, point, ..., snap = grd_snap_next) {
UseMethod("grd_cell")
}
#' @export
grd_cell.wk_grd_rct <- function(grid, point, ..., snap = grd_snap_next) {
s <- grd_summary(grid)
point <- unclass(as_xy(point))
i <- if (s$width == -Inf) rep(NA_real_, length(point$x)) else (s$ymax - point$y) / s$dy
j <- if (s$height == -Inf) rep(NA_real_, length(point$x)) else (point$x - s$xmin) / s$dx
new_data_frame(list(i = unname(snap(i - 0.5) + 1L), j = unname(snap(j - 0.5) + 1L)))
}
#' @export
grd_cell.wk_grd_xy <- function(grid, point, ..., snap = grd_snap_next) {
grd_cell(as_grd_rct(grid), point, snap = snap)
}
#' @rdname grd_cell
#' @export
grd_cell_range <- function(grid, bbox = wk_bbox(grid), ..., step = 1L, snap = grd_snap_next) {
UseMethod("grd_cell_range")
}
#' @export
grd_cell_range.default <- function(grid, bbox = wk_bbox(grid), ..., step = 1L, snap = grd_snap_next) {
# normalized so that xmin < xmax, ymin < ymax
if (inherits(bbox, "wk_rct")) {
bbox <- wk_bbox(as_wkb(bbox))
} else {
bbox <- wk_bbox(bbox)
}
# step can be length to for i, j steps
if (length(step) == 1L) {
step <- step[c(1L, 1L)]
}
if (is.function(snap)) {
snap <- list(snap, snap)
}
indices <- grd_cell(grid, as_xy(wk_vertices(bbox)))
# return a consistent value for an empty grid subset
s <- grd_summary(grid)
rct_target <- unclass(bbox)
rct_target_width <- rct_target$xmax - rct_target$xmin
rct_target_height <- rct_target$ymax - rct_target$ymin
indices_min <- grd_cell(grid, xy(rct_target$xmin, rct_target$ymax), snap = snap[[1]])
indices_max <- grd_cell(grid, xy(rct_target$xmax, rct_target$ymin), snap = snap[[2]])
if (rct_target_height == -Inf || s$height == -Inf) {
i <- integer()
} else {
i <- c(start = indices_min$i - 1L, stop = indices_max$i, step = 1L)
}
if (rct_target_width == -Inf || s$width == -Inf) {
j <- integer()
} else {
j <- c(start = indices_min$j - 1L, stop = indices_max$j, step = 1L)
}
# process downsample if requested
if (!identical(step, c(1L, 1L))) {
n <- c(0L, 0L)
if (!identical(i, integer())) {
n[1] <- i["stop"] - i["start"]
}
if (!identical(j, integer())) {
n[2] <- j["stop"] - j["start"]
}
step <- pmin(n, pmax(1L, step))
if (!identical(i, integer())) {
i["step"] <- step[1]
i["start"] <- i["start"] + (step[1] %/% 2L)
i["stop"] <- i["stop"] - ((step[1] + 1L) %/% 2L)
}
if (!identical(j, integer())) {
j["step"] <- step[2]
j["start"] <- j["start"] + (step[2] %/% 2L)
j["stop"] <- j["stop"] - ((step[2] + 1L) %/% 2L)
}
}
list(i = i, j = j)
}
#' @rdname grd_cell
#' @export
grd_cell_rct <- function(grid, i, j = NULL, ...) {
UseMethod("grd_cell_rct")
}
#' @rdname grd_cell
#' @export
grd_cell_rct.wk_grd_rct <- function(grid, i, j = NULL, ..., out_of_bounds = "keep") {
s <- grd_summary(grid)
# non-numeric values don't make sense here because i and j are vectorized
# instead of crossed to form the final values
ij <- ij_from_args(i, j)
if (!is.numeric(ij$i) || !is.numeric(ij$j)) {
stop("`i` and `j` must be numeric index vectors in grd_cell_rct()")
}
# recycle to a common length
ij[] <- recycle_common(ij$i, ij$j)
# handle out_of_bounds
ij <- ij_handle_out_of_bounds2(ij, list(s$ny, s$nx), out_of_bounds)
xmin <- s$xmin + (ij$j - 1) * s$dx
xmax <- s$xmin + ij$j * s$dx
ymin <- s$ymax - ij$i * s$dy
ymax <- s$ymax - (ij$i - 1) * s$dy
rct(xmin, ymin, xmax, ymax, crs = wk_crs(grid))
}
#' @rdname grd_cell
#' @export
grd_cell_rct.wk_grd_xy <- function(grid, i, j = NULL, ..., out_of_bounds = "keep") {
grd_cell_rct(as_grd_rct(grid), i, j, out_of_bounds = out_of_bounds)
}
#' @rdname grd_cell
#' @export
grd_cell_xy <- function(grid, i, j = NULL, ...) {
UseMethod("grd_cell_xy")
}
#' @rdname grd_cell
#' @export
grd_cell_xy.wk_grd_rct <- function(grid, i, j = NULL, ..., out_of_bounds = "keep") {
s <- grd_summary(grid)
# non-numeric values don't make sense here because i and j are vectorized
# instead of crossed to form the final values
ij <- ij_from_args(i, j)
if (!is.numeric(ij$i) || !is.numeric(ij$j)) {
stop("`i` and `j` must be numeric index vectors in grd_cell_rct()")
}
# recycle to a common length
ij[] <- recycle_common(ij$i, ij$j)
# handle out_of_bounds
ij <- ij_handle_out_of_bounds2(ij, list(s$ny, s$nx), out_of_bounds)
x <- s$xmin + (ij$j - 1) * s$dx + s$dx / 2
y <- s$ymax - (ij$i - 1) * s$dy - s$dy / 2
xy(x, y, crs = wk_crs(grid))
}
#' @rdname grd_cell
#' @export
grd_cell_xy.wk_grd_xy <- function(grid, i, j = NULL, ..., out_of_bounds = "keep") {
grd_cell_xy(as_grd_rct(grid), i, j, out_of_bounds = out_of_bounds)
}
ij_from_args <- function(i, j = NULL) {
if (is.null(i) && is.null(j)) {
list(i = NULL, j = NULL)
} else if (is.null(j) && is.list(i)) {
i
} else {
list(i = i, j = j)
}
}
ij_expand_one <- function(i, n, out_of_bounds = "keep") {
if (is.null(i)) {
i <- if (n > 0) seq(1L, n) else integer()
} else if (identical(names(i), c("start", "stop", "step"))) {
value_na <- is.na(i)
i[value_na] <- c(0L, n, 1L)[value_na]
if (i["stop"] > i["start"]) {
i <- unname(seq(i["start"] + 1L, i["stop"], by = i["step"]))
} else {
i <- integer()
}
} else if (is.numeric(i)) {
i <- i
} else {
stop(
"index vectors must be NULL, numeric, or c(start = , stop =, step =)",
call. = FALSE
)
}
if (out_of_bounds == "censor") {
i[(i > n) | (i < 1)] <- NA_integer_
} else if (out_of_bounds == "keep") {
# do nothing
} else if (out_of_bounds == "discard") {
i <- i[(i <= n) & (i >= 1)]
} else if (out_of_bounds == "squish") {
i[i < 1L] <- 1L
i[i > n] <- n
} else {
stop(
"`out_of_bounds` must be one of 'censor', 'keep', 'discard', or 'squish'",
call. = FALSE
)
}
i
}
ij_to_slice_one <- function(i, n) {
if (is.null(i)) {
i <- if (n == 0L) integer() else c(start = 0L, stop = n, step = 1L)
} else if (identical(names(i), c("start", "stop", "step"))) {
value_na <- is.na(i)
i[value_na] <- c(0L, n, 1L)[value_na]
i <- if (i["start"] >= i["stop"]) integer() else i
} else if (is.numeric(i)) {
if (length(i) == 0L) {
i <- integer()
} else if ((length(i) == 1L) && is.finite(i)) {
i <- c(start = i - 1L, stop = i, step = 1L)
} else {
if (any(!is.finite(i))) {
stop("numeric index vectors must be finite in `grd_subset()`", call. = FALSE)
}
step <- unique(diff(i))
if ((length(step) != 1) || (step <= 0)) {
stop("numeric index vectors must be equally spaced and ascending", call. = FALSE)
}
i <- c(start = min(i) - 1L, stop = max(i), step = step)
}
} else {
stop(
"index vectors must be NULL, numeric, or c(start = , stop =, step =)",
call. = FALSE
)
}
i
}
# used by extractors to handle out-of-bounds points and/or cells
ij_handle_out_of_bounds2 <- function(ij, n, out_of_bounds) {
if (out_of_bounds == "keep") {
return(ij)
}
oob_i <- !is.na(ij$i) & ((ij$i > n[[1]]) | (ij$i < 1L))
oob_j <- !is.na(ij$j) & ((ij$j > n[[2]]) | (ij$j < 1L))
oob_either <- oob_i | oob_j
if (!any(oob_either)) {
return(ij)
}
if (out_of_bounds == "censor") {
ij$i[oob_either] <- NA_integer_
ij$j[oob_either] <- NA_integer_
} else if (out_of_bounds == "discard") {
ij$i <- ij$i[!oob_either]
ij$j <- ij$j[!oob_either]
} else if (out_of_bounds == "squish") {
ij$i[!is.na(ij$i) & (ij$i < 1L)] <- 1L
ij$j[!is.na(ij$j) & (ij$j < 1L)] <- 1L
ij$i[!is.na(ij$i) & (ij$i > n[[1]])] <- n[[1]]
ij$j[!is.na(ij$j) & (ij$j > n[[2]])] <- n[[2]]
} else {
stop(
"`out_of_bounds` must be one of 'censor', 'keep', 'discard', or 'squish'",
call. = FALSE
)
}
ij
}
#' Index snap functions
#'
#' These functions can be used in [grd_cell()] and
#' [grd_cell_range()]. These functions differ in the way
#' they round 0.5: [grd_snap_next()] always rounds up
#' and [grd_snap_previous()] always rounds down. You can
#' also use [floor()] and [ceiling()] as index
#' snap functions.
#'
#' @param x A vector of rescaled but non-integer indices
#'
#' @return A vector of integer indices
#' @export
#'
#' @examples
#' grd_snap_next(seq(0, 2, 0.25))
#' grd_snap_previous(seq(0, 2, 0.25))
#'
grd_snap_next <- function(x) {
ifelse(((x + 0.5) %% 1L) == 0, ceiling(x), round(x))
}
#' @rdname grd_snap_next
#' @export
grd_snap_previous <- function(x) {
ifelse(((x + 0.5) %% 1L) == 0, floor(x), round(x))
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/grd-subset.R
|
#' Compute overview grid tile
#'
#' A useful workflow for raster data in a memory bounded environment is to
#' chunk a grid into sections or tiles. These functions compute tiles
#' suitable for such processing. Use [grd_tile_summary()] to generate
#' statistics for `level` values to choose for your application.
#'
#' @inheritParams grd_summary
#' @param level An integer describing the overview level. This is related to
#' the `step` value by a power of 2 (i.e., a level of `1` indicates a step of
#' `2`, a level of `2` indicates a step of `4`, etc.).
#' @param levels A vector of `level` values or `NULL` to use a sequence from
#' 0 to the level that would result in a 1 x 1 grid.
#'
#' @return A [grd()]
#' @export
#'
#' @examples
#' grid <- grd_rct(volcano)
#' grd_tile_summary(grid)
#' grd_tile_template(grid, 3)
#'
grd_tile_template <- function(grid, level) {
level <- normalize_level(grid, level)
grid <- as_grd_rct(grid)
# clamp the step to a reasonable bound
s <- grd_summary(grid)
step <- 2 ^ level
step_clamp <- pmax(1L, pmin(c(s$ny, s$nx), step))
level_clamp <- ceiling(log2(step_clamp))
step_final <- 2 ^ level_clamp
# calculate the new grid parameters
final_dy <- s$dy * step_final[1]
final_dx <- s$dx * step_final[2]
final_ny <- ceiling(s$ny / step_final[1])
final_nx <- ceiling(s$nx / step_final[2])
final_bbox <- rct(
s$xmin,
s$ymax - final_ny * final_dy,
s$xmin + final_nx * final_dx,
s$ymax,
crs = wk_crs(grid)
)
grd_rct(
array(dim = c(final_ny, final_nx, 0)),
final_bbox
)
}
#' @rdname grd_tile_template
#' @export
grd_tile_summary <- function(grid, levels = NULL) {
if (is.null(levels)) {
s <- grd_summary(grid)
level0 <- max(floor(log2(c(s$nx, s$ny)))) + 1L
levels <- 0:level0
}
overviews <- lapply(levels, function(level) grd_tile_template(grid, level))
summaries <- lapply(overviews, grd_summary)
summary_df <- lapply(summaries, new_data_frame)
cbind(level = levels, do.call(rbind, summary_df))
}
#' Extract normalized grid tiles
#'
#' Unlike [grd_tile_template()], which returns a [grd()] whose elements are
#' the boundaries of the specified tiles with no data attached, [grd_tile()]
#' returns the actual tile with the data.
#'
#' @inheritParams grd_tile_summary
#' @inheritParams grd_subset
#'
#' @return A [grd_subset()]ed version
#' @export
#'
#' @examples
#' grid <- grd_rct(volcano)
#' plot(grd_tile(grid, 4, 1, 1))
#'
#' plot(grd_tile(grid, 3, 1, 1), add = TRUE)
#' plot(grd_tile(grid, 3, 1, 2), add = TRUE)
#' plot(grd_tile(grid, 3, 2, 1), add = TRUE)
#' plot(grd_tile(grid, 3, 2, 2), add = TRUE)
#'
#' grid <- as_grd_xy(grd_tile(grid, 4, 1, 1))
#' plot(grid, add = TRUE, pch = ".")
#' plot(grd_tile(grid, 3, 1, 1), add = TRUE, col = "green", pch = ".")
#' plot(grd_tile(grid, 3, 1, 2), add = TRUE, col = "red", pch = ".")
#' plot(grd_tile(grid, 3, 2, 1), add = TRUE, col = "blue", pch = ".")
#' plot(grd_tile(grid, 3, 2, 2), add = TRUE, col = "magenta", pch = ".")
#'
grd_tile <- function(grid, level, i, j = NULL) {
UseMethod("grd_tile")
}
#' @rdname grd_tile
#' @export
grd_tile.wk_grd_rct <- function(grid, level, i, j = NULL) {
overview <- grd_tile_template(grid, level)
bbox <- grd_cell_rct(overview, i, j)
ranges <- grd_cell_range(grid, bbox, snap = list(grd_snap_next, grd_snap_previous))
grd_subset(grid, ranges)
}
#' @rdname grd_tile
#' @export
grd_tile.wk_grd_xy <- function(grid, level, i, j = NULL) {
grid_rct <- as_grd_rct(grid)
overview <- grd_tile_template(grid_rct, level)
bbox <- grd_cell_rct(overview, i, j)
ranges <- grd_cell_range(grid, bbox, snap = list(grd_snap_next, grd_snap_previous))
grd_subset(grid, ranges)
}
# This could maybe in the future deal with negative levels based on the
# grd_tile_summary() so that one could work down from coarse->fine
normalize_level <- function(grid, level, s = grd_summary(grid)) {
if (length(level) == 1L) {
level <- c(level, level)
}
level
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/grd-tile.R
|
#' Raster-like objects
#'
#' [grd()] objects are just an array (any object with more than
#' two [dim()]s) and a bounding box (a [rct()], which may or
#' may not have a [wk_crs()] attached). The ordering of the dimensions
#' is y (indices increasing downwards), x (indices increasing to the right).
#' This follows the ordering of [as.raster()]/[rasterImage()] and aligns
#' with the printing of matrices.
#'
#' @param data An object with two or more dimensions. Most usefully, a matrix.
#' @param bbox A [rct()] containing the bounds and CRS of the object. You can
#' specify a [rct()] with `xmin > xmax` or `ymin > ymax` which will flip
#' the underlying data and return an object with a normalized bounding
#' box and data.
#' @param nx,ny,dx,dy Either a number of cells in the x- and y- directions
#' or delta in the x- and y-directions (in which case `bbox` must
#' be specified).
#' @param type Use "polygons" to return a grid whose objects can be
#' represented using an [rct()]; use "centers" to return a grid whose
#' objects are the center of the [rct()] grid; use "corners" to return
#' a grid along the corners of `bbox`.
#' @param x An object to convert to a grid
#' @param ... Passed to S3 methods
#'
#' @return
#' - `grd()` returns a `grd_rct()` for `type == "polygons` or
#' a `grd_xy()` otherwise.
#' - `grd_rct()` returns an object of class "wk_grd_rct".
#' - `grd_xy()` returns an object of class "wk_grd_xy".
#' @export
#'
#' @examples
#' # create a grid with no data (just for coordinates)
#' (grid <- grd(nx = 2, ny = 2))
#' as_rct(grid)
#' as_xy(grid)
#' plot(grid, border = "black")
#'
#' # more usefully, wraps a matrix or nd array + bbox
#' # approx volcano in New Zealand Transverse Mercator
#' bbox <- rct(
#' 5917000, 1757000 + 870,
#' 5917000 + 610, 1757000,
#' crs = "EPSG:2193"
#' )
#' (grid <- grd_rct(volcano, bbox))
#'
#' # these come with a reasonable default plot method for matrix data
#' plot(grid)
#'
#' # you can set the data or the bounding box after creation
#' grid$bbox <- rct(0, 0, 1, 1)
#'
#' # subset by indices or rct
#' plot(grid[1:2, 1:2])
#' plot(grid[c(start = NA, stop = NA, step = 2), c(start = NA, stop = NA, step = 2)])
#' plot(grid[rct(0, 0, 0.5, 0.5)])
#'
grd <- function(bbox = NULL, nx = NULL, ny = NULL, dx = NULL, dy = NULL,
type = c("polygons", "corners", "centers")) {
if (is.null(bbox)) {
bbox <- NULL
} else if (inherits(bbox, "wk_rct")) {
bbox
} else {
wk_bbox(bbox)
}
type <- match.arg(type)
if (is.null(nx) && is.null(ny) && !is.null(dx) && !is.null(dy) && !is.null(bbox)) {
rct <- unclass(bbox)
width <- rct$xmax - rct$xmin
height <- rct$ymax - rct$ymin
if (type == "polygons") {
nx <- width / dx
ny <- height / dy
} else if (type == "corners") {
nx <- width / dx + 1
ny <- height / dy + 1
} else if (type == "centers") {
nx <- width / dx
ny <- height / dy
bbox <- rct(
rct$xmin + dx / 2,
rct$ymin + dy / 2,
rct$xmax - dx / 2,
rct$ymax - dy / 2,
crs = wk_crs(bbox)
)
}
} else if (is.null(dx) && is.null(dy) && !is.null(nx) && !is.null(ny)) {
if (is.null(bbox)) {
bbox <- rct(0, 0, nx, ny)
}
nx <- nx
ny <- ny
if (type == "centers") {
rct <- unclass(bbox)
width <- rct$xmax - rct$xmin
height <- rct$ymax - rct$ymin
dx <- width / nx
dy <- height / ny
bbox <- rct(
rct$xmin + dx / 2,
rct$ymin + dy / 2,
rct$xmax - dx / 2,
rct$ymax - dy / 2,
crs = wk_crs(bbox)
)
} else if (type == "corners") {
nx <- nx + 1
ny <- ny + 1
}
} else {
stop(
"Must specify dx, dy, and bbox OR nx and ny.",
call. = FALSE
)
}
# use a length-zero logical() with correct x and y dims
data <- array(dim = c(ny, nx, 0))
if (type == "polygons") {
grd_rct(data, bbox)
} else {
grd_xy(data, bbox)
}
}
#' @rdname grd
#' @export
grd_rct <- function(data, bbox = rct(0, 0, dim(data)[2], dim(data)[1])) {
bbox <- if (inherits(bbox, "wk_rct")) bbox else wk_bbox(bbox)
# normalize data and bbox so that max > min
normalized <- grd_internal_normalize(data, bbox)
data <- normalized[[1]]
bbox <- normalized[[2]]
# with zero values, bbox in that direction is empty
rct <- unclass(bbox)
if (dim(data)[2] == 0) {
rct$xmin <- Inf
rct$xmax <- -Inf
}
if (dim(data)[1] == 0) {
rct$ymin <- Inf
rct$ymax <- -Inf
}
bbox <- new_wk_rct(rct, crs = wk_crs(bbox))
new_wk_grd(list(data = data, bbox = bbox), "wk_grd_rct")
}
#' @rdname grd
#' @export
grd_xy <- function(data, bbox = rct(0, 0, dim(data)[2] - 1, dim(data)[1] - 1)) {
bbox <- if (inherits(bbox, "wk_rct")) bbox else wk_bbox(bbox)
# normalize data and bbox so that max > min
normalized <- grd_internal_normalize(data, bbox)
data <- normalized[[1]]
bbox <- normalized[[2]]
# with zero values, bbox in that direction is empty
rct <- unclass(bbox)
if (dim(data)[2] == 0) {
rct$xmin <- Inf
rct$xmax <- -Inf
}
if (dim(data)[1] == 0) {
rct$ymin <- Inf
rct$ymax <- -Inf
}
bbox <- new_wk_rct(rct, crs = wk_crs(bbox))
# with one value in the x dimension, we need a zero width bbox
if (dim(data)[2] == 1) {
stopifnot(
unclass(bbox)$xmax == unclass(bbox)$xmin
)
}
# with one value in the y dimension, we need a zero height bbox
if (dim(data)[1] == 1) {
stopifnot(
unclass(bbox)$ymax == unclass(bbox)$ymin
)
}
new_wk_grd(list(data = data, bbox = bbox), "wk_grd_xy")
}
#' @rdname grd
#' @export
as_grd_rct <- function(x, ...) {
UseMethod("as_grd_rct")
}
#' @rdname grd
#' @export
as_grd_rct.wk_grd_rct <- function(x, ...) {
x
}
#' @rdname grd
#' @export
as_grd_rct.wk_grd_xy <- function(x, ...) {
# from a grd_xy, we assume these were the centres
s <- grd_summary(x)
bbox <- rct(
s$xmin - s$dx / 2,
s$ymin - s$dy / 2,
s$xmax + s$dx / 2,
s$ymax + s$dy / 2,
crs = wk_crs(x$bbox)
)
grd_rct(x$data, bbox = bbox)
}
#' @rdname grd
#' @export
as_grd_xy <- function(x, ...) {
UseMethod("as_grd_xy")
}
#' @rdname grd
#' @export
as_grd_xy.wk_grd_xy <- function(x, ...) {
x
}
#' @rdname grd
#' @export
as_grd_xy.wk_grd_rct <- function(x, ...) {
# from a grid_rct() we take the centers
s <- grd_summary(x)
bbox <- rct(
s$xmin + s$dx / 2,
s$ymin + s$dy / 2,
s$xmax - s$dx / 2,
s$ymax - s$dy / 2,
crs = wk_crs(x$bbox)
)
grd_xy(x$data, bbox = bbox)
}
#' S3 details for grid objects
#'
#' @param x A [grd()]
#' @param subclass An optional subclass.
#'
#' @return An object inheriting from 'grd'
#'
#' @export
#'
new_wk_grd <- function(x, subclass = character()) {
structure(x, class = union(subclass, "wk_grd"))
}
#' Grid information
#'
#' @param grid A [grd_xy()], [grd_rct()], or other object
#' implementing `grd_*()` methods.
#' @return
#' - `grd_summary()` returns a `list()` with components
#' `xmin`, `ymin`, `xmax`, `ymax`,
#' `nx`, `ny`, `dx`, `dy`, `width`, and `height`.
#' @export
#'
#' @examples
#' grd_summary(grd(nx = 3, ny = 2))
#'
grd_summary <- function(grid) {
UseMethod("grd_summary")
}
#' @export
grd_summary.wk_grd_rct <- function(grid) {
nx <- dim(grid$data)[2]
ny <- dim(grid$data)[1]
rct <- unclass(grid$bbox)
width <- rct$xmax - rct$xmin
height <- rct$ymax - rct$ymin
dx <- width / nx
dy <- height / ny
list(
xmin = rct$xmin,
ymin = rct$ymin,
xmax = rct$xmax,
ymax = rct$ymax,
nx = nx,
ny = ny,
dx = dx,
dy = dy,
width = width,
height = height
)
}
#' @export
grd_summary.wk_grd_xy <- function(grid) {
nx <- dim(grid$data)[2]
ny <- dim(grid$data)[1]
rct <- unclass(grid$bbox)
width <- rct$xmax - rct$xmin
height <- rct$ymax - rct$ymin
dx <- if (nx > 1) width / (nx - 1) else 0
dy <- if (ny > 1) height / (ny - 1) else 0
list(
xmin = rct$xmin,
ymin = rct$ymin,
xmax = rct$xmax,
ymax = rct$ymax,
nx = nx,
ny = ny,
dx = dx,
dy = dy,
width = width,
height = height
)
}
# interface for wk methods
#' @export
wk_bbox.wk_grd <- function(handleable, ...) {
handleable$bbox
}
#' @export
wk_crs.wk_grd <- function(x) {
attr(x$bbox, "crs", exact = TRUE)
}
#' @export
wk_set_crs.wk_grd <- function(x, crs) {
x$bbox <- wk_set_crs(x$bbox, crs)
x
}
# interface for setting data and bbox
#' @export
`[[<-.wk_grd` <- function(x, i, value) {
x_bare <- unclass(x)
if (identical(i, "data")) {
stopifnot(length(dim(value)) >= 2)
x_bare$data <- value
} else if (identical(i, "bbox")) {
if (inherits(value, "wk_rct")) {
# normalize so that max > min, but empty (Inf -Inf) is OK
rct <- unclass(value)
# missings make no sense in this context
if (any(vapply(rct, is.na, logical(1)))) {
stop("Can't set missing bounding box for grd objects", call. = FALSE)
}
if ((rct$xmin > rct$xmax) && (rct$xmin != Inf) && (rct$xmax != -Inf)) {
rct[c("xmin", "xmax")] <- rct[c("xmax", "xmin")]
}
if ((rct$ymin > rct$ymax) && (rct$ymin != Inf) && (rct$ymax != -Inf)) {
rct[c("ymin", "ymax")] <- rct[c("ymax", "ymin")]
}
value <- new_wk_rct(rct, crs = wk_crs(value))
} else {
value <- wk_bbox(value)
}
x_bare$bbox <- value
} else {
stop("Can't set element of a grd that is not 'data' or 'bbox'", call. = FALSE)
}
class(x_bare) <- class(x)
x_bare
}
#' @export
`$<-.wk_grd` <- function(x, i, value) {
x[[i]] <- value
x
}
# interface for matrix-like extraction and subsetting
#' @export
dim.wk_grd <- function(x) {
dim(x$data)
}
#' @export
`[.wk_grd` <- function(x, i, j, ..., drop = FALSE) {
# for this method we never drop dimensions (can use $data[] to do this)
stopifnot(identical(drop, FALSE))
bbox <- NULL
if (missing(i)) {
i <- NULL
}
if (missing(j)) {
j <- NULL
}
# allow combination of i, j to be a rct() instead
if (inherits(i, "wk_rct") && is.null(j)) {
result_xy <- grd_crop(x, bbox = i)
if (length(dim(x$data)) > 2) {
result_xy$data <- result_xy$data[, , , ..., drop = FALSE]
} else {
result_xy$data <- result_xy$data[, , ..., drop = FALSE]
}
} else if (inherits(i, "wk_rct")) {
result_xy <- grd_crop(x, bbox = i)
result_xy$data <- result_xy$data[, , j, ..., drop = FALSE]
} else {
result_xy <- grd_subset(x, i = i, j = j)
result_xy$data <- result_xy$data[, , ..., drop = FALSE]
}
result_xy
}
#' @export
format.wk_grd <- function(x, ...) {
crs <- wk_crs(x)
sprintf(
"<%s [%s] => %s%s>",
class(x)[1],
paste0(dim(x$data), collapse = " x "),
wk_bbox(x),
if (is.null(crs)) "" else paste0(" with crs=", format(crs))
)
}
#' @export
print.wk_grd <- function(x, ...) {
cat(paste0(format(x), "\n"))
utils::str(x)
invisible(x)
}
# normalize the data and the bbox such that xmax > xmin and ymax > ymin
grd_internal_normalize <- function(x, bbox) {
rct <- unclass(bbox)
new_rct <- rct
if ((rct$ymin > rct$ymax) && (dim(x)[1] > 0)) {
new_rct$ymin <- rct$ymax
new_rct$ymax <- rct$ymin
if (inherits(x, "nativeRaster")) {
# the dimensions of a nativeRaster are lying in the sense that
# they are row-major but are being stored column-major in the way
# that R's indexing functions work
attrs <- attributes(x)
dim(x) <- rev(dim(x))
x <- x[, ncol(x):1, drop = FALSE]
attributes(x) <- attrs
} else {
x <- x[nrow(x):1, , drop = FALSE]
}
}
if ((rct$xmin > rct$xmax) && (dim(x)[2] > 0)) {
new_rct$xmin <- rct$xmax
new_rct$xmax <- rct$xmin
if (inherits(x, "nativeRaster")) {
attrs <- attributes(x)
dim(x) <- rev(dim(x))
x <- x[nrow(x):1, , drop = FALSE]
attributes(x) <- attrs
} else {
x <- x[, ncol(x):1, drop = FALSE]
}
}
list(x = x, bbox = new_wk_rct(new_rct, crs = wk_crs(bbox)))
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/grd.R
|
#' @rdname wk_handle
#' @export
wk_handle.wk_crc <- function(handleable, handler, ...,
n_segments = getOption("wk.crc_n_segments", NULL),
resolution = getOption("wk.crc_resolution", NULL)) {
if (is.null(n_segments) && is.null(resolution)) {
n_segments <- 100L
} else if (is.null(n_segments)) {
n_segments <- ceiling(2 * pi / (resolution / unclass(handleable)$r))
}
n_segments <- as.integer(pmax(4L, n_segments))
n_segments[is.na(n_segments)] <- 4L
if ((length(n_segments) != 1) && (length(n_segments) != length(handleable))) {
stop(
sprintf(
"`n_segments`/`resolution` must be length 1 or length of data (%s)",
length(handleable)
),
call. = FALSE
)
}
handler <- as_wk_handler(handler)
.Call(wk_c_read_crc, handleable, handler, n_segments)
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/handle-crc.R
|
#' @rdname wk_handle
#' @export
wk_handle.wk_rct <- function(handleable, handler, ...) {
handler <- as_wk_handler(handler)
.Call(wk_c_read_rct, handleable, handler)
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/handle-rct.R
|
#' @rdname wk_handle
#' @export
wk_handle.sfc <- function(handleable, handler, ...) {
handler <- as_wk_handler(handler)
.Call(wk_c_read_sfc, handleable, handler)
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/handle-sfc.R
|
#' Handle specific regions of objects
#'
#' @inheritParams wk_handle
#' @param from 1-based index of the feature to start from
#' @param to 1-based index of the feature to end at
#'
#' @return A subset of `handleable`
#' @export
#'
#' @examples
#' wk_handle_slice(xy(1:5, 1:5), wkt_writer(), from = 3, to = 5)
#' wk_handle_slice(
#' data.frame(let = letters[1:5], geom = xy(1:5, 1:5)),
#' wkt_writer(),
#' from = 3, to = 5
#' )
#'
wk_handle_slice <- function(handleable, handler = wk_writer(handleable),
from = NULL, to = NULL, ...) {
UseMethod("wk_handle_slice")
}
#' @rdname wk_handle_slice
#' @export
wk_handle_slice.default <- function(handleable, handler = wk_writer(handleable),
from = NULL, to = NULL, ...) {
# make sure we're dealing with a handleable and a vector
stopifnot(is_handleable(handleable), is_vector_class(handleable))
from <- from %||% 1L
to <- to %||% length(handleable)
from <- max(from, 1L)
to <- min(to, length(handleable))
if (to >= from) {
wk_handle(handleable[from:to], handler, ...)
} else {
wk_handle(handleable[integer(0)], handler, ...)
}
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/handle-slice.R
|
#' @rdname wk_handle
#' @export
wk_handle.wk_wkb <- function(handleable, handler, ...) {
handler <- as_wk_handler(handler)
.Call(wk_c_read_wkb, handleable, handler)
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/handle-wkb.R
|
#' @rdname wk_handle
#' @export
wk_handle.wk_wkt <- function(handleable, handler, ...) {
handler <- as_wk_handler(handler)
.Call(
wk_c_read_wkt,
list(handleable, TRUE),
handler
)
}
#' Test handlers for handling of unknown size vectors
#'
#' @inheritParams wk_handle
#' @export
#'
#' @examples
#' handle_wkt_without_vector_size(wkt(), wk_vector_meta_handler())
#'
handle_wkt_without_vector_size <- function(handleable, handler) {
handler <- as_wk_handler(handler)
.Call(
wk_c_read_wkt,
list(handleable, FALSE),
handler
)
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/handle-wkt.R
|
#' @rdname wk_handle
#' @export
wk_handle.wk_xy <- function(handleable, handler, ...) {
handler <- as_wk_handler(handler)
.Call(wk_c_read_xy, handleable, handler)
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/handle-xy.R
|
#' Read geometry vectors
#'
#' The handler is the basic building block of the wk package. In
#' particular, the [wk_handle()] generic allows operations written
#' as handlers to "just work" with many different input types. The
#' wk package provides the [wk_void()] handler, the [wk_format()]
#' handler, the [wk_debug()] handler, the [wk_problems()] handler,
#' and [wk_writer()]s for [wkb()], [wkt()], [xy()], and [sf::st_sfc()])
#' vectors.
#'
#' @param handler_ptr An external pointer to a newly created WK handler
#' @param handler A [wk_handler][wk_handle] object.
#' @param subclass The handler subclass
#' @param handleable A geometry vector (e.g., [wkb()], [wkt()], [xy()],
#' [rct()], or [sf::st_sfc()]) for which [wk_handle()] is defined.
#' @param n_segments,resolution The number of segments to use when approximating
#' a circle. The default uses `getOption("wk.crc_n_segments")` so that
#' this value can be set for implicit conversions (e.g., `as_wkb()`).
#' Alternatively, set the minimum distance between points on the circle
#' (used to estimate `n_segments`). The default is obtained
#' using `getOption("wk.crc_resolution")`.
#' @param ... Passed to the [wk_handle()] method.
#'
#' @return A WK handler.
#' @export
#'
wk_handle <- function(handleable, handler, ...) {
UseMethod("wk_handle")
}
#' @rdname wk_handle
#' @export
is_handleable <- function(handleable) {
force(handleable)
# use vector_meta because it doesn't ever iterate over an entire vector
tryCatch({wk_vector_meta(handleable); TRUE}, error = function(e) FALSE)
}
#' @rdname wk_handle
#' @export
new_wk_handler <- function(handler_ptr, subclass = character()) {
stopifnot(typeof(handler_ptr) == "externalptr")
structure(handler_ptr, class = union(subclass, "wk_handler"))
}
#' @rdname wk_handle
#' @export
is_wk_handler <- function(handler) {
inherits(handler, "wk_handler")
}
#' @rdname wk_handle
#' @export
as_wk_handler <- function(handler, ...) {
if (is.function(handler)) {
handler()
} else if (is_wk_handler(handler)) {
handler
} else {
stop("`handler` must be a wk handler object", call. = FALSE)
}
}
#' @export
print.wk_handler <- function(x, ...) {
cat(sprintf("<%s at %s>\n", class(x)[1], .Call(wk_c_handler_addr, x)))
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/handler.R
|
#' Create lines, polygons, and collections
#'
#' @inheritParams wk_handle
#' @param feature_id An identifier where changes in sequential
#' values indicate a new feature. This is recycled silently
#' as needed.
#' @param ring_id An identifier where changes in sequential
#' values indicate a new ring. Rings are automatically
#' closed. This is recycled silently as needed.
#' @param geometry_type The collection type to create.
#' @param geodesic Use `TRUE` or `FALSE` to explicitly force
#' the geodesic-ness of the output.
#'
#' @return An object of the same class as `handleable` with
#' whose coordinates have been assembled into the given
#' type.
#' @export
#'
#' @examples
#' wk_linestring(xy(c(1, 1), c(2, 3)))
#' wk_polygon(xy(c(0, 1, 0), c(0, 0, 1)))
#' wk_collection(xy(c(1, 1), c(2, 3)))
#'
wk_linestring <- function(handleable, feature_id = 1L, ..., geodesic = NULL) {
writer <- wk_writer(handleable, generic = TRUE)
result <- wk_handle(handleable, wk_linestring_filter(writer, as.integer(feature_id)), ...)
wk_crs(result) <- wk_crs(handleable)
wk_is_geodesic(result) <- geodesic %||% wk_is_geodesic(handleable)
result
}
#' @rdname wk_linestring
#' @export
wk_polygon <- function(handleable, feature_id = 1L, ring_id = 1L, ..., geodesic = NULL) {
writer <- wk_writer(handleable, generic = TRUE)
result <- wk_handle(
handleable,
wk_polygon_filter(
writer,
as.integer(feature_id),
as.integer(ring_id)
),
...
)
wk_crs(result) <- wk_crs(handleable)
wk_is_geodesic(result) <- geodesic %||% wk_is_geodesic(handleable)
result
}
#' @rdname wk_linestring
#' @export
wk_collection <- function(handleable, geometry_type = wk_geometry_type("geometrycollection"),
feature_id = 1L, ...) {
writer <- wk_writer(handleable, generic = TRUE)
result <- wk_handle(
handleable,
wk_collection_filter(
writer,
as.integer(geometry_type)[1],
as.integer(feature_id)
),
...
)
result <- wk_set_crs(result, wk_crs(handleable))
wk_set_geodesic(result, wk_is_geodesic(handleable))
}
#' @rdname wk_linestring
#' @export
wk_linestring_filter <- function(handler, feature_id = 1L) {
new_wk_handler(
.Call(wk_c_linestring_filter_new, as_wk_handler(handler), feature_id),
"wk_linestring_filter"
)
}
#' @rdname wk_linestring
#' @export
wk_polygon_filter <- function(handler, feature_id = 1L, ring_id = 1L) {
new_wk_handler(
.Call(wk_c_polygon_filter_new, handler, feature_id, ring_id),
"wk_polygon_filter"
)
}
#' @rdname wk_linestring
#' @export
wk_collection_filter <- function(handler, geometry_type = wk_geometry_type("geometrycollection"),
feature_id = 1L) {
new_wk_handler(
.Call(wk_c_collection_filter_new, as_wk_handler(handler), geometry_type, feature_id),
"wk_collection_filter"
)
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/make.R
|
#' Extract feature-level meta
#'
#' These functions return the non-coordinate information of a geometry
#' and/or vector. They do not parse an entire geometry/vector and are
#' intended to be very fast even for large vectors.
#'
#' @inheritParams wk_handle
#' @param geometry_type An integer code for the geometry type. These
#' integers follow the WKB specification (e.g., 1 for point,
#' 7 for geometrycollection).
#' @param geometry_type_label A character vector of (lowercase)
#' geometry type labels as would be found in WKT (e.g., point,
#' geometrycollection).
#'
#' @return A data.frame with columns:
#' - `geometry_type`: An integer identifying the geometry type.
#' A value of 0 indicates that the types of geometry in the vector
#' are not known without parsing the entire vector.
#' - `size`: For points and linestrings, the number of coordinates; for
#' polygons, the number of rings; for collections, the number of
#' child geometries. A value of zero indicates an EMPTY geometry.
#' A value of `NA` means this value is unknown without parsing the
#' entire geometry.
#' - `has_z`: `TRUE` if coordinates contain a Z value. A value of `NA`
#' means this value is unknown without parsing the entire vector.
#' - `has_m`: `TRUE` if coordinates contain an M value. A value of `NA`
#' means this value is unknown without parsing the entire vector.
#' - `srid`: An integer identifying a CRS or NA if this value was not
#' provided.
#' - `precision`: A grid size or 0.0 if a grid size was not provided.
#' Note that coordinate values may not have been rounded; the grid
#' size only refers to the level of detail with which they should
#' be interpreted.
#' - `is_empty`: `TRUE` if there is at least one non-empty coordinate.
#' For the purposes of this value, a non-empty coordinate is one that
#' contains at least one value that is not `NA` or `NaN`.
#'
#' @export
#'
#' @examples
#' wk_vector_meta(as_wkt("LINESTRING (0 0, 1 1)"))
#' wk_meta(as_wkt("LINESTRING (0 0, 1 1)"))
#' wk_meta(as_wkb("LINESTRING (0 0, 1 1)"))
#'
#' wk_geometry_type_label(1:7)
#' wk_geometry_type(c("point", "geometrycollection"))
#'
wk_meta <- function(handleable, ...) {
UseMethod("wk_meta")
}
#' @rdname wk_meta
#' @export
wk_meta.default <- function(handleable, ...) {
new_data_frame(wk_handle(handleable, wk_meta_handler(), ...))
}
#' @rdname wk_meta
#' @export
wk_vector_meta <- function(handleable, ...) {
UseMethod("wk_vector_meta")
}
#' @rdname wk_meta
#' @export
wk_vector_meta.default <- function(handleable, ...) {
new_data_frame(wk_handle(handleable, wk_vector_meta_handler(), ...))
}
#' @rdname wk_meta
#' @export
wk_meta_handler <- function() {
new_wk_handler(.Call(wk_c_meta_handler_new), "wk_meta_handler")
}
#' @rdname wk_meta
#' @export
wk_vector_meta_handler <- function() {
new_wk_handler(.Call(wk_c_vector_meta_handler_new), "wk_vector_meta_handler")
}
#' @rdname wk_meta
#' @export
wk_geometry_type_label <- function(geometry_type) {
c(
"point", "linestring", "polygon",
"multipoint", "multilinestring", "multipolygon",
"geometrycollection"
)[as.integer(geometry_type)]
}
#' @rdname wk_meta
#' @export
wk_geometry_type <- function(geometry_type_label) {
match(
geometry_type_label,
c(
"point", "linestring", "polygon",
"multipoint", "multilinestring", "multipolygon",
"geometrycollection"
)
)
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/meta.R
|
#' Orient polygon coordinates
#'
#' @inheritParams wk_handle
#' @param direction The winding polygon winding direction
#'
#' @return `handleable` with consistently oriented polygons, in `direction`
#' winding order.
#' @export
#'
#' @examples
#' wk_orient(wkt("POLYGON ((0 0, 1 0, 1 1, 0 1, 0 0))"))
#' wk_orient(
#' wkt("POLYGON ((0 0, 0 1, 1 1, 1 0, 0 0))"),
#' direction = wk_clockwise()
#' )
#'
wk_orient <- function(handleable, ..., direction = wk_counterclockwise()) {
result <- wk_handle(
handleable,
wk_orient_filter(wk_writer(handleable), direction),
...
)
result <- wk_restore(handleable, result, ...)
result <- wk_set_geodesic(result, wk_is_geodesic(handleable))
wk_set_crs(result, wk_crs(handleable))
}
#' @rdname wk_orient
#' @export
wk_orient_filter <- function(handler, direction = wk_counterclockwise()) {
stopifnot(direction %in% c(wk_clockwise(), wk_counterclockwise()))
new_wk_handler(
.Call(
wk_c_orient_filter_new,
as_wk_handler(handler),
as.integer(direction)[1]
),
"wk_orient_filter"
)
}
#' @rdname wk_orient
#' @export
wk_clockwise <- function() {
-1L
}
#' @rdname wk_orient
#' @export
wk_counterclockwise <- function() {
1L
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/orient-filter.R
|
# registered in zzz.R
output_column_wk <- function(x) {
out <- as.character(as_wkt(x))
out[is.na(x)] <- NA_character_
out
}
output_column.wk_wkt <- function(x, name) {
output_column_wk(x)
}
output_column.wk_wkb <- function(x, name) {
output_column_wk(x)
}
output_column.wk_xy <- function(x, name) {
output_column_wk(x)
}
output_column.wk_crc <- function(x, name) {
output_column_wk(x)
}
output_column.wk_rct <- function(x, name) {
output_column_wk(x)
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/pkg-readr.R
|
#' @rdname wk_handle
#' @export
wk_handle.sfg <- function(handleable, handler, ...) {
wk_handle(sf::st_sfc(handleable), handler, ...)
}
#' @rdname wk_handle
#' @export
wk_handle.sf <- function(handleable, handler, ...) {
wk_handle(sf::st_geometry(handleable), handler, ...)
}
#' @rdname wk_handle
#' @export
wk_handle.bbox <- function(handleable, handler, ...) {
wk_handle(as_rct(handleable), handler, ...)
}
#' @rdname wk_writer
#' @export
wk_writer.sfc <- function(handleable, ...) {
sfc_writer()
}
#' @rdname wk_writer
#' @export
wk_writer.sf <- function(handleable, ...) {
sfc_writer()
}
#' @rdname wk_translate
#' @export
wk_translate.sfc <- function(handleable, to, ...) {
result <- wk_handle(handleable, sfc_writer(), ...)
attr(result, "crs") <- sf::st_crs(wk_crs_output(handleable, to))
result
}
#' @rdname wk_handle.data.frame
#' @export
wk_translate.sf <- function(handleable, to, ...) {
col_value <- wk_handle(handleable, sfc_writer(), ...)
crs_out <- sf::st_crs(wk_crs_output(handleable, to))
if (inherits(handleable, "sf")) {
sf::st_geometry(handleable) <- col_value
} else if (inherits(handleable, "data.frame")) {
col <- handleable_column_name(handleable)
handleable[col] <- list(col_value)
handleable <- sf::st_as_sf(handleable, sf_column_name = col)
} else {
handleable <- sf::st_as_sf(data.frame(geometry = col_value))
}
sf::st_crs(handleable) <- crs_out
handleable
}
#' @rdname wk_handle.data.frame
#' @export
wk_restore.sf <- function(handleable, result, ...) {
col <- handleable_column_name(handleable)
if(nrow(handleable) == length(result)) {
sf::st_geometry(handleable) <- result
handleable
} else if (nrow(handleable) == 1) {
handleable <- handleable[rep(1L, length(result)), , drop = FALSE]
sf::st_geometry(handleable) <- result
handleable
} else {
stop(
sprintf(
"Can't assign result of length %d to sf with %d rows",
length(result), nrow(handleable)
),
call. = FALSE
)
}
}
#' @export
wk_crs.sfc <- function(x) {
sf::st_crs(x)
}
#' @export
wk_set_crs.sfc <- function(x, crs) {
sf::st_crs(x) <- sf::st_crs(crs)
x
}
#' @export
wk_crs.sf <- function(x) {
sf::st_crs(x)
}
#' @export
wk_set_crs.sf <- function(x, crs) {
sf::st_crs(x) <- sf::st_crs(crs)
x
}
#' @export
wk_crs.sfg <- function(x) {
sf::NA_crs_
}
#' @export
as_wkb.sfc <- function(x, ...) {
wk_translate(x, new_wk_wkb(crs = wk_crs_inherit()))
}
#' @export
as_wkb.sfg <- function(x, ...) {
wk_translate(x, new_wk_wkb(crs = wk_crs_inherit()))
}
#' @export
wk_crs_equal_generic.crs <- function(x, y, ...) {
x == sf::st_crs(y)
}
#' @export
wk_crs_proj_definition.crs <- function(crs, proj_version = NULL, verbose = FALSE) {
if (is.na(crs)) {
wk_crs_proj_definition(NULL)
} else if (isTRUE(verbose)) {
crs$Wkt %||% crs$wkt
} else if (isTRUE(is.na(crs$epsg)) || isTRUE(grepl("^[0-9A-Za-z]+:[0-9A-Za-z]+$", crs$input))) {
wk_crs_proj_definition(crs$input)
} else {
paste0("EPSG:", crs$epsg)
}
}
#' @export
wk_crs_projjson.crs <- function(crs) {
json <- crs$ProjJson
if (is.null(json)) {
# i.e., GDAL is not >= 3.1.0
NextMethod()
} else {
json
}
}
wk_crs_from_sf <- function(x) {
crs <- sf::st_crs(x)
if (is.na(crs)) NULL else crs
}
sf_crs_from_wk <- function(x) {
sf::st_crs(wk_crs(x))
}
#' @export
as_xy.sfc <- function(x, ...) {
if (length(x) == 0) {
xy(crs = wk_crs_from_sf(x))
} else if (inherits(x, "sfc_POINT")) {
coords <- sf::st_coordinates(x)
dims <- colnames(coords)
dimnames(coords) <- NULL
if (anyNA(coords)) {
coords[is.na(coords)] <- NaN
}
if (identical(dims, c("X", "Y"))) {
new_wk_xy(
list(
x = coords[, 1, drop = TRUE],
y = coords[, 2, drop = TRUE]
),
crs = wk_crs_from_sf(x)
)
} else if (identical(dims, c("X", "Y", "Z"))) {
new_wk_xyz(
list(
x = coords[, 1, drop = TRUE],
y = coords[, 2, drop = TRUE],
z = coords[, 3, drop = TRUE]
),
crs = wk_crs_from_sf(x)
)
} else if (identical(dims, c("X", "Y", "M"))) {
new_wk_xym(
list(
x = coords[, 1, drop = TRUE],
y = coords[, 2, drop = TRUE],
m = coords[, 3, drop = TRUE]
),
crs = wk_crs_from_sf(x)
)
} else if (identical(dims, c("X", "Y", "Z", "M"))) {
new_wk_xyzm(
list(
x = coords[, 1, drop = TRUE],
y = coords[, 2, drop = TRUE],
z = coords[, 3, drop = TRUE],
m = coords[, 4, drop = TRUE]
),
crs = wk_crs_from_sf(x)
)
} else {
stop("Unknown dimensions.", call. = FALSE) # nocov
}
} else {
NextMethod()
}
}
#' @export
as_rct.bbox <- function(x, ...) {
x_bare <- unclass(x)
new_wk_rct(as.list(x_bare[c("xmin", "ymin", "xmax", "ymax")]), crs = wk_crs_from_sf(x))
}
#' @export
as_wkb.sf <- function(x, ...) {
as_wkb(sf::st_geometry(x), ...)
}
#' @export
as_wkt.sf <- function(x, ...) {
as_wkt(sf::st_geometry(x), ...)
}
#' @export
as_xy.sf <- function(x, ..., dims = NULL) {
as_xy(sf::st_geometry(x), ..., dims = dims)
}
# dynamically exported
st_as_sfc.wk_wkb <- function(x, ...) {
sf::st_set_crs(wk_handle(x, sfc_writer()), sf_crs_from_wk(x))
}
st_as_sf.wk_wkb <- function(x, ...) {
sf::st_as_sf(
new_data_frame(
list(geometry = st_as_sfc.wk_wkb(x, ...))
)
)
}
st_as_sfc.wk_wkt <- function(x, ...) {
sf::st_set_crs(wk_handle(x, sfc_writer()), sf_crs_from_wk(x))
}
st_as_sf.wk_wkt <- function(x, ...) {
sf::st_as_sf(
new_data_frame(
list(geometry = st_as_sfc.wk_wkt(x, ...))
)
)
}
st_as_sfc.wk_xy <- function(x, ...) {
if (all(!is.na(x))) {
st_as_sf.wk_xy(x, ...)$geometry
} else {
sf::st_as_sfc(as_wkb(x), ...)
}
}
st_as_sf.wk_xy <- function(x, ...) {
is_na_or_nan <- Reduce("&", lapply(unclass(x), is.na))
if ((length(x) > 0) && all(!is_na_or_nan)) {
sf::st_as_sf(as.data.frame(x), coords = xy_dims(x), crs = sf_crs_from_wk(x))
} else {
sf::st_as_sf(
new_data_frame(
list(geometry = sf::st_as_sfc(as_wkb(x), ...))
)
)
}
}
st_as_sfc.wk_rct <- function(x, ...) {
sf::st_set_crs(wk_handle(x, sfc_writer()), sf_crs_from_wk(x))
}
st_as_sfc.wk_crc <- function(x, ...) {
sf::st_set_crs(wk_handle(x, sfc_writer()), sf_crs_from_wk(x))
}
st_as_sf.wk_rct <- function(x, ...) {
sf::st_as_sf(
new_data_frame(
list(geometry = st_as_sfc.wk_rct(x, ...))
)
)
}
st_as_sf.wk_crc <- function(x, ...) {
sf::st_as_sf(
new_data_frame(
list(geometry = st_as_sfc.wk_crc(x, ...))
)
)
}
st_as_sfc.wk_grd <- function(x, ...) {
result <- wk_handle(x, sfc_writer())
sf::st_crs(result) <- sf::st_crs(wk_crs(x))
result
}
st_as_sf.wk_grd <- function(x, ...) {
sf::st_as_sf(data.frame(geometry = st_as_sfc.wk_grd(x)))
}
# st_geometry methods()
st_geometry.wk_wkb <- function(x, ...) {
st_as_sfc.wk_wkb(x, ...)
}
st_geometry.wk_wkt <- function(x, ...) {
st_as_sfc.wk_wkt(x, ...)
}
st_geometry.wk_xy <- function(x, ...) {
st_as_sfc.wk_xy(x, ...)
}
st_geometry.wk_rct <- function(x, ...) {
st_as_sfc.wk_rct(x, ...)
}
st_geometry.wk_crc <- function(x, ...) {
st_as_sfc.wk_crc(x, ...)
}
st_geometry.wk_grd <- function(x, ...) {
st_as_sfc.wk_grd(x)
}
# st_bbox() methods
st_bbox.wk_wkb <- function(x, ...) {
sf::st_bbox(wk_bbox(x))
}
st_bbox.wk_wkt <- function(x, ...) {
sf::st_bbox(wk_bbox(x))
}
st_bbox.wk_xy <- function(x, ...) {
sf::st_bbox(wk_bbox(x))
}
st_bbox.wk_rct <- function(x, ...) {
sf::st_bbox(unlist(x), crs = wk_crs(x))
}
st_bbox.wk_crc <- function(x, ...) {
sf::st_bbox(wk_bbox(x))
}
st_bbox.wk_grd <- function(x, ...) {
sf::st_bbox(wk_bbox(x))
}
# st_crs() methods
st_crs.wk_wkb <- function(x, ...) {
sf::st_crs(wk_crs(x))
}
st_crs.wk_wkt <- function(x, ...) {
sf::st_crs(wk_crs(x))
}
st_crs.wk_xy <- function(x, ...) {
sf::st_crs(wk_crs(x))
}
st_crs.wk_rct <- function(x, ...) {
sf::st_crs(wk_crs(x))
}
st_crs.wk_crc <- function(x, ...) {
sf::st_crs(wk_crs(x))
}
st_crs.wk_grd <- function(x, ...) {
sf::st_crs(wk_crs(x$bbox))
}
# st_crs<-() methods
`st_crs<-.wk_wkb` <- function(x, value) {
wk_set_crs(x, sf::st_crs(value))
}
`st_crs<-.wk_wkt` <- function(x, value) {
wk_set_crs(x, sf::st_crs(value))
}
`st_crs<-.wk_xy` <- function(x, value) {
wk_set_crs(x, sf::st_crs(value))
}
`st_crs<-.wk_rct` <- function(x, value) {
wk_set_crs(x, sf::st_crs(value))
}
`st_crs<-.wk_crc` <- function(x, value) {
wk_set_crs(x, sf::st_crs(value))
}
`st_crs<-.wk_grd` <- function(x, value) {
wk_set_crs(x, sf::st_crs(value))
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/pkg-sf.R
|
#' Vctrs methods
#'
#' @param x,y,to,... See [vctrs::vec_cast()] and [vctrs::vec_ptype2()].
#' @rdname vctrs-methods
#' @name vctrs-methods
#'
NULL
# wkb() --------
vec_proxy.wk_wkb <- function(x, ...) {
unclass(x)
}
vec_proxy_equal.wk_wkb <- function(x, ...) {
wkb_to_hex(x)
}
vec_restore.wk_wkb <- function(x, to, ...) {
crs_out <- attr(to, "crs", exact = TRUE) %||% attr(x, "crs", exact = TRUE)
geodesic_out <- attr(to, "geodesic", exact = TRUE) %||% attr(x, "geodesic", exact = TRUE)
attr(x, "crs") <- NULL
attr(x, "geodesic") <- NULL
new_wk_wkb(x, crs = crs_out, geodesic = geodesic_out)
}
#' @rdname vctrs-methods
#' @export vec_cast.wk_wkb
vec_cast.wk_wkb <- function(x, to, ...) {
UseMethod("vec_cast.wk_wkb") # nocov
}
#' @method vec_cast.wk_wkb default
#' @export
vec_cast.wk_wkb.default <- function(x, to, ...) {
vctrs::vec_default_cast(x, to) # nocov
}
#' @method vec_cast.wk_wkb wk_wkb
#' @export
vec_cast.wk_wkb.wk_wkb <- function(x, to, ...) {
wk_crs_output(x, to)
wk_is_geodesic_output(x, to)
x
}
#' @method vec_cast.wk_wkb wk_wkt
#' @export
vec_cast.wk_wkb.wk_wkt <- function(x, to, ...) {
wk_crs_output(x, to)
wk_is_geodesic_output(x, to)
as_wkb(x)
}
#' @method vec_cast.wk_wkb wk_xy
#' @export
vec_cast.wk_wkb.wk_xy <- function(x, to, ...) {
wk_translate(x, to)
}
#' @method vec_cast.wk_wkb wk_xyz
#' @export
vec_cast.wk_wkb.wk_xyz <- function(x, to, ...) {
wk_translate(x, to)
}
#' @method vec_cast.wk_wkb wk_xym
#' @export
vec_cast.wk_wkb.wk_xym <- function(x, to, ...) {
wk_translate(x, to)
}
#' @method vec_cast.wk_wkb wk_xyzm
#' @export
vec_cast.wk_wkb.wk_xyzm <- function(x, to, ...) {
wk_translate(x, to)
}
#' @method vec_cast.wk_wkb wk_rct
#' @export
vec_cast.wk_wkb.wk_rct <- function(x, to, ...) {
wk_translate(x, to)
}
#' @method vec_cast.wk_wkb wk_crc
#' @export
vec_cast.wk_wkb.wk_crc <- function(x, to, ...) {
wk_crs_output(x, to)
as_wkb(x)
}
#' @rdname vctrs-methods
#' @export vec_ptype2.wk_wkb
vec_ptype2.wk_wkb <- function(x, y, ...) {
UseMethod("vec_ptype2.wk_wkb", y) # nocov
}
#' @method vec_ptype2.wk_wkb default
#' @export
vec_ptype2.wk_wkb.default <- function(x, y, ..., x_arg = "x", y_arg = "y") {
vctrs::vec_default_ptype2(x, y, x_arg = x_arg, y_arg = y_arg) # nocov
}
#' @method vec_ptype2.wk_wkb wk_wkb
#' @export
vec_ptype2.wk_wkb.wk_wkb <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y), geodesic = geodesic_attr(wk_is_geodesic_output(x, y)))
}
#' @method vec_ptype2.wk_wkb wk_wkt
#' @export
vec_ptype2.wk_wkb.wk_wkt <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y), geodesic = geodesic_attr(wk_is_geodesic_output(x, y)))
}
#' @method vec_ptype2.wk_wkb wk_xy
#' @export
vec_ptype2.wk_wkb.wk_xy <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y), geodesic = attr(x, "geodesic", exact = TRUE))
}
#' @method vec_ptype2.wk_wkb wk_xyz
#' @export
vec_ptype2.wk_wkb.wk_xyz <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y), geodesic = attr(x, "geodesic", exact = TRUE))
}
#' @method vec_ptype2.wk_wkb wk_xym
#' @export
vec_ptype2.wk_wkb.wk_xym <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y), geodesic = attr(x, "geodesic", exact = TRUE))
}
#' @method vec_ptype2.wk_wkb wk_xyzm
#' @export
vec_ptype2.wk_wkb.wk_xyzm <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y), geodesic = attr(x, "geodesic", exact = TRUE))
}
#' @method vec_ptype2.wk_wkb wk_rct
#' @export
vec_ptype2.wk_wkb.wk_rct <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y), geodesic = geodesic_attr(wk_is_geodesic_output(x, y)))
}
#' @method vec_ptype2.wk_wkb wk_crc
#' @export
vec_ptype2.wk_wkb.wk_crc <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y), geodesic = attr(x, "geodesic", exact = TRUE))
}
# wkt() --------
vec_proxy.wk_wkt <- function(x, ...) {
unclass(x)
}
vec_restore.wk_wkt <- function(x, to, ...) {
crs_out <- attr(to, "crs", exact = TRUE) %||% attr(x, "crs", exact = TRUE)
geodesic_out <- attr(to, "geodesic", exact = TRUE) %||% attr(x, "geodesic", exact = TRUE)
attr(x, "crs") <- NULL
attr(x, "geodesic") <- NULL
new_wk_wkt(x, crs = crs_out, geodesic = geodesic_out)
}
#' @rdname vctrs-methods
#' @export vec_cast.wk_wkt
vec_cast.wk_wkt <- function(x, to, ...) {
UseMethod("vec_cast.wk_wkt") # nocov
}
#' @method vec_cast.wk_wkt default
#' @export
vec_cast.wk_wkt.default <- function(x, to, ...) {
vctrs::vec_default_cast(x, to) # nocov
}
#' @method vec_cast.wk_wkt wk_wkt
#' @export
vec_cast.wk_wkt.wk_wkt <- function(x, to, ...) {
wk_crs_output(x, to)
wk_is_geodesic_output(x, to)
x
}
#' @method vec_cast.wk_wkt wk_wkb
#' @export
vec_cast.wk_wkt.wk_wkb <- function(x, to, ...) {
wk_crs_output(x, to)
wk_is_geodesic_output(x, to)
as_wkt(x)
}
#' @method vec_cast.wk_wkt wk_xy
#' @export
vec_cast.wk_wkt.wk_xy <- function(x, to, ...) {
wk_translate(x, to)
}
#' @method vec_cast.wk_wkt wk_xyz
#' @export
vec_cast.wk_wkt.wk_xyz <- function(x, to, ...) {
wk_translate(x, to)
}
#' @method vec_cast.wk_wkt wk_xym
#' @export
vec_cast.wk_wkt.wk_xym <- function(x, to, ...) {
wk_translate(x, to)
}
#' @method vec_cast.wk_wkt wk_xyzm
#' @export
vec_cast.wk_wkt.wk_xyzm <- function(x, to, ...) {
wk_translate(x, to)
}
#' @method vec_cast.wk_wkt wk_rct
#' @export
vec_cast.wk_wkt.wk_rct <- function(x, to, ...) {
wk_translate(x, to)
}
#' @method vec_cast.wk_wkt wk_crc
#' @export
vec_cast.wk_wkt.wk_crc <- function(x, to, ...) {
wk_translate(x, to)
}
#' @rdname vctrs-methods
#' @export vec_ptype2.wk_wkt
vec_ptype2.wk_wkt <- function(x, y, ...) {
UseMethod("vec_ptype2.wk_wkt", y) # nocov
}
#' @method vec_ptype2.wk_wkt default
#' @export
vec_ptype2.wk_wkt.default <- function(x, y, ..., x_arg = "x", y_arg = "y") {
vctrs::vec_default_ptype2(x, y, x_arg = x_arg, y_arg = y_arg) # nocov
}
#' @method vec_ptype2.wk_wkt wk_wkt
#' @export
vec_ptype2.wk_wkt.wk_wkt <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y), geodesic = geodesic_attr(wk_is_geodesic_output(x, y)))
}
#' @method vec_ptype2.wk_wkt wk_wkb
#' @export
vec_ptype2.wk_wkt.wk_wkb <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y), geodesic = geodesic_attr(wk_is_geodesic_output(x, y)))
}
#' @method vec_ptype2.wk_wkt wk_xy
#' @export
vec_ptype2.wk_wkt.wk_xy <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y), geodesic = attr(x, "geodesic", exact = TRUE))
}
#' @method vec_ptype2.wk_wkt wk_xyz
#' @export
vec_ptype2.wk_wkt.wk_xyz <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y), geodesic = attr(x, "geodesic", exact = TRUE))
}
#' @method vec_ptype2.wk_wkt wk_xym
#' @export
vec_ptype2.wk_wkt.wk_xym <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y), geodesic = attr(x, "geodesic", exact = TRUE))
}
#' @method vec_ptype2.wk_wkt wk_xyzm
#' @export
vec_ptype2.wk_wkt.wk_xyzm <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y), geodesic = attr(x, "geodesic", exact = TRUE))
}
#' @method vec_ptype2.wk_wkt wk_rct
#' @export
vec_ptype2.wk_wkt.wk_rct <- function(x, y, ..., x_arg = "x", y_arg = "y") {
wk_is_geodesic_output(x, y)
new_wk_wkt(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_wkt wk_crc
#' @export
vec_ptype2.wk_wkt.wk_crc <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y), geodesic = attr(x, "geodesic", exact = TRUE))
}
# xy() --------
vec_proxy.wk_xy <- function(x, ...) {
new_data_frame(unclass(x))
}
vec_restore.wk_xy <- function(x, to, ...) {
crs_out <- attr(to, "crs", exact = TRUE) %||% attr(x, "crs", exact = TRUE)
attr(x, "crs") <- NULL
attr(x, "row.names") <- NULL
new_wk_xy(x, crs = crs_out)
}
#' @rdname vctrs-methods
#' @export vec_cast.wk_xy
vec_cast.wk_xy <- function(x, to, ...) {
UseMethod("vec_cast.wk_xy") # nocov
}
#' @method vec_cast.wk_xy default
#' @export
vec_cast.wk_xy.default <- function(x, to, ...) {
vctrs::vec_default_cast(x, to) # nocov
}
#' @method vec_cast.wk_xy wk_xy
#' @export
vec_cast.wk_xy.wk_xy <- function(x, to, ...) {
wk_crs_output(x, to)
x
}
#' @method vec_cast.wk_xy wk_wkb
#' @export
vec_cast.wk_xy.wk_wkb <- function(x, to, ...) {
wk_crs_output(x, to)
as_xy(x)
}
#' @method vec_cast.wk_xy wk_wkt
#' @export
vec_cast.wk_xy.wk_wkt <- function(x, to, ...) {
wk_crs_output(x, to)
as_xy(x)
}
#' @method vec_cast.wk_xy wk_xyz
#' @export
vec_cast.wk_xy.wk_xyz <- function(x, to, ...) {
wk_crs_output(x, to)
vctrs::maybe_lossy_cast(
as_xy(x, dims = c("x", "y")),
x, to,
!is.na(unclass(x)$z)
)
}
#' @method vec_cast.wk_xy wk_xym
#' @export
vec_cast.wk_xy.wk_xym <- function(x, to, ...) {
wk_crs_output(x, to)
vctrs::maybe_lossy_cast(
as_xy(x, dims = c("x", "y")),
x, to,
!is.na(unclass(x)$m)
)
}
#' @method vec_cast.wk_xy wk_xyzm
#' @export
vec_cast.wk_xy.wk_xyzm <- function(x, to, ...) {
wk_crs_output(x, to)
vctrs::maybe_lossy_cast(
as_xy(x, dims = c("x", "y")),
x, to,
!is.na(unclass(x)$z) & !is.na(unclass(x)$m)
)
}
#' @rdname vctrs-methods
#' @export vec_ptype2.wk_xy
vec_ptype2.wk_xy <- function(x, y, ...) {
UseMethod("vec_ptype2.wk_xy", y) # nocov
}
#' @method vec_ptype2.wk_xy wk_xy
#' @export
vec_ptype2.wk_xy.wk_xy <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xy(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_xy wk_wkb
#' @export
vec_ptype2.wk_xy.wk_wkb <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y), geodesic = attr(y, "geodesic", exact = TRUE))
}
#' @method vec_ptype2.wk_xy wk_wkt
#' @export
vec_ptype2.wk_xy.wk_wkt <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y), geodesic = attr(y, "geodesic", exact = TRUE))
}
#' @method vec_ptype2.wk_xy wk_xyz
#' @export
vec_ptype2.wk_xy.wk_xyz <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xyz(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_xy wk_xym
#' @export
vec_ptype2.wk_xy.wk_xym <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xym(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_xy wk_xyzm
#' @export
vec_ptype2.wk_xy.wk_xyzm <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xyzm(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_xy wk_rct
#' @export
vec_ptype2.wk_xy.wk_rct <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_xy wk_crc
#' @export
vec_ptype2.wk_xy.wk_crc <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
# xyz() --------
vec_proxy.wk_xyz <- function(x, ...) {
new_data_frame(unclass(x))
}
vec_restore.wk_xyz <- function(x, to, ...) {
crs_out <- attr(to, "crs", exact = TRUE) %||% attr(x, "crs", exact = TRUE)
attr(x, "crs") <- NULL
attr(x, "row.names") <- NULL
new_wk_xyz(x, crs = crs_out)
}
#' @rdname vctrs-methods
#' @export vec_cast.wk_xyz
vec_cast.wk_xyz <- function(x, to, ...) {
UseMethod("vec_cast.wk_xyz") # nocov
}
#' @method vec_cast.wk_xyz default
#' @export
vec_cast.wk_xyz.default <- function(x, to, ...) {
vctrs::vec_default_cast(x, to) # nocov
}
#' @method vec_cast.wk_xyz wk_xyz
#' @export
vec_cast.wk_xyz.wk_xyz <- function(x, to, ...) {
wk_crs_output(x, to)
x
}
#' @method vec_cast.wk_xyz wk_wkb
#' @export
vec_cast.wk_xyz.wk_wkb <- function(x, to, ...) {
wk_crs_output(x, to)
as_xy(x, dims = c("x", "y", "z"))
}
#' @method vec_cast.wk_xyz wk_wkt
#' @export
vec_cast.wk_xyz.wk_wkt <- function(x, to, ...) {
wk_crs_output(x, to)
as_xy(x, dims = c("x", "y", "z"))
}
#' @method vec_cast.wk_xyz wk_xy
#' @export
vec_cast.wk_xyz.wk_xy <- function(x, to, ...) {
wk_crs_output(x, to)
as_xy(x, dims = c("x", "y", "z"))
}
#' @method vec_cast.wk_xyz wk_xym
#' @export
vec_cast.wk_xyz.wk_xym <- function(x, to, ...) {
wk_crs_output(x, to)
vctrs::maybe_lossy_cast(
as_xy(x, dims = c("x", "y", "z")),
x, to,
!is.na(unclass(x)$m)
)
}
#' @method vec_cast.wk_xyz wk_xyzm
#' @export
vec_cast.wk_xyz.wk_xyzm <- function(x, to, ...) {
wk_crs_output(x, to)
vctrs::maybe_lossy_cast(
as_xy(x, dims = c("x", "y", "z")),
x, to,
!is.na(unclass(x)$m)
)
}
#' @rdname vctrs-methods
#' @export vec_ptype2.wk_xyz
vec_ptype2.wk_xyz <- function(x, y, ...) {
UseMethod("vec_ptype2.wk_xyz", y) # nocov
}
#' @method vec_ptype2.wk_xyz wk_xyz
#' @export
vec_ptype2.wk_xyz.wk_xyz <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xyz(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_xyz wk_wkb
#' @export
vec_ptype2.wk_xyz.wk_wkb <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y), geodesic = attr(y, "geodesic", exact = TRUE))
}
#' @method vec_ptype2.wk_xyz wk_wkt
#' @export
vec_ptype2.wk_xyz.wk_wkt <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y), geodesic = attr(y, "geodesic", exact = TRUE))
}
#' @method vec_ptype2.wk_xyz wk_xy
#' @export
vec_ptype2.wk_xyz.wk_xy <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xyz(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_xyz wk_xym
#' @export
vec_ptype2.wk_xyz.wk_xym <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xyzm(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_xyz wk_xyzm
#' @export
vec_ptype2.wk_xyz.wk_xyzm <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xyzm(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_xyz wk_rct
#' @export
vec_ptype2.wk_xyz.wk_rct <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_xyz wk_crc
#' @export
vec_ptype2.wk_xyz.wk_crc <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
# xym() --------
vec_proxy.wk_xym <- function(x, ...) {
new_data_frame(unclass(x))
}
vec_restore.wk_xym <- function(x, to, ...) {
crs_out <- attr(to, "crs", exact = TRUE) %||% attr(x, "crs", exact = TRUE)
attr(x, "crs") <- NULL
attr(x, "row.names") <- NULL
new_wk_xym(x, crs = crs_out)
}
#' @rdname vctrs-methods
#' @export vec_cast.wk_xym
vec_cast.wk_xym <- function(x, to, ...) {
UseMethod("vec_cast.wk_xym") # nocov
}
#' @method vec_cast.wk_xym default
#' @export
vec_cast.wk_xym.default <- function(x, to, ...) {
vctrs::vec_default_cast(x, to) # nocov
}
#' @method vec_cast.wk_xym wk_xym
#' @export
vec_cast.wk_xym.wk_xym <- function(x, to, ...) {
wk_crs_output(x, to)
x
}
#' @method vec_cast.wk_xym wk_wkb
#' @export
vec_cast.wk_xym.wk_wkb <- function(x, to, ...) {
wk_crs_output(x, to)
as_xy(x, dims = c("x", "y", "m"))
}
#' @method vec_cast.wk_xym wk_wkt
#' @export
vec_cast.wk_xym.wk_wkt <- function(x, to, ...) {
wk_crs_output(x, to)
as_xy(x, dims = c("x", "y", "m"))
}
#' @method vec_cast.wk_xym wk_xy
#' @export
vec_cast.wk_xym.wk_xy <- function(x, to, ...) {
wk_crs_output(x, to)
as_xy(x, dims = c("x", "y", "m"))
}
#' @method vec_cast.wk_xym wk_xyz
#' @export
vec_cast.wk_xym.wk_xyz <- function(x, to, ...) {
wk_crs_output(x, to)
vctrs::maybe_lossy_cast(
as_xy(x, dims = c("x", "y", "m")),
x, to,
!is.na(unclass(x)$z)
)
}
#' @method vec_cast.wk_xym wk_xyzm
#' @export
vec_cast.wk_xym.wk_xyzm <- function(x, to, ...) {
wk_crs_output(x, to)
vctrs::maybe_lossy_cast(
as_xy(x, dims = c("x", "y", "m")),
x, to,
!is.na(unclass(x)$z)
)
}
#' @rdname vctrs-methods
#' @export vec_ptype2.wk_xym
vec_ptype2.wk_xym <- function(x, y, ...) {
UseMethod("vec_ptype2.wk_xym", y) # nocov
}
#' @method vec_ptype2.wk_xym wk_xym
#' @export
vec_ptype2.wk_xym.wk_xym <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xym(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_xym wk_wkb
#' @export
vec_ptype2.wk_xym.wk_wkb <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y), geodesic = attr(y, "geodesic", exact = TRUE))
}
#' @method vec_ptype2.wk_xym wk_wkt
#' @export
vec_ptype2.wk_xym.wk_wkt <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y), geodesic = attr(y, "geodesic", exact = TRUE))
}
#' @method vec_ptype2.wk_xym wk_xy
#' @export
vec_ptype2.wk_xym.wk_xy <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xym(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_xym wk_xyz
#' @export
vec_ptype2.wk_xym.wk_xyz <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xyzm(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_xym wk_xyzm
#' @export
vec_ptype2.wk_xym.wk_xyzm <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xyzm(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_xym wk_rct
#' @export
vec_ptype2.wk_xym.wk_rct <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_xym wk_crc
#' @export
vec_ptype2.wk_xym.wk_crc <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
# xyzm() --------
vec_proxy.wk_xyzm <- function(x, ...) {
new_data_frame(unclass(x))
}
vec_restore.wk_xyzm <- function(x, to, ...) {
crs_out <- attr(to, "crs", exact = TRUE) %||% attr(x, "crs", exact = TRUE)
attr(x, "crs") <- NULL
attr(x, "row.names") <- NULL
new_wk_xyzm(x, crs = crs_out)
}
#' @rdname vctrs-methods
#' @export vec_cast.wk_xyzm
vec_cast.wk_xyzm <- function(x, to, ...) {
UseMethod("vec_cast.wk_xyzm") # nocov
}
#' @method vec_cast.wk_xyzm default
#' @export
vec_cast.wk_xyzm.default <- function(x, to, ...) {
vctrs::vec_default_cast(x, to) # nocov
}
#' @method vec_cast.wk_xyzm wk_xyzm
#' @export
vec_cast.wk_xyzm.wk_xyzm <- function(x, to, ...) {
wk_crs_output(x, to)
x
}
#' @method vec_cast.wk_xyzm wk_wkb
#' @export
vec_cast.wk_xyzm.wk_wkb <- function(x, to, ...) {
wk_crs_output(x, to)
as_xy(x, dims = c("x", "y", "z", "m"))
}
#' @method vec_cast.wk_xyzm wk_wkt
#' @export
vec_cast.wk_xyzm.wk_wkt <- function(x, to, ...) {
wk_crs_output(x, to)
as_xy(x, dims = c("x", "y", "z", "m"))
}
#' @method vec_cast.wk_xyzm wk_xy
#' @export
vec_cast.wk_xyzm.wk_xy <- function(x, to, ...) {
wk_crs_output(x, to)
as_xy(x, dims = c("x", "y", "z", "m"))
}
#' @method vec_cast.wk_xyzm wk_xyz
#' @export
vec_cast.wk_xyzm.wk_xyz <- function(x, to, ...) {
wk_crs_output(x, to)
as_xy(x, dims = c("x", "y", "z", "m"))
}
#' @method vec_cast.wk_xyzm wk_xym
#' @export
vec_cast.wk_xyzm.wk_xym <- function(x, to, ...) {
wk_crs_output(x, to)
as_xy(x, dims = c("x", "y", "z", "m"))
}
#' @rdname vctrs-methods
#' @export vec_ptype2.wk_xyzm
vec_ptype2.wk_xyzm <- function(x, y, ...) {
UseMethod("vec_ptype2.wk_xyzm", y) # nocov
}
#' @method vec_ptype2.wk_xyzm wk_xyzm
#' @export
vec_ptype2.wk_xyzm.wk_xyzm <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xyzm(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_xyzm wk_wkb
#' @export
vec_ptype2.wk_xyzm.wk_wkb <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y), geodesic = attr(y, "geodesic", exact = TRUE))
}
#' @method vec_ptype2.wk_xyzm wk_wkt
#' @export
vec_ptype2.wk_xyzm.wk_wkt <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y), geodesic = attr(y, "geodesic", exact = TRUE))
}
#' @method vec_ptype2.wk_xyzm wk_xy
#' @export
vec_ptype2.wk_xyzm.wk_xy <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xyzm(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_xyzm wk_xyz
#' @export
vec_ptype2.wk_xyzm.wk_xyz <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xyzm(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_xyzm wk_xym
#' @export
vec_ptype2.wk_xyzm.wk_xym <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_xyzm(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_xyzm wk_rct
#' @export
vec_ptype2.wk_xyzm.wk_rct <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_xyzm wk_crc
#' @export
vec_ptype2.wk_xyzm.wk_crc <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
# rct() --------
vec_proxy.wk_rct <- function(x, ...) {
new_data_frame(unclass(x))
}
vec_restore.wk_rct <- function(x, to, ...) {
crs_out <- attr(to, "crs", exact = TRUE) %||% attr(x, "crs", exact = TRUE)
attr(x, "crs") <- NULL
attr(x, "row.names") <- NULL
new_wk_rct(x, crs = crs_out)
}
#' @rdname vctrs-methods
#' @export vec_cast.wk_rct
vec_cast.wk_rct <- function(x, to, ...) {
UseMethod("vec_cast.wk_rct") # nocov
}
#' @method vec_cast.wk_rct default
#' @export
vec_cast.wk_rct.default <- function(x, to, ...) {
vctrs::vec_default_cast(x, to) # nocov
}
#' @rdname vctrs-methods
#' @export vec_ptype2.wk_rct
vec_ptype2.wk_rct <- function(x, y, ...) {
UseMethod("vec_ptype2.wk_rct", y) # nocov
}
#' @method vec_ptype2.wk_rct wk_rct
#' @export
vec_ptype2.wk_rct.wk_rct <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_rct(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_rct wk_wkb
#' @export
vec_ptype2.wk_rct.wk_wkb <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_rct wk_wkt
#' @export
vec_ptype2.wk_rct.wk_wkt <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_rct wk_xy
#' @export
vec_ptype2.wk_rct.wk_xy <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_rct wk_xyz
#' @export
vec_ptype2.wk_rct.wk_xyz <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_rct wk_xym
#' @export
vec_ptype2.wk_rct.wk_xym <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_rct wk_xyzm
#' @export
vec_ptype2.wk_rct.wk_xyzm <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_rct wk_crc
#' @export
vec_ptype2.wk_rct.wk_crc <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
# crc() --------
vec_proxy.wk_crc <- function(x, ...) {
new_data_frame(unclass(x))
}
vec_restore.wk_crc <- function(x, to, ...) {
crs_out <- attr(to, "crs", exact = TRUE) %||% attr(x, "crs", exact = TRUE)
attr(x, "crs") <- NULL
attr(x, "row.names") <- NULL
new_wk_crc(x, crs = crs_out)
}
#' @rdname vctrs-methods
#' @export vec_cast.wk_crc
vec_cast.wk_crc <- function(x, to, ...) {
UseMethod("vec_cast.wk_crc") # nocov
}
#' @method vec_cast.wk_crc default
#' @export
vec_cast.wk_crc.default <- function(x, to, ...) {
vctrs::vec_default_cast(x, to) # nocov
}
#' @rdname vctrs-methods
#' @export vec_ptype2.wk_crc
vec_ptype2.wk_crc <- function(x, y, ...) {
UseMethod("vec_ptype2.wk_crc", y) # nocov
}
#' @method vec_ptype2.wk_crc wk_crc
#' @export
vec_ptype2.wk_crc.wk_crc <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_crc(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_crc wk_wkb
#' @export
vec_ptype2.wk_crc.wk_wkb <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y), geodesic = attr(y, "geodesic", exact = TRUE))
}
#' @method vec_ptype2.wk_crc wk_wkt
#' @export
vec_ptype2.wk_crc.wk_wkt <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkt(crs = wk_crs_output(x, y), geodesic = attr(y, "geodesic", exact = TRUE))
}
#' @method vec_ptype2.wk_crc wk_xy
#' @export
vec_ptype2.wk_crc.wk_xy <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_crc wk_xyz
#' @export
vec_ptype2.wk_crc.wk_xyz <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_crc wk_xym
#' @export
vec_ptype2.wk_crc.wk_xym <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
#' @method vec_ptype2.wk_crc wk_xyzm
#' @export
vec_ptype2.wk_crc.wk_xyzm <- function(x, y, ..., x_arg = "x", y_arg = "y") {
new_wk_wkb(crs = wk_crs_output(x, y))
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/pkg-vctrs.R
|
#' Plot well-known geometry vectors
#'
#' @param x A [wkb()] or [wkt()]
#' @param add Should a new plot be created, or should `handleable` be added to the
#' existing plot?
#' @param ... Passed to plotting functions for features: [graphics::points()]
#' for point and multipoint geometries, [graphics::lines()] for linestring
#' and multilinestring geometries, and [graphics::polypath()] for polygon
#' and multipolygon geometries.
#' @param bbox The limits of the plot as a [rct()] or compatible object
#' @param asp,xlab,ylab Passed to [graphics::plot()]
#' @param rule The rule to use for filling polygons (see [graphics::polypath()])
#' @inheritParams wk_handle
#'
#' @return The input, invisibly.
#' @importFrom graphics plot
#' @export
#'
#' @examples
#' plot(as_wkt("LINESTRING (0 0, 1 1)"))
#' plot(as_wkb("LINESTRING (0 0, 1 1)"))
#'
wk_plot <- function(handleable, ...,
asp = 1, bbox = NULL, xlab = "", ylab = "",
rule = "evenodd", add = FALSE) {
UseMethod("wk_plot")
}
#' @rdname wk_plot
#' @export
wk_plot.default <- function(handleable, ...,
asp = 1, bbox = NULL, xlab = "", ylab = "",
rule = "evenodd", add = FALSE) {
# this is too hard without vctrs (already in Suggests)
if (!requireNamespace("vctrs", quietly = TRUE)) {
stop("Package 'vctrs' is required for wk_plot()", call. = FALSE) # nocov
}
if (isTRUE(wk_is_geodesic(handleable))) {
stop(
paste0(
"wk_plot.default() can't plot geodesic objects.\n",
"Use `wk_set_geodesic(x, FALSE)` to ignore geodesic edge specification"
),
call. = FALSE
)
}
# should be refactored
x <- handleable
if (!add) {
bbox <- unclass(bbox)
bbox <- bbox %||% unclass(wk_bbox(x))
xlim <- c(bbox$xmin, bbox$xmax)
ylim <- c(bbox$ymin, bbox$ymax)
graphics::plot(
numeric(0),
numeric(0),
xlim = xlim,
ylim = ylim,
xlab = xlab,
ylab = ylab,
asp = asp
)
}
# for everything below we'll need to be able to subset
if (!vctrs::vec_is(x)) {
wk_plot(as_wkb(x), ..., rule = rule, add = TRUE) # nocov
return(invisible(x)) # nocov
}
# get some background info
size <- vctrs::vec_size(x)
meta <- wk_meta(x)
# points can be handled by as_xy()
if (all(meta$geometry_type == 1L, na.rm = TRUE)) {
coords <- unclass(as_xy(x))
graphics::points(coords, ...)
return(invisible(x))
}
# evaluate the dots
dots <- list(..., rule = rule)
is_scalar <- !vapply(dots, vctrs::vec_is, logical(1))
dots[is_scalar] <- lapply(dots[is_scalar], list)
dots_length <- vapply(dots, vctrs::vec_size, integer(1))
dots_constant <- all(dots_length == 1L)
is_rule <- length(dots)
# point + multipoint is probably faster with a single coord vector
if (all(meta$geometry_type %in% c(1, 4), na.rm = TRUE)) {
coords <- wk_coords(x)
if (dots_constant) {
graphics::points(coords[c("x", "y")], ...)
} else {
dots$rule <- NULL
dots <- vctrs::vec_recycle_common(!!!dots, .size = size)
dots_tbl <- vctrs::new_data_frame(dots, n = size)
do.call(graphics::points, c(coords[c("x", "y")], dots_tbl[coords$feature_id, , drop = FALSE]))
}
return(invisible(x))
}
# it's not faster to flatten big vectors into a single go for anything else
dots <- vctrs::vec_recycle_common(!!!dots, .size = size)
for (i in seq_len(size)) {
xi <- vctrs::vec_slice(x, i)
dotsi <- lapply(dots, "[[", i)
if (meta$geometry_type[i] %in% c(1, 4)) {
wk_plot_point_or_multipoint(xi, dotsi[-is_rule])
} else if (meta$geometry_type[i] %in% c(2, 5)) {
wk_plot_line_or_multiline(xi, dotsi[-is_rule])
} else if (meta$geometry_type[i] %in% c(3, 6)) {
wk_plot_poly_or_multi_poly(xi, dotsi)
} else {
do.call(wk_plot, c(list(wk_flatten(xi, max_depth = .Machine$integer.max), add = TRUE), dotsi))
}
}
invisible(x)
}
wk_plot_point_or_multipoint <- function(x, dots) {
dots_without_border <- dots[setdiff(names(dots), "border")]
coords <- wk_coords(x)
do.call(graphics::points, c(coords[c("x", "y")], dots_without_border))
}
wk_plot_line_or_multiline <- function(x, dots) {
coords <- wk_coords(x)
if (nrow(coords) == 0) {
return()
}
geom_id <- coords$part_id
geom_id_lag <- c(-1L, geom_id[-length(geom_id)])
new_geom <- geom_id != geom_id_lag
na_shift <- cumsum(new_geom) - 1L
coords_seq <- seq_along(geom_id)
coord_x <- rep(NA_real_, length(geom_id) + sum(new_geom) - 1L)
coord_y <- rep(NA_real_, length(geom_id) + sum(new_geom) - 1L)
coord_x[coords_seq + na_shift] <- coords$x
coord_y[coords_seq + na_shift] <- coords$y
dots$rule <- NULL
do.call(graphics::lines, c(list(coord_x, coord_y), dots))
}
wk_plot_poly_or_multi_poly <- function(x, dots) {
coords <- wk_coords(x)
if (nrow(coords) == 0) {
return()
}
# for polygons we can use the coord vectors directly
# because the graphics device expects open loops
geom_id <- coords$ring_id
n <- length(geom_id)
# leave the last loop closed the avoid a trailing NA (which results in error)
geom_id_lead <- c(geom_id[-1L], geom_id[n])
new_geom_next <- geom_id != geom_id_lead
coords$x[new_geom_next] <- NA_real_
coords$y[new_geom_next] <- NA_real_
do.call(graphics::polypath, c(coords[c("x", "y")], dots))
}
#' @rdname wk_plot
#' @export
plot.wk_wkt <- function(x, ..., asp = 1, bbox = NULL, xlab = "", ylab = "",
rule = "evenodd", add = FALSE) {
wk_plot(
x,
...,
asp = asp,
bbox = bbox,
xlab = xlab,
ylab = ylab,
rule = rule,
add = add
)
invisible(x)
}
#' @rdname wk_plot
#' @export
plot.wk_wkb <- function(x, ..., asp = 1, bbox = NULL, xlab = "", ylab = "",
rule = "evenodd", add = FALSE) {
wk_plot(
x,
...,
asp = asp,
bbox = bbox,
xlab = xlab,
ylab = ylab,
rule = rule,
add = add
)
invisible(x)
}
#' @rdname wk_plot
#' @export
plot.wk_xy <- function(x, ..., asp = 1, bbox = NULL, xlab = "", ylab = "", add = FALSE) {
x_bare <- unclass(x)
if (!add) {
graphics::plot(
double(), double(),
xlim = range(x_bare$x, finite = TRUE),
ylim = range(x_bare$y, finite = TRUE),
xlab = xlab,
ylab = ylab,
asp = asp
)
}
graphics::points(x_bare$x, x_bare$y, ...)
invisible(x)
}
#' @rdname wk_plot
#' @export
plot.wk_rct <- function(x, ..., asp = 1, bbox = NULL, xlab = "", ylab = "", add = FALSE) {
x_bare <- unclass(x)
if (!add) {
xlim_min <- range(x_bare$xmin, finite = TRUE)
xlim_max <- range(x_bare$xmax, finite = TRUE)
ylim_min <- range(x_bare$ymin, finite = TRUE)
ylim_max <- range(x_bare$ymax, finite = TRUE)
graphics::plot(
double(), double(),
xlim = range(c(xlim_min, xlim_max), finite = TRUE),
ylim = range(c(ylim_min, ylim_max), finite = TRUE),
xlab = xlab,
ylab = ylab,
asp = asp
)
}
graphics::rect(x_bare$xmin, x_bare$ymin, x_bare$xmax, x_bare$ymax, ...)
invisible(x)
}
#' @rdname wk_plot
#' @export
plot.wk_crc <- function(x, ..., asp = 1, bbox = NULL, xlab = "", ylab = "",
add = FALSE) {
x_bare <- unclass(x)
if (!add) {
xlim_min <- range(x_bare$x + x_bare$r, finite = TRUE)
xlim_max <- range(x_bare$x - x_bare$r, finite = TRUE)
ylim_min <- range(x_bare$y + x_bare$r, finite = TRUE)
ylim_max <- range(x_bare$y - x_bare$r, finite = TRUE)
graphics::plot(
double(), double(),
xlim = range(c(xlim_min, xlim_max), finite = TRUE),
ylim = range(c(ylim_min, ylim_max), finite = TRUE),
xlab = xlab,
ylab = ylab,
asp = asp
)
}
# estimate resolution for turning circles into segments
usr <- graphics::par("usr")
usr_x <- usr[1:2]
usr_y <- usr[3:4]
device_x <- graphics::grconvertX(usr_x, to = "device")
device_y <- graphics::grconvertY(usr_y, to = "device")
# Use resolution of 1 at the device level, scale to usr coords.
# Changing this number to 2 or 4 doesn't really affect the speed
# at which these plot; a value of 1 tends to give very good
# resolution and is acceptable even when a plot in the interactive
# device is zoomed.
scale_x <- diff(device_x) / diff(usr_x)
scale_y <- diff(device_y) / diff(usr_y)
scale <- min(abs(scale_x), abs(scale_y))
resolution_usr <- 1 / scale
plot(
wk_handle(x, wkb_writer(), resolution = resolution_usr),
...,
add = TRUE
)
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/plot.R
|
#' Validate well-known binary and well-known text
#'
#' The problems handler returns a character vector of parse
#' errors and can be used to validate input of any type
#' for which [wk_handle()] is defined.
#'
#' @inheritParams wk_handle
#'
#' @return A character vector of parsing errors. `NA` signifies
#' that there was no parsing error.
#' @export
#'
#' @examples
#' wk_problems(new_wk_wkt(c("POINT EMTPY", "POINT (20 30)")))
#' wk_handle(
#' new_wk_wkt(c("POINT EMTPY", "POINT (20 30)")),
#' wk_problems_handler()
#' )
#'
wk_problems <- function(handleable, ...) {
wk_handle(handleable, wk_problems_handler(), ...)
}
#' @rdname wk_problems
#' @export
wk_problems_handler <- function() {
new_wk_handler(.Call(wk_c_problems_handler_new), "wk_problems_handler")
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/problems.R
|
#' 2D rectangle vectors
#'
#' @param xmin,ymin,xmax,ymax Rectangle bounds.
#' @param x An object to be converted to a [rct()].
#' @param ... Extra arguments passed to `as_rct()`.
#' @inheritParams new_wk_wkb
#'
#' @return A vector along the recycled length of bounds.
#' @export
#'
#' @examples
#' rct(1, 2, 3, 4)
#'
rct <- function(xmin = double(), ymin = double(), xmax = double(), ymax = double(),
crs = wk_crs_auto()) {
vec <- new_wk_rct(
recycle_common(
xmin = as.double(xmin),
ymin = as.double(ymin),
xmax = as.double(xmax),
ymax = as.double(ymax)
),
crs = wk_crs_auto_value(xmin, crs)
)
validate_wk_rct(vec)
vec
}
#' @rdname rct
#' @export
as_rct <- function(x, ...) {
UseMethod("as_rct")
}
#' @rdname rct
#' @export
as_rct.wk_rct <- function(x, ...) {
x
}
#' @rdname rct
#' @export
as_rct.matrix <- function(x, ..., crs = NULL) {
if (ncol(x) == 4) {
colnames(x) <- c("xmin", "ymin", "xmax", "ymax")
}
as_rct(as.data.frame(x), ..., crs = crs)
}
#' @rdname rct
#' @export
as_rct.data.frame <- function(x, ..., crs = NULL) {
stopifnot(all(c("xmin", "ymin", "xmax", "ymax") %in% names(x)))
new_wk_rct(
lapply(x[c("xmin", "ymin", "xmax", "ymax")], as.double),
crs = crs
)
}
validate_wk_rct <- function(x) {
validate_wk_rcrd(x)
stopifnot(
identical(names(unclass(x)), c("xmin", "ymin", "xmax", "ymax"))
)
invisible(x)
}
#' S3 details for rct objects
#'
#' @param x A [rct()]
#' @inheritParams new_wk_wkb
#'
#' @export
#'
new_wk_rct <- function(x = list(xmin = double(), ymin = double(), xmax = double(), ymax = double()),
crs = NULL) {
structure(x, class = c("wk_rct", "wk_rcrd"), crs = crs)
}
#' @export
format.wk_rct <- function(x, ...) {
x <- unclass(x)
sprintf(
"[%s %s %s %s]",
format(x$xmin, ...), format(x$ymin, ...),
format(x$xmax, ...), format(x$ymax, ...)
)
}
#' @export
`[<-.wk_rct` <- function(x, i, value) {
replacement <- as_rct(value)
result <- Map("[<-", unclass(x), i, unclass(replacement))
names(result) <- c("xmin", "ymin", "xmax", "ymax")
new_wk_rct(
result,
crs = wk_crs_output(x, replacement)
)
}
#' Rectangle accessors and operators
#'
#' @param x,y [rct()] vectors
#'
#' @return
#' - `rct_xmin()`, `rct_xmax()`, `rct_ymin()`, and `rct_ymax()` return
#' the components of the [rct()].
#' @export
#'
#' @examples
#' x <- rct(0, 0, 10, 10)
#' y <- rct(5, 5, 15, 15)
#'
#' rct_xmin(x)
#' rct_ymin(x)
#' rct_xmax(x)
#' rct_ymax(x)
#' rct_height(x)
#' rct_width(x)
#' rct_intersects(x, y)
#' rct_intersection(x, y)
#' rct_contains(x, y)
#' rct_contains(x, rct(4, 4, 6, 6))
#'
rct_xmin <- function(x) {
x <- as_rct(x)
unclass(x)$xmin
}
#' @rdname rct_xmin
#' @export
rct_ymin <- function(x) {
x <- as_rct(x)
unclass(x)$ymin
}
#' @rdname rct_xmin
#' @export
rct_xmax <- function(x) {
x <- as_rct(x)
unclass(x)$xmax
}
#' @rdname rct_xmin
#' @export
rct_ymax <- function(x) {
x <- as_rct(x)
unclass(x)$ymax
}
#' @rdname rct_xmin
#' @export
rct_width <- function(x) {
x <- as_rct(x)
x <- unclass(x)
x$xmax - x$xmin
}
#' @rdname rct_xmin
#' @export
rct_height <- function(x) {
x <- as_rct(x)
x <- unclass(x)
x$ymax - x$ymin
}
#' @rdname rct_xmin
#' @export
rct_intersects <- function(x, y) {
x <- as_rct(x)
y <- as_rct(y)
wk_crs_output(x, y)
x <- unclass(x)
y <- unclass(y)
limits <- list(
xmin = pmax(x$xmin, y$xmin),
xmax = pmin(x$xmax, y$xmax),
ymin = pmax(x$ymin, y$ymin),
ymax = pmin(x$ymax, y$ymax)
)
(limits$xmax >= limits$xmin) & (limits$ymax >= limits$ymin)
}
#' @rdname rct_xmin
#' @export
rct_contains <- function(x, y) {
x <- as_rct(x)
y <- wk_envelope(y)
wk_crs_output(x, y)
x <- unclass(x)
y <- unclass(y)
(y$xmin >= x$xmin) &
(y$xmax <= x$xmax) &
(y$ymin >= x$ymin) &
(y$ymax <= x$ymax)
}
#' @rdname rct_xmin
#' @export
rct_intersection <- function(x, y) {
x <- as_rct(x)
y <- as_rct(y)
crs <- wk_crs_output(x, y)
x <- unclass(x)
y <- unclass(y)
limits <- list(
xmin = pmax(x$xmin, y$xmin),
ymin = pmax(x$ymin, y$ymin),
xmax = pmin(x$xmax, y$xmax),
ymax = pmin(x$ymax, y$ymax)
)
any_na <- Reduce("|", lapply(limits, is.na))
not_valid <- any_na | !((limits$xmax >= limits$xmin) & (limits$ymax >= limits$ymin))
limits$xmin[not_valid] <- NA_real_
limits$xmax[not_valid] <- NA_real_
limits$ymin[not_valid] <- NA_real_
limits$ymax[not_valid] <- NA_real_
new_wk_rct(limits, crs = crs)
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/rct.R
|
#' Set coordinate values
#'
#' @inheritParams wk_handle
#' @param z,m A vector of Z or M values applied feature-wise and recycled
#' along `handleable`. Use `NA` to keep the existing value of a given
#' feature.
#' @param value An [xy()], [xyz()], [xym()], or [xyzm()] of coordinates
#' used to replace values in the input. Use `NA` to keep the existing
#' value.
#' @param use_z,use_m Used to declare the output type. Use `TRUE` to
#' ensure the output has that dimension, `FALSE` to ensure it does not,
#' and `NA` to leave the dimension unchanged.
#'
#' @export
#'
#' @examples
#' wk_set_z(wkt("POINT (0 1)"), 2)
#' wk_set_m(wkt("POINT (0 1)"), 2)
#' wk_drop_z(wkt("POINT ZM (0 1 2 3)"))
#' wk_drop_m(wkt("POINT ZM (0 1 2 3)"))
#'
wk_set_z <- function(handleable, z, ...) {
wk_set_base(handleable, wk_trans_set(xyz(NA, NA, z), use_z = TRUE), ...)
}
#' @rdname wk_set_z
#' @export
wk_set_m <- function(handleable, m, ...) {
wk_set_base(handleable, wk_trans_set(xym(NA, NA, m), use_m = TRUE), ...)
}
#' @rdname wk_set_z
#' @export
wk_drop_z <- function(handleable, ...) {
wk_set_base(handleable, wk_trans_set(xy(NA, NA), use_z = FALSE), ...)
}
#' @rdname wk_set_z
#' @export
wk_drop_m <- function(handleable, ...) {
wk_set_base(handleable, wk_trans_set(xy(NA, NA), use_m = FALSE), ...)
}
#' @rdname wk_set_z
#' @export
wk_trans_set <- function(value, use_z = NA, use_m = NA) {
value <- as_xy(value)
value <- as_xy(value, dims = c("x", "y", "z", "m"))
new_wk_trans(
.Call(wk_c_trans_set_new, value, as.logical(use_z)[1], as.logical(use_m)[1]),
"wk_trans_set"
)
}
wk_set_base <- function(handleable, trans, ...) {
result <- wk_handle(handleable, wk_transform_filter(wk_writer(handleable), trans), ...)
wk_set_crs(wk_restore(handleable, result), wk_crs(handleable))
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/set.R
|
#' @rdname wk_writer
#' @export
sfc_writer <- function(promote_multi = FALSE) {
new_wk_handler(.Call(wk_c_sfc_writer_new, as.logical(promote_multi)[1]), "wk_sfc_writer")
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/sfc-writer.R
|
#' Transform using explicit coordinate values
#'
#' A [wk_trans][wk::wk_transform] implementation that replaces coordinate values
#' using a vector of pre-calculated coordinates. This is used to perform generic
#' transforms using R functions and system calls that are impossible or impractical
#' to implement at the C level.
#'
#' @inheritParams wk_trans_set
#'
#' @export
#'
#' @seealso [wk_coords()] which has a replacement version "`wk_coords<-`"
#' @examples
#' trans <- wk_trans_explicit(xy(1:5, 1:5))
#' wk_transform(rep(xy(0, 0), 5), trans)
wk_trans_explicit <- function(value, use_z = NA, use_m = NA) {
value <- wk::as_xy(value)
value <- wk::as_xy(value, dims = c("x", "y", "z", "m"))
wk::new_wk_trans(
.Call(wk_c_trans_explicit_new, value, as.logical(use_z)[1], as.logical(use_m)[1]),
"wk_trans_explicit"
)
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/trans-explicit.R
|
#' Apply coordinate transformations
#'
#' @inheritParams wk_handle
#' @param trans An external pointer to a wk_trans object
#'
#' @export
#'
#' @examples
#' wk_transform(xy(0, 0), wk_affine_translate(2, 3))
#'
wk_transform <- function(handleable, trans, ...) {
result <- wk_handle(
handleable,
wk_transform_filter(wk_writer(handleable), trans),
...
)
wk_restore(handleable, result, ...)
}
#' @rdname wk_transform
#' @export
wk_transform_filter <- function(handler, trans) {
new_wk_handler(
.Call(wk_c_trans_filter_new, as_wk_handler(handler), as_wk_trans(trans)),
"wk_transform_filter"
)
}
#' Generic transform class
#'
#' @param ... Passed to S3 methods
#' @param trans_ptr An external pointer to a wk_trans_t transform
#' struct.
#' @param subclass An optional subclass to apply to the pointer
#' @param x An object to be converted to a transform.
#' @inheritParams wk_transform
#'
#' @export
#'
wk_trans_inverse <- function(trans, ...) {
UseMethod("wk_trans_inverse")
}
#' @rdname wk_trans_inverse
#' @export
as_wk_trans <- function(x, ...) {
UseMethod("as_wk_trans")
}
#' @rdname wk_trans_inverse
#' @export
as_wk_trans.wk_trans <- function(x, ...) {
x
}
#' @rdname wk_trans_inverse
#' @export
new_wk_trans <- function(trans_ptr, subclass = character()) {
stopifnot(typeof(trans_ptr) == "externalptr")
structure(trans_ptr, class = union(subclass, "wk_trans"))
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/transform.R
|
#' Translate geometry vectors
#'
#' @inheritParams wk_handle
#' @param to A prototype object.
#'
#' @export
#'
wk_translate <- function(handleable, to, ...) {
UseMethod("wk_translate", to)
}
#' @rdname wk_translate
#' @export
wk_translate.default <- function(handleable, to, ...) {
result <- wk_handle(handleable, wk_writer(to), ...)
attr(result, "crs") <- wk_crs_output(handleable, to)
wk_set_geodesic(result, wk_is_geodesic_output(handleable, to))
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/translate.R
|
`%||%` <- function(x, y) {
if (is.null(x)) y else x
}
new_data_frame <- function(x) {
structure(x, row.names = c(NA, length(x[[1]])), class = "data.frame")
}
# rep_len became an S3 generic in R 3.6, so we need to use
# something else to make sure recycle_common() works on old
# R versions
rep_len_compat <- function(x, length_out) {
rep(x, length.out = length_out)
}
recycle_common <- function(...) {
dots <- list(...)
lengths <- vapply(dots, length, integer(1))
non_constant_lengths <- unique(lengths[lengths != 1])
if (length(non_constant_lengths) == 0) {
final_length <- 1
} else if(length(non_constant_lengths) == 1) {
final_length <- non_constant_lengths
} else {
lengths_label <- paste0(non_constant_lengths, collapse = ", ")
stop(sprintf("Incompatible lengths: %s", lengths_label))
}
dots[lengths != final_length] <- lapply(dots[lengths != final_length], rep_len_compat, final_length)
dots
}
is_vector_class <- function(x) {
identical(class(x[integer(0)]), class(x))
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/utils.R
|
#' Extract vertices
#'
#' These functions provide ways to extract individual coordinate values.
#' Whereas `wk_vertices()` returns a vector of coordinates as in the same
#' format as the input, `wk_coords()` returns a data frame with coordinates
#' as columns.
#'
#' `wk_coords<-` is the replacement-function version of 'wk_coords'.
#' Using the engine of [wk_trans_explicit()] the coordinates of an object
#' can be transformed in a generic way using R functions as needed.
#'
#' @inheritParams wk_handle
#' @param add_details Use `TRUE` to add a "wk_details" attribute, which
#' contains columns `feature_id`, `part_id`, and `ring_id`.
#' @inheritParams wk_trans_set
#'
#' @return
#' - `wk_vertices()` extracts vertices and returns the in the same format as
#' the handler
#' - `wk_coords()` returns a data frame with columns columns `feature_id`
#' (the index of the feature from whence it came), `part_id` (an arbitrary
#' integer identifying the point, line, or polygon from whence it came),
#' `ring_id` (an arbitrary integer identifying individual rings within
#' polygons), and one column per coordinate (`x`, `y`, and/or `z` and/or `m`).
#' @export
#'
#' @examples
#' wk_vertices(wkt("LINESTRING (0 0, 1 1)"))
#' wk_coords(wkt("LINESTRING (0 0, 1 1)"))
#'
#' # wk_coords() replacement function
#' x <- xy(1:5, 1:5)
#' y <- as_wkt(x)
#' wk_coords(y) <- cbind(5:1, 0:4)
#' wk_coords(x) <- y[5:1]
#' y
#' x
#'
wk_vertices <- function(handleable, ...) {
# the results of this handler are not necessarily the same length as the input,
# so we need to special-case data frames
if (is.data.frame(handleable)) {
result <- wk_handle(
handleable,
wk_vertex_filter(wk_writer(handleable), add_details = TRUE),
...
)
feature_id <- attr(result, "wk_details", exact = TRUE)$feature_id
attr(result, "wk_details") <- NULL
result <- wk_restore(handleable[feature_id, , drop = FALSE], result, ...)
} else {
result <- wk_handle(handleable, wk_vertex_filter(wk_writer(handleable, generic = TRUE)), ...)
result <- wk_restore(handleable, result, ...)
}
wk_set_crs(result, wk_crs(handleable))
}
#' @rdname wk_vertices
#' @export
wk_coords <- function(handleable, ...) {
UseMethod("wk_coords")
}
#' @export
wk_coords.default <- function(handleable, ...) {
result <- wk_handle(
handleable,
wk_vertex_filter(xy_writer(), add_details = TRUE),
...
)
details <- attr(result, "wk_details", exact = TRUE)
attr(result, "wk_details") <- NULL
new_data_frame(c(details, unclass(result)))
}
#' @rdname wk_vertices
#' @export
`wk_coords<-` <- function(handleable, use_z = NA, use_m = NA, value) {
wk_transform(handleable, wk_trans_explicit(value, use_z = use_z, use_m = use_m))
}
#' @rdname wk_vertices
#' @export
wk_vertex_filter <- function(handler, add_details = FALSE) {
new_wk_handler(
.Call("wk_c_vertex_filter_new", as_wk_handler(handler), as.logical(add_details)[1]),
"wk_vertex_filter"
)
}
#' @export
wk_coords.wk_xy <- function(handleable, ...) {
feature_id <- seq_along(handleable)
is_na <- Reduce("&", lapply(unclass(handleable), is.na))
has_coord <- !is_na
if (!all(has_coord)) {
handleable <- handleable[has_coord]
feature_id <- feature_id[has_coord]
}
new_data_frame(
c(
list(
feature_id = feature_id,
part_id = feature_id,
ring_id = rep_len(0L, length(feature_id))
),
unclass(handleable)
)
)
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/vertex-filter.R
|
#' Do nothing
#'
#' This handler does nothing and returns `NULL`. It is useful for
#' benchmarking readers and handlers and when using filters
#' that have side-effects (e.g., [wk_debug()]). Note that this
#' handler stops on the first parse error; to see a list of parse
#' errors see the [wk_problems()] handler.
#'
#' @inheritParams wk_handle
#'
#' @return `NULL`
#' @export
#'
#' @examples
#' wk_void(wkt("POINT (1 4)"))
#' wk_handle(wkt("POINT (1 4)"), wk_void_handler())
#'
wk_void <- function(handleable, ...) {
invisible(wk_handle(handleable, wk_void_handler(), ...))
}
#' @rdname wk_void
#' @export
wk_void_handler <- function() {
new_wk_handler(.Call(wk_c_handler_void_new), "wk_void_handler")
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/void.R
|
#' Set and get vector CRS
#'
#' The wk package doesn't operate on CRS objects, but does propagate them
#' through subsetting and concatenation. A CRS object can be any R object,
#' and x can be any object whose 'crs' attribute carries a CRS. These functions
#' are S3 generics to keep them from being used
#' on objects that do not use this system of CRS propagation.
#'
#' @param x,... Objects whose "crs" attribute is used to carry a CRS.
#' @param crs An object that can be interpreted as a CRS
#' @param value See `crs`.
#'
#' @export
#'
wk_crs <- function(x) {
UseMethod("wk_crs")
}
#' @rdname wk_crs
#' @export
wk_crs.wk_vctr <- function(x) {
attr(x, "crs", exact = TRUE)
}
#' @rdname wk_crs
#' @export
wk_crs.wk_rcrd <- function(x) {
attr(x, "crs", exact = TRUE)
}
#' @rdname wk_crs
#' @export
`wk_crs<-` <- function(x, value) {
wk_set_crs(x, value)
}
#' @rdname wk_crs
#' @export
wk_set_crs <- function(x, crs) {
UseMethod("wk_set_crs")
}
#' @export
wk_set_crs.wk_vctr <- function(x, crs) {
attr(x, "crs") <- crs
x
}
#' @export
wk_set_crs.wk_rcrd <- function(x, crs) {
attr(x, "crs") <- crs
x
}
#' @rdname wk_crs
#' @export
wk_crs_output <- function(...) {
dots <- list(...)
crs <- lapply(dots, wk_crs)
Reduce(wk_crs2, crs)
}
#' @rdname wk_crs
#' @export
wk_is_geodesic_output <- function(...) {
dots <- list(...)
geodesic <- lapply(dots, wk_is_geodesic)
Reduce(wk_is_geodesic2, geodesic)
}
wk_crs2 <- function(x, y) {
if (inherits(y, "wk_crs_inherit")) {
x
} else if (inherits(x, "wk_crs_inherit")) {
y
} else if (wk_crs_equal(x, y)) {
x
} else {
stop(sprintf("CRS objects '%s' and '%s' are not equal.", format(x), format(y)), call. = FALSE)
}
}
wk_is_geodesic2 <- function(x, y) {
if (identical(x, y)) {
x
} else if (identical(x, NA)) {
y
} else if (identical(y, NA)) {
x
} else {
stop("objects have differing values for geodesic", call. = FALSE)
}
}
#' Compare CRS objects
#'
#' The [wk_crs_equal()] function uses special S3 dispatch on [wk_crs_equal_generic()]
#' to evaluate whether or not two CRS values can be considered equal. When implementing
#' [wk_crs_equal_generic()], every attempt should be made to make `wk_crs_equal(x, y)`
#' and `wk_crs_equal(y, x)` return identically.
#'
#' @param x,y Objects stored in the `crs` attribute of a vector.
#' @param ... Unused
#'
#' @return `TRUE` if `x` and `y` can be considered equal, `FALSE` otherwise.
#' @export
#'
wk_crs_equal <- function(x, y) {
if (is.object(y)) {
wk_crs_equal_generic(y, x)
} else {
wk_crs_equal_generic(x, y)
}
}
#' @rdname wk_crs_equal
#' @export
wk_crs_equal_generic <- function(x, y, ...) {
UseMethod("wk_crs_equal_generic")
}
#' @export
wk_crs_equal_generic.default <- function(x, y, ...) {
identical(x, y)
}
#' @export
wk_crs_equal_generic.integer <- function(x, y, ...) {
isTRUE(x == y)
}
#' @export
wk_crs_equal_generic.double <- function(x, y, ...) {
isTRUE(x == y)
}
#' Set and get vector geodesic edge interpolation
#'
#' @param x An R object that contains edges
#' @param geodesic `TRUE` if edges must be interpolated as geodesics when
#' coordinates are spherical, `FALSE` otherwise.
#' @param value See `geodesic`.
#'
#' @return `TRUE` if edges must be interpolated as geodesics when
#' coordinates are spherical, `FALSE` otherwise.
#' @export
#'
wk_is_geodesic <- function(x) {
UseMethod("wk_is_geodesic")
}
#' @rdname wk_is_geodesic
#' @export
wk_set_geodesic <- function(x, geodesic) {
UseMethod("wk_set_geodesic")
}
#' @rdname wk_is_geodesic
#' @export
`wk_is_geodesic<-` <- function(x, value) {
wk_set_geodesic(x, value)
}
#' @rdname wk_is_geodesic
#' @export
wk_geodesic_inherit <- function() {
NA
}
#' @export
wk_is_geodesic.default <- function(x) {
FALSE
}
#' @export
wk_is_geodesic.wk_wkb <- function(x) {
attr(x, "geodesic", exact = TRUE) %||% FALSE
}
#' @export
wk_is_geodesic.wk_wkt <- function(x) {
attr(x, "geodesic", exact = TRUE) %||% FALSE
}
#' @export
wk_set_geodesic.default <- function(x, geodesic) {
if (geodesic) {
warning(
sprintf(
"Ignoring wk_set_geodesic(x, TRUE) for object of class '%s'",
class(x)[1]
)
)
}
x
}
#' @export
wk_set_geodesic.wk_wkb <- function(x, geodesic) {
attr(x, "geodesic") <- geodesic_attr(geodesic)
x
}
#' @export
wk_set_geodesic.wk_wkt <- function(x, geodesic) {
attr(x, "geodesic") <- geodesic_attr(geodesic)
x
}
geodesic_attr <- function(geodesic) {
if (!is.logical(geodesic) || (length(geodesic) != 1L)) {
stop("`geodesic` must be TRUE, FALSE, or NA", call. = FALSE)
}
if (identical(geodesic, FALSE)) {
NULL
} else {
geodesic
}
}
#' CRS object generic methods
#'
#' @param crs An arbitrary R object
#' @param verbose Use `TRUE` to request a more verbose version of the
#' PROJ definition (e.g., PROJJSON). The default of `FALSE` should return
#' the most compact version that completely describes the CRS. An
#' authority:code string (e.g., "OGC:CRS84") is the recommended way
#' to represent a CRS when `verbose` is `FALSE`, if possible, falling
#' back to the most recent version of WKT2 or PROJJSON.
#' @param proj_version A [package_version()] of the PROJ version, or
#' `NULL` if the PROJ version is unknown.
#'
#' @return
#' - `wk_crs_proj_definition()` Returns a string used to represent the
#' CRS in PROJ. For recent PROJ version you'll want to return PROJJSON;
#' however you should check `proj_version` if you want this to work with
#' older versions of PROJ.
#' - `wk_crs_projjson()` Returns a PROJJSON string or NA_character_ if this
#' representation is unknown or can't be calculated.
#' @export
#'
#' @examples
#' wk_crs_proj_definition("EPSG:4326")
#'
wk_crs_proj_definition <- function(crs, proj_version = NULL, verbose = FALSE) {
UseMethod("wk_crs_proj_definition")
}
#' @rdname wk_crs_proj_definition
#' @export
wk_crs_projjson <- function(crs) {
UseMethod("wk_crs_projjson")
}
#' @export
wk_crs_projjson.default <- function(crs) {
maybe_auth_code_or_json <- wk_crs_proj_definition(crs, verbose = FALSE)
# check for most probably JSON
if (isTRUE(grepl("^\\{.*?\\}$", maybe_auth_code_or_json))) {
return(maybe_auth_code_or_json)
}
# look up by auth_name / code
split <- strsplit(maybe_auth_code_or_json, ":", fixed = TRUE)[[1]]
query <- new_data_frame(list(auth_name = split[1], code = split[2]))
merge(query, wk::wk_proj_crs_json, all.x = TRUE)$projjson
}
#' @rdname wk_crs_proj_definition
#' @export
wk_crs_proj_definition.NULL <- function(crs, proj_version = NULL, verbose = FALSE) {
NA_character_
}
#' @rdname wk_crs_proj_definition
#' @export
wk_crs_proj_definition.wk_crs_inherit <- function(crs, proj_version = NULL,
verbose = FALSE) {
NA_character_
}
#' @rdname wk_crs_proj_definition
#' @export
wk_crs_proj_definition.character <- function(crs, proj_version = NULL, verbose = FALSE) {
stopifnot(length(crs) == 1)
crs
}
#' @rdname wk_crs_proj_definition
#' @export
wk_crs_proj_definition.double <- function(crs, proj_version = NULL, verbose = FALSE) {
stopifnot(length(crs) == 1)
if (is.na(crs)) wk_crs_proj_definition(NULL) else paste0("EPSG:", crs)
}
#' @rdname wk_crs_proj_definition
#' @export
wk_crs_proj_definition.integer <- function(crs, proj_version = NULL, verbose = FALSE) {
stopifnot(length(crs) == 1)
if (is.na(crs)) wk_crs_proj_definition(NULL) else paste0("EPSG:", crs)
}
#' Special CRS values
#'
#' The CRS handling in the wk package requires two sentinel CRS values.
#' The first, [wk_crs_inherit()], signals that the vector should inherit
#' a CRS of another vector if combined. This is useful for empty, `NULL`,
#' and/or zero-length geometries. The second, [wk_crs_auto()], is used
#' as the default argument of `crs` for constructors so that zero-length
#' geometries are assigned a CRS of `wk_crs_inherit()` by default.
#'
#' @param x A raw input to a construuctor whose length and crs attributte
#' is used to determine the default CRS returned by [wk_crs_auto()].
#' @param crs A value for the coordinate reference system supplied by
#' the user.
#'
#' @export
#'
#' @examples
#' wk_crs_auto_value(list(), wk_crs_auto())
#' wk_crs_auto_value(list(), 1234)
#' wk_crs_auto_value(list(NULL), wk_crs_auto())
#'
wk_crs_inherit <- function() {
structure(list(), class = "wk_crs_inherit")
}
#' @rdname wk_crs_inherit
#' @export
wk_crs_longlat <- function(crs = NULL) {
if (inherits(crs, "wk_crs_inherit") || is.null(crs) || identical(crs, "WGS84")) {
return("OGC:CRS84")
}
crs_proj <- wk_crs_proj_definition(crs)
switch(
crs_proj,
"OGC:CRS84" = ,
"EPSG:4326" = ,
"WGS84" = "OGC:CRS84",
"OGC:CRS27" = ,
"EPSG:4267" = ,
"NAD27" = "OGC:CRS27",
"OGC:CRS83" = ,
"EPSG:4269" = ,
"NAD83" = "OGC:CRS83",
stop(
sprintf(
"Can't guess authority-compliant long/lat definition from CRS '%s'",
format(crs_proj)
)
)
)
}
#' @rdname wk_crs_inherit
#' @export
wk_crs_auto <- function() {
structure(list(), class = "wk_crs_auto")
}
#' @rdname wk_crs_inherit
#' @export
wk_crs_auto_value <- function(x, crs) {
if (inherits(crs, "wk_crs_auto")) {
if (length(x) == 0) wk_crs_inherit() else attr(x, "crs", exact = TRUE)
} else {
crs
}
}
#' @export
format.wk_crs_inherit <- function(x, ...) {
format("wk_crs_inherit()", ...)
}
#' @export
print.wk_crs_inherit <- function(x, ...) {
cat("<wk_crs_inherit>\n")
}
wk_crs_format <- function(x, ...) {
tryCatch(
wk_crs_proj_definition(x, verbose = FALSE),
error = function(e) format(x, ...)
)
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/wk-crs.R
|
#' @keywords internal
"_PACKAGE"
# The following block is used by usethis to automatically manage
# roxygen namespace tags. Modify with care!
## usethis namespace: start
#' @useDynLib wk, .registration = TRUE
## usethis namespace: end
NULL
|
/scratch/gouwar.j/cran-all/cranData/wk/R/wk-package.R
|
new_wk_rcrd <- function(x, template) {
stopifnot(
is.list(x),
is.null(attr(x, "class")),
!is.null(names(x)),
all(names(x) != "")
)
structure(
x,
class = unique(class(template)),
crs = attr(template, "crs", exact = TRUE),
geodesic = attr(template, "geodesic", exact = TRUE)
)
}
validate_wk_rcrd <- function(x) {
x_bare <- unclass(x)
stopifnot(
typeof(x) == "list",
!is.null(names(x_bare)),
all(names(x_bare) != ""),
all(vapply(x_bare, is.double, logical(1)))
)
invisible(x)
}
#' @export
format.wk_rcrd <- function(x, ...) {
vapply(x, function(item) paste0(format(unclass(item), ...), collapse = "\n"), character(1))
}
#' @export
print.wk_rcrd <- function(x, ...) {
crs <- wk_crs(x)
is_geodesic <- wk_is_geodesic(x)
header <- sprintf("%s[%s]", class(x)[1], length(x))
if (!is.null(crs)) {
header <- paste0(header, " with CRS=", wk_crs_format(crs))
}
if (isTRUE(is_geodesic)) {
header <- paste0("geodesic ", header)
}
cat(sprintf("<%s>\n", header))
if (length(x) == 0) {
return(invisible(x))
}
max_print <- getOption("max.print", 1000)
x_head <- format(utils::head(x, max_print))
out <- format(x_head)
print(out, quote = FALSE)
if (length(x) > max_print) {
cat(sprintf("Reached max.print (%s)\n", max_print))
}
invisible(x)
}
#' @export
str.wk_rcrd <- function(object, ...) {
str.wk_vctr(object, ...)
}
#' @export
as.character.wk_rcrd <- function(x, ...) {
format(x, ...)
}
#' @export
is.na.wk_rcrd <- function(x, ...) {
is_na <- lapply(unclass(x), is.na)
Reduce("&", is_na)
}
#' @export
`[.wk_rcrd` <- function(x, i) {
new_wk_rcrd(lapply(unclass(x), "[", i), x)
}
#' @export
`[[.wk_rcrd` <- function(x, i) {
x[i]
}
#' @export
`$.wk_rcrd` <- function(x, i) {
stop("`$` is not meaningful for 'wk_rcrd' objects", call. = FALSE)
}
#' @export
`[[<-.wk_rcrd` <- function(x, i, value) {
x[i] <- value
x
}
#' @export
names.wk_rcrd <- function(x) {
NULL
}
#' @export
`names<-.wk_rcrd` <- function(x, value) {
if (is.null(value)) {
x
} else {
stop("Names of a 'wk_rcrd' must be NULL.")
}
}
#' @export
length.wk_rcrd <- function(x) {
length(unclass(x)[[1]])
}
#' @export
rep.wk_rcrd <- function(x, ...) {
new_wk_rcrd(lapply(unclass(x), rep, ...), x)
}
#' @method rep_len wk_rcrd
#' @export
rep_len.wk_rcrd <- function(x, ...) {
new_wk_rcrd(lapply(unclass(x), rep_len, ...), x)
}
#' @export
c.wk_rcrd <- function(...) {
dots <- list(...)
classes <- lapply(dots, class)
first_class <- classes[[1]]
if (!all(vapply(classes, identical, first_class, FUN.VALUE = logical(1)))) {
stop("Can't combine 'wk_rcrd' objects that do not have identical classes.", call. = FALSE)
}
# compute output crs
attr(dots[[1]], "crs") <- wk_crs_output(...)
geodesic <- wk_is_geodesic_output(...)
attr(dots[[1]], "geodesic") <- if (geodesic) TRUE else NULL
new_wk_vctr(do.call(Map, c(list(c), lapply(dots, unclass))), dots[[1]])
}
# data.frame() will call as.data.frame() with optional = TRUE
#' @export
as.data.frame.wk_rcrd <- function(x, ..., optional = FALSE) {
if (!optional) {
new_data_frame(unclass(x))
} else {
new_data_frame(list(x))
}
}
#' @export
as.matrix.wk_rcrd <- function(x, ...) {
x_bare <- unclass(x)
matrix(
unlist(x_bare, use.names = FALSE),
nrow = length(x),
ncol = length(x_bare),
byrow = FALSE,
dimnames = list(NULL, names(x_bare))
)
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/wk-rcrd.R
|
#' @export
print.wk_vctr <- function(x, ...) {
crs <- wk_crs(x)
is_geodesic <- wk_is_geodesic(x)
header <- sprintf("%s[%s]", class(x)[1], length(x))
if (!is.null(crs)) {
header <- paste0(header, " with CRS=", wk_crs_format(crs))
}
if (isTRUE(is_geodesic)) {
header <- paste0("geodesic ", header)
}
cat(sprintf("<%s>\n", header))
if (length(x) == 0) {
return(invisible(x))
}
max_print <- getOption("max.print", 1000)
x_head <- format(utils::head(x, max_print))
out <- stats::setNames(format(x_head), names(x_head))
print(out, quote = FALSE)
if (length(x) > max_print) {
cat(sprintf("Reached max.print (%s)\n", max_print))
}
invisible(x)
}
# lifted from vctrs::obj_leaf()
#' @export
str.wk_vctr <- function(object, ..., indent.str = "", width = getOption("width")) {
if (length(object) == 0) {
cat(paste0(" ", class(object)[1], "[0]\n"))
return(invisible(object))
}
# estimate possible number of elements that could be displayed
# to avoid formatting too many
width <- width - nchar(indent.str) - 2
length <- min(length(object), ceiling(width / 5))
formatted <- format(object[seq_len(length)], trim = TRUE)
title <- paste0(" ", class(object)[1], "[1:", length(object), "]")
cat(
paste0(
title,
" ",
strtrim(paste0(formatted, collapse = ", "), width - nchar(title)),
"\n"
)
)
invisible(object)
}
#' @export
`[.wk_vctr` <- function(x, i) {
new_wk_vctr(NextMethod(), x)
}
#' @export
`[[.wk_vctr` <- function(x, i) {
x[i]
}
#' @export
`[[<-.wk_vctr` <- function(x, i, value) {
x[i] <- value
x
}
#' @export
c.wk_vctr <- function(...) {
dots <- list(...)
classes <- lapply(dots, class)
first_class <- classes[[1]]
if (!all(vapply(classes, identical, first_class, FUN.VALUE = logical(1)))) {
stop("Can't combine 'wk_vctr' objects that do not have identical classes.", call. = FALSE)
}
# compute output crs, geodesic
attr(dots[[1]], "crs") <- wk_crs_output(...)
geodesic <- wk_is_geodesic_output(...)
attr(dots[[1]], "geodesic") <- if (geodesic) TRUE else NULL
new_wk_vctr(NextMethod(), dots[[1]])
}
#' @export
rep.wk_vctr <- function(x, ...) {
new_wk_vctr(NextMethod(), x)
}
#' @method rep_len wk_vctr
#' @export
rep_len.wk_vctr <- function(x, ...) {
new_wk_vctr(NextMethod(), x)
}
# data.frame() will call as.data.frame() with optional = TRUE
#' @export
as.data.frame.wk_vctr <- function(x, ..., optional = FALSE) {
if (!optional) {
stop(sprintf("cannot coerce object of tyoe '%s' to data.frame", class(x)[1]))
} else {
new_data_frame(list(x))
}
}
new_wk_vctr <- function(x, template) {
structure(
x,
class = unique(class(template)),
crs = attr(template, "crs", exact = TRUE),
geodesic = attr(template, "geodesic", exact = TRUE)
)
}
parse_base <- function(x, problems) {
x[!is.na(problems)] <- x[NA_integer_]
problems_df <- action_for_problems(
problems,
function(msg) warning(paste0(msg, '\nSee attr(, "problems") for details.'), call. = FALSE)
)
if (nrow(problems_df) > 0) {
problems_df$actual <- unclass(x)[problems_df$row]
attr(x, "problems") <- problems_df
}
x
}
stop_for_problems <- function(problems) {
action_for_problems(problems, stop, call. = FALSE)
}
action_for_problems <- function(problems, action, ...) {
if (any(!is.na(problems))) {
n_problems <- sum(!is.na(problems))
summary_problems <- utils::head(which(!is.na(problems)))
problem_summary <- paste0(
sprintf("[%s] %s", summary_problems, problems[summary_problems]),
collapse = "\n"
)
if (n_problems > length(summary_problems)) {
problem_summary <- paste0(
problem_summary,
sprintf("\n...and %s more problems", n_problems - length(summary_problems))
)
}
action(
sprintf(
"Encountered %s parse problem%s:\n%s",
n_problems,
if (n_problems == 1) "" else "s",
problem_summary
),
...
)
}
data.frame(
row = which(!is.na(problems)),
col = rep_len(NA_integer_, sum(!is.na(problems))),
expected = problems[!is.na(problems)],
stringsAsFactors = FALSE
)
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/wk-vctr.R
|
#' @rdname wk_writer
#' @export
wkb_writer <- function(buffer_size = 2048L, endian = NA_integer_) {
new_wk_handler(
.Call(wk_c_wkb_writer_new, as.integer(buffer_size), as.integer(endian)),
"wk_wkb_writer"
)
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/wkb-writer.R
|
#' Mark lists of raw vectors as well-known binary
#'
#' @param x A [list()] of [raw()] vectors or `NULL`.
#' @inheritParams new_wk_wkb
#' @param ... Unused
#'
#' @return A [new_wk_wkb()]
#' @export
#'
#' @examples
#' as_wkb("POINT (20 10)")
#'
wkb <- function(x = list(), crs = wk_crs_auto(), geodesic = FALSE) {
crs <- wk_crs_auto_value(x, crs)
attributes(x) <- NULL
wkb <- new_wk_wkb(x, crs = crs, geodesic = geodesic_attr(geodesic))
validate_wk_wkb(wkb)
wkb
}
#' @rdname wkb
#' @export
parse_wkb <- function(x, crs = wk_crs_auto(), geodesic = FALSE) {
crs <- wk_crs_auto_value(x, crs)
attributes(x) <- NULL
wkb <- new_wk_wkb(x, crs = crs, geodesic = geodesic_attr(geodesic))
parse_base(wkb, wk_problems(wkb))
}
#' @rdname wkb
#' @export
wk_platform_endian <- function() {
match(.Platform$endian, c("big", "little")) - 1L
}
#' @rdname wkb
#' @export
as_wkb <- function(x, ...) {
UseMethod("as_wkb")
}
#' @rdname wkb
#' @export
as_wkb.default <- function(x, ...) {
wk_translate(
x,
new_wk_wkb(crs = wk_crs_inherit(), geodesic = wk_geodesic_inherit()),
...
)
}
#' @rdname wkb
#' @export
as_wkb.character <- function(x, ..., crs = NULL, geodesic = FALSE) {
as_wkb(wkt(x, crs = crs, geodesic = geodesic), ...)
}
#' @rdname wkb
#' @export
as_wkb.wk_wkb <- function(x, ...) {
x
}
#' @rdname wkb
#' @export
as_wkb.blob <- function(x, ..., crs = NULL, geodesic = FALSE) {
as_wkb(wkb(x, crs = crs, geodesic = geodesic), ...)
}
#' @rdname wkb
#' @export
as_wkb.WKB <- function(x, ..., crs = NULL, geodesic = FALSE) {
as_wkb(wkb(x, crs = crs, geodesic = geodesic), ...)
}
#' S3 Details for wk_wkb
#'
#' @param x A (possibly) [wkb()] vector
#' @param crs A value to be propagated as the CRS for this vector.
#' @inheritParams wk_is_geodesic
#'
#' @export
#'
new_wk_wkb <- function(x = list(), crs = NULL, geodesic = NULL) {
if (typeof(x) != "list" || !is.null(attributes(x))) {
stop("wkb input must be a list without attributes", call. = FALSE)
}
structure(x, class = c("wk_wkb", "wk_vctr"), crs = crs, geodesic = geodesic)
}
#' @rdname new_wk_wkb
#' @export
validate_wk_wkb <- function(x) {
if (typeof(x) != "list") {
stop("wkb() must be of type list()", call. = FALSE)
}
good_types <- .Call(wk_c_wkb_is_raw_or_null, x)
if (!all(good_types)) {
stop("items in wkb input must be raw() or NULL", call. = FALSE)
}
if (!inherits(x, "wk_wkb") || !inherits(x, "wk_vctr")) {
attributes(x) <- NULL
problems <- wk_problems(new_wk_wkb(x))
} else {
problems <- wk_problems(x)
}
stop_for_problems(problems)
invisible(x)
}
#' @rdname new_wk_wkb
#' @export
is_wk_wkb <- function(x) {
inherits(x, "wk_wkb")
}
#' @export
`[<-.wk_wkb` <- function(x, i, value) {
replacement <- as_wkb(value)
crs_out <- wk_crs_output(x, replacement)
geodesic_out <- wk_is_geodesic_output(x, replacement)
x <- unclass(x)
x[i] <- replacement
attr(x, "crs") <- NULL
attr(x, "geodesic") <- NULL
new_wk_wkb(x, crs = crs_out, geodesic = geodesic_attr(geodesic_out))
}
#' @export
is.na.wk_wkb <- function(x) {
.Call(wk_c_wkb_is_na, x)
}
#' @export
format.wk_wkb <- function(x, ...) {
paste0("<", wk_format(x), ">")
}
# as far as I can tell, this is the only way to change
# how the object appears in the viewer
#' @export
as.character.wk_wkb <- function(x, ...) {
format(x, ...)
}
#' Convert well-known binary to hex
#'
#' @param x A [wkb()] vector
#'
#' @return A hex encoded [wkb()] vector
#' @export
#'
#' @examples
#' x <- as_wkb(xyz(1:5, 6:10, 11:15))
#' wkb_to_hex(x)
#'
wkb_to_hex <- function(x) {
.Call(wk_c_wkb_to_hex, as_wkb(x))
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/wkb.R
|
#' @rdname wk_writer
#' @export
wkt_writer <- function(precision = 16L, trim = TRUE) {
new_wk_handler(
.Call(
wk_c_wkt_writer,
as.integer(precision)[1],
as.logical(trim)[1]
),
"wk_wkt_writer"
)
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/wkt-writer.R
|
#' Mark character vectors as well-known text
#'
#' @param x A [character()] vector containing well-known text.
#' @inheritParams new_wk_wkb
#' @param ... Unused
#'
#' @return A [new_wk_wkt()]
#' @export
#'
#' @examples
#' wkt("POINT (20 10)")
#'
wkt <- function(x = character(), crs = wk_crs_auto(), geodesic = FALSE) {
x <- as.character(x)
crs <- wk_crs_auto_value(x, crs)
wkt <- new_wk_wkt(x, crs = crs, geodesic = geodesic_attr(geodesic))
validate_wk_wkt(wkt)
wkt
}
#' @rdname wkt
#' @export
parse_wkt <- function(x, crs = wk_crs_auto(), geodesic = FALSE) {
x <- as.character(x)
crs <- wk_crs_auto_value(x, crs)
wkt <- new_wk_wkt(x, crs = crs, geodesic = geodesic_attr(geodesic))
parse_base(wkt, wk_problems(wkt))
}
#' @rdname wkt
#' @export
as_wkt <- function(x, ...) {
UseMethod("as_wkt")
}
#' @rdname wkt
#' @export
as_wkt.default <- function(x, ...) {
wk_translate(
x,
new_wk_wkt(crs = wk_crs_inherit(), geodesic = wk_geodesic_inherit())
)
}
#' @rdname wkt
#' @export
as_wkt.character <- function(x, ..., crs = NULL, geodesic = FALSE) {
wkt(x, crs = crs, geodesic = geodesic)
}
#' @rdname wkt
#' @export
as_wkt.wk_wkt <- function(x, ...) {
x
}
#' S3 Details for wk_wkt
#'
#' @param x A (possibly) [wkt()] vector
#' @inheritParams new_wk_wkb
#'
#' @export
#'
new_wk_wkt <- function(x = character(), crs = NULL, geodesic = NULL) {
if (typeof(x) != "character" || !is.null(attributes(x))) {
stop("wkt input must be a character() without attributes", call. = FALSE)
}
structure(x, class = c("wk_wkt", "wk_vctr"), crs = crs, geodesic = geodesic)
}
#' @rdname new_wk_wkt
#' @export
is_wk_wkt <- function(x) {
inherits(x, "wk_wkt")
}
#' @rdname new_wk_wkt
#' @export
validate_wk_wkt <- function(x) {
if (typeof(x) != "character") {
stop("wkt() must be of type character()", call. = FALSE)
}
if (!inherits(x, "wk_wkt") || !inherits(x, "wk_vctr")) {
stop('wkt() must inherit from c("wk_wkt", "wk_vctr")', call. = FALSE)
} else {
problems <- wk_problems(x)
}
stop_for_problems(problems)
invisible(x)
}
#' @export
`[<-.wk_wkt` <- function(x, i, value) {
replacement <- as_wkt(value)
crs_out <- wk_crs_output(x, replacement)
geodesic_out <- wk_is_geodesic_output(x, replacement)
x <- unclass(x)
x[i] <- replacement
attr(x, "crs") <- NULL
attr(x, "geodesic") <- NULL
new_wk_wkt(x, crs = crs_out, geodesic = geodesic_attr(geodesic_out))
}
#' @export
format.wk_wkt <- function(x, ..., max_coords = 6) {
wk_format(x, max_coords = max_coords)
}
#' @export
as.character.wk_wkt <- function(x, ...) {
attr(x, "crs") <- NULL
unclass(x)
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/wkt.R
|
#' Write geometry vectors
#'
#' When writing transformation functions, it is often useful to know which
#' handler should be used to create a (potentially modified) version
#' of an object. Some transformers (e.g., [wk_vertices()]) modify
#' the geometry type of an object, in which case a generic writer is needed.
#' This defaults to [wkb_writer()] because it is fast and can handle
#' all geometry types.
#'
#' @inheritParams wk_handle
#' @param precision If `trim` is `TRUE`, the total number of significant digits to keep
#' for each result or the number of digits after the decimal place otherwise.
#' @param trim Use `FALSE` to keep trailing zeroes after the decimal place.
#' @param endian Use 1 for little endian, 0 for big endian, or NA for
#' system endian.
#' @param generic Use `TRUE` to obtain a writer that can write all geometry
#' types.
#' @param buffer_size Control the initial buffer size used when writing WKB.
#' @param promote_multi Use TRUE to promote all simple geometries to a multi
#' type when reading to sfc. This is useful to increase the likelihood that
#' the sfc will contain a single geometry type.
#' @param ... Passed to the writer constructor.
#'
#' @return A [wk_handler][wk_handle].
#' @export
#'
wk_writer <- function(handleable, ..., generic = FALSE) {
UseMethod("wk_writer")
}
#' @rdname wk_writer
#' @export
wk_writer.default <- function(handleable, ...) {
wkb_writer()
}
#' @rdname wk_writer
#' @export
wk_writer.wk_wkt <- function(handleable, ..., precision = 16, trim = TRUE) {
wkt_writer(precision, trim)
}
#' @rdname wk_writer
#' @export
wk_writer.wk_wkb <- function(handleable, ...) {
wkb_writer()
}
#' @rdname wk_writer
#' @export
wk_writer.wk_xy <- function(handleable, ..., generic = FALSE) {
if (generic) wkb_writer() else xy_writer()
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/writer.R
|
#' @rdname wk_writer
#' @export
xy_writer <- function() {
new_wk_handler(.Call(wk_c_xy_writer_new), "wk_xy_writer")
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/xy-writer.R
|
#' Efficient point vectors
#'
#' @param x,y,z,m Coordinate values.
#' @param dims A set containing one or more of `c("x", "y", "z", "m")`.
#' @param ... Passed to methods.
#' @inheritParams new_wk_wkb
#'
#' @return A vector of coordinate values.
#' @export
#'
#' @examples
#' xy(1:5, 1:5)
#' xyz(1:5, 1:5, 10)
#' xym(1:5, 1:5, 10)
#' xyzm(1:5, 1:5, 10, 12)
#'
#' # NA, NA maps to a null/na feature; NaN, NaN maps to EMPTY
#' as_wkt(xy(NaN, NaN))
#' as_wkt(xy(NA, NA))
#'
xy <- function(x = double(), y = double(), crs = wk_crs_auto()) {
vec <- new_wk_xy(recycle_common(x = as.double(x), y = as.double(y)), crs = wk_crs_auto_value(x, crs))
validate_wk_xy(vec)
vec
}
#' @rdname xy
#' @export
xyz <- function(x = double(), y = double(), z = double(), crs = wk_crs_auto()) {
vec <- new_wk_xyz(recycle_common(x = as.double(x), y = as.double(y), z = as.double(z)), crs = wk_crs_auto_value(x, crs))
validate_wk_xyz(vec)
vec
}
#' @rdname xy
#' @export
xym <- function(x = double(), y = double(), m = double(), crs = wk_crs_auto()) {
vec <- new_wk_xym(recycle_common(x = as.double(x), y = as.double(y), m = as.double(m)), crs = wk_crs_auto_value(x, crs))
validate_wk_xym(vec)
vec
}
#' @rdname xy
#' @export
xyzm <- function(x = double(), y = double(), z = double(), m = double(), crs = wk_crs_auto()) {
vec <- new_wk_xyzm(
recycle_common(
x = as.double(x),
y = as.double(y),
z = as.double(z),
m = as.double(m)
),
crs = wk_crs_auto_value(x, crs)
)
validate_wk_xyzm(vec)
vec
}
#' @rdname xy
#' @export
xy_dims <- function(x) {
names(unclass(x))
}
#' @rdname xy
#' @export
as_xy <- function(x, ...) {
UseMethod("as_xy")
}
#' @rdname xy
#' @export
as_xy.default <- function(x, ..., dims = NULL) {
result <- wk_handle(x, xy_writer())
wk_crs(result) <- wk_crs(x)
if (is.null(dims)) {
result
} else {
as_xy(result, dims = dims)
}
}
#' @rdname xy
#' @export
as_xy.wk_xy <- function(x, ..., dims = NULL) {
if (is.null(dims)) {
x
} else if (setequal(dims, c("x", "y"))) {
new_wk_xy(fill_missing_dims(unclass(x), c("x", "y"), length(x)), crs = wk_crs(x))
} else if (setequal(dims, c("x", "y", "z"))) {
new_wk_xyz(fill_missing_dims(unclass(x), c("x", "y", "z"), length(x)), crs = wk_crs(x))
} else if (setequal(dims, c("x", "y", "m"))) {
new_wk_xym(fill_missing_dims(unclass(x), c("x", "y", "m"), length(x)), crs = wk_crs(x))
} else if (setequal(dims, c("x", "y", "z", "m"))) {
new_wk_xyzm(fill_missing_dims(unclass(x), c("x", "y", "z", "m"), length(x)), crs = wk_crs(x))
} else {
stop("Unknown dims in as_xy().", call. = FALSE)
}
}
#' @rdname xy
#' @export
as_xy.matrix <- function(x, ..., crs = NULL) {
x[] <- as.numeric(x)
colnames(x) <- tolower(colnames(x))
cols <- colnames(x)
if (!is.null(cols)) {
dim_cols <- intersect(c("x", "y", "z", "m"), cols)
if (length(dim_cols) == 0) {
stop(
paste0(
"Can't guess dimensions of matrix with column names\n",
paste0("'", cols, "'", collapse = ", ")
),
call. = FALSE
)
}
if (!identical(dim_cols, colnames(x))) {
x <- x[, dim_cols, drop = FALSE]
}
}
# prevent named subsets
dimnames(x) <- NULL
if (ncol(x) == 2) {
new_wk_xy(
list(
x = x[, 1, drop = TRUE],
y = x[, 2, drop = TRUE]
),
crs = crs
)
} else if (ncol(x) == 4) {
new_wk_xyzm(
list(
x = x[, 1, drop = TRUE],
y = x[, 2, drop = TRUE],
z = x[, 3, drop = TRUE],
m = x[, 4, drop = TRUE]
),
crs = crs
)
} else if (identical(cols, c("x", "y", "m"))) {
new_wk_xym(
list(
x = x[, 1, drop = TRUE],
y = x[, 2, drop = TRUE],
m = x[, 3, drop = TRUE]
),
crs = crs
)
} else if (ncol(x) == 3) {
new_wk_xyz(
list(
x = x[, 1, drop = TRUE],
y = x[, 2, drop = TRUE],
z = x[, 3, drop = TRUE]
),
crs = crs
)
} else {
stop(
sprintf("Can't guess dimensions of matrix with %s columns", ncol(x)),
call. = FALSE
)
}
}
#' @rdname xy
#' @export
as_xy.data.frame <- function(x, ..., dims = NULL, crs = NULL) {
col_handleable <- vapply(x, is_handleable, logical(1))
if (any(col_handleable)) {
stopifnot(missing(crs))
return(as_xy.default(x[[which(col_handleable)[1]]], dims = dims))
}
if (is.null(dims)) {
dims <- intersect(c("x", "y", "z", "m"), names(x))
}
if (setequal(dims, c("x", "y"))) {
new_wk_xy(fill_missing_dims(unclass(x), c("x", "y"), nrow(x)), crs = crs)
} else if (setequal(dims, c("x", "y", "z"))) {
new_wk_xyz(fill_missing_dims(unclass(x), c("x", "y", "z"), nrow(x)), crs = crs)
} else if (setequal(dims, c("x", "y", "m"))) {
new_wk_xym(fill_missing_dims(unclass(x), c("x", "y", "m"), nrow(x)), crs = crs)
} else if (setequal(dims, c("x", "y", "z", "m"))) {
new_wk_xyzm(fill_missing_dims(unclass(x), c("x", "y", "z", "m"), nrow(x)), crs = crs)
} else {
stop("Unknown dims in as_xy.data.frame().", call. = FALSE)
}
}
fill_missing_dims <- function(x, dims, len) {
missing_dims <- setdiff(dims, names(x))
x[missing_dims] <- lapply(
stats::setNames(missing_dims, missing_dims),
function(x) rep_len(NA_real_, len)
)
lapply(x[dims], as.double)
}
#' S3 details for xy objects
#'
#' @param x A [xy()] object.
#' @inheritParams new_wk_wkb
#'
#' @export
#'
new_wk_xy <- function(x = list(x = double(), y = double()), crs = NULL) {
structure(x, class = c("wk_xy", "wk_rcrd"), crs = crs)
}
#' @rdname new_wk_xy
#' @export
new_wk_xyz <- function(x = list(x = double(), y = double(), z = double()), crs = NULL) {
structure(x, class = c("wk_xyz", "wk_xy", "wk_rcrd"), crs = crs)
}
#' @rdname new_wk_xy
#' @export
new_wk_xym <- function(x = list(x = double(), y = double(), m = double()), crs = NULL) {
structure(x, class = c("wk_xym", "wk_xy", "wk_rcrd"), crs = crs)
}
#' @rdname new_wk_xy
#' @export
new_wk_xyzm <- function(x = list(x = double(), y = double(), z = double(), m = double()), crs = NULL) {
structure(x, class = c("wk_xyzm", "wk_xyz", "wk_xym", "wk_xy", "wk_rcrd"), crs = crs)
}
#' @rdname new_wk_xy
#' @export
validate_wk_xy <- function(x) {
validate_wk_rcrd(x)
stopifnot(identical(names(unclass(x)), c("x", "y")))
invisible(x)
}
#' @rdname new_wk_xy
#' @export
validate_wk_xyz <- function(x) {
validate_wk_rcrd(x)
stopifnot(identical(names(unclass(x)), c("x", "y", "z")))
invisible(x)
}
#' @rdname new_wk_xy
#' @export
validate_wk_xym <- function(x) {
validate_wk_rcrd(x)
stopifnot(identical(names(unclass(x)), c("x", "y", "m")))
invisible(x)
}
#' @rdname new_wk_xy
#' @export
validate_wk_xyzm <- function(x) {
validate_wk_rcrd(x)
stopifnot(identical(names(unclass(x)), c("x", "y", "z", "m")))
invisible(x)
}
#' @export
format.wk_xy <- function(x, ...) {
x <- unclass(x)
sprintf("(%s %s)", format(x$x, ...), format(x$y, ...))
}
#' @export
format.wk_xyz <- function(x, ...) {
x <- unclass(x)
sprintf("Z (%s %s %s)", format(x$x, ...), format(x$y, ...), format(x$z, ...))
}
#' @export
format.wk_xym <- function(x, ...) {
x <- unclass(x)
sprintf("M (%s %s %s)", format(x$x, ...), format(x$y, ...), format(x$m, ...))
}
#' @export
format.wk_xyzm <- function(x, ...) {
x <- unclass(x)
sprintf("ZM (%s %s %s %s)", format(x$x, ...), format(x$y, ...), format(x$z, ...), format(x$m, ...))
}
#' @export
`[<-.wk_xy` <- function(x, i, value) {
replacement <- as_xy(value)
result <- Map(
"[<-",
unclass(x),
list(i),
fill_missing_dims(unclass(replacement), xy_dims(x), length(replacement))
)
names(result) <- names(unclass(x))
structure(result, class = class(x), crs = wk_crs_output(x, replacement))
}
#' @export
is.na.wk_xy <- function(x, ...) {
is_na <- Reduce("&", lapply(unclass(x), is.na))
is_nan <- Reduce("&", lapply(unclass(x), is.nan))
is_na & !is_nan
}
#' XY vector extractors
#'
#' @param x An [xy()] vector
#'
#' @return Components of the [xy()] vector or NULL if the dimension is missing
#' @export
#'
#' @examples
#' x <- xyz(1:5, 6:10, 11:15)
#' xy_x(x)
#' xy_y(x)
#' xy_z(x)
#' xy_m(x)
#'
xy_x <- function(x) {
unclass(as_xy(x))$x
}
#' @rdname xy_x
#' @export
xy_y <- function(x) {
unclass(as_xy(x))$y
}
#' @rdname xy_x
#' @export
xy_z <- function(x) {
unclass(as_xy(x))$z
}
#' @rdname xy_x
#' @export
xy_m <- function(x) {
unclass(as_xy(x))$m
}
|
/scratch/gouwar.j/cran-all/cranData/wk/R/xyzm.R
|
# nocov start
.onLoad <- function(...) {
# Register S3 methods for Suggests
for (cls in c("wk_wkb", "wk_wkt",
"wk_xy", "wk_xyz", "wk_xym", "wk_xyzm",
"wk_rct", "wk_crc")) {
s3_register("vctrs::vec_proxy", cls)
s3_register("vctrs::vec_restore", cls)
s3_register("vctrs::vec_cast", cls)
s3_register("vctrs::vec_ptype2", cls)
}
for (cls in c("wk_wkb", "wk_wkt", "wk_xy", "wk_rct", "wk_crc")) {
s3_register("sf::st_as_sfc", cls)
s3_register("sf::st_as_sf", cls)
s3_register("sf::st_geometry", cls)
s3_register("sf::st_bbox", cls)
s3_register("sf::st_crs", cls)
s3_register("sf::st_crs<-", cls)
s3_register("readr::output_column", cls)
}
# grd is not a vector class, but does have sf methods
s3_register("sf::st_as_sfc", "wk_grd")
s3_register("sf::st_as_sf", "wk_grd")
s3_register("sf::st_geometry", "wk_grd")
s3_register("sf::st_bbox", "wk_grd")
s3_register("sf::st_crs", "wk_grd")
s3_register("sf::st_crs<-", "wk_grd")
# wkb vec_proxy_equal
s3_register("vctrs::vec_proxy_equal", "wk_wkb")
}
.onUnload <- function (libpath) {
library.dynam.unload("wk", libpath)
}
s3_register <- function(generic, class, method = NULL) {
stopifnot(is.character(generic), length(generic) == 1)
stopifnot(is.character(class), length(class) == 1)
pieces <- strsplit(generic, "::")[[1]]
stopifnot(length(pieces) == 2)
package <- pieces[[1]]
generic <- pieces[[2]]
caller <- parent.frame()
get_method_env <- function() {
top <- topenv(caller)
if (isNamespace(top)) {
asNamespace(environmentName(top))
} else {
caller
}
}
get_method <- function(method, env) {
if (is.null(method)) {
get(paste0(generic, ".", class), envir = get_method_env())
} else {
method
}
}
method_fn <- get_method(method)
stopifnot(is.function(method_fn))
# Always register hook in case package is later unloaded & reloaded
setHook(
packageEvent(package, "onLoad"),
function(...) {
ns <- asNamespace(package)
# Refresh the method, it might have been updated by `devtools::load_all()`
method_fn <- get_method(method)
registerS3method(generic, class, method_fn, envir = ns)
}
)
# Avoid registration failures during loading (pkgload or regular)
if (!isNamespaceLoaded(package)) {
return(invisible())
}
envir <- asNamespace(package)
# Only register if generic can be accessed
if (exists(generic, envir)) {
registerS3method(generic, class, method_fn, envir = envir)
}
invisible()
}
# nocov end
|
/scratch/gouwar.j/cran-all/cranData/wk/R/zzz.R
|
# Convert a SpatialLines or SpatialLinesDataFrame object
# to a well-known binary (WKB) geometry representation of line segments
#' Convert SpatialLines to \acronym{WKB} MultiLineString
#'
#' Converts an object of class \code{SpatialLines} or
#' \code{SpatialLinesDataFrame} to a list of well-known binary (\acronym{WKB})
#' geometry representations of type MultiLineString.
#'
#' This function is called by the \code{\link{writeWKB}} function. Call the
#' \code{\link{writeWKB}} function instead of calling this function directly.
#'
#' The argument \code{obj} may have multiple objects of class \code{Lines} in
#' each position of the \code{list} in slot \code{lines}.
#'
#' @param obj an object of class
#' \code{\link[sp:SpatialLines-class]{SpatialLines}} or
#' \code{\link[sp:SpatialLinesDataFrame-class]{SpatialLinesDataFrame}}.
#' @param endian The byte order (\code{"big"} or \code{"little"}) for encoding
#' numeric types. The default is \code{"little"}.
#' @return A \code{list} with class \code{AsIs}. The length of the returned list
#' is the same as the length of the argument \code{obj}. Each element of the
#' returned list is a \code{\link[base]{raw}} vector consisting of a
#' well-known binary (\acronym{WKB}) geometry representation of type
#' MultiLineString.
#'
#' When this function is run in TIBCO Enterprise Runtime for R
#' (\acronym{TERR}), the return value has the SpotfireColumnMetaData attribute
#' set to enable TIBCO Spotfire to recognize it as a \acronym{WKB} geometry
#' representation.
#' @examples
#' # load package sp
#' library(sp)
#'
#' # create an object of class SpatialLines
#' l1 <- data.frame(x = c(1, 2, 3), y = c(3, 2, 2))
#' l1a <- data.frame(x = l1[, 1] + .05, y = l1[, 2] + .05)
#' l2 <- data.frame(x = c(1, 2, 3), y = c(1, 1.5, 1))
#' Sl1 <- Line(l1)
#' Sl1a <- Line(l1a)
#' Sl2 <- Line(l2)
#' S1 <- Lines(list(Sl1, Sl1a), ID = "a")
#' S2 <- Lines(list(Sl2), ID = "b")
#' Sl <- SpatialLines(list(S1, S2))
#'
#' # convert to WKB MultiLineString
#' wkb <- wkb:::SpatialLinesToWKBMultiLineString(Sl)
#'
#' # use as a column in a data frame
#' ds <- data.frame(ID = names(Sl), Geometry = wkb)
#'
#' # calculate envelope columns and cbind to the data frame
#' coords <- wkb:::SpatialLinesEnvelope(Sl)
#' ds <- cbind(ds, coords)
#' @seealso \code{\link{writeWKB}}, \code{\link{SpatialLinesToWKBLineString}},
#' \code{\link{SpatialLinesEnvelope}}
#' @noRd
SpatialLinesToWKBMultiLineString <- function(obj, endian) {
wkb <- lapply(X = obj@lines, FUN = function(mylines) {
rc <- rawConnection(raw(0), "r+")
on.exit(close(rc))
if(endian == "big") {
writeBin(as.raw(0L), rc)
} else {
writeBin(as.raw(1L), rc)
}
writeBin(5L, rc, size = 4, endian = endian)
lineStrings <- mylines@Lines
writeBin(length(lineStrings), rc, size = 4, endian = endian)
lapply(X = lineStrings, FUN = function(myline) {
if(endian == "big") {
writeBin(as.raw(0L), rc)
} else {
writeBin(as.raw(1L), rc)
}
writeBin(2L, rc, size = 4, endian = endian)
coords <- myline@coords
writeBin(nrow(coords), rc, size = 4, endian = endian)
apply(X = coords, MARGIN = 1, FUN = function(coord) {
writeBin(coord[1], rc, size = 8, endian = endian)
writeBin(coord[2], rc, size = 8, endian = endian)
NULL
})
})
rawConnectionValue(rc)
})
if(identical(version$language, "TERR")) {
attr(wkb, "SpotfireColumnMetaData") <-
list(ContentType = "application/x-wkb", MapChart.ColumnTypeId = "Geometry")
}
I(wkb)
}
#' Convert SpatialLines to \acronym{WKB} LineString
#'
#' Converts an object of class \code{SpatialLines} or
#' \code{SpatialLinesDataFrame} to a list of well-known binary (\acronym{WKB})
#' geometry representations of type LineString.
#'
#' The argument \code{obj} must have only one object of class \code{Lines} in
#' each position of the \code{list} in slot \code{lines}. If there are multiple
#' objects of class \code{Lines} in each position of the \code{list} in slot
#' \code{lines}, use \code{\link{SpatialLinesToWKBMultiLineString}}.
#'
#' @param obj an object of class
#' \code{\link[sp:SpatialLines-class]{SpatialLines}} or
#' \code{\link[sp:SpatialLinesDataFrame-class]{SpatialLinesDataFrame}}.
#' @param endian The byte order (\code{"big"} or \code{"little"}) for encoding
#' numeric types. The default is \code{"little"}.
#' @return A \code{list} with class \code{AsIs}. The length of the returned list
#' is the same as the length of the argument \code{obj}. Each element of the
#' returned list is a \code{\link[base]{raw}} vector consisting of a
#' well-known binary (\acronym{WKB}) geometry representation of type
#' LineString.
#'
#' When this function is run in TIBCO Enterprise Runtime for R
#' (\acronym{TERR}), the return value has the SpotfireColumnMetaData attribute
#' set to enable TIBCO Spotfire to recognize it as a \acronym{WKB} geometry
#' representation.
#' @examples
#' # create an object of class SpatialLines
#' l1 <- data.frame(x = c(1, 2, 3), y = c(3, 2, 2))
#' l2 <- data.frame(x = c(1, 2, 3), y = c(1, 1.5, 1))
#' Sl1 <- Line(l1)
#' Sl2 <- Line(l2)
#' S1 <- Lines(list(Sl1), ID = "a")
#' S2 <- Lines(list(Sl2), ID = "b")
#' Sl <- SpatialLines(list(S1, S2))
#'
#' # convert to WKB LineString
#' wkb <- wkb:::SpatialLinesToWKBLineString(Sl)
#'
#' # use as a column in a data frame
#' ds <- data.frame(ID = names(Sl), Geometry = wkb)
#'
#' # calculate envelope columns and cbind to the data frame
#' coords <- wkb:::SpatialLinesEnvelope(Sl)
#' ds <- cbind(ds, coords)
#' @seealso \code{\link{writeWKB}},
#' \code{\link{SpatialLinesToWKBMultiLineString}},
#' \code{\link{SpatialLinesEnvelope}}
#' @noRd
SpatialLinesToWKBLineString <- function(obj, endian) {
wkb <- lapply(X = obj@lines, FUN = function(mylines) {
rc <- rawConnection(raw(0), "r+")
on.exit(close(rc))
if(endian == "big") {
writeBin(as.raw(0L), rc)
} else {
writeBin(as.raw(1L), rc)
}
writeBin(2L, rc, size = 4, endian = endian)
lineStrings <- mylines@Lines
if(isTRUE(length(lineStrings) > 1)) {
stop("Argument obj must have only one object of class Lines in each ",
"position of the list in slot lines. Use ",
"SpatialLinesToWKBMultiLineString instead of ",
"SpatialLinesToWKBLineString.")
}
myline <- lineStrings[[1]]
coords <- myline@coords
writeBin(nrow(coords), rc, size = 4, endian = endian)
apply(X = coords, MARGIN = 1, FUN = function(coord) {
writeBin(coord[1], rc, size = 8, endian = endian)
writeBin(coord[2], rc, size = 8, endian = endian)
NULL
})
rawConnectionValue(rc)
})
if(identical(version$language, "TERR")) {
attr(wkb, "SpotfireColumnMetaData") <-
list(ContentType = "application/x-wkb", MapChart.ColumnTypeId = "Geometry")
}
I(wkb)
}
#' Envelope of SpatialLines
#'
#' Takes an object of class \code{SpatialLines} or \code{SpatialLinesDataFrame}
#' and returns a data frame with six columns representing the envelope of each
#' object of class \code{Lines}.
#'
#' This function is called by the \code{\link{writeEnvelope}} function. Call the
#' \code{\link{writeEnvelope}} function instead of calling this function
#' directly.
#'
#' @param obj an object of class
#' \code{\link[sp:SpatialLines-class]{SpatialLines}} or
#' \code{\link[sp:SpatialLinesDataFrame-class]{SpatialLinesDataFrame}}.
#' @param centerfun function to apply to the x-axis limits and y-axis limits of
#' the bounding box to obtain the x-coordinate and y-coordinate of the center
#' of the bounding box.
#' @return A data frame with six columns named XMax, XMin, YMax, YMin, XCenter,
#' and YCenter. The first four columns represent the corners of the bounding
#' box of each object of class \code{Lines}. The last two columns represent
#' the center of the bounding box of each object of class \code{Lines}. The
#' number of rows in the returned data frame is the same as the length of the
#' argument \code{obj}.
#'
#' When this function is run in TIBCO Enterprise Runtime for R
#' (\acronym{TERR}), the columns of the returned data frame have the
#' SpotfireColumnMetaData attribute set to enable TIBCO Spotfire to recognize
#' them as containing envelope information.
#' @seealso \code{\link{writeEnvelope}}
#'
#' Example usage at \code{\link{SpatialLinesToWKBMultiLineString}}
#' @noRd
#' @importFrom sp bbox
SpatialLinesEnvelope <- function(obj, centerfun = mean) {
if(is.character(centerfun)) {
centerfun <- eval(parse(text = centerfun))
}
coords <- as.data.frame(t(vapply(X = obj@lines, FUN = function(mylines) {
c(XMax = bbox(mylines)["x", "max"],
XMin = bbox(mylines)["x", "min"],
YMax = bbox(mylines)["y", "max"],
YMin = bbox(mylines)["y", "min"],
XCenter = centerfun(bbox(mylines)["x", ], na.rm = TRUE),
YCenter = centerfun(bbox(mylines)["y", ], na.rm = TRUE))
}, FUN.VALUE = rep(0, 6))))
if(identical(version$language, "TERR")) {
attr(coords$XMax, "SpotfireColumnMetaData") <- list(MapChart.ColumnTypeId = "XMax")
attr(coords$XMin, "SpotfireColumnMetaData") <- list(MapChart.ColumnTypeId = "XMin")
attr(coords$YMax, "SpotfireColumnMetaData") <- list(MapChart.ColumnTypeId = "YMax")
attr(coords$YMin, "SpotfireColumnMetaData") <- list(MapChart.ColumnTypeId = "YMin")
attr(coords$XCenter, "SpotfireColumnMetaData") <- list(MapChart.ColumnTypeId = "XCenter")
attr(coords$YCenter, "SpotfireColumnMetaData") <- list(MapChart.ColumnTypeId = "YCenter")
}
coords
}
|
/scratch/gouwar.j/cran-all/cranData/wkb/R/SpatialLinesToWKBLineString.R
|
# Convert a SpatialPoints or SpatialPointsDataFrame object
# to a well-known binary (WKB) geometry representation of points
#' Convert List of SpatialPoints to \acronym{WKB} MultiPoint
#'
#' Converts a list of objects of class \code{SpatialPoints} or
#' \code{SpatialPointsDataFrame} to a list of well-known binary (\acronym{WKB})
#' geometry representations of type MultiPoint.
#'
#' This function is called by the \code{\link{writeWKB}} function. Call the
#' \code{\link{writeWKB}} function instead of calling this function directly.
#'
#' Use this function when each item in the \acronym{WKB} representation should
#' represent multiple points. Use \code{\link{SpatialPointsToWKBPoint}} when
#' each item in the \acronym{WKB} representation should represent only one
#' point.
#'
#' @param obj a \code{list} in which each element is an object of class
#' \code{\link[sp:SpatialPoints-class]{SpatialPoints}} or
#' \code{\link[sp:SpatialPointsDataFrame-class]{SpatialPointsDataFrame}}.
#' @param endian The byte order (\code{"big"} or \code{"little"}) for encoding
#' numeric types. The default is \code{"little"}.
#' @return A \code{list} with class \code{AsIs}. The length of the returned list
#' is the same as the length of the argument \code{obj}. Each element of the
#' returned list is a \code{\link[base]{raw}} vector consisting of a
#' well-known binary (\acronym{WKB}) geometry representation of type
#' MultiPoint.
#'
#' When this function is run in TIBCO Enterprise Runtime for R
#' (\acronym{TERR}), the return value has the SpotfireColumnMetaData attribute
#' set to enable TIBCO Spotfire to recognize it as a \acronym{WKB} geometry
#' representation.
#' @examples
#' # load package sp
#' library(sp)
#'
#' # create a list of objects of class SpatialPoints
#' x1 = c(1, 2, 3, 4, 5)
#' y1 = c(3, 2, 5, 1, 4)
#' x2 <- c(9, 10, 11, 12, 13)
#' y2 <- c(-1, -2, -3, -4, -5)
#' Sp1 <- SpatialPoints(data.frame(x1, y1))
#' Sp2 <- SpatialPoints(data.frame(x2, y2))
#' obj <- list("a"=Sp1, "b"=Sp2)
#'
#' # convert to WKB MultiPoint
#' wkb <- wkb:::ListOfSpatialPointsToWKBMultiPoint(obj)
#'
#' # use as a column in a data frame
#' ds <- data.frame(ID = names(obj), Geometry = wkb)
#'
#' # calculate envelope columns and cbind to the data frame
#' coords <- wkb:::ListOfSpatialPointsEnvelope(obj)
#' ds <- cbind(ds, coords)
#' @seealso \code{\link{writeWKB}}, \code{\link{SpatialPointsToWKBPoint}},
#' \code{\link{ListOfSpatialPointsEnvelope}}
#' @noRd
ListOfSpatialPointsToWKBMultiPoint <- function(obj, endian) {
wkb <- lapply(X = obj, FUN = function(mypoints) {
rc <- rawConnection(raw(0), "r+")
on.exit(close(rc))
if(endian == "big") {
writeBin(as.raw(0L), rc)
} else {
writeBin(as.raw(1L), rc)
}
writeBin(4L, rc, size = 4, endian = endian)
coords <- mypoints@coords
writeBin(nrow(coords), rc, size = 4, endian = endian)
apply(X = coords, MARGIN = 1, FUN = function(coord) {
if(endian == "big") {
writeBin(as.raw(0L), rc)
} else {
writeBin(as.raw(1L), rc)
}
writeBin(1L, rc, size = 4, endian = endian)
writeBin(coord[1], rc, size = 8, endian = endian)
writeBin(coord[2], rc, size = 8, endian = endian)
NULL
})
rawConnectionValue(rc)
})
if(identical(version$language, "TERR")) {
attr(wkb, "SpotfireColumnMetaData") <-
list(ContentType = "application/x-wkb", MapChart.ColumnTypeId = "Geometry")
}
I(wkb)
}
#' Convert SpatialPoints to \acronym{WKB} Point
#'
#' Converts an object of class \code{SpatialPoints} or
#' \code{SpatialPointsDataFrame} to a list of well-known binary (\acronym{WKB})
#' geometry representations of type Point.
#'
#' This function is called by the \code{\link{writeWKB}} function. Call the
#' \code{\link{writeWKB}} function instead of calling this function directly.
#'
#' Use this function when each item in the \acronym{WKB} representation should
#' represent only one point. Use
#' \code{\link{ListOfSpatialPointsToWKBMultiPoint}} when each item in the
#' \acronym{WKB} representation should represent multiple points.
#'
#' @param obj an object of class
#' \code{\link[sp:SpatialPoints-class]{SpatialPoints}} or
#' \code{\link[sp:SpatialPointsDataFrame-class]{SpatialPointsDataFrame}}.
#' @param endian The byte order (\code{"big"} or \code{"little"}) for encoding
#' numeric types. The default is \code{"little"}.
#' @return A \code{list} with class \code{AsIs}. The length of the returned list
#' is the same as the length of the argument \code{obj}. Each element of the
#' returned list is a \code{\link[base]{raw}} vector consisting of a
#' well-known binary (\acronym{WKB}) geometry representation of type Point.
#'
#' When this function is run in TIBCO Enterprise Runtime for R
#' (\acronym{TERR}), the return value has the SpotfireColumnMetaData attribute
#' set to enable TIBCO Spotfire to recognize it as a \acronym{WKB} geometry
#' representation.
#' @examples
#' # create an object of class SpatialPoints
#' x = c(1, 2, 3, 4, 5)
#' y = c(3, 2, 5, 1, 4)
#' Sp <- SpatialPoints(data.frame(x, y))
#'
#' # convert to WKB Point
#' wkb <- wkb:::SpatialPointsToWKBPoint(Sp)
#'
#' # use as a column in a data frame
#' ds <- data.frame(ID = c("a", "b", "c", "d", "e"), Geometry = wkb)
#'
#' # calculate envelope and center columns and cbind to the data frame
#' coords <- wkb:::SpatialPointsEnvelope(Sp)
#' ds <- cbind(ds, coords)
#' @seealso \code{\link{writeWKB}},
#' \code{\link{ListOfSpatialPointsToWKBMultiPoint}},
#' \code{\link{SpatialPointsEnvelope}}
#' @noRd
SpatialPointsToWKBPoint <- function(obj, endian) {
wkb <- lapply(apply(X = obj@coords, MARGIN = 1, FUN = function(coord) {
rc <- rawConnection(raw(0), "r+")
on.exit(close(rc))
if(endian == "big") {
writeBin(as.raw(0L), rc)
} else {
writeBin(as.raw(1L), rc)
}
writeBin(1L, rc, size = 4, endian = endian)
writeBin(coord[1], rc, size = 8, endian = endian)
writeBin(coord[2], rc, size = 8, endian = endian)
list(rawConnectionValue(rc))
}), unlist)
if(identical(version$language, "TERR")) {
attr(wkb, "SpotfireColumnMetaData") <-
list(ContentType = "application/x-wkb", MapChart.ColumnTypeId = "Geometry")
}
I(wkb)
}
#' Envelope of List of SpatialPoints
#'
#' Takes a list of objects of class \code{SpatialPoints} or
#' \code{SpatialPointsDataFrame} and returns a data frame with six columns
#' representing the envelope of each object of class \code{SpatialPoints} or
#' \code{SpatialPointsDataFrame}.
#'
#' This function is called by the \code{\link{writeEnvelope}} function. Call the
#' \code{\link{writeEnvelope}} function instead of calling this function
#' directly.
#'
#' @param obj an object of class
#' \code{\link[sp:SpatialPoints-class]{SpatialPoints}} or
#' \code{\link[sp:SpatialPointsDataFrame-class]{SpatialPointsDataFrame}}.
#' @param centerfun function to apply to the x-axis limits and y-axis limits of
#' the bounding box to obtain the x-coordinate and y-coordinate of the center
#' of the bounding box.
#' @return A data frame with six columns named XMax, XMin, YMax, YMin, XCenter,
#' and YCenter. The first four columns represent the corners of the bounding
#' box of each object of class \code{SpatialPoints} or
#' \code{SpatialPointsDataFrame}. The last two columns represent the center of
#' the bounding box of each object of class \code{SpatialPoints} or
#' \code{SpatialPointsDataFrame}. The number of rows in the returned data
#' frame is the same as the length of the argument \code{obj}.
#'
#' When this function is run in TIBCO Enterprise Runtime for R
#' (\acronym{TERR}), the columns of the returned data frame have the
#' SpotfireColumnMetaData attribute set to enable TIBCO Spotfire to recognize
#' them as containing envelope information.
#' @seealso \code{\link{writeEnvelope}}
#'
#' Example usage at \code{\link{ListOfSpatialPointsToWKBMultiPoint}}
#' @noRd
#' @importFrom sp bbox
ListOfSpatialPointsEnvelope <- function(obj, centerfun = mean) {
if(is.character(centerfun)) {
centerfun <- eval(parse(text = centerfun))
}
coords <- as.data.frame(t(vapply(X = obj, FUN = function(mypoints) {
c(XMax = bbox(mypoints)[1, "max"],
XMin = bbox(mypoints)[1, "min"],
YMax = bbox(mypoints)[2, "max"],
YMin = bbox(mypoints)[2, "min"],
XCenter = centerfun(bbox(mypoints)[1, ], na.rm = TRUE),
YCenter = centerfun(bbox(mypoints)[2, ], na.rm = TRUE))
}, FUN.VALUE = rep(0, 6))))
if(identical(version$language, "TERR")) {
attr(coords$XMax, "SpotfireColumnMetaData") <- list(MapChart.ColumnTypeId = "XMax")
attr(coords$XMin, "SpotfireColumnMetaData") <- list(MapChart.ColumnTypeId = "XMin")
attr(coords$YMax, "SpotfireColumnMetaData") <- list(MapChart.ColumnTypeId = "YMax")
attr(coords$YMin, "SpotfireColumnMetaData") <- list(MapChart.ColumnTypeId = "YMin")
attr(coords$XCenter, "SpotfireColumnMetaData") <- list(MapChart.ColumnTypeId = "XCenter")
attr(coords$YCenter, "SpotfireColumnMetaData") <- list(MapChart.ColumnTypeId = "YCenter")
}
coords
}
#' Envelope of SpatialPoints
#'
#' Takes an object of class \code{SpatialPoints} or
#' \code{SpatialPointsDataFrame} and returns a data frame with six columns
#' representing the envelope of each point (which is each point itself).
#'
#' This function is called by the \code{\link{writeEnvelope}} function. Call the
#' \code{\link{writeEnvelope}} function instead of calling this function
#' directly.
#'
#' @param obj an object of class
#' \code{\link[sp:SpatialPoints-class]{SpatialPoints}} or
#' \code{\link[sp:SpatialPointsDataFrame-class]{SpatialPointsDataFrame}}.
#' @return A data frame with six columns named XMax, XMin, YMax, YMin, XCenter,
#' and YCenter. The first four columns represent the corners of the bounding
#' box of each point. The last two columns represent the center of the
#' bounding box of each point. (Note that the bounding box of a point is the
#' point itself.) The number of rows in the returned data frame is the same as
#' the length of the argument \code{obj}.
#'
#' When this function is run in TIBCO Enterprise Runtime for R
#' (\acronym{TERR}), the columns of the returned data frame have the
#' SpotfireColumnMetaData attribute set to enable TIBCO Spotfire to recognize
#' them as containing envelope information.
#' @seealso \code{\link{writeEnvelope}}
#'
#' Example usage at \code{\link{SpatialPointsToWKBPoint}}
#' @noRd
SpatialPointsEnvelope <- function(obj) {
coords <- as.data.frame(t(apply(X = obj@coords, MARGIN = 1, FUN = function(coord) {
c(coord[1], # XMax
coord[1], # XMin
coord[2], # YMax
coord[2], # YMin
coord[1], # XCenter
coord[2]) # YCenter
})))
colnames(coords) <- c("XMax", "XMin", "YMax", "YMin", "XCenter", "YCenter")
if(identical(version$language, "TERR")) {
attr(coords$XMax, "SpotfireColumnMetaData") <- list(MapChart.ColumnTypeId = "XMax")
attr(coords$XMin, "SpotfireColumnMetaData") <- list(MapChart.ColumnTypeId = "XMin")
attr(coords$YMax, "SpotfireColumnMetaData") <- list(MapChart.ColumnTypeId = "YMax")
attr(coords$YMin, "SpotfireColumnMetaData") <- list(MapChart.ColumnTypeId = "YMin")
attr(coords$XCenter, "SpotfireColumnMetaData") <- list(MapChart.ColumnTypeId = "XCenter")
attr(coords$YCenter, "SpotfireColumnMetaData") <- list(MapChart.ColumnTypeId = "YCenter")
}
coords
}
|
/scratch/gouwar.j/cran-all/cranData/wkb/R/SpatialPointsToWKBPoint.R
|
# Convert a SpatialPolygons or SpatialPolygonsDataFrame object
# to a well-known binary (WKB) geometry representation of polygons
#' Convert SpatialPolygons to \acronym{WKB} MultiPolygon
#'
#' Converts an object of class \code{SpatialPolygons} or
#' \code{SpatialPolygonsDataFrame} to a list of well-known binary
#' (\acronym{WKB}) geometry representations of type MultiPolygon.
#'
#' This function is called by the \code{\link{writeWKB}} function. Call the
#' \code{\link{writeWKB}} function instead of calling this function directly.
#'
#' @param obj an object of class
#' \code{\link[sp:SpatialPolygons-class]{SpatialPolygons}} or
#' \code{\link[sp:SpatialPolygonsDataFrame-class]{SpatialPolygonsDataFrame}}.
#' @param endian The byte order (\code{"big"} or \code{"little"}) for encoding
#' numeric types. The default is \code{"little"}.
#' @return A \code{list} with class \code{AsIs}. The length of the returned list
#' is the same as the length of the argument \code{obj}. Each element of the
#' returned list is a \code{\link[base]{raw}} vector consisting of a
#' well-known binary (\acronym{WKB}) geometry representation of type
#' MultiPolygon.
#'
#' When this function is run in TIBCO Enterprise Runtime for R
#' (\acronym{TERR}), the return value has the SpotfireColumnMetaData attribute
#' set to enable TIBCO Spotfire to recognize it as a \acronym{WKB} geometry
#' representation.
#' @examples
#' # load package sp
#' library(sp)
#'
#' # create an object of class SpatialPolygons
#' triangle <- Polygons(
#' list(
#' Polygon(data.frame(x = c(2, 2.5, 3, 2), y = c(2, 3, 2, 2)))
#' ), "triangle")
#' rectangles <- Polygons(
#' list(
#' Polygon(data.frame(x = c(0, 0, 1, 1, 0), y = c(0, 1, 1, 0, 0))),
#' Polygon(data.frame(x = c(0, 0, 2, 2, 0), y = c(-2, -1, -1, -2, -2)))
#' ), "rectangles")
#' Sp <- SpatialPolygons(list(triangle, rectangles))
#'
#' # convert to WKB MultiPolygon
#' wkb <- wkb:::SpatialPolygonsToWKBMultiPolygon(Sp)
#'
#' # use as a column in a data frame
#' ds <- data.frame(ID = names(Sp), Geometry = wkb)
#'
#' # calculate envelope columns and cbind to the data frame
#' coords <- wkb:::SpatialPolygonsEnvelope(Sp)
#' ds <- cbind(ds, coords)
#' @seealso \code{\link{writeWKB}}, \code{\link{SpatialPolygonsEnvelope}}
#' @noRd
SpatialPolygonsToWKBMultiPolygon <- function(obj, endian) {
wkb <- lapply(X = obj@polygons, FUN = function(mymultipolygon) {
rc <- rawConnection(raw(0), "r+")
on.exit(close(rc))
if(endian == "big") {
writeBin(as.raw(0L), rc)
} else {
writeBin(as.raw(1L), rc)
}
writeBin(6L, rc, size = 4, endian = endian)
mypolygons <- mymultipolygon@Polygons
writeBin(length(mypolygons), rc, size = 4, endian = endian)
lapply(X = mypolygons, FUN = function(mypolygon) {
if(endian == "big") {
writeBin(as.raw(0L), rc)
} else {
writeBin(as.raw(1L), rc)
}
writeBin(3L, rc, size = 4, endian = endian)
writeBin(1L, rc, size = 4, endian = endian)
coords <- mypolygon@coords
writeBin(nrow(coords), rc, size = 4, endian = endian)
apply(X = coords, MARGIN = 1, FUN = function(coord) {
writeBin(coord[1], rc, size = 8, endian = endian)
writeBin(coord[2], rc, size = 8, endian = endian)
NULL
})
})
rawConnectionValue(rc)
})
if(identical(version$language, "TERR")) {
attr(wkb, "SpotfireColumnMetaData") <-
list(ContentType = "application/x-wkb", MapChart.ColumnTypeId = "Geometry")
}
I(wkb)
}
#' Convert SpatialPolygons to \acronym{WKB} Polygon
#'
#' Converts an object of class \code{SpatialPolygons} or
#' \code{SpatialPolygonsDataFrame} to a list of well-known binary
#' (\acronym{WKB}) geometry representations of type Polygon.
#'
#' This function is called by the \code{\link{writeWKB}} function. Call the
#' \code{\link{writeWKB}} function instead of calling this function directly.
#'
#' @param obj an object of class
#' \code{\link[sp:SpatialPolygons-class]{SpatialPolygons}} or
#' \code{\link[sp:SpatialPolygonsDataFrame-class]{SpatialPolygonsDataFrame}}.
#' @param endian The byte order (\code{"big"} or \code{"little"}) for encoding
#' numeric types. The default is \code{"little"}.
#' @return A \code{list} with class \code{AsIs}. The length of the returned list
#' is the same as the length of the argument \code{obj}. Each element of the
#' returned list is a \code{\link[base]{raw}} vector consisting of a
#' well-known binary (\acronym{WKB}) geometry representation of type Polygon.
#'
#' When this function is run in TIBCO Enterprise Runtime for R
#' (\acronym{TERR}), the return value has the SpotfireColumnMetaData attribute
#' set to enable TIBCO Spotfire to recognize it as a \acronym{WKB} geometry
#' representation.
#' @examples
#' # load package sp
#' library(sp)
#'
#' # create an object of class SpatialPolygons
#' triangle <- Polygons(
#' list(
#' Polygon(data.frame(x = c(2, 2.5, 3, 2), y = c(2, 3, 2, 2)))
#' ), "triangle")
#' rectangles <- Polygons(
#' list(
#' Polygon(data.frame(x = c(0, 0, 1, 1, 0), y = c(0, 1, 1, 0, 0))),
#' Polygon(data.frame(x = c(0, 0, 2, 2, 0), y = c(-2, -1, -1, -2, -2)))
#' ), "rectangles")
#' Sp <- SpatialPolygons(list(triangle, rectangles))
#'
#' # convert to WKB Polygon
#' wkb <- wkb:::SpatialPolygonsToWKBPolygon(Sp)
#'
#' # use as a column in a data frame
#' ds <- data.frame(ID = names(Sp), Geometry = wkb)
#'
#' # calculate envelope columns and cbind to the data frame
#' coords <- wkb:::SpatialPolygonsEnvelope(Sp)
#' ds <- cbind(ds, coords)
#' @seealso \code{\link{writeWKB}}, \code{\link{SpatialPolygonsEnvelope}}
#' @noRd
SpatialPolygonsToWKBPolygon <- function(obj, endian) {
wkb <- lapply(X = obj@polygons, FUN = function(mypolygon) {
rc <- rawConnection(raw(0), "r+")
on.exit(close(rc))
if(endian == "big") {
writeBin(as.raw(0L), rc)
} else {
writeBin(as.raw(1L), rc)
}
writeBin(3L, rc, size = 4, endian = endian)
rings <- mypolygon@Polygons
writeBin(length(rings), rc, size = 4, endian = endian)
lapply(X = rings, FUN = function(ring) {
coords <- ring@coords
writeBin(nrow(coords), rc, size = 4, endian = endian)
apply(X = coords, MARGIN = 1, FUN = function(coord) {
writeBin(coord[1], rc, size = 8, endian = endian)
writeBin(coord[2], rc, size = 8, endian = endian)
NULL
})
})
rawConnectionValue(rc)
})
if(identical(version$language, "TERR")) {
attr(wkb, "SpotfireColumnMetaData") <-
list(ContentType = "application/x-wkb", MapChart.ColumnTypeId = "Geometry")
}
I(wkb)
}
#' Envelope of SpatialPolygons
#'
#' Takes an object of class \code{SpatialPolygons} or
#' \code{SpatialPolygonsDataFrame} and returns a data frame with six columns
#' representing the envelope of each object of class \code{Polygons}.
#'
#' This function is called by the \code{\link{writeEnvelope}} function. Call the
#' \code{\link{writeEnvelope}} function instead of calling this function
#' directly.
#'
#' @param obj an object of class
#' \code{\link[sp:SpatialPolygons-class]{SpatialPolygons}} or
#' \code{\link[sp:SpatialPolygonsDataFrame-class]{SpatialPolygonsDataFrame}}.
#' @return A data frame with six columns named XMax, XMin, YMax, YMin, XCenter,
#' and YCenter. The first four columns represent the corners of the bounding
#' box of each object of class \code{Polygons}. The last two columns represent
#' the center of the bounding box of each object of class \code{Polygons}. The
#' number of rows in the returned data frame is the same as the length of the
#' argument \code{obj}.
#'
#' When this function is run in TIBCO Enterprise Runtime for R
#' (\acronym{TERR}), the columns of the returned data frame have the
#' SpotfireColumnMetaData attribute set to enable TIBCO Spotfire to recognize
#' them as containing envelope information.
#' @seealso \code{\link{writeEnvelope}}
#'
#' Example usage at \code{\link{SpatialPolygonsToWKBPolygon}}
#' @noRd
#' @importFrom sp bbox
SpatialPolygonsEnvelope <- function(obj) {
coords <- as.data.frame(t(vapply(X = obj@polygons, FUN = function(mypolygon) {
c(XMax = bbox(mypolygon)["x", "max"],
XMin = bbox(mypolygon)["x", "min"],
YMax = bbox(mypolygon)["y", "max"],
YMin = bbox(mypolygon)["y", "min"],
XCenter = mypolygon@labpt[1],
YCenter = mypolygon@labpt[2])
}, FUN.VALUE = rep(0, 6))))
if(identical(version$language, "TERR")) {
attr(coords$XMax, "SpotfireColumnMetaData") <- list(MapChart.ColumnTypeId = "XMax")
attr(coords$XMin, "SpotfireColumnMetaData") <- list(MapChart.ColumnTypeId = "XMin")
attr(coords$YMax, "SpotfireColumnMetaData") <- list(MapChart.ColumnTypeId = "YMax")
attr(coords$YMin, "SpotfireColumnMetaData") <- list(MapChart.ColumnTypeId = "YMin")
attr(coords$XCenter, "SpotfireColumnMetaData") <- list(MapChart.ColumnTypeId = "XCenter")
attr(coords$YCenter, "SpotfireColumnMetaData") <- list(MapChart.ColumnTypeId = "YCenter")
}
coords
}
|
/scratch/gouwar.j/cran-all/cranData/wkb/R/SpatialPolygonsToWKBPolygon.R
|
# Convert a string hexadecimal representation to a raw vector
#' Convert String Hex Representation to Raw Vector
#'
#' Converts a string hexadecimal representation to a \code{raw} vector.
#'
#' @param hex character string or character vector containing a hexadecimal
#' representation.
#' @details Non-hexadecimal characters are removed.
#' @return A \code{\link[base]{raw}} vector.
#'
#' The return value is a \code{list} of \code{raw} vectors when the argument
#' \code{hex} contains more than one hexadecimal representation.
#' @examples
#' # create a character string containing a hexadecimal representation
#' hex <- "0101000000000000000000f03f0000000000000840"
#'
#' # convert to raw vector
#' wkb <- hex2raw(hex)
#'
#'
#' # create a character vector containing a hexadecimal representation
#' hex <- c("01", "01", "00", "00", "00", "00", "00", "00", "00", "00", "00",
#' "f0", "3f", "00", "00", "00", "00", "00", "00", "08", "40")
#'
#' # convert to raw vector
#' wkb <- hex2raw(hex)
#'
#'
#' # create vector of two character strings each containing a hex representation
#' hex <- c("0101000000000000000000f03f0000000000000840",
#' "010100000000000000000000400000000000000040")
#'
#' # convert to list of two raw vectors
#' wkb <- hex2raw(hex)
#' @seealso \code{raw2hex} in package
#' \href{https://cran.r-project.org/package=PKI}{\pkg{PKI}}, \code{\link{readWKB}}
#' @export
hex2raw <- function(hex) {
if(!(is.character(hex) || (is.list(hex) &&
all(vapply(X = hex, FUN = is.character, FUN.VALUE = logical(1)))))) {
stop("hex must be a character string or character vector")
}
if(is.list(hex) || (length(hex) > 1 &&
all(vapply(X = hex, FUN = nchar, FUN.VALUE = integer(1)) > 2))) {
lapply(hex, .hex2raw)
} else {
.hex2raw(hex)
}
}
.hex2raw <- function(hex) {
hex <- gsub("[^0-9a-fA-F]", "", hex)
if(length(hex) == 1) {
if(nchar(hex) < 2 || nchar(hex) %% 2 != 0) {
stop("hex is not a valid hexadecimal representation")
}
hex <- strsplit(hex, character(0))[[1]]
hex <- paste(hex[c(TRUE, FALSE)], hex[c(FALSE, TRUE)], sep = "")
}
if(!all(vapply(X = hex, FUN = nchar, FUN.VALUE = integer(1)) == 2)) {
stop("hex is not a valid hexadecimal representation")
}
as.raw(as.hexmode(hex))
}
|
/scratch/gouwar.j/cran-all/cranData/wkb/R/hex2raw.R
|
# Convert a well-known binary (WKB) geometry representation to an R spatial
# object
#' Convert \acronym{WKB} to Spatial Objects
#'
#' Converts well-known binary (\acronym{WKB}) geometry representations to
#' \code{Spatial} objects.
#'
#' @param wkb \code{list} in which each element is a \code{\link[base]{raw}}
#' vector consisting of a \acronym{WKB} geometry representation.
#' @param id character vector of unique identifiers of geometries. The length of
#' \code{id} must be the same as the length of the \code{wkb} list.
#' @param proj4string projection string of class
#' \code{\link[sp:CRS-class]{CRS}}.
#' @details Supported \acronym{WKB} geometry types are Point, LineString,
#' Polygon, MultiPoint, MultiLineString, and MultiPolygon. All elements in the
#' \code{list} must have the same \acronym{WKB} geometry type. The
#' \acronym{WKB} geometry representations may use little-endian or big-endian
#' byte order.
#'
#' The argument \code{wkb} may also be a \code{\link[base]{raw}} vector
#' consisting of one \acronym{WKB} geometry representation. In that case, the
#' argument \code{id} must have length one.
#' @return An object inheriting class \code{\link[sp:Spatial-class]{Spatial}}.
#'
#' The return value may be an object of class
#' \code{\link[sp:SpatialPoints-class]{SpatialPoints}},
#' \code{\link[sp:SpatialLines-class]{SpatialLines}},
#' \code{\link[sp:SpatialPolygons-class]{SpatialPolygons}}, or a \code{list}
#' in which each element is an object of class
#' \code{\link[sp:SpatialPoints-class]{SpatialPoints}}. The class of the
#' return value depends on the \acronym{WKB} geometry type as shown in the
#' table below.
#'
#' \tabular{ll}{
#' \strong{Type of \acronym{WKB} geometry} \tab \strong{Class of return value}\cr
#' Point \tab \code{SpatialPoints}\cr
#' LineString \tab \code{SpatialLines}\cr
#' Polygon \tab \code{SpatialPolygons}\cr
#' MultiPoint \tab \code{list} of \code{SpatialPoints}\cr
#' MultiLineString \tab \code{SpatialLines}\cr
#' MultiPolygon \tab \code{SpatialPolygons}\cr
#' }
#' @examples
#' # create a list of WKB geometry representations of type Point
#' wkb <- list(
#' as.raw(c(0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
#' 0xf0, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x40)),
#' as.raw(c(0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
#' 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40))
#' )
#'
#' # convert to object of class SpatialPoints
#' obj <- readWKB(wkb)
#'
#'
#' # create a list of WKB geometry representations of type MultiPoint
#' wkb <- list(
#' as.raw(c(0x01, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x01,
#' 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3f,
#' 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x40)),
#' as.raw(c(0x01, 0x04, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x01,
#' 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40,
#' 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40)))
#'
#' # convert to list of objects of class SpatialPoints
#' obj <- readWKB(wkb)
#'
#'
#' # create a list of WKB geometry representations of type MultiLineString
#' wkb <- list(
#' as.raw(c(0x01, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x02,
#' 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
#' 0x00, 0x00, 0xf0, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08,
#' 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00,
#' 0x00, 0x00, 0x00, 0x00, 0x00, 0x40)),
#' as.raw(c(0x01, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x02,
#' 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
#' 0x00, 0x00, 0xf0, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0,
#' 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00,
#' 0x00, 0x00, 0x00, 0x00, 0xf8, 0x3f)))
#'
#' # convert to object of class SpatialLines
#' obj <- readWKB(wkb)
#'
#'
#' # create a list of WKB geometry representations of type Polygon
#' wkb <- list(
#' as.raw(c(0x01, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x05, 0x00,
#' 0x00, 0x00, 0x34, 0x03, 0xf0, 0xac, 0xce, 0x66, 0x5d, 0xc0, 0x8f,
#' 0x27, 0x95, 0x21, 0xab, 0xa6, 0x44, 0x40, 0xa0, 0x32, 0x81, 0x18,
#' 0x78, 0x83, 0x5d, 0xc0, 0xc8, 0xd2, 0xa0, 0xee, 0x23, 0x0b, 0x41,
#' 0x40, 0x80, 0xec, 0x72, 0x54, 0xde, 0xb1, 0x5f, 0xc0, 0xc8, 0xd2,
#' 0xa0, 0xee, 0x23, 0x0b, 0x41, 0x40, 0xec, 0x1b, 0x04, 0xc0, 0x87,
#' 0xce, 0x5f, 0xc0, 0x8f, 0x27, 0x95, 0x21, 0xab, 0xa6, 0x44, 0x40,
#' 0x34, 0x03, 0xf0, 0xac, 0xce, 0x66, 0x5d, 0xc0, 0x8f, 0x27, 0x95,
#' 0x21, 0xab, 0xa6, 0x44, 0x40)),
#' as.raw(c(0x01, 0x03, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x05, 0x00,
#' 0x00, 0x00, 0x08, 0x36, 0xdc, 0x8b, 0x9f, 0x3d, 0x51, 0xc0, 0x0f,
#' 0xb3, 0x2a, 0x6a, 0x3f, 0x1c, 0x46, 0x40, 0x47, 0xcb, 0x54, 0xe7,
#' 0xcb, 0x5e, 0x51, 0xc0, 0x45, 0x81, 0x50, 0x31, 0xfa, 0x80, 0x42,
#' 0x40, 0xa9, 0xba, 0x74, 0x6d, 0xf5, 0xa1, 0x53, 0xc0, 0x45, 0x81,
#' 0x50, 0x31, 0xfa, 0x80, 0x42, 0x40, 0xe8, 0x4f, 0xed, 0xc8, 0x21,
#' 0xc3, 0x53, 0xc0, 0x0f, 0xb3, 0x2a, 0x6a, 0x3f, 0x1c, 0x46, 0x40,
#' 0x08, 0x36, 0xdc, 0x8b, 0x9f, 0x3d, 0x51, 0xc0, 0x0f, 0xb3, 0x2a,
#' 0x6a, 0x3f, 0x1c, 0x46, 0x40)))
#'
#' # convert to object of class SpatialPolygons
#' obj <- readWKB(wkb)
#'
#'
#' # specify id and proj4string
#' obj <- readWKB(
#' wkb,
#' id = c("San Francisco", "New York"),
#' proj4string = sp::CRS("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
#' )
#' @seealso \code{\link{writeWKB}}, \code{\link{hex2raw}}
#' @keywords wkb
#' @export
#' @importFrom sp CRS
#' @importFrom sp SpatialPoints
#' @importFrom sp SpatialLines
#' @importFrom sp SpatialPolygons
readWKB <- function(wkb, id = NULL, proj4string = CRS(as.character(NA))) {
if(inherits(wkb, "raw") && (is.null(id) || length(id) == 1)) {
wkb <- list(wkb)
}
if(!is.list(wkb)) {
stop("wkb must be a list")
}
if(isTRUE(length(wkb) < 1)) {
stop("wkb must have length 1 or greater")
}
if(!all(vapply(X = wkb, FUN = inherits, FUN.VALUE = logical(1), "raw"))) {
stop("Each element of wkb must be a raw vector")
}
namesSpecified <- TRUE
if(is.null(id)) {
if(is.null(names(wkb))) {
namesSpecified <- FALSE
id <- as.character(seq_along(wkb))
} else {
id <- names(wkb)
}
}
if(!identical(length(wkb), length(id))) {
stop("wkb and id must have same length")
}
if(is.character(proj4string)) {
proj4string = CRS(proj4string)
}
if(length(proj4string) != 1) {
stop("proj4string must have length 1")
}
obj <- mapply(wkb, id, FUN = function(WkbGeom, Id) {
rc <- rawConnection(WkbGeom, "r")
on.exit(close(rc))
seek(rc, 0L)
byteOrder <- readByteOrder(rc)
if(byteOrder == as.raw(1L)) {
endian <- "little"
} else {
endian <- "big"
}
wkbType <- readWkbType(rc, endian)
if(wkbType == 1L) {
readWkbPoint(rc, endian)
} else if(wkbType == 2L) {
readWkbLineString(rc, Id, endian)
} else if(wkbType == 3L) {
readWkbPolygon(rc, Id, endian)
} else if(wkbType == 4L) {
readWkbMultiPoint(rc, endian)
} else if(wkbType == 5L) {
readWkbMultiLineString(rc, Id, endian)
} else if(wkbType == 6L) {
readWkbMultiPolygon(rc, Id, endian)
} else if(wkbType == 7L) {
stop("GeometryCollection is not a supported geometry type")
} else {
stop("Supported geometry types are Point, LineString, Polygon, MultiPoint, MultiLineString, and MultiPolygon")
}
}, SIMPLIFY = FALSE, USE.NAMES = FALSE)
objClass <- unique(vapply(obj, function(x) class(x)[1], character(1)))
if(isTRUE(length(objClass) > 1)) {
stop("Elements of wkb cannot have different geometry types")
}
if(objClass == "numeric") {
if(namesSpecified) {
names(obj) <- id
}
SpatialPoints(do.call("rbind", obj), proj4string = proj4string)
} else if(objClass == "matrix" || objClass == "data.frame") {
if(namesSpecified) {
names(obj) <- id
}
lapply(X = obj, FUN = SpatialPoints, proj4string = proj4string)
} else if(objClass == "Lines") {
SpatialLines(obj, proj4string = proj4string)
} else if(objClass == "Polygons") {
SpatialPolygons(obj, proj4string = proj4string)
} else {
stop("Unexpected object")
}
}
readWkbMultiPoint <- function(rc, endian) {
numPoints <- readInteger(rc, endian)
t(vapply(seq_len(numPoints), function(...) {
byteOrder <- readByteOrder(rc)
if(byteOrder == as.raw(1L)) {
endian <- "little"
} else {
endian <- "big"
}
wkbType <- readWkbType(rc, endian)
if(wkbType != 1L) {
stop("MultiPoints may contain only Points")
}
readPoint(rc, endian)
}, numeric(2)))
}
#' @importFrom sp Lines
#' @importFrom sp Line
readWkbMultiLineString <- function(rc, multiLineStringId, endian) {
numLineStrings <- readInteger(rc, endian)
Lines(unlist(lapply(seq_len(numLineStrings), function(...) {
byteOrder <- readByteOrder(rc)
if(byteOrder == as.raw(1L)) {
endian <- "little"
} else {
endian <- "big"
}
wkbType <- readWkbType(rc, endian)
if(wkbType != 2L) {
stop("MultiLineStrings may contain only LineStrings")
}
numPoints <- readInteger(rc, endian)
Line(readPoints(rc, numPoints, endian))
})), multiLineStringId)
}
#' @importFrom sp Polygons
readWkbMultiPolygon <- function(rc, multiPolygonId, endian) {
numPolygons <- readInteger(rc, endian)
Polygons(unlist(lapply(seq_len(numPolygons), function(...) {
byteOrder <- readByteOrder(rc)
if(byteOrder == as.raw(1L)) {
endian <- "little"
} else {
endian <- "big"
}
wkbType <- readWkbType(rc, endian)
if(wkbType != 3L) {
stop("MultiPolygons may contain only Polygons")
}
numRings <- readInteger(rc, endian)
readLinearRings(rc, numRings, endian)
})), multiPolygonId)
}
readWkbPoint <- function(rc, endian) {
readPoint(rc, endian)
}
#' @importFrom sp Lines
#' @importFrom sp Line
readWkbLineString <- function(rc, lineStringId, endian) {
numPoints <- readInteger(rc, endian)
Lines(list(Line(readPoints(rc, numPoints, endian))), lineStringId)
}
#' @importFrom sp Polygons
readWkbPolygon <- function(rc, polygonId, endian) {
numRings <- readInteger(rc, endian)
Polygons(readLinearRings(rc, numRings, endian), polygonId)
}
readLinearRings <- function(rc, numRings, endian) {
lapply(seq_len(numRings), function(ringId) {
readLinearRing(rc, endian)
})
}
#' @importFrom sp Polygon
readLinearRing <- function(rc, endian) {
numPoints <- readInteger(rc, endian)
Polygon(readPoints(rc, numPoints, endian))
}
readPoints <- function(rc, numPoints, endian) {
t(vapply(seq_len(numPoints), function(pointId) {
readPoint(rc, endian)
}, numeric(2)))
}
readPoint <- function(rc, endian) {
c(x = readDouble(rc, endian), y = readDouble(rc, endian))
}
readByteOrder <- function(rc) {
readByte(rc)
}
readWkbType <- function(rc, endian) {
readInteger(rc, endian)
}
readByte <- function(rc) {
readBin(rc, what = "raw", size = 1L)
}
readInteger <- function(rc, endian) {
readBin(rc, what = "integer", size = 4L, endian = endian)
}
readDouble <- function(rc, endian) {
readBin(rc, what = "double", size = 8L, endian = endian)
}
|
/scratch/gouwar.j/cran-all/cranData/wkb/R/readWKB.R
|
# Envelope information from R spatial objects
#' Envelope of Spatial Objects
#'
#' Takes a \code{Spatial} object and returns a data frame with six columns
#' representing the envelope of each element in the \code{Spatial} object.
#'
#' @param obj object inheriting class \code{\link[sp:Spatial-class]{Spatial}}.
#' @details \code{obj} may be an object of class
#' \code{\link[sp:SpatialPoints-class]{SpatialPoints}},
#' \code{\link[sp:SpatialPointsDataFrame-class]{SpatialPointsDataFrame}},
#' \code{\link[sp:SpatialLines-class]{SpatialLines}},
#' \code{\link[sp:SpatialLinesDataFrame-class]{SpatialLinesDataFrame}},
#' \code{\link[sp:SpatialPolygons-class]{SpatialPolygons}}, or
#' \code{\link[sp:SpatialPolygonsDataFrame-class]{SpatialPolygonsDataFrame}},
#' or a \code{list} in which each element is an object of class
#' \code{\link[sp:SpatialPoints-class]{SpatialPoints}} or
#' \code{\link[sp:SpatialPointsDataFrame-class]{SpatialPointsDataFrame}}.
#' @param centerfun function to apply to the x-axis limits and y-axis limits
#' of the bounding box to obtain the x-coordinate and y-coordinate of the
#' center of the bounding box.
#' @return A data frame with six columns named XMax, XMin, YMax, YMin, XCenter,
#' and YCenter. The first four columns represent the corners of the bounding
#' box of each element in \code{obj}. The last two columns represent the
#' center of the bounding box of each element in \code{obj}. The number of
#' rows in the returned data frame is the same as the length of the argument
#' \code{obj}.
#'
#' When this function is run in TIBCO Enterprise Runtime for R
#' (\acronym{TERR}), the columns of the returned data frame have the
#' SpotfireColumnMetaData attribute set to enable TIBCO Spotfire to recognize
#' them as containing envelope information.
#' @seealso Example usage at \code{\link{writeWKB}}
#' @export
writeEnvelope <- function(obj, centerfun = mean) {
if(inherits(obj, c("SpatialPoints", "SpatialPointsDataFrame"), which = FALSE)) {
SpatialPointsEnvelope(obj)
} else if(inherits(obj, "list") && length(obj) > 0 &&
all(vapply(
X = obj,
FUN = inherits,
FUN.VALUE = logical(1),
c("SpatialPoints", "SpatialPointsDataFrame"))
)
) {
ListOfSpatialPointsEnvelope(obj, centerfun = mean)
} else if(inherits(obj, c("SpatialLines", "SpatialLinesDataFrame"), which = FALSE)) {
SpatialLinesEnvelope(obj, centerfun = mean)
} else if(inherits(obj, c("SpatialPolygons", "SpatialPolygonsDataFrame"), which = FALSE)) {
SpatialPolygonsEnvelope(obj)
} else {
stop("obj must be an object of class SpatialPoints, SpatialPointsDataFrame, ",
"SpatialLines, SpatialLinesDataFrame, SpatialPolygons, ",
"or SpatialPolygonsDataFrame, or a list of objects of class ",
"SpatialPoints or SpatialPointsDataFrame")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wkb/R/writeEnvelope.R
|
# Convert an R spatial object to a well-known binary (WKB) geometry
# representation
#' Convert Spatial Objects to \acronym{WKB}
#'
#' Converts \code{Spatial} objects to well-known binary (\acronym{WKB}) geometry
#' representations.
#'
#' @param obj object inheriting class \code{\link[sp:Spatial-class]{Spatial}}.
#' @param endian The byte order (\code{"big"} or \code{"little"}) for encoding
#' numeric types. The default is \code{"little"}.
#' @details The argument \code{obj} may be an object of class
#' \code{\link[sp:SpatialPoints-class]{SpatialPoints}},
#' \code{\link[sp:SpatialPointsDataFrame-class]{SpatialPointsDataFrame}},
#' \code{\link[sp:SpatialLines-class]{SpatialLines}},
#' \code{\link[sp:SpatialLinesDataFrame-class]{SpatialLinesDataFrame}},
#' \code{\link[sp:SpatialPolygons-class]{SpatialPolygons}}, or
#' \code{\link[sp:SpatialPolygonsDataFrame-class]{SpatialPolygonsDataFrame}},
#' or a \code{list} in which each element is an object of class
#' \code{\link[sp:SpatialPoints-class]{SpatialPoints}} or
#' \code{\link[sp:SpatialPointsDataFrame-class]{SpatialPointsDataFrame}}.
#' @return A \code{list} with class \code{AsIs}. The length of the returned list
#' is the same as the length of the argument \code{obj}. Each element of the
#' returned list is a \code{\link[base]{raw}} vector consisting of a
#' \acronym{WKB} geometry representation. The \acronym{WKB} geometry type
#' depends on the class of \code{obj} as shown in the table below.
#'
#' \tabular{ll}{
#' \strong{Class of \code{obj}} \tab \strong{Type of \acronym{WKB} geometry}\cr
#' \code{SpatialPoints} or \code{SpatialPointsDataFrame} \tab Point\cr
#' \code{list} of \code{SpatialPoints} or \code{SpatialPointsDataFrame} \tab MultiPoint\cr
#' \code{SpatialLines} or \code{SpatialLinesDataFrame} \tab MultiLineString\cr
#' \code{SpatialPolygons} or \code{SpatialPolygonsFrame} \tab Polygon or MultiPolygon\cr
#' }
#'
#' A \code{SpatialPolygons} or \code{SpatialPolygonsFrame} object is represented
#' as \acronym{WKB} Polygons if each \code{Polygons} object within it represents
#' a single polygon; otherwise it is represented as \acronym{WKB} MultiPolygons.
#'
#' The byte order of numeric types in the returned \acronym{WKB} geometry
#' representations depends on the value of the argument \code{endian}.
#' Little-endian byte order is known as \acronym{NDR} encoding, and big-endian
#' byte order is known as \acronym{XDR} encoding.
#'
#' When this function is run in TIBCO Enterprise Runtime for R (\acronym{TERR}),
#' the return value has the SpotfireColumnMetaData attribute set to enable TIBCO
#' Spotfire to recognize it as a \acronym{WKB} geometry representation.
#' @examples
#' # load package sp
#' library(sp)
#'
#' # create an object of class SpatialPoints
#' x = c(1, 2)
#' y = c(3, 2)
#' obj <- SpatialPoints(data.frame(x, y))
#'
#' # convert to WKB Point
#' wkb <- writeWKB(obj)
#'
#'
#' # create a list of objects of class SpatialPoints
#' x1 = c(1, 2, 3, 4, 5)
#' y1 = c(3, 2, 5, 1, 4)
#' x2 <- c(9, 10, 11, 12, 13)
#' y2 <- c(-1, -2, -3, -4, -5)
#' Sp1 <- SpatialPoints(data.frame(x1, y1))
#' Sp2 <- SpatialPoints(data.frame(x2, y2))
#' obj <- list("a"=Sp1, "b"=Sp2)
#'
#' # convert to WKB MultiPoint
#' wkb <- writeWKB(obj)
#'
#'
#' # create an object of class SpatialLines
#' l1 <- data.frame(x = c(1, 2, 3), y = c(3, 2, 2))
#' l1a <- data.frame(x = l1[, 1] + .05, y = l1[, 2] + .05)
#' l2 <- data.frame(x = c(1, 2, 3), y = c(1, 1.5, 1))
#' Sl1 <- Line(l1)
#' Sl1a <- Line(l1a)
#' Sl2 <- Line(l2)
#' S1 <- Lines(list(Sl1, Sl1a), ID = "a")
#' S2 <- Lines(list(Sl2), ID = "b")
#' obj <- SpatialLines(list(S1, S2))
#'
#' # convert to WKB MultiLineString
#' wkb <- writeWKB(obj)
#'
#'
#' # create an object of class SpatialPolygons
#' triangle <- Polygons(
#' list(
#' Polygon(data.frame(x = c(2, 2.5, 3, 2), y = c(2, 3, 2, 2)))
#' ), "triangle")
#' rectangles <- Polygons(
#' list(
#' Polygon(data.frame(x = c(0, 0, 1, 1, 0), y = c(0, 1, 1, 0, 0))),
#' Polygon(data.frame(x = c(0, 0, 2, 2, 0), y = c(-2, -1, -1, -2, -2)))
#' ), "rectangles")
#' obj <- SpatialPolygons(list(triangle, rectangles))
#'
#' # convert to WKB MultiPolygon
#' wkb <- writeWKB(obj)
#'
#'
#' # use the WKB as a column in a data frame
#' ds <- data.frame(ID = c("a","b"), Geometry = wkb)
#'
#' # calculate envelope columns and cbind to the data frame
#' coords <- writeEnvelope(obj)
#' ds <- cbind(ds, coords)
#' @seealso \code{\link{writeEnvelope}}, \code{\link{readWKB}}
#' @keywords wkb
#' @export
writeWKB <- function(obj, endian = "little") {
if(!identical(endian, "little") && !identical(endian, "big")) {
stop("endian must have value \"little\" or \"big\"")
}
if(inherits(obj, c("SpatialPoints", "SpatialPointsDataFrame"), which = FALSE)) {
SpatialPointsToWKBPoint(obj, endian)
} else if(inherits(obj, c("SpatialLines", "SpatialLinesDataFrame"), which = FALSE)) {
SpatialLinesToWKBMultiLineString(obj, endian)
} else if(inherits(obj, c("SpatialPolygons", "SpatialPolygonsDataFrame"), which = FALSE)) {
isPolygon <- all(vapply(
X = obj@polygons,
FUN = function(mypolygons) {
length(mypolygons) == 1 &&
all(
vapply(
X = mypolygons@Polygons[-1],
FUN = function(mypolygon) {
mypolygon@hole
},
FUN.VALUE = logical(1)
)
)
},
FUN.VALUE = logical(1)
))
if(isPolygon) {
SpatialPolygonsToWKBPolygon(obj, endian)
} else {
SpatialPolygonsToWKBMultiPolygon(obj, endian)
}
} else if(inherits(obj, "list") && length(obj) > 0 &&
all(vapply(
X = obj,
FUN = inherits,
FUN.VALUE = logical(1),
c("SpatialPoints", "SpatialPointsDataFrame"),
which = FALSE)
)
) {
ListOfSpatialPointsToWKBMultiPoint(obj, endian)
} else {
stop("obj must be an object of class SpatialPoints, SpatialPointsDataFrame, ",
"SpatialLines, SpatialLinesDataFrame, SpatialPolygons, ",
"or SpatialPolygonsDataFrame, or a list of objects of class ",
"SpatialPoints or SpatialPointsDataFrame")
}
}
|
/scratch/gouwar.j/cran-all/cranData/wkb/R/writeWKB.R
|
#' Return the dates of a particular week
#' @description Returns the dates of a particular week.
#' The week can be defined by ISO week or epi week.
#' @param year a value for the year.
#' @param wkIndex a value for the week index of the year.
#' @param wkMethod a character string for the week-counting method.
#' Default is "ISO" for ISO-week;
#' other options are "epiSat", "epiSun" and "epiMon" for epi-week method
#' defining Saturday, Sunday and Monday as the firstday in a week, respectively.
#' @return a vector of length 7, containing all the dates in the week, with the format
#' of yyyy-mm-dd.
#' @author You Li
#' @examples
#' dateFromWeek(year = 2000, wkIndex = 20)
#' dateFromWeek(year = 2009, wkIndex = 53)
#' dateFromWeek(year = 2015, wkIndex = 1, wkMethod = "epiSun")
#' @seealso weekToMonth
#' @export
dateFromWeek <- function(year, wkIndex, wkMethod = "ISO") {
# check input
if (wkMethod != "ISO" & wkMethod != "epiSat" & wkMethod != "epiSun" &
wkMethod != "epiMon") {
warning("Please check the week method. Should be 'ISO', 'epiSat', 'epiSun' or
'epiMon'.")
stop()
}
if (class(year) != "numeric") {
warning("Please check 'year'. Should be a numeric value")
stop()
}
if (class(wkIndex) != "numeric") {
warning("Please check 'wkIndex'. Should be a numeric value")
stop()
}
if (wkMethod != "ISO") {
if (wkIndex < 0.50 | wkIndex > 52.49) {
warning("wkIndex should be between 1 and 52.")
stop()
}
} else {
if (wkIndex <0.50 | wkIndex > 53.49) {
warning("wkIndex should be between 1 and 53.")
}
}
# wkIndex for ISO will be checked later
year <- round(year[1],0); wkIndex = round(wkIndex[1],0)
day1 <- strptime(paste(1, 1, year, sep = "-"), format = "%d-%m-%Y")
day1w <- day1$wday
dayStep <- 0
if (wkMethod == "ISO") {
if (day1w == 1 | day1w == 2 | day1w == 3 | day1w == 4) {
dayStep <- 1 - day1w
} else {
if (day1w == 0) {
dayStep <- 1
} else {
dayStep <- 8 - day1w
}
}
w1 <- day1 + dayStep * 86400
# check if there is week 53 for the given year
w53d4 <- w1 + 86400 * 52 * 7 + 3 * 86400
if (wkIndex == 53) {
if (as.numeric(substr(w53d4, 1, 4)) != year) {
warning("This year doesn't have week 53.")
stop()
}
}
}
if (wkMethod == "epiSat") {
if (day1w == 0 | day1w == 1 | day1w == 2) {
dayStep <- -1 - day1w
}
if (day1w == 3 | day1w == 4 | day1w == 5) {
dayStep <- 6 - day1w
}
}
if (wkMethod == "epiSun") {
if (day1w == 0 | day1w == 1 | day1w == 2) {
dayStep <- -day1w
} else {
dayStep <- 7 - day1w
}
}
if (wkMethod == "epiMon") {
if (day1w == 1 | day1w == 2 | day1w == 3 | day1w == 4) {
dayStep <- 1 - day1w
} else {
if (day1w == 0) {
dayStep <- 1
} else {
dayStep <- 8 - day1w
}
}
}
w1 <- day1 + dayStep * 86400
wxd1 <- w1 + 86400 * 7 * (wkIndex - 1)
return(as.Date(wxd1 + 86400 * (0:6)))
}
|
/scratch/gouwar.j/cran-all/cranData/wktmo/R/dateFromWeek.R
|
#' Convert weekly data to monthly data
#' @description Converts weekly data to monthly data.
#' The start week or date is needed along with the data. The start week can be
#' defined by ISO week or epi week.
#' @param wkdata a numeric vector for weekly data to be converted.
#' @param year a value for the year of the start of the data.
#' @param wkIndex a value for the week index of the start of the data if a week-counting
#' method is used.
#' @param wkMethod a character string for the week-counting methods.
#' Default is "ISO" for ISO-week;
#' other options are "epiSat", "epiSun" and "epiMon" for epi-week method
#' defining Saturday, Sunday and Monday as the firstday in a week, respectively.
#' In addition, users also have the option of specifying the start date of
#' the data by "startDat" method.
#' @param datStart a character string for the start date of the data.
#' If left blank, the date generated from the week-counting method will be applied.
#' @param format a character string specifying the input formate for \code{datStart}.
#' @return a dataframe containing two column vectors: \code{yearMonth} and
#' \code{value}.
#' @author You Li
#' @examples
#' # extract data
#' data(weeklyFlu)
#' # subset data of interest, e.g. to convert weekly influenza A cases in China
#' weeklyData <- weeklyFlu$fluA[weeklyFlu$country == "China"]
#' # convert weekly data to monthly data;
#' # these two input methods below will return the same results.
#' monthlyData <- weekToMonth(weeklyData, year = 2010, wkIndex = 1, wkMethod = "ISO")
#' monthlyData <- weekToMonth(weeklyData, datStart = "04-01-2010", wkMethod = "startDat")
#' @seealso dateFromWeek
#' @export
weekToMonth <- function(wkdata, year = NULL, wkIndex = NULL, wkMethod = "ISO",
datStart = NULL, format = "%d-%m-%Y") {
# check input
if (wkMethod != "ISO" & wkMethod != "epiSat" & wkMethod != "epiSun" &
wkMethod != "epiMon" & wkMethod != "startDat") {
warning("Please check the week method. Should be 'ISO', 'epiSat', 'epiSun',
'epiMon' or 'startDat'.")
stop()
}
if (is.null(datStart)) {
if (wkMethod == "startDat") {
warning("Please input datStart.")
stop()
} else {
if (class(year) != "numeric") {
warning("Please check 'year'. Should be a numeric value")
stop()
}
if (class(wkIndex) != "numeric") {
warning("Please check 'wkIndex'. Should be a numeric value")
stop()
}
}
}
if (is.numeric(wkdata) != TRUE) {
warning("Please check wkdata. Should be a numeric vector")
stop()
}
len <- length(wkdata)
daydata <- rep(wkdata/7, each = 7)
if (is.null(datStart)) {
if (wkMethod == "epiSat" | wkMethod == "epiSun" | wkMethod == "epiMon") {
dateSeq <- NULL
if (wkIndex < 0.50 | wkIndex > 52.49) {
warning("wkIndex should be between 1 and 52.")
stop()
}
for (i in 1:len) {
yearIndex <- floor((wkIndex - 1 + i - 1) / 52 )
dateSeq <- c(dateSeq, dateFromWeek(wkMethod = wkMethod,
year = year + yearIndex,
wkIndex = wkIndex + i - 1 - yearIndex * 52 ))
}
dateSeq <- as.Date(dateSeq, origin = "1970-01-01")
} else {
dateSeqw1 <- dateFromWeek(wkMethod = wkMethod, year = year, wkIndex = wkIndex)
dateSeq <- dateSeqw1[1] + 1:(7 * len) - 1
}
} else {
dateSeqw1 <- as.Date(datStart, format = format)
dateSeq <- dateSeqw1[1] + 1:(7 * len) -1
}
dfday <- data.frame(dateSeq, daydata)
dfday$yearMonth = as.factor(paste(substr(dfday$dateSeq, 1, 4),
substr(dfday$dateSeq, 6, 7), sep = "-"))
byRes <- by(dfday$daydata, dfday$yearMonth, sum)
weekdata <- data.frame(yearMonth = attributes(byRes)$dimnames$`dfday$yearMonth`,
value = as.numeric(byRes))
return(weekdata)
}
|
/scratch/gouwar.j/cran-all/cranData/wktmo/R/weekToMonth.R
|
#' Weekly influenza cases in 18 countries, 2010-2015
#'
#' A dataset containing weekly influenza cases, including influenza A, influenza B
#' and influenza A+B, in 18 countries during 2010-2015. Data are from FluNet,
#' a global web-based tool for influenza virological surveillance.
#'
#' @format a data frame containing 5616 rows and 10 variables.
#' \describe{
#' \item{country}{country: Argentina, Australia, Brazil, Chile, China, Egypt,
#' Germany, Ghana, Indonesia, Iran, Japan, Mongolia, Niger, Peru, Singapore,
#' Thailand, Tanzania, Zambia}
#' \item{whoRegion}{WHO region}
#' \item{fluRegion}{influenza region}
#' \item{year}{year of data}
#' \item{isoWeek}{index of ISO week}
#' \item{startDat}{start date of the week}
#' \item{endDat}{end date of the week}
#' \item{fluA}{number of influenza A cases}
#' \item{fluB}{number of influenza B cases}
#' \item{fluAll}{number of influenza A+B cases}
#' }
#' @source \url{http://www.who.int/influenza/gisrs_laboratory/flunet/en/}
"weeklyFlu"
|
/scratch/gouwar.j/cran-all/cranData/wktmo/R/weeklyFlu.R
|
# Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
cpp_coords_point_translate_wkt <- function(x, y, z, m, precision, trim) {
.Call(`_wkutils_cpp_coords_point_translate_wkt`, x, y, z, m, precision, trim)
}
cpp_coords_point_translate_wkb <- function(x, y, z, m, endian, bufferSize) {
.Call(`_wkutils_cpp_coords_point_translate_wkb`, x, y, z, m, endian, bufferSize)
}
cpp_coords_linestring_translate_wkt <- function(x, y, z, m, featureId, precision, trim) {
.Call(`_wkutils_cpp_coords_linestring_translate_wkt`, x, y, z, m, featureId, precision, trim)
}
cpp_coords_linestring_translate_wkb <- function(x, y, z, m, featureId, endian, bufferSize) {
.Call(`_wkutils_cpp_coords_linestring_translate_wkb`, x, y, z, m, featureId, endian, bufferSize)
}
cpp_coords_polygon_translate_wkt <- function(x, y, z, m, featureId, ringId, precision, trim) {
.Call(`_wkutils_cpp_coords_polygon_translate_wkt`, x, y, z, m, featureId, ringId, precision, trim)
}
cpp_coords_polygon_translate_wkb <- function(x, y, z, m, featureId, ringId, endian, bufferSize) {
.Call(`_wkutils_cpp_coords_polygon_translate_wkb`, x, y, z, m, featureId, ringId, endian, bufferSize)
}
cpp_coords_wkb <- function(wkb, sepNA) {
.Call(`_wkutils_cpp_coords_wkb`, wkb, sepNA)
}
cpp_coords_wkt <- function(wkt, sepNA) {
.Call(`_wkutils_cpp_coords_wkt`, wkt, sepNA)
}
cpp_debug_wkb <- function(wkb) {
invisible(.Call(`_wkutils_cpp_debug_wkb`, wkb))
}
cpp_debug_wkt <- function(input) {
invisible(.Call(`_wkutils_cpp_debug_wkt`, input))
}
cpp_debug_wkt_streamer <- function(input) {
invisible(.Call(`_wkutils_cpp_debug_wkt_streamer`, input))
}
cpp_wkt_set_srid <- function(wkt, srid, precision = 16L, trim = TRUE) {
.Call(`_wkutils_cpp_wkt_set_srid`, wkt, srid, precision, trim)
}
cpp_wkb_set_srid <- function(wkb, srid, endian) {
.Call(`_wkutils_cpp_wkb_set_srid`, wkb, srid, endian)
}
cpp_wkt_set_z <- function(wkt, z, precision = 16L, trim = TRUE) {
.Call(`_wkutils_cpp_wkt_set_z`, wkt, z, precision, trim)
}
cpp_wkb_set_z <- function(wkb, z, endian) {
.Call(`_wkutils_cpp_wkb_set_z`, wkb, z, endian)
}
cpp_wkt_transform <- function(wkt, transform, precision = 16L, trim = TRUE) {
.Call(`_wkutils_cpp_wkt_transform`, wkt, transform, precision, trim)
}
cpp_wkb_transform <- function(wkb, transform, endian) {
.Call(`_wkutils_cpp_wkb_transform`, wkb, transform, endian)
}
cpp_wkt_has_non_finite <- function(wkt) {
.Call(`_wkutils_cpp_wkt_has_non_finite`, wkt)
}
cpp_wkb_has_non_finite <- function(wkb) {
.Call(`_wkutils_cpp_wkb_has_non_finite`, wkb)
}
cpp_wkt_has_missing <- function(wkt) {
.Call(`_wkutils_cpp_wkt_has_missing`, wkt)
}
cpp_wkb_has_missing <- function(wkb) {
.Call(`_wkutils_cpp_wkb_has_missing`, wkb)
}
cpp_meta_wkb <- function(wkb, recursive) {
.Call(`_wkutils_cpp_meta_wkb`, wkb, recursive)
}
cpp_meta_wkt <- function(wkt, recursive) {
.Call(`_wkutils_cpp_meta_wkt`, wkt, recursive)
}
cpp_meta_wkt_streamer <- function(wkt, recursive) {
.Call(`_wkutils_cpp_meta_wkt_streamer`, wkt, recursive)
}
cpp_ranges_wkb <- function(wkb, naRm, onlyFinite) {
.Call(`_wkutils_cpp_ranges_wkb`, wkb, naRm, onlyFinite)
}
cpp_ranges_wkt <- function(wkt, naRm, onlyFinite) {
.Call(`_wkutils_cpp_ranges_wkt`, wkt, naRm, onlyFinite)
}
cpp_feature_ranges_wkb <- function(wkb, naRm, onlyFinite) {
.Call(`_wkutils_cpp_feature_ranges_wkb`, wkb, naRm, onlyFinite)
}
cpp_feature_ranges_wkt <- function(wkt, naRm, onlyFinite) {
.Call(`_wkutils_cpp_feature_ranges_wkt`, wkt, naRm, onlyFinite)
}
cpp_wkt_unnest <- function(wkt, keepEmpty, keepMulti, maxUnnestDepth) {
.Call(`_wkutils_cpp_wkt_unnest`, wkt, keepEmpty, keepMulti, maxUnnestDepth)
}
cpp_wkb_unnest <- function(wkb, keepEmpty, keepMulti, maxUnnestDepth, endian) {
.Call(`_wkutils_cpp_wkb_unnest`, wkb, keepEmpty, keepMulti, maxUnnestDepth, endian)
}
|
/scratch/gouwar.j/cran-all/cranData/wkutils/R/RcppExports.R
|
#' Parse coordinates into well-known formats
#'
#' These functions provide the reverse function of [wkt_coords()]
#' and company: they parse vectors of coordinate values into well-known
#' formats. Polygon rings are automatically closed, as
#' closed rings are assumed or required by many parsers.
#'
#' @param x,y,z,m Vectors of coordinate values
#' @param feature_id,ring_id Vectors for which a change in
#' sequential values indicates a new feature or ring. Use [factor()]
#' to convert from a character vector.
#' @param buffer_size The buffer size to use when converting to WKB.
#' @inheritParams wk::wkb_translate_wkt
#'
#' @return `*_translate_wkt()` returns a character vector of
#' well-known text; `*_translate_wkb()` returns a list
#' of raw vectors.
#'
#' @export
#'
#' @examples
#' coords_point_translate_wkt(1:3, 2:4)
#' coords_linestring_translate_wkt(1:5, 2:6, feature_id = c(1, 1, 1, 2, 2))
#' coords_polygon_translate_wkt(c(0, 10, 0), c(0, 0, 10))
#'
coords_point_translate_wkt <- function(x, y, z = NA, m = NA,
precision = 16, trim = TRUE) {
recycled <- vctrs::vec_recycle_common(x, y, z, m)
cpp_coords_point_translate_wkt(
recycled[[1]], recycled[[2]], recycled[[3]], recycled[[4]],
precision = precision,
trim = trim
)
}
#' @rdname coords_point_translate_wkt
#' @export
coords_point_translate_wkb <- function(x, y, z = NA, m = NA,
endian = wk::wk_platform_endian(), buffer_size = 2048) {
recycled <- vctrs::vec_recycle_common(x, y, z, m)
cpp_coords_point_translate_wkb(
recycled[[1]], recycled[[2]], recycled[[3]], recycled[[4]],
endian = endian,
bufferSize = buffer_size
)
}
#' @rdname coords_point_translate_wkt
#' @export
coords_linestring_translate_wkt <- function(x, y, z = NA, m = NA, feature_id = 1L,
precision = 16, trim = TRUE) {
recycled <- vctrs::vec_recycle_common(x, y, z, m, feature_id)
cpp_coords_linestring_translate_wkt(
recycled[[1]], recycled[[2]], recycled[[3]], recycled[[4]],
recycled[[5]],
precision = precision,
trim = trim
)
}
#' @rdname coords_point_translate_wkt
#' @export
coords_linestring_translate_wkb <- function(x, y, z = NA, m = NA, feature_id = 1L,
endian = wk::wk_platform_endian(), buffer_size = 2048) {
recycled <- vctrs::vec_recycle_common(x, y, z, m, feature_id)
cpp_coords_linestring_translate_wkb(
recycled[[1]], recycled[[2]], recycled[[3]], recycled[[4]],
recycled[[5]],
endian = endian,
bufferSize = buffer_size
)
}
#' @rdname coords_point_translate_wkt
#' @export
coords_polygon_translate_wkt <- function(x, y, z = NA, m = NA, feature_id = 1L, ring_id = 1L,
precision = 16, trim = TRUE) {
recycled <- vctrs::vec_recycle_common(x, y, z, m, feature_id, ring_id)
cpp_coords_polygon_translate_wkt(
recycled[[1]], recycled[[2]], recycled[[3]], recycled[[4]],
recycled[[5]], recycled[[6]],
precision = precision,
trim = trim
)
}
#' @rdname coords_point_translate_wkt
#' @export
coords_polygon_translate_wkb <- function(x, y, z = NA, m = NA, feature_id = 1L, ring_id = 1L,
endian = wk::wk_platform_endian(), buffer_size = 2048) {
recycled <- vctrs::vec_recycle_common(x, y, z, m, feature_id, ring_id)
cpp_coords_polygon_translate_wkb(
recycled[[1]], recycled[[2]], recycled[[3]], recycled[[4]],
recycled[[5]], recycled[[6]],
endian = endian,
bufferSize = buffer_size
)
}
|
/scratch/gouwar.j/cran-all/cranData/wkutils/R/coords-translate.R
|
#' Extract coordinates from well-known geometries
#'
#' These functions are optimised for graphics output,
#' which in R require flat coordinate structures. See
#' [graphics::points()], [graphics::lines()],
#' and [graphics::polypath()] for how to send these
#' to a graphics device, or [grid::pointsGrob()],
#' [grid::linesGrob()], and [grid::pathGrob()] for how
#' to create graphical objects using this output.
#'
#' @inheritParams wk::wkb_translate_wkt
#' @param sep_na Use `TRUE` to separate geometries and linear
#' rings with a row of `NA`s. This is useful for generating
#' output that can be fed directly to [graphics::polypath()]
#' or [graphics::lines()] without modification.
#'
#' @return A data.frame with columns:
#' - `feature_id`: The index of the top-level feature
#' - `part_id`: The part identifier, guaranteed to be unique for every simple geometry
#' (including those contained within a multi-geometry or collection)
#' - `ring_id`: The ring identifier, guaranteed to be unique for every ring.
#' - `x`, `y`, `z`, `m`: Coordinaate values (both absence and `nan` are recorded
#' as `NA`)
#'
#' @export
#'
#' @examples
#' text <- c("LINESTRING (0 1, 19 27)", "LINESTRING (-1 -1, 4 10)")
#' wkt_coords(text)
#' wkt_coords(text, sep_na = TRUE)
#'
wkb_coords <- function(wkb, sep_na = FALSE) {
new_data_frame(cpp_coords_wkb(wkb, sep_na))
}
#' @rdname wkb_coords
#' @export
wkt_coords <- function(wkt, sep_na = FALSE) {
new_data_frame(cpp_coords_wkt(wkt, sep_na))
}
|
/scratch/gouwar.j/cran-all/cranData/wkutils/R/coords.R
|
#' Debug well-known geometry
#'
#' Prints the raw calls to the `WKBGeometryHandler()`. Useful for writing
#' custom C++ handlers and debugging read problems.
#'
#' @inheritParams wk::wkb_translate_wkt
#'
#' @return The input, invisibly
#' @export
#'
#' @examples
#' wkt_debug("MULTIPOLYGON (((0 0, 10 0, 0 10, 0 0)))")
#' wkt_streamer_debug("MULTIPOLYGON (((0 0, 10 0, 0 10, 0 0)))")
#' wkb_debug(
#' wk::wkt_translate_wkb(
#' "MULTIPOLYGON (((0 0, 10 0, 0 10, 0 0)))"
#' )
#' )
#'
wkb_debug <- function(wkb) {
cpp_debug_wkb(wkb)
invisible(wkb)
}
#' @rdname wkb_debug
#' @export
wkt_debug <- function(wkt) {
cpp_debug_wkt(wkt)
invisible(wkt)
}
#' @rdname wkb_debug
#' @export
wkt_streamer_debug <- function(wkt) {
cpp_debug_wkt_streamer(wkt)
invisible(wkt)
}
|
/scratch/gouwar.j/cran-all/cranData/wkutils/R/debug.R
|
#' Draw well-known geometries
#'
#' These functions send well-known geometry vectors to a
#' graphics device using [graphics::points()],
#' [graphics::lines()], and [graphics::polypath()]. These are
#' minimal wrappers aimed at developers who need to visualize
#' test data: they do not check geometry type and are unlikely
#' to work with vectorized graphical parameters in `...`. Use
#' the `wk*_plot_new()` functions to initialize a plot using the
#' extent of all coordinates in the vector.
#'
#' @inheritParams wk::wkb_translate_wkt
#' @param ... Passed to [graphics::points()],
#' [graphics::lines()], or [graphics::polypath()]
#' @param rule Passed to [graphics::polypath()]
#' @param asp,xlab,ylab,main Passed to [graphics::plot()] to
#' initialize a new plot.
#'
#' @return The input, invisibly
#' @export
#'
#' @examples
#' x <- "POLYGON ((0 0, 10 0, 10 10, 0 10, 0 0))"
#'
#' wkt_plot_new(x)
#' wkt_draw_polypath(x, col = "grey90")
#' wkt_draw_lines(x, col = "red")
#' wkt_draw_points(x)
#'
wkb_draw_points <- function(wkb, ...) {
wkcoords_draw_points(wkb_coords(wkb), ...)
invisible(wkb)
}
#' @rdname wkb_draw_points
#' @export
wkt_draw_points <- function(wkt, ...) {
wkcoords_draw_points(wkt_coords(wkt), ...)
invisible(wkt)
}
#' @rdname wkb_draw_points
#' @export
wkb_draw_lines <- function(wkb, ...) {
wkcoords_draw_lines(wkb_coords(wkb, sep_na = TRUE), ...)
invisible(wkb)
}
#' @rdname wkb_draw_points
#' @export
wkt_draw_lines <- function(wkt, ...) {
wkcoords_draw_lines(wkt_coords(wkt, sep_na = TRUE), ...)
invisible(wkt)
}
#' @rdname wkb_draw_points
#' @export
wkb_draw_polypath <- function(wkb, ..., rule = "evenodd") {
wkcoords_draw_polypath(wkb_coords(wkb, sep_na = TRUE), ..., rule = rule)
invisible(wkb)
}
#' @rdname wkb_draw_points
#' @export
wkt_draw_polypath <- function(wkt, ..., rule = "evenodd") {
wkcoords_draw_polypath(wkt_coords(wkt, sep_na = TRUE), ..., rule = rule)
invisible(wkt)
}
#' @rdname wkb_draw_points
#' @export
wkb_plot_new <- function(wkb, ..., asp = 1, xlab = "", ylab = "", main = deparse(substitute(wkb))) {
wkranges_plot_new(wkb_ranges(wkb, finite = TRUE), ..., asp = asp, xlab = xlab, ylab = ylab, main = main)
invisible(wkb)
}
#' @rdname wkb_draw_points
#' @export
wkt_plot_new <- function(wkt, ..., asp = 1, xlab = "", ylab = "", main = deparse(substitute(wkt))) {
wkranges_plot_new(wkt_ranges(wkt, finite = TRUE), ..., asp = asp, xlab = xlab, ylab = ylab, main = main)
invisible(wkt)
}
wkcoords_draw_points <- function(coords, ...) {
graphics::points(coords$x, coords$y, ...)
}
wkcoords_draw_lines <- function(coords, ...) {
graphics::lines(coords$x, coords$y, ...)
}
wkcoords_draw_polypath <- function(coords, ..., rule = "evenodd") {
graphics::polypath(coords$x, coords$y, ..., rule = rule)
}
wkranges_plot_new <- function(ranges, ..., xlab = "", ylab = "", main = "") {
graphics::plot(
double(), double(),
...,
xlim = c(ranges$xmin, ranges$xmax),
ylim = c(ranges$ymin, ranges$ymax),
xlab = xlab,
ylab = ylab,
main = main
)
}
|
/scratch/gouwar.j/cran-all/cranData/wkutils/R/draw.R
|
#' Modify well-known geometries
#'
#' @inheritParams wk::wkb_translate_wkt
#' @param srid An integer spatial reference identifier with a user-defined meaning.
#' Use `NA` to unset this value.
#' @param z A Z value that will be assigned to every coordinate in each feature.
#' Use `NA` to unset this value.
#' @param trans A 3x3 transformation matrix that will be applied to all coordinates
#' in the input.
#'
#' @return An unclassed well-known vector with the same type
#' as the input.
#' @export
#'
#' @examples
#' wkt_set_srid("POINT (30 10)", 1234)
#' wkt_set_z("POINT (30 10)", 1234)
#' wkt_transform(
#' "POINT (0 0)",
#' # translation +12 +13
#' matrix(c(1, 0, 0, 0, 1, 0, 12, 13, 1), ncol = 3)
#' )
#'
wkt_set_srid <- function(wkt, srid, precision = 16, trim = TRUE) {
recycled <- vctrs::vec_recycle_common(wkt, srid)
cpp_wkt_set_srid(recycled[[1]], recycled[[2]], precision, trim)
}
#' @rdname wkt_set_srid
#' @export
wkb_set_srid <- function(wkb, srid) {
recycled <- vctrs::vec_recycle_common(wkb, srid)
cpp_wkb_set_srid(recycled[[1]], recycled[[2]], wk_platform_endian())
}
#' @rdname wkt_set_srid
#' @export
wkt_set_z <- function(wkt, z, precision = 16, trim = TRUE) {
recycled <- vctrs::vec_recycle_common(wkt, z)
cpp_wkt_set_z(recycled[[1]], recycled[[2]], precision, trim)
}
#' @rdname wkt_set_srid
#' @export
wkb_set_z <- function(wkb, z) {
recycled <- vctrs::vec_recycle_common(wkb, z)
cpp_wkb_set_z(recycled[[1]], recycled[[2]], wk_platform_endian())
}
#' @rdname wkt_set_srid
#' @export
wkt_transform <- function(wkt, trans, precision = 16, trim = TRUE) {
cpp_wkt_transform(wkt, as_trans_matrix(trans)[c(1, 2), ], precision, trim)
}
#' @rdname wkt_set_srid
#' @export
wkb_transform <- function(wkb, trans) {
cpp_wkb_transform(wkb, as_trans_matrix(trans)[c(1, 2), ], endian = wk_platform_endian())
}
as_trans_matrix <- function(trans) {
trans <- as.matrix(trans)
stopifnot(ncol(trans) == 3, nrow(trans) == 3)
trans
}
|
/scratch/gouwar.j/cran-all/cranData/wkutils/R/filters.R
|
#' Test well-known geometries for missing and non-finite coordinates
#'
#' Note that EMTPY geometries are considered finite and non-missing.
#' Use the `size` column of [wkt_meta()] to test for empty geometries.
#'
#' @inheritParams wk::wkb_translate_wkt
#'
#' @return A logical vector with the same length as the input.
#' @export
#'
#' @examples
#' wkt_has_missing("POINT (0 1)")
#' wkt_has_missing("POINT (nan nan)")
#' wkt_has_missing("POINT (inf inf)")
#'
#' wkt_is_finite("POINT (0 1)")
#' wkt_is_finite("POINT (nan nan)")
#' wkt_is_finite("POINT (inf inf)")
#'
wkt_has_missing <- function(wkt) {
cpp_wkt_has_missing(wkt)
}
#' @rdname wkt_has_missing
#' @export
wkb_has_missing <- function(wkb) {
cpp_wkb_has_missing(wkb)
}
#' @rdname wkt_has_missing
#' @export
wkt_is_finite <- function(wkt) {
!cpp_wkt_has_non_finite(wkt)
}
#' @rdname wkt_has_missing
#' @export
wkb_is_finite <- function(wkb) {
!cpp_wkb_has_non_finite(wkb)
}
|
/scratch/gouwar.j/cran-all/cranData/wkutils/R/finite.R
|
#' Generate grid geometries from well-known geometries
#'
#' Using [wkt_meta()] and [wkt_coords()], these functions create graphical objects
#' using the grid package. Vectors that contain geometries of a single dimension
#' are efficiently packed into a [grid::pointsGrob()], [grid::polylineGrob()],
#' or [grid::pathGrob()]. Vectors with mixed types and nested collections are encoded
#' less efficiently using a [grid::gTree()].
#'
#' @inheritParams wk::wkb_translate_wkt
#' @param ... Graphical parameters passed to [grid::gpar()]. These are recycled along
#' the input. Dynamic dots (e.g., `!!!`) are supported.
#' @param rule Use "winding" if polygon rings are correctly encoded with a winding
#' direction.
#' @param default.units Coordinate units, which may be defined by the viewport (see
#' [grid::unit()]). Defaults to native.
#' @param name,vp Passed to [grid::pointsGrob()], [grid::polylineGrob()],
#' [grid::pathGrob()], or [grid::gTree()] depending on the types of geometries
#' in the input.
#'
#' @return A [graphical object][grid::grob]
#' @export
#'
#' @examples
#' grid::grid.newpage()
#' grid::grid.draw(wkt_grob("POINT (0.5 0.5)", pch = 16, default.units = "npc"))
#'
wkt_grob <- function(wkt, ..., rule = "evenodd", default.units = "native", name = NULL, vp = NULL) {
grob_wk_possibly_nested(
wkt,
...,
unnest_fun = wkt_unnest,
meta_fun = wkt_meta,
coords_fun = wkt_coords,
rule = rule,
default.units = default.units,
name = name,
vp = vp
)
}
#' @rdname wkt_grob
#' @export
wkb_grob <- function(wkt, ..., rule = "evenodd", default.units = "native", name = NULL, vp = NULL) {
grob_wk_possibly_nested(
wkt,
...,
unnest_fun = wkb_unnest,
meta_fun = wkb_meta,
coords_fun = wkb_coords,
rule = rule,
default.units = default.units,
name = name,
vp = vp
)
}
grob_wk_possibly_nested <- function(x, ..., unnest_fun, meta_fun, coords_fun,
rule, default.units, name, vp) {
meta <- meta_fun(x)
gpar_values_all <- vctrs::vec_recycle_common(..., .size = length(x))
# if there are any collections, unnest everything
if (any((meta$size > 0) & (meta$type_id == 7))) {
unnested <- unnest_fun(x, keep_empty = FALSE, keep_multi = TRUE, max_depth = 10)
lengths <- attr(unnested, "lengths")
run_length_enc <- structure(
list(lengths = lengths, values = seq_along(lengths)),
class = "rle"
)
unnested_gpar <- lapply(gpar_values_all, "[", inverse.rle(run_length_enc))
return(
wkt_grob(
unnested, !!!unnested_gpar,
rule = rule,
default.units = default.units,
name = name,
vp = vp
)
)
}
coords <- coords_fun(x)
# grid doesn't do zero-length input, so if there are no coordinates, return
# an empty grob
if (nrow(coords) == 0) {
return(grid::gTree(name = name, vp = vp, children = grid::gList()))
}
grob_wk_base(
meta, coords, gpar_values_all,
rule = rule,
default.units = default.units,
name = name,
vp = vp
)
}
grob_wk_base <- function(meta, coords, gpar_values_all, rule, default.units, name = NULL, vp = NULL) {
# use meta to try to create the most efficient grob possible
non_empty_types <- meta$type_id[meta$size > 0]
# non-empty IDs are used by mixed types and polygons
non_empty_features <- unique(meta$feature_id[meta$size > 0])
if (all(non_empty_types %in% c(1, 4))) {
# Need to get a tiny bit creative here, because pointsGrob
# doesn't have a pathId argument like pathGrob. The key here is
# to select gpar_values_all so that its rows match the
# number of actual part_id values for each feature
part_lengths <- rle(coords$part_id)
part_row_start <- c(0, cumsum(part_lengths$lengths)) + 1
part_feature_ids <- coords$feature_id[part_row_start[-length(part_row_start)]]
gpar_values_all <- lapply(gpar_values_all, "[", part_feature_ids)
pch <- gpar_values_all$pch %||% 1
size <- gpar_values_all$size %||% grid::unit(1, "char")
gpar_values_all$pch <- NULL
gpar_values_all$size <- NULL
grid::pointsGrob(
x = coords$x,
y = coords$y,
pch = pch,
size = size,
gp = do.call(grid::gpar, gpar_values_all),
default.units = default.units,
name = name,
vp = vp
)
} else if (all(non_empty_types %in% c(2, 5))) {
# Need to get a tiny bit creative here, because polylineGrob
# doesn't have a pathId argument like pathGrob. The key here is
# to select gpar_values_all so that its rows match the
# number of actual part_id values for each feature
part_lengths <- rle(coords$part_id)
part_row_start <- c(0, cumsum(part_lengths$lengths)) + 1
part_feature_ids <- coords$feature_id[part_row_start[-length(part_row_start)]]
gpar_values_all <- lapply(gpar_values_all, "[", part_feature_ids)
grid::polylineGrob(
x = coords$x,
y = coords$y,
id.lengths = part_lengths$lengths,
gp = do.call(grid::gpar, gpar_values_all),
default.units = default.units,
name = name,
vp = vp
)
} else if (all(non_empty_types %in% c(3, 6))) {
non_empty_gpar_values <- lapply(gpar_values_all, "[", non_empty_features)
grid::pathGrob(
x = coords$x,
y = coords$y,
id = coords$ring_id,
pathId = coords$feature_id,
gp = do.call(grid::gpar, non_empty_gpar_values),
default.units = default.units,
name = name,
vp = vp,
rule = rule
)
} else if (all(non_empty_types != 7)) {
# Mixed input, but no collections (collections should be handled by unnest())
# not very efficient, but better than failing
grobs <- lapply(non_empty_features, function(feature_id) {
grob_wk_base(
meta[feature_id, ],
coords[coords$feature_id == feature_id, ],
gpar_values_all,
rule = rule,
default.units = default.units
# name and vp are passed to the gTree
)
})
grid::gTree(children = do.call(grid::gList, grobs), name = name, vp = vp)
} else {
stop("Can't use grob_wk_base() on a GEOMETRYCOLLECTION") # nocov
}
}
|
/scratch/gouwar.j/cran-all/cranData/wkutils/R/grob.R
|
#' Extract meta information
#'
#' @inheritParams wk::wkb_translate_wkt
#' @param recursive Pass `TRUE` to recurse into multi-geometries
#' and collections to extract meta of sub-geometries
#' @param type A string version of the geometry type (e.g.,
#' point, linestring, polygon, multipoint, multilinestring,
#' multipolygon, geometrycollection)
#' @param type_id An integer version of the geometry type
#'
#' @return A data.frame with columns:
#' - `feature_id`: The index of the top-level feature
#' - `nest_id`: The recursion level (if feature is a geometry collection)
#' - `part_id`: The part index (if nested within a multi-geometry or collection)
#' - `type_id`: The type identifier (see [wk_geometry_type()])
#' - `size`: For points and linestrings the number of points, for polygons
#' the number of rings, and for mutlti-geometries and collection types,
#' the number of child geometries.
#' - `srid`: The spatial reference identifier as an integer
#'
#' @export
#'
#' @examples
#' wkt_meta("POINT (30 10)")
#' wkt_meta("GEOMETRYCOLLECTION (POINT (30 10))", recursive = FALSE)
#' wkt_meta("GEOMETRYCOLLECTION (POINT (30 10))", recursive = TRUE)
#'
wkb_meta <- function(wkb, recursive = FALSE) {
new_data_frame(cpp_meta_wkb(wkb, recursive = recursive))
}
#' @rdname wkb_meta
#' @export
wkt_meta <- function(wkt, recursive = FALSE) {
new_data_frame(cpp_meta_wkt(wkt, recursive = recursive))
}
#' @rdname wkb_meta
#' @export
wkt_streamer_meta <- function(wkt, recursive = FALSE) {
new_data_frame(cpp_meta_wkt_streamer(wkt, recursive = recursive))
}
#' @rdname wkb_meta
#' @export
wk_geometry_type <- function(type_id) {
c(
"point", "linestring", "polygon",
"multipoint", "multilinestring", "multipolygon",
"geometrycollection"
)[as.integer(type_id)]
}
#' @rdname wkb_meta
#' @export
wk_geometry_type_id <- function(type) {
match(
type,
c(
"point", "linestring", "polygon",
"multipoint", "multilinestring", "multipolygon",
"geometrycollection"
)
)
}
|
/scratch/gouwar.j/cran-all/cranData/wkutils/R/meta.R
|
#' Plot well-known geometry vectors
#'
#' These plot functions are intended to help debug geometry vectors,
#' and are not intended to be high-performance.
#'
#' @param x A [wkt()] or [wkb()] vector.
#' @param add Should a new plot be created, or should `x` be added to the
#' existing plot?
#' @param ... Passed to plotting functions for features: [graphics::points()]
#' for point and multipoint geometries, [graphics::lines()] for linestring
#' and multilinestring geometries, and [graphics::polypath()] for polygon
#' and multipolygon geometries.
#' @param bbox The limits of the plot in the form returned by [wkt_ranges()].
#' @param asp,xlab,ylab Passed to [graphics::plot()]
#' @param rule The rule to use for filling polygons (see [graphics::polypath()])
#'
#' @return `x`, invisibly
#' @export
#'
#' @examples
#' wkt_plot("POINT (30 10)")
#'
wkt_plot <- function(x, ...,
asp = 1, bbox = NULL, xlab = "", ylab = "",
rule = "evenodd", add = FALSE) {
plot_wk(
x, wkt_ranges, wkt_meta, wkt_coords, wkt_unnest,
...,
asp = asp, bbox = bbox, xlab = xlab,
rule = rule, add = add
)
}
#' @rdname wkt_plot
#' @export
wkb_plot <- function(x, ...,
asp = 1, bbox = NULL, xlab = "", ylab = "",
rule = "evenodd", add = FALSE) {
plot_wk(
x, wkb_ranges, wkb_meta, wkb_coords, wkb_unnest,
...,
asp = asp, bbox = bbox, xlab = xlab,
rule = rule, add = add
)
}
plot_wk <- function(x, ranges_fun, meta_fun, coords_fun, unnest_fun, ...,
asp = 1, bbox = NULL, xlab = "", ylab = "",
rule = "evenodd", add = FALSE) {
if (!add) {
bbox <- unclass(bbox)
bbox <- bbox %||% ranges_fun(x, finite = TRUE)
xlim <- c(bbox$xmin, bbox$xmax)
ylim <- c(bbox$ymin, bbox$ymax)
graphics::plot(
numeric(0),
numeric(0),
xlim = xlim,
ylim = ylim,
xlab = xlab,
ylab = ylab,
asp = asp
)
}
plot_add_wk(x, meta_fun, coords_fun, unnest_fun, ..., rule = rule)
}
plot_add_wk <- function(x, meta_fun, coords_fun, unnest_fun, ..., rule = "evenodd") {
# evaluate dots, wrap scalar types in a list(), and vectorize
x <- unclass(x)
dots <- list(..., rule = rule)
is_scalar <- !vapply(dots, vctrs::vec_is, logical(1))
dots[is_scalar] <- lapply(dots[is_scalar], list)
dots_tbl <- vctrs::vec_recycle_common(!!!dots, .size = length(x))
meta <- unclass(meta_fun(x, recursive = FALSE))
# using for() because the user interrupt is respected in RStudio
for (i in seq_along(x)) {
coords <- coords_fun(x[i], sep_na = TRUE)[c("x", "y")]
if (nrow(coords) == 0) {
next
}
dots_item <- lapply(dots_tbl, "[[", i)
type_id <- meta$type[i]
args <- c(coords, dots_item)
if (type_id == 1 || type_id == 4) {
args$rule <- NULL
do.call(graphics::points, args)
} else if (type_id == 2 || type_id == 5) {
args$rule <- NULL
do.call(graphics::lines, args)
} else if (type_id == 3 || type_id == 6) {
do.call(graphics::polypath, args)
} else if (type_id == 7) {
unnested <- unnest_fun(x[i])
do.call(
plot_add_wk,
c(
list(unnested, meta_fun = meta_fun, coords_fun = coords_fun, unnest_fun = unnest_fun),
dots_item
)
)
} else {
stop("Unknown geometry type", call. = FALSE) # nocov
}
}
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/wkutils/R/plot.R
|
#' Extract ranges information
#'
#' This is intended to behave the same as [range()], returning the
#' minimum and maximum x, y, z, and m coordinate values.
#'
#' @inheritParams wk::wkb_translate_wkt
#' @param na.rm Pass `TRUE` to not consider missing (nan) values
#' @param finite Pass `TRUE` to only consider finite
#' (non-missing, non-infinite) values.
#' @export
#'
#' @return A data.frame with columns:
#' - `xmin`, `ymin`, `zmin`, and `mmin`: Minimum coordinate values
#' - `xmax`, `ymax`, `zmax`, and `mmax`: Maximum coordinate values
#'
#' @examples
#' wkt_ranges("POINT (30 10)")
#'
wkb_ranges <- function(wkb, na.rm = FALSE, finite = FALSE) {
new_data_frame(cpp_ranges_wkb(wkb, naRm = na.rm, onlyFinite = finite))
}
#' @rdname wkb_ranges
#' @export
wkt_ranges <- function(wkt, na.rm = FALSE, finite = FALSE) {
new_data_frame(cpp_ranges_wkt(wkt, naRm = na.rm, onlyFinite = finite))
}
#' @rdname wkb_ranges
#' @export
wkb_feature_ranges <- function(wkb, na.rm = FALSE, finite = FALSE) {
new_data_frame(cpp_feature_ranges_wkb(wkb, naRm = na.rm, onlyFinite = finite))
}
#' @rdname wkb_ranges
#' @export
wkt_feature_ranges <- function(wkt, na.rm = FALSE, finite = FALSE) {
new_data_frame(cpp_feature_ranges_wkt(wkt, naRm = na.rm, onlyFinite = finite))
}
|
/scratch/gouwar.j/cran-all/cranData/wkutils/R/ranges.R
|
#' Flatten nested geometry structures
#'
#' @inheritParams wk::wkb_translate_wkt
#' @param keep_empty If `TRUE`, a GEOMETRYCOLLECTION EMPTY is left as-is
#' rather than collapsing to length 0.
#' @param keep_multi If `TRUE`, MULTI* geometries are not expanded to sub-features.
#' @param max_depth The maximum recursive GEOMETRYCOLLECTION depth to unnest.
#'
#' @return An unclassed vector with attribute `lengths`, which is an integer vector
#' with the same length as the input denoting the length to which each
#' feature was expanded.
#' @export
#'
#' @examples
#' wkt_unnest("GEOMETRYCOLLECTION (POINT (1 2), POINT (3 4))")
#' wkt_unnest("GEOMETRYCOLLECTION EMPTY")
#' wkt_unnest("GEOMETRYCOLLECTION EMPTY", keep_empty = TRUE)
#'
wkt_unnest <- function(wkt, keep_empty = FALSE, keep_multi = TRUE, max_depth = 1) {
cpp_wkt_unnest(wkt, keep_empty, keep_multi, max_depth)
}
#' @rdname wkt_unnest
#' @export
wkb_unnest <- function(wkb, keep_empty = FALSE, keep_multi = TRUE, max_depth = 1) {
cpp_wkb_unnest(wkb, keep_empty, keep_multi, max_depth, endian = wk_platform_endian())
}
|
/scratch/gouwar.j/cran-all/cranData/wkutils/R/unnest.R
|
new_data_frame <- function(x, nrow = length(x[[1]])) {
tibble::new_tibble(x, nrow = nrow)
}
`%||%` <- function (x, y) {
if (is.null(x)) y else x
}
|
/scratch/gouwar.j/cran-all/cranData/wkutils/R/utils.R
|
#' @keywords internal
"_PACKAGE"
# The following block is used by usethis to automatically manage
# roxygen namespace tags. Modify with care!
## usethis namespace: start
#' @useDynLib wkutils, .registration = TRUE
#' @importFrom Rcpp sourceCpp
#' @import wk
## usethis namespace: end
NULL
|
/scratch/gouwar.j/cran-all/cranData/wkutils/R/wkutils-package.R
|
#' Lookup Table for Gauss coefficients g & h
#'
#' Find Gauss coefficient \eqn{g_{n,m}(t)} consistent with the World Magnetic Model.
#'
#' @param t Annualized date time. E.g., 2015-02-01 = (2015 + 32/365) = 2015.088
#' @param t0 Annualized reference time associated with \code{t}
#' @param wmmVersion String representing WMM version to use. Must be consistent with \code{time} and one of the following: 'derived', 'WMM2000', 'WMM2005', 'WMM2010', 'WMM2015', 'WMM2015v2', 'WMM2020'. Default 'derived' value will infer the latest WMM version consistent with \code{time}.
#'
#' @return vector of Gauss coefficients, \eqn{g_{n,m}(t)} and \eqn{h_{n,m}(t)}
.CalculateGaussCoef <- function(t, t0, wmmVersion = 'derived') {
gaussG <- .kLegendreTemplate
gaussH <- .kLegendreTemplate
gaussGDot <- .kLegendreTemplate
gaussHDot <- .kLegendreTemplate
gaussG[1:12, 1:13] <- .kCoefficientsWMMg[[wmmVersion]] +
(t - t0) * .kCoefficientsWMMgDot[[wmmVersion]]
gaussH[1:12, 1:13] <- .kCoefficientsWMMh[[wmmVersion]] +
(t - t0) * .kCoefficientsWMMhDot[[wmmVersion]]
gaussGDot[1:12, 1:13] <- .kCoefficientsWMMgDot[[wmmVersion]]
gaussHDot[1:12, 1:13] <- .kCoefficientsWMMhDot[[wmmVersion]]
output <- list(
'g' = gaussG,
'h' = gaussH,
'gDot0' = gaussGDot,
'hDot0' = gaussHDot
)
return(output)
}
|
/scratch/gouwar.j/cran-all/cranData/wmm/R/functions_coefficients.R
|
#' Radius of curvature of prime vertical
#'
#' Calculate radius of curvature of prime vertical at given geodetic latitude.
#'
#' @param latitudeGD Geodetic latitude in decimal degrees
#' @return Radius of curvature of prime vertical at given geodetic latitude
.CalculateRadiusCurvature <- function(latitudeGD) {
output <- .kEarthSemimajorAxis / sqrt(
1 - .kEccentricity^2 * sin(latitudeGD / .kRadToDegree)^2
)
return(output)
}
#' Convert from Geodetic to Geocentric Coordinates
#'
#' Convert geodetic coordinates to geocentric coordinates
#'
#' @param latitudeGD Geodetic latitude in decimal degrees
#' @param height Height in meters above ellipsoid (not mean sea level)
#' @return List with first element as geocentric latitude in decimal degrees and second element as geocentric radius
.ConvertGeodeticToGeocentricGPS <- function(latitudeGD, height) {
radiusCurvature <- .CalculateRadiusCurvature(latitudeGD)
latitudeGD <- latitudeGD / .kRadToDegree
p <- (radiusCurvature + height) * cos(latitudeGD)
z <- (radiusCurvature * (1 - .kEccentricity^2) + height) * sin(latitudeGD)
r <- sqrt(p^2 + z^2)
latitudeGC <- asin(z / r) * .kRadToDegree
output <- list(latitudeGC, r)
names(output) <- c('latitude_GC', 'radius_GC')
return(output)
}
#' Geocentric Coordinates to Geodetic Coordinates
#'
#' Convert Geocentric Coordinates to Geodetic Coordinates.
#'
#' @param xGeocentric X-coordinate in geocentric system
#' @param yGeocentric Y-coordinate in geocentric system
#' @param zGeocentric Z-coordinate in geocentric system
#' @param deltaLat (Geocentric Latitude - Geodetic Latitude) in decimal degrees
#' @return Vector of length 3 representing geodetic coordinates consistent with given geocentric data
.ConvertGeocentricToGeodeticFieldComponents <- function(
xGeocentric,
yGeocentric,
zGeocentric,
deltaLat
) {
# Get difference in latitude angle
deltaLat <- deltaLat / .kRadToDegree
cosDeltLat <- cos(deltaLat)
sinDeltLat <- sin(deltaLat)
xGeodetic <- xGeocentric * cosDeltLat - zGeocentric * sinDeltLat
yGeodetic <- yGeocentric
zGeodetic <- xGeocentric * sinDeltLat + zGeocentric * cosDeltLat
output <- list(
'x' = xGeodetic,
'y' = yGeodetic,
'z' = zGeodetic
)
return(output)
}
#' Calculate sum of geocentric field components
#'
#' @param legendreTable \code{data.table} modified by \code{.CalculateSchmidtLegendreDerivative}
#' @param gaussCoef Gauss coefficients as calculated by \code{.CalculateGaussCoef}
#' @param radius Radius of curvature of prime vertical at given geodetic latitude
#' @param lon GPS longitude
#' @param latGC GPS latitude, geocentric
#' @param deltaLatitude (Geocentric Latitude - Geodetic Latitude) in decimal degrees
.CalculateGeocentricFieldSum <- function(
legendreTable,
gaussCoef,
radius,
lon,
latGC,
deltaLatitude
) {
cosLonM <- outer(
1:13,
0:13,
FUN = function(n, m) cos(lon * m)
)
sinLonM <- outer(
1:13,
0:13,
FUN = function(n, m) sin(lon * m)
)
radiusRatioPower <- (.kGeomagneticRadius / radius) ^ (.kDegreeIndexMatrix + 2)
gaussCoefGCosLonM <- gaussCoef[['g']] * cosLonM
gaussCoefGSinLonM <- gaussCoef[['g']] * sinLonM
gaussCoefHCosLonM <- gaussCoef[['h']] * cosLonM
gaussCoefHSinLonM <- gaussCoef[['h']] * sinLonM
gaussCoefGDot0CosLonM <- gaussCoef[['gDot0']] * cosLonM
gaussCoefGDot0SinLonM <- gaussCoef[['gDot0']] * sinLonM
gaussCoefHDot0CosLonM <- gaussCoef[['hDot0']] * cosLonM
gaussCoefHDot0SinLonM <- gaussCoef[['hDot0']] * sinLonM
xGeocentric <- -radiusRatioPower * (
gaussCoefGCosLonM + gaussCoefHSinLonM
) * legendreTable[['Derivative Schmidt P']] * cos(latGC)
yGeocentric <- radiusRatioPower * .kOrderIndexMatrix * (
gaussCoefGSinLonM - gaussCoefHCosLonM
) * legendreTable[['Schmidt P']] / cos(latGC)
zGeocentric <- -(.kDegreeIndexMatrix + 1) * radiusRatioPower * (
gaussCoefGCosLonM + gaussCoefHSinLonM
) * legendreTable[['Schmidt P']]
xDotGeocentric <- -radiusRatioPower * (
gaussCoefGDot0CosLonM + gaussCoefHDot0SinLonM
) * legendreTable[['Derivative Schmidt P']] * cos(latGC)
yDotGeocentric <- radiusRatioPower * .kOrderIndexMatrix * (
gaussCoefGDot0SinLonM - gaussCoefHDot0CosLonM
) * legendreTable[['Schmidt P']] / cos(latGC)
zDotGeocentric <- -(.kDegreeIndexMatrix + 1) * radiusRatioPower * (
gaussCoefGDot0CosLonM + gaussCoefHDot0SinLonM
) * legendreTable[['Schmidt P']]
# Package the sum of geocentric values with deltaLatitude to later calculate
# geodentric values
geocentricField <- list(
sum(xGeocentric[-13, -14], na.rm = TRUE),
sum(yGeocentric[-13, -14], na.rm = TRUE),
sum(zGeocentric[-13, -14], na.rm = TRUE),
deltaLatitude
)
geocentricDotField <- list(
sum(xDotGeocentric[-13, -14], na.rm = TRUE),
sum(yDotGeocentric[-13, -14], na.rm = TRUE),
sum(zDotGeocentric[-13, -14], na.rm = TRUE),
deltaLatitude
)
output <- list(
'Main Field' = geocentricField,
'Secular Variation' = geocentricDotField
)
return(output)
}
|
/scratch/gouwar.j/cran-all/cranData/wmm/R/functions_geocoordinates.R
|
#' Compute Legendre Components
#'
#' Function that computes the components of the associated Legendre function, \eqn{P_{n,m}(\mu)}{P(mu, n, m)}, only dependent on (degree, order) indices. This function is only used to precompute values.
#'
#' The underlying equation used is: \deqn{P(x, n, m)=(-1)^m * 2^n * (1-x^2)^(m/2) * sum(for m <= k <= n: k!/(k-m)! * x^(k-m) * choose(n, k) * choose((n+k-1)/2, n))}
#'
#' @param n degree of associated Legendre function
#' @param m order of associated Legendre function
.CalcLegendreComponents <- function(n, m) {
# Since these values will be in a product, just zero out the non-sense indices
if (m > n) {
return(NA)
}
mSequence <- seq(from = m, to = n)
# Keep only the indices where the binomial coefficient,
# choose((n + k - 1)/2, n), is non-zero.
mSequence <- mSequence[which((n + mSequence - 1) %% 2 == 1)]
mRange <- length(mSequence)
output <- vector(mode = 'numeric', length = mRange)
for (
index in seq_along(mSequence)
) {
k <- mSequence[index]
# Note: When calcuating the magnetic field, the associated values of mu
# will be multiplied and summed: (1 - mu^2)^(m/2) * mu^mSequence
output[index] <- 2^n * factorial(k) / factorial(k - m) * choose(n, k) *
choose((n + k - 1)/2, n)
}
return(output)
}
#' Calculate Polynomial Components for Associated Legendre Function
#'
#' Function that computes the polynomial components of \code{mu} that are paired with the output of \code{.CalcLegendreComponents} to create the indiviudal components of the associated Legendre function, \eqn{P_{n,m}(\mu)}{P_{n,m}(mu)}.
#'
#' The underlying equation used is: \deqn{P(x, n, m)=(-1)^m * 2^n * (1-x^2)^(m/2) * sum(for m <= k <= n: k!/(k-m)! * x^(k-m) * choose(n, k) * choose((n+k-1)/2, n))}
#'
#' @param mu Function argument to \eqn{P_{n,m}(\mu)}{P_{n,m}(mu)}
.CalcPolynomialComponents <- function(mu) {
output <- (1 - mu^2)^.kSelectedExponentsM * mu^.kSelectedIndicesM
output <- replace(output, which(is.na(output)), 0)
return(output)
}
#' Compute Associated Legendre Functions Given Sequence of (degree, order) Indices
#'
#' Procedure that computes the associated Legendre function, \eqn{P_{n,m}(\mu)}{P_{n,m}(mu)}, given a sequence of (degree, order) indices and function argument \eqn{\mu}{mu}. This is computed via a closed-form equation.
#'
#' The underlying equation used is: \deqn{P(x, n, m)=(-1)^m * 2^n * (1-x^2)^(m/2) * sum(for m <= k <= n: k!/(k-m)! * x^(k-m) * choose(n, k) * choose((n+k-1)/2, n))}
#'
#' @param mu Function argument to \eqn{P_{n,m}(\mu)}{P_{n,m}(mu)}
.CalcLegendre <- function(mu) {
polynomialComponents <- .CalcPolynomialComponents(mu)
legendreP <- rowSums(.kLegendreComponents * polynomialComponents, dims = 2)
# Compute semi-normalized Schmidt Legendre values
legendreSchmidtP <- .kNormalizationFactors * legendreP
# Get the next n value of the Schmidt semi-normalized P calculation
legendreSchmidtPNext <- rbind(
legendreSchmidtP[-1, ],
matrix(
rep(0, 14),
ncol = ncol(legendreSchmidtP),
dimnames = dimnames(legendreSchmidtP)
)
)
legendreDerivSchmidtP <- (
(.kDegreeIndexMatrix + 1) * mu * legendreSchmidtP -
sqrt((.kDegreeIndexMatrix + 1)^2 - .kOrderIndexMatrix^2) *
legendreSchmidtPNext
) / ((1 - mu) * (1 + mu))
output <- list(
'P' = legendreP,
'Schmidt P' = legendreSchmidtP,
'Derivative Schmidt P' = legendreDerivSchmidtP
)
return(output)
}
|
/scratch/gouwar.j/cran-all/cranData/wmm/R/functions_legendre.R
|
#' Derive WMM version based on given time
#'
#' @param t Annualized date time. E.g., 2015-02-01 = (2015 + 32/365) = 2015.088
#'
#' @return List of reference year and compatible WMM versions inferred from \code{time}.
.DeriveVersionInfo <- function(t) {
output <- if(t >= 2025) {
stop('Time value not supported in current version of wmm package.')
} else if(t >= 2020 & t < 2025) {
list(
'year' = 2020,
'version' = 'WMM2020'
)
} else if(t >= 2015 & t < 2020) {
list(
'year' = 2015,
'version' = c('WMM2015v2', 'WMM2015')
)
} else if(t >= 2010) {
list(
'year' = 2010,
'version' = 'WMM2010'
)
} else if(t >= 2005){
list(
'year' = 2005,
'version' = 'WMM2005'
)
} else {
stop('Time value not supported in current version of wmm package.')
}
return(output)
}
#' Check if given time is consistent with available WMM versions
#'
#' @param t Annualized date time. E.g., 2015-02-01 = (2015 + 32/365) = 2015.088
#' @param wmmVersion String representing WMM version to use. Must be consistent with \code{time} and one of the following: 'derived', 'WMM2000', 'WMM2005', 'WMM2010', 'WMM2015', 'WMM2015v2'.
.CheckVersionWMM <- function(t, wmmVersion) {
# Get what WMM versions are compatible with the input time
derivedVersionInfo <- .DeriveVersionInfo(t)
if(wmmVersion != 'derived') {
# Check if the input WMM version is consistent with time-compatible versions
if(!(wmmVersion %in% derivedVersionInfo[['version']])) {
stop(
paste(
paste(
'WMM version can only be 1 of the following for the time value',
'provided:'
),
paste0(shQuote(derivedVersionInfo[['version']]), collapse = ', ')
)
)
}
}
return(derivedVersionInfo)
}
#' Check if given horizontal intensity triggers a blackout zone
#'
#' @param h horizontal intensity, \code{numeric}
#'
#' @return \code{warning} if warranted
#'
.CheckBlackoutZone <- function(h) {
if (h < 2000) {
warning(
'Location is in the blackout zone around the magnetic pole as defined by the WMM military specification (https://www.ngdc.noaa.gov/geomag/WMM/data/MIL-PRF89500B.pdf). Compass accuracy is highly degraded in this region.'
)
} else if (h < 6000) {
warning(
'Location is approaching the blackout zone around the magnetic pole as defined by the WMM military specification (https://www.ngdc.noaa.gov/geomag/WMM/data/MIL-PRF89500B.pdf). Compass accuracy may be degraded in this region.'
)
}
}
|
/scratch/gouwar.j/cran-all/cranData/wmm/R/functions_misc.R
|
#' Calculate Expected Magnetic Elements from WMM2020
#'
#' Calculate the magnetic elements (i.e., horizontal intensity, total intensity, inclination, declination, and their secular variation) for given magnetic orthogonal components
#'
#' @param orthComps named \code{list} containing magnetic orthogonal components
#'
#' @return Expected magnetic components from WMM2020. \code{list}
#'
.CalculateMagneticElements <- function(
orthComps
) {
h <- sqrt(orthComps[['x']]^2 + orthComps[['y']]^2)
f <- sqrt(h^2 + orthComps[['z']]^2)
i <- atan2(orthComps[['z']], h)
d <- atan2(orthComps[['y']], orthComps[['x']])
hDot <- (
orthComps[['x']] * orthComps[['xDot']] +
orthComps[['y']] * orthComps[['yDot']]
) / h
fDot <- (
orthComps[['x']] * orthComps[['xDot']] +
orthComps[['y']] * orthComps[['yDot']] +
orthComps[['z']] * orthComps[['zDot']]
) / f
iDot <- (
h * orthComps[['zDot']] -
orthComps[['z']] * hDot
) / f^2
dDot <- (
orthComps[['x']] * orthComps[['yDot']] -
orthComps[['y']] * orthComps[['xDot']]
) / h^2
output <- list(
'h' = h,
'f' = f,
'i' = i * .kRadToDegree,
'd' = d * .kRadToDegree,
'hDot' = hDot,
'fDot' = fDot,
'iDot' = iDot * .kRadToDegree,
'dDot' = dDot * .kRadToDegree
)
return(output)
}
#' Calculate Expected Magnetic Field from WMM2020
#'
#' Calculate the magnetic field for a given location and time using the fitted spherical harmonic model from the 2020 World Magnetic Model.
#'
#' @param lon GPS longitude
#' @param latGD GPS latitude, geodetic
#' @param latGC GPS latitude, geocentric
#' @param radius Radius of curvature of prime vertical at given geodetic latitude
#' @param time Annualized date time. E.g., 2015-02-01 = (2015 + 32/365) = 2015.088
#' @param wmmVersion String representing WMM version to use. Must be consistent with \code{time} and one of the following: 'derived', 'WMM2005', 'WMM2010', 'WMM2015', 'WMM2015v2', 'WMM2020'. Default 'derived' value will infer the latest WMM version consistent with \code{time}.
#'
#' @return Expected magnetic field from WMM2020, \eqn{m_{\lambda_t,\varphi_t,h_t,t}^{WMM}}{m_wmm(lambda_t, phi_t, h_t, t)}. \code{list}
.CalculateMagneticField <- function(
lon,
latGD,
latGC,
radius,
time,
wmmVersion = 'derived'
) {
# Check consistency of given time and wmmVersion
derivedVersionInfo <- .CheckVersionWMM(t = time, wmmVersion = wmmVersion)
if(wmmVersion == 'derived') {
# Assume first value of 'version' output from .DeriveVersionInfo is the most
# appropriate.
# E.g., if the derived reference year is 2015, use the out-of-cycle version.
wmmVersion <- derivedVersionInfo[['version']][1]
}
deltaLatitude <- latGC - latGD # Leave in degrees for deltaLatitude
lon <- lon / .kRadToDegree
latGC <- latGC / .kRadToDegree
latGD <- latGD / .kRadToDegree
# Run workhorse of algorithm, i.e., use recursion relations to sequentially
# calculate different Legendre values to later be summed
mu <- sin(latGC)
legendreTable <- .CalcLegendre(mu)
# Get Gauss coefficients given input time and reference year
gaussCoef <- .CalculateGaussCoef(
t = time,
t0 = derivedVersionInfo[['year']],
wmmVersion = wmmVersion
)
geocentricFields <- .CalculateGeocentricFieldSum(
legendreTable,
gaussCoef,
radius,
lon,
latGC,
deltaLatitude
)
# Convert predicted magnetic field from geocentric to geodetic coordinates
geodentricField <- do.call(
.ConvertGeocentricToGeodeticFieldComponents,
geocentricFields[['Main Field']]
)
geodentricDotField <- do.call(
.ConvertGeocentricToGeodeticFieldComponents,
geocentricFields[['Secular Variation']]
)
output <- union(
geodentricField,
geodentricDotField
)
names(output) <- c(
'x', 'y', 'z',
'xDot', 'yDot', 'zDot'
)
magElements <- .CalculateMagneticElements(output)
output <- c(
output,
magElements
)
return(output)
}
#' Calculate Expected Magnetic Field from WMM
#'
#' Function that takes in geodetic GPS location and annualized time, and returns the expected magnetic field from WMM.
#'
#' @param lon GPS longitude
#' @param lat GPS latitude, geodetic
#' @param height GPS height in meters above ellipsoid
#' @param time Annualized date time. E.g., 2015-02-01 = (2015 + 32/365) = 2015.088; optionally an object (length 1) of class 'POSIXt' or 'Date'
#' @param wmmVersion String representing WMM version to use. Must be consistent with \code{time} and one of the following: 'derived', 'WMM2000', 'WMM2005', 'WMM2010', 'WMM2015', 'WMM2015v2', 'WMM2020'. Default 'derived' value will infer the latest WMM version consistent with \code{time}.
#'
#' @return \code{list} of calculated main field and secular variation vector components in nT and nT/yr, resp. The magnetic element intensities (i.e., horizontal and total intensities, h & f) are in nT and the magnetic element angles (i.e., inclination and declination, i & d) are in degrees, with their secular variation in nT/yr and deg/yr, resp.: \code{x}, \code{y}, \code{z}, \code{xDot}, \code{yDot}, \code{zDot}, \code{h}, \code{f}, \code{i}, \code{d}, \code{hDot}, \code{fDot}, \code{iDot}, \code{dDot}
#' @export
#'
#' @examples
#' GetMagneticFieldWMM(
#' lon = 240,
#' lat = -80,
#' height = 1e5,
#' time = 2022.5,
#' wmmVersion = 'WMM2020'
#' )
#'
#' ## Expected output
#' # x = 5814.9658886215 nT
#' # y = 14802.9663839328 nT
#' # z = -49755.3119939183 nT
#' # xDot = 28.0381961827 nT/yr
#' # yDot = 1.3970624624 nT/yr
#' # zDot = 85.6309533031 nT/yr
#' # h = 15904.1391483373 nT
#' # f = 52235.3588449608 nT
#' # i = -72.27367 deg
#' # d = 68.55389 deg
#' # hDot = 11.5518244235 nT/yr
#' # fDot = -78.0481471753 nT/yr
#' # iDot = 0.04066726 deg/yr
#' # dDot = -0.09217566 deg/yr
#'
#' ## Calculated output
#' #$x
#' #[1] 5814.966
#'
#' #$y
#' #[1] 14802.97
#'
#' #$z
#' #[1] -49755.31
#'
#' #$xDot
#' #[1] 28.0382
#'
#' #$yDot
#' #[1] 1.397062
#'
#' #$zDot
#' #[1] 85.63095
#'
#' #$h
#' #[1] 15904.14
#'
#' #$f
#' #[1] 52235.36
#'
#' #$i
#' #[1] -72.27367
#'
#' #$d
#' #[1] 68.55389
#'
#' #$hDot
#' #[1] 11.55182
#'
#' #$fDot
#' #[1] -78.04815
#'
#' #$iDot
#' #[1] 0.04066726
#'
#' #$dDot
#' #[1] -0.09217566
#'
GetMagneticFieldWMM <- function(
lon,
lat,
height,
time,
wmmVersion = 'derived'
) {
geocentric <- .ConvertGeodeticToGeocentricGPS(lat, height)
if (!is.numeric(time)) {
if (inherits(time, c("POSIXt", "Date"))) {
YrJul <- with(
as.POSIXlt(time),
c(1900 + year, yday + hour/24 + min/1440 + sec/86400)
)
# https://www.timeanddate.com/date/leapyear.html#rules
leapyear <- +((YrJul[1] %% 4 == 0) & ((!YrJul[1] %% 100 == 0) | (YrJul[1] %% 400 == 0)))
ydays <- 365 + leapyear
time <- YrJul[1] + YrJul[2]/ydays
} else {
stop("unrecognized 'time': ", paste(sQuote(class(time)), collapse = ", "))
}
}
output <- .CalculateMagneticField(
lon = lon,
latGD = lat,
latGC = geocentric[['latitude_GC']][1],
radius = geocentric[['radius_GC']][1],
time = time,
wmmVersion = wmmVersion
)
h <- output[['h']]
.CheckBlackoutZone(h)
return(output)
}
|
/scratch/gouwar.j/cran-all/cranData/wmm/R/functions_wmm.R
|
.datatable.aware = TRUE
#' wmm: R Implementation of World Magnetic Model
#'
#' The \code{wmm} package calculates magnetic field at a given location and time according to the World Magnetic Model.
#'
#' @section WMM functions:
#' This package has 1 exported function, \code{\link{GetMagneticFieldWMM}}, which returns a list of:
#' \itemize{
#' \item Main field and secular variation vector components in nT and nT/yr, resp.
#' \item Magnetic element intensities (i.e., horizontal and total intensities, \code{h} & \code{f}) in nT with their secular variation in nT/yr
#' \item Magnetic element angles (i.e., inclination and declination, \code{i} & \code{d}) in degrees with their secular variation in deg/yr
#' }
#'
#' \code{GetMagneticFieldWMM(lambda_t, phi_t, h_t, t)} = (\code{x}, \code{y}, \code{z}, \code{xDot}, \code{yDot}, \code{zDot}, \code{h}, \code{f}, \code{i}, \code{d}, \code{hDot}, \code{fDot}, \code{iDot}, \code{dDot})
#'
#' @section Acknowledgments:
#' Thanks to:
#' \itemize{
#' \item The WMM team past, present, and future for making the Gauss coefficients public domain
#' \item Alex Breeze for tech reviewing the original version of this code, years ago
#' }
#'
#' @docType package
#' @name wmm
NULL
|
/scratch/gouwar.j/cran-all/cranData/wmm/R/wmm.R
|
#' @title Power Calculation Using the Shieh et. al. Approach
#' @name shiehpow
#' @import lamW
#' @description The purpose of \emph{shiehpow} is to perform a power analysis for a one
#' or two-sided Wilcoxon-Mann-Whitney test using the method developed by Shieh and
#' colleagues.
#'
#' @importFrom stats integrate nlm pnorm qnorm rnorm wilcox.test
#'
#' @param n Sample size of first sample (numeric)
#' @param m Sample size of second sample (numeric)
#' @param p Effect size, P(X<Y) (numeric)
#' @param alpha Type I error rate (numeric)
#' @param dist The distribution type for the two groups (“exp”, “dexp”, or “norm”) (string)
#' @param sides Options are “two.sided” and “one.sided” (string)
#' @note When calculating power for dist=”norm”, \emph{shiehpow} uses 100,000 draws from a Z ~ N(0,1)
#' distribution for the internal calculation of p2 and p3 from Shieh et al. (2006); thus
#' \emph{shiehpow} normal distribution power results may vary in the thousandths place from one run
#' to the next.
#'
#' @references
#' Shieh, G., Jan, S. L., Randles, R. H. (2006). On power and sample size
#' determinations for the Wilcoxon–Mann–Whitney test. Journal of Nonparametric
#' Statistics, 18(1), 33-43.
#'
#' Mollan K.R., Trumble I.M., Reifeis S.A., Ferrer O., Bay C.P., Baldoni P.L.,
#' Hudgens M.G. Exact Power of the Rank-Sum Test for a Continuous Variable,
#' arXiv:1901.04597 [stat.ME], Jan. 2019.
#'
#' @examples
#' # We want to calculate the statistical power to compare the distance between mutations on a DNA
#' # strand in two groups of people. Each group (X and Y) has 10 individuals. We assume that the
#' # distance between mutations in the first group is exponentially distributed with rate 3. We assume
#' # that the probability that the distance in the first group is less than the distance in the second
#' # group (i.e., P(X<Y)) is 0.8. The desired type I error is 0.05.
#'
#' shiehpow(n = 10, m = 10, p = 0.80, alpha = 0.05, dist = "exp", sides = "two.sided")
#'
#' @export
#################################################################################
# Author: Orlando Ferrer
# Edited by: Camden Bay, Katie Mollan
# Date: 29JUNE2017, last edited: 20JAN2018
# Notes:
# Ha: theta is not equal to 0, theta is abbreviated as 'tht'
# N is the total sample size, n and m are the group sizes
# calculated parameters: tht, muo, sigo, mu, sig
# p = P(X_1 < Y_1), alpha is set at a default of 0.05,
# "dist" will take inputs: "exp","norm", or "dexp". And the "sides" input will
# take either "one.sided" or "two.sided"
#################################################################################
library(lamW)
shiehpow <- function(n, m, p, alpha=.05, dist, sides="two.sided")
{
if(!(dist %in% c("exp", "norm", "dexp")))
{
stop('dist must be equal to "exp", "norm", or "dexp."')
}
if(sides == "two.sided"){test_sides <- "Two-sided"}
if(sides == "one.sided"){test_sides <- "One-sided"}
# Below we define internal parameters needed for calculating power
N=m+n
np<-length(p)
nn<-length(n)
tht = vector(length=length(p))
muo=vector(length=length(n))
mu=matrix(0,nrow=length(p),ncol=length(n))
sigo=vector(length=length(n))
p2=vector(length=length(p))
p3=vector(length=length(p))
sig=matrix(0,nrow=length(p),ncol=length(n))
p1=vector(length=length(p))
power <- matrix(0,nrow=np,ncol=nn)
# Within this double for-loop we calculate power for 3 different cases: Exponential
# distributions, Standard Normal distributrions, and Double Exponentials distributions
for(i in 1:np) {
for(j in 1:nn) {
# Exponential Case
if (dist == "exp"){
# Here we fix for when theta is negative, which happens when p < 0.5
if(p[i] >= .5) {
tht[i]= -log(2*(1-p[i]))
p1[i] <- p[i]
}
else if (p[i] < .5) {
p1[i] <- 1 - p[i] #When p < 0.5, we evaluate theta[1-p] instead of theta[p]
tht[i]= -log(2*(1-p1[i]))
}
p2[i]= 1-(2/3)*exp(-tht[i]) #P2 value for exp dist
p3[i]= 1-exp(-tht[i]) + (1/3)*exp(-2*tht[i]) #P3 value for exp dist
}
# Standard normal dist case
if(dist=="norm"){
if(p[i] >= .5) {
tht[i]= sqrt(2)*qnorm(p[i])
p1[i] <- p[i]
}
else if (p[i] < .5) {
p1[i] <- 1 - p[i]
tht[i]= sqrt(2)*qnorm(p1[i])
}
p2[i]= mean((pnorm(rnorm(100000)+tht[i]))^2) #P2 value for standard norm
p3[i]= p2[i] #P3 value for standard norm
}
# Double Exp dist case
if(dist=="dexp"){
if(p[i] >= .5) {
# Here we use a "Lambert W" function to be able to write theta in terms of p
# Need to install "lamW" package
tht[i]= (-lamW::lambertWm1(4*(p[i]-1)/(exp(1)^2))) -2
p1[i] <- p[i]
}
else if (p[i] < .5) {
p1[i] <- 1 - p[i]
}
tht[i]= (-lamW::lambertWm1(4*(p1[i]-1)/(exp(1)^2)))-2
p2[i]= 1-(7/12 + tht[i]/2)*exp(-tht[i]) -(1/12)*exp(-2*tht[i])
p3[i]= p2[i]
}
N[j]= m[j]+n[j]
muo[j]= m[j]*n[j]/2
mu[i,j]= (m[j])*(n[j])*p1[i]
sigo[j]= sqrt(m[j]*n[j]*(m[j]+n[j]+1)/12)
sig[i,j]=sqrt(m[j]*n[j]*p1[i]*(1-p1[i]) + m[j]*n[j]*(n[j]-1)*(p2[i]-(p1[i])^2) + m[j]*n[j]*(m[j]-1)*(p3[i]-(p1[i])^2))
za1<-qnorm(alpha,lower.tail=F) #one-sided
za2<-qnorm(alpha/2,lower.tail=F) #two-sided
power[i,j]<-pnorm((mu[i,j]-muo[j]-za2*sigo[j])/sig[i,j]) + pnorm((-mu[i,j]+muo[j]-za2*sigo[j])/sig[i,j])
# if one-sided, we use: power[i,j]<-pnorm((mu[i,j]-muo[j]-za2*sigo[j])/sig[i,j])
# and we would use za1 instead of za2
# one-sided case
if (sides=="one.sided") {
power[i,j]<-pnorm((mu[i,j]-muo[j]-za1*sigo[j])/sig[i,j])
}
}
}
wmw_odds <- round(p/(1-p),3)
cat("Distribution: ", dist, "\n",
"Sample sizes: ", n, " and ", m, "\n",
"p: ", p, "\n",
"WMW odds: ", wmw_odds, "\n",
"sides: ", test_sides, "\n",
"alpha: ", alpha, "\n\n",
"Shieh Power: ", round(power,3),sep = "")
output_list <- list(distribution = dist,n = n, m = m, p = p, wmw_odds = wmw_odds,
alpha = alpha, test_sides = test_sides, power = round(power,3))
}
#shiehpow(n = 9, m = 9, p = 0.76, alpha=.05, dist = "exp", sides="two.sided")
|
/scratch/gouwar.j/cran-all/cranData/wmwpow/R/shiehpow.R
|
#' @title Precise and Accurate Monte Carlo Power Calculation by Inputting Distributions F and G (wmwpowd)
#' @name wmwpowd
#' @description \emph{wmwpowd} has two purposes:
#'
#' 1. Calculate the power for a one-sided or two-sided Wilcoxon-Mann-Whitney test
#' with an empirical p-value given two user specified distributions.
#'
#' 2. Calculate p, the P(X<Y), where X represents random draws from one continuous
#' probability distribution and Y represents random draws from another distribution;
#' p is useful for quantifying the effect size that the Wilcoxon-Mann-Whitney test is
#' assessing.
#'
#' Both 1. and 2. are calculated empirically using simulated data and output automatically.
#'
#' @importFrom stats integrate nlm pnorm qnorm rnorm wilcox.test
#'
#' @usage wmwpowd(n, m, distn, distm, sides, alpha = 0.05, nsims = 10000)
#' @param n Sample size for the first distribution (numeric)
#' @param m Sample size for the second distribution (numeric)
#' @param alpha Type I error rate or significance level (numeric)
#' @param distn Base R’s name for the first distribution and any required parameters
#' ("norm", "beta", "cauchy", "f", "gamma", "lnorm", "unif", "weibull","exp", "chisq", "t", "doublex")
#' @param distm Base R’s name for the second distribution and any required parameters
#' ("norm", "beta", "cauchy", "f", "gamma", "lnorm", "unif", "weibull","exp", "chisq", "t", "doublex")
#' @param sides Options are “two.sided”, “less”, or “greater”. “less” means the
#' alternative hypothesis is that distn is less than distm (string)
#' @param nsims Number of simulated datasets for calculating power; 10,000 is the default.
#' For exact power to the hundredths place (e.g., 0.90 or 90\%) around 100,000 simulated
#' datasets is recommended (numeric)
#' @note Example of distn, distm: “norm(1,2)” or “exp(1)”
#'
#' In addition to all continuous distributions supported in Base R, \emph{wmwpowd} also supports the
#' double exponential distribution from the smoothmest package
#'
#' The output WMWOdds is p expressed as odds p/(1-p)
#'
#' Use $ notation to select specific output parameters
#'
#' The function has been optimized to run through simulations quickly; long wait times are unlikely
#' for n and m of 50 or fewer
#'
#' @references
#' Mollan K.R., Trumble I.M., Reifeis S.A., Ferrer O., Bay C.P., Baldoni P.L.,
#' Hudgens M.G. Exact Power of the Rank-Sum Test for a Continuous Variable,
#' arXiv:1901.04597 [stat.ME], Jan. 2019.
#'
#' @examples
#' # 1. We want to calculate the statistical power to compare body length measured on two groups of
#' # rabbits. Each group (X and Y) has 7 rabbits. We assume that body length will be normally
#' # distributed and have a constant standard deviation of 2 cm among groups. We assume that Group X
#' # will have a mean of 35 cm and Group Y will have a mean of 32 cm; the desired type I error is 0.05.
#'
#' # For real world applications, we recommend increasing nsims to 10000
#' wmwpowd(n = 7, m = 7, distn = "norm(35,2)", distm = "norm(32,2)", sides = "two.sided",
#' alpha = 0.05, nsims=2000)}
#'
#'
#'
#' # 2. We are interested in calculating the statistical power (with type I error = 0.05) for a
#' # comparison of the use of ornamentation among fiddle players living in two regions of the United
#' # States: X county, Texas and Y county, North Carolina. A random sample of 18 fiddlers will be
#' # collected within each state. The fiddlers will practice and perform a standardized version of the
#' # Tennessee Waltz. The proportion of melody notes that are ornamented (including vibrato) will be
#' # calculated. We assume that the proportion will follow a beta distribution with a mean of 0.40 and
#' # a shape well described by alpha = 8 and beta = 12 among the Texas fiddlers. We assume that
#' # the distribution will be shifted to a lower mean of 0.25 and have the shape alpha = 2,
#' # beta = 6 for the North Carolina fiddlers.
#'
#' # For real world applications, we recommend increasing nsims to 10000
#' wmwpowd(n=18, m=18, distn = "beta(8,12)", distm = "beta(2,6)", sides = "two.sided",
#' alpha = 0.05, nsims=2000)
#'
#' @export
#'
#'
#'
###########################################################################################################################
#Name: wmwpowd.R
#Programmer: Camden Bay
#Purpose: A flexible function to perform a power analysis for a precise and accurate Monte-Carlo WMW test through simulation AND output p''
#Notes: p'' is calculated empirically. smoothmest must be installed.
#Date Completed: 11/22/2017
###########################################################################################################################
library(smoothmest)
wmwpowd <- function(n,m,distn,distm,sides="two.sided",alpha = 0.05,nsims=10000)
{
dist1<-distn
dist2<-distm
n1=n
n2=m
if(is.numeric(n1) == F | is.numeric(n2) == F)
{
stop("n1 and n2 must be numeric")
}
if(is.character(dist1) == F | is.character(dist2) == F |
!(sub("[^A-z]+", "", dist1) %in% c("norm", "beta", "cauchy", "f", "gamma", "lnorm", "unif", "weibull","exp", "chisq", "t", "doublex")) |
!(sub("[^A-z]+", "", dist2) %in% c("norm", "beta", "cauchy", "f", "gamma", "lnorm", "unif", "weibull","exp", "chisq", "t", "doublex")))
{
stop("distn and distm must be characters in the form of distribution(parmater1) or distribution(paramter1, parameter2).
See documentation for details.")
}
if(is.numeric(alpha) == F)
{
stop("alpha must be numeric")
}
if(is.numeric(nsims) == F)
{
stop("nsims must be numeric")
}
if (!(sides %in% c("less","greater","two.sided"))){
stop("sides must be character value of less, greater, or two.sided")
}
if(sides == "two.sided"){test_sides <- "Two-sided"}
if(sides %in% c("less", "greater")){test_sides <- "One-sided"}
#Power Simulation
dist1_func_char <- paste("r",sub("\\(.*", "", dist1),"(",n1,",",sub(".*\\(", "", dist1),sep="")
dist2_func_char <- paste("r",sub("\\(.*", "", dist2),"(",n2,",",sub(".*\\(", "", dist2),sep="")
power_sim_func <- function()
{
wilcox.test(eval(parse(text = dist1_func_char)),eval(parse(text = dist2_func_char)),paired=F,correct=F,alternative=sides,
exact=T)$p.value
}
pval_vect <- replicate(nsims,power_sim_func())
empirical_power <- round(sum(pval_vect<alpha)/length(pval_vect),3)
#p
dist1_func_ppp <- paste("r",sub("\\(.*", "", dist1),"(",10000000,",",sub(".*\\(", "", dist1),sep="")
dist2_func_ppp <- paste("r",sub("\\(.*", "", dist2),"(",10000000,",",sub(".*\\(", "", dist2),sep="")
p <- round(sum(eval(parse(text = dist1_func_ppp)) < eval(parse(text = dist2_func_ppp)))/10000000,3)
wmw_odds <- round(p/(1-p),3)
#Output
cat("Supplied distribution 1: ", dist1, "; n = ", n1, "\n",
"Supplied distribution 2: ", dist2, "; m = ", n2, "\n\n",
"p: ", p, "\n",
"WMW odds: ", wmw_odds, "\n",
"Number of simulated datasets: ", nsims, "\n",
test_sides, " WMW test (alpha = ", alpha, ")\n\n",
"Empirical power: ", empirical_power,sep = "")
output_list <- list(empirical_power = empirical_power, alpha = alpha, test_sides = test_sides, p = p,
wmw_odds = wmw_odds, distn = dist1, distm = dist2, n = n1, m= n2)
}
|
/scratch/gouwar.j/cran-all/cranData/wmwpow/R/wmwpowd.R
|
#' @title Precise and Accurate Monte Carlo Power Calculation by Inputting P (wmwpowp)
#' @name wmwpowp
#' @import smoothmest
#' @description \emph{wmwpowp} has two purposes:
#'
#' 1. Calculate the power for a
#' one-sided or two-sided Wilcoxon-Mann-Whitney test with an empirical Monte Carlo p-value given
#' one user specified distribution and p (defined as P(X<Y)).
#'
#' 2. Calculate the parameters of the second
#' distribution. It is assumed that the second population is from the same type of
#' continuous probability distribution as the first population.
#'
#' Power is calculated empirically using simulated data and the parameters are calculated using derived
#' mathematical formulas for P(X<Y).
#'
#' @importFrom stats integrate nlm pnorm qnorm rnorm wilcox.test
#'
#' @usage wmwpowp(n, m, distn, k = 1, p = NA, wmwodds = NA, sides, alpha = 0.05, nsims = 10000)
#' @param n Sample size for the first distribution (numeric)
#' @param m Sample size for the second distribution (numeric)
#' @param p The effect size, i.e., the probability that the first random variable is less than the
#' second random variable (P(X<Y)) (numeric)
#' @param alpha Type I error rate or significance level (numeric)
#' @param distn Base R’s name for the first distribution (known as X in the above notation) and any
#' required parameters. Supported distributions are normal, exponential, and double exponential
#' ("norm","exp", "doublex"). User may enter distribution without parameters, and default parameters will
#' be set (i.e., "norm" defaults to "norm(0,1)"), or user may specify both distribution and parameters
#' (i.e., "norm(0,1)").
#' @param sides Options are “two.sided”, “less”, or “greater”. “less” means the alternative
#' hypothesis is that distn is less than distm (string)
#' @param k Standard deviation (SD) scalar for use with the normal or double
#' exponential distribution options. The SD for distm is computed as k multiplied by
#' the SD for distn. Equivalently, k is the ratio of the SDs of the second and first
#' distribution (k = SDm/SDn). Default is k=1 (equal SDs) (numeric)
#' @param wmwodds The effect size expressed as odds = p/(1-p). Either p or wmwodds must be
#' input (numeric)
#' @param nsims Number of simulated datasets for calculating power; 10,000 is the default.
#' For exact power to the hundredths place (e.g., 0.90 or 90\%) around 100,000 simulated
#' datasets is recommended (numeric)
#'
#' @references
#' Mollan K.R., Trumble I.M., Reifeis S.A., Ferrer O., Bay C.P., Baldoni P.L.,
#' Hudgens M.G. Exact Power of the Rank-Sum Test for a Continuous Variable,
#' arXiv:1901.04597 [stat.ME], Jan. 2019.
#'
#' @examples
#' # We want to calculate the statistical power to compare the distance between mutations on a DNA
#' # strand in two groups of people. Each group (X and Y) has 10 individuals. We assume that the
#' # distance between mutations in the first group is exponentially distributed with rate 3. We assume
#' # that the probability that the distance in the first group is less than the distance in the second
#' # group (i.e., P(X<Y)) is 0.8. The desired type I error is 0.05.
#'
#' wmwpowp(n = 10, m = 10, distn = "exp(3)", p = 0.8, sides = "two.sided", alpha = 0.05)
#'
#' @export
###########################################################################################################################
#Name: wmwpowp.R
#Programmer: Ilana Trumble
#Purpose: Write a flexible function to perform a power analysis for a precise and accurate Monte Carlo WMW test,
# given p'' and one distribution, through simulation. Also return shifted distribution
#Notes: p''=P(X<Y) given by the user; Works with continuous pdfs: norm, exp, double exponential
#Date Completed: 22NOV2017
###########################################################################################################################
library(smoothmest)
wmwpowp<- function(n,m,distn,k=1,p=NA,wmwodds=NA,sides="two.sided",alpha=0.05,nsims=10000)
{
dist1<-distn
if (dist1=="norm"){
dist1<-"norm(0,1)"
}
if (dist1=="exp"){
dist1<-"exp(1)"
}
if (dist1=="doublex"){
dist1<-"doublex(0,1)"
}
n1=n
n2=m
#warnings
if(is.numeric(n1) == F | is.numeric(n2) == F)
{
stop("n1 and n2 must be numeric")
}
if(is.numeric(k) == F)
{
stop("k must be numeric")
}
if(is.character(dist1) == F |
!(sub("[^A-z]+", "", dist1) %in% c("norm","exp", "doublex")))
{
stop("distn must be characters in the form of distribution(parmater1) or distribution(paramter1, parameter2).
See documentation for details.")
}
if(is.numeric(alpha) == F)
{
stop("alpha must be numeric")
}
if(is.numeric(nsims) == F)
{
stop("nsims must be numeric")
}
if(!(sides %in% c("less","greater","two.sided")))
{
stop("sides must be character value of less, greater, or two.sided")
}
if(sub("[^A-z]+", "", dist1) == "exp" & k != 1)
{
stop("the parameter k is not applicable to the exponential distribution")
}
#wmwodds and p warnings
if(is.na(p) == F & is.na(wmwodds) == F)
{
stop("please enter either p or wmwodds, not both")
}
if(is.na(p) == F)
{
if (is.numeric(p) == F | p<0 | p>1)
{
stop("p must be a probability between 0 and 1")
}
wmwodds <- round(p/(1-p),3)
}
else if(is.na(wmwodds) == F)
{
if (is.numeric(wmwodds) == F | wmwodds < 0)
{
stop("wmwodds must be a positive number")
}
p <- wmwodds/(1+wmwodds)
}
# calculate dist2
create_dist2 <- function(input_dist_char,p)
{
dist_name <- sub("[^A-z]+", "", input_dist_char)
if(dist_name =="norm")
{
# calculate mu2
mu1<- as.numeric(gsub(".*\\(|,.*","",input_dist_char))
sd1 <- as.numeric(gsub(".*,|\\)","",input_dist_char))
sd2<-k*sd1
mu2<- (sqrt(sd1^2+sd2^2)*qnorm(p))+mu1
return(paste(dist_name,"(",mu2,",",sd2,")",sep=""))
}
else if(dist_name == "exp")
{
mu <- as.numeric(gsub(".*\\(|\\).*","",input_dist_char))
lambda<- (mu/p)*(1-p)
return(paste(dist_name,"(",lambda,")",sep=""))
}
else if(dist_name=="doublex")
{
mu1<- as.numeric(gsub(".*\\(|,.*","",input_dist_char))
sigma1 <- as.numeric(gsub(".*,|\\)","",input_dist_char))
sigma2<- k*sigma1
integral<-function(mu1,mu2,sigma1,sigma2){
a <- integrate(function(y)
(1/(2*sigma2))*exp(-abs(y-mu2)/sigma2) * (1/2)*exp((y-mu1)/sigma1),
-Inf,mu1
)$value
b <- integrate(function(y)
(1/(2*sigma2))*exp(-abs(y-mu2)/sigma2) * (1-(1/2)*exp(-(y-mu1)/sigma1)),
mu1, Inf
)$value
return(a+b)
}
rootfunc<-function(mu1,mu2,sigma1,sigma2,pr){
s<-integral(mu1,mu2,sigma1,sigma2)-pr
m<-s^2 #square so can use minimization
return(m)
}
muy<-function(mu1,sigma1,sigma2,pr){
start=mu1
# non linear minimization
mu2<-nlm(rootfunc,p=start,
mu1=mu1,sigma1=sigma1,sigma2=sigma2,pr=pr)$estimate
return(mu2)
}
mu2<-muy(mu1=mu1,sigma1=sigma1,sigma2=sigma2,pr=p)
return(paste(dist_name,"(",mu2,",",sigma2,")",sep=""))
}
}
dist2<-create_dist2(dist1,p)
#Power Simulation
power_sim_func<-function(){
dist1_func_char <- paste("r",sub("\\(.*", "", dist1),"(",n1,",",sub(".*\\(", "", dist1),sep="")
dist2_func_char <- paste("r",sub("\\(.*", "", dist2),"(",n2,",",sub(".*\\(", "", dist2),sep="")
return(wilcox.test(eval(parse(text = dist1_func_char)),eval(parse(text = dist2_func_char)),
paired=F,correct=F,exact=T,alternative=sides)$p.value)
}
#vectorize
pval_vect<-replicate(nsims,power_sim_func())
empirical_power <- round(sum(pval_vect<alpha)/length(pval_vect),3)
# shorten decimals in dist2
dist2print <- function(input_dist_char)
{
dist_name <- sub("[^A-z]+", "", input_dist_char)
if(dist_name =="norm")
{
muorig<- as.numeric(gsub(".*\\(|,.*","",input_dist_char))
munew<-round(muorig,3)
var<- as.numeric(gsub(".*,|\\)","",input_dist_char))
return(paste(dist_name,"(",munew,",",var,")",sep=""))
}
if(dist_name =="doublex")
{
muorig<- as.numeric(gsub(".*\\(|,.*","",input_dist_char))
munew<-round(muorig,3)
sigma<- as.numeric(gsub(".*,|\\)","",input_dist_char))
return(paste(dist_name,"(",munew,",",sigma,")",sep=""))
}
if(dist_name == "exp")
{
muorig <- as.numeric(gsub(".*\\(|\\).*","",input_dist_char))
munew<-round(muorig,3)
return(paste(dist_name,"(",munew,")",sep=""))
}
}
#Output
if (sides=="two.sided"){test_sides<-"Two-sided"}
if (sides %in% c("less","greater")){test_sides<-"One-sided"}
# Round p and wmwodds as last step for printing output
cat("Supplied distribution: ", dist1, "; n = ", n1, "\n",
"Shifted distribution: ", dist2print(dist2), "; m = ", n2, "\n\n",
"p: ", round(p,3), "\n",
"WMW odds: ", round(wmwodds,3), "\n",
"Number of simulated datasets: ", nsims, "\n",
test_sides, " WMW test (alpha = ", alpha, ")\n\n",
"Empirical power: ", empirical_power,sep = "")
output_list <- list(empirical_power = empirical_power, alpha = alpha, test_sides = test_sides, p = p,
wmw_odds = wmwodds, distn = dist1, distm = dist2print(dist2), n = n1, m = n2)
}
#wmwpowp(n1=10,n2=9,dist1="exp(2)",k=1,p=.67,wmwodds=NA,sides="two.sided",alpha=0.05,nsims=10000)
|
/scratch/gouwar.j/cran-all/cranData/wmwpow/R/wmwpowp.R
|
#BasicUtil.R
#Note = function() file.show(system.file("NOTE.txt", package="NonCompart"))
s2o = function(vPara) # scaled to original parameters
{
b0 = exp(vPara - e$alpha)
return(b0/(b0 + 1)*(e$UB - e$LB) + e$LB)
}
prun = function(m, n, r)
{
# INPUT
# m : count of fewer species (minimum value = 0)
# n : count of more frequent species (minimum value = 1)
# r : count of run (minimum value = 1)
# RETURNS probability of run count to be less than or equal to r with m and n
# P(Run count <= r | m, n)
# Reference:
# Reviewed Work: Run Test for Randomness by Dorothy Kerr
# Review by: J. W. W.
# Mathematics of Computation
# Vol. 22, No. 102 (Apr., 1968), p. 468
# Published by: American Mathematical Society
# DOI: 10.2307/2004702
# Stable URL: http://www.jstor.org/stable/2004702
if (m==0 & r==1) {
return(1)
} else if (m > n | m < 1 | n < 1 | r < 2 | (r > min(m + n, 2 * m + 1))) {
return(0);
}
sumfu = 0
for (u in 2:r) {
if (u %% 2 == 0) {
k = u/2
fu = 2*choose(m-1, k-1)*choose(n-1, k-1)
} else {
k = (u + 1)/2
fu = choose(m-1, k-1)*choose(n-1, k-2) + choose(m-1, k-2)*choose(n-1, k-1)
}
sumfu = sumfu + fu
}
return(sumfu / choose(m + n, m))
}
run.test = function(Residuals)
{
Resid = Residuals[Residuals != 0] # Zeros are removed.
nResid = length(Resid)
r = Resid > 0
m = sum(r)
if (nResid > 1) {
j = 2:nResid
run = sum(abs(r[j] - r[j - 1])) + 1
} else {
run = 1
}
m = min(m, nResid - m)
n = max(m, nResid - m)
if (run > 1) {
p = prun(m, n, run)
if (p > 0.5) {
p = 1 - prun(m, n, run - 1)
}
} else {
p = 0.5^(nResid - 1)
}
Result = list(m, n, run, p)
names(Result) = c("m", "n", "run", "p.value")
return(Result)
}
nGradient = function(func, x)
{
nVar = length(x)
nRec = length(func(x))
x1 = vector(length = nVar)
x2 = vector(length = nVar)
mga = matrix(nrow=nRec, ncol = 4)
mgr = matrix(nrow=nRec, ncol = nVar)
for (i in 2:nVar) x1[i] = x2[i] = x[i]
for (i in 1:nVar) {
axi = abs(x[i])
if (axi <= 1) { hi = 1e-04
} else { hi = 1e-04*axi }
for (k in 1:4) {
x1[i] = x[i] - hi
x2[i] = x[i] + hi
mga[, k] = (func(x2) - func(x1))/(2*hi)
hi = hi/2
}
mga[, 1] = (mga[, 2]*4 - mga[, 1])/3
mga[, 2] = (mga[, 3]*4 - mga[, 2])/3
mga[, 3] = (mga[, 4]*4 - mga[, 3])/3
mga[, 1] = (mga[, 2]*16 - mga[, 1])/15
mga[, 2] = (mga[, 3]*16 - mga[, 2])/15
mgr[, i] = (mga[, 2]*64 - mga[, 1])/63
x1[i] = x2[i] = x[i]
}
return(mgr)
}
nHessian = function(fx, x)
{
nVar = length(x)
h0 = vector(length=nVar)
x1 = vector(length=nVar)
x2 = vector(length=nVar)
f0 = fx(x)
nRec = length(f0)
ha = matrix(nrow=nRec, ncol=4) # Hessian Approximation
H = rep(0, nRec*nVar*nVar) # Hessian Matrix
dim(H) = c(nRec, nVar, nVar)
for (i in 1:nVar) {
x1[i] = x2[i] = x[i]
axi = abs(x[i])
if (axi < 1) { h0[i] = 1e-4
} else { h0[i] = 1e-4*axi }
}
for (i in 1:nVar) {
for (j in i:1) {
hi = h0[i]
if (i == j) {
for (k in 1:4) {
x1[i] = x[i] - hi
x2[i] = x[i] + hi
ha[, k] = (fx(x1) - 2*f0 + fx(x2))/(hi*hi)
hi = hi/2
}
} else {
hj = h0[j]
for (k in 1:4) {
x1[i] = x[i] - hi
x1[j] = x[j] - hj
x2[i] = x[i] + hi
x2[j] = x[j] + hj
ha[, k] = (fx(x1) - 2*f0 + fx(x2) - H[, i, i]*hi*hi - H[, j, j]*hj*hj)/(2*hi*hj)
hi = hi / 2
hj = hj / 2
}
}
w = 4
for (m in 1:2) {
for (k in 1:(4 - m)) ha[, k] = (ha[, k + 1]*w - ha[, k])/(w - 1)
w = w*4
}
H[, i, j] = (ha[, 2]*64 - ha[, 1]) / 63
if (i != j) H[, j, i] = H[, i, j]
x1[j] = x2[j] = x[j]
}
x1[i] = x2[i] = x[i]
}
return(H)
}
g2inv = function(A, eps=1e-8)
{
idx = abs(diag(A)) > eps
p = sum(idx, na.rm=T)
if (p == 0) { M[, ] = 0 ; attr(M, "rank") = 0 ; return(M) }
B = A[idx, idx, drop=F]
r = 0
for (k in 1:p) {
d = B[k, k]
if (abs(d) < eps) { B[k, ] = 0 ; B[, k] = 0 ; next }
B[k, ] = B[k, ]/d
r = r + 1
for (i in 1:p) {
if (i != k) {
c0 = B[i, k]
B[i, ] = B[i, ] - c0*B[k, ]
B[i, k] = -c0/d
}
}
B[k, k] = 1/d
}
M = matrix(0, nrow=NCOL(A), ncol=NROW(A))
M[1:r, 1:r] = B[1:r, 1:r]
attr(M, "rank") = r
return(M)
}
Hougaard = function(J, H, ssq)
{# J : graident, H: hessian, ssq: sigma square
z = NCOL(J)
m = NROW(J)
if (z*m == 0) stop("No graident information!")
L = g2inv(crossprod(J))
if (attr(L, "rank") < ncol(L)) warning("Crossproduct of gradient is singular!")
W = rep(0, z^3)
dim(W) = rep(z, 3)
for (k in 1:z) {
for (p in 1:z) {
for(j in 1:z) {
for (i in 1:m) W[k, p, j] = W[k, p, j] + J[i, k]*H[i, p, j]
}
}
}
TM = rep(NA, z)
for (i in 1:z) {
tRes = 0
for (j in 1:z) {
for (k in 1:z) {
for (p in 1:z) {
tRes = tRes + L[i, j]*L[i, k]*L[i, p]*(W[j, k, p] + W[k, j, p] + W[p, k, j])
}
}
}
TM[i] = -ssq^2*tRes
}
SK = rep(NA, z)
for (i in 1:z) SK[i] = TM[i]/(ssq*L[i, i])^1.5
names(SK) = colnames(J)
return(SK)
}
|
/scratch/gouwar.j/cran-all/cranData/wnl/R/BasicUtil.R
|
Comp1 = function(Ke, Ka=0, DH) # DH: Dosing History
{
NCOMP = 1
NTIME = nrow(DH)
if (NTIME < 2) stop("Dosing history table should have at least two rows.")
X = matrix(rep(0, (NCOMP + 1)*NTIME), ncol=(NCOMP + 1), nrow=NTIME)
for (i in 2:NTIME) {
pX = X[i - 1, ]
for (j in 1:(NCOMP + 1)) {
if (DH[i - 1, "CMT"] == j & DH[i - 1, "BOLUS"] > 0) {
pX[j] = pX[j] + DH[i - 1, "BOLUS"]
}
}
dT = DH[i, "TIME"] - DH[i - 1, "TIME"]
cR = DH[i - 1, "RATE2"]
E = exp(-Ke*dT)
if (abs(Ka - Ke) > 1e-8) {
Ea = exp(-Ka*dT)
X[i, 1] = pX[1]*Ea
X[i, 2] = pX[2]*E + cR*(1 - E)/Ke + pX[1]*Ka*(E - Ea)/(Ka - Ke)
} else {
X[i, 1] = pX[1]*E
X[i, 2] = pX[2]*E + cR*(1 - E)/Ke + pX[1]*Ke*dT*E
}
}
return(X)
}
|
/scratch/gouwar.j/cran-all/cranData/wnl/R/Comp1.R
|
EnvObj = function(envir = e)
{
Name0 = ls(envir)
nObj = length(Name0)
Result = list()
for (i in 1:nObj) Result[[i]] = get(Name0[i], envir=envir)
names(Result) = Name0
return(Result)
}
|
/scratch/gouwar.j/cran-all/cranData/wnl/R/EnvObj.R
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.