mirror of
https://github.com/qgis/QGIS.git
synced 2025-03-08 00:02:35 -05:00
Algorithms and other processing code should use this method (instead of dataobjects.getLayerFromString) to retrieve layers from a string, as it considers the processing context and allows resolving strings to temporarily stored layers. This permits processing models to function correctly when intermediate results are stored as memory layers. Subsequent model algorithms can then access these temporary layers as inputs. All temporary layers will be removed when the context object is destroyed after the model algorithm is run.
35 lines
1.1 KiB
Python
35 lines
1.1 KiB
Python
##Table=group
|
|
##Input=vector
|
|
##Fields=Field Input
|
|
##Frequency=output table
|
|
|
|
from processing.tools.vector import TableWriter
|
|
from collections import defaultdict
|
|
from qgis.core import QgsProcessingUtils
|
|
from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException
|
|
from processing.tools import dataobjects
|
|
|
|
layer = dataobjects.QgsProcessingUtils.mapLayerFromString(Input, context)
|
|
inputFields = layer.fields()
|
|
fieldIdxs = []
|
|
fields = Fields.split(',')
|
|
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'])
|
|
|
|
counts = {}
|
|
feats = QgsProcessingUtils.getFeatures(layer, context)
|
|
nFeats = QgsProcessingUtils.featureCount(layer, context)
|
|
counts = defaultdict(int)
|
|
for i, feat in enumerate(feats):
|
|
feedback.setProgress(int(100 * i / nFeats))
|
|
attrs = feat.attributes()
|
|
clazz = tuple([attrs[i] for i in fieldIdxs])
|
|
counts[clazz] += 1
|
|
|
|
for c in counts:
|
|
writer.addRecord(list(c) + [counts[c]])
|