mirror of
https://github.com/qgis/QGIS.git
synced 2025-10-16 00:05:45 -04:00
[processing] added extract algorithm as alternative to selection algorithms that can be used in the modeler
This commit is contained in:
parent
0150fe7c98
commit
cecfff0408
@ -26,6 +26,11 @@ __copyright__ = '(C) 2012, Victor Olaya'
|
||||
__revision__ = '$Format:%H$'
|
||||
|
||||
from PyQt4.QtGui import *
|
||||
from processing.algs.ftools.RandomExtract import RandomExtract
|
||||
from processing.algs.ftools.RandomExtractWithinSubsets import \
|
||||
RandomExtractWithinSubsets
|
||||
from processing.algs.ftools.ExtractByLocation import ExtractByLocation
|
||||
|
||||
from processing.core.AlgorithmProvider import AlgorithmProvider
|
||||
from processing.algs.ftools.PointsInPolygon import PointsInPolygon
|
||||
from processing.algs.ftools.PointsInPolygonUnique import PointsInPolygonUnique
|
||||
@ -80,7 +85,8 @@ from processing.algs.mmqgisx.MMQGISXAlgorithms import \
|
||||
mmqgisx_geometry_convert_algorithm, mmqgisx_grid_algorithm, \
|
||||
mmqgisx_gridify_algorithm, mmqgisx_hub_distance_algorithm, \
|
||||
mmqgisx_hub_lines_algorithm, mmqgisx_merge_algorithm, \
|
||||
mmqgisx_select_algorithm, mmqgisx_text_to_float_algorithm
|
||||
mmqgisx_select_algorithm, mmqgisx_text_to_float_algorithm,\
|
||||
mmqgisx_extract_algorithm
|
||||
|
||||
from processing.algs.Polygonize import Polygonize
|
||||
from processing.algs.RasterLayerStatistics import RasterLayerStatistics
|
||||
@ -128,7 +134,8 @@ class QGISAlgorithmProvider(AlgorithmProvider):
|
||||
VariableDistanceBuffer(), Dissolve(), Difference(),
|
||||
Intersection(), Union(), Clip(), ExtentFromLayer(),
|
||||
RandomSelection(), RandomSelectionWithinSubsets(),
|
||||
SelectByLocation(),
|
||||
SelectByLocation(), RandomExtract(), RandomExtractWithinSubsets(),
|
||||
ExtractByLocation(),
|
||||
# ------ mmqgisx ------
|
||||
mmqgisx_delete_columns_algorithm(),
|
||||
mmqgisx_delete_duplicate_geometries_algorithm(),
|
||||
@ -139,6 +146,7 @@ class QGISAlgorithmProvider(AlgorithmProvider):
|
||||
mmqgisx_hub_lines_algorithm(),
|
||||
mmqgisx_merge_algorithm(),
|
||||
mmqgisx_select_algorithm(),
|
||||
mmqgisx_extract_algorithm(),
|
||||
mmqgisx_text_to_float_algorithm(),
|
||||
# ------ native algs ------
|
||||
AddTableField(), FieldsCalculator(),
|
||||
|
84
python/plugins/processing/algs/ftools/ExtractByLocation.py
Normal file
84
python/plugins/processing/algs/ftools/ExtractByLocation.py
Normal file
@ -0,0 +1,84 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
***************************************************************************
|
||||
ExtractByLocation.py
|
||||
---------------------
|
||||
Date : August 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__ = 'August 2012'
|
||||
__copyright__ = '(C) 2012, Victor Olaya'
|
||||
|
||||
# This will get replaced with a git SHA1 when you do a git archive
|
||||
|
||||
__revision__ = '$Format:%H$'
|
||||
|
||||
from PyQt4.QtCore import *
|
||||
from qgis.core import *
|
||||
from processing.core.GeoAlgorithm import GeoAlgorithm
|
||||
from processing.parameters.ParameterVector import ParameterVector
|
||||
from processing.outputs.OutputVector import OutputVector
|
||||
from processing.tools import dataobjects, vector
|
||||
|
||||
|
||||
class ExtractByLocation(GeoAlgorithm):
|
||||
|
||||
INPUT = 'INPUT'
|
||||
INTERSECT = 'INTERSECT'
|
||||
OUTPUT = 'OUTPUT'
|
||||
|
||||
def defineCharacteristics(self):
|
||||
self.name = 'Extract by location'
|
||||
self.group = 'Vector selection tools'
|
||||
self.addParameter(ParameterVector(self.INPUT, 'Layer to select from',
|
||||
[ParameterVector.VECTOR_TYPE_ANY]))
|
||||
self.addParameter(ParameterVector(self.INTERSECT,
|
||||
'Additional layer (intersection layer)',
|
||||
[ParameterVector.VECTOR_TYPE_ANY]))
|
||||
self.addOutput(OutputVector(self.OUTPUT, 'Selection'))
|
||||
|
||||
def processAlgorithm(self, progress):
|
||||
filename = self.getParameterValue(self.INPUT)
|
||||
layer = dataobjects.getObjectFromUri(filename)
|
||||
filename = self.getParameterValue(self.INTERSECT)
|
||||
selectLayer = dataobjects.getObjectFromUri(filename)
|
||||
index = vector.spatialindex(layer)
|
||||
|
||||
geom = QgsGeometry()
|
||||
selectedSet = []
|
||||
current = 0
|
||||
features = vector.features(selectLayer)
|
||||
featureCount = len(features)
|
||||
total = 100.0 / float(len(features))
|
||||
for current,f in enumerate(features):
|
||||
geom = QgsGeometry(f.geometry())
|
||||
intersects = index.intersects(geom.boundingBox())
|
||||
for i in intersects:
|
||||
request = QgsFeatureRequest().setFilterFid(i)
|
||||
feat = layer.getFeatures(request).next()
|
||||
tmpGeom = QgsGeometry(feat.geometry())
|
||||
if geom.intersects(tmpGeom):
|
||||
selectedSet.append(feat.id())
|
||||
progress.setPercentage(int(current * total))
|
||||
|
||||
output = self.getOutputFromName(self.OUTPUT)
|
||||
writer = output.getVectorWriter(layer.fields(),
|
||||
layer.geometryType(), layer.crs())
|
||||
|
||||
for (i, feat) in enumerate(features):
|
||||
if feat.id() in selectedSet:
|
||||
writer.addFeature(feat)
|
||||
progress.setPercentage(100 * i / float(featureCount))
|
||||
del writer
|
96
python/plugins/processing/algs/ftools/RandomExtract.py
Normal file
96
python/plugins/processing/algs/ftools/RandomExtract.py
Normal file
@ -0,0 +1,96 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
***************************************************************************
|
||||
RandomExtract.py
|
||||
---------------------
|
||||
Date : August 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__ = 'August 2012'
|
||||
__copyright__ = '(C) 2012, Victor Olaya'
|
||||
|
||||
# This will get replaced with a git SHA1 when you do a git archive
|
||||
|
||||
__revision__ = '$Format:%H$'
|
||||
|
||||
import random
|
||||
|
||||
from PyQt4.QtCore import *
|
||||
from qgis.core import *
|
||||
|
||||
from processing.core.GeoAlgorithm import GeoAlgorithm
|
||||
from processing.core.GeoAlgorithmExecutionException import \
|
||||
GeoAlgorithmExecutionException
|
||||
from processing.parameters.ParameterSelection import ParameterSelection
|
||||
from processing.parameters.ParameterVector import ParameterVector
|
||||
from processing.parameters.ParameterNumber import ParameterNumber
|
||||
from processing.outputs.OutputVector import OutputVector
|
||||
from processing.tools import dataobjects, vector
|
||||
|
||||
|
||||
class RandomExtract(GeoAlgorithm):
|
||||
|
||||
INPUT = 'INPUT'
|
||||
OUTPUT = 'OUTPUT'
|
||||
METHOD = 'METHOD'
|
||||
NUMBER = 'NUMBER'
|
||||
|
||||
METHODS = ['Number of selected features',
|
||||
'Percentage of selected features']
|
||||
def defineCharacteristics(self):
|
||||
self.name = 'Random extract'
|
||||
self.group = 'Vector selection tools'
|
||||
|
||||
self.addParameter(ParameterVector(self.INPUT, 'Input layer',
|
||||
[ParameterVector.VECTOR_TYPE_ANY]))
|
||||
self.addParameter(ParameterSelection(self.METHOD, 'Method',
|
||||
self.METHODS, 0))
|
||||
self.addParameter(ParameterNumber(self.NUMBER,
|
||||
'Number/percentage of selected features', 0, None,
|
||||
10))
|
||||
self.addOutput(OutputVector(self.OUTPUT, 'Selection'))
|
||||
|
||||
def processAlgorithm(self, progress):
|
||||
filename = self.getParameterValue(self.INPUT)
|
||||
layer = dataobjects.getObjectFromUri(filename)
|
||||
method = self.getParameterValue(self.METHOD)
|
||||
|
||||
features = vector.features(layer)
|
||||
featureCount = len(features)
|
||||
value = int(self.getParameterValue(self.NUMBER))
|
||||
|
||||
if method == 0:
|
||||
if value > featureCount:
|
||||
raise GeoAlgorithmExecutionException(
|
||||
'Selected number is greater than feature count. \
|
||||
Choose a lower value and try again.')
|
||||
else:
|
||||
if value > 100:
|
||||
raise GeoAlgorithmExecutionException(
|
||||
"Percentage can't be greater than 100. Set a \
|
||||
different value and try again.")
|
||||
value = int(round(value / 100.0000, 4) * featureCount)
|
||||
|
||||
selran = random.sample(xrange(0, featureCount), value)
|
||||
|
||||
output = self.getOutputFromName(self.OUTPUT)
|
||||
writer = output.getVectorWriter(layer.fields(),
|
||||
layer.geometryType(), layer.crs())
|
||||
|
||||
for (i, feat) in enumerate(features):
|
||||
if i in selran:
|
||||
writer.addFeature(feat)
|
||||
progress.setPercentage(100 * i / float(featureCount))
|
||||
del writer
|
@ -0,0 +1,134 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
***************************************************************************
|
||||
RandomSelectionWithinSubsets.py
|
||||
---------------------
|
||||
Date : August 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__ = 'August 2012'
|
||||
__copyright__ = '(C) 2012, Victor Olaya'
|
||||
|
||||
# This will get replaced with a git SHA1 when you do a git archive
|
||||
|
||||
__revision__ = '$Format:%H$'
|
||||
|
||||
import random
|
||||
from PyQt4.QtCore import *
|
||||
from qgis.core import *
|
||||
from processing.core.GeoAlgorithm import GeoAlgorithm
|
||||
from processing.core.GeoAlgorithmExecutionException import \
|
||||
GeoAlgorithmExecutionException
|
||||
from processing.parameters.ParameterSelection import ParameterSelection
|
||||
from processing.parameters.ParameterVector import ParameterVector
|
||||
from processing.parameters.ParameterNumber import ParameterNumber
|
||||
from processing.parameters.ParameterTableField import ParameterTableField
|
||||
from processing.outputs.OutputVector import OutputVector
|
||||
from processing.tools import dataobjects, vector
|
||||
|
||||
|
||||
class RandomExtractWithinSubsets(GeoAlgorithm):
|
||||
|
||||
INPUT = 'INPUT'
|
||||
METHOD = 'METHOD'
|
||||
NUMBER = 'NUMBER'
|
||||
FIELD = 'FIELD'
|
||||
OUTPUT = 'OUTPUT'
|
||||
|
||||
METHODS = ['Number of selected features',
|
||||
'Percentage of selected features']
|
||||
|
||||
def defineCharacteristics(self):
|
||||
self.name = 'Random extract within subsets'
|
||||
self.group = 'Vector selection tools'
|
||||
|
||||
self.addParameter(ParameterVector(self.INPUT, 'Input layer',
|
||||
[ParameterVector.VECTOR_TYPE_ANY]))
|
||||
self.addParameter(ParameterTableField(self.FIELD, 'ID Field',
|
||||
self.INPUT))
|
||||
self.addParameter(ParameterSelection(self.METHOD, 'Method',
|
||||
self.METHODS, 0))
|
||||
self.addParameter(ParameterNumber(self.NUMBER,
|
||||
'Number/percentage of selected features', 1, None,
|
||||
10))
|
||||
|
||||
self.addOutput(OutputVector(self.OUTPUT, 'Selection'))
|
||||
|
||||
def processAlgorithm(self, progress):
|
||||
filename = self.getParameterValue(self.INPUT)
|
||||
|
||||
layer = dataobjects.getObjectFromUri(filename)
|
||||
field = self.getParameterValue(self.FIELD)
|
||||
method = self.getParameterValue(self.METHOD)
|
||||
|
||||
index = layer.fieldNameIndex(field)
|
||||
|
||||
features = vector.features(layer)
|
||||
featureCount = len(features)
|
||||
unique = vector.getUniqueValues(layer, index)
|
||||
value = int(self.getParameterValue(self.NUMBER))
|
||||
if method == 0:
|
||||
if value > featureCount:
|
||||
raise GeoAlgorithmExecutionException(
|
||||
'Selected number is greater that feature count. \
|
||||
Choose lesser value and try again.')
|
||||
else:
|
||||
if value > 100:
|
||||
raise GeoAlgorithmExecutionException(
|
||||
"Percentage can't be greater than 100. Set correct \
|
||||
value and try again.")
|
||||
value = value / 100.0
|
||||
|
||||
|
||||
output = self.getOutputFromName(self.OUTPUT)
|
||||
writer = output.getVectorWriter(layer.fields(),
|
||||
layer.geometryType(), layer.crs())
|
||||
|
||||
selran = []
|
||||
current = 0
|
||||
total = 100.0 / float(featureCount * len(unique))
|
||||
features = vector.features(layer)
|
||||
|
||||
if not len(unique) == featureCount:
|
||||
for classValue in unique:
|
||||
classFeatures = []
|
||||
for i, feature in enumerate(features):
|
||||
attrs = feature.attributes()
|
||||
if attrs[index] == classValue:
|
||||
classFeatures.append(i)
|
||||
current += 1
|
||||
progress.setPercentage(int(current * total))
|
||||
|
||||
if method == 1:
|
||||
selValue = int(round(value * len(classFeatures), 0))
|
||||
else:
|
||||
selValue = value
|
||||
|
||||
if selValue >= len(classFeatures):
|
||||
selFeat = classFeatures
|
||||
else:
|
||||
selFeat = random.sample(classFeatures, selValue)
|
||||
|
||||
selran.extend(selFeat)
|
||||
else:
|
||||
selran = range(0, featureCount)
|
||||
|
||||
|
||||
features = vector.features(layer)
|
||||
for (i, feat) in enumerate(features):
|
||||
if i in selran:
|
||||
writer.addFeature(feat)
|
||||
progress.setPercentage(100 * i / float(featureCount))
|
||||
del writer
|
@ -50,12 +50,6 @@ class RandomSelectionWithinSubsets(GeoAlgorithm):
|
||||
METHODS = ['Number of selected features',
|
||||
'Percentage of selected features']
|
||||
|
||||
# =========================================================================
|
||||
# def getIcon(self):
|
||||
# return QIcon(os.path.dirname(__file__) + \
|
||||
# "/icons/random_selection.png")
|
||||
# =========================================================================
|
||||
|
||||
def defineCharacteristics(self):
|
||||
self.allowOnlyOpenedLayers = True
|
||||
self.name = 'Random selection within subsets'
|
||||
|
@ -44,10 +44,6 @@ class SelectByLocation(GeoAlgorithm):
|
||||
METHODS = ['creating new selection', 'adding to current selection',
|
||||
'removing from current selection']
|
||||
|
||||
# =========================================================================
|
||||
# def getIcon(self):
|
||||
# return QIcon(os.path.dirname(__file__) + "/icons/select_location.png")
|
||||
# =========================================================================
|
||||
|
||||
def defineCharacteristics(self):
|
||||
self.allowOnlyOpenedLayers = True
|
||||
@ -70,9 +66,8 @@ class SelectByLocation(GeoAlgorithm):
|
||||
selectLayer = dataobjects.getObjectFromUri(filename)
|
||||
|
||||
oldSelection = set(inputLayer.selectedFeaturesIds())
|
||||
index = spatialIndex = vector.spatialindex(inputLayer)
|
||||
|
||||
feat = QgsFeature()
|
||||
index = vector.spatialindex(inputLayer)
|
||||
|
||||
geom = QgsGeometry()
|
||||
selectedSet = []
|
||||
current = 0
|
||||
|
@ -47,12 +47,6 @@ class mmqgisx_delete_columns_algorithm(GeoAlgorithm):
|
||||
self.LAYERNAME))
|
||||
self.addOutput(OutputVector(self.SAVENAME, 'Output'))
|
||||
|
||||
# =========================================================================
|
||||
# def getIcon(self):
|
||||
# return QIcon(os.path.dirname(__file__) +
|
||||
# "/icons/mmqgis_attribute_join.png")
|
||||
# =========================================================================
|
||||
|
||||
def processAlgorithm(self, progress):
|
||||
|
||||
layer = dataobjects.getObjectFromUri(
|
||||
@ -100,12 +94,6 @@ class mmqgisx_delete_duplicate_geometries_algorithm(GeoAlgorithm):
|
||||
[ParameterVector.VECTOR_TYPE_ANY]))
|
||||
self.addOutput(OutputVector(self.SAVENAME, 'Output'))
|
||||
|
||||
# ===========================================================================
|
||||
# def getIcon(self):
|
||||
# return QIcon(os.path.dirname(__file__) +
|
||||
# "/icons/mmqgis_attribute_join.png")
|
||||
# ===========================================================================
|
||||
|
||||
def processAlgorithm(self, progress):
|
||||
layer = dataobjects.getObjectFromUri(
|
||||
self.getParameterValue(self.LAYERNAME))
|
||||
@ -146,12 +134,6 @@ class mmqgisx_geometry_convert_algorithm(GeoAlgorithm):
|
||||
|
||||
self.addOutput(OutputVector(self.SAVENAME, 'Output'))
|
||||
|
||||
# ===========================================================================
|
||||
# def getIcon(self):
|
||||
# return QIcon(os.path.dirname(__file__) +
|
||||
# "/icons/mmqgis_attribute_export.png")
|
||||
# ===========================================================================
|
||||
|
||||
def processAlgorithm(self, progress):
|
||||
|
||||
layer = dataobjects.getObjectFromUri(
|
||||
@ -429,11 +411,6 @@ class mmqgisx_grid_algorithm(GeoAlgorithm):
|
||||
self.addParameter(ParameterCrs(self.CRS, 'CRS'))
|
||||
self.addOutput(OutputVector(self.SAVENAME, 'Output'))
|
||||
|
||||
# ===========================================================================
|
||||
# def getIcon(self):
|
||||
# return QtGui.QIcon(os.path.dirname(__file__) + "/icons/mmqgis_grid.png")
|
||||
# ===========================================================================
|
||||
|
||||
def processAlgorithm(self, progress):
|
||||
hspacing = self.getParameterValue(self.HSPACING)
|
||||
vspacing = self.getParameterValue(self.VSPACING)
|
||||
@ -618,11 +595,6 @@ class mmqgisx_gridify_algorithm(GeoAlgorithm):
|
||||
default=0.1))
|
||||
self.addOutput(OutputVector(self.SAVENAME, 'Output'))
|
||||
|
||||
# ===========================================================================
|
||||
# def getIcon(self):
|
||||
# return QIcon(os.path.dirname(__file__) + "/icons/mmqgis_gridify.png")
|
||||
# ===========================================================================
|
||||
|
||||
def processAlgorithm(self, progress):
|
||||
|
||||
layer = dataobjects.getObjectFromUri(
|
||||
@ -817,12 +789,6 @@ class mmqgisx_hub_distance_algorithm(GeoAlgorithm):
|
||||
|
||||
self.addOutput(OutputVector(self.SAVENAME, 'Output'))
|
||||
|
||||
# ===========================================================================
|
||||
# def getIcon(self):
|
||||
# return QIcon(os.path.dirname(__file__) +
|
||||
# "/icons/mmqgis_hub_distance.png")
|
||||
# ===========================================================================
|
||||
|
||||
def processAlgorithm(self, progress):
|
||||
|
||||
layersource = dataobjects.getObjectFromUri(
|
||||
@ -936,12 +902,6 @@ class mmqgisx_hub_lines_algorithm(GeoAlgorithm):
|
||||
'Spoke Hub ID Attribute', self.SPOKENAME))
|
||||
self.addOutput(OutputVector(self.SAVENAME, 'Output'))
|
||||
|
||||
# ===========================================================================
|
||||
# def getIcon(self):
|
||||
# return QIcon(os.path.dirname(__file__) +
|
||||
# "/icons/mmqgis_hub_distance.png")
|
||||
# ===========================================================================
|
||||
|
||||
def processAlgorithm(self, progress):
|
||||
|
||||
hublayer = dataobjects.getObjectFromUri(
|
||||
@ -1020,11 +980,6 @@ class mmqgisx_merge_algorithm(GeoAlgorithm):
|
||||
[ParameterVector.VECTOR_TYPE_ANY]))
|
||||
self.addOutput(OutputVector(self.SAVENAME, 'Output'))
|
||||
|
||||
# ===========================================================================
|
||||
# def getIcon(self):
|
||||
# return QtGui.QIcon(os.path.dirname(__file__) + "/icons/mmqgis_merge.png")
|
||||
# ===========================================================================
|
||||
|
||||
def processAlgorithm(self, progress):
|
||||
|
||||
layer1 = dataobjects.getObjectFromUri(
|
||||
@ -1130,11 +1085,52 @@ class mmqgisx_select_algorithm(GeoAlgorithm):
|
||||
|
||||
self.addOutput(OutputVector(self.RESULT, 'Output', True))
|
||||
|
||||
# ===========================================================================
|
||||
# def getIcon(self):
|
||||
# return QIcon(os.path.dirname(__file__) +
|
||||
# "/icons/mmqgis_attribute_export.png")
|
||||
# ===========================================================================
|
||||
def processAlgorithm(self, progress):
|
||||
|
||||
filename = self.getParameterValue(self.LAYERNAME)
|
||||
layer = dataobjects.getObjectFromUri(filename)
|
||||
|
||||
attribute = self.getParameterValue(self.ATTRIBUTE)
|
||||
comparison = self.comparisons[self.getParameterValue(self.COMPARISON)]
|
||||
comparisonvalue = self.getParameterValue(self.COMPARISONVALUE)
|
||||
|
||||
selected = select(layer, attribute, comparison, comparisonvalue, progress)
|
||||
|
||||
layer.setSelectedFeatures(selected)
|
||||
self.setOutputValue(self.RESULT, filename)
|
||||
|
||||
class mmqgisx_extract_algorithm(GeoAlgorithm):
|
||||
|
||||
LAYERNAME = 'LAYERNAME'
|
||||
ATTRIBUTE = 'ATTRIBUTE'
|
||||
COMPARISONVALUE = 'COMPARISONVALUE'
|
||||
COMPARISON = 'COMPARISON'
|
||||
RESULT = 'RESULT'
|
||||
|
||||
def defineCharacteristics(self):
|
||||
self.name = 'Extract by attribute'
|
||||
self.group = 'Vector selection tools'
|
||||
|
||||
self.addParameter(ParameterVector(self.LAYERNAME, 'Input Layer',
|
||||
[ParameterVector.VECTOR_TYPE_ANY]))
|
||||
self.addParameter(ParameterTableField(self.ATTRIBUTE,
|
||||
'Selection attribute', self.LAYERNAME))
|
||||
self.comparisons = [
|
||||
'==',
|
||||
'!=',
|
||||
'>',
|
||||
'>=',
|
||||
'<',
|
||||
'<=',
|
||||
'begins with',
|
||||
'contains',
|
||||
]
|
||||
self.addParameter(ParameterSelection(self.COMPARISON, 'Comparison',
|
||||
self.comparisons, default=0))
|
||||
self.addParameter(ParameterString(self.COMPARISONVALUE, 'Value',
|
||||
default='0'))
|
||||
|
||||
self.addOutput(OutputVector(self.RESULT, 'Output'))
|
||||
|
||||
def processAlgorithm(self, progress):
|
||||
|
||||
@ -1145,118 +1141,130 @@ class mmqgisx_select_algorithm(GeoAlgorithm):
|
||||
comparison = self.comparisons[self.getParameterValue(self.COMPARISON)]
|
||||
comparisonvalue = self.getParameterValue(self.COMPARISONVALUE)
|
||||
|
||||
selectindex = layer.dataProvider().fieldNameIndex(attribute)
|
||||
selected = select(layer, attribute, comparison, comparisonvalue, progress)
|
||||
|
||||
features = vector.features(layer)
|
||||
featureCount = len(features)
|
||||
output = self.getOutputFromName(self.OUTPUT)
|
||||
writer = output.getVectorWriter(layer.fields(),
|
||||
layer.geometryType(), layer.crs())
|
||||
for (i, feat) in enumerate(features):
|
||||
if feat.id() in selected:
|
||||
writer.addFeature(feat)
|
||||
progress.setPercentage(100 * i / float(featureCount))
|
||||
del writer
|
||||
|
||||
selectType = layer.dataProvider().fields()[selectindex].type()
|
||||
selectionError = False
|
||||
def select(layer, attribute, comparison, comparisonvalue, progress):
|
||||
selectindex = layer.dataProvider().fieldNameIndex(attribute)
|
||||
selectType = layer.dataProvider().fields()[selectindex].type()
|
||||
selectionError = False
|
||||
|
||||
if selectType == 2:
|
||||
try:
|
||||
y = int(comparisonvalue)
|
||||
except ValueError:
|
||||
selectionError = True
|
||||
msg = 'Cannot convert "' + unicode(comparisonvalue) \
|
||||
+ '" to integer'
|
||||
elif selectType == 6:
|
||||
try:
|
||||
y = float(comparisonvalue)
|
||||
except ValueError:
|
||||
selectionError = True
|
||||
msg = 'Cannot convert "' + unicode(comparisonvalue) \
|
||||
+ '" to float'
|
||||
elif selectType == 10:
|
||||
# string, boolean
|
||||
try:
|
||||
y = unicode(comparisonvalue)
|
||||
except ValueError:
|
||||
selectionError = True
|
||||
msg = 'Cannot convert "' + unicode(comparisonvalue) \
|
||||
+ '" to unicode'
|
||||
elif selectType == 14:
|
||||
# Date
|
||||
dateAndFormat = comparisonvalue.split(' ')
|
||||
if selectType == 2:
|
||||
try:
|
||||
y = int(comparisonvalue)
|
||||
except ValueError:
|
||||
selectionError = True
|
||||
msg = 'Cannot convert "' + unicode(comparisonvalue) \
|
||||
+ '" to integer'
|
||||
elif selectType == 6:
|
||||
try:
|
||||
y = float(comparisonvalue)
|
||||
except ValueError:
|
||||
selectionError = True
|
||||
msg = 'Cannot convert "' + unicode(comparisonvalue) \
|
||||
+ '" to float'
|
||||
elif selectType == 10:
|
||||
# string, boolean
|
||||
try:
|
||||
y = unicode(comparisonvalue)
|
||||
except ValueError:
|
||||
selectionError = True
|
||||
msg = 'Cannot convert "' + unicode(comparisonvalue) \
|
||||
+ '" to unicode'
|
||||
elif selectType == 14:
|
||||
# Date
|
||||
dateAndFormat = comparisonvalue.split(' ')
|
||||
|
||||
if len(dateAndFormat) == 1:
|
||||
# QtCore.QDate object
|
||||
y = QLocale.system().toDate(dateAndFormat[0])
|
||||
|
||||
if y.isNull():
|
||||
msg = 'Cannot convert "' + unicode(dateAndFormat) \
|
||||
+ '" to date with system date format ' \
|
||||
+ QLocale.system().dateFormat()
|
||||
elif len(dateAndFormat) == 2:
|
||||
y = QDate.fromString(dateAndFormat[0], dateAndFormat[1])
|
||||
|
||||
if y.isNull():
|
||||
msg = 'Cannot convert "' + unicode(dateAndFormat[0]) \
|
||||
+ '" to date with format string "' \
|
||||
+ unicode(dateAndFormat[1] + '". ')
|
||||
else:
|
||||
y = QDate()
|
||||
msg = ''
|
||||
if len(dateAndFormat) == 1:
|
||||
# QtCore.QDate object
|
||||
y = QLocale.system().toDate(dateAndFormat[0])
|
||||
|
||||
if y.isNull():
|
||||
# Conversion was unsuccessfull
|
||||
selectionError = True
|
||||
msg += 'Enter the date and the date format, e.g. \
|
||||
"07.26.2011" "MM.dd.yyyy".'
|
||||
msg = 'Cannot convert "' + unicode(dateAndFormat) \
|
||||
+ '" to date with system date format ' \
|
||||
+ QLocale.system().dateFormat()
|
||||
elif len(dateAndFormat) == 2:
|
||||
y = QDate.fromString(dateAndFormat[0], dateAndFormat[1])
|
||||
|
||||
if (comparison == 'begins with' or comparison == 'contains') \
|
||||
and selectType != 10:
|
||||
if y.isNull():
|
||||
msg = 'Cannot convert "' + unicode(dateAndFormat[0]) \
|
||||
+ '" to date with format string "' \
|
||||
+ unicode(dateAndFormat[1] + '". ')
|
||||
else:
|
||||
y = QDate()
|
||||
msg = ''
|
||||
|
||||
if y.isNull():
|
||||
# Conversion was unsuccessfull
|
||||
selectionError = True
|
||||
msg = '"' + comparison + '" can only be used with string fields'
|
||||
msg += 'Enter the date and the date format, e.g. \
|
||||
"07.26.2011" "MM.dd.yyyy".'
|
||||
|
||||
if selectionError:
|
||||
raise GeoAlgorithmExecutionException('Error in selection input: '
|
||||
+ msg)
|
||||
if (comparison == 'begins with' or comparison == 'contains') \
|
||||
and selectType != 10:
|
||||
selectionError = True
|
||||
msg = '"' + comparison + '" can only be used with string fields'
|
||||
|
||||
readcount = 0
|
||||
selected = []
|
||||
totalcount = layer.featureCount()
|
||||
for feature in layer.getFeatures():
|
||||
aValue = feature[selectindex]
|
||||
if selectionError:
|
||||
raise GeoAlgorithmExecutionException('Error in selection input: '
|
||||
+ msg)
|
||||
|
||||
if aValue is None:
|
||||
continue
|
||||
readcount = 0
|
||||
selected = []
|
||||
features = vector.features(layer)
|
||||
totalcount = len(features)
|
||||
for feature in features:
|
||||
aValue = feature[selectindex]
|
||||
|
||||
if selectType == 2:
|
||||
x = int(aValue)
|
||||
elif selectType == 6:
|
||||
x = float(aValue)
|
||||
elif selectType == 10:
|
||||
# string, boolean
|
||||
x = unicode(aValue)
|
||||
elif selectType == 14:
|
||||
# date
|
||||
x = aValue
|
||||
if aValue is None:
|
||||
continue
|
||||
|
||||
match = False
|
||||
if comparison == '==':
|
||||
match = x == y
|
||||
elif comparison == '!=':
|
||||
match = x != y
|
||||
elif comparison == '>':
|
||||
match = x > y
|
||||
elif comparison == '>=':
|
||||
match = x >= y
|
||||
elif comparison == '<':
|
||||
match = x < y
|
||||
elif comparison == '<=':
|
||||
match = x <= y
|
||||
elif comparison == 'begins with':
|
||||
match = x.startswith(y)
|
||||
elif comparison == 'contains':
|
||||
match = x.find(y) >= 0
|
||||
if selectType == 2:
|
||||
x = int(aValue)
|
||||
elif selectType == 6:
|
||||
x = float(aValue)
|
||||
elif selectType == 10:
|
||||
# string, boolean
|
||||
x = unicode(aValue)
|
||||
elif selectType == 14:
|
||||
# date
|
||||
x = aValue
|
||||
|
||||
readcount += 1
|
||||
if match:
|
||||
selected.append(feature.id())
|
||||
match = False
|
||||
if comparison == '==':
|
||||
match = x == y
|
||||
elif comparison == '!=':
|
||||
match = x != y
|
||||
elif comparison == '>':
|
||||
match = x > y
|
||||
elif comparison == '>=':
|
||||
match = x >= y
|
||||
elif comparison == '<':
|
||||
match = x < y
|
||||
elif comparison == '<=':
|
||||
match = x <= y
|
||||
elif comparison == 'begins with':
|
||||
match = x.startswith(y)
|
||||
elif comparison == 'contains':
|
||||
match = x.find(y) >= 0
|
||||
|
||||
progress.setPercentage(float(readcount) / totalcount * 100)
|
||||
|
||||
layer.setSelectedFeatures(selected)
|
||||
self.setOutputValue(self.RESULT, filename)
|
||||
readcount += 1
|
||||
if match:
|
||||
selected.append(feature.id())
|
||||
|
||||
progress.setPercentage(float(readcount) / totalcount * 100)
|
||||
|
||||
return selected
|
||||
|
||||
class mmqgisx_text_to_float_algorithm(GeoAlgorithm):
|
||||
|
||||
@ -1275,12 +1283,6 @@ class mmqgisx_text_to_float_algorithm(GeoAlgorithm):
|
||||
self.LAYERNAME))
|
||||
self.addOutput(OutputVector(self.SAVENAME, 'Output'))
|
||||
|
||||
# ===========================================================================
|
||||
# def getIcon(self):
|
||||
# return QIcon(os.path.dirname(__file__) +
|
||||
# "/icons/mmqgis_text_to_float.png")
|
||||
# ===========================================================================
|
||||
|
||||
def processAlgorithm(self, progress):
|
||||
layer = dataobjects.getObjectFromUri(
|
||||
self.getParameterValue(self.LAYERNAME))
|
||||
|
Loading…
x
Reference in New Issue
Block a user