ropensci / tidync

NetCDF exploration and data extraction
https://docs.ropensci.org/tidync
90 stars 12 forks source link

function to produce arbitrarily oriented rasters #47

Open mdsumner opened 7 years ago

mdsumner commented 7 years ago

This would be useful for building rasters and other formats:

hf <- tidync(source) %<% hyper_filter(...) 
raw <- hyper_slice(hf)
## modify time filter or update file/source
raw2 <- hyper_slice(hf)

hyper_combine(hf, raw) %>% hyper_output("raster") ## something like this
mdsumner commented 6 years ago

I think we can just do hyper_raster. This needs a whole lot more, to allow 3D slices, or to collapse multiple 2D variables onto a brick.

hyper_raster <- function(x, ...) {
  UseMethod("hyper_raster")
}
hyper_raster.tidync <- function(x, ...) {
  tnc <- hyper_filter(x, ...) 
  ax <- tidync:::active_axis_transforms(tnc)
  revy <- identical(order(ax[[2]][[names(ax)[2]]]), rev(seq_len(nrow(ax[[2]]))))
  arr <- hyper_slice(tnc)
  if (length(arr) > 1) warning("only first variable will be used")
  arr <- arr[[1]]
  xx <- ax[[1]] %>% dplyr::filter(.data$selected)
  yy <- ax[[2]] %>% dplyr::filter(.data$selected)
  if (revy) {
    yy <- yy[nrow(yy):1, ]
    arr <- arr[, ncol(arr):1]
  } else {
    #arr <- arr[nrow(arr):1, ]
  }
  ## need to buffer the range by half cell here
  ex <- raster::extent(range(xx[[names(ax)[1]]]), range(yy[[names(ax)[2]]]))
  setExtent(raster::raster(t(arr[, ncol(arr):1])), ex)
}

file <- system.file("extdata", "oceandata", "S20092742009304.L3m_MO_CHL_chlor_a_9km.nc", package = "tidync")
#file <- raadtools::sstfiles()$fullname[1]
library(raster)
library(tidync)

x <- tidync(file)
tnc <- hyper_filter(x, lon = dplyr::between(lon, 100, 200), lat = lat < 0 & lat > -55)
plot(hyper_raster(tnc), col = palr::sstPal(1000))
maps::map(add = TRUE)
mdsumner commented 6 years ago

I inadvertently recreated hyper_raster with the y-direction check: https://github.com/hypertidy/tidync/blob/expt-group-by/R/filter-groupby.R