Skip to content

Commit df43236

Browse files
authored
Add fasterRaster tutorial (#51)
1 parent 0362fff commit df43236

File tree

4 files changed

+330
-0
lines changed

4 files changed

+330
-0
lines changed
Lines changed: 330 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,330 @@
1+
---
2+
title: "fasterRaster: Faster Raster Processing in R Using GRASS"
3+
author: "Adam B. Smith"
4+
date: 2026-01-02
5+
date-modified: today
6+
format:
7+
html:
8+
toc: true
9+
code-tools: true
10+
code-copy: true
11+
code-fold: false
12+
categories: [R, rgrass, raster, intermediate]
13+
description: Learn how to use GRASS in R with the fasterRaster package
14+
engine: knitr
15+
execute:
16+
eval: false
17+
---
18+
19+
![](images/fasterRaster_logo.png){.preview-image width=25%}
20+
21+
This tutorial introduces the [**fasterRaster** package](https://github.com/adamlilith/fasterRaster)
22+
for **R**, which uses the **GRASS** engine for geospatial processing.
23+
24+
**fasterRaster** interfaces with **GRASS** to process rasters and spatial vector data.
25+
It is intended as an add-on to the **terra** and **sf** packages, and relies heavily upon them.
26+
For most rasters and vectors that are small or medium-sized in memory/disk, those packages will almost always be faster.
27+
They may also be faster for large objects. But when they aren't, **fasterRaster** can step in.
28+
29+
## Installing **fasterRaster**
30+
31+
You probably already have **fasterRaster** installed on your computer,
32+
but if not, start **R** and install the latest release version from CRAN using:
33+
34+
```{r install, eval = FALSE}
35+
install.packages("fasterRaster")
36+
```
37+
38+
or the latest development version using:
39+
40+
```{r install_dev, eval = FALSE}
41+
remotes::install_github("adamlilith/fasterRaster", dependencies = TRUE)
42+
```
43+
44+
(You may need to install the `remotes` package first.)
45+
46+
## Installing GRASS
47+
48+
**fasterRaster** uses **GRASS** to do its operations.
49+
On Windows you will need to install GRASS using the "stand-alone" installer,
50+
available through the [GRASS](https://grass.osgeo.org/).
51+
*Be sure to use the "stand-alone" installer, not the "OSGeo4W" installer!*
52+
53+
::: {.callout-note title="What about GRASS addons?"}
54+
A few functions in **fasterRaster** require GRASS addon tools, which do not come bundled with GRASS.
55+
You do not need to install these addons if you do not use functions that call them.
56+
A list of functions that require addons can be seen in the "addons" vignette
57+
(in R, use `vignette("addons", package = "fasterRaster")`). This vignette also explains how to install addons.
58+
:::
59+
60+
61+
## Starting a **fasterRaster** session
62+
63+
You should attach the **data.table**, **terra**, and **sf** packages before attaching **fasterRaster** package to avoid function conflicts.
64+
The **data.table** package is not required, but you most surely will use at least one of the other two.
65+
66+
```{r packages}
67+
library(terra)
68+
library(sf)
69+
library(data.table)
70+
library(fasterRaster)
71+
```
72+
73+
To begin, you need to tell **fasterRaster** the full file path of the folder where **GRASS** is installed on your system.
74+
Where this is will depend on your operating system and the version of **GRASS** installed.
75+
Three examples below show you what this might look like, but you may need to change the file path to match your case:
76+
77+
```{r grassDir_examples, eval = FALSE}
78+
grassDir <- "C:/Program Files/GRASS GIS 8.4" # Windows
79+
grassDir <- "/Applications/GRASS-8.4.app/Contents/Resources" # Mac OS
80+
grassDir <- "/usr/local/grass" # Linux
81+
```
82+
83+
```{r grassDir, echo = FALSE}
84+
grassDir <- "C:/Program Files/GRASS GIS 8.4" # Windows
85+
```
86+
To tell **fasterRaster** where **GRASS** is installed, use the `faster()` function:
87+
88+
```{r faster_grassDir, eval = FALSE}
89+
faster(grassDir = grassDir)
90+
```
91+
92+
You can also use the [`faster()`](https://adamlilith.github.io/fasterRaster/reference/faster.html) function to set options that affect how **fasterRaster** functions run. This includes setting the amount of maximum memory and number of computer cores allocated to operations.
93+
94+
## Importing spatial objects into **fasterRaster** `GRaster`s and `GVector`s
95+
96+
In **fasterRaster**, rasters are called `GRaster`s and vectors are called `GVector`s. The easiest (but not always fastest) way to start using a `GRaster` or `GVector` is to convert it from one already in **R**. In the example below, we use a raster that comes with the **fasterRaster** package. The raster represents elevation of a portion of eastern Madagascar. We first load the `SpatRaster` using [`fastData()`](https://adamlilith.github.io/fasterRaster/reference/fastData.html), a helper function for loading example data objects that comes with the **fasterRaster** package.
97+
98+
```{r madElev, eval = FALSE}
99+
madElev <- fastData("madElev") # example SpatRaster
100+
madElev
101+
```
102+
103+
```
104+
class : SpatRaster
105+
dimensions : 1024, 626, 1 (nrow, ncol, nlyr)
106+
resolution : 59.85157, 59.85157 (x, y)
107+
extent : 731581.6, 769048.6, 1024437, 1085725 (xmin, xmax, ymin, ymax)
108+
coord. ref. : Tananarive (Paris) / Laborde Grid
109+
source : madElev.tif
110+
name : madElev
111+
min value : 1
112+
max value : 570
113+
```
114+
115+
Now, we do the conversion to a `GRaster` and a `GVector` using [`fast()`](https://adamlilith.github.io/fasterRaster/reference/fast.html). This function can create a `GRaster` or `GVector` from a `SpatRaster` or a file representing a raster.
116+
117+
```{r elev, eval = FALSE}
118+
elev <- fast(madElev)
119+
elev
120+
```
121+
122+
```
123+
class : GRaster
124+
topology : 2D
125+
dimensions : 1024, 626, NA, 1 (nrow, ncol, ndepth, nlyr)
126+
resolution : 59.85157, 59.85157, NA (x, y, z)
127+
extent : 731581.552, 769048.635, 1024437.272, 1085725.279 (xmin, xmax, ymin, ymax)
128+
coord ref. : Tananarive (Paris) / Laborde Grid
129+
name(s) : madElev
130+
datatype : integer
131+
min. value : 1
132+
max. value : 570
133+
```
134+
135+
Converting rasters and vectors that are already in **R** to `GRaster`s usually takes more time than loading them directly from disk. To load from disk, simply replace the first argument in `fast()` with a string representing the folder path and file name of the raster you want to load into the session. For example, you can do:
136+
137+
```{r elev_from_file, eval = FALSE}
138+
rastFile <- system.file("extdata", "madElev.tif", package = "fasterRaster")
139+
elev2 <- fast(rastFile)
140+
```
141+
142+
Now, let's create a `GVector`. The `fast()` function can take a `SpatVector` from the **terra** package, an `sf` object from the **sf** package, or a string representing the file path and file name of a vector file (e.g., a GeoPackage file or a shapefile).
143+
144+
```{r madRivers, eval = FALSE}
145+
madRivers <- fastData("madRivers") # sf vector
146+
madRivers
147+
```
148+
149+
```
150+
Simple feature collection with 11 features and 5 fields
151+
Geometry type: LINESTRING
152+
Dimension: XY
153+
Bounding box: xmin: 731627.1 ymin: 1024541 xmax: 762990.1 ymax: 1085580
154+
Projected CRS: Tananarive (Paris) / Laborde Grid
155+
First 10 features:
156+
F_CODE_DES HYC_DESCRI NAM ISO NAME_0 geometry
157+
1180 River/Stream Perennial/Permanent MANANARA MDG Madagascar LINESTRING (739818.2 108005...
158+
1185 River/Stream Perennial/Permanent MANANARA MDG Madagascar LINESTRING (739818.2 108005...
159+
1197 River/Stream Perennial/Permanent UNK MDG Madagascar LINESTRING (747857.8 108558...
160+
1216 River/Stream Perennial/Permanent UNK MDG Madagascar LINESTRING (739818.2 108005...
161+
1248 River/Stream Perennial/Permanent UNK MDG Madagascar LINESTRING (762990.1 105737...
162+
1256 River/Stream Perennial/Permanent UNK MDG Madagascar LINESTRING (742334.2 106858...
163+
1257 River/Stream Perennial/Permanent UNK MDG Madagascar LINESTRING (731803.7 105391...
164+
1264 River/Stream Perennial/Permanent UNK MDG Madagascar LINESTRING (755911.6 104957...
165+
1300 River/Stream Perennial/Permanent UNK MDG Madagascar LINESTRING (731871 1044531,...
166+
1312 River/Stream Perennial/Permanent UNK MDG Madagascar LINESTRING (750186.1 103441...
167+
```
168+
169+
```{r rivers, eval = FALSE}
170+
rivers <- fast(madRivers)
171+
rivers
172+
```
173+
174+
```
175+
class : GVector
176+
geometry : 2D lines
177+
dimensions : 11, 11, 5 (geometries, sub-geometries, columns)
178+
extent : 731627.0998, 762990.1321, 1024541.23477, 1085580.45359 (xmin, xmax, ymin, ymax)
179+
coord ref. : Tananarive (Paris) / Laborde Grid
180+
names : F_CODE_DES HYC_DESCRI NAM ISO NAME_0
181+
type : <chr> <chr> <chr> <chr> <chr>
182+
values : River/Stream Perennial/Perm~ MANANARA MDG Madagascar
183+
River/Stream Perennial/Perm~ MANANARA MDG Madagascar
184+
River/Stream Perennial/Perm~ UNK MDG Madagascar
185+
(and 8 more rows)
186+
```
187+
188+
## Operations on `GRaster`s and `GVector`s
189+
190+
You can do operations on `GRaster`s and `GVector`s as if they were `SpatRaster`s, `SpatVector`s, and `sf` objects. For example, you plot them as if the were any other spatial object:
191+
```{r how_to_plot, eval = FALSE}
192+
plot(elev)
193+
plot(rivers, col = 'lightblue', add = TRUE)
194+
```
195+
![Elevation and rivers](./images/elev_rivers.png){width=50%}
196+
197+
You can use mathematical operators and functions:
198+
199+
```{r multiplication, eval = FALSE}
200+
elev_feet <- elev * 3.28084
201+
elev_feet
202+
```
203+
204+
```
205+
class : GRaster
206+
topology : 2D
207+
dimensions : 1024, 626, NA, 1 (nrow, ncol, ndepth, nlyr)
208+
resolution : 59.85157, 59.85157, NA (x, y, z)
209+
extent : 731581.552, 769048.635, 1024437.272, 1085725.279 (xmin, xmax, ymin, ymax)
210+
coord ref. : Tananarive (Paris) / Laborde Grid
211+
name(s) : layer
212+
datatype : double
213+
min. value : 3.2808
214+
max. value : 1870.056
215+
```
216+
217+
```{r log, eval = FALSE}
218+
log10_elev <- log10(elev)
219+
log10_elev
220+
```
221+
222+
```
223+
class : GRaster
224+
topology : 2D
225+
dimensions : 1024, 626, NA, 1 (nrow, ncol, ndepth, nlyr)
226+
resolution : 59.85157, 59.85157, NA (x, y, z)
227+
extent : 731581.552, 769048.635, 1024437.272, 1085725.279 (xmin, xmax, ymin, ymax)
228+
coord ref. : Tananarive (Paris) / Laborde Grid
229+
name(s) : log
230+
datatype : double
231+
min. value : 0
232+
max. value : 2.75587485567249
233+
```
234+
235+
You can also use the many **fasterRaster** functions. In general, these functions have the same names as their **terra** counterparts and often the same arguments. Note that even many **terra** and **fasterRaster** functions have the same name, they do not necessarily produce the exact same output. Much care has been taken to ensure they do, but sometimes there are multiple ways to do the same task, so choices made by the authors of **terra** and **GRASS** can lead to differences.
236+
237+
The following code 1) creates a raster where cell values reflect the distance between them and the nearest river;
238+
2) makes a buffer around the rivers; then 3) plots the output:
239+
240+
```{r distance_buffers, eval = FALSE}
241+
dist <- distance(elev, rivers)
242+
dist
243+
```
244+
245+
```
246+
class : GRaster
247+
topology : 2D
248+
dimensions : 1024, 626, NA, 1 (nrow, ncol, ndepth, nlyr)
249+
resolution : 59.85157, 59.85157, NA (x, y, z)
250+
extent : 731581.552, 769048.635, 1024437.272, 1085725.279 (xmin, xmax, ymin, ymax)
251+
coord ref. : Tananarive (Paris) / Laborde Grid
252+
name(s) : distance
253+
datatype : double
254+
min. value : 0
255+
max. value : 21310.9411762729
256+
```
257+
258+
```{r buffer, eval = FALSE}
259+
river_buff <- buffer(rivers, 2000)
260+
river_buff
261+
```
262+
263+
```
264+
class : GVector
265+
geometry : 2D polygons
266+
dimensions : 1, 5, 0 (geometries, sub-geometries, columns)
267+
extent : 729629.19151, 764989.97343, 1022544.92079, 1087580.24979 (xmin, xmax, ymin, ymax)
268+
coord ref. : Tananarive (Paris) / Laborde Grid
269+
```
270+
271+
```{r plot_rivers_buffer, eval = FALSE}
272+
plot(dist)
273+
plot(rivers, col = 'lightblue', add = TRUE)
274+
plot(river_buff, border = 'white', add = TRUE)
275+
```
276+
277+
![Distance between each cell and the nearest major river](./images/dist_to_rivers.png){width=50%}
278+
279+
And that's how you get started! Now that you have a raster and a vector in your **fasterRaster** "project", you can start doing manipulations and analyses using any of the **fasterRaster** functions! To see an annotated list of these functions, use `?fasterRaster`.
280+
281+
## Converting and saving `GRaster`s and `GVector`s
282+
283+
You can convert a `GRaster` to a `SpatRaster` raster using [`rast()`](https://adamlilith.github.io/fasterRaster/reference/rast.html):
284+
285+
```{r rast, eval = FALSE}
286+
terra_elev <- rast(elev)
287+
```
288+
289+
To convert a `GVector` to the **terra** package's `SpatVector` format or to an `sf` vector, use [`vect()`](https://adamlilith.github.io/fasterRaster/reference/vect.html) or [`st_as_sf()`](https://adamlilith.github.io/fasterRaster/reference/st_as_sf.html):
290+
291+
```{r vect, eval = FALSE}
292+
terra_rivers <- vect(rivers)
293+
sf_rivers <- st_as_sf(rivers)
294+
```
295+
296+
Finally, you can use [`writeRaster()`](https://adamlilith.github.io/fasterRaster/reference/writeRaster.html) and [`writeVector()`](https://adamlilith.github.io/fasterRaster/reference/writeVector.html) to save `GRaster`s and `GVector`s directly to disk. This will always be faster than using `rast()`, `vect()`, or `st_as_sf()` then saving the result from those functions.
297+
298+
```{r write, eval = FALSE}
299+
elev_temp_file <- tempfile(fileext = ".tif") # save as GeoTIFF
300+
writeRaster(elev, elev_temp_file)
301+
302+
vect_temp_file <- tempfile(fileext = ".shp") # save as shapefile
303+
writeVector(rivers, vect_temp_file)
304+
```
305+
306+
There are several ways to speed up **fasterRaster** functions. These are listed below in order of their most likely gains, with the first few being potentially the largest.
307+
308+
# Making fasterRaster faster
309+
310+
1. **Load rasters and vectors directly from disk**: Use [`fast()`](https://adamlilith.github.io/fasterRaster/reference/fast.html) to load rasters and vectors directly from disk. Converting `terra` or `sf` objects to `GRaster`s and `GVector`s can be slower. Why? Because if the object does not have a file to which the `R` object points, use [`fast()`](https://adamlilith.github.io/fasterRaster/reference/fast.html) has to save it to disk first as a GeoTIFF or GeoPackage file, then load it into `GRASS`.
311+
312+
2. **Save `GRaster`s and `GVector`s directly to disk**: Converting `GRaster`s and `GVector`s to `SpatRaster`s or `SpatVector` using [`rast()`](https://adamlilith.github.io/fasterRaster/reference/rast.html) or [`vect()`](https://adamlilith.github.io/fasterRaster/reference/vect.html), then saving them is much slower than just saving them. Why? Because these functions save the file to disk, they then use the respective function from the respective package to connect to the file.
313+
314+
3. **Increase memory and the number of cores usable by GRASS:** By default, `fasterRaster` uses 2 cores and 2048 MB (2 GB) of memory for `GRASS` modules that allow users to specify these values. You can set these to higher values using [`faster()`](https://adamlilith.github.io/fasterRaster/reference/faster.html) and thus potentially speed up some calculations. Functions in newer versions of `GRASS` have more capacity to use these options, so updating `GRASS` to the latest version can help, too.
315+
316+
4. **Do operations on `GRaster`s and `GVector`s in the same coordinate reference system together:** Every time you switch between using a `GRaster` or `GVector` with a different coordinate reference system (CRS), `GRASS` has to spend a few seconds changing to that CRS. You can save some time by doing as much work as possible with objects in one CRS, then switching to work on objects in another CRS.
317+
318+
# Known issues
319+
320+
* Comparability between **terra** and **fasterRaster**: As much as possible, **fasterRaster** functions were written to recreate the output that functions in **terra** produce. However, owing to implementation choices made by the respective developers of **terra** and **GRASS**, outputs are not always the same.
321+
322+
* **fasterRaster** can crash when the temporary folder is cleaned: Some operating systems have automated procedures that clean out the system's temporary folders when they get too large. This can remove files **GRASS** is using and **fasterRaster** is pointing to, rendering them broken. In Windows, this setting can be changed by going to `Settings`, then `Storage`, then `Storage Sense`. Turn off the setting "Keep Windows running smoothly by automatically cleaning up temporary system and app files".
323+
324+
* Disk space fills up: As counter to the previous issue, prolonged use of **fasterRaster** by the same **R** process can create a lot of temporary files in the **GRASS** cache that fills your hard drive. **fasterRaster** does its best to remove these files when they are not needed. However, temporary files can still accumulate. For example, the operation `new_raster <- 2 * old_raster^3` creates a raster file with the `^3` operation, which is then multiplied by 2 to get the desired output. The raster from the `^3` operation is still left in the disk cache, even though it does not have a "name" in **R**. Judicious use of the [`mow()`](https://adamlilith.github.io/fasterRaster/reference/mow.html) function can remove these temporary files.
325+
326+
## References
327+
* [fasterRaster](https://adamlilith.github.io/fasterRaster/articles/fasterRaster.html)
328+
* [rgrass](https://osgeo.github.io/rgrass/)
329+
* [sf](https://r-spatial.github.io/sf/articles/sf1.html)
330+
* [terra](https://rspatial.org/index.html)
36.4 KB
Loading
84.5 KB
Loading
308 KB
Loading

0 commit comments

Comments
 (0)