Skip to content

Commit 7b7fc10

Browse files
committed
Add fasterRaster tutorial
Add new tutorial for getting started with the fasterRaster R package
1 parent ac2c26e commit 7b7fc10

File tree

4 files changed

+284
-0
lines changed

4 files changed

+284
-0
lines changed
Lines changed: 284 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,284 @@
1+
---
2+
title: "fasterRaster: Faster Raster Processing in R Using GRASS"
3+
author: "Adam B. Smith"
4+
date: 2025-05-20
5+
date-modified: today
6+
format:
7+
ipynb: default
8+
html:
9+
toc: true
10+
code-tools: true
11+
code-copy: true
12+
code-fold: false
13+
categories: [R]
14+
description: Learn how to use GRASS in R with the fasterRaster package
15+
engine: knitr
16+
execute:
17+
eval: false
18+
---
19+
20+
![](images/fasterRaster_logo.png){.preview-image width=25%}
21+
22+
This tutorial introduces the **fasterRaster** package for **R**, which uses the **GRASS** engine for geospatial processing.
23+
24+
**fasterRaster** interfaces with **GRASS** to process rasters and spatial vector data. It is intended as an add-on to the **terra** and **sf** packages, and relies heavily upon them. For most rasters and vectors that are small or medium-sized in memory/disk, those packages will almost always be faster. They may also be faster for very large objects. But when they aren't, **fasterRaster** can step in.
25+
26+
## Installing **fasterRaster**
27+
28+
You probably already have **fasterRaster** installed on your computer, but if not, start **R** and install the latest release version from CRAN using:
29+
```{r install, eval = FALSE}
30+
install.packages("fasterRaster")
31+
```
32+
or the latest development version using:
33+
```{r install_dev, eval = FALSE}
34+
remotes::install_github("adamlilith/fasterRaster", dependencies = TRUE)
35+
```
36+
(You may need to install the `remotes` package first.)
37+
38+
## Installing **GRASS**
39+
40+
**fasterRaster** uses **GRASS** to do its operations. You will need to install **GRASS** using the "stand-alone" installer, available through the [GRASS](https://grass.osgeo.org/). *Be sure to use the "stand-alone" installer, not the "OSGeo4W" installer!*
41+
42+
Optional: A few functions in **fasterRaster** require **GRASS** "addon" modules, which do not come bundled with **GRASS**. You do not need to install these addons if you do not use functions that call them. A list of functions that require addons can be seen in the "addons" vignette (in **R**, use `vignette("addons", package = "fasterRaster")`). This vignette also explains how to install addons.
43+
44+
## Starting a **fasterRaster** session
45+
46+
I recommend attaching the **data.table**, **terra**, and **sf** packages before attaching **fasterRaster** package to avoid function conflicts. The **data.table** package is not required, but you most surely will use at least one of the other two.
47+
```{r packages}
48+
library(terra)
49+
library(sf)
50+
library(data.table)
51+
library(fasterRaster)
52+
```
53+
To begin, you need to tell **fasterRaster** the full file path of the folder where **GRASS** is installed on your system. Where this is well depend on your operating system and the version of **GRASS** installed. Three examples below show you what this might look like, but you may need to change the file path to match your case:
54+
55+
```{r grassDir_examples, eval = FALSE}
56+
grassDir <- "C:/Program Files/GRASS GIS 8.4" # Windows
57+
grassDir <- "/Applications/GRASS-8.4.app/Contents/Resources" # Mac OS
58+
grassDir <- "/usr/local/grass" # Linux
59+
```
60+
```{r grassDir, echo = FALSE}
61+
grassDir <- "C:/Program Files/GRASS GIS 8.4" # Windows
62+
```
63+
To tell **fasterRaster** where **GRASS** is installed, use the `faster()` function:
64+
65+
```{r faster_grassDir, eval = FALSE}
66+
faster(grassDir = grassDir)
67+
```
68+
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.
69+
70+
Importantly, some **fasterRaster** functions require addons (**GRASS** modules that are optional and are not included with teh **GRASS** download). To see how to set up addons so functions that use them can operate, see `vignette("addons", package = "fasterRaster").
71+
72+
## Importing spatial objects into **fasterRaster** `GRaster`s and `GVector`s
73+
74+
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 come with the **fasterRaster** package.
75+
```{r madElev, eval = FALSE}
76+
madElev <- fastData("madElev") # example SpatRaster
77+
madElev
78+
79+
class : SpatRaster
80+
dimensions : 1024, 626, 1 (nrow, ncol, nlyr)
81+
resolution : 59.85157, 59.85157 (x, y)
82+
extent : 731581.6, 769048.6, 1024437, 1085725 (xmin, xmax, ymin, ymax)
83+
coord. ref. : Tananarive (Paris) / Laborde Grid
84+
source : madElev.tif
85+
name : madElev
86+
min value : 1
87+
max value : 570
88+
```
89+
90+
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.
91+
```{r elev, eval = FALSE}
92+
elev <- fast(madElev)
93+
elev
94+
95+
class : GRaster
96+
topology : 2D
97+
dimensions : 1024, 626, NA, 1 (nrow, ncol, ndepth, nlyr)
98+
resolution : 59.85157, 59.85157, NA (x, y, z)
99+
extent : 731581.552, 769048.635, 1024437.272, 1085725.279 (xmin, xmax, ymin, ymax)
100+
coord ref. : Tananarive (Paris) / Laborde Grid
101+
name(s) : madElev
102+
datatype : integer
103+
min. value : 1
104+
max. value : 570
105+
```
106+
107+
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:
108+
109+
```{r elev_from_file, eval = FALSE}
110+
rastFile <- system.file("extdata", "madElev.tif", package = "fasterRaster")
111+
elev2 <- fast(rastFile)
112+
```
113+
114+
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).
115+
```{r madRivers, eval = FALSE}
116+
madRivers <- fastData("madRivers") # sf vector
117+
madRivers
118+
119+
Simple feature collection with 11 features and 5 fields
120+
Geometry type: LINESTRING
121+
Dimension: XY
122+
Bounding box: xmin: 731627.1 ymin: 1024541 xmax: 762990.1 ymax: 1085580
123+
Projected CRS: Tananarive (Paris) / Laborde Grid
124+
First 10 features:
125+
F_CODE_DES HYC_DESCRI NAM ISO NAME_0 geometry
126+
1180 River/Stream Perennial/Permanent MANANARA MDG Madagascar LINESTRING (739818.2 108005...
127+
1185 River/Stream Perennial/Permanent MANANARA MDG Madagascar LINESTRING (739818.2 108005...
128+
1197 River/Stream Perennial/Permanent UNK MDG Madagascar LINESTRING (747857.8 108558...
129+
1216 River/Stream Perennial/Permanent UNK MDG Madagascar LINESTRING (739818.2 108005...
130+
1248 River/Stream Perennial/Permanent UNK MDG Madagascar LINESTRING (762990.1 105737...
131+
1256 River/Stream Perennial/Permanent UNK MDG Madagascar LINESTRING (742334.2 106858...
132+
1257 River/Stream Perennial/Permanent UNK MDG Madagascar LINESTRING (731803.7 105391...
133+
1264 River/Stream Perennial/Permanent UNK MDG Madagascar LINESTRING (755911.6 104957...
134+
1300 River/Stream Perennial/Permanent UNK MDG Madagascar LINESTRING (731871 1044531,...
135+
1312 River/Stream Perennial/Permanent UNK MDG Madagascar LINESTRING (750186.1 103441...
136+
```
137+
138+
```{r rivers, eval = FALSE}
139+
rivers <- fast(madRivers)
140+
rivers
141+
142+
class : GVector
143+
geometry : 2D lines
144+
dimensions : 11, 11, 5 (geometries, sub-geometries, columns)
145+
extent : 731627.0998, 762990.1321, 1024541.23477, 1085580.45359 (xmin, xmax, ymin, ymax)
146+
coord ref. : Tananarive (Paris) / Laborde Grid
147+
names : F_CODE_DES HYC_DESCRI NAM ISO NAME_0
148+
type : <chr> <chr> <chr> <chr> <chr>
149+
values : River/Stream Perennial/Perm~ MANANARA MDG Madagascar
150+
River/Stream Perennial/Perm~ MANANARA MDG Madagascar
151+
River/Stream Perennial/Perm~ UNK MDG Madagascar
152+
(and 8 more rows)
153+
```
154+
155+
## Operations on `GRaster`s and `GVector`s
156+
157+
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:
158+
```{r how_to_plot, eval = FALSE}
159+
plot(elev)
160+
plot(rivers, col = 'lightblue', add = TRUE)
161+
```
162+
![Elevation and rivers](./images/elev_rivers.png){.preview-image width=50%}
163+
164+
You can use mathematical operators and functions:
165+
166+
```{r multiplication, eval = FALSE}
167+
elev_feet <- elev * 3.28084
168+
elev_feet
169+
170+
class : GRaster
171+
topology : 2D
172+
dimensions : 1024, 626, NA, 1 (nrow, ncol, ndepth, nlyr)
173+
resolution : 59.85157, 59.85157, NA (x, y, z)
174+
extent : 731581.552, 769048.635, 1024437.272, 1085725.279 (xmin, xmax, ymin, ymax)
175+
coord ref. : Tananarive (Paris) / Laborde Grid
176+
name(s) : layer
177+
datatype : double
178+
min. value : 3.2808
179+
max. value : 1870.056
180+
```
181+
182+
```{r log, eval = FALSE}
183+
log10_elev <- log10(elev)
184+
log10_elev
185+
186+
class : GRaster
187+
topology : 2D
188+
dimensions : 1024, 626, NA, 1 (nrow, ncol, ndepth, nlyr)
189+
resolution : 59.85157, 59.85157, NA (x, y, z)
190+
extent : 731581.552, 769048.635, 1024437.272, 1085725.279 (xmin, xmax, ymin, ymax)
191+
coord ref. : Tananarive (Paris) / Laborde Grid
192+
name(s) : log
193+
datatype : double
194+
min. value : 0
195+
max. value : 2.75587485567249
196+
```
197+
198+
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.
199+
200+
The following code 1) creates a raster where cell values reflect the distance between them and the nearest river; b) makes a buffer around the rivers; then c) plots the output:
201+
```{r distance_buffers, eval = FALSE}
202+
dist <- distance(elev, rivers)
203+
dist
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) : distance
212+
datatype : double
213+
min. value : 0
214+
max. value : 21310.9411762729
215+
```
216+
```{r buffer, eval = FALSE}
217+
218+
river_buff <- buffer(rivers, 2000)
219+
river_buff
220+
221+
class : GVector
222+
geometry : 2D polygons
223+
dimensions : 1, 5, 0 (geometries, sub-geometries, columns)
224+
extent : 729629.19151, 764989.97343, 1022544.92079, 1087580.24979 (xmin, xmax, ymin, ymax)
225+
coord ref. : Tananarive (Paris) / Laborde Grid
226+
227+
```
228+
```{r plot_rivers_buffer, eval = FALSE}
229+
plot(dist)
230+
plot(rivers, col = 'lightblue', add = TRUE)
231+
plot(river_buff, border = 'white', add = TRUE)
232+
```
233+
![Distance between each cell and nearest major river](./images/dist_to_rivers.png){.preview-image width=50%}
234+
235+
And that's how you get started! Now that you have a raster and a vector in your **fasterRaster** "location", you can start doing manipulations and analyses using any of the **fasterRaster** functions! To see an annotated list of these functions, use `?fasterRaster`.
236+
237+
## Converting and saving `GRaster`s and `GVector`s
238+
239+
You can convert a `GRaster` to a `SpatRaster` raster using [`rast()`](https://adamlilith.github.io/fasterRaster/reference/rast.html):
240+
```{r rast, eval = FALSE}
241+
terra_elev <- rast(elev)
242+
```
243+
244+
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):
245+
```{r vect, eval = FALSE}
246+
terra_rivers <- vect(rivers)
247+
sf_rivers <- st_as_sf(rivers)
248+
```
249+
250+
251+
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.
252+
```{r write, eval = FALSE}
253+
elev_temp_file <- tempfile(fileext = ".tif") # save as GeoTIFF
254+
writeRaster(elev, elev_temp_file)
255+
256+
vect_temp_file <- tempfile(fileext = ".shp") # save as shapefile
257+
writeVector(rivers, vect_temp_file)
258+
```
259+
260+
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.
261+
262+
# Making fasterRaster faster
263+
264+
1. **Load rasters and vectors directly from disk**: Use [`fast()`](https://adamlilith.github.io/fasterRaster/reference/fast.html) to load rasters and vectrors 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`.
265+
266+
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 actually save the file to disk then uses the respective function from the respective package to connect to the file.
267+
268+
3. **Increase memory and the number of cores usable by GRASS:** By default, `fasterRaster` use 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.
269+
270+
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.
271+
272+
# Known issues
273+
274+
* 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.
275+
276+
* **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".
277+
278+
* 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.
279+
280+
## References
281+
* [fasterRaster](https://adamlilith.github.io/fasterRaster/articles/fasterRaster.html)
282+
* [rgrass](https://osgeo.github.io/rgrass/)
283+
* [sf](https://r-spatial.github.io/sf/articles/sf1.html)
284+
* [terra](https://rspatial.org/index.html)
36.4 KB
Loading
84.5 KB
Loading
366 KB
Loading

0 commit comments

Comments
 (0)