Skip to content


Restore frequency analysis script
Browse files Browse the repository at this point in the history
This script has been changed to use a sink output, not the previous
TableWriter csv output.

All algorithms which output flat tables should now still output
feature sinks, to allow correct use in later model steps.
  • Loading branch information
nyalldawson committed Jun 26, 2017
1 parent d49114c commit 86d33c1
Showing 1 changed file with 22 additions and 12 deletions.
34 changes: 22 additions & 12 deletions python/plugins/processing/algs/qgis/scripts/
Expand Up @@ -3,37 +3,47 @@

##Fields=field Input
##Frequency=output table
##Fields=field multiple Input
##Frequency=sink table


##Frequency=output outputVector

from import TableWriter
from collections import defaultdict
from qgis.core import QgsProcessingUtils
from qgis.core import QgsProcessingUtils, QgsFields, QgsField, QgsWkbTypes, QgsFeature
from qgis.PyQt.QtCore import QVariant
from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException

layer = QgsProcessingUtils.mapLayerFromString(Input, context)
inputFields = layer.fields()
inputFields = Input.fields()
fieldIdxs = []
fields = Fields.split(',')
for f in fields:
out_fields = QgsFields()
for f in Fields:
idx = inputFields.indexFromName(f)
if idx == -1:
raise GeoAlgorithmExecutionException('Field not found:' + f)
writer = TableWriter(Frequency, None, fields + ['FREQ'])

out_fields.append(QgsField('FREQ', QVariant.Int))

(sink, Frequency) = self.parameterAsSink(parameters, 'Frequency', context,

counts = {}
feats = QgsProcessingUtils.getFeatures(layer, context)
nFeats = QgsProcessingUtils.featureCount(layer, context)
feats = Input.getFeatures()
nFeats = Input.featureCount()
counts = defaultdict(int)
for i, feat in enumerate(feats):
feedback.setProgress(int(100 * i / nFeats))
if feedback.isCanceled():

attrs = feat.attributes()
clazz = tuple([attrs[i] for i in fieldIdxs])
counts[clazz] += 1

for c in counts:
writer.addRecord(list(c) + [counts[c]])
f = QgsFeature()
f.setAttributes(list(c) + [counts[c]])

0 comments on commit 86d33c1

Please sign in to comment.