Skip to content

Commit

Permalink
Grass bindings improvements in SEXTANTE
Browse files Browse the repository at this point in the history
Fixed minor bugs in SAGA an GDAL merge algorithms
  • Loading branch information
volaya committed Dec 3, 2012
1 parent fb51c27 commit f1c95a9
Show file tree
Hide file tree
Showing 7 changed files with 124 additions and 100 deletions.
6 changes: 4 additions & 2 deletions python/plugins/sextante/gdal/merge.py
Expand Up @@ -60,10 +60,12 @@ def processAlgorithm(self, progress):
commands.append("-separate")
if self.getParameterValue(merge.PCT):
commands.append("-pct")
commands.append("-of")
commands.append("-o")
out = self.getOutputValue(merge.OUTPUT)
commands.append(out)
commands.append("-of")
commands.append(GdalUtils.getFormatShortNameFromFilename(out))
commands.append(self.getParameterValue(merge.INPUT).replace(";", " "))
commands.append(out)


GdalUtils.runGdal(commands, progress)
79 changes: 57 additions & 22 deletions python/plugins/sextante/grass/GrassAlgorithm.py
Expand Up @@ -53,6 +53,8 @@
from sextante.parameters.ParameterNumber import ParameterNumber

class GrassAlgorithm(GeoAlgorithm):



GRASS_REGION_EXTENT_PARAMETER = "GRASS_REGION_PARAMETER"
GRASS_REGION_CELLSIZE_PARAMETER = "GRASS_REGION_CELLSIZE_PARAMETER"
Expand All @@ -62,6 +64,8 @@ def __init__(self, descriptionfile):
self.descriptionFile = descriptionfile
self.defineCharacteristicsFromFile()
self.numExportedLayers = 0
#GRASS console output, needed to do postprocessing in case GRASS dumps results to the console
self.consoleOutput = []

def getCopy(self):
newone = GrassAlgorithm(self.descriptionFile)
Expand Down Expand Up @@ -153,8 +157,9 @@ def getDefaultCellsize(self):

if cellsize == 0:
cellsize = 1
return cellsize

return cellsize


def processAlgorithm(self, progress):
if SextanteUtils.isWindows():
path = GrassUtils.grassPath()
Expand All @@ -163,6 +168,7 @@ def processAlgorithm(self, progress):

commands = []
self.exportedLayers = {}
outputCommands = []

# if GRASS session has been created outside of this algorithm then get the list of layers loaded in GRASS
# otherwise start a new session
Expand All @@ -171,21 +177,7 @@ def processAlgorithm(self, progress):
self.exportedLayers = GrassUtils.getSessionLayers()
else:
GrassUtils.startGrassSession()


#self.calculateRegion()
region = str(self.getParameterValue(self.GRASS_REGION_EXTENT_PARAMETER))
regionCoords = region.split(",")
command = "g.region"
command += " n=" + str(regionCoords[3])
command +=" s=" + str(regionCoords[2])
command +=" e=" + str(regionCoords[1])
command +=" w=" + str(regionCoords[0])
if self.getParameterValue(self.GRASS_REGION_CELLSIZE_PARAMETER) == 0:
command +=" res=" + str(self.getDefaultCellsize())
else:
command +=" res=" + str(self.getParameterValue(self.GRASS_REGION_CELLSIZE_PARAMETER));
commands.append(command)


#1: Export layer to grass mapset
for param in self.parameters:
Expand All @@ -197,6 +189,7 @@ def processAlgorithm(self, progress):
if value in self.exportedLayers.keys():
continue
else:
self.setSessionProjection(value, commands)
commands.append(self.exportRasterLayer(value))
if isinstance(param, ParameterVector):
if param.value == None:
Expand All @@ -205,6 +198,7 @@ def processAlgorithm(self, progress):
if value in self.exportedLayers.keys():
continue
else:
self.setSessionProjection(value, commands)
commands.append(self.exportVectorLayer(value))
if isinstance(param, ParameterTable):
pass
Expand All @@ -219,14 +213,29 @@ def processAlgorithm(self, progress):
if layer in self.exportedLayers.keys():
continue
else:
self.setSessionProjection(value, commands)
commands.append(self.exportRasterLayer(layer))
elif param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
for layer in layers:
if layer in self.exportedLayers.keys():
continue
else:
self.setSessionProjection(value, commands)
commands.append(self.exportVectorLayer(layer))

region = str(self.getParameterValue(self.GRASS_REGION_EXTENT_PARAMETER))
regionCoords = region.split(",")
command = "g.region"
command += " n=" + str(regionCoords[3])
command +=" s=" + str(regionCoords[2])
command +=" e=" + str(regionCoords[1])
command +=" w=" + str(regionCoords[0])
if self.getParameterValue(self.GRASS_REGION_CELLSIZE_PARAMETER) == 0:
command +=" res=" + str(self.getDefaultCellsize())
else:
command +=" res=" + str(self.getParameterValue(self.GRASS_REGION_CELLSIZE_PARAMETER));
commands.append(command)

#2: set parameters and outputs
command = self.grassName
for param in self.parameters:
Expand Down Expand Up @@ -276,11 +285,13 @@ def processAlgorithm(self, progress):
filename = out.value
#Raster layer output: adjust region to layer before exporting
commands.append("g.region rast=" + out.name + uniqueSufix)
outputCommands.append("g.region rast=" + out.name)
command = "r.out.gdal -c createopt=\"TFW=YES,COMPRESS=LZW\""
command += " input="
command += out.name + uniqueSufix
command += " output=\"" + filename + "\""
commands.append(command)
commands.append(command)
outputCommands.append(command)

if isinstance(out, OutputVector):
filename = out.value
Expand All @@ -290,6 +301,7 @@ def processAlgorithm(self, progress):
command += " olayer=" + os.path.basename(out.value)[:-4]
command += " type=auto"
commands.append(command)
outputCommands.append("g.region rast=" + out.name)

#4 Run GRASS
loglines = []
Expand All @@ -299,14 +311,25 @@ def processAlgorithm(self, progress):
loglines.append(line)
if SextanteConfig.getSetting(GrassUtils.GRASS_LOG_COMMANDS):
SextanteLog.addToLog(SextanteLog.LOG_INFO, loglines)
GrassUtils.executeGrass(commands, progress);
self.consoleOutput = GrassUtils.executeGrass(commands, progress, outputCommands);
self.postProcessResults();
# if the session has been created outside of this algorithm, add the new GRASS layers to it
# otherwise finish the session
if existingSession:
GrassUtils.addSessionLayers(self.exportedLayers)
else:
else:
GrassUtils.endGrassSession()

def postProcessResults(self):
name = self.commandLineName().replace('.','_')
try:
module = __import__ ('sextante.grass.postproc.' + name)
except ImportError:
return
if hasattr(module, 'postProcessResults'):
func = getattr(module,'postProcessResults')
func(self)

def exportVectorLayer(self, orgFilename):
#only export to an intermediate shp if the layer is not file-based.
#We assume that almost all file formats will be supported by ogr
Expand Down Expand Up @@ -336,13 +359,25 @@ def exportVectorLayer(self, orgFilename):
return command


def setSessionProjection(self, layer, commands):
if not GrassUtils.projectionSet:
qGisLayer = QGisLayers.getObjectFromUri(layer)
if qGisLayer:
proj4 = str(qGisLayer.crs().toProj4())
command = "g.proj"
command +=" -c"
command +=" proj4=\""+proj4+"\""
commands.append(command)
GrassUtils.projectionSet = True


def exportRasterLayer(self, layer):
destFilename = self.getTempFilename()
self.exportedLayers[layer]= destFilename
command = "r.in.gdal"
command = "r.external"
command +=" input=\"" + layer + "\""
command +=" band=1"
command +=" out=" + destFilename;
command +=" output=" + destFilename;
command +=" --overwrite -o"
return command

Expand Down
2 changes: 0 additions & 2 deletions python/plugins/sextante/grass/GrassAlgorithmProvider.py
Expand Up @@ -47,15 +47,13 @@ def initializeSettings(self):
SextanteConfig.addSetting(Setting(self.getDescription(), GrassUtils.GRASS_WIN_SHELL, "Msys folder", GrassUtils.grassWinShell()))
SextanteConfig.addSetting(Setting(self.getDescription(), GrassUtils.GRASS_LOG_COMMANDS, "Log execution commands", False))
SextanteConfig.addSetting(Setting(self.getDescription(), GrassUtils.GRASS_LOG_CONSOLE, "Log console output", False))
SextanteConfig.addSetting(Setting(self.getDescription(), GrassUtils.GRASS_LATLON, "Coordinates are lat/lon", False))
SextanteConfig.addSetting(Setting(self.getDescription(), GrassUtils.GRASS_HELP_FOLDER, "GRASS help folder", GrassUtils.grassHelpPath()))

def unload(self):
AlgorithmProvider.unload(self)
if SextanteUtils.isWindows() or SextanteUtils.isMac():
SextanteConfig.removeSetting(GrassUtils.GRASS_FOLDER)
SextanteConfig.removeSetting(GrassUtils.GRASS_WIN_SHELL)
SextanteConfig.removeSetting(GrassUtils.GRASS_LATLON)
SextanteConfig.removeSetting(GrassUtils.GRASS_HELP_FOLDER)
SextanteConfig.removeSetting(GrassUtils.GRASS_LOG_COMMANDS)
SextanteConfig.removeSetting(GrassUtils.GRASS_LOG_CONSOLE)
Expand Down

0 comments on commit f1c95a9

Please sign in to comment.