3

I am developing a Python standalone script to process DEM in order to produce slope in vector format. I used PyQt5 to make a GUI to accept input data and parameters from user.

My script is like this:

from qgis.core import QgsApplication, QgsRasterLayer, QgsVectorLayer, QgsProcessingFeedback, QgsField, NULL
from qgis.analysis import QgsNativeAlgorithms

from PyQt5.QtWidgets import QDialog, QApplication, QFileDialog, QMessageBox
from PyQt5.QtCore import QFileInfo, QVariant

from subprocess import call

QgsApplication.setPrefixPath(r"C:\OSGeo4W64\apps\qgis", True)
qgs = QgsApplication([], True)
qgs.initQgis()

import processing
from processing.core.Processing import Processing
Processing.initialize()


class MyClass(QDialog):

    def __init__(self):
        """ Constructor """
        .
        .
        .
    .
    .
    .

    def createGrids(self):
        """ Create grids based on extent of DEM using qgis:creategrid """

        feedback = QgsProcessingFeedback()

        alg_params = {'CRS': 'EPSG:4326', 'EXTENT': self.demLayer, 'HOVERLAY': 0, 'HSPACING': 0.045, 'TYPE': 2, 'VOVERLAY': 0, 'VSPACING': 0.045, 'OUTPUT': gridOutput}
        CreateGrid = processing.run('qgis:creategrid', alg_params, feedback=feedback)
        gridLayer = QgsVectorLayer(CreateGrid['OUTPUT'])
        print(gridLayer.extent().xMinimum())
        .
        .
        .
    .
    .
    .
    def runMainAlgorithms(self):
        .
        .
        .
        countGrid = 1
        for bufferGrid in glob(self.bufferGridDir + "\\*.gpkg"):
            gridID = QFileInfo(bufferGrid).baseName() ### file name without extension
            self.listOfGrid.append(gridID)
            self.appendLogFile(f"{gridID} - start")

            ### Execute gdalwarp for clip and interpolation
            outputGdalWarp = clip_interpolation_Output_Dir + "\\" + self.demBaseName + "_" + gridID + ".tif"
            my_call = ['gdalwarp', '-of', 'GTiff', '-cutline', bufferGrid, '-crop_to_cutline', self.demDir, outputGdalWarp, '-t_srs', self.sourceCRS, '-tr', self.outputResolution, self.outputResolution, '-r', self.interpolationMethod, '-overwrite']
            call(my_call)
            self.appendLogFile(f"{gridID} - gdalwarp for clip and interpolation finished")
            .
            .
            .
            ### Add provider of QGIS native algorithms
            QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())

            ### Run QGIS native algorithms for smoothing and simplification
            feedback = QgsProcessingFeedback()
            smoothOutput = smoothing_simplification_Output_Dir + "\\" + QFileInfo(firstStepOutput).fileName()  ### file name including extension

            ### Fix geometries
            alg_params = {'INPUT': firstStepOutput, 'OUTPUT': 'memory:'}
            fixGeometry1 = processing.run('native:fixgeometries', alg_params, feedback=feedback)
            print("Fix Geometries finished")
            self.appendLogFile(f"{gridID} - QGIS fix geometry finished")

            ### Smooth
            alg_params = {'INPUT': fixGeometry1['OUTPUT'], 'ITERATIONS': int(self.smoothIteration), 'MAX_ANGLE': float(self.smoothMaxAngle), 'OFFSET': float(self.smoothOffset), 'OUTPUT': 'memory:'}
            smooth = processing.run('native:smoothgeometry', alg_params, feedback=feedback)
            print("Smooth finished")
            self.appendLogFile(f"{gridID} - QGIS smooth finished")
            .
            .
            .
            ### Remove provider of QGIS native algorithms
            QgsApplication.processingRegistry().removeProvider(QgsNativeAlgorithms())
            .
            .
            .
            ### Execute ogr2ogr for clip
            my_call = ['ogr2ogr', '-clipsrc', grid, '-clipsrclayer', gridmName, output, smoothOutput, simplifiedSHPName, '-f', 'ESRI Shapefile', '-t_srs', 'EPSG:3857', '-nlt', 'POLYGON', '-skipfailures', '-overwrite']
            command_call = call(my_call)
            .
            .
            .
        ### Delete layer registries from memory
        qgs.exitQgis()
    .
    .
    .
### Instantiate QApplication and show GUI
app = QApplication([])
mainWindow = MyClass()
mainWindow.show()
sys.exit(app.exec_())

createGrids method and runMainAlgorithms method are not connected to each other and are executed separately by different buttons in GUI. runMainAlgorithms method contatins some GDAL/OGR commands and QGIS native algorithms, and it works fine.

The problem is that once I run createGrids method, it does not execute QGIS processing algorithms (in this case qgis:creategrid). I thought Processing.initialize() enables to access all QGIS processing algorithms (not native algorithms), but I was not able to use the algorithms. Am I missing something here? QGIS processing algorithm is not executable inside runMainAlgorithms method either if I insert them.

Once I run createGrids methods, an error occurs like this:

_core.QgsProcessingException: Error: Algorithm qgis:creategrid not found
3

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.