0

I want to calculate area of all polygon features using Field Geometry function of QGIS 3.22 version. But somehow it always gives an import QGIS error, but when I tried to do a simple buffer of a vector layer in same Jupyter Notebook environment it worked.

import time
from qgis.core import (
    QgsApplication,
    QgsVectorLayer,
    QgsFields,
    QgsField,
    QgsFeature,
    QgsGeometry,
    QgsProject,
    QgsVectorFileWriter,
)
import processing

def calculate_area_with_qgis(vector_layer_path, output_layer_path):
    # Initialize QGIS application
    QgsApplication.setPrefixPath("C:/Program Files/QGIS 3.22.5/apps/gis-ltr/qgiscrashhandler.exe", True)
    os.environ['QGIS_PREFIX_PATH'] = 'C:/Program Files/QGIS 3.22.5'

    QgsApplication.initQgis()

    # Load the vector layer
    vector_layer = QgsVectorLayer(vector_layer_path, "vector_layer", "ogr")
    if not vector_layer.isValid():
        print("Failed to load the vector layer")
        return None

    # Set up the field calculator parameters
    parameters = {
        'INPUT': vector_layer,
        'FIELD_NAME': 'AREA',
        'FIELD_TYPE': 0,  # Double
        'FIELD_LENGTH': 10,
        'FIELD_PRECISION': 3,
        'FORMULA': '$area',
        'OUTPUT': output_layer_path
    }

    # Run the field calculator algorithm
    start_time = time.time()
    processing.run("native:fieldcalculator", parameters)
    end_time = time.time()
    elapsed_time = end_time - start_time

    # Exit QGIS application
    QgsApplication.exitQgis()

    return elapsed_time

vector_layer_path = r"C:/Users/schakraborty/OneDrive - RMS/Desktop/INDUSTRIES/South Africa/Provinces/Kwaza_u_natul/Output/try_xyz/kwaza_natul_merged.shp"
output_layer_path = r"C:/Users/schakraborty/OneDrive - RMS/Desktop/INDUSTRIES/South Africa/Provinces/Kwaza_u_natul/Output/try_xyz/kwaza_natul_merged_area.shp"

elapsed_time = calculate_area_with_qgis(vector_layer_path, output_layer_path)
print(f"Elapsed time: {elapsed_time} seconds")

The error is coming as this -

ImportError Traceback (most recent call last)
Cell In[4], line 12
      1 import time
      2 from qgis.core import (
      3     QgsApplication,
      4     QgsVectorLayer,
   (...)
     10     QgsVectorFileWriter,
     11 )
---> 12 import processing
     14 def calculate_area_with_qgis(vector_layer_path, output_layer_path):
     15     # Initialize QGIS application
     16     QgsApplication.setPrefixPath("C:/Program Files/QGIS 3.22.5/apps/gis-ltr/qgiscrashhandler.exe", True)

File ~\AppData\Local\anaconda3\envs\testing1\Library\python\qgis\utils.py:888, in _import(name, globals, locals, fromlist, level)
    884                     _RemoveDllDirectory(_import_paths.pop(p))
    886             _import_path = new_path
--> 888 mod = _builtin_import(name, globals, locals, fromlist, level)
    890 if mod and getattr(mod, '__file__', None):
    891     module_name = mod.__name__ if fromlist else name


File ~\AppData\Local\anaconda3\envs\testing1\Library\python\qgis\analysis\__init__.py:26
     22 __copyright__ = '(C) 2014, Nathan Woodrow'
     24 from qgis.PyQt import QtCore
---> 26 from qgis._analysis import *
     28 # preserve API compatibility following QgsExifTools moved to core
     29 from qgis.core import QgsExifTools

File ~\AppData\Local\anaconda3\envs\testing1\Library\python\qgis\utils.py:888, in _import(name, globals, locals, fromlist, level)
    884                     _RemoveDllDirectory(_import_paths.pop(p))
    886             _import_path = new_path
--> 888 mod = _builtin_import(name, globals, locals, fromlist, level)
    890 if mod and getattr(mod, '__file__', None):
    891     module_name = mod.__name__ if fromlist else name

ImportError: DLL load failed while importing _analysis: The specified module could not be found.
4
  • Right now your code is half formatted and unclear here, could you edit the question to make sure it is easy to understand? Jun 22, 2023 at 10:28
  • I seem to recall when doing some testing that the qgis toolbox/processing algorithms are not loaded by default. In other words, QgsApplication.initQgis(), does some critical initialization but is not sufficient. Compare output of QgsApplication.processingRegistry().algorithms() in qgis console vs standalone Jun 22, 2023 at 22:50
  • from qgis.analysis import QgsNativeAlgorithms QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) reg = QgsApplication.processingRegistry() reg.algorithms() This will add content to the registtry and you can find the processing algorithm. To cal the algorithm still need more steps to call the algorithm Jun 22, 2023 at 23:20
  • @GaultDrakkor Cell In[3], line 15 QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()), ^ SyntaxError: invalid syntax Jun 26, 2023 at 6:51

1 Answer 1

0
Since I couldn't format well in a comment:

This is partial answer in terms of going from processing functions not available to being available. Including an example use.

What functions to call was taken from test_qgsprocessinginplace.py

Ubuntu Linux so adjust prefix path as needed.

    import qgis.core as core
    core.QgsApplication.setPrefixPath("/usr", True)
    qgs = core.QgsApplication([], False)
    qgs.initQgis()
    register = core.QgsApplication.processingRegistry()
    print(len(register.algorithms()))
    from qgis.analysis import QgsNativeAlgorithms
    core.QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())
    print(len(register.algorithms()))
    algorithm_subset = [alg for alg in register.algorithms() if 'fieldcalculator' in alg.name()]
    print(len(algorithm_subset))
    if len(algorithm_subset) == 1:
       algorithm_subset[0].run
    alg = register.createAlgorithmById('native:creategrid')
    argz = {'TYPE':0,'EXTENT':'539540,540123,5446000,5446600 [EPSG:26900]',
        'HSPACING':250,'SPACING':500,'HOVERLAY':0,'VOVERLAY':0,
        'CRS':core.QgsCoordinateReferenceSystem('EPSG:26909'),'OUTPUT':'TEMPORARY_OUTPUT'}
    context = core.QgsProcessingContext()
    invalid_geometry_policy=core.QgsFeatureRequest.GeometryNoCheck
    context.setInvalidGeometryCheck(invalid_geometry_policy)
    context.setProject(core.QgsProject.instance())
    alg.asPythonCommand(argz, context)
    qgs.exitQgis()

I get number of algorithms going from zero to 238.

Addressing the exception reported in the question

If import processing is used outside of qgis I get import error

In qgis python console: processing <module 'processing' from '/usr/share/qgis/python/plugins/processing/init.py'>

So can't use import processing in the script.

2
  • But I want to use outside of qgis in virtual environment where I installed qgis using conda, and the buffer program is working fine. for feature in vector_layer.getFeatures(): # Get the geometry of the feature geometry = feature.geometry() # Create the buffer geometry buffer_geometry = geometry.buffer(buffer_distance, 5) # 8 represents the number of segments for the buffer # Create a new feature with the buffer geometry buffer_feature = QgsFeature(fields) buffer_feature.setGeometry(buffer_geometry) Jun 27, 2023 at 5:54
  • @soumikchakraborty I edited the answer to fix some bugs and add an example of calling processing item. I tested the code of my answer in both stand alone and running in a conda environment. My answer answers the original question of import error and running native functions. I am ignoring the buffer stuff. Jun 27, 2023 at 20:24

Your Answer

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

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