Skip to content

Requirements

⚠️ This tutorial is not about python in general, neither about how tu use python for GIS, but only about using python to interact with Qgis.

CRS

Today we will work on Madagascar. Let us first find an good CRS for this area. The CRS should be a projected system.

PyQgis

Qgis comes with its own python distribution. You can open a console by clicking on Python icon.

Check that python is there by typing print("Hello world") and press Enter.

Now open the script editor by clicking on Editor icon., and save the script on your computer.

Again, type print("Hello world") and execute the script by clicking on Python icon.

Preamble

In the preamble, we want to:

This gives the following:

# path to the working directory
path = 'path/to/the/folder'

# crs of the country
epsg =

# set project crs
crs = QgsCoordinateReferenceSystem(epsg)
QgsProject.instance().setCrs(crs)

# clear work space
QgsProject.instance().removeAllMapLayers()

Load the data

Now let us load the administrative shapefile, the TRMM raster and vizualize the two.

# Load the admin vector layer
admin = QgsVectorLayer(path + '/rawdata/Madagascar/MDG_adm2.shp', 'admin', 'ogr')
print('admin', admin.isValid())

# Load the TMMM raster layer
trmm = QgsRasterLayer(path + '/rawdata/TRMM/trmm_proj.tif', 'TRMM')
print('TRMM', trmm.isValid())

# Vizualize the layers
QgsProject.instance().addMapLayers([admin, trmm])

⚠️ Each time you load a new layer, you need to run layer.isValid(). Having a print is just for convenience.

Algorithms

The main objective of this tutorial is to have a script that make the kind of procedure we had last week replicable. Today, we will compute zonal statistics of the TRMM file for the administrative regions of Madagascar, with a slightly different approach. Here is the roadmap:

  1. Reproject the administrative layer
  2. Clip the raster data to the administrative regions
    1. Create a buffer around the regions
    2. Clip the data to the buffers
  3. Transform the raster pixels to polygons
  4. Interesect this grid with the administrative regions
  5. Computing the area of each feature and save it as an attribute

 

Using any algorithm

The general way to use a Qgis algorithm is

params = {
    'PARAM1': val1,
    'PARAM2': val2,
    ...
}

processing.run('module:algorithm', params)

If you pass your mouse on any alogrithm on the toolbox, you should see something like Algorithm ID module:algorithm.

Now using the console, you can access the documentation of the algorithm by typing processing.algorithmHelp("module:algorithm").

If you run an alogrithm manually, you can check the log to simply copy-paste the parameters that were used.

Now you can follow the roadmap to write your own script!

← back