How to store a d8 pointer as a terra::SpatRaster?

23 Views Asked by At

I am developing code in R that relies on the flowdem package for hydrological analysis. I chose flowdem because it was the only R package I could find that can delineate a watershed and return the result as an R object stored in memory, while other packages are wrappers around command line tools that write the result on disk. And I need to do delineate many watersheds.

However, flowdem depends on raster, which is deprecated, so I am considering updating flowdem to remove the dependency to raster and switch to terra instead. One thing that will likely be a problem, though, is that while raster had a datatype() <- function that allowed to set cell values type, terra does not (at least according to this answer by Robert Hijmans : Controlling terra SpatRaster size in memory) and all SpatRasters internally use 8 bytes floating point values. In hydrological analysis, the direction towards which water flows from each cell is commonly represented as a d8 pointer, ie a raster with integer values 1 to 8, each value indicating a direction. Storing a d8 as double instead of uint8 is suboptimal for memory usage, but more importantly, it makes the comparison with integer values more complex and costly.

Is there a way to use terra to store and process d8 pointers efficiently ? If you have another package than flowdem to recommend to perform hydrological analysis (one that does not rely on deprecated packages), that would also be an acceptable answer.

In flowdem, most of the processing is done in C++, so I guess one way could be to cast the cell values from double to uint8 at the beginning of the C++ functions that use d8. Not very elegant, though, and likely not performant when calling those functions repeatedly.

I have read about categorical rasters in terra, but I don't know how they are internally stored and whether they would require conversion to uint8 when calling C++ functions.

0

There are 0 best solutions below