---
author: "Chris Reudenbach"
title: "Basic usage of link2GI"
date: "`r Sys.Date()`"
editor_options:
  chunk_output_type: console
output:
  html_document: 
    theme: united
    toc: yes
  rmarkdown: default
  pdf_document:
    latex_engine: xelatex
    toc: yes
urlcolor: blue
vignette: >
  %\VignetteIndexEntry{Basic usage of link2GI}
  %\VignetteEncoding{UTF-8}{inputenc}\
  %\VignetteEngine{knitr::knitr}
---



##  Brute force search
Automatic searching and finding of installed GIS software binaries is done by the `find` functions. Depending on your operating system and the number of installed versions you will get a data frame with the binary and module folders.


```{r, eval=FALSE}
# find all SAGA GIS installations at the default search location
require(link2GI)
saga <- link2GI::findSAGA()
saga
```

Same with `GRASS` and `OTB`

```{r, eval=FALSE}
require(link2GI)
grass <- link2GI::findGRASS()
grass
otb <- link2GI::findOTB(searchLocation = "~/")
otb
```


The `find' functions provide an overview of the installed software. These functions do not create links or change settings.

## Setting up project structures

If you are just calling link2GI on the fly, i.e. for a single temporary operation, there is no need to set up folders and project structures. If you are working on a more complex project, it might be helpful to have a fixed structure. The same goes for existing `GRASS` projects that need to be in specific mapsets and locations. 

A simple (you can call it dirty) approach is the `initProj` function, which creates folder structures (if not existing) and sets global variables (if desired) containing the paths as strings.

```{r, eval=FALSE}
require(link2GI)
dirs = link2GI::createFolders(root_folder = tempdir(),
                                folders = c("data/",
                                            "data/level0/",
                                            "data/level1/",
                                            "output/",
                                            "run/",
                                            "fun/")
                                )
dirs
```


## linkSAGA - Find and set up 'SAGA' API bindings
In the past it was quite tedious to link the correct `SAGA GIS` version. Since version 1.x.x of `RSAGA` things are much better. The new `RSAGA::rsaga.env()` function is to get the first `RSAGA` version in the search path. It is also possible to pass the version number as shown below. Storing the result in appropriate variables will even allow you to easily switch between different `SAGA GIS` installations.


```{R eval=FALSE, echo=FALSE, message=FALSE, warning=FALSE}
require(link2GI)
# find all SAGA GIS installations and take the first one
saga1 <- link2GI::linkSAGA() 
saga1

```

## linkGRASS - Find and set up GRASS 7/8 API bindings

`linkGRASS` initializes the session environment and system paths for easy access to `GRASS GIS 7.x./8.x`. The correct setting of spatial and projection parameters is done automatically either by using an existing and valid `raster` or `terra`, `sp` or `sf` object or manually by providing a list of minimum required parameters. These properties are used to initialize either a temporary or a permanent `rgrass` environment, including the correct `GRASS 7/8` database structure. If you do not specify any of the above, `linkGRASS` will create an EPSG:4326 worldwide site.

The most time consuming part on Windows systems is the search process. This can easily take 10 minutes or more. To speed up this process, you can also provide a correct parameter set. The best way to do this is to call `findGRASS` manually. Then call `linkGRASS` with the returned version arguments of your choice.

The `linkGRASS` function tries to find all valid `GRASS GIS` binaries by analyzing the `GRASS GIS` startup script files. After identifying the `GRASS GIS` binaries, all necessary system variables and settings are generated and passed to a temporary `R` environment.

If you have more than one valid installation and run `linkGRASS` with the arguments `select_ver = TRUE`, you will be asked to select one.



#### Standard full search usage 
The most common use of `GRASS` is for a single call or algorithm. The user is not interested in setting all the parameters. linGRASS7(georeferenced-dataset)` does an automatic search and finds all the `GRASS` binaries using the georeferenced-dataset object for spatial referencing and other necessary settings. 
**NOTE:** This is the highly recommended linking procedure for all on-the-fly invocations of `GRASS`. Please also note that if more than one `GRASS` installation is found, the one with the highest version number is automatically selected. 

Take a look at the following examples, which show a typical call for the well-known `sp` and `sf` vector data objects.

Starting with `sp`.

```{r, eval=FALSE}
# get meuse data as sp object and link it temporary to GRASS
require(link2GI)
require(sf)
require(sp)
crs = 28992
# get data 
data(meuse) 
meuse_sf = st_as_sf(meuse, coords = c("x", "y"), crs = crs, agr = "constant")

# Automatic search and find of GRASS binaries
# using the meuse sp data object for spatial referencing
# This is the highly recommended linking procedure for on the fly jobs
# NOTE: if more than one GRASS installation is found the highest version will be selected

linkGRASS(meuse_sf,epsg = crs)
```
Now do the same with  `sf` based data.

```{r, eval=FALSE}
 require(link2GI)
 require(sf)

 # get  data
 nc <- st_read(system.file("shape/nc.shp", package="sf"))
terra::crs(nc)
 # Automatic search and find of GRASS binaries
 # using the nc sf data object for spatial referencing
 # This is the highly recommended linking procedure for on the fly jobs
 # NOTE: if more than one GRASS installation is found the highest version will be selected
 
 grass<-linkGRASS(nc,returnPaths = TRUE)
```
 
 The second most common situation is to use an existing `GRASS` site and project, either with existing data sets or manually provided parameters. 
 
```{r, eval=FALSE}
  library(link2GI)
 require(sf)

 # proj folders
 root_folder<-tempdir()
 paths<-link2GI::createFolders(root_folder = root_folder,
                          folders = c("project1/"))

 # get  data
 nc <- st_read(system.file("shape/nc.shp", package="sf"))

 # CREATE and link to a permanent GRASS folder at "root_folder", location named "project1"
 linkGRASS(nc, gisdbase = root_folder, location = "project1")

 # ONLY LINK to a permanent GRASS folder at "root_folder", location named "project1"
 linkGRASS(gisdbase = root_folder, location = "project1", gisdbase_exist = TRUE )


 # setting up GRASS manually with spatial parameters of the nc data
 epsg = 28992
 proj4_string <- sp::CRS(paste0("+init=epsg:",epsg))
 
 linkGRASS(spatial_params = c(178605,329714,181390,333611,proj4_string@projargs),epsg=epsg)

 # creating a GRASS gisdbase manually with spatial parameters of the nc data
 # additionally using a peramanent directory "root_folder" and the location "nc_spatial_params "
 epsg = 4267
 proj4_string <- sp::CRS(paste0("+init=epsg:",epsg))@projargs
 linkGRASS(gisdbase = root_folder,
            location = "nc_spatial_params",
            spatial_params = c(-84.32385, 33.88199,-75.45698,36.58965,proj4_string),epsg = epsg)

```

 



#### Typical for specified search paths and OS
 
The full disk search can be tedious, especially on Windows it can easily take 10 minutes or more. So it is helpful to specify a search path to narrow down the search. To search for `GRASS` installations in the home directory, you can use the following command. 


```{r, eval=FALSE}
# Link the GRASS installation and define the search location
 linkGRASS(nc, search_path = "~/")
```

If  you already did a full search and kow your installation fo example using the command `findGRASS` you can use the result directly for linking.


```{r, eval=FALSE}
findGRASS()
     instDir version installation_type
1 /usr/lib/grass83   8.3.2             grass

# now linking it 
linkGRASS(nc,c("/usr/lib/grass83","8.3.2","grass"),epsg = 4267) 

# corresponding linkage running windows
linkGRASS(nc,c("C:/Program Files/GRASS GIS7.0.5","GRASS GIS 7.0.5","NSIS")) 
```


#### Manual version selection
Finally, some more specific examples related to interactive selection or OS-specific settings.
Manually select the `GRASS` installation and use the meuse `sf` object for spatial referencing. If you only have one installation it is directly selected. 



```{r, eval=FALSE}
linkGRASS(nc, ver_select = TRUE)
```


#### Creating a permanent gisdbase folder

Create and link a permanent `GRASS` gisdbase (folder structure) in "~/temp3" with the default mapset "PERMANENT"" and the location "project1". Use the `sf` object for all spatial attributes.


```{r, eval=FALSE}
linkGRASS(x = nc, 
                     gisdbase = "~/temp3",
                     location = "project1")   
```


#### Using a permanent gisdbase folder
Link to the permanent `GRASS` gisdbase (folder structure) in "~/temp3" with the default mapset "PERMANENT" and the location named "project1". Use the formerly referencend nc `sf` object parameter for all spatial attributes.



```{r, eval=FALSE}
linkGRASS(gisdbase = "~/temp3", location = "project1", 
                     gisdbase_exist = TRUE)   
```

#### Manual Setup of the spatial attributes
Setting up `GRASS` manually with spatial parameters of the meuse data




```{r, eval=FALSE}
 linkGRASS(spatial_params = c(178605,329714,181390,333611,
                              "+proj=sterea +lat_0=52.15616055555555 
                               +lon_0=5.38763888888889 +k=0.9999079 
                               +x_0=155000 +y_0=463000 +no_defs 
                               +a=6377397.155 +rf=299.1528128
                               +towgs84=565.4171,50.3319,465.5524,
                                -0.398957,0.343988,-1.8774,4.0725
                               +to_meter=1"),epsg = 28992) 
```

## A typical use case for the Orfeo Toolbox wrapper
link2GI supports the use of the Orfeo Toolbox with a simple list-based wrapper function. Actually, two functions parse the module and function syntax dumps and generate a command list that can be easily modified with the necessary arguments. If you have installed it in a user home directory you need to adrees this:

Usually you have to get the module list first:

```{r, eval=FALSE}
# link to the installed OTB Linux HOME directory
otblink<-link2GI::linkOTB(searchLocation = "~/apps/OTB-8.1.2-Linux64/")  


# get the list of modules from the linked version
algo<-parseOTBAlgorithms(gili = otblink)
```

Based on the modules of the current version of `OTB', you can then select the module(s) you want to use.


```{r, eval=FALSE}
## for the example we use the edge detection, 
algoKeyword <- "EdgeExtraction"

## extract the command list for the selected algorithm 
cmd <- parseOTBFunction(algo = algoKeyword, gili = otblink)

## print the current command
print(cmd)
```

Admittedly, this is a very simple and preliminary approach. Nevertheless, it will give you a valid list of all `OTB` API calls that you can easily manipulate to suit your needs. The following working example will give you an idea of how to use it.


```{r eval=FALSE}
require(link2GI)
require(terra)
require(listviewer)

otblink <- link2GI::linkOTB(searchLocation = "~/apps/OTB-8.1.2-Linux64/")
 root_folder<-tempdir()
 
fn <- system.file("ex/elev.tif", package = "terra")

## for the example we use the edge detection, 
algoKeyword<- "EdgeExtraction"

## extract the command list for the selected algorithm 
cmd<-parseOTBFunction(algo = algoKeyword, gili = otblink)

## define the mandatory arguments all other will be default
cmd$help = NULL
cmd$input_in  <- fn
cmd$filter <- "touzi"
cmd$channel <- 1
cmd$out <- file.path(root_folder,paste0("out",cmd$filter,".tif"))

## run algorithm
retStack<-runOTB(cmd,gili = otblink)

## plot filter raster on the green channel
plot(retStack)


```



## Usecases presented on the GEOSTAT August 2018

During the GEOSTAT 2018 (see https://opengeohub.org) in Prague some more complex use cases have been presented.

### Find slides and materials
- [Presentation slides](https://gisma.github.io/link2gi2018/link2gi2018.html#1)
- [Github Repository](https://github.com/gisma/link2gi2018)


### The examples

- Basic usage of `SAGA` and `OTB` calls - [SAGA & OTB basic usecase](https://github.com/gisma/link2gi2018/blob/master/R/usecases/saga-otb/useCaseSAGA-OTB.R)
- Wrapping a [GRASS GIS example](https://neteler.gitlab.io/grass-gis-analysis/02_grass-gis_ecad_analysis/) of Markus Neteler as presented on GEOSTAT 2018 - [Analysing the ECA&D climatic data - reloaded](https://github.com/gisma/link2gi2018/blob/master/R/usecases/grass/useCaseGRASS-Neteler2018.R)
- Performing a `GRASS` based cost analysis on a huge cost raster - [Beetle spread over high asia](https://github.com/gisma/link2gi2018/blob/master/R/usecases/cost-analysis/useCaseBeetle.R)
- Deriving a canopy height model using a mixed API approach - [Canopy Height Model from UAV derived point clouds](https://github.com/gisma/link2gi2018/blob/master/R/usecases/uav-pc/useCaseCHM.R)
