Currently testing a pit filling solution using focal(). It works on the mock example but it is not consistent when used on a real world DEM;
WIP workflow: Check if cell is on raster edge, if not, it cannot have a lower elevation than its neighbors (pit), elevate it to the minimum of its 8 neighbors + 1 meter.
Question: Can I limit focal to just cells found with pitfinder?
fill_pit <- function(x) {
pit_x <- as.vector(x)
pit_center <- pit_x[5]
if(is.na(pit_center)){ # for use with pitfinder
pit_center <- min(pit_x[-5], na.rm = TRUE) + 1
}
# edge nodes will have atleast 3 NA neighbors
if(length(which(is.na(pit_x[-5]))) < 3){
if (pit_center <= min(pit_x[-5], na.rm = TRUE)) {
pit_center <- min(pit_x[-5], na.rm = TRUE) + 1
}
}
return(pit_center)
}
set.seed(1)
r <- focal(x = extend(elev_B, y = 1), na.policy = "all", fillvalue = NA,
w = 3, fun = function(i) fill_pit(x = i)) %>% crop(ext(elev_B))
# Compute flow direction and accumulation
flowdir <- terrain(elev_B, "flowdir")
flowacc_wBug <- flowAccumulation(flowdir)
# Compute flow direction and accumulation
flowdir <- terrain(r, "flowdir")
flowacc_xBug <- flowAccumulation(flowdir)