diff --git a/docs/articles/OSGeo4W_QGIS_Rgui.png b/docs/articles/OSGeo4W_QGIS_Rgui.png new file mode 100644 index 0000000..44a72c4 Binary files /dev/null and b/docs/articles/OSGeo4W_QGIS_Rgui.png differ diff --git a/docs/articles/OSGeo4W_QGIS_navbar.png b/docs/articles/OSGeo4W_QGIS_navbar.png new file mode 100644 index 0000000..21f4488 Binary files /dev/null and b/docs/articles/OSGeo4W_QGIS_navbar.png differ diff --git a/docs/articles/OSGeo4W_QGIS_rstudio.png b/docs/articles/OSGeo4W_QGIS_rstudio.png new file mode 100644 index 0000000..11c6db2 Binary files /dev/null and b/docs/articles/OSGeo4W_QGIS_rstudio.png differ diff --git a/docs/articles/OSGeo4W_Rgui.png b/docs/articles/OSGeo4W_Rgui.png new file mode 100644 index 0000000..5b6cb28 Binary files /dev/null and b/docs/articles/OSGeo4W_Rgui.png differ diff --git a/docs/articles/OSGeo4W_rstudio.png b/docs/articles/OSGeo4W_rstudio.png new file mode 100644 index 0000000..5729caa Binary files /dev/null and b/docs/articles/OSGeo4W_rstudio.png differ diff --git a/docs/articles/use.html b/docs/articles/use.html index b122486..78670e3 100644 --- a/docs/articles/use.html +++ b/docs/articles/use.html @@ -113,14 +113,13 @@

Introduction

Starting R inside GRASS

-

When starting GRASS GIS from a terminal console (here GRASS 8.2.0), +

When starting GRASS GIS from a terminal console (here GRASS 8.3.2), one can continue in the GRASS terminal console, starting an interactive -R session from there (here R 4.2.1). Loading and attaching the R-GRASS +R session from there (here R 4.3.3). Loading and attaching the R-GRASS interface package rgrass in the R session, we see that the current GRASS location is detected and reported:

-
$ /home/rsb/topics/grass/g820/bin/grass /home/rsb/topics/grassdata/nc_basic_spm_grass7/rsb
+
$ grass
 Starting GRASS GIS...
-Cleaning up temporary files...
 
           __________  ___   __________    _______________
          / ____/ __ \/   | / ___/ ___/   / ____/  _/ ___/
@@ -128,7 +127,7 @@ 

Starting R inside GRASSStarting R inside GRASS

Since rgrass knows the current location, we can for example use execGRASS() to list GRASS rasters in @@ -164,8 +162,7 @@

Starting R inside GRASS

@@ -188,38 +185,64 @@

Starting GRASS inside RGISBASE, as shown for example in the GRASS terminal console:

GRASS nc_basic_spm_grass7/rsb:github-rsb > echo $GISBASE
-/home/rsb/topics/grass/g820/grass82
+/home/rsb/topics/grass/g832/grass83

Starting R with such a suitable environment variable set lets us retrieve it later when needed. When loaded and attached, rgrass reports that it seems that GRASS is not running:

-
$ GRASS_INSTALLATION=/home/rsb/topics/grass/g820/grass82 R
+
$ GRASS_INSTALLATION=/home/rsb/topics/grass/g832/grass83 R
 
-R version 4.2.1 (2022-06-23) -- "Funny-Looking Kid"
-Copyright (C) 2022 The R Foundation for Statistical Computing
+R version 4.3.3 (2024-02-29) -- "Angel Food Cake"
+Copyright (C) 2024 The R Foundation for Statistical Computing
 Platform: x86_64-pc-linux-gnu (64-bit)
 
 ...
 
 > library(rgrass)
-Loading required package: XML
-GRASS GIS interface loaded with GRASS version: (GRASS not running)
-

On Windows, if OSGeo4W GRASS is being used, the R session must be -started in the OSGeo4W shell. If not, the non-standard placing of files -and of environment variables confuses the function. If -toupper(gisBase)}contains OSGEO4W64/APPS/GRASS -or OSGEO4W/APPS/GRASS, but the environment variable -OSGEO4W_ROOT is not defined, initGRASS will -exit with an error before confusion leads to further errors. For further -details, see https://github.com/rsbivand/rgrass/issues/16 and https://lists.osgeo.org/pipermail/grass-stats/2018-November/001800.html.

+GRASS GIS interface loaded with GRASS version: GRASS 8.3.2 (2024) +and location: nc_basic_spm_grass7
+

On Windows, if GRASS was installed through the OSGeo4W installer, the +R session must be started in the OSGeo4W shell, including starting +RStudio. In using the OSGeo4W shell, found in the Windows left app +navbar (for example here in thw QGIS app group, also found in the +OSGeo4W app group):

+

+

note that the standard PATH to Rgui or RStudio apps is overwritten, +so the program name has to be entered with its full path, for example +"C:\Program Files\R\R-4.3.3\bin\x64\Rgui.exe" or +"C:\Program Files\RStudio\rstudio.exe" in quotes because of +the space. In addition, the working directory in not user-writable, so +also needs to be changed when using Rgui, while RStudio itself changes +to the directory Windows treats as your home directory. First Rgui:

+

+

and RStudio:

+

+

In both cases, warnings can be seen on loading terra +which are not associated with RStudio, Rgui or R, but in this case were +caused by the OSGeo4W express installer not installing the correct +plugins for the GDAL version it installed by default. Using the OSGeo4W +custom installer from OSGeo4W Setup (also in the left app navbar), the +latest version of GDAL can be installed, resolving the non-critical +warnings.

+

If not started in the OSGeo4W shell, the non-standard placing of +files and of environment variables confuses the function and +initGRASS will exit with an error before confusion leads to +further errors. For further details, see https://github.com/rsbivand/rgrass/issues/16 and https://lists.osgeo.org/pipermail/grass-stats/2018-November/001800.html.

The same restriction applies to use of GRASS with QGIS Windows standalone installations, which may be used with initGRASS only if the R session is started from the OSGeo4W shell shipped as part -of the standalone installer (see https://github.com/rsbivand/rgrass/issues/87). The -function will exit with an error if R was not started from the QGIS -OSGeo4W shell before confusion leads to further errors.

+of the standalone installer (see https://github.com/rsbivand/rgrass/issues/87).

+

The QGIS Windows standalone installer may be used to install GRASS +for rgrass, but if GRASS is to be run within R, again R or +RStudio must be started in the OSGeo4W shell installed this time by the +QGIS Windows standalone installer:

+

+

If not started from the required OSGeo4W shell, the function will +exit with an error before confusion leads to further errors.

+

Starting GRASS from R may use a temporary or an existing GRASS -LOCATION.

+LOCATION, as has already been demonstrated in the temporary +directory case in the OSGeo4W and QGIS standalone installer cases.

Temporary GRASS location

@@ -228,7 +251,7 @@

Temporary GRASS locationHere we’ll use a raster file provided with terra:

> library(terra)
-terra 1.6.0
+terra 1.7.71
 > f <- system.file("ex/elev.tif", package="terra")
 > r <- rast(f)

The first argument to initGRASS() is @@ -314,16 +337,15 @@

Existing GRASS locationSimilarly, GRASS may be started in an R session with an existing location by providing the gisDbase=, location= and mapset= arguments with valid values:

-
$ GRASS_INSTALLATION=/home/rsb/topics/grass/g820/grass82 R
+
$ GRASS_INSTALLATION=/home/rsb/topics/grass/g832/grass83 R
 
-R version 4.2.1 (2022-06-23) -- "Funny-Looking Kid"
-Copyright (C) 2022 The R Foundation for Statistical Computing
+R version 4.3.3 (2024-02-29) -- "Angel Food Cake"
+Copyright (C) 2024 The R Foundation for Statistical Computing
 Platform: x86_64-pc-linux-gnu (64-bit)
 
 ...
 
 > library(rgrass)
-Loading required package: XML
 GRASS GIS interface loaded with GRASS version: (GRASS not running)
 > GRASS_INSTALLATION <- Sys.getenv("GRASS_INSTALLATION")
 > loc <- initGRASS(GRASS_INSTALLATION, home=tempdir(), gisDbase="/home/rsb/topics/grassdata", location="nc_basic_spm_grass7", mapset="rsb", override=TRUE)
diff --git a/docs/pkgdown.yml b/docs/pkgdown.yml
index aa1c3a2..04c8dae 100644
--- a/docs/pkgdown.yml
+++ b/docs/pkgdown.yml
@@ -4,5 +4,5 @@ pkgdown_sha: ~
 articles:
   coerce: coerce.html
   use: use.html
-last_built: 2024-03-20T16:36Z
+last_built: 2024-03-22T16:45Z
 
diff --git a/docs/reference/readRAST.html b/docs/reference/readRAST.html
index 60d5208..48d56a1 100644
--- a/docs/reference/readRAST.html
+++ b/docs/reference/readRAST.html
@@ -207,7 +207,7 @@ 

Examples

} #> SpatialGridDataFrame read into GRASS using r.in.bin #> +----------------------------------------------------------------------------+ -#> | Map: sqdemSP Date: Wed Mar 20 17:36:48 2024 | +#> | Map: sqdemSP Date: Fri Mar 22 17:45:27 2024 | #> | Mapset: rsb Login of Creator: rsb | #> | Location: nc_basic_spm_grass7 | #> | DataBase: /home/rsb/topics/grassdata | @@ -241,13 +241,13 @@

Examples

return_format="SGDF"))) } #> user system elapsed -#> 0.665 0.119 0.789 +#> 0.645 0.149 0.799 if (run) {
print(system.time(sqdem <- read_RAST(c("sqdemSP", "elevation"), return_format="terra"))) } #> user system elapsed -#> 0.574 0.128 0.708 +#> 0.596 0.121 0.723 if (run) { names(sqdem) } @@ -306,10 +306,10 @@

Examples

#> resolution : 10, 10 (x, y) #> extent : 630000, 645000, 215000, 228500 (xmin, xmax, ymin, ymax) #> coord. ref. : NAD83(HARN) / North Carolina (EPSG:3358) -#> source : file414998718382.grd -#> name : file414998718382 -#> min value : 0 -#> max value : 66000 +#> source : file8c9c17276bcfe.grd +#> name : file8c9c17276bcfe +#> min value : 0 +#> max value : 66000 if (run) { execGRASS("g.remove", flags="f", name="test_t", type="raster") } diff --git a/docs/reference/readVECT.html b/docs/reference/readVECT.html index dec4012..59ae117 100644 --- a/docs/reference/readVECT.html +++ b/docs/reference/readVECT.html @@ -245,7 +245,7 @@

Examples

write_VECT(schs, "newsch", flags=c("o", "overwrite")) execGRASS("v.info", map="newsch", layer="1") } -#> Warning: GDAL Message 6: dataset /tmp/grass8-rsb-264685/RtmprKPNk7/file414993f57124a.gpkg does not support layer creation option ENCODING +#> Warning: GDAL Message 6: dataset /tmp/grass8-rsb-572678/RtmpRYBNju/file8c9c121531749.gpkg does not support layer creation option ENCODING #> +----------------------------------------------------------------------------+ #> | Name: newsch | #> | Mapset: rsb | @@ -255,7 +255,7 @@

Examples

#> | Map scale: 1:1 | #> | Name of creator: rsb | #> | Organization: | -#> | Source date: Wed Mar 20 17:36:53 2024 | +#> | Source date: Fri Mar 22 17:45:32 2024 | #> | Timestamp (first layer): none | #> |----------------------------------------------------------------------------| #> | Map format: native | diff --git a/docs/reference/rgrass.html b/docs/reference/rgrass.html index 50add33..b1d8036 100644 --- a/docs/reference/rgrass.html +++ b/docs/reference/rgrass.html @@ -132,7 +132,7 @@

Examples

if (run) { write_VECT(smple, "sp_dem", flags=c("overwrite", "o"), ignore.stderr=TRUE) } -#> Warning: GDAL Message 6: dataset /tmp/grass8-rsb-264685/RtmprKPNk7/file414995fcbb924.gpkg does not support layer creation option ENCODING +#> Warning: GDAL Message 6: dataset /tmp/grass8-rsb-572678/RtmpRYBNju/file8c9c15af7295d.gpkg does not support layer creation option ENCODING #> WARNING: Vector map <sp_dem> already exists and will be overwritten if (run) { schoolsDF <- read_VECT("schools", ignore.stderr=TRUE) diff --git a/vignettes/OSGeo4W_QGIS_Rgui.png b/vignettes/OSGeo4W_QGIS_Rgui.png new file mode 100644 index 0000000..44a72c4 Binary files /dev/null and b/vignettes/OSGeo4W_QGIS_Rgui.png differ diff --git a/vignettes/OSGeo4W_QGIS_navbar.png b/vignettes/OSGeo4W_QGIS_navbar.png new file mode 100644 index 0000000..21f4488 Binary files /dev/null and b/vignettes/OSGeo4W_QGIS_navbar.png differ diff --git a/vignettes/OSGeo4W_QGIS_rstudio.png b/vignettes/OSGeo4W_QGIS_rstudio.png new file mode 100644 index 0000000..11c6db2 Binary files /dev/null and b/vignettes/OSGeo4W_QGIS_rstudio.png differ diff --git a/vignettes/OSGeo4W_Rgui.png b/vignettes/OSGeo4W_Rgui.png new file mode 100644 index 0000000..5b6cb28 Binary files /dev/null and b/vignettes/OSGeo4W_Rgui.png differ diff --git a/vignettes/OSGeo4W_rstudio.png b/vignettes/OSGeo4W_rstudio.png new file mode 100644 index 0000000..5729caa Binary files /dev/null and b/vignettes/OSGeo4W_rstudio.png differ diff --git a/vignettes/use.Rmd b/vignettes/use.Rmd index 23f856d..718f5e3 100644 --- a/vignettes/use.Rmd +++ b/vignettes/use.Rmd @@ -1,246 +1,273 @@ ---- -title: "Use of GRASS interface" -author: "Roger Bivand" -output: - html_document: - toc: true - toc_float: - collapsed: false - smooth_scroll: false - toc_depth: 2 -bibliography: refs.bib -vignette: > - %\VignetteIndexEntry{Use of GRASS interface} - %\VignetteEngine{knitr::rmarkdown} - %\VignetteEncoding{UTF-8} ---- - -```{r setup, include=FALSE} -knitr::opts_chunk$set(message = FALSE, warning = FALSE) -``` - -## Introduction - -The original R-GRASS interface [@bivand:00; @neteler+mitasova:08] was written mainly to permit R objects represented as **sp** class objects to be moved to GRASS, and GRASS objects to be moved to R for statistical analysis. From **spgrass6** 0.6-3 (April 2009) following a fruitful workshop at Queen's University, Belfast, the interface was re-written to use the `--interface-description` flag provided for each GRASS command, also used by the Python interface to GRASS commands. Command interface descriptions are parsed from XML and cached as R objects for efficiency. The current version of the R-GRASS interface is contained in this package, **rgrass**. In addition, an R function `initGRASS()` was written to permit GRASS to be started from within GRASS to which we will return below. - -## Starting R inside GRASS - -When starting GRASS GIS from a terminal console (here GRASS 8.2.0), one can continue in the GRASS terminal console, starting an interactive R session from there (here R 4.2.1). Loading and attaching the R-GRASS interface package **rgrass** in the R session, we see that the current GRASS location is detected and reported: - -``` -$ /home/rsb/topics/grass/g820/bin/grass /home/rsb/topics/grassdata/nc_basic_spm_grass7/rsb -Starting GRASS GIS... -Cleaning up temporary files... - - __________ ___ __________ _______________ - / ____/ __ \/ | / ___/ ___/ / ____/ _/ ___/ - / / __/ /_/ / /| | \__ \\_ \ / / __ / / \__ \ - / /_/ / _, _/ ___ |___/ /__/ / / /_/ // / ___/ / - \____/_/ |_/_/ |_/____/____/ \____/___//____/ - -Welcome to GRASS GIS 8.2.0 -GRASS GIS homepage: https://grass.osgeo.org -This version running through: Bash Shell (/bin/bash) -Help is available with the command: g.manual -i -See the licence terms with: g.version -c -See citation options with: g.version -x -If required, restart the GUI with: g.gui wxpython -When ready to quit enter: exit - -Launching GUI in the background, please wait... -GRASS nc_basic_spm_grass7/rsb:github-rsb > R - -R version 4.2.1 (2022-06-23) -- "Funny-Looking Kid" -Copyright (C) 2022 The R Foundation for Statistical Computing -Platform: x86_64-pc-linux-gnu (64-bit) - -... - -> library(rgrass) -Loading required package: XML -GRASS GIS interface loaded with GRASS version: GRASS 8.2.0 (2022) -and location: nc_basic_spm_grass7 -``` -Since **rgrass** *knows* the current location, we can for example use `execGRASS()` to list GRASS rasters in the PERMANENT mapset in the standard North Carolina basic data set (https://grass.osgeo.org/sampledata/north_carolina/nc_basic_spm_grass7.zip): - -``` -> execGRASS("g.list", type="raster", mapset="PERMANENT") -basins -elevation -elevation_shade -geology -lakes -landuse -soils -> q() -Save workspace image? [y/n/c]: n -GRASS nc_basic_spm_grass7/rsb:github-rsb > exit -Cleaning up default sqlite database ... -Cleaning up temporary files... -Done. - -Goodbye from GRASS GIS -``` -Leaving R returns us to the GRASS terminal console, which we can also exit. - -R can also be started within the GRASS GUI, by choosing the console tab, and entering for example `rstudio`, or another R graphical user interface. This screendump shows the same listing of rasters in PERMANENT in `rstudio`: - -```{r, out.width=800, echo=FALSE} -knitr::include_graphics("rstudio_in_GRASS.png") -``` - -## Starting GRASS inside R - -From **spgrass6** 0.6-3, it has also been possible to start a GRASS session from a running R session using the `initGRASS()` function. This is done by setting GRASS and environment variables from the R session (https://grass.osgeo.org/grass-stable/manuals/variables.html). - -It may be useful to set an environment variable to the value of `GISBASE`, as shown for example in the GRASS terminal console: - -``` -GRASS nc_basic_spm_grass7/rsb:github-rsb > echo $GISBASE -/home/rsb/topics/grass/g820/grass82 -``` - -Starting R with such a suitable environment variable set lets us retrieve it later when needed. When loaded and attached, **rgrass** reports that it seems that GRASS is not running: - -``` -$ GRASS_INSTALLATION=/home/rsb/topics/grass/g820/grass82 R - -R version 4.2.1 (2022-06-23) -- "Funny-Looking Kid" -Copyright (C) 2022 The R Foundation for Statistical Computing -Platform: x86_64-pc-linux-gnu (64-bit) - -... - -> library(rgrass) -Loading required package: XML -GRASS GIS interface loaded with GRASS version: (GRASS not running) -``` - -On Windows, if OSGeo4W GRASS is being used, the R session must be started in the OSGeo4W shell. If not, the non-standard placing of files and of environment variables confuses the function. If `toupper(gisBase)}`contains `OSGEO4W64/APPS/GRASS` or `OSGEO4W/APPS/GRASS`, but the environment variable `OSGEO4W_ROOT` is not defined, `initGRASS` will exit with an error before confusion leads to further errors. For further details, see https://github.com/rsbivand/rgrass/issues/16 and https://lists.osgeo.org/pipermail/grass-stats/2018-November/001800.html. - -The same restriction applies to use of GRASS with QGIS Windows standalone installations, which may be used with `initGRASS` only if the R session is started from the OSGeo4W shell shipped as part of the standalone installer (see https://github.com/rsbivand/rgrass/issues/87). The function will exit with an error if R was not started from the QGIS OSGeo4W shell before confusion leads to further errors. - - -Starting GRASS from R may use a temporary or an existing GRASS `LOCATION`. - -### Temporary GRASS location - -If we don't pass an existing location to `initGRASS()`, a temporary GRASS location will be created and set. - -Here we'll use a raster file provided with **terra**: - -``` -> library(terra) -terra 1.6.0 -> f <- system.file("ex/elev.tif", package="terra") -> r <- rast(f) -``` -The first argument to `initGRASS()` is `gisBase=`, which here we are passing the value of the environment variable after checking that it is a directory. The second argument is where to write the `GISRC` file. The third is a template raster (here a `"SpatRaster"` object) from which to clone the temporary location size, position, resolution and projection: - -``` -> GRASS_INSTALLATION <- Sys.getenv("GRASS_INSTALLATION") -> file.info(GRASS_INSTALLATION)$isdir -[1] TRUE -> loc <- initGRASS(gisBase=GRASS_INSTALLATION, home=tempdir(), SG=r, override=TRUE) -``` - -If the `gisBase` argument is missing, `initGRASS()` will do a minimal effort of guessing it. -Firstly, if a `GRASS_INSTALLATION` environment variable is availabe, then its value will automatically be used for `gisBase`. -If not, then the system command `grass --config path` will be tried to get the value of `GISBASE` that corresponds to the GRASS installation in the system PATH (if any). - -As can be seen, `initGRASS()` creates not only environment and GRASS variables, but also many files in the location mapsets; `g.gisenv` also shows details: - -``` -> list.files(file.path(loc$GISDBASE, loc$LOCATION_NAME), recursive=TRUE) -[1] "file28aaf6dc1c44c/WIND" "file28aaf6dc1c44c/windows/input" -[3] "PERMANENT/DEFAULT_WIND" "PERMANENT/PROJ_EPSG" -[5] "PERMANENT/PROJ_INFO" "PERMANENT/PROJ_SRID" -[7] "PERMANENT/PROJ_UNITS" "PERMANENT/PROJ_WKT" -[9] "PERMANENT/WIND" -> execGRASS("g.gisenv") -GISDBASE='/tmp/Rtmpe7QdVd'; -LOCATION_NAME='file28aaf5be4b905'; -MAPSET='file28aaf6dc1c44c'; -GRASS_GUI='text'; -``` -We may now write R objects to the temporary GRASS location for manipulation and analysis, here calculating slope and aspect layers: - -``` -> write_RAST(r, vname="terra_elev") -Importing raster map ... - 100% -SpatRaster read into GRASS using r.in.gdal from file -> execGRASS("g.list", type="raster", mapset=loc$MAPSET) -terra_elev -> execGRASS("r.slope.aspect", flags="overwrite", elevation="terra_elev", slope="slope", aspect="aspect") - 100% -Aspect raster map complete -Slope raster map complete -> u1 <- read_RAST(c("terra_elev", "slope", "aspect")) -Checking GDAL data type and nodata value... - 100% -Using GDAL data type -Exporting raster data to RRASTER format... - 100% -r.out.gdal complete. File created. -Checking GDAL data type and nodata value... - 100% -Using GDAL data type -Exporting raster data to RRASTER format... - 100% -r.out.gdal complete. File created. -Checking GDAL data type and nodata value... - 100% -Using GDAL data type -Exporting raster data to RRASTER format... - 100% -r.out.gdal complete. File created. -> u1 -class : SpatRaster -dimensions : 90, 95, 3 (nrow, ncol, nlyr) -resolution : 0.008333326, 0.008333333 (x, y) -extent : 5.741667, 6.533333, 49.44167, 50.19167 (xmin, xmax, ymin, ymax) -coord. ref. : lon/lat WGS 84 (EPSG:4326) -sources : file29f4b33cd20f6.grd - file29f4b2d2e045b.grd - file29f4b52cab445.grd -names : terra_elev, slope, aspect -min values : 141.00000000, 0.01416342, 0.08974174 -max values : 547.000000, 7.229438, 360.000000 -``` - -### Existing GRASS location - -Similarly, GRASS may be started in an R session with an existing location by providing the `gisDbase=`, `location=` and `mapset=` arguments with valid values: - -``` -$ GRASS_INSTALLATION=/home/rsb/topics/grass/g820/grass82 R - -R version 4.2.1 (2022-06-23) -- "Funny-Looking Kid" -Copyright (C) 2022 The R Foundation for Statistical Computing -Platform: x86_64-pc-linux-gnu (64-bit) - -... - -> library(rgrass) -Loading required package: XML -GRASS GIS interface loaded with GRASS version: (GRASS not running) -> GRASS_INSTALLATION <- Sys.getenv("GRASS_INSTALLATION") -> loc <- initGRASS(GRASS_INSTALLATION, home=tempdir(), gisDbase="/home/rsb/topics/grassdata", location="nc_basic_spm_grass7", mapset="rsb", override=TRUE) -> execGRASS("g.gisenv") -GISDBASE='/home/rsb/topics/grassdata'; -LOCATION_NAME='nc_basic_spm_grass7'; -MAPSET='rsb'; -GRASS_GUI='text'; -> execGRASS("g.list", type="raster", mapset="PERMANENT") -basins -elevation -elevation_shade -geology -lakes -landuse -soils -``` - -## References - +--- +title: "Use of GRASS interface" +author: "Roger Bivand" +output: + html_document: + toc: true + toc_float: + collapsed: false + smooth_scroll: false + toc_depth: 2 +bibliography: refs.bib +vignette: > + %\VignetteIndexEntry{Use of GRASS interface} + %\VignetteEngine{knitr::rmarkdown} + %\VignetteEncoding{UTF-8} +--- + +```{r setup, include=FALSE} +knitr::opts_chunk$set(message = FALSE, warning = FALSE) +``` + +## Introduction + +The original R-GRASS interface [@bivand:00; @neteler+mitasova:08] was written mainly to permit R objects represented as **sp** class objects to be moved to GRASS, and GRASS objects to be moved to R for statistical analysis. From **spgrass6** 0.6-3 (April 2009) following a fruitful workshop at Queen's University, Belfast, the interface was re-written to use the `--interface-description` flag provided for each GRASS command, also used by the Python interface to GRASS commands. Command interface descriptions are parsed from XML and cached as R objects for efficiency. The current version of the R-GRASS interface is contained in this package, **rgrass**. In addition, an R function `initGRASS()` was written to permit GRASS to be started from within GRASS to which we will return below. + +## Starting R inside GRASS + +When starting GRASS GIS from a terminal console (here GRASS 8.3.2), one can continue in the GRASS terminal console, starting an interactive R session from there (here R 4.3.3). Loading and attaching the R-GRASS interface package **rgrass** in the R session, we see that the current GRASS location is detected and reported: + +``` +$ grass +Starting GRASS GIS... + + __________ ___ __________ _______________ + / ____/ __ \/ | / ___/ ___/ / ____/ _/ ___/ + / / __/ /_/ / /| | \__ \\_ \ / / __ / / \__ \ + / /_/ / _, _/ ___ |___/ /__/ / / /_/ // / ___/ / + \____/_/ |_/_/ |_/____/____/ \____/___//____/ + +Welcome to GRASS GIS 8.3.2 +GRASS GIS homepage: https://grass.osgeo.org +This version running through: Bash Shell (/bin/bash) +Help is available with the command: g.manual -i +See the licence terms with: g.version -c +See citation options with: g.version -x +If required, restart the GUI with: g.gui wxpython +When ready to quit enter: exit + +Launching GUI in the background, please wait... +GRASS nc_basic_spm_grass7/rsb:~ > R + +R version 4.3.3 (2024-02-29) -- "Angel Food Cake" +Copyright (C) 2024 The R Foundation for Statistical Computing +Platform: x86_64-pc-linux-gnu (64-bit) + +... + +> library(rgrass) +GRASS GIS interface loaded with GRASS version: GRASS 8.3.2 (2024) +and location: nc_basic_spm_grass7 +``` +Since **rgrass** *knows* the current location, we can for example use `execGRASS()` to list GRASS rasters in the PERMANENT mapset in the standard North Carolina basic data set (https://grass.osgeo.org/sampledata/north_carolina/nc_basic_spm_grass7.zip): + +``` +> execGRASS("g.list", type="raster", mapset="PERMANENT") +basins +elevation +elevation_shade +geology +lakes +landuse +soils +> q() +Save workspace image? [y/n/c]: n +GRASS nc_basic_spm_grass7/rsb:github-rsb > exit +exit +Done. + +Goodbye from GRASS GIS +``` +Leaving R returns us to the GRASS terminal console, which we can also exit. + +R can also be started within the GRASS GUI, by choosing the console tab, and entering for example `rstudio`, or another R graphical user interface. This screendump shows the same listing of rasters in PERMANENT in `rstudio`: + +```{r, out.width=800, echo=FALSE} +knitr::include_graphics("rstudio_in_GRASS.png") +``` + +## Starting GRASS inside R + +From **spgrass6** 0.6-3, it has also been possible to start a GRASS session from a running R session using the `initGRASS()` function. This is done by setting GRASS and environment variables from the R session (https://grass.osgeo.org/grass-stable/manuals/variables.html). + +It may be useful to set an environment variable to the value of `GISBASE`, as shown for example in the GRASS terminal console: + +``` +GRASS nc_basic_spm_grass7/rsb:github-rsb > echo $GISBASE +/home/rsb/topics/grass/g832/grass83 +``` + +Starting R with such a suitable environment variable set lets us retrieve it later when needed. When loaded and attached, **rgrass** reports that it seems that GRASS is not running: + +``` +$ GRASS_INSTALLATION=/home/rsb/topics/grass/g832/grass83 R + +R version 4.3.3 (2024-02-29) -- "Angel Food Cake" +Copyright (C) 2024 The R Foundation for Statistical Computing +Platform: x86_64-pc-linux-gnu (64-bit) + +... + +> library(rgrass) +GRASS GIS interface loaded with GRASS version: GRASS 8.3.2 (2024) +and location: nc_basic_spm_grass7 +``` + +On Windows, if GRASS was installed through the OSGeo4W installer, the R session must be started in the OSGeo4W shell, including starting RStudio. In using the OSGeo4W shell, found in the Windows left app navbar (for example here in thw QGIS app group, also found in the OSGeo4W app group): + +```{r, out.width=200, echo=FALSE} +knitr::include_graphics("OSGeo4W_QGIS_navbar.png") +``` + +note that the standard PATH to Rgui or RStudio apps is overwritten, so the program name has to be entered with its full path, for example `"C:\Program Files\R\R-4.3.3\bin\x64\Rgui.exe"` or `"C:\Program Files\RStudio\rstudio.exe"` in quotes because of the space. In addition, the working directory in not user-writable, so also needs to be changed when using Rgui, while RStudio itself changes to the directory Windows treats as your home directory. First Rgui: + +```{r, out.width=426, echo=FALSE} +knitr::include_graphics("OSGeo4W_Rgui.png") +``` + +and RStudio: + +```{r, out.width=520, echo=FALSE} +knitr::include_graphics("OSGeo4W_rstudio.png") +``` + +In both cases, warnings can be seen on loading `terra` which are not associated with RStudio, Rgui or R, but in this case were caused by the OSGeo4W express installer not installing the correct plugins for the GDAL version it installed by default. Using the OSGeo4W custom installer from OSGeo4W Setup (also in the left app navbar), the latest version of GDAL can be installed, resolving the non-critical warnings. + +If not started in the OSGeo4W shell, the non-standard placing of files and of environment variables confuses the function and `initGRASS` will exit with an error before confusion leads to further errors. For further details, see https://github.com/rsbivand/rgrass/issues/16 and https://lists.osgeo.org/pipermail/grass-stats/2018-November/001800.html. + +The same restriction applies to use of GRASS with QGIS Windows standalone installations, which may be used with `initGRASS` only if the R session is started from the OSGeo4W shell shipped as part of the standalone installer (see https://github.com/rsbivand/rgrass/issues/87). + +The QGIS Windows standalone installer may be used to install GRASS for `rgrass`, but if GRASS is to be run within R, again R or RStudio must be started in the OSGeo4W shell installed this time by the QGIS Windows standalone installer: + +```{r, out.width=426, echo=FALSE} +knitr::include_graphics("OSGeo4W_QGIS_Rgui.png") +``` + +If not started from the required OSGeo4W shell, the function will exit with an error before confusion leads to further errors. + +```{r, out.width=518, echo=FALSE} +knitr::include_graphics("OSGeo4W_QGIS_rstudio.png") +``` + +Starting GRASS from R may use a temporary or an existing GRASS `LOCATION`, as has already been demonstrated in the temporary directory case in the OSGeo4W and QGIS standalone installer cases. + +### Temporary GRASS location + +If we don't pass an existing location to `initGRASS()`, a temporary GRASS location will be created and set. + +Here we'll use a raster file provided with **terra**: + +``` +> library(terra) +terra 1.7.71 +> f <- system.file("ex/elev.tif", package="terra") +> r <- rast(f) +``` +The first argument to `initGRASS()` is `gisBase=`, which here we are passing the value of the environment variable after checking that it is a directory. The second argument is where to write the `GISRC` file. The third is a template raster (here a `"SpatRaster"` object) from which to clone the temporary location size, position, resolution and projection: + +``` +> GRASS_INSTALLATION <- Sys.getenv("GRASS_INSTALLATION") +> file.info(GRASS_INSTALLATION)$isdir +[1] TRUE +> loc <- initGRASS(gisBase=GRASS_INSTALLATION, home=tempdir(), SG=r, override=TRUE) +``` + +If the `gisBase` argument is missing, `initGRASS()` will do a minimal effort of guessing it. +Firstly, if a `GRASS_INSTALLATION` environment variable is availabe, then its value will automatically be used for `gisBase`. +If not, then the system command `grass --config path` will be tried to get the value of `GISBASE` that corresponds to the GRASS installation in the system PATH (if any). + +As can be seen, `initGRASS()` creates not only environment and GRASS variables, but also many files in the location mapsets; `g.gisenv` also shows details: + +``` +> list.files(file.path(loc$GISDBASE, loc$LOCATION_NAME), recursive=TRUE) +[1] "file28aaf6dc1c44c/WIND" "file28aaf6dc1c44c/windows/input" +[3] "PERMANENT/DEFAULT_WIND" "PERMANENT/PROJ_EPSG" +[5] "PERMANENT/PROJ_INFO" "PERMANENT/PROJ_SRID" +[7] "PERMANENT/PROJ_UNITS" "PERMANENT/PROJ_WKT" +[9] "PERMANENT/WIND" +> execGRASS("g.gisenv") +GISDBASE='/tmp/Rtmpe7QdVd'; +LOCATION_NAME='file28aaf5be4b905'; +MAPSET='file28aaf6dc1c44c'; +GRASS_GUI='text'; +``` +We may now write R objects to the temporary GRASS location for manipulation and analysis, here calculating slope and aspect layers: + +``` +> write_RAST(r, vname="terra_elev") +Importing raster map ... + 100% +SpatRaster read into GRASS using r.in.gdal from file +> execGRASS("g.list", type="raster", mapset=loc$MAPSET) +terra_elev +> execGRASS("r.slope.aspect", flags="overwrite", elevation="terra_elev", slope="slope", aspect="aspect") + 100% +Aspect raster map complete +Slope raster map complete +> u1 <- read_RAST(c("terra_elev", "slope", "aspect")) +Checking GDAL data type and nodata value... + 100% +Using GDAL data type +Exporting raster data to RRASTER format... + 100% +r.out.gdal complete. File created. +Checking GDAL data type and nodata value... + 100% +Using GDAL data type +Exporting raster data to RRASTER format... + 100% +r.out.gdal complete. File created. +Checking GDAL data type and nodata value... + 100% +Using GDAL data type +Exporting raster data to RRASTER format... + 100% +r.out.gdal complete. File created. +> u1 +class : SpatRaster +dimensions : 90, 95, 3 (nrow, ncol, nlyr) +resolution : 0.008333326, 0.008333333 (x, y) +extent : 5.741667, 6.533333, 49.44167, 50.19167 (xmin, xmax, ymin, ymax) +coord. ref. : lon/lat WGS 84 (EPSG:4326) +sources : file29f4b33cd20f6.grd + file29f4b2d2e045b.grd + file29f4b52cab445.grd +names : terra_elev, slope, aspect +min values : 141.00000000, 0.01416342, 0.08974174 +max values : 547.000000, 7.229438, 360.000000 +``` + +### Existing GRASS location + +Similarly, GRASS may be started in an R session with an existing location by providing the `gisDbase=`, `location=` and `mapset=` arguments with valid values: + +``` +$ GRASS_INSTALLATION=/home/rsb/topics/grass/g832/grass83 R + +R version 4.3.3 (2024-02-29) -- "Angel Food Cake" +Copyright (C) 2024 The R Foundation for Statistical Computing +Platform: x86_64-pc-linux-gnu (64-bit) + +... + +> library(rgrass) +GRASS GIS interface loaded with GRASS version: (GRASS not running) +> GRASS_INSTALLATION <- Sys.getenv("GRASS_INSTALLATION") +> loc <- initGRASS(GRASS_INSTALLATION, home=tempdir(), gisDbase="/home/rsb/topics/grassdata", location="nc_basic_spm_grass7", mapset="rsb", override=TRUE) +> execGRASS("g.gisenv") +GISDBASE='/home/rsb/topics/grassdata'; +LOCATION_NAME='nc_basic_spm_grass7'; +MAPSET='rsb'; +GRASS_GUI='text'; +> execGRASS("g.list", type="raster", mapset="PERMANENT") +basins +elevation +elevation_shade +geology +lakes +landuse +soils +``` + +## References +