Configurar aplicaciones externas

El entorno de procesamiento se puede extender el uso de aplicaciones adicionales. Actualmente, SAGA, GRASS, OTB (Orfeo Toolbox) y R son reconocidos, junto con algunas otras aplicaciones de línea de comandos que proporcionan funcionalidades de análisis de datos espaciales. Los algoritmos que dependen de una aplicación externa son administrados por su propio proveedor de algoritmos.

Esta sección le mostrará cómo configurar el entorno de procesamiento para incluir estas aplicaciones adicionales, y le explicará algunas de las características particulares de los algoritmos basados en ellos. Una vez que haya configurado correctamente el sistema, usted será capaz de ejecutar algoritmos externos de cualquier componente, como la caja de herramientas o el modelador gráfico, tal como lo hace con cualquier otro geoalgoritmo.

By default, all algorithms that rely on an external application not shipped with QGIS are not enabled. You can enable them in the settings dialog. Make sure that the corresponding application is already installed in your system.

Aclaración para los usuarios de Windows

Si no es un usuario avanzado y está ejecutando QGIS en Windows, podría no estar interesado en leer el resto de este capítulo. Asegure que la instalación de QGIS en su sistema utiliza el instalador independiente. Esto instalará automáticamente SAGA, GRASS y OTB en su sistema y configurarlos para que se pueden ejecutar desde QGIS. Todos los algoritmos estarán listas para ser ejecutados sin necesidad de alguna configuración adicional. Si va a instalar mediante la aplicación OSGeo4W, asegúrese de seleccionar SAGA, OTB para la instalación.

Si quiere saber más sobre cómo funcionan estos proveedores, o si quiere utilizar algún algoritmo que no se encuentre en la Caja de Herramientas simplificada (como los scripts de R), siga leyendo.

Aclaración respecto a los formatos de archivos

Cuando se utiliza un software externo, la apertura de un archivo en QGIS no significa que se puede abrir y procesar bien en ese otro software. En la mayoría de los casos, otro software puede leer lo que ha abierto en QGIS, pero en algunos casos, eso puede no ser cierto. Al utilizar las bases de datos o formatos de archivo poco comunes, ya sea para capas raster o vectoriales, podrían surgir problemas. Si eso sucede, trate de utilizar formatos de archivo conocidos que este seguro que ambos programas entiendan, y comprobar la salida de la consola (en el historico y el diálogo de registro) para saber más acerca de lo que va mal.

Utilizar capas raster de GRASS es, por ejemplo, uno de los casos en los que pueden existir problemas y no completarse el trabajo si se invoca un algoritmo externo que use dicha capa como entrada. Por este motivo, estas capas no aparecerán como disponibles para los algoritmos.

Debe, sin embargo, no encontrar ningún problema en absoluto con las capas vectoriales, ya que QGIS convierte automáticamente desde el formato de archivo original a uno aceptado por la aplicación externa antes de pasar la capa a la misma. Esto suma tiempo de procesamiento adicional, que podría ser significativo si la capa tiene un tamaño grande, así que no se sorprenda si se necesita más tiempo para procesar una capa de una conexión de DB que lo hace para procesar una de un tamaño similar almacenada en un archivo de shape.

Providers not using external applications can process any layer that you can open in QGIS, since they open it for analysis through QGIS.

Regarding output formats, all formats supported by QGIS as output can be used, both for raster and vector layers. Some providers do not support certain formats, but all can export to common formats that can later be transformed by QGIS automatically. As in the case of input layers, if this conversion is needed, that might increase the processing time.

Nota referente a las seleccion de capas vectoriales

Las aplicaciones externas pueden también ser conscientes de las selecciones que existen en capas vectoriales dentro QGIS. Sin embargo, eso requiere reescribir todas las capas vectoriales de entrada, al igual que si originalmente estuvieran en un formato no compatible con la aplicación externa. Sólo cuando no existe ninguna selección o la opción *Utilizar sólo objetos espaciales seleccionados * no está activada en la configuración general de procesamiento, puede una capa ser directamente pasada a una aplicación externa.

En otros casos sólo es necesario exportar un conjunto de características seleccionadas, lo que hará que los tiempos de ejecución sean mayores.

SAGA

Los algoritmos de SAGA pueden ser ejecutados desde QGIS si se tiene SAGA instalado en su sistema y se puede configurar correctamente el entorno de procesamiento para que pueda encontrar ejecutables SAGA. En particular, se necesita la línea de comandos SAGA ejecutable para ejecutar algoritmos SAGA.

If you are running Windows, both the stand-alone installer and the OSGeo4W installer include SAGA along with QGIS, and the path is automatically configured, so there is no need to do anything else.

If you have installed SAGA yourself and your QGIS installer did not include it, the path to the SAGA executable must be configured. To do this, open the configuration dialog. In the SAGA block, you will find a setting named SAGA Folder. Enter the path to the folder where SAGA is installed. Close the configuration dialog, and now you are ready to run SAGA algorithms from QGIS.

If you are running Linux, SAGA binaries are not included with Processing, so you have to download and install the software yourself. Please check the SAGA website for more information.

En este caso, no hay necesidad de configurar la ruta al ejecutable de SAGA, y no se verán esas carpetas. En su lugar, debe asegurarse de que SAGA está correctamente instalado y se añade su carpeta a la variable de entorno PATH. Sólo tiene que abrir una consola y escribir saga_cmd para comprobar que el sistema puede encontrar donde se encuentran los archivos binarios de SAGA.

Sobre las limitaciones del sistema de cuadrícula de SAGA

Most SAGA algorithms that require several input raster layers require them to have the same grid system. That is, they must cover the same geographic area and have the same cell size, so their corresponding grids match. When calling SAGA algorithms from QGIS, you can use any layer, regardless of its cell size and extent. When multiple raster layers are used as input for a SAGA algorithm, QGIS resamples them to a common grid system and then passes them to SAGA (unless the SAGA algorithm can operate with layers from different grid systems).

La definición de este sistema de cuadrícula común es controlado por el usuario, y se encontrará varios parámetros en el grupo SAGA de la ventana de configuración para hacerlo. Hay dos formas de establecer el sistema de cuadrícula de destino.

  • Establecerlo manualmente. se define la extensión estableciendo los valores de los siguientes parámetros:

    • Resampling min X
    • Resampling max X
    • Resampling min Y
    • Resampling max Y
    • Resampling cellsize

    Notice that QGIS will resample input layers to that extent, even if they do not overlap with it.

  • Ajuste de forma automática a partir de capas de entrada. Para seleccionar esta opción, simplemente marque la opción Utilizar el sistema de cuadrícula mínima para remuestreo. Todos los demás ajustes se ignoran y la medida mínima que cubre todas las capas de entrada que se utilizarán. El tamaño de celda de la capa de destino es el máximo de todos los tamaños celulares de las capas de entrada.

Para los algoritmos que no utilizan múltiples capas raster, o para aquellos que no necesitan un único sistema de cuadrícula de entrada, no se realizará un remuestreo antes de invocar SAG y dichos parámetros no son utilizados.

Limitaciones para las capas multibanda

A diferencia de QGIS, SAGA no tiene soporte para capas multibanda. Si desea utilizar una capa multibanda (como un RGB o imagen multiespectral), primero hay que dividirlo en imágenes de un sola banda. Para ello, se puede utilizar el algoritmo ‘imagen SAGA/Grid - Herramientas/Dividir’ (que crea tres imágenes de una imagen RGB) o el algoritmo ‘banda SAGA/Grid - Herramientas / Extracto’ (para extraer una sola banda).

Limitaciones en el tamaño de celda

SAGA asume que las capas ráster tienen el mismo tamaño de celda en el eje X y Y. Si se está trabajando con una capa con diferentes valores para el tamaño de celda horizontal y vertical, es posible que obtenga resultados inesperados. En este caso, se añadirá una advertencia al registro de procesamiento, lo que indica que una capa de entrada podría no ser adecuada para ser procesada por SAGA.

Registro

When QGIS calls SAGA, it does so using its command-line interface, thus passing a set of commands to perform all the required operations. SAGA shows its progress by writing information to the console, which includes the percentage of processing already done, along with additional content. This output is filtered and used to update the progress bar while the algorithm is running.

Both the commands sent by QGIS and the additional information printed by SAGA can be logged along with other processing log messages, and you might find them useful to track in detail what is going on when QGIS runs a SAGA algorithm. You will find two settings, namely Log console output and Log execution commands, to activate that logging mechanism.

La mayoría del resto de proveedores que utilizan una aplicación externa y la invocan a través de la línea de comandos tienen opciones similares, de forma que las podrá encontrar también en otros lugares de la lista de ajustes de procesamiento.

R. Creating R scripts

R integration in QGIS is different from that of SAGA in that there is not a predefined set of algorithms you can run (except for a few examples). Instead, you should write your scripts and call R commands, much like you would do from R, and in a very similar manner to what we saw in the section dedicated to processing scripts. This section shows you the syntax to use to call those R commands from QGIS and how to use QGIS objects (layers, tables) in them.

The first thing you have to do, as we saw in the case of SAGA, is to tell QGIS where your R binaries are located. You can do this using the R folder entry in the processing configuration dialog. Once you have set that parameter, you can start creating and executing your own R scripts.

Nota

for Windows user, usually the R executable file is in the C:Program FilesRR-3.2 folder. Add just the folder and NOT the binary!

De nuevo, esto es diferente en Linux, dónde sólo hay que asegurarse de que el directorio de R está correctamente incluido en la variable de entorno PATH. Si R puede iniciarse simplemente escribiendo R en una consola, entonces la configuración es correcta.

To add a new algorithm that calls an R function (or a more complex R script that you have developed and you would like to have available from QGIS), you have to create a script file that tells the processing framework how to perform that operation and the corresponding R commands to do so.

Los archivos de script de R tienen la extensión .rsx, y crearlos es bastante sencillo si sólo tiene un conocimiento básico de la sintaxis y script de R. Deben ser almacenados en la carpeta de scripts de R. Se puede establecer esta carpeta en el grupo de ajustes R (disponible desde el diálogo de Configuración de procesamiento), al igual que se hace con la carpeta para scripts de procesamiento regular.

Vamos a echar un vistazo a un archivo de script muy simple, que llama al método R spsample para crear una cuadricula al azar dentro de los límites de los polígonos en una capa de polígono dada. Este método pertenece al paquete maptools. Dado que casi todos los algoritmos que pueden gustar incorporar a QGIS utilizará o generará datos espaciales, el conocimiento de paquetes espaciales como maptools y sobretodo sp es obligatoria.

##polyg=vector
##numpoints=number 10
##output=output vector
##sp=group
pts=spsample(polyg,numpoints,type="random")
output=SpatialPointsDataFrame(pts, as.data.frame(pts))

The first lines, which start with a double Python comment sign (##), tell QGIS the inputs of the algorithm described in the file and the outputs that it will generate. They work with exactly the same syntax as the Processing scripts that we have already seen, so they will not be described here again.

Please have a look at the R Intro and the R Syntax Training Manual Chapters to have more information on how to write your own R scripts-

Cuando se declara un parámetro de entrada, QGIS usa esa información con dos finalidades: crear la interfaz de usuario que solicita al usuario el valor de dicho parámetro y crear la variable correspondiente en R que se pueda usar después como entrada para los comandos en R.

In el ejemplo anterior, estamos declarando un tipo de entrada vector llamado polyg. Al ejecutar el algoritmo, QGIS abrirá en R la capa seleccionada por el usuario y almacenarlo en una variable llamada polyg`. Así el nombre de uno de los parámetros también es el nombre de la variable que se puede utilizar en R para acceder el valor de ese parámetro (así, se debe evitar utilizar palabras de R reservadas como nombres de parámetros).

Los elementos espaciales como las capas vectoriales y ráster se leen utilizando los comandos readOGR() y brick() (no tiene que preocuparse acerca de cómo agregar estos comandos a su archivo de descripción - QGIS lo hará), y se almacenan como objetos Spatial*DataFrame. Los campos de la tabla se almacenan como cadenas que contienen el nombre del campo seleccionado.

Las tablas se abren con el comando read.csv(). Sin una tabla introducida por el usuario no esta en formato CSV, será convertirá antes de importarlo en R.

Además, los ráster se pueden leer con el comando readGDAL()` en lugar de ``brick() utilizando el ##usereadgdal.

Si se es un usuario avanzado y no quiere QGIS para crear el objeto que representado la capa, puede utilizar la etiqueta ##passfilenames para indicar que prefiere una cadena con el nombre de archivo en su lugar. En este caso, le corresponde abrir el archivo antes de realizar cualquier operación sobre los datos que contiene.

Con la información anterior, se puede comprender la primera línea de nuestro primer script de ejemplo (la primera línea que no comienza con un comentario de Python).

pts=spsample(polyg,numpoints,type="random")

La variable polygon ya contiene un objeto SpatialPolygonsDataFrame, por lo que se puede utilizar para llamar al método spsample, al igual que numpoints, que indica el número de puntos a añadir a la rejilla de ejemplo creada.

Como hemos declarado una salida de tipo vectorial llamada salida, tenemos que crear una variable llamada salida y almacenar un objeto Spatial*DataFrame en ella (en este caso, un SpatialPointsDataFrame). Se puede utilizar cualquier nombre para sus variables intermedias. Sólo asegúrese de que la variable almacena su resultado final y que tiene el mismo nombre que utilizó al declararla, y que contiene un valor adecuado.

In this case, the result obtained from the spsample method has to be converted explicitly into a SpatialPointsDataFrame object, since it is itself an object of class ppp, which is not a suitable class to be returned to QGIS.

If your algorithm generates raster layers, the way they are saved will depend on whether or not you have used the ##dontuserasterpackage option. If you have used it, layers are saved using the writeGDAL() method. If not, the writeRaster() method from the raster package will be used.

Si ha utilizado la opción #passfilenames, las salidas se generan utilizando el paquete raster (mediante writeRaster()), incluso cuando no se utiliza para las entradas.

Si el algoritmo no genera ninguna capa, sino más bien en su lugar regresa un texto en la consola, tiene que indicar lo que desea que la consola mostrará una vez finalizada la ejecución. Para ello, basta con iniciar la línea de comandos que producen los resultados que desea imprimir con el signo > `(‘mayor’). La salida de todas las otras líneas no se mostrará. Por ejemplo, aquí está el archivo de descripción de un algoritmo que realiza una prueba normalmente en un determinado campo (columna) de los atributos de una capa vectorial:

##layer=vector
##field=field layer
##nortest=group
library(nortest)
>lillie.test(layer[[field]])

La salida de la última línea se imprime, pero la salida de la primera no (y tampoco están las salida de otras líneas de comando agregadas automáticamente por QGIS).

Si su algoritmo crea algún tipo de gráficos (utilizando el método plot()), añada la siguiente línea:

##showplots

Esto provocará que QGIS redireccione todas las salidas de gráficas R a un archivo temporal, que se abrirá una vez que terminé la ejecución de R.

Tanto los resultados gráficos como de consola, se mostrará en el gesto de resultados de procesamiento.

For more information, please check the script files provided with Processing. Most of them are rather simple and will greatly help you understand how to create your own scripts.

Nota

rgdal and raster libraries are loaded by default, so you do not have to add the corresponding library() commands (you just have to make sure that those two packages are installed in your R distribution). However, other additional libraries that you might need have to be explicitly loaded by typing, library(ggplot2). If the package is not already installed on your machine, Processing will download and install it. In this way the package will be also available in R Standalone. Be aware that if the package has to be downloaded, the first time you run the script it might take a long time.

GRASS

Configurar GRASS no es muy diferente de la configuración de SAGA. En primer lugar, la ruta de la carpeta GRASS debe ser definido, pero solo si se ejecuta en Windows. Adicionalmente, un interprete de comandos (usualmente msys.exe, que se puede encontrar en la mayoría de distribuciones GRASS para Windows) tiene que ser definido y establecer la ruta también.

Por defecto, el marco de procesamiento intenta configurar el conector de GRASS para utilizar la distribución GRASS que se incluye junto con QGIS. Esto debería funcionar sin problemas en la mayoría de los sistemas, pero si tiene problemas, puede que tenga que configurar el conector GRASS manualmente. Además, si usted desea utilizar una instalación diferente de GRASS, puede cambiar esta configuración y seleccionar la carpeta donde está instalada la otra versión. GRASS 6.4 es necesaria para que los algoritmos funcione correctamente.

Si se utiliza Linux, hay que asegurarse de que GRASS está correctamente instalado y que se puede ejecutar sin problemas desde una consola.

Los algoritmos de GRASS utilizan una región para cálculos. Esta región se puede definir manualmente utilizando valores similares a los encontrados en la configuración de SAGA, o automáticamente tomara la extensión mínima que cubre todas las capas de entrada utilizadas para ejecutar el algoritmo cada vez. Si el último enfoque es el comportamiento que prefiere, simplemente marque la opción Utilizar la región de cobertura mínima en los parámetros de configuración de GRASS.

GDAL

No additional configuration is needed to run GDAL algorithms. Since they are already incorporated into QGIS, the algorithms can infer their configuration from it.

Caja de Herramientas de Orfeo

Orfeo Toolbox (OTB) algorithms can be run from QGIS if you have OTB installed in your system and you have configured QGIS properly, so it can find all necessary files (command-line tools and libraries).

As in the case of SAGA, OTB binaries are included in the stand-alone installer for Windows, but they are not included if you are running Linux, so you have to download and install the software yourself. Please check the OTB website for more information.

Once OTB is installed, start QGIS, open the processing configuration dialog and configure the OTB algorithm provider. In the Orfeo Toolbox (image analysis) block, you will find all settings related to OTB. First, ensure that algorithms are enabled.

Entonces, configurar la ruta al directorio donde las aplicaciones de línea de comandos y las librerías de OTB se encuentran instaladas:

  • nix Normalmente, el directorio de aplicaciones de OTB apunta a `/usr/lib/otb/applications`` y el directorio con los programas de línea de comandos de OTB es `/usr/bin``.

  • win If you use any of the installers that include OTB, such as OSGeo4W, there is no need for further configuration. Processing will detect the path automatically and will not show the corresponding configuration entries. Otherwise, fill the OTB applications folder and OTB command line tools folder parameters with the to the corresponding values for your installation.

TauDEM

TauDEM (Terrain Analysis Using Digital Elevation Models) is a tools for the extraction and analysis of hydrological information from Digital Elevation Models (DEM). TauDEM can be used from QGIS if you have it installed in your system and configured QGIS properly, so it can find all necessary files.

There are two versions of TauDEM tools: singlefile (TauDEM 5.0.6 or 5.1.2) and multifile (TauDEM 5.2.0). The difference between these versions in the supported inputs/outputs. Single files version accepts only single raster file and write single file as output. Multifile version accepts a directory with rasters and writes directory with rasters as output. Such directory should contain rasters that will be treated as a single DEM grid.

TauDEM Processing provider supports both single- and multifile versions of TauDEM and even allows to use them simultaneously.

Nota

While TauDEM Processing provider supports TauDEM 5.0.6, 5.1.2 and 5.2.0 we recommend to use 5.1.2 and/or 5.2.0 as this versions have some new tools available, like Gage Watershed and TWI.

Instalando TauDEM bajo Windows

Please visit the TauDEM homepage and download desired version of the precompiled binaries for your platform (32-bit or 64-bit), usually this is “Command Line Executables”. Also you need to download Microsoft HPC Pack 2012 MS-MPI. First install Microsoft HPC Pack 2012 MS-MPI by runing mpi_x64.Msi for 64-bit platforms and mpi_x86.Msi for 32-bit platforms.

Nota

Si quiere usar TauDEM 5.0.6

Instalando TauDEM bajo Linux

Unfortunately there are no packages for most Linux distributions, so you should compile TauDEM by yourself. As TauDEM uses MPI it is necessary to install first any MPI implementation e.g MPICH or OpenMPI. Use your favorite package manager to install MPICH or OpenMPI.

Download TauDEM 5.2.0 source code package from GitHub repository and extract archive contents. Open terminal and cd into src directory inside extracted folder. Create build directory and cd into it

mkdir build
cd build

Configure your build (change install prefix if necessary) and compile

CXX=mpicxx cmake -DCMAKE_INSTALL_PREFIX=/usr/local ..
make

When compilation finished install TauDEM tools by running

sudo make install

Nota

Executable files will be installed into bin subdirectory inside prefix you specified at the configure stage. For example if you specified prefix /opt/taudem5.2 than binaries will be installed into /opt/taudem5.2/bin.

To use singlefile version — download source package here and perform above mentioned steps to compile and install it.

Old TauDEM 5.0.6 also available. But before compiling this version it is necessary to edit some source files.

Abrir el archivo linearpart.h , y después de la línea

#include "mpi.h"

añadir una nueva linea con

#include <stdint.h>

y obtendrá

#include "mpi.h"
#include <stdint.h>

Guardar los cambios y cerrar el archivo. Ahora abir tiffIO.h, buscar la línea #include "stdint.h" y sustituir las comillas ("") con <>, para obtener

#include <stdint.h>

Save the changes and close the file.

Now configure, compile and install TauDEM 5.0.6 using same commands as described above.

Configurar proveedor TauDEM

Once TauDEM is installed, start QGIS, open the Processing options dialog from Processing ‣ Options... and configure the TauDEM algorithm provider. In the Providers group find TauDEM (hydrologic analysis) block, and expand it. Here you will see all settings related to TauDEM.

First, ensure that algorithms are enabled, and activate provider if necessary.

Next step is to configure MPI. The MPICH/OpenMPI bin directory setting used to define location of the mpiexec program. In most Linux distributions you can safely leave this empty, as mpiexec available in your PATH.

The Number of MPI parallel processes to use is a second setting related to MPI. It defines number of processes that will be used to execute TauDEM commands. If you don’t know which value to use, it is better to leave this value unchanged.

Now we need to configure the path to the folder(s) where TauDEM command-line tools are installed. As we already mention TauDEM provider supports both single- and multifile TauDEM, so there are two settings for TauDEM folders:

  • TauDEM command line tools folder used to set location of the singlefile tools
  • TauDEM multifile command line tools folder used to set location of the multifile tools

If you have both TauDEM versions installed in different directories it is possible to specify both options.

The last step is to define which TauDEM version to use:

  • with Enable multifile TauDEM tools option checked you will use multifile TauDEM tools from directory, specified in the TauDEM multifile command line tools folder. Multifile tools have same name as singlefile with “(multifile)” suffix added
  • with Enable single TauDEM tools option checked you will use multifile TauDEM tools from directory, specified in the TauDEM command line tools folder.

It is possible to enable both tools simultaneously. In this case you will have two instances of each tool in toolbox and can use them in your analysis.

Nota

Be careful with developing Processing models using TauDEM!

As single- and multifile versions have different inputs, model created with singlefile algorithms will not work if only multifile algorithms are available. If you plan to share your model please specify which TauDEM version should be used or, better, provide two versions of your model: for single- and multifile TauDEM.