r-lidar / lidR

Airborne LiDAR data manipulation and visualisation for forestry application
https://CRAN.R-project.org/package=lidR
GNU General Public License v3.0
582 stars 130 forks source link

QUESTION: Use SpatRaster in pixel_metrics #740

Closed ouroukhai closed 6 months ago

ouroukhai commented 6 months ago

UPDATE: I read that SpatRaster objects can not be used in parallel. In my pipeline, I used parallel programming, so some of the problems might occur there. Nevertheless, a suggestion on how to handle a similar situation would be really helpful.

Hello lidR team, And thank you for the excellent package!

I am currently working on a problem for which I want to use raster data (specifically a DTM) in a user-specified function in a pixel_metric() operation. Ideally, I want to be able to write something like this (given that ctg and dtm are defined):

rast <- catalog_map(ctg, funlas, DTM = dtm)

where

fun <- function(X, Y, Z, DTM){
          ---OPERATIONS---
          return(named_list)
}
funlas <- function(las, DTM){
          if (is.empty(las)) return(NULL)
          return(pixel_metrics(las, ~fun(X,Y,Z,DTM), res = 100))
}

When I tried the naive approach of using the DTM immediately, I get error: "external pointer is not valid". I tried also to use merge_spatial() via catalog_map(), but got errors, probably data-specific ones. Is there a suggested method to do such a calculation? My current approach is to write a cropped version (to the las coordinates) of the raster file into a temporary folder and then read it each time, with rast() in the fun(), but it feels too artificial and slow.

Jean-Romain commented 6 months ago

I suggest that your function funlas get a serialized SpatRaster as input and unserialize it on the fly. Look at terra::serialize() and terra::unserialize(). You can also use raster. RasterLayer are serializable