User Tools

Site Tools


r:r-tutorials:saga-grass-plus

Setup SAGA, GRASS & more

It is a bit tricky to automate the initialization of the GIS bindings. This depends a lot on the actual preferences and state of the Operation System (OS). The function initEnvironGIS does both. It initialize GRASS, QGIs and GDAL and the R packages on the one hand on the other it provides all necessary arguments as provided by an separate control file that is parsed by the function iniParse. The usage of an control file is somehow outdated nevertheless we first will setup this parsing function.

Function iniParse

You may use this function for several purposes. You learn how basic parsing and string manipulation works and finally you can use it to get hold of your configuration parameters as stored in an Windows like INI file.

iniParse.R
#'@name iniParse
#'@title Parse an Windows like ini file to get the the entries
#'@description  Any Windows type ini file will be parsed so that the sections and the variables may be used within R for all kind of settings.
#'
#'@usage iniParse(fname)
#'@author Gabor Grothendieck <ggrothendieck at gmail.com>,  
#' \cr
#' \emph{Maintainer:} Chris Reudenbach \email{giswerk@@gis-ma.org}
#'
#'@references \url{http://moc.environmentalinformatics-marburg.de/doku.php?id=courses:msc:advanced-gis:description}
#'            \url{https://stat.ethz.ch/pipermail/r-help/2007-June/134115.html}
#' 
#'@param fname file name of the ASCII INI file
#'
#'@return iniParse returns a list ordered by sections variablenames and values 
#'
#'@export iniParse
#'@examples   
#'#### Example to parse an windows type of ini file
#'#### create a list for each ini section containing the variables and params
#'       
#' ini.example=system.file("demo.ini", package="Rpeak")
#' iniParse(ini.example)
 
 
iniParse <- function(fname)
{
  ini.file <- file(fname)
  Lines  <- readLines(ini.file)
  close(ini.file)
 
  Lines <- chartr("[]", "==", Lines)  # change section headers
 
  ini.file <- textConnection(Lines)
  d <- read.table(ini.file, as.is = TRUE, sep = "=", fill = TRUE)
  close(ini.file)
 
  L <- d$V1 == ""                    # location of section breaks
  d <- subset(transform(d, V3 = V2[which(L)[cumsum(L)]])[1:3],
              V1 != "")
 
  to.parse  <- trim(paste("ini.list$", trim(d$V3), "$",  trim(d$V1), " <- '",
                     trim(d$V2), "'", sep=""))
 
  ini.list <- list()
  eval(parse(text=to.parse))
 
  return(ini.list)
}

Using it for your GIS projecta

Again I have to admit that the following solution is somehow old fashioned and not very R like. Nevertheless it can be very useful if you need to read parameters from Windows generated INI files or if you like from your self generated INI files. So (just because I like it ;)) we store our project control data in an Windows like INI file. However you can also easily source a normal R file doing so if you want. For editing and writing comments the INI formating seems to be much more comfortable because the parser just ignores all stuff except the important ones. Using the ini you have to address [Section] using square brackets and variables by assigning them with an equality sign variable=xyzcontent. The whole bunch of GIS settings we are using up to now is looking like this:

control.ini
[Pathes]                                   # NOTE if the pathes are not existing they will be created
workhome=/home/MOC/GISPROJECT              # project root directory
runtimedata=run                            # project runtime directory
rawdata=./inst                             # project additional data directory
src=./src                                  # project source directory
 
[Projection]
targetepsg=31254                           # epsg code of DEM data 
targetproj4=+proj=tmerc +lat_0=0 +lon_0=10.33333333333333 +k=1 +x_0=0 +y_0=-5000000 +ellps=bessel +towgs84=577.326,90.129,463.919,5.137,1.474,5.297,2.4232 +units=m +no_defs'  
latlonproj4='+proj=longlat +datum=WGS84 +no_defs
 
[SysPath]                                  # the pathes for the used SAGA and GRASS  binaries ( NOTE they are correct for the WinGIS2go bundle and the Linux distro)
wossaga=C:/MyApps/GIS_ToGo/QGIS_portable_Chugiak_24_32bit/QGIS/apps/saga
wsagamodules=C:/MyApps/GIS_ToGo/QGIS_portable_Chugiak_24_32bit/QGIS/apps/saga/modules
wgrassgisbase=C:/MyApps/GIS_ToGo/GRASSGIS643/bin
lossaga=/home/creu/SAGA-2.1.0-fixed/initial/bin
lsagamodules=/home/creu/SAGA-2.1.0-fixed/initial/lib/saga
lgrassgisbase=/usr/lib/grass64

It is structured and easy to maintain. For your convenience you can use the initParse function to read it. Put the function into your fun directory (named after the same conventions as the others) and you can use it for retrieving an nice R list:

List of 7
 $ Pathes    :List of 4
  ..$ workhome   : chr "/home/creu/MOC/aGIS/perfectPeak"
  ..$ runtimedata: chr "run"
  ..$ rawdata    : chr "./inst"
  ..$ src        : chr "./src"
 $ Projection:List of 3
  ..$ targetepsg : chr "31254             "
  ..$ targetproj4: chr "+proj=tmerc +lat_0=0 +lon_0=10.33333333333333 +k=1 +x_0=0 +y_0=-5000000 +ellps=bessel +towgs84=577.326,90.129,463.919,5.137,1.4"| __truncated__
  ..$ latlonproj4: chr "+proj=longlat +datum=WGS84 +no_defs"
 $ SysPath   :List of 6
  ..$ wossaga      : chr "C:/MyApps/GIS_ToGo/QGIS_portable_Chugiak_24_32bit/QGIS/apps/saga"
  ..$ wsagamodules : chr "C:/MyApps/GIS_ToGo/QGIS_portable_Chugiak_24_32bit/QGIS/apps/saga/modules"
  ..$ wgrassgisbase: chr "C:/MyApps/GIS_ToGo/GRASSGIS643/bin"
  ..$ lossaga      : chr "/home/MOC/SAGA-2.1.0-fixed/initial/bin"
  ..$ lsagamodules : chr "/home/MOC/SAGA-2.1.0-fixed/initial/lib/saga"
  ..$ lgrassgisbase: chr "/usr/lib/grass64"

Now setting up the GIS bindings initEnvironGIS

Please note: The initialization of GRASS will still show you an error/warning but nevertheless it should work. For all issues dealing with the projection parameters please refer to Projection adventures.

FIXME Still has to be tested for Windows 8 sorry so far.

initEnvironGIS.R
#'@name initEnvironGIS
#'
#'@title Function that initializes RSAGA, GRASS GDAL and the R packages 
#'
#'@description Function that initializes environment pathes, SAGA, GRASS and GDAL support (and the bindings to the corresponding R packages and the R packages *NOTE* you probably have to customize some settings ini file
#' 
#'@usage initEnvironGIS(ini.file)
#'
#'@param ini.file name of the session ini.file
#'@param DEMfname name of used raster DEM (GDAL format)
#'
#'@author Chris Reudenbach 
#'
#'
#'@return initEnvironGIS initializes the usage of the GIS packages and other utilities
#'@export initEnvironGIS
#'
#'@examples   
#'#### Example to initialize the enviroment and GIS bindings for use with R
#'#### uses the ini list from an ini file
#'       
#' ini.example=system.file("demo.ini", package="perfectPeak")
#' dem.example=system.file("test.asc", package="perfectPeak")
#' initEnvironGIS(ini.example,dem.example)
#' gmeta6()
#' 
 
initEnvironGIS <- function(fname,DEMfname){
 
  # check for packages and if necessary install libs 
  libraries<-c("downloader","sp","raster","maptools","osmar",
               "RSAGA","rgeos","gdata","Matrix","igraph",
               "rgdal","gdistance", "spgrass6", "gdalUtils")
 
  # Install CRAN packages (if not already installed)
  inst <- libraries %in% installed.packages()
  if(length(libraries[!inst]) > 0) install.packages(libraries[!inst])
 
  # Load packages into session 
  lapply(libraries, require, character.only=TRUE)
 
  # get environment
  ini<-iniParse(fname)  
 
  # (R) assign local vars for working folder 
  root.dir <- ini$Pathes$workhome               # project folder 
  working.dir <- ini$Pathes$runtimedata         # working folder 
 
  ### assign correct projection information
  # To derive the correct proj.4 string for Austria MGI (EPSG:31254) is very NOT straightforward
  # please refer to: http://moc.environmentalinformatics-marburg.de/doku.php?id=courses:msc:advanced-gis:code-examples:ag-ce-09-01
  # taget EPSG code
  epsg.code<-ini$Projection$targetepsg
 
  # target projection (actually the projection of the DEM)
  target.proj4<-ini$Projection$targetproj4
 
  # we will also need the  basic latlon wgs84 proj4 string
  latlon.proj4<-as.character(CRS("+init=epsg:4326")) 
 
  ### now starting the setup of the packages bindings
 
  ## (gdalUtils) check for a valid GDAL binary installation on your system
  gdal_setInstallation()
  valid.install<-!is.null(getOption("gdalUtils_gdalPath"))
  if (!valid.install){stop('no valid GDAL/OGR found')} else{print('gdalUtils status is ok')}
 
  #--- set environment variables for RSAGA and GRASS
  # (spgrass6) define GRASS variables
  grass.epsg.code<- as.numeric(epsg.code)  # grass needs the projection numeric
  grass.loc<- paste0('loc',epsg.code)      # define corresponding folder name
  grass.mapset<- 'PERMANENT'                               # NOTE PERMANENT" is the default one and it has to be in upper cases
 
 
  # (R) set pathes  of SAGA/GRASS modules and binaries depending on OS
  if(Sys.info()["sysname"] == "Windows"){
    os.saga.path<-ini$SysPath$wossaga
    saga.modules<-ini$SysPath$wsagamodules
    grass.gis.base<-ini$SysPath$wgrassgisbase
  }else if (Sys.info()["sysname"] == "Linux"){
    os.saga.path<-ini$SysPath$lossaga
    saga.modules<-ini$SysPath$lsagamodules
    grass.gis.base<-ini$SysPath$lgrassgisbase
  }
  if (!file.exists(file.path(root.dir, working.dir))){
    dir.create(file.path(root.dir, 'run'),recursive = TRUE)
    dir.create(file.path(root.dir, 'run',grass.loc),recursive = TRUE)
    dir.create(file.path(root.dir, 'run',grass.loc,grass.mapset),recursive = TRUE)
 
  }  
  # (R) set R working directory
  setwd(file.path(root.dir, working.dir))
  getwd()
  # (RSAGA) set SAGA environment 
  myenv=rsaga.env(check.libpath=FALSE,
                  check.SAGA=FALSE,
                  workspace=file.path(root.dir, working.dir),
                  os.default.path=os.saga.path,
                  modules=saga.modules)
 
  # Create a new grass location with epsg from the data import dataset as a
  # subfolder of the working folder
  initGRASS(gisBase=grass.gis.base,  home=tempdir(),
            gisDbase=file.path(root.dir, working.dir),
            location=grass.loc,
            override=TRUE,
            ifelse(Sys.info()["sysname"] == "Windows", use_g.dirseps.exe=FALSE, use_g.dirseps.exe=TRUE))
 
  execGRASS("g.gisenv", parameters=list(set=paste("'MAPSET=", grass.mapset,"'", sep="")))
 
  # get extent BE CAREFULL this works only if the INPUT ASCII FILE CONTAINS TRULY THIS Projection
  # (1) import data in GRASS
  execGRASS('r.in.gdal',  flags=c('o',"overwrite"), input=DEMfname,  output='rastgrass', band=1)
  # (2) use the derived informations to complete the location settings
 
  execGRASS('g.region',rast="rastgrass")
  execGRASS('g.proj', flags=c('c') ,  epsg=grass.epsg.code)
 
  # provide myenv and parameterlist for common use
  result=list(ini,myenv)
  names(result)=c('ini','myenv')
  return (result)  
}
r/r-tutorials/saga-grass-plus.txt · Last modified: 2018/12/23 19:46 (external edit)