QGIS/python/plugins/processing/algs/qgis/RandomSelectionWithinSubsets.py

144 lines
5.3 KiB
Python
Raw Normal View History

2012-10-04 19:33:47 +02:00
# -*- 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. *
* *
***************************************************************************
"""
2016-09-21 18:24:26 +02:00
from builtins import range
2012-10-04 19:33:47 +02:00
__author__ = 'Victor Olaya'
__date__ = 'August 2012'
__copyright__ = '(C) 2012, Victor Olaya'
2012-10-04 19:33:47 +02:00
# This will get replaced with a git SHA1 when you do a git archive
2012-10-04 19:33:47 +02:00
__revision__ = '$Format:%H$'
import os
import random
2016-04-22 10:38:48 +02:00
from qgis.PyQt.QtGui import QIcon
from qgis.core import QgsFeature, QgsFeatureSink, QgsProcessingUtils
2017-06-06 13:41:42 +10:00
from processing.algs.qgis.QgisAlgorithm import QgisAlgorithm
from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException
from processing.core.parameters import ParameterSelection
from processing.core.parameters import ParameterVector
from processing.core.parameters import ParameterNumber
from processing.core.parameters import ParameterTableField
from processing.core.outputs import OutputVector
pluginPath = os.path.split(os.path.split(os.path.dirname(__file__))[0])[0]
2012-09-15 18:25:25 +03:00
class RandomSelectionWithinSubsets(QgisAlgorithm):
2012-09-15 18:25:25 +03:00
INPUT = 'INPUT'
METHOD = 'METHOD'
NUMBER = 'NUMBER'
FIELD = 'FIELD'
OUTPUT = 'OUTPUT'
def icon(self):
return QIcon(os.path.join(pluginPath, 'images', 'ftools', 'sub_selection.png'))
def group(self):
return self.tr('Vector selection tools')
def __init__(self):
super().__init__()
def initAlgorithm(self, config=None):
self.methods = [self.tr('Number of selected features'),
self.tr('Percentage of selected features')]
2015-01-15 20:41:15 +02:00
self.addParameter(ParameterVector(self.INPUT,
self.tr('Input layer')))
2015-01-15 20:41:15 +02:00
self.addParameter(ParameterTableField(self.FIELD,
self.tr('ID Field'), self.INPUT))
2015-01-15 20:41:15 +02:00
self.addParameter(ParameterSelection(self.METHOD,
self.tr('Method'), self.methods, 0))
self.addParameter(ParameterNumber(self.NUMBER,
self.tr('Number/percentage of selected features'), 1, None, 10))
self.addOutput(OutputVector(self.OUTPUT, self.tr('Selection stratified'), True))
def name(self):
return 'randomselectionwithinsubsets'
def displayName(self):
return self.tr('Random selection within subsets')
def processAlgorithm(self, parameters, context, feedback):
filename = self.getParameterValue(self.INPUT)
layer = QgsProcessingUtils.mapLayerFromString(filename, context)
field = self.getParameterValue(self.FIELD)
2012-09-15 18:25:25 +03:00
method = self.getParameterValue(self.METHOD)
2013-05-11 20:40:57 +05:30
layer.removeSelection()
2016-09-22 12:09:13 +02:00
index = layer.fields().lookupField(field)
unique = QgsProcessingUtils.uniqueValues(layer, index, context)
featureCount = layer.featureCount()
value = int(self.getParameterValue(self.NUMBER))
if method == 0:
if value > featureCount:
raise GeoAlgorithmExecutionException(
2015-01-15 20:41:15 +02:00
self.tr('Selected number is greater that feature count. '
'Choose lesser value and try again.'))
else:
if value > 100:
raise GeoAlgorithmExecutionException(
self.tr("Percentage can't be greater than 100. Set a "
2015-01-15 20:41:15 +02:00
"different value and try again."))
value = value / 100.0
2012-09-15 18:25:25 +03:00
selran = []
inFeat = QgsFeature()
current = 0
total = 100.0 / (featureCount * len(unique)) if featureCount else 1
if not len(unique) == featureCount:
2012-09-15 18:25:25 +03:00
for i in unique:
features = QgsProcessingUtils.getFeatures(layer, context)
FIDs = []
for inFeat in features:
attrs = inFeat.attributes()
2013-06-03 21:25:22 +02:00
if attrs[index] == i:
FIDs.append(inFeat.id())
current += 1
feedback.setProgress(int(current * total))
if method == 1:
selValue = int(round(value * len(FIDs), 0))
2012-09-15 18:25:25 +03:00
else:
selValue = value
if selValue >= len(FIDs):
2012-09-15 18:25:25 +03:00
selFeat = FIDs
else:
selFeat = random.sample(FIDs, selValue)
2012-09-15 18:25:25 +03:00
selran.extend(selFeat)
layer.selectByIds(selran)
2012-09-15 18:25:25 +03:00
else:
2016-09-21 18:24:26 +02:00
layer.selectByIds(list(range(featureCount))) # FIXME: implies continuous feature ids
2012-09-15 18:25:25 +03:00
self.setOutputValue(self.OUTPUT, filename)