lunes, 28 de enero de 2013

Using selection algorithms

Among the long list of algorithms in SEXTANTE, selection algorithms are a very interesting group. Instead of producing new layers, they just modify the selection that exist in one of them. They cannot be used from the batch processing interface (since it works with layers that are not loaded in QGIS, so there is no selection at all), and using them from the SEXTANTE toolbox is not such an useful tool, but in the modeler and the Python console they can really help us simplify things and automate tasks.

This short post shows how to use them to automate a task that would otherwise involve a large amount of work,  but that can be solved this way with just a few lines. It is inspired by this question recently asked at StackOverflow

The problem is as follows: given a points layer (species) with the presence of different species, and a polygon layer(zones) with vegetation types, generate N new polygon layer, each one with the areas where each specie can be found.

Assuming that the specie represented at each point is stored in an attribute named specie, the following script will solve out problem

import sextante
import os
basefolder = "[put_your_destination_folder_here]"
species = sextante.runalg('qgis:listuniquevalues', 'species', 'specie', None)['UNIQUE_VALUES'].split(";")
for specie in species:
  sextante.runalg('qgis:selectbyattribute', 'species', 'specie', 0, specie)
  sextante.runalg('qgis:selectbylocation', 'zones', 'species', 0)
  filename = os.path.join(basefolder, specie + ".shp")
  sextante.runalg('qgis:saveselectedfeatures', 'zones', filename)

Just two selections, and then we save the resulting selected features to a file whose name is created from the name of the corresponding specie.

This should work on the just-released 1.0.9 version of SEXTANTE. Just make sure you do not enable executing in a separate thread, since it seems to still cause some strange errors when using the console, and it tends to freeze QGIS when a runalg command is put in a loop.

1 comentario:

  1. Ola.

    Someone pointed out Sextante to me. I'm trying to process several thousand features that I need to put a "donut hole" mask on to highlight the point of interest, and make the surrounding features less prominent for the prints.

    I haven't used Sextante. Can you help me by pointing out what I should do to make this happen?