The console allows advanced users to increase their productivity and perform complex operations that cannot be performed using any of the other GUI elements of the processing framework GUI. Models involving several algorithms can be defined using the command-line interface, and additional operations such as loops and conditional sentences can be added to create more flexible and powerful workflows.
There is not a proccesing console in QGIS, but all processing commands are available instead from the QGIS built-in Python console. That means that you can incorporate those command to your console work and connect processing algorithms to all the other features (including methods from the QGIS API) available from there.
The code that you can execute from the Python console, even if it does not call any specific processing method, can be converted into a new algorithm that you can later call from the toolbox, the graphical modeler or any other component, just like you do with any other algorithm. In fact, some algorithms that you can find in the toolbox are simple scripts.
In this chapter we will see how to use processing algorithms from the QGIS Python console, and also how to write your own algorithms using Python.
The first thing you have to do is to import the processing functions with the following line:
>>> import processing
Now, there is basically just one (interesting) thing you can do with that
from the console: to execute an algorithm. That is done using the runalg()
method, which takes the name of the algorithm to execute as its first parameter,
and then a variable number of additional parameter depending on the requirements
of the algorithm. So the first thing you need to know is the name of the algorithm
to execute. That is not the name you see in the toolbox, but rather a unique
command–line name. To find the right name for your algorithm, you can use the
algslist()
method. Type the following line in you console:
>>> processing.alglist()
Il risultato dovrebbe essere.
Accumulated Cost (Anisotropic)---------------->saga:accumulatedcost(anisotropic)
Accumulated Cost (Isotropic)------------------>saga:accumulatedcost(isotropic)
Add Coordinates to points--------------------->saga:addcoordinatestopoints
Add Grid Values to Points--------------------->saga:addgridvaluestopoints
Add Grid Values to Shapes--------------------->saga:addgridvaluestoshapes
Add Polygon Attributes to Points-------------->saga:addpolygonattributestopoints
Aggregate------------------------------------->saga:aggregate
Aggregate Point Observations------------------>saga:aggregatepointobservations
Aggregation Index----------------------------->saga:aggregationindex
Analytical Hierarchy Process------------------>saga:analyticalhierarchyprocess
Analytical Hillshading------------------------>saga:analyticalhillshading
Average With Mask 1--------------------------->saga:averagewithmask1
Average With Mask 2--------------------------->saga:averagewithmask2
Average With Thereshold 1--------------------->saga:averagewiththereshold1
Average With Thereshold 2--------------------->saga:averagewiththereshold2
Average With Thereshold 3--------------------->saga:averagewiththereshold3
B-Spline Approximation------------------------>saga:b-splineapproximation
...
Questa è la lista di tutti gli algoritmi disponibili in ordine alfabetico, con il corrispondente nome da utilizzare nella riga di comando.
È possibile utilizzare una stringa come parametro per questo comando. Invece di restituire l’elenco completo degli algoritmi, verranno visualizzati solo quelli che includono tale stringa. Se, per esempio, si sta cercando un algoritmo per calcolare la pendenza da un DEM, si digiti ``alglist (“slope”) ” per ottenere il seguente risultato:
DTM Filter (slope-based)---------------------->saga:dtmfilter(slope-based)
Downslope Distance Gradient------------------->saga:downslopedistancegradient
Relative Heights and Slope Positions---------->saga:relativeheightsandslopepositions
Slope Length---------------------------------->saga:slopelength
Slope, Aspect, Curvature---------------------->saga:slopeaspectcurvature
Upslope Area---------------------------------->saga:upslopearea
Vegetation Index[slope based]----------------->saga:vegetationindex[slopebased]
Il risultato potrebbe cambiare a seconda degli algoritmi che sono disponibili.
È più facile ora trovare l’algoritmo che si sta cercando e il suo nome da utilizzare nella riga di comando, in questo caso `` saga: slopeaspectcurvature ``.
Once you know the command-line name of the algorithm, the next thing to do is to
know the right syntax to execute it. That means knowing which parameters are
needed and the order in which they have to be passed when calling the runalg()
method. There is a method to describe an algorithm in detail, which can be
used to get a list of the parameters that an algorithms require and the outputs
that it will generate. To do it, you can use the alghelp(name_of_the_algorithm)
method. Use the command-line name of the algorithm, not the full descriptive name.
Chiamando la funzione saga:slopeaspectcurvature
come parametro, si otterrà la seguente descrizione.
>>> processing.alghelp("saga:slopeaspectcurvature")
ALGORITHM: Slope, Aspect, Curvature
ELEVATION <ParameterRaster>
METHOD <ParameterSelection>
SLOPE <OutputRaster>
ASPECT <OutputRaster>
CURV <OutputRaster>
HCURV <OutputRaster>
VCURV <OutputRaster>
Ora si ha tutto il necessario per eseguire qualsiasi algoritmo. Come già accennato, vi è solo un unico comando per eseguire algoritmi: `` runalg () ``. La sua sintassi è la seguente:
>>> processing.runalg(name_of_the_algorithm, param1, param2, ..., paramN,
Output1, Output2, ..., OutputN)
L’elenco dei parametri e degli output da aggiungere dipende dall’algoritmo che si desidera eseguire, ed è esattamente la lista che il comando `` alghelp () `` restituisce, nello stesso ordine, come mostrato.
Depending on the type of parameter, values are introduced differently. The next one is a quick review of how to introduce values for each type of input parameter:
Raster Layer, Vector Layer or Table. Simply use a string with the name that
identifies the data object to use (the name it has in the QGIS Table of
Contents) or a filename (if the corresponding layer is not opened, it will be
opened, but not added to the map canvas). If you have an instance of a QGIS
object representing the layer, you can also pass it as parameter. If the input
is optional and you do not want to use any data object, use None
.
Selection. If an algorithm has a selection parameter, the value of that
parameter should be entered using an integer value. To know the available
options, you can use the algoptions()
command, as shown in the following
example:
>>> processing.algoptions("saga:slopeaspectcurvature")
METHOD(Method)
0 - [0] Maximum Slope (Travis et al. 1975)
1 - [1] Maximum Triangle Slope (Tarboton 1997)
2 - [2] Least Squares Fitted Plane (Horn 1981, Costa-Cabral & Burgess 1996)
3 - [3] Fit 2.Degree Polynom (Bauer, Rohdenburg, Bork 1985)
4 - [4] Fit 2.Degree Polynom (Heerdegen & Beran 1982)
5 - [5] Fit 2.Degree Polynom (Zevenbergen & Thorne 1987)
6 - [6] Fit 3.Degree Polynom (Haralick 1983)
In questo caso, l’algoritmo ha uno di questi parametri con 7 opzioni, ordinate a partire da zero.
Multiple input. The value is a string with input descriptors separated by
semicolons (;
). As in the case of single layers or tables, each input
descriptor can be the data object name, or its filepath.
Campo di una Tabella da XXX. Inserire una stringa con il nome del campo da utilizzare. Il parametro è sensibile alle lettere maiuscole
Fixed Table. Type the list of all table values separated by commas (,
) and
enclosed between quotes ("
). Values start on the upper row and go from left
to right. You can also use a 2D array of values representing the table.
Sistema di Riferimento per le Coordinate (Coordinate Reference System, CRS). Inserire il codice EPSG per indicare il sistema di riferimento desiderato.
Extent. You must use a string with xmin
, xmax
, ymin
and ymax
values separated by commas (,
).
Parametri booleani, di file, di stringa e numerici non hanno bisogno di ulteriori spiegazioni.
I parametri di input, come stringhe o valori numerici o booleani hanno valori di default. Per utilizzarli, usare ``None ``nella voce del parametro corrispondente.
Per per salvare i dati di output, digitare il percorso del file da utilizzare, così come viene fatto nella finestra degli strumenti. Se si desidera salvare il risultato in un file temporaneo, utilizzare ``None ``. L’estensione del file determina il formato del file. Se si immette un’estensione del file non inclusa tra quelle supportate dall’algoritmo, verrà utilizzato il formato di file predefinito per il tipo di output e sarà aggiunta al percorso del file specificato la sua estensione corrispondente .
Unlike when an algorithm is executed from the toolbox, outputs are not added to the map canvas if you execute that same algorithm from the Python Console. If you want to add an output to it, you have to do it yourself after running the algorithm. To do so, you can use QGIS API commands, or, even easier, use one of the handy methods provided for such task.
The runalg
method returns a dictionary with the output names (the
ones shown in the algorithm description) as keys and the filepaths of
those outputs as values. You can load those layers by passing its
filepath to the load()
method.
Apart from the functions used to call algorithms, importing the
processing
package will also import some additional functions that make it
easier to work with data, particularly vector data. They are just convenience
functions that wrap some functionality from the QGIS API, usually with a less
complex syntax. These functions should be used when developing new algorithms,
as they make it easier to operate with input data.
Below is a list of some of this commands. More information can be found in the
classes under the processing/tools
package, and aso in the example scripts
provided with QGIS.
getobject(obj)
: Returns a QGIS object (a layer or table) from the passed
object, which can be a filename or the name of the object in the QGIS Table of
Contents.values(layer, fields)
: Returns the values in the attributes table of a
vector layer, for the passed fields. Fields can be passed as field names or as
zero-based field indices. Returns a dict of lists, with the passed field
identifiers as keys. It considers the existing selectiongetfeatures(layer)
: Returns an iterator over the features of a vector
layer, considering the existing selection.uniquelabels(layer, field)
: Returns a list of unique values for a given
attribute. Attribute can be passed as a field name or a zero-based field
index. It considers the existing selectionYou can create your own algorithms by writing the corresponding Python code and
adding a few extra lines to supply additional information needed to define the semantics of the algorithm.
You can find a Create new script menu under the Tools
group in the Script algorithms block of the toolbox. Double-click on
it to open the script edition dialog. That’s where you should type your code.
Saving the script from there in the scripts
folder (the default one when
you open the save file dialog), with .py
extension, will automatically
create the corresponding algorithm.
Il nome dell’algoritmo (quello si vedrà nella finestra degli strumenti) viene creato dal nome del file, rimuovendo la sua estensione e sostituendoi trattini bassi con spazi vuoti.
Ad esempio, quello seguente è il codice che calcola l’Indice di Umidità Topografica (Topographic Wetness Index, TWI) direttamente da un DEM
##dem=raster
##twi=output
ret_slope = processing.runalg("saga:slopeaspectcurvature", dem, 0, None,
None, None, None, None)
ret_area = processing.runalg("saga:catchmentarea(mass-fluxmethod)", dem,
0, False, False, False, False, None, None, None, None, None)
processing.runalg("saga:topographicwetnessindex(twi), ret_slope['SLOPE'],
ret_area['AREA'], None, 1, 0, twi)
As you can see, it involves 3 algorithms, all of them coming from SAGA. The last one of them calculates the TWI, but it needs a slope layer and a flow accumulation layer. We do not have these ones, but since we have the DEM, we can calculate them calling the corresponding SAGA algorithms.
The part of the code where this processing takes place is not difficult to understand if you have read the previous sections in this chapter. The first lines, however, need some additional explanation. They provide the information that is needed to turn your code into an algorithm that can be run from any of the GUI components, like the toolbox or the graphical modeler.
These lines start with a double Python comment symbol (##
) and have the
following structure
[parameter_name]=[parameter_type] [optional_values]
Here is a list of all the parameter types that are supported in processign scripts, their syntax and some examples.
raster
. Un layer raster
vector
. Un layer vettoriale
table
. Una tabella
number
. Un valore numerico. Deve essere indicato un valore di default. Ad esempio, depth=number 2.4
string
. Una stringa di testo. Come nel caso dei valori numerici, deve essere indicato un valore di default. Ad esempio, name=string Victor````number
boolean
. Un valore booleano. Aggiungere True
o False
dopo di esso per indicare il valore di default. Ad esempio, verbose=boolean True
multiple raster
. Un insieme di layer raster di input.
multiple vector
. A set of input vector layers.field
. Un campo nella tabella degli attributi di un layer vettoriale. Il nome del layer deve essere aggiunto dopo il tag field
. Ad esempio, una volta dichiarato il layer vettoriale di input con mylayer=vector
, si può usare myfield=field mylayer
per aggiungere come parametro un campo di quel layer.
folder
. Una cartella
file
. Un nome di un file
Il nome del parametro è il nome che verrà mostrato all’utente durante l’esecuzione dell’algoritmo, ed è anche il nome della variabile da utilizzare nel codice dello script. Il valore immesso dall’utente per quel parametro sarà assegnato a una variabile con quel nome.
When showing the name of the parameter to the user, the name will be edited it to
improve its appearance, replacing low hyphens with spaces. So, for instance,
if you want the user to see a parameter named A numerical value
, you can use
the variable name A_numerical_value
.
Layers and tables values are strings containing the filepath of the corresponding
object. To turn them into a QGIS object, you can use the processing.getObjectFromUri()
function. Multiple inputs also have a string value, which contains the filepaths
to all selected object, separated by semicolons (;
).
Gli output sono definiti in maniera simile, usando i seguenti tag:
output raster
output vector
output table
output html
output file
output number
output string
The value assigned to the output variables is always a string with a filepath. It will correspond to a temporary filepath in case the user has not entered any output filename.
When you declare an output, the algorithm will try to add it to QGIS once it
is finished. That is the reason why, although the runalg()
method does not
load the layers it produces, the final TWI layer will be loaded, since it is saved
to the file entered by the user, which is the value of the corresponding output.
Non usare il comando `` load() `` negli algoritmi di script, ma solo quando si lavora con la linea di comando. Se un layer viene creato come output di un algoritmo, esso dovrebbe essere dichiarato come tale. In caso contrario, l’algoritmo nel modellatore non potrà essere utilizzato correttamente, dal momento che la sua sintassi (come definita dai tag spiegato sopra) non corrisponde a ciò che l’algoritmo in realtà crea.
Output nascosti (numeri e stringhe) non hanno un valore. È invece l’utente che deve assegnare loro un valore. Per farlo, è sufficiente impostare il valore di una variabile con il nome utilizzato per dichiarare quell’output. Per esempio, se è stata usata questa dichiarazione,
##average=output number
la riga seguente imposterà il valore dell’output a 5:
average = 5
Oltre ai tag per i parametri e gli output, è anche possibile definire il gruppo in cui verrà mostrato l’algoritmo, utilizzando il tag `` group ``.
Se l’algoritmo impiega molto tempo per elaborare, è una buona idea informare l’utente. Si dispone di due comandi globali denominati ``progress ``con due metodi disponibile : `` setText (testo) `` e `` setPercentage (percent) `` per modificare il testo e la barra di avanzamento.
Several examples are provided. Please, check them to see real examples of how to create algorithms using the processing framework classes. You can right-click on any script algorithm and select Edit script to edit its code or just to see it.
Come nel caso dei modelli, è possibile creare una documentazione aggiuntiva per gli script, per spiegare che cosa fanno e come usarli. Nella finestra di modifica dello script si trova un pulsante [Edit script help]. Fare clic su di esso e si aprirà una finestra di editing dell’help. Controllare il capitolo sul modellatore grafico per sapere di più su questa finestra di dialogo e come usarla.
I file della guida vengono salvati nella stessa cartella dello stesso script, aggiungendo l’estensione .help
al nome del file. Si noti che è possibile modificare la guida dello script prima di salvarlo per la prima volta. Se in seguito si chiude la finestra di modifica dello script senza salvare lo script (cioè la si scarta), il contenuto già scritto della guida verrà perso. Se lo script è già stato salvato ed è associato ad un nome di file, il salvataggio è fatto automaticamente.
Scripts can also be used to set pre- and post-execution hooks that are run before and after an algorithm is run. This can be used to automate tasks that should be performed whenever an algorithm is executed.
The syntax is identical to the syntax explained above, but an additional global
variable named alg
is available, representing the algorithm that has just
been (or is about to be) executed.
In the General group of the processing config dialog you will find two entries named Pre-execution script file and Post-execution script file where the filename of the scripts to be run in each case can be entered.