0

I'm trying to run a processing script in QGIS 3.4.

It doesn't complete because it seems that step 3 is not generated. A few seconds later (after I got the error), QGIS completely crashes (I get the crash window with the options to close or reload. )

Is the script causing this issue? If so, how can I make it run properly? I assume the main issue should be between the chair and the keyboard as I have very little experience with PyQgis.

The working example :

from qgis.core import *
from qgis.gui import *
from qgis.utils import iface
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import os
import processing
from datetime import datetime
import subprocess
import glob
import shutil
import re
import qgis.core

class IntensityMap(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.

    INPUT1 = 'INPUT1'
    INPUT2 = 'INPUT2'
    INPUT3 = 'INPUT3'
    INPUT4 = 'INPUT4'
    Extent = 'Extent'
    OUTPUT1 = 'OUTPUT1'
    OUTPUT2 = 'OUTPUT2'
    OUTPUT3 = 'OUTPUT3'
    OUTPUT4 = 'OUTPUT4'


    def __init__(self):
        super().__init__()

    def tr(self, string):
        """
        Returns a translatable string with the self.tr() function.
        """
        return QCoreApplication.translate('Processing', string)

    def helpUrl(self):
        return "https://qgis.org"

    def shortHelpString(self):
        return self.tr("My Script")

    def createInstance(self):
        return type(self)()

    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 'gisscript'

    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('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 'homemadescripts'

    def initAlgorithm(self, config=None):
        """
        Here we define the inputs and output of the algorithm, along
        with some other properties.
        """
        self.addParameter(QgsProcessingParameterRasterLayer(
            self.INPUT1,
            self.tr("Input 1"), None, False))       
        self.addParameter(QgsProcessingParameterRasterLayer(
            self.INPUT2,
            self.tr("Input 2"), None, False))
        self.addParameter(QgsProcessingParameterRasterLayer(
            self.INPUT3,
            self.tr("Input 3"), None, False))
        self.addParameter(QgsProcessingParameterRasterLayer(
            self.INPUT4,
            self.tr("Input 4"), None, True))    
        self.addParameter(QgsProcessingParameterRasterLayer(
            self.Extent,
            self.tr("Extent"), None, True))

    def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """         
        #"*********************************************************************************************************************************************
        #1. initialisations
        vals_reclass= ['0.01,1,1,1,5,2,5,1000,3', '0.01,2,1,2,10,2,10,1000,3','0.01,20,1,20,100,2,100,1000,3','0.01,1000,0']
        i = 0
        tm = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        rootTempPath=QgsProcessingUtils.generateTempFilename("step")

        print ("Start: " + tm)


        INPUT1 = self.parameterAsRasterLayer(parameters, self.INPUT1, context)
        INPUT2 = self.parameterAsRasterLayer(parameters, self.INPUT2, context)
        INPUT3 = self.parameterAsRasterLayer(parameters, self.INPUT3, context)
        INPUT4 = self.parameterAsRasterLayer(parameters, self.INPUT4, context)
        Extent_calcul = self.Extent



        #If input 4 is not provided
        if INPUT4:
            layers_h=[INPUT1, INPUT2, INPUT3, INPUT4]
        else:
            layers_h=[INPUT1, INPUT2, INPUT3]

        #Projects' CRS definition 
        canvas = iface.mapCanvas()
        #ProjectCRS=canvas.mapRenderer().destinationCrs().authid()
        #Qgis3.0
        ProjectCRS=QgsCoordinateReferenceSystem("EPSG:2056")

        for strs in layers_h:
            #print (strs)
            #print (strs.name())
            #Extent definition for GRASS
            e = strs.extent()
            mapExtent=str(e.xMinimum())+','+str(e.xMaximum())+','+str(e.yMinimum())+','+str(e.yMaximum())


            #*********************************************************************************************************************************************
            #2. STEP 1

            #processing.algorithmHelp("saga:reclassifyvalues")

            reclassifyParameters = { 'INPUT':strs, 
                                        'METHOD':2, 
                                        'OLD':0, 
                                        'NEW':0, 
                                        'SOPERATOR':0, 
                                        'MIN':0,
                                        'MAX':0, 
                                        'RNEW':0, 
                                        'ROPERATOR':0, 
                                        'RETAB':vals_reclass[i], 
                                        'TOPERATOR':0, 
                                        'NODATAOPT':1, 
                                        'NODATA':-99999, 
                                        'OTHEROPT':1, 
                                        'OTHERS':-99999, 
                                        #'RESULT':'memory:' }
                                        'RESULT': QgsProcessingUtils.generateTempFilename("step2_"+str(i)+".sdat")}
            STEP_2=processing.run('saga:reclassifyvalues',reclassifyParameters)

            #print ("Couche " + str(i) + "; 2 ok")

            #*********************************************************************************************************************************************
            #3. Vectorisation
            #processing.algorithmHelp("gdal:polygonize")


            VectorisationParameters = { 'INPUT':STEP_2['RESULT'],
                                            'BAND':1,
                                            'FIELD':'DN',
                                            'EIGHT_CONNECTEDNESS':True,
                                            'OUTPUT':rootTempPath+"3_"+str(i)+".shp"}
            #print("bip")
            STEP_3=processing.run('gdal:polygonize', VectorisationParameters)
            #print("bip")
            reprojectionParametersS3 = {'INPUT':STEP_3['OUTPUT'],
                                        'TARGET_CRS':ProjectCRS,
                                        'OUTPUT':rootTempPath+"3reproj_"+str(i)+".shp"}

            #print("bip")
            STEP_3b=processing.run("native:reprojectlayer", reprojectionParametersS3)           
            #print ("Couche " + str(i) + "; 3 ok")

            #*********************************************************************************************************************************************
            #4. Generalisation
            #processing.algorithmHelp("grass7:v.generalize")
            GeneralisationParameters1={'input':STEP_3b['OUTPUT'],
                                        'type':[0,1,2],
                                        'cats':'',
                                        'where':'',
                                        'method':10,
                                        'threshold':3,
                                        'look_ahead':7,
                                        'reduction':50,
                                        'slide':0.5,
                                        'angle_thresh':3,
                                        'closeness_thresh':0,
                                        'betweeness_thresh':0,
                                        'alpha':0.3,
                                        'beta':0.3,
                                        'iterations':3,
                                        'output':rootTempPath+"4_"+str(i)+".shp",
                                        'error':rootTempPath+"4_"+str(i)+"_err.shp",
                                        'GRASS_REGION_PARAMETER':None,
                                        'GRASS_SNAP_TOLERANCE_PARAMETER':0.1,
                                        'GRASS_MIN_AREA_PARAMETER':0.0001,
                                        'GRASS_OUTPUT_TYPE_PARAMETER':0,
                                        'GRASS_VECTOR_DSCO':'',
                                        'GRASS_VECTOR_LCO':''}

            #print("bip")
            STEP_4=processing.run("grass7:v.generalize",GeneralisationParameters1)
            #print("bip")
            #Put the layer back in the correct CRS after GRASS algorithm
            reprojectionParametersS4 = {'INPUT':STEP_4['output'],
                                        'TARGET_CRS':ProjectCRS,
                                        'OUTPUT':rootTempPath+"4reproj_"+str(i)+".shp"}
            #print("bip")
            STEP_4b=processing.run("native:reprojectlayer", reprojectionParametersS4)                                       
            #print ("Couche " + str(i) + "; 4 ok")

            #*********************************************************************************************************************************************
            #5. Cleaning

            #processing.algorithmHelp("grass7:v.clean")
            CleaningParameters={'input':STEP_4b['OUTPUT'],
                                    'type':[0,1,2,3,4,5,6],
                                    'tool':[0,10],
                                    'threshold':'0,20',
                                    '-b':False,
                                    '-c':False,
                                    'output':rootTempPath+"5_"+str(i)+".shp",
                                    'error':rootTempPath+"5_"+str(i)+"_err.shp",
                                    'GRASS_REGION_PARAMETER':None,
                                    'GRASS_SNAP_TOLERANCE_PARAMETER':-1,
                                    'GRASS_MIN_AREA_PARAMETER':0.0001,
                                    'GRASS_OUTPUT_TYPE_PARAMETER':0,
                                    'GRASS_VECTOR_DSCO':'',
                                    'GRASS_VECTOR_LCO':''}

            #print("bip")
            STEP_5=processing.run("grass7:v.clean",CleaningParameters)
            #Put the layer back in the correct CRS after GRASS algorithm
            reprojectionParametersS5 = {'INPUT':STEP_5['output'],
                                        'TARGET_CRS':ProjectCRS,
                                        'OUTPUT':rootTempPath+"4reproj_"+str(i)+".shp"}
            #print("bip")
            STEP_5b=processing.run("native:reprojectlayer", reprojectionParametersS5)               
            #print ("Couche " + str(i) + "; 5 ok")
            layers_out[i]=STEP_5b['OUTPUT']

            i = i+1

        results = {} 
        results[self.OUTPUT1]=layers_out[0]
        results[self.OUTPUT2]=layers_out[1]
        results[self.OUTPUT3]=layers_out[2]
        if INPUT4:
            results[self.OUTPUT4]=layers_out[3]

        return results
        tm = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        #print ("END: " + tm)

I get the following error :

Traceback (most recent call last):
File "E:\Divers\Qgis\Scripts_Qgis3_clean\myscript_v3_SE.py", line 241, in processAlgorithm
STEP_4b=processing.run("native:reprojectlayer", reprojectionParametersS4)
File "C:/OSGEO4~1/apps/qgis/./python/plugins\processing\tools\general.py", line 96, in run
return Processing.runAlgorithm(algOrName, parameters, onFinish, feedback, context)
File "C:/OSGEO4~1/apps/qgis/./python/plugins\processing\core\Processing.py", line 139, in runAlgorithm
raise QgsProcessingException(msg)
_core.QgsProcessingException: Unable to execute algorithm
Could not load source layer for INPUT: E:/System_Temp/processing_c085ab382a9c43d28a941d109b84c3f1/44fd11d9e4b14c2d8df25128bb56a83a/step4_0.shp not found

A few seconds later, the following window appears (without any additional actions from my part)

Qgis crash

  • Does it randomly crash or always or with specific input? – bugmenot123 Feb 6 at 9:15
  • I edited the question to show the error and the behaviour afterwards – Kantan Feb 6 at 10:10
  • 1
    I would recommend a divide and conquer approach. If it works up until just before step 4, take the output you gathered by then and make a script that only takes that and tries that single step. This will help you nail down the problem. – bugmenot123 Feb 6 at 11:58

Your Answer

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

Browse other questions tagged or ask your own question.