4

I use QGIS 3.10.14 and I begin with PyQGIS.

When I tried to make a simple script which use the native buffer algorithm, the output layer came out exactly like the input layer, with the same polygons without geometrical change.

The exact same thing happens when I just run the script from the base template. I just changed the 'DISTANCE' parameter to 1500 to clearly see if there was a change.

Here is the code of the template:

# -*- coding: utf-8 -*-
"""
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (QgsProcessing,
 QgsFeatureSink,
 QgsProcessingException,
 QgsProcessingAlgorithm,
 QgsProcessingParameterFeatureSource,
 QgsProcessingParameterFeatureSink)
from qgis import processing
class ExampleProcessingAlgorithm(QgsProcessingAlgorithm):
 """
 This is an example algorithm that takes a vector layer and
 creates a new identical one.
 It is meant to be used as an example of how to create your own
 algorithms and explain methods and variables used to do it. An
 algorithm like this will be available in all elements, and there
 is not need for additional work.
 All Processing algorithms should extend the QgsProcessingAlgorithm
 class.
 """
 # Constants used to refer to parameters and outputs. They will be
 # used when calling the algorithm from another algorithm, or when
 # calling from the QGIS console.
 INPUT = 'INPUT'
 OUTPUT = 'OUTPUT'
 def tr(self, string):
 """
 Returns a translatable string with the self.tr() function.
 """
 return QCoreApplication.translate('Processing', string)
 def createInstance(self):
 return ExampleProcessingAlgorithm()
 def name(self):
 """
 Returns the algorithm name, used for identifying the algorithm. This
 string should be fixed for the algorithm, and must not be localised.
 The name should be unique within each provider. Names should contain
 lowercase alphanumeric characters only and no spaces or other
 formatting characters.
 """
 return 'myscript'
 def displayName(self):
 """
 Returns the translated algorithm name, which should be used for any
 user-visible display of the algorithm name.
 """
 return self.tr('My Script')
 def group(self):
 """
 Returns the name of the group this algorithm belongs to. This string
 should be localised.
 """
 return self.tr('Example scripts')
 def groupId(self):
 """
 Returns the unique ID of the group this algorithm belongs to. This
 string should be fixed for the algorithm, and must not be localised.
 The group id should be unique within each provider. Group id should
 contain lowercase alphanumeric characters only and no spaces or other
 formatting characters.
 """
 return 'examplescripts'
 def shortHelpString(self):
 """
 Returns a localised short helper string for the algorithm. This string
 should provide a basic description about what the algorithm does and the
 parameters and outputs associated with it..
 """
 return self.tr("Example algorithm short description")
 def initAlgorithm(self, config=None):
 """
 Here we define the inputs and output of the algorithm, along
 with some other properties.
 """
 # We add the input vector features source. It can have any kind of
 # geometry.
 self.addParameter(
 QgsProcessingParameterFeatureSource(
 self.INPUT,
 self.tr('Input layer'),
 [QgsProcessing.TypeVectorAnyGeometry]
 )
 )
 # We add a feature sink in which to store our processed features (this
 # usually takes the form of a newly created vector layer when the
 # algorithm is run in QGIS).
 self.addParameter(
 QgsProcessingParameterFeatureSink(
 self.OUTPUT,
 self.tr('Output layer')
 )
 )
 def processAlgorithm(self, parameters, context, feedback):
 """
 Here is where the processing itself takes place.
 """
 # Retrieve the feature source and sink. The 'dest_id' variable is used
 # to uniquely identify the feature sink, and must be included in the
 # dictionary returned by the processAlgorithm function.
 source = self.parameterAsSource(
 parameters,
 self.INPUT,
 context
 )
 # If source was not found, throw an exception to indicate that the algorithm
 # encountered a fatal error. The exception text can be any string, but in this
 # case we use the pre-built invalidSourceError method to return a standard
 # helper text for when a source cannot be evaluated
 if source is None:
 raise QgsProcessingException(self.invalidSourceError(parameters, self.INPUT))
 (sink, dest_id) = self.parameterAsSink(
 parameters,
 self.OUTPUT,
 context,
 source.fields(),
 source.wkbType(),
 source.sourceCrs()
 )
 # Send some information to the user
 feedback.pushInfo('CRS is {}'.format(source.sourceCrs().authid()))
 # If sink was not created, throw an exception to indicate that the algorithm
 # encountered a fatal error. The exception text can be any string, but in this
 # case we use the pre-built invalidSinkError method to return a standard
 # helper text for when a sink cannot be evaluated
 if sink is None:
 raise QgsProcessingException(self.invalidSinkError(parameters, self.OUTPUT))
 # Compute the number of steps to display within the progress bar and
 # get features from source
 total = 100.0 / source.featureCount() if source.featureCount() else 0
 features = source.getFeatures()
 for current, feature in enumerate(features):
 # Stop the algorithm if cancel button has been clicked
 if feedback.isCanceled():
 break
 # Add a feature in the sink
 sink.addFeature(feature, QgsFeatureSink.FastInsert)
 # Update the progress bar
 feedback.setProgress(int(current * total))
 # To run another Processing algorithm as part of this algorithm, you can use
 # processing.run(...). Make sure you pass the current context and feedback
 # to processing.run to ensure that all temporary layer outputs are available
 # to the executed algorithm, and that the executed algorithm can send feedback
 # reports to the user (and correctly handle cancellation and progress reports!)
 if False:
 buffered_layer = processing.run("native:buffer", {
 'INPUT': dest_id,
 'DISTANCE': 1500,
 'SEGMENTS': 5,
 'END_CAP_STYLE': 0,
 'JOIN_STYLE': 0,
 'MITER_LIMIT': 2,
 'DISSOLVE': False,
 'OUTPUT': 'memory:'
 }, context=context, feedback=feedback)['OUTPUT']
 # Return the results of the algorithm. In this case our only result is
 # the feature sink which contains the processed features, but some
 # algorithms may return multiple feature sinks, calculated numeric
 # statistics, etc. These should all be included in the returned
 # dictionary, with keys matching the feature corresponding parameter
 # or output names.
 return {self.OUTPUT: dest_id}

I have this warning when I launch QGIS:

WARNING Duplicate parameter coordinates registered for alg v.net.visibility

I don't have warning or error messages in the journal after running the script.

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Feb 13, 2021 at 18:25
5
  • There is an open issue about the warning you receive github.com/qgis/QGIS/issues/41030 Commented Feb 13, 2021 at 19:11
  • I tried the code with a polygon layer and it worked well. Maybe the problem is because of your input layer. In my opinion, your input layer crs is something like EPSG:3857 and your project crs is something like EPSG:4326. This is problem. In my case, I used 15000 m as distance and it was slightly little different than input. if you use same crs, it will be solved. Commented Feb 14, 2021 at 15:33
  • I just checked, the project seems to take input layer crs when I add it in. I also tried a layer with default project crs EPSG:4326 but it still doesn't change my output geometry. Commented Feb 14, 2021 at 18:24
  • In the code, you are getting the 'dest_id' not buffered_layer. "return {self.OUTPUT: dest_id}" Commented Feb 15, 2021 at 4:32
  • It didn't work, I got the error "UnboundLocalError: local variable 'buffered_layer' referenced before assignment". Even if it didn't work, I thank you for your help. I must add some information: I installed QGIS and my shapes on the second hard drive of my computer. However, I would have got an error if some tool was misplaced. Commented Feb 15, 2021 at 21:34

2 Answers 2

2

There are 2 things that I think aren't correct. First "if False:" part and second "return..". Meaning of "if False:" is that "don't run the code below this statement". So "the buffer processing algorithm" will never be executed. You should change it to "if True:" or just delete if statement. Second is that you return the input layer "dest_id". You should change it to "return {self.OUTPUT: buffered_layer}". If you get any error, please run the following code in Qgis/Python Console. You can open it with pressing "Ctrl+Alt+P" when Qgis opened.

#Just replace your layer name in Qgis with 'my_input_layer'.
dest_id = QgsProject().instance().mapLayersByName('my_input_layer')[0]
buffered_layer = processing.run("native:buffer", {
 'INPUT': dest_id,
 'DISTANCE': 1,
 'SEGMENTS': 5,
 'END_CAP_STYLE': 0,
 'JOIN_STYLE': 0,
 'MITER_LIMIT': 2,
 'DISSOLVE': False,
 'OUTPUT': 'memory:'
 })['OUTPUT']
QgsProject().instance().addMapLayer(buffered_layer)

By the way, Distance parameter is very sensitive to Crs.

answered Feb 16, 2021 at 18:31
4
  • I tried to delete the "if False" and changed "return {self.OUTPUT:dest_id)" to "return {self.OUTPUT: buffered_layer}" but QGIS crashed with the "unexpectedly ended" window. I think it's because buffered_layer is already the 'OUTPUT' of the algorithm and QGIS is searching the self.OUTPUT of the layer, which doesn't exist. If I write "return buffered_layer" instead, I get this error : "TypeError: invalid result from ExampleProcessingAlgorithm.processAlgorithm(), QgsVectorLayer cannot be converted to a C/C++ QVariantMap in this context". Commented Feb 18, 2021 at 18:43
  • I tried your code but it didn't work too. The algorithm run without ending. When I replace QgsProject().instance().addMapLayer(buffered_layer) by the return function I get an output layer but still without buffer. Commented Feb 18, 2021 at 18:45
  • Please watch this video: youtu.be/0YQNfWeybRE Commented Feb 18, 2021 at 19:10
  • 1
    I did like everything you did in your video and it worked! But I also wanted the user to chose their layer in a window instead of writing it directly inside the script. I used the help of Underdark tutorial here and it did help on this point : anitagraser.com/… Don't know why the sink doesn't work as intended with the base template of QGIS though. Anyway I consider my problem resolved and I will post my final code. Thank you for your help. Commented Feb 20, 2021 at 17:54
1

Here is the final code that resolved the problem:

# -*- coding: utf-8 -*-
"""
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (QgsProcessing,
 QgsProcessingException,
 QgsProcessingAlgorithm,
 QgsProcessingParameterFeatureSource,
 QgsProcessingParameterVectorDestination)
from qgis import processing
class ExampleProcessingAlgorithm(QgsProcessingAlgorithm):
 """
 This is an example algorithm that takes a vector layer and
 creates a new identical one.
 It is meant to be used as an example of how to create your own
 algorithms and explain methods and variables used to do it. An
 algorithm like this will be available in all elements, and there
 is not need for additional work.
 All Processing algorithms should extend the QgsProcessingAlgorithm
 class.
 """
 # Constants used to refer to parameters and outputs. They will be
 # used when calling the algorithm from another algorithm, or when
 # calling from the QGIS console.
 INPUT = 'INPUT'
 OUTPUT = 'OUTPUT'
 def tr(self, string):
 """
 Returns a translatable string with the self.tr() function.
 """
 return QCoreApplication.translate('Processing', string)
 def createInstance(self):
 return ExampleProcessingAlgorithm()
 def name(self):
 """
 Returns the algorithm name, used for identifying the algorithm. This
 string should be fixed for the algorithm, and must not be localised.
 The name should be unique within each provider. Names should contain
 lowercase alphanumeric characters only and no spaces or other
 formatting characters.
 """
 return 'myscript'
 def displayName(self):
 """
 Returns the translated algorithm name, which should be used for any
 user-visible display of the algorithm name.
 """
 return self.tr('My Script')
 def group(self):
 """
 Returns the name of the group this algorithm belongs to. This string
 should be localised.
 """
 return self.tr('Example scripts')
 def groupId(self):
 """
 Returns the unique ID of the group this algorithm belongs to. This
 string should be fixed for the algorithm, and must not be localised.
 The group id should be unique within each provider. Group id should
 contain lowercase alphanumeric characters only and no spaces or other
 formatting characters.
 """
 return 'examplescripts'
 def shortHelpString(self):
 """
 Returns a localised short helper string for the algorithm. This string
 should provide a basic description about what the algorithm does and the
 parameters and outputs associated with it..
 """
 return self.tr("Example algorithm short description")
 def initAlgorithm(self, config=None):
 """
 Here we define the inputs and output of the algorithm, along
 with some other properties.
 """
 # We add the input vector features source. It can have any kind of
 # geometry.
 self.addParameter(
 QgsProcessingParameterFeatureSource(
 self.INPUT,
 self.tr('Input layer'),
 [QgsProcessing.TypeVectorAnyGeometry]
 )
 )
 # We add a feature sink in which to store our processed features (this
 # usually takes the form of a newly created vector layer when the
 # algorithm is run in QGIS).
 self.addParameter(
 QgsProcessingParameterVectorDestination(
 self.OUTPUT,
 self.tr('Output layer')
 )
 )
 def processAlgorithm(self, parameters, context, feedback):
 """
 Here is where the processing itself takes place.
 """
 # To run another Processing algorithm as part of this algorithm, you can use
 # processing.run(...). Make sure you pass the current context and feedback
 # to processing.run to ensure that all temporary layer outputs are available
 # to the executed algorithm, and that the executed algorithm can send feedback
 # reports to the user (and correctly handle cancellation and progress reports!)
 outputFile = self.parameterAsOutputLayer(parameters, self.OUTPUT, context)
 buffered_layer = processing.run("native:buffer", {
 'INPUT': parameters['INPUT'],
 'DISTANCE': 1500,
 'SEGMENTS': 5,
 'END_CAP_STYLE': 0,
 'JOIN_STYLE': 0,
 'MITER_LIMIT': 2,
 'DISSOLVE': False,
 'OUTPUT': outputFile
 }, is_child_algorithm=True, context=context, feedback=feedback)['OUTPUT']
 # Return the results of the algorithm. In this case our only result is
 # the feature sink which contains the processed features, but some
 # algorithms may return multiple feature sinks, calculated numeric
 # statistics, etc. These should all be included in the returned
 # dictionary, with keys matching the feature corresponding parameter
 # or output names.
 return {self.OUTPUT: buffered_layer}

It seems to work on my system without sink. This code let the user choose their layer and then apply a buffer on it. Don't know why the base template doesn't work on my computer with sink but it works now.

answered Feb 20, 2021 at 18:05
2
  • 1
    FloSnow, thank you, your answer solved a problem I'd been working on for two weeks. Zonal stats and zonal histogram, I owe you a beer Commented Aug 12, 2023 at 4:07
  • Glad it helped you. ^^ Good luck for your project. Commented Aug 24, 2023 at 22:03

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.