coolbutuseless/nara

Timings to display 1920x1080 nativeRaster slower than to display regular raster using grid.raster or plot.raster?

tomwenseleers opened this issue · 1 comments

Based on my question here
https://stackoverflow.com/questions/48119360/performant-2d-opengl-graphics-in-r-for-fast-display-of-raster-image-using-rdynca

I did some timings to display a 1920x1080 raster image, either using a regular raster or using a nara::nativeRaster.

Strangely enough, I get that a regular raster is faster, presumably due to a bottleneck in the raster_to_nr naster to native raster conversion. Do you see what I might be doing wrong?
Other slight problem seems to be that grid.raster(nara::raster_to_nr(rast), interpolate=FALSE) rotates my raster. Any easy solution for that?

# some example data & desired colour mapping of [0-1] ranged data matrix
library(RColorBrewer)
ncol=1080
cols=colorRampPalette(RColorBrewer::brewer.pal(11, "RdYlBu"))(ncol)
colfun=colorRamp(RColorBrewer::brewer.pal(11, "RdYlBu"))
col = rgb(colfun(seq(0,1, length.out = ncol)), max = 255)
mat=matrix(seq(1:1080)/1080,nrow=1920,ncol=1080,byrow=TRUE)
# function to convert matrix of values to colour raster based on given colour mapping
mat2rast = function(mat, col) {
  idx = findInterval(mat, seq(0, 1, length.out = length(col)))
  colors = col[idx]
  rastmat = t(matrix(colors, ncol = ncol(mat), nrow = nrow(mat), byrow = TRUE))
  class(rastmat) = "raster"
  return(rastmat)
}
system.time(rast <- mat2rast(mat, col)) # 0.05s

# Setup a fast graphics device that can render quickly
x11(type = 'dbcairo', antialias = 'none', width = 8, height = 6)

# grid graphics - fastest of the regular solutions
library(grid)
system.time(grid.raster(rast, interpolate=FALSE)) # 0.04s

# plot.raster method - tie with grid.raster?
par(mar=c(0, 0, 0, 0))
system.time(plot(rast, asp=NA)) # 0.04s

# base R image()
par(mar=c(0, 0, 0, 0))
system.time(image(mat,axes=FALSE,useRaster=TRUE,col=cols)) # 0.21s # note Y is flipped to compared to 2 options above - but not so important as I can fill matrix the way I want

# ggplot2 - just for the record...
df=expand.grid(y=1:1080,x=1:1920)
df$z=seq(1,1080)/1080
library(ggplot2)
system.time({q <- qplot(data=df,x=x,y=y,fill=z,geom="raster") + 
  scale_x_continuous(expand = c(0,0)) + 
  scale_y_continuous(expand = c(0,0)) +
  scale_fill_gradientn(colours = cols) + 
  theme_void() + theme(legend.position="none"); print(q)}) # 2.72s

# timings native raster - 2x slower than grid.raster or plot.raster??
system.time(grid.raster(nara::raster_to_nr(rast))) # 0.1s

The point of this package isn't to do a fast conversion from raster to nativeraster. raster_to_nr() is a convenience function for when you might start with data in that format.

In general, when using nara package, the idea would always be to have the data in nativeraster format (after any initial conversion).