Skip to content
Permalink
Browse files
[sextante] added preprocessing of input params for saga algorithms
  • Loading branch information
volaya committed Jul 23, 2013
1 parent ab98569 commit c7eb99bae1e86e19a8e120b65a213aedea6fc924
@@ -47,13 +47,9 @@ class FieldsCalculator(GeoAlgorithm):
FORMULA = "FORMULA"
OUTPUT_LAYER = "OUTPUT_LAYER"

TYPE_NAMES = ["Integer", "Float", "String"]
TYPES = [QVariant.Int, QVariant.Double, QVariant.String]
TYPE_NAMES = ["Float", "Integer", "String", "Boolean"]
TYPES = [QVariant.Double, QVariant.Int, QVariant.String. QVariant.Bool]

#===========================================================================
# def getIcon(self):
# return QtGui.QIcon(os.path.dirname(__file__) + "/../images/qgis.png")
#===========================================================================

def defineCharacteristics(self):
self.name = "Field calculator"
@@ -62,7 +58,7 @@ def defineCharacteristics(self):
self.addParameter(ParameterString(self.FIELD_NAME, "Result field name"))
self.addParameter(ParameterSelection(self.FIELD_TYPE, "Field type", self.TYPE_NAMES))
self.addParameter(ParameterNumber(self.FIELD_LENGTH, "Field length", 1, 255, 10))
self.addParameter(ParameterNumber(self.FIELD_PRECISION, "Field precision", 0, 10, 0))
self.addParameter(ParameterNumber(self.FIELD_PRECISION, "Field precision", 0, 10, 5))
self.addParameter(ParameterString(self.FORMULA, "Formula"))
self.addOutput(OutputVector(self.OUTPUT_LAYER, "Output layer"))

@@ -85,17 +81,20 @@ def processAlgorithm(self, progress):
nFeat = provider.featureCount()
nElement = 0
features = QGisLayers.features(layer)

fieldnames = [field.name() for field in provider.fields()]
fieldnames.sort(key=len, reverse=False)
fieldidx = [fieldnames.index(field.name()) for field in provider.fields()]
print fieldidx
for inFeat in features:
progress.setPercentage(int((100 * nElement) / nFeat))
attrs = inFeat.attributes()
expression = formula
k = 0
for attr in attrs:
expression = expression.replace(unicode(fields[k].name()), unicode(attr))
k += 1
try:
expression = formula
for idx in fieldidx:
expression = expression.replace(unicode(fields[idx].name()), unicode(attrs[idx]))
try:
result = eval(expression)
except Exception:
except Exception:
result = None
#raise GeoAlgorithmExecutionException("Problem evaluation formula: Wrong field values or formula")
nElement += 1
@@ -1,5 +1,7 @@
FILE(GLOB PY_FILES *.py)
FILE(GLOB DESCR_FILES description/*.txt)

ADD_SUBDIRECTORY(ext)

PLUGIN_INSTALL(sextante saga ${PY_FILES})
PLUGIN_INSTALL(sextante saga/description ${DESCR_FILES})
@@ -16,6 +16,7 @@
* *
***************************************************************************
"""
import importlib

__author__ = 'Victor Olaya'
__date__ = 'August 2012'
@@ -180,6 +181,8 @@ def processAlgorithm(self, progress):
raise GeoAlgorithmExecutionException("SAGA folder is not configured.\nPlease configure it before running SAGA algorithms.")
commands = list()
self.exportedLayers = {}

self.preProcessInputs()

#1: Export rasters to sgrd and vectors to shp
# Tables must be in dbf format. We check that.
@@ -306,8 +309,9 @@ def processAlgorithm(self, progress):
else:
commands.append("libio_gdal 1 -GRIDS \"" + filename2 + "\" -FORMAT 1 -TYPE 0 -FILE \"" + filename + "\"");


#4 Run SAGA
commands = self.editCommands(commands)
SagaUtils.createSagaBatchJobFileFromSagaCommands(commands)
loglines = []
loglines.append("SAGA execution commands")
@@ -319,6 +323,28 @@ def processAlgorithm(self, progress):
SagaUtils.executeSaga(progress);


def preProcessInputs(self):
name = self.commandLineName().replace('.','_')[len('saga:'):]
try:
module = importlib.import_module('sextante.grass.ext.' + name)
except ImportError:
return
if hasattr(module, 'preProcessInputs'):
func = getattr(module,'preProcessInputs')
func(self)

def editCommands(self, commands):
name = self.commandLineName()[len('saga:'):]
try:
module = importlib.import_module('sextante.grass.ext.' + name)
except ImportError:
return commands
if hasattr(module, 'editCommands'):
func = getattr(module,'editCommands')
return func(commands)
else:
return commands

def getOutputCellsize(self):
'''tries to guess the cellsize of the output, searching for a parameter with an appropriate name for it'''
cellsize = 0;
@@ -11,4 +11,4 @@ ParameterSelection|RELATIVE_PROB|Probability Reference|[0] absolute;[1] relative
ParameterNumber|THRESHOLD_ANGLE|Spectral Angle Threshold (Degree)|None|None|0.0
OutputTable|CLASS_INFO|Class Information
OutputRaster|CLASSES|Classification
OutputRaster|QUALITY|Quality
OutputRaster|QUALITY|Quality
@@ -0,0 +1,3 @@
FILE(GLOB PY_FILES *.py)

PLUGIN_INSTALL(sextante saga/ext ${PY_FILES})
Empty file.
@@ -0,0 +1,31 @@
# -*- coding: utf-8 -*-

"""
***************************************************************************
supervisedclassification.py
---------------------
Date : July 2013
Copyright : (C) 2013 by Victor Olaya
Email : volayaf at gmail dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
from sextante.tests.TestData import table
__author__ = 'Victor Olaya'
__date__ = 'July 2013'
__copyright__ = '(C) 2013, Victor Olaya'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'


def editCommands(commands):
commands[-1] = commands[-1] + " -STATS" + table()
return commands


0 comments on commit c7eb99b

Please sign in to comment.