Skip to content
Prev 20510 / 29559 Next

Speeding up raster calculations

Franz:

Here is an example of a weighted by distance from center of the window
function using rasterEngine.  I'd recommend grabbing the latest
version from r-forge (1.3.4 at the time of this email).  I'm
calculating a distance matrix within the function that can be used to
create the weights.  You'd probably want to make the distance matrix
once outside of the function and feed it in as an args=.

library(spatial.tools)

focal_function_with_distance <- function(resource_map,inverse_distance_weight)
{

# You can actually do this calculation once outside of the function,
and feed it in as a weight.
# Create a vector of x-distances from the center of the window:
x_vector <- -floor(dim(resource_map)[1]/2):floor(dim(resource_map)[1]/2)
# Create a vector of y-distance from the center of the window:
y_vector <- -floor(dim(resource_map)[2]/2):floor(dim(resource_map)[2]/2)
# Now turn them into matrices:
x_matrix <- matrix(data=x_vector,ncol=dim(resource_map)[1],nrow=dim(resource_map)[2],byrow=TRUE)
y_matrix <- matrix(data=y_vector,ncol=dim(resource_map)[1],nrow=dim(resource_map)[2],byrow=FALSE)
# Now create a window of the same size as the local window that
contains the distance to the
# center of the window:
distance_matrix <- sqrt(x_matrix^2 + y_matrix^2)

# Some random weighting function:
# Avoid dividing by 0:
weighted_matrix <- 1/(distance_matrix+0.00001)^inverse_distance_weight

# Calculate the mean of the weight times the local window:
weighted_mean <- mean(resource_map*array(weighted_matrix,dim=dim(resource_map)))

# Return the value:
return(weighted_mean)
}



tahoe_lidar_highesthit <-
  raster(system.file("external/tahoe_lidar_highesthit.tif",
package="spatial.tools"))

# Turn on the parallel engine:
sfQuickInit()
# Use rasterEngine.  Turn debugmode=TRUE if you want to debug your
function on a single window.
# This uses a 5 x 5 window:

weighted_by_distance_raster <-
rasterEngine(resource_map=tahoe_lidar_highesthit,fun=focal_function_with_distance,
args=list(inverse_distance_weight=2),window_dims=c(5,5),debugmode=FALSE)

# When you are done it is usually a good idea to shut down the engine
unless you plan
# on doing more rasterEngine runs:
sfQuickStop()
On Mon, Mar 3, 2014 at 8:22 PM, Jonathan Greenberg <jgrn at illinois.edu> wrote: