1

I am using QGIS 3.

The following script code is generated from a model. At the end the code has to create a field Fl_m2, if the blnFl is true.

    if ['blnFl'] is True:

If it is not true the result has to be a memory layer without a field Fl_m2. The if-clause doesn't work properly.

All other steps fix, multipartToSinglepart, PolygonsToLines, SpatialJoin etc. has to run.

"""
Model exported as python.
Name : CloseGaps
Group : Büro F+K
With QGIS : 31100
"""

from qgis.core import QgsProcessing
from qgis.core import QgsProcessingAlgorithm
from qgis.core import QgsProcessingMultiStepFeedback
from qgis.core import QgsProcessingParameterExpression
from qgis.core import QgsProcessingParameterBoolean
from qgis.core import QgsProcessingParameterVectorLayer
from qgis.core import QgsProcessingParameterFeatureSink
from qgis.core import QgsProcessingParameterDefinition
import processing


class Closegaps(QgsProcessingAlgorithm):

    def initAlgorithm(self, config=None):
        param = QgsProcessingParameterBoolean('blnFl', 'blnFl', defaultValue=True)
        param.setFlags(param.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
        self.addParameter(param)
        param = QgsProcessingParameterExpression('aa', 'Kleinstpolygone ohne Sachdaten mit Nachbarpolygon verschmelzen (im SQL-Ausdruck ggf. nur den rechten Wert 5 ändern)', parentLayerParameterName='', defaultValue='\"dist_pole\" is null AND area($geometry)<5')
        param.setFlags(param.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
        self.addParameter(param)
        self.addParameter(QgsProcessingParameterVectorLayer('layerauswhlen', 'Layer_auswählen', types=[QgsProcessing.TypeVectorPolygon], defaultValue=None))
        param = QgsProcessingParameterExpression('sqlstaement', 'Kleinstpolygone mit Sachdaten mit Nachbarpolygon verschmelzen (ggf. nur den Wert 2 ändern)', parentLayerParameterName='', defaultValue='\"dist_pole\" is not null AND area($geometry)<2')
        param.setFlags(param.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
        self.addParameter(param)
        self.addParameter(QgsProcessingParameterFeatureSink('Resafterfielddrops', 'resAfterFieldDrops', type=QgsProcessing.TypeVectorAnyGeometry, createByDefault=True, defaultValue=None))
        self.addParameter(QgsProcessingParameterFeatureSink('Resfinal', 'resFinal', type=QgsProcessing.TypeVectorAnyGeometry, createByDefault=True, defaultValue=None))

    def processAlgorithm(self, parameters, context, model_feedback):
        # Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the
        # overall progress through the model
        feedback = QgsProcessingMultiStepFeedback(12, model_feedback)
        results = {}
        outputs = {}

        # Fix geometries
        alg_params = {
            'INPUT': parameters['layerauswhlen'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['FixGeometries'] = processing.run('native:fixgeometries', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}

        # Multipart to singleparts
        alg_params = {
            'INPUT': outputs['FixGeometries']['OUTPUT'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['MultipartToSingleparts'] = processing.run('native:multiparttosingleparts', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(2)
        if feedback.isCanceled():
            return {}

        # Pole of inaccessibility
        alg_params = {
            'INPUT': outputs['MultipartToSingleparts']['OUTPUT'],
            'TOLERANCE': 0.1,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['PoleOfInaccessibility'] = processing.run('qgis:poleofinaccessibility', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(3)
        if feedback.isCanceled():
            return {}

        # Polygons to lines
        alg_params = {
            'INPUT': outputs['MultipartToSingleparts']['OUTPUT'],
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['PolygonsToLines'] = processing.run('native:polygonstolines', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(4)
        if feedback.isCanceled():
            return {}

        # Polygonize
        alg_params = {
            'INPUT': outputs['PolygonsToLines']['OUTPUT'],
            'KEEP_FIELDS': False,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['Polygonize'] = processing.run('qgis:polygonize', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(5)
        if feedback.isCanceled():
            return {}

        # SpaitalJoin
        alg_params = {
            'DISCARD_NONMATCHING': False,
            'INPUT': outputs['Polygonize']['OUTPUT'],
            'JOIN': outputs['PoleOfInaccessibility']['OUTPUT'],
            'JOIN_FIELDS': None,
            'METHOD': 1,
            'PREDICATE': [0],
            'PREFIX': '',
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['Spaitaljoin'] = processing.run('qgis:joinattributesbylocation', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(6)
        if feedback.isCanceled():
            return {}

        # SelMitAttribute
        alg_params = {
            'EXPRESSION': parameters['sqlstaement'],
            'INPUT': outputs['Spaitaljoin']['OUTPUT'],
            'METHOD': 0
        }
        outputs['Selmitattribute'] = processing.run('qgis:selectbyexpression', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(7)
        if feedback.isCanceled():
            return {}

        # EliminateMitAttribute
        alg_params = {
            'INPUT': outputs['Selmitattribute']['OUTPUT'],
            'MODE': 2,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['Eliminatemitattribute'] = processing.run('qgis:eliminateselectedpolygons', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(8)
        if feedback.isCanceled():
            return {}

        # SelOhneAttribute
        alg_params = {
            'EXPRESSION': parameters['aa'],
            'INPUT': outputs['Eliminatemitattribute']['OUTPUT'],
            'METHOD': 0
        }
        outputs['Selohneattribute'] = processing.run('qgis:selectbyexpression', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(9)
        if feedback.isCanceled():
            return {}

        # EliminateOhneAttribute
        alg_params = {
            'INPUT': outputs['Selohneattribute']['OUTPUT'],
            'MODE': 2,
            'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
        }
        outputs['Eliminateohneattribute'] = processing.run('qgis:eliminateselectedpolygons', alg_params, context=context, feedback=feedback, is_child_algorithm=True)

        feedback.setCurrentStep(10)
        if feedback.isCanceled():
            return {}

        if ['blnFl'] is True:
            # FL_m2
            alg_params = {
                'FIELD_LENGTH': 10,
                'FIELD_NAME': 'Fl_m2',
                'FIELD_PRECISION': 0,
                'FIELD_TYPE': 1,
                'FORMULA': '$area',
                'INPUT': outputs['Eliminateohneattribute']['OUTPUT'],
                'NEW_FIELD': True,
                'OUTPUT': parameters['Resfinal']
            }
            outputs['Fl_m2'] = processing.run('qgis:fieldcalculator', alg_params, context=context, feedback=feedback, is_child_algorithm=True)
            results['Resfinal'] = outputs['Fl_m2']['OUTPUT']

        # Drop field(s)
        alg_params = {
            'COLUMN': 'dist_pole',
            'INPUT': outputs['Eliminateohneattribute']['OUTPUT'],
            'OUTPUT': parameters['Resafterfielddrops']
        }
        outputs['DropFields'] = processing.run('qgis:deletecolumn', alg_params, context=context, feedback=feedback, is_child_algorithm=True)
        results['Resafterfielddrops'] = outputs['DropFields']['OUTPUT']

        feedback.setCurrentStep(11)
        if feedback.isCanceled():
            return {}

        return results

    def name(self):
        return 'CloseGaps'

    def displayName(self):
        return 'CloseGaps'

    def group(self):
        return 'Büro F+K'

    def groupId(self):
        return 'Büro F+K'

    def createInstance(self):
        return Closegaps()
2

['blnFl'] is a list which includes one string item. A list which includes an item returns always True in if clause.

Add next line before if ['blnFl'] is True:

blnFl = self.parameterAsBool(parameters, "blnFl", context)

And change if ['blnFl'] is True: as if blnFl is True:

blnFl = self.parameterAsBool(parameters, "blnFl", context)
if blnFl is True:
    ...
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.