Skip to content

Commit

Permalink
[processing] Port refactor fields to new API
Browse files Browse the repository at this point in the history
  • Loading branch information
arnaud-morvan authored and m-kuhn committed Aug 14, 2017
1 parent 2364801 commit b3a9e46
Show file tree
Hide file tree
Showing 10 changed files with 409 additions and 310 deletions.
2 changes: 2 additions & 0 deletions python/core/processing/qgsprocessingoutputs.sip
Expand Up @@ -40,6 +40,8 @@ class QgsProcessingOutputDefinition
sipType = sipType_QgsProcessingOutputString; sipType = sipType_QgsProcessingOutputString;
else if ( sipCpp->type() == QgsProcessingOutputFolder::typeName() ) else if ( sipCpp->type() == QgsProcessingOutputFolder::typeName() )
sipType = sipType_QgsProcessingOutputFolder; sipType = sipType_QgsProcessingOutputFolder;
else
sipType = nullptr;
%End %End
public: public:


Expand Down
2 changes: 2 additions & 0 deletions python/core/processing/qgsprocessingparameters.sip
Expand Up @@ -191,6 +191,8 @@ class QgsProcessingParameterDefinition
sipType = sipType_QgsProcessingParameterFolderDestination; sipType = sipType_QgsProcessingParameterFolderDestination;
else if ( sipCpp->type() == QgsProcessingParameterBand::typeName() ) else if ( sipCpp->type() == QgsProcessingParameterBand::typeName() )
sipType = sipType_QgsProcessingParameterBand; sipType = sipType_QgsProcessingParameterBand;
else
sipType = nullptr;
%End %End
public: public:


Expand Down
222 changes: 102 additions & 120 deletions python/plugins/processing/algs/qgis/FieldsMapper.py
Expand Up @@ -25,159 +25,141 @@


__revision__ = '$Format:%H$' __revision__ = '$Format:%H$'


from qgis.core import (QgsField, from qgis.core import (
QgsFields, QgsApplication,
QgsExpression, QgsDistanceArea,
QgsDistanceArea, QgsExpression,
QgsFeatureSink, QgsFeature,
QgsProject, QgsFeatureSink,
QgsFeature, QgsField,
QgsApplication, QgsFields,
QgsProcessingUtils) QgsProcessingException,
from processing.algs.qgis.QgisAlgorithm import QgisAlgorithm QgsProcessingParameterDefinition,
from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException QgsProcessingUtils,
from processing.core.parameters import ParameterTable QgsProject,
from processing.core.parameters import Parameter )
from processing.core.outputs import OutputVector

from processing.algs.qgis.QgisAlgorithm import QgisFeatureBasedAlgorithm


class FieldsMapper(QgisAlgorithm):
class FieldsMapper(QgisFeatureBasedAlgorithm):


INPUT_LAYER = 'INPUT_LAYER' INPUT_LAYER = 'INPUT_LAYER'
FIELDS_MAPPING = 'FIELDS_MAPPING' FIELDS_MAPPING = 'FIELDS_MAPPING'
OUTPUT_LAYER = 'OUTPUT_LAYER' OUTPUT_LAYER = 'OUTPUT_LAYER'


def __init__(self):
GeoAlgorithm.__init__(self)
self.mapping = None

def group(self): def group(self):
return self.tr('Vector table tools') return self.tr('Vector table tools')


def __init__(self): def initParameters(self, config=None):
super().__init__()

def initAlgorithm(self, config=None):
self.addParameter(ParameterTable(self.INPUT_LAYER,
self.tr('Input layer'),
False))


class ParameterFieldsMapping(Parameter): class ParameterFieldsMapping(QgsProcessingParameterDefinition):


default_metadata = { def __init__(self, name, description, parentLayerParameterName='INPUT'):
'widget_wrapper': 'processing.algs.qgis.ui.FieldsMappingPanel.FieldsMappingWidgetWrapper' super().__init__(name, description)
} self._parentLayerParameter = parentLayerParameterName


def __init__(self, name='', description='', parent=None): def type(self):
Parameter.__init__(self, name, description) return 'fields_mapping'
self.parent = parent
self.value = []


def getValueAsCommandLineParameter(self): def checkValueIsAcceptable(self, value, context):
return '"' + str(self.value) + '"' if not isinstance(value, list):

def setValue(self, value):
if value is None:
return False return False
if isinstance(value, list): for field_def in value:
self.value = value if not isinstance(field_def, dict):
return True return False
if isinstance(value, str): if not field_def.get('name', False):
try: return False
self.value = eval(value) if not field_def.get('type', False):
return True return False
except Exception as e: if not field_def.get('expression', False):
# fix_print_with_import
print(str(e)) # display error in console
return False return False
return False return True


self.addParameter(ParameterFieldsMapping(self.FIELDS_MAPPING, def valueAsPythonString(self, value, context):
self.tr('Fields mapping'), return str(value)
self.INPUT_LAYER))
self.addOutput(OutputVector(self.OUTPUT_LAYER, def asScriptCode(self):
self.tr('Refactored'), raise NotImplementedError()
base_input=self.INPUT_LAYER))
@classmethod
def fromScriptCode(cls, name, description, isOptional, definition):
raise NotImplementedError()

def parentLayerParameter(self):
return self._parentLayerParameter

fields_mapping = ParameterFieldsMapping(self.FIELDS_MAPPING,
description=self.tr('Fields mapping'))
fields_mapping.setMetadata({
'widget_wrapper': 'processing.algs.qgis.ui.FieldsMappingPanel.FieldsMappingWidgetWrapper'
})
self.addParameter(fields_mapping)


def name(self): def name(self):
return 'refactorfields' return 'refactorfields'


def displayName(self): def displayName(self):
return self.tr('Refactor fields') return self.tr('Refactor fields')


def processAlgorithm(self, parameters, context, feedback): def outputName(self):
layer = self.getParameterValue(self.INPUT_LAYER) return self.tr('Refactored')
mapping = self.getParameterValue(self.FIELDS_MAPPING)
output = self.getOutputFromName(self.OUTPUT_LAYER)


layer = QgsProcessingUtils.mapLayerFromString(layer, context) def parameterAsFieldsMapping(self, parameters, name, context):
fields = QgsFields() return parameters[name]
expressions = []
def prepareAlgorithm(self, parameters, context, feedback):
source = self.parameterAsSource(parameters, 'INPUT', context)
mapping = self.parameterAsFieldsMapping(parameters, self.FIELDS_MAPPING, context)

self.fields = QgsFields()
self.expressions = []


da = QgsDistanceArea() da = QgsDistanceArea()
da.setSourceCrs(layer.crs()) da.setSourceCrs(source.sourceCrs())
da.setEllipsoid(context.project().ellipsoid()) da.setEllipsoid(context.project().ellipsoid())


exp_context = layer.createExpressionContext()

for field_def in mapping: for field_def in mapping:
fields.append(QgsField(field_def['name'], self.fields.append(QgsField(name=field_def['name'],
field_def['type'], type=field_def['type'],
field_def['length'], typeName="",
field_def['precision'])) len=field_def.get('length', 0),

prec=field_def.get('precision', 0)))
expression = QgsExpression(field_def['expression']) expression = QgsExpression(field_def['expression'])
expression.setGeomCalculator(da) expression.setGeomCalculator(da)
expression.setDistanceUnits(context.project().distanceUnits()) expression.setDistanceUnits(context.project().distanceUnits())
expression.setAreaUnits(context.project().areaUnits()) expression.setAreaUnits(context.project().areaUnits())
expression.prepare(exp_context)
if expression.hasParserError(): if expression.hasParserError():
raise GeoAlgorithmExecutionException( raise QgsProcessingException(
self.tr(u'Parser error in expression "{}": {}') self.tr(u'Parser error in expression "{}": {}')
.format(str(expression.expression()), .format(str(expression.expression()),
str(expression.parserErrorString()))) str(expression.parserErrorString())))
expressions.append(expression) self.expressions.append(expression)

return True
writer = output.getVectorWriter(fields, layer.wkbType(), layer.crs(), context)

def outputFields(self, inputFields):
# Create output vector layer with new attributes return self.fields
error_exp = None
inFeat = QgsFeature() def processAlgorithm(self, parameters, context, feeback):
outFeat = QgsFeature() # create an expression context using thead safe processing context
features = QgsProcessingUtils.getFeatures(layer, context) self.expr_context = self.createExpressionContext(parameters, context)
count = QgsProcessingUtils.featureCount(layer, context) for expression in self.expressions:
if count > 0: expression.prepare(self.expr_context)
total = 100.0 / count self._row_number = 0
for current, inFeat in enumerate(features): return super().processAlgorithm(parameters, context, feeback)
rownum = current + 1

def processFeature(self, feature, feedback):
geometry = inFeat.geometry() attributes = []
outFeat.setGeometry(geometry) for expression in self.expressions:

self.expr_context.setFeature(feature)
attrs = [] self.expr_context.lastScope().setVariable("row_number", self._row_number)
for i in range(0, len(mapping)): value = expression.evaluate(self.expr_context)
field_def = mapping[i] if expression.hasEvalError():
expression = expressions[i] raise QgsProcessingException(
exp_context.setFeature(inFeat) self.tr(u'Evaluation error in expression "{}": {}')
exp_context.lastScope().setVariable("row_number", rownum) .format(str(expression.expression()),
value = expression.evaluate(exp_context) str(expression.parserErrorString())))
if expression.hasEvalError(): attributes.append(value)
error_exp = expression feature.setAttributes(attributes)
break self._row_number += 1

return feature
attrs.append(value)
outFeat.setAttributes(attrs)

writer.addFeature(outFeat, QgsFeatureSink.FastInsert)

feedback.setProgress(int(current * total))
else:
feedback.setProgress(100)

del writer

if error_exp is not None:
raise GeoAlgorithmExecutionException(
self.tr(u'Evaluation error in expression "{}": {}')
.format(str(error_exp.expression()),
str(error_exp.parserErrorString())))
3 changes: 2 additions & 1 deletion python/plugins/processing/algs/qgis/QGISAlgorithmProvider.py
Expand Up @@ -160,7 +160,7 @@
# from .SetRasterStyle import SetRasterStyle # from .SetRasterStyle import SetRasterStyle
# from .SelectByAttributeSum import SelectByAttributeSum # from .SelectByAttributeSum import SelectByAttributeSum
# from .HypsometricCurves import HypsometricCurves # from .HypsometricCurves import HypsometricCurves
# from .FieldsMapper import FieldsMapper from .FieldsMapper import FieldsMapper
# from .Datasources2Vrt import Datasources2Vrt # from .Datasources2Vrt import Datasources2Vrt
# from .OrientedMinimumBoundingBox import OrientedMinimumBoundingBox # from .OrientedMinimumBoundingBox import OrientedMinimumBoundingBox
# from .DefineProjection import DefineProjection # from .DefineProjection import DefineProjection
Expand Down Expand Up @@ -231,6 +231,7 @@ def getAlgs(self):
ExtentFromLayer(), ExtentFromLayer(),
ExtractNodes(), ExtractNodes(),
ExtractSpecificNodes(), ExtractSpecificNodes(),
FieldsMapper(),
FixedDistanceBuffer(), FixedDistanceBuffer(),
FixGeometry(), FixGeometry(),
GeometryByExpression(), GeometryByExpression(),
Expand Down

0 comments on commit b3a9e46

Please sign in to comment.