Skip to content
Permalink
Browse files
Added mechanism for better handling selected features in algorithms
Implemented it in fTools Simplify algorithm
  • Loading branch information
volaya committed Dec 23, 2012
1 parent 5c64c10 commit 8761cf2118ee6ee8066884ea5a3c9725cf5677d7
@@ -62,7 +62,7 @@ def processAlgorithm(self, progress):
vproviderA.select( allAttrsA )
vproviderB = vlayerB.dataProvider()
allAttrsB = vproviderB.attributeIndexes()
vproviderB.select( allAttrsB )
vproviderB.select(allAttrsB )
# check for crs compatibility
crsA = vproviderA.crs()
crsB = vproviderB.crs()
@@ -140,7 +140,7 @@ def processAlgorithm(self, progress):
outFeat.setAttributeMap( ftools_utils.combineVectorAttributes( atMapA, atMapB ) )
writer.addFeature( outFeat )
except:
EATURE_EXCEPT = False
FEATURE_EXCEPT = False
continue
except:
GEOS_EXCEPT = False
@@ -57,14 +57,12 @@ def defineCharacteristics(self):
self.group = "Vector geometry tools"

self.addParameter(ParameterVector(self.INPUT, "Input layer", ParameterVector.VECTOR_TYPE_ANY))
self.addParameter(ParameterNumber(self.TOLERANCE, "Tolerance", 0.0, 10000000.0, 1.0))
self.addParameter(ParameterBoolean(self.USE_SELECTION, "Use only selected features", False))
self.addParameter(ParameterNumber(self.TOLERANCE, "Tolerance", 0.0, 10000000.0, 1.0))

self.addOutput(OutputVector(self.OUTPUT, "Simplified layer"))

def processAlgorithm(self, progress):
layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT))
useSelection = self.getParameterValue(self.USE_SELECTION)
layer = QGisLayers.getObjectFromUri(self.getParameterValue(self.INPUT))
tolerance =self.getParameterValue(self.TOLERANCE)

pointsBefore = 0
@@ -76,43 +74,22 @@ def processAlgorithm(self, progress):
writer = self.getOutputFromName(self.OUTPUT).getVectorWriter(layer.pendingFields(),
layer.wkbType(), provider.crs())

current = 0
if useSelection:
selection = layer.selectedFeatures()
total = 100.0 / float(len(selection))
for f in selection:
featGeometry = QgsGeometry(f.geometry())
attrMap = f.attributeMap()

pointsBefore += self.geomVertexCount(featGeometry)
newGeometry = featGeometry.simplify(tolerance)
pointsAfter += self.geomVertexCount(newGeometry)

feature = QgsFeature()
feature.setGeometry(newGeometry)
feature.setAttributeMap(attrMap)
writer.addFeature(feature)
current += 1
progress.setPercentage(int(current * total))
else:
total = 100.0 / float(provider.featureCount())
f = QgsFeature()
while layer.nextFeature(f):
featGeometry = QgsGeometry(f.geometry())
attrMap = f.attributeMap()

pointsBefore += self.geomVertexCount(featGeometry)
newGeometry = featGeometry.simplify(tolerance)
pointsAfter += self.geomVertexCount(newGeometry)

feature = QgsFeature()
feature.setGeometry(newGeometry)
feature.setAttributeMap(attrMap)
writer.addFeature(feature)

current += 1
progress.setPercentage(int(current * total))

current = 0
selection = QGisLayers.features(layer)
total = 100.0 / float(len(selection))
for f in selection:
featGeometry = QgsGeometry(f.geometry())
attrMap = f.attributeMap()
pointsBefore += self.geomVertexCount(featGeometry)
newGeometry = featGeometry.simplify(tolerance)
pointsAfter += self.geomVertexCount(newGeometry)
feature = QgsFeature()
feature.setGeometry(newGeometry)
feature.setAttributeMap(attrMap)
writer.addFeature(feature)
current += 1
progress.setPercentage(int(current * total))

del writer

SextanteLog.addToLog(SextanteLog.LOG_INFO, "Simplify: Input geometries have been simplified from"
@@ -52,11 +52,12 @@ def getRasterLayers():
def getVectorLayers(shapetype=-1):
layers = QGisLayers.iface.legendInterface().layers()
vector = list()
for layer in layers:
if layer.type() == layer.VectorLayer:
if shapetype == QGisLayers.ALL_TYPES or layer.geometryType() == shapetype:
uri = unicode(layer.source())
for layer in layers:
if layer.type() == layer.VectorLayer:
if shapetype == QGisLayers.ALL_TYPES or layer.geometryType() == shapetype:
uri = unicode(layer.source())
if not uri.endswith("csv") and not uri.endswith("dbf"):

vector.append(layer)
return vector

@@ -169,6 +170,53 @@ def getObjectFromUri(uri, forceLoad = True):
else:
return None

@staticmethod
def features(layer):
'''this returns an iterator over features in a vector layer, considering the
selection that might exist in the layer, and the SEXTANTE configuration that
indicates whether to use only selected feature or all of them.
This should be used by algorithms instead of calling the QGis API directly,
to ensure a consistent behaviour across algorithms'''
return Features(layer)


class Features():

def __init__(self, layer):
self.layer = layer
self.selection = False;
if SextanteConfig.getSetting(SextanteConfig.USE_SELECTED):
self.selected = layer.selectedFeatures()
if len(self.selected) > 0:
self.selection = True
self.idx = 0;

def __iter__(self):
return self

def next(self):
if self.selection:
if self.idx < len(self.selected):
feature = self.selected[self.idx]
self.idx += 1
return feature
else:
raise StopIteration()
else:
f = QgsFeature()
if self.layer.dataProvider().nextFeature(f):
return f
else:
raise StopIteration()

def __len__(self):
if self.selection:
return int(self.layer.selectedFeatureCount())
else:
return int(self.layer.dataProvider().featureCount())






@@ -54,7 +54,7 @@ def initialize():
SextanteConfig.addSetting(Setting("General", SextanteConfig.USE_THREADS, "Run algorithms in a new thread (still unstable)", False))
SextanteConfig.addSetting(Setting("General", SextanteConfig.SHOW_DEBUG_IN_DIALOG, "Show debug information and commands executed in the execution dialog's Log panel (threaded execution only)", True))
SextanteConfig.addSetting(Setting("General", SextanteConfig.KEEP_DIALOG_OPEN, "Keep dialog open after running an algorithm", False))
SextanteConfig.addSetting(Setting("General", SextanteConfig.USE_SELECTED, "Use only selected features in external applications", True))
SextanteConfig.addSetting(Setting("General", SextanteConfig.USE_SELECTED, "Use only selected features", True))
SextanteConfig.addSetting(Setting("General", SextanteConfig.TABLE_LIKE_PARAM_PANEL, "Show table-like parameter panels", False))
SextanteConfig.addSetting(Setting("General", SextanteConfig.USE_FILENAME_AS_LAYER_NAME, "Use filename as layer name", True))
SextanteConfig.addSetting(Setting("General", SextanteConfig.SHOW_RECENT_ALGORITHMS, "Show recently executed algorithms", True))
@@ -0,0 +1,36 @@
# -*- coding: utf-8 -*-

"""
***************************************************************************
r_describe.py
---------------------
Date : December 2012
Copyright : (C) 2012 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. *
* *
***************************************************************************
"""
__author__ = 'Victor Olaya'
__date__ = 'December 2012'
__copyright__ = '(C) 2012, Victor Olaya'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'

def postProcessResults(alg):
htmlFile = alg.getOutputFromName('html').value
found = False
f = open(htmlFile, "w")
f.write("<h2>r.describe</h2>\n")
for line in alg.consoleOutput:
if found and not line.strip().endswith('exit'):
f.write(line + "<br>\n")
if 'r.describe' in line:
found = True
f.close()

@@ -175,8 +175,7 @@ def processAlgorithm(self, progress):
if SextanteUtils.isWindows():
path = SagaUtils.sagaPath()
if path == "":
raise GeoAlgorithmExecutionException("SAGA folder is not configured.\nPlease configure it before running SAGA algorithms.")
#useSelection = SextanteConfig.getSetting(SagaUtils.SAGA_USE_SELECTED)
raise GeoAlgorithmExecutionException("SAGA folder is not configured.\nPlease configure it before running SAGA algorithms.")
commands = list()
self.exportedLayers = {}

0 comments on commit 8761cf2

Please sign in to comment.