Skip to content

Commit

Permalink
added addfield and fieldcalculator algorithms
Browse files Browse the repository at this point in the history
git-svn-id: http://sextante.googlecode.com/svn/trunk/soft/bindings/qgis-plugin@150 881b9c09-3ef8-f3c2-ec3d-21d735c97f4d
  • Loading branch information
volayaf committed Apr 25, 2012
1 parent 36db53a commit 0928180
Show file tree
Hide file tree
Showing 8 changed files with 157 additions and 7 deletions.
43 changes: 43 additions & 0 deletions src/sextante/algs/AddTableField.py
@@ -0,0 +1,43 @@
from sextante.core.GeoAlgorithm import GeoAlgorithm
from sextante.outputs.OutputVector import OutputVector
from sextante.parameters.ParameterVector import ParameterVector
from qgis.core import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from sextante.parameters.ParameterString import ParameterString
from sextante.parameters.ParameterSelection import ParameterSelection
from sextante.core.QGisLayers import QGisLayers
import os
from PyQt4 import QtGui


class AddTableField(GeoAlgorithm):

OUTPUT_LAYER = "OUTPUT_LAYER"
INPUT_LAYER = "INPUT_LAYER"
FIELD_NAME = "FIELD_NAME"
FIELD_TYPE = "FIELD_TYPE"
TYPE_NAMES = ["Integer", "Float", "String"]
TYPES = [QVariant.Int, QVariant.Double, QVariant.String]

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

def defineCharacteristics(self):
self.name = "Add field to attributes table"
self.group = "Algorithms for vector layers"
self.addParameter(ParameterVector(self.INPUT_LAYER, "Input layer", ParameterVector.VECTOR_TYPE_ANY, False))
self.addParameter(ParameterString(self.FIELD_NAME, "Field name"))
self.addParameter(ParameterSelection(self.FIELD_TYPE, "Field type", self.TYPE_NAMES))
self.addOutput(OutputVector(self.OUTPUT_LAYER, "Output layer", True))

def processAlgorithm(self, progress):
inputFilename = self.getParameterValue(self.INPUT_LAYER)
layer = QGisLayers.getObjectFromUri(inputFilename)
caps = layer.dataProvider().capabilities()
if caps & QgsVectorDataProvider.AddAttributes:
fieldName = self.getParameterValue(self.FIELD_NAME)
fieldType = self.TYPES[self.getParameterValue(self.FIELD_TYPE)]
layer.dataProvider().addAttributes([QgsField(fieldName, fieldType)])


61 changes: 61 additions & 0 deletions src/sextante/algs/FieldsCalculator.py
@@ -0,0 +1,61 @@
from sextante.core.GeoAlgorithm import GeoAlgorithm
from sextante.outputs.OutputVector import OutputVector
from sextante.parameters.ParameterVector import ParameterVector
from qgis.core import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from sextante.parameters.ParameterString import ParameterString
from sextante.parameters.ParameterSelection import ParameterSelection
from sextante.core.QGisLayers import QGisLayers
import os
from PyQt4 import QtGui
from sextante.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException


class FieldsCalculator(GeoAlgorithm):

INPUT_LAYER = "INPUT_LAYER"
FIELD_NAME = "FIELD_NAME"
FORMULA = "FORMULA"
OUTPUT_LAYER ="OUTPUT_LAYER"

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

def defineCharacteristics(self):
self.name = "Field calculator"
self.group = "Algorithms for vector layers"
self.addParameter(ParameterVector(self.INPUT_LAYER, "Input layer", ParameterVector.VECTOR_TYPE_ANY, False))
self.addParameter(ParameterString(self.FIELD_NAME, "Result field name"))
self.addParameter(ParameterString(self.FORMULA, "Formula"))
self.addOutput(OutputVector(self.OUTPUT_LAYER, "Output layer", True))

def processAlgorithm(self, progress):
inputFilename = self.getParameterValue(self.INPUT_LAYER)
formula = self.getParameterValue(self.FORMULA)
layer = QGisLayers.getObjectFromUri(inputFilename)
provider = layer.dataProvider()
caps = provider.capabilities()
if caps & QgsVectorDataProvider.AddAttributes:
fieldName = self.getParameterValue(self.FIELD_NAME)
layer.dataProvider().addAttributes([QgsField(fieldName, QVariant.Double)])
feat = QgsFeature()
allAttrs = provider.attributeIndexes()
provider.select(allAttrs)
fields = provider.fields()
while provider.nextFeature(feat):
attrs = feat.attributeMap()
expression = formula
for (k,attr) in attrs.iteritems():
expression = expression.replace(str(fields[k].name()), str(attr.toString()))
try:
result = eval(expression)
except Exception:
raise GeoAlgorithmExecutionException("Problem evaluation formula: Wrong field values or formula")
attrs[len(attrs) - 1] = QVariant(result)
provider.changeAttributeValues({feat.id() : attrs})


def checkParameterValuesBeforeExecuting(self):
##TODO check that formula is correct and fields exist

31 changes: 31 additions & 0 deletions src/sextante/algs/SextanteAlgorithmProvider.py
@@ -0,0 +1,31 @@
from sextante.core.AlgorithmProvider import AlgorithmProvider
from sextante.algs.AddTableField import AddTableField
from PyQt4 import QtGui
import os
from sextante.algs.FieldsCalculator import FieldsCalculator

class SextanteAlgorithmProvider(AlgorithmProvider):

def __init__(self):
AlgorithmProvider.__init__(self)
self.alglist = [AddTableField(), FieldsCalculator()]

def initializeSettings(self):
AlgorithmProvider.initializeSettings(self)


def unload(self):
AlgorithmProvider.unload(self)


def getName(self):
return "sextante"

def getDescription(self):
return "SEXTANTE geoalgorithms"

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

def _loadAlgorithms(self):
self.algs = self.alglist
Empty file added src/sextante/algs/__init__.py
Empty file.
10 changes: 9 additions & 1 deletion src/sextante/core/GeoAlgorithm.py
Expand Up @@ -84,6 +84,13 @@ def checkBeforeOpeningParametersDialog(self):
Note that this check should also be done in the processAlgorithm method,
since algorithms can be called without opening the parameters dialog.'''
return None

def checkParameterValuesBeforeExecuting(self):
'''If there is any check to do before launching the execution of the algorithm,
it should be done here. If values are not correct, a message should be returned
explaining the problem
This check is called from the parameters dialog, and also when calling from the console'''
return None
#=========================================================

def execute(self, progress):
Expand Down Expand Up @@ -237,6 +244,7 @@ def getAsCommand(self):
for param in self.parameters:
s+=param.getValueAsCommandLineParameter() + ","
for out in self.outputs:
s+=out.getValueAsCommandLineParameter() + ","
if not out.hidden:
s+=out.getValueAsCommandLineParameter() + ","
s= s[:-1] + ")"
return s
2 changes: 2 additions & 0 deletions src/sextante/core/Sextante.py
Expand Up @@ -21,6 +21,7 @@
from sextante.otb.OTBAlgorithmProvider import OTBAlgorithmProvider
from sextante.lastools.LasToolsAlgorithmProvider import LasToolsAlgorithmProvider
from sextante.core.SextanteUtils import SextanteUtils
from sextante.algs.SextanteAlgorithmProvider import SextanteAlgorithmProvider

class Sextante:

Expand Down Expand Up @@ -79,6 +80,7 @@ def setInterface(iface):
@staticmethod
def initialize():
#add the basic providers
Sextante.addProvider(SextanteAlgorithmProvider())
Sextante.addProvider(MMQGISAlgorithmProvider())
Sextante.addProvider(FToolsAlgorithmProvider())
Sextante.addProvider(ModelerOnlyAlgorithmProvider())
Expand Down
16 changes: 11 additions & 5 deletions src/sextante/gui/ParametersDialog.py
Expand Up @@ -43,8 +43,6 @@ class Ui_ParametersDialog(object):
def setupUi(self, dialog, alg):
self.alg = alg
self.dialog = dialog
#self.valueItems = {}
#self.dependentItems = {}
dialog.resize(650, 450)
self.buttonBox = QtGui.QDialogButtonBox()
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
Expand Down Expand Up @@ -134,7 +132,12 @@ def setParamValue(self, param, widget):

def accept(self):
try:
keepOpen = SextanteConfig.getSetting(SextanteConfig.KEEP_DIALOG_OPEN)
if self.setParamValues():
msg = self.alg.checkParameterValuesBeforeExecuting()
if msg:
QMessageBox.critical(self.dialog, "Unable to execute algorithm", msg)
return
keepOpen = SextanteConfig.getSetting(SextanteConfig.KEEP_DIALOG_OPEN)
self.buttonBox.button(QtGui.QDialogButtonBox.Ok).setEnabled(False)
buttons = self.paramTable.iterateButtons
Expand Down Expand Up @@ -174,12 +177,15 @@ def accept(self):
QApplication.restoreOverrideCursor()
QMessageBox.critical(self, "Error",e.msg)
SextanteLog.addToLog(SextanteLog.LOG_ERROR, e.msg)
self.dialog.executed = False
self.dialog.close()
if not keepOpen:
self.dialog.close()
else:
self.progressLabel.setText("")
self.progress.setValue(0)
self.buttonBox.button(QtGui.QDialogButtonBox.Ok).setEnabled(True)


def reject(self):
#self.dialog.executed = False
self.dialog.close()

def setPercentage(self, i):
Expand Down
1 change: 0 additions & 1 deletion src/sextante/otb/OTBAlgorithmProvider.py
@@ -1,7 +1,6 @@
import os
from PyQt4.QtGui import *
from sextante.core.AlgorithmProvider import AlgorithmProvider
from sextante.core.SextanteUtils import SextanteUtils
from sextante.core.SextanteConfig import SextanteConfig, Setting
from sextante.otb.OTBUtils import OTBUtils
from sextante.otb.OTBAlgorithm import OTBAlgorithm
Expand Down

0 comments on commit 0928180

Please sign in to comment.