Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

unexpected results with shade when stacking different angles and directions with large file #1452

Closed
francisvolh opened this issue Mar 9, 2024 · 3 comments

Comments

@francisvolh
Copy link

francisvolh commented Mar 9, 2024

I am having issues with the example code for the shade function in terra when using a larger raster and attempting the stacked example of angles and directions. . It seems the function does run but the produced object has no layers (as expected from the stacked shade angles).

We have been trying to figure out the issue in this stackoverflow questions:
https://stackoverflow.com/questions/78116098/terra-shade-function-not-stacking-different-angles-and-directions-with-my-own-da?noredirect=1#comment137741126_78116098

Coming to the conclusion that it is a memory issue that breaks the function internally and no error is reported. Also, when attempting to produce 4 individual shades, and averaging them, it works (with my data).

This is a reproducible example, with a different map from the stackoverflow (so I don't have to paste the link here) but its producing the same results in my computer:

library(giscoR)
library(elevatr)
country_sf <- giscoR::gisco_get_countries(
  country = "PE",
  resolution = "1"
)

elev <- elevatr::get_elev_raster(
  locations = country_sf, #warn about locations
  z = 7, clip = "locations"
)




alt<- terra::mask(terra::rast(elev), terra::vect(country_sf))


alt <- terra::disagg(alt, 10, method="bilinear")

slope <- terra::terrain(alt, "slope", unit="radians")

aspect <- terra::terrain(alt, "aspect", unit="radians")


hill <- terra::shade(slope, aspect, 40, 270)

terra::plot(hill, col=grey(0:100/100), legend=FALSE)

The previous output works fine. But the following just runs h but produces either two things:

  1. no layers or no error message
  2. An object as shown below (when more memory is available maybe? but still not enough) where there is one layer and the other 3 are "question marked"/empty, but the layers "exist".
#get a better shade with different angles and directions
h <- terra::shade(slope, aspect, angle = c(45, 45, 45, 80), direction = c(225, 270, 315, 135))

Output with bug:

h
class       : SpatRaster 
dimensions  : 33820, 23310, 4  (nrow, ncol, nlyr)
resolution  : 0.0005423858, 0.0005423858  (x, y)
extent      : -81.32385, -68.68084, -18.35433, -0.01084772  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +no_defs 
sources     : spat__2.tif  
              memory  
              memory  
              memory  
names       :  hs_45_225, hs_45_270, hs_45_315, hs_80_135 
min values  : -0.3026005,        ? ,        ? ,        ?  
max values  :  0.9999985,        ? ,        ? ,        ?  

A raster with some more resolution, may produce zero layer but an SpatRaster with dimensions, resolution, extent, but no min or max values.

I tried just producing the individual shades, and getting a mean via terra::app() which seemed to work.

h1 <- terra::shade(slope, aspect, angle = 45, direction = 225)
h2 <- terra::shade(slope, aspect, angle = 45, direction = 270)
h3 <- terra::shade(slope, aspect, angle = 45, direction = 315)
h4 <- terra::shade(slope, aspect, angle = 80, direction = 135)

stack1 <- c(h1, h2, h3, h4)

meanh <- terra::app(stack1, "mean")

A secondary issue, was that when looking
But when I looked into the example in the documentation, using my "optional method", the average products seem different (just checking the min and max values of the mean output rasters), which Chris mentioned in the SO question that should not be the case.

Original h object from the documentation example (grouped shading)

h
class       : SpatRaster 
dimensions  : 900, 950, 1  (nrow, ncol, nlyr)
resolution  : 0.0008333333, 0.0008333333  (x, y)
extent      : 5.741667, 6.533333, 49.44167, 50.19167  (xmin, xmax, ymin, ymax)
coord. ref. : lon/lat WGS 84 (EPSG:4326) 
source(s)   : memory
varname     : elev 
name        : hs_45_225 
min value   : 0.5087930 
max value   : 0.8495533 


My version of the object with the documentation example data ("individual shading and mean after")

meanh
class : SpatRaster
dimensions : 900, 950, 1 (nrow, ncol, nlyr)
resolution : 0.0008333333, 0.0008333333 (x, y)
extent : 5.741667, 6.533333, 49.44167, 50.19167 (xmin, xmax, ymin, ymax)
coord. ref. : lon/lat WGS 84 (EPSG:4326)
source(s) : memory
name : mean
min value : 0.6748505
max value : 0.8538219

packageVersion("terra")
[1] ‘1.7.73’
@chris-english
Copy link

Can be achieved increasing memory in wopt=list(memmax=.06, or .07. See SO where worked out and likely close. Sorry for my bad advice, but workable now, knowing more.

@francisvolh
Copy link
Author

francisvolh commented Mar 12, 2024

Thanks @chris-english !

So modifying the wopt does help but only if filename is given. I attempted to run it without writing the file (without filename) and the code for shade did run and produced an output, but with no layers at all.

I think terra does give out warning or error messages for other process where it runs out of memory (it has happened to me already), so maybe they can add this to the package in a future release? Plus a warning on the documentation that dissag is needed only for low resolution rasters, and using it in larger rasters will produce unexpected results.

I will leave it to the developer team to close the issue if they see fit or whenever they address some of these suggestions!

cheers!

@rhijmans
Copy link
Member

Sorry for the long response time. I have updated the manual (warning about disagg) and I have made the method more memory safe.

netbsd-srcmastr pushed a commit to NetBSD/pkgsrc that referenced this issue Feb 8, 2025
# Version 1.8-15

## Bug Fixes

- `Readrds` Failed For Rasters With Timestep="Seconds"
  [#1711](Https://Github.Com/Rspatial/terra/issues/1711) by Pascal
  Oettli

- `divide<SpatVector>` always returned NULL
  [#1724](rspatial/terra#1724) by Márcia
  Barbosa

- `erase` failed in some cases
  [#1710](rspatial/terra#1710) by
  erkent-carb

## enhancements

- `bestMatch` now has argument "fun" to allow the use of different
  distance measures, and a <matrix> method

- `wrap` (and `writeRDS`) now captures varnames/longnames
  [#1719](rspatial/terra#1719) by Andrew
  Gene Brown

- improved raster metadata writing
  [#1714](rspatial/terra#1714) by Andrew Gene
  Brown

- `vect` and `writeVector` now properly read and write date and
  datetime
  data. [#1718](rspatial/terra#1718) by
  Andrew Gene Brown

- improved estimate of available memory on linux systems
  [#1506](rspatial/terra#1506) by Cedric
  Rossi

# version 1.8-10

Released 2025-01-13

## bug fixes

- `expanse<SpatRaster>(transform=TRUE)` crashed R when the crs was
  "local". [#1671](rspatial/terra#1671) by
  Michael Chirico

- `patches(values=TRUE)` wrapped around the edges
  [#1675](rspatial/terra#1675) by Michael
  Chirico

- `spin` now correctly handles spherical coordinates
  [#1576](rspatial/terra#1576) by jeanlobry

- `mosaic` sometimes crashed R
  [#1524](rspatial/terra#1524) by John
  Baums, Dave Klinges, and Hugh Graham.

- `spatSample` ignored argument "exp" when taking a random sample with
  na.rm=TRUE on a large raster
  [#1437](rspatial/terra#1437) by Babak
  Naimi

- `split<SpatVector,SpatVector>` did not work properly
  [#1619](rspatial/terra#1619) by Michael
  Sumner

- `autocor` improved handling of NA cells for global Moran computation
  [#1992](rspatial/terra#1592) by Nicholas
  Berryman

- `shade` is more
  memory-safe. [#1452](rspatial/terra#1452)
  by Francis van Oordt and Chris English

- fixed bug in `rasterize` revealed when using `crop(mask=TRUE)`
  [#1686](rspatial/terra#1686) by edixon1

- fixed `to_id = NA` bug in `nearest`
  [#1471](rspatial/terra#1471) by Mats
  Blomqvist

- better handling of date/unit
  [#1684](rspatial/terra#1684) and
  [#1688](rspatial/terra#1688) by Andrew
  Gene Brown

- `spatSample(method="regular")` on a raster with one column returned
  too many samples
  [#1362](rspatial/terra#1362) by Daniel R
  Schlaepfer


## enhancements

- `plot<SpatVector>` now uses the same default viridis color palette
  as `plot<SpatRaster>`
  [#1670](rspatial/terra#1670) by Márcia
  Barbosa

- `relate` now accepts relation="equals"
  [#1672](rspatial/terra#1672) by Krzysztof
  Dyba

- `init` now accepts additional arguments for function "fun"

- better handling of the 32 connections limitation set by the HDF4
  library [#1481](rspatial/terra#1481) by
  Dimitri Falk

- When using RStudio a once per session warning is given when using
  draw, sel or click
  [#1063](rspatial/terra#1063) by Sergei
  Kharchenko

- `distance<SpatRaster>` from lon and lat lines/polygons computes
  distance to the edges instead of the nodes
  [#1462](rspatial/terra#1462) by Derek
  Friend

- `distance<SpatVector,SpatVector>` now works for lon/lat data
  [#1615](rspatial/terra#1615) by Wencheng
  Lau-Medrano

- using overviews for faster plotting of COGs over http
  [#1353](rspatial/terra#1353) by Michael
  Sumner and [#1412](rspatial/terra#1412);
  and argument `plot(x, overview=)` to change the default behavior.

- `extract` with points is now faster for rasters accessed over http
  [#1504](rspatial/terra#1504) by Krzysztof
  Dyba

- `extract` with many points on very large rasters was slower in
  compared to doing the same with "raster" (which uses terra for
  that!) [#1584](rspatial/terra#1584) by
  Hassan Masoomi

- `merge` now has three alternative algorithms
  [1366](rspatial/terra#1366) by Hassan
  Masoomi and [#1650](rspatial/terra#1650)
  by Agustin Lobo


## new

- `$<SpatRaster>` can now be used to get a categorical SpatRaster with
  a different active category

- `scale_linear<SpatRaster>` method for linear scaling of cell values
  between a minimum and maximum value such as 0 and 1

- `distance` and related methods get argument "method" to choose the
  distance algorithm for lon/lat data
  [#1677](rspatial/terra#1677) by Márcia
  Barbosa

- `divide<SpatRaster>` and `divide<SpatVector>` methods

- `nseg` counts the number of segments in a SpatVector
  [#1647](rspatial/terra#1674) by Michael
  Chirico

- `extract` argument "search_radius" to extract values from the
  nearest raster cell that is not `NA`
  [#873](rspatial/terra#873) by
  matthewseanmarcus

- `combineLevels` to combine the levels of all layers
  [link](https://stackoverflow.com/questions/79340152/how-to-set-factor-levels-in-a-rast-stack-using-terra-when-different-levels-exi)
  on SO by Sam
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants