## classic fasterize
library(fasterize)
library(raster)
library(stars)
r0 <- raster(extent(-180, 180, -90, 90), nrows = 360, ncols = 720, crs = "+init=epsg:4326")
s0 <- st_as_stars(st_bbox(c(xmin = -180, ymin = -90, xmax = 180, ymax = 90), crs = 4326),
nx = 720, ny = 360)
pols <- rnaturalearth::ne_countries(returnclass = "sf")
pols$row_index <- seq_len(nrow(pols))
## fudge this happy future day of cell abstraction
fudge <- fasterize(pols, r0, field = "row_index")
nc <- ncol(fudge)
l <- vector("list", nrow(fudge))
set_na_Inf <- function(x) {x[is.na(x)] <- Inf; x}
for (rownum in seq_along(l)) {
rl <- rle(set_na_Inf(raster::extract(fudge, cellFromRow(fudge, rownum))))
## clean up NA
# bad <- is.na(rl$values)
## catch start index of non-NA values
# v <- rl$values
# v[is.na(v)] <- 1
# vstart <- cumsum(v)[!is.na(rl$values)]
l[[rownum]] <- tibble::tibble(row = rownum, value = rl$values[!bad], length = rl$lengths[!bad])
}
library(dplyr)
index <- bind_rows(l)
pryr::object_size(index)
pryr::object_size(fudge)
set_inf_NA <- function(x) {x[!is.finite(x)] <- NA; x}
unpack_rle_stars <- function(rl, template) {
template[[1]][] <- set_inf_NA(rep(rl$value, rl$length))
template
}
unpack_rle_raster <- function(rl, template) {
setValues(template, rep(rl$value, rl$length))
}
plot(unpack_rle_stars(index, s0))
plot(unpack_rle_raster(index, r0))
Comment 1 (2019-06-05)
This way, not the above
Next to write a
pack_raster()function (for this kind of demo, and for quantifying this encoding), and anunpack_raster()or something …Created on 2019-06-05 by the reprex package (v0.3.0)