Skip to content
Permalink
Browse files

Restore frequency analysis script

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 86d33c1875540cfdf323f1eb6b99c92b6686ee12
Showing with 22 additions and 12 deletions.
  1. +22 −12 python/plugins/processing/algs/qgis/scripts/Frequency_analysis.py
@@ -3,37 +3,47 @@
#inputs

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

#outputs

##Frequency=output outputVector

from processing.tools.vector 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)
fieldIdxs.append(idx)
writer = TableWriter(Frequency, None, fields + ['FREQ'])
out_fields.append(inputFields.at(idx))

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

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

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():
break

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]])
sink.addFeature(f)

0 comments on commit 86d33c1

Please sign in to comment.
You can’t perform that action at this time.