The GRASS plugin provides access to GRASS GIS (see GRASS-PROJECT Literatura e Referências Web) databases and functionalities. This includes visualization of GRASS raster and vector layers, digitizing vector layers, editing vector attributes, creating new vector layers and analysing GRASS 2D and 3D data with more than 400 GRASS modules.
Nesta Secção nós iremos apresentar as funcionalidades do módulo e dar alguns exemplos da gestão e no trabalho dos dados GRASS. As seguintes características principais são fornecidas com o menu da barra de ferramentas, quando inicia o módulo GRASS, como é descrito em sec_starting_grass :
Para usar as funcionalidades e/ou visualizar camadas vectoriais e raster do GRASS no QGIS, deve seleccionar e carregar o módulo GRASS com o Gestor de Módulos. Portanto, vá ao menu Módulos ‣ Gerir Módulos, e seleccione GRASS e clique [OK].
Pode agora iniciar o carregamento das camadas raster e vectorial a partir de um file:LOCALIZAÇÃO (see section sec_load_grassdata) GRASS. Ou pode criar um novo LOCALIZAÇÃO com o QGIS (veja a secção Criando uma nova LOCALIZAÇÃO GRASS) e importe alguns dados vectoriais e raster (veja a Secção Importando dados para uma LOCALIZAÇÃO GRASS) para mais análises com a Caixa de Ferramentas GRASS (veja a secção The GRASS toolbox).
Com o módulo GRASS, pode carregar camadas vectoriais e raster usando o botão apropriadado no menu da barra de ferramentas. Como exemplo, nós usamos o conjunto de dados QGIS do alaska (veja Secção Amostra de Dados). Inclue uma pequena amostra de LOCALIZAÇÃO GRASS com 3 camadas vectoriais e 1 raster de elevação.
Crie uma nova pasta grassdata, transfira o conjunto de dados QGIS ‘Alaska’ qgis_sample_data.zip apartir do http://download.osgeo.org/qgis/data/ e descompacte o ficheiro no grassdata.
Iniciar o QGIS.
Se ainda não fez numa sessão QGIS anterior, carrega o módulo GRASS clicando no Módulos ‣ Gestor de Módulos e active GRASS. A barra de ferramentas GRASS aparece na janela principal do QGIS.
Na barra de ferramentas GRASS, clique no ícone Abrir conjunto de mapas para iniciar o assistente de instalação do CONJUNTO DE DADOS.
Para a Gisdbase procure e seleccione ou introduza o directório para a nova pasta criada grassdata.
Poderá agora ser capaz de seleccionar a LOCALIZAÇÃO alaska e o guilabel:CONJUNTO DE DADOS demo.
Clique [OK]. Repare que algumas das ferramentas na barra de ferramentas GRASS que estão desactivadas agora estão activas.
Clique no Adicionar camada raster GRASS, escolha o nome do mapa gtopo30 e cliquem em [OK]. A camada de elevação irá ser visualizada.
Carregue também as outras duas camadas vectoriais rivers e airports e adaptar as suas propriedades.
As you see, it is very simple to load GRASS raster and vector layers in QGIS. See following sections for editing GRASS data and creating a new LOCATION. More sample GRASS LOCATIONs are available at the GRASS website at http://grass.osgeo.org/download/sample-data/.
Tip
Carregamento de Dados GRASS
Se tem problemas no carregamento de dados ou o QGIS determina inesperadamente, certifique-se que carregou o módulo GRASS correctamente como está descrito na secção sec_starting_grass.
GRASS data are stored in a directory referred to as GISDBASE. This directory often called grassdata, must be created before you start working with the GRASS plugin in QGIS. Within this directory, the GRASS GIS data are organized by projects stored in subdirectories called LOCATION. Each LOCATION is defined by its coordinate system, map projection and geographical boundaries. Each LOCATION can have several MAPSETs (subdirectories of the LOCATION) that are used to subdivide the project into different topics, subregions, or as workspaces for individual team members (Neteler & Mitasova 2008 Literatura e Referências Web). In order to analyze vector and raster layers with GRASS modules, you must import them into a GRASS LOCATION (This is not strictly true - with the GRASS modules r.external and v.external you can create read-only links to external GDAL/OGR-supported data sets without importing them. But because this is not the usual way for beginners to work with GRASS, this functionality will not be described here.).
Figure GRASS location 1:
O exemplo aqui é como a amostra GRASS LOCALIZAÇÃO alaska, que é projectado na projecção Albers Equal Area com a unidade em pés e que foi criado para a amostra do conjunto de dados QGIS. Esta amostra GRASS LOCALIZAÇÃO alaska irá ser usado para todos os exemplos e exercícios nos seguintes capítulos do GRASS GIS. É útil transferir e instalar o conjunto de dados no computador Amostra de Dados).
Inicie o QGIS e certifique-se que o módulo GRASS foi carregado.
Visualize a shapefile alaska.shp (veja Secção vector_load_shapefile) a partir do Amostra de Dados do conjunto de dados QGIS alaska.
Na barra de ferramentas GRASS, clique no ícone Novo conjunto de mapas para iniciar o assistente de instalação do CONJUNTO DE DADOS.
Seleccione uma pasta de base de dados GRASS (GISDBASE) grassdata ou crie um para a nova LOCALIZAÇÃO usando um gestor de ficheiros no seu computador. De seguida, clique em [Seguinte].
Nós podemos usar este assistente para criar um novo CONJUNTO DE MAPAS dentro de uma LOCALIZAÇÃO existente (veja secção Adicionando um novo CONJUNTO DE MAPAS) ou pata criar juntamente um nova LOCALIZAÇÃO. Seleccione Criar nova localização (veja figure_grass_location_2).
Introduza o nome para LOCALIZAÇÃO - nós usámos ‘alaska’ e clique [Seguinte].
Defina a projecção clicando no botão Projecção para activar a lista de projecção.
Em Filtrar insira 2964 para seleccionar a projecção.
Clique [Seguinte].
Para definir uma região padrão, nós temos de introduzir os limites da LOCALIZAÇÃO na direcção norte, sul, oeste e este. Aqui simplesmente clicamos no botão [Definir a extensão actual do QGIS], para aplicar a extensão da camada carregada alaska.shp como região de extensão padrão do GRASS.
Clique [Seguinte].
Necessitaremos também de definir o CONJUNTO DE MAPAS dentro da nossa nova LOCALIZAÇÃO. Pode dar o nome que quiser - nós usámos ‘demo’ (quando é criado uma nova LOCALIZAÇÃO). O GRASS cria automaticamente um CONJUNTO DE MAPAS especial denominado de PERMANENTE desenhado para armazenar os dados importantes para o projecto, é uma extensão espacial padrão com definições de sistemas de coordenadas (Neteler & Mitasova 2008 Literatura e Referências Web).
Verifique o sumário para ter a certeza que está correcto e clique em [Concluído].
A nova LOCALIZAÇÃO ‘alaska’ e dois CONJUNTO DE MAPAS ‘demo’ e ‘PERMANENTE’ são criados. O conjunto de trabalho actualmente aberto é o ‘demo’, como tinha definido.
Repare que algumas das ferramentas na barra de ferramentas GRASS que estão desactivadas agora estão activas.
Figure GRASS location 2:
Se achar que são muitos passos, não é assim tão mau e há uma forma rápida para criar uma LOCALIZAÇÃO. A LOCALIZAÇÃO 'alaska não está preparada para importação de dados (veja Secção Importando dados para uma LOCALIZAÇÃO GRASS). Pode também usar os dados vectoriais e raster existentes na amostra GRASS LOCALIZAÇÃO ‘alaska’ incluída no conjunto de dados do QGIS ‘Alaska’ Amostra de Dados e siga para a Secção O modelo de dados vectoriais do GRASS.
Um utilizador apenas tem acesso de escrita no GRASS CONJUNTO DE MAPAS que criou. Isto significa que apesar do acesso ao seu CONJUNTO DE MAPAS, cada utilizador pode ler os mapas de outros utilizadores CONJUNTO DE MAPAS, mas ele pode modificar ou remover apenas os mapas do seu CONJUNTO DE MAPAS.
Todos os CONJUNTO DE MAPAS inclui um ficheiro WIND que armazena os limites actuais com os valores das coordenadas e a resolução do raster actualmente seleccionado (Neteler & Mitasova 2008 Literatura e Referências Web, veja Secção A ferramenta da região GRASS).
Inicie o QGIS e certifique-se que o módulo GRASS foi carregado.
Na barra de ferramentas GRASS, clique no ícone Novo conjunto de mapas para iniciar o assistente de instalação do CONJUNTO DE DADOS.
Seleccione a pasta da base de dados (GISDBASE) GRASS grassdata com a LOCALIZAÇÃO ‘alaska’, onde queremos adicionar o CONJUNTO DE MAPAS, chamado de ‘test’.
Clique [Seguinte].
Podemos usar este assistente para criar um novo CONJUNTO DE MAPAS dentro de uma LOCALIZAÇÃO existente ou criar uma nova LOCALIZAÇÃO tudo junto. Clique no botão de rádio Seleccionar localização (veja figure_grass_location_2) e clique [Próximo].
Introduza o nome text para o novo CONJUNTO DE MAPAS. Em baixo no assistente vê uma lista de um CONJUNTO DE MAPAS existentes e os seus proprietários.
Clique [Seguinte], e verifique o sumário para ter a certeza que está tudo correcto e clique em [Concluído].
This Section gives an example how to import raster and vector data into the ‘alaska’ GRASS LOCATION provided by the QGIS ‘Alaska’ dataset. Therefore we use a landcover raster map landcover.img and a vector GML file lakes.gml from the QGIS ‘Alaska’ dataset Amostra de Dados.
Inicie o QGIS e certifique-se que o módulo GRASS foi carregado.
Na barra de ferramentas GRASS, clique no ícone Abrir CONJUNTO DE MAPAS para trazer o assistente de CONJUNTO DE MAPAS.
Seleccione como base de dados GRASS a pasta grassdata no conjunto de dados QGIS alasca, assim como LOCALIZAÇÃO ‘alaska’, e o CONJUNTO DE MAPAS ‘demo’ e clique [OK].
Agora clique no ícone Abrir ferramentas GRASS. O diálogo da Caixa de Ferramentas GRASS (veja secção The GRASS toolbox) aparece.
Procure na pasta raster no conjunto de dados QGIS ‘Alaska’ e seleccione o ficheiro landcover.img.
Quando diz Finalizado com sucesso clique em [Ver Saída]. A camada raster landcover:grass está agora importada dentro do GRASS e será visualizada no enquadramento do QGIS.
Procure na pasta por gml no conjunto de dados QGIS Alaska e seleccione o ficheiro lakes.gml como ficheiro OGR.
Quando diz Finalizado com Sucesso clique [Ver Saída]. O ficheiro da camada vectorial lakes_grass foi importado para o GRASS e irá visualizar no enquadramento do QGIS.
É importante perceber previamente o modelo de dados vectorial GRASS antes da digitalização.
O GRASS usa um modelo topológico vectorial.
This means that areas are not represented as closed polygons, but by one or more boundaries. A boundary between two adjacent areas is digitized only once, and it is shared by both areas. Boundaries must be connected and closed without gaps. An area is identified (and labeled) by the centroid of the area.
Besides boundaries and centroids, a vector map can also contain points and lines. All these geometry elements can be mixed in one vector and will be represented in different so called ‘layers’ inside one GRASS vector map. So in GRASS a layer is not a vector or raster map but a level inside a vector layer. This is important to distinguish carefully (Although it is possible to mix geometry elements, it is unusual and even in GRASS only used in special cases such as vector network analysis. Normally you should prefere to store different geometry elements in different layers.).
It is possible to store several ‘layers’ in one vector dataset. For example, fields, forests and lakes can be stored in one vector. Adjacent forest and lake can share the same boundary, but they have separate attribute tables. It is also possible to attach attributes to boundaries. For example, the boundary between lake and forest is a road, so it can have a different attribute table.
The ‘layer’ of the feature is defined by ‘layer’ inside GRASS. ‘Layer’ is the number which defines if there are more than one layer inside the dataset, e.g. if the geometry is forest or lake. For now, it can be only a number, in the future GRASS will also support names as fields in the user interface.
Attributes can be stored inside the GRASS LOCATION as DBase or SQLITE3 or in external database tables, for example PostgreSQL, MySQL, Oracle, etc.
Os atributos nas tabelas das base de dados estão ligados aos elementos de geometria usando o valor ‘categoria’.
‘Categoria’ (chave, ID) é um inteiro anexado às primitivas da geometria, e é usado como ligação a uma coluna de chave na tabela da base de dados.
Tip
Aprendendo o Modelo Vectorial GRASS
The best way to learn the GRASS vector model and its capabilities is to download one of the many GRASS tutorials where the vector model is described more deeply. See http://grass.osgeo.org/documentation/manuals/ for more information, books and tutorials in several languages.
To create a new GRASS vector layer with the GRASS plugin click the Create new GRASS vector toolbar icon. Enter a name in the text box and you can start digitizing point, line or polygon geometries, following the procedure described in Section Digitalizando e editando as camadas vectoriais GRASS.
In GRASS it is possible to organize all sort of geometry types (point, line and area) in one layer, because GRASS uses a topological vector model, so you don’t need to select the geometry type when creating a new GRASS vector. This is different from Shapefile creation with QGIS, because Shapefiles use the Simple Feature vector model (see Section Criando novas camadas Vectoriais).
Tip
Criando uma tabela de atributos para uma nova camada vectorial GRASS
Se desejar atribuir atributos aos seus elementos de geometria digitalizados, tenha a certeza que criou uma tabela de atributos com as colunas antes de começar a digitalizar (veja figure_grass_digitizing_5).
The digitizing tools for GRASS vector layers are accessed using the Edit GRASS vector layer icon on the toolbar. Make sure you have loaded a GRASS vector and it is the selected layer in the legend before clicking on the edit tool. Figure figure_grass_digitizing_2 shows the GRASS edit dialog that is displayed when you click on the edit tool. The tools and settings are discussed in the following sections.
Tip
Digitalizando polígonos no GRASS
If you want to create a polygon in GRASS, you first digitize the boundary of the polygon, setting the mode to ‘No category’. Then you add a centroid (label point) into the closed boundary, setting the mode to ‘Next not used’. The reason is, that a topological vector model links attribute information of a polygon always to the centroid and not to the boundary.
Barra de Ferramentas
In figure_grass_digitizing_1 you see the GRASS digitizing toolbar icons provided by the GRASS plugin. Table table_grass_digitizing_1 explains the available functionalities.
Figure GRASS digitizing 1:
Tabela GRASS Digitalização 1: Ferramentas de Digitalização GRASS
Separador Categoria
O separador Categoria permite definir a forma de como os valores categoria serão atribuídos a um novo elemento de geometria.
Figure GRASS digitizing 2:
Modo: que valor de categoria deverá ser aplicado aos novos elementos de geometria.
Entrada manual - defina manualmente os valores de categoria para o elemento da geometria no campo de entrada -‘Categoria’.
Sem categoria - Não aplica o valor da categoria ao elemento de geometria. Isto é por exemplo, usado para limites de áreas, porque os valores da categoria são ligados através do centróide.
Categoria - Um número (ID) é anexado a cada elemento de geometria digitalizado. É usado para ligar cada elemento de geometria com os seus atributos.
Campo(camada) - Cada elemento de geometria pode ser ligada a várias tabelas de atributos usando diferentes camadas de geometria GRASS. O número da camada padrão é 1.
Tip
Criando uma ‘camada’ GRASS adicional com o |qg|
If you would like to add more layers to your dataset, just add a new number in the ‘Field (layer)’ entry box and press return. In the Table tab you can create your new table connected to your new layer.
Separador das Configurações
The Settings tab allows you to set the snapping in screen pixels. The threshold defines at what distance new points or line ends are snapped to existing nodes. This helps to prevent gaps or dangles between boundaries. The default is set to 10 pixels.
Figure GRASS digitizing 3:
Separador da Simbologia
The Symbology tab allows you to view and set symbology and color settings for various geometry types and their topological status (e.g. closed / opened boundary).
Figure GRASS digitizing 4:
Separador Tabela
The Table tab provides information about the database table for a given ‘layer’. Here you can add new columns to an existing attribute table, or create a new database table for a new GRASS vector layer (see Section Criando uma nova camada vectorial GRASS).
Figure GRASS digitizing 5:
Tip
Editar Permissões GRASS
You must be the owner of the GRASS MAPSET you want to edit. It is impossible to edit data layers in a MAPSET that is not yours, even if you have write permissions.
The region definition (setting a spatial working window) in GRASS is important for working with raster layers. Vector analysis is by default not limited to any defined region definitions. But all newly-created rasters will have the spatial extension and resolution of the currently defined GRASS region, regardless of their original extension and resolution. The current GRASS region is stored in the $LOCATION/$MAPSET/WIND file, and it defines north, south, east and west bounds, number of columns and rows, horizontal and vertical spatial resolution.
It is possible to switch on/off the visualization of the GRASS region in the QGIS canvas using the Display current GRASS region button.
With the Edit current GRASS region icon you can open a dialog to change the current region and the symbology of the GRASS region rectangle in the QGIS canvas. Type in the new region bounds and resolution and click [OK]. It also allows to select a new region interactively with your mouse on the QGIS canvas. Therefore click with the left mouse button in the QGIS canvas, open a rectangle, close it using the left mouse button again and click [OK].
The GRASS module g.region provide a lot more parameters to define an appropriate region extend and resolution for your raster analysis. You can use these parameters with the GRASS Toolbox, described in Section The GRASS toolbox.
The Open GRASS Tools box provides GRASS module functionalities to work with data inside a selected GRASS LOCATION and MAPSET. To use the GRASS toolbox you need to open a LOCATION and MAPSET where you have write-permission (usually granted, if you created the MAPSET). This is necessary, because new raster or vector layers created during analysis need to be written to the currently selected LOCATION and MAPSET.
Figure GRASS toolbox 1:
The GRASS Shell inside the GRASS Toolbox provides access to almost all (more than 330) GRASS modules through a command line interface. To offer a more user friendly working environment, about 200 of the available GRASS modules and functionalities are also provided by graphical dialogs within the GRASS plugin Toolbox.
The GRASS Shell inside the GRASS Toolbox provides access to almost all (more than 300) GRASS modules in a command line interface. To offer a more user friendly working environment, about 200 of the available GRASS modules and functionalities are also provided by graphical dialogs.
A complete list of GRASS modules available in the graphical Toolbox in QGIS version 2.0 is available in the GRASS wiki (http://grass.osgeo.org/wiki/GRASS-QGIS_relevant_module_list).
It is also possible to customize the GRASS Toolbox content. This procedure is described in Section Customizing the GRASS Toolbox.
As shown in figure_grass_toolbox_1 , you can look for the appropriate GRASS module using the thematically grouped Modules Tree or the searchable Modules List tab.
Clicando no ícone do módulo gráfico será adicionado um novo separador ao diálogo da caixa de ferramentas fornecendo novos sub-separadores Opções, Saída e Manual.
Opções
The Options tab provides a simplified module dialog where you can usually select a raster or vector layer visualized in the QGIS canvas and enter further module specific parameters to run the module.
Figure GRASS module 1:
The provided module parameters are often not complete to keep the dialog clear. If you want to use further module parameters and flags, you need to start the GRASS Shell and run the module in the command line.
A new feature since QGIS 1.8 is the support for a show advanced options button below the simplified module dialog in the Options tab. At the moment it is only added to the module v.in.ascii as an example use, but will probably be part of more / all modules in the GRASS toolbox in future versions of QGIS. This allows to use the complete GRASS module options without the need to switch to the GRASS Shell.
Ficheiro de Saída
Figure GRASS module 2:
The Output tab provides information about the output status of the module. When you click the [Run] button, the module switches to the Output tab and you see information about the analysis process. If all works well, you will finally see a Successfully finished message.
Manual
Figure GRASS module 3:
The Manual tab shows the HTML help page of the GRASS module. You can use it to check further module parameters and flags or to get a deeper knowledge about the purpose of the module. At the end of each module manual page you see further links to the Main Help index, the Thematic index and the Full index. These links provide the same information as if you use the module g.manual.
Tip
Exibir os resultados imediatamente
Se quiser exibir os seus resultados do cálculo imediatamente no seu enquadramento do mapa, pode usar o botão ‘Ver ficheiro de saída’ no fundo do separador do módulo.
Os seguintes exemplos irão demonstrar o poder de alguns módulos GRASS.
The first example creates a vector contour map from an elevation raster (DEM). Assuming you have the Alaska LOCATION set up as explained in Section Importando dados para uma LOCALIZAÇÃO GRASS.
Since this is a large region, it will take a while to display. After it finishes rendering, you can open the layer properties window to change the line color so that the contours appear clearly over the elevation raster, as in The Vector Properties Dialog.
Next zoom in to a small mountainous area in the center of Alaska. Zooming in close you will notice that the contours have sharp corners. GRASS offers the v.generalize tool to slightly alter vector maps while keeping their overall shape. The tool uses several different algorithms with different purposes. Some of the algorithms (i.e. Douglas Peuker and Vertex reduction) simplify the line by removing some of the vertices. The resulting vector will load faster. This process will be used when you have a highly detailed vector, but you are creating a very small scale map, so the detail is unnecessary.
Tip
**A ferramenta de simplificação
Note that the QGIS fTools plugin has a Simplify geometries ‣ tool that works just like the GRASS v.generalize Douglas-Peuker algorithm.
However, the purpose of this example is different. The contour lines created by r.contour have sharp angles that should be smoothed. Among the v.generalize algorithms there is Chaikens which does just that (also Hermite splines). Be aware that these algorithms can add additional vertices to the vector, causing it to load even more slowly.
Figure GRASS module 4:
Tip
Outros usos para o r.contour
The procedure described above can be used in other equivalent situations. If you have a raster map of precipitation data, for example, then the same method will be used to create a vector map of isohyetal (constant rainfall) lines.
Several methods are used to display elevation layers and give a 3D effect to maps. The use of contour lines as shown above is one popular method often chosen to produce topographic maps. Another way to display a 3D effect is by hillshading. The hillshade effect is created from a DEM (elevation) raster by first calculating the slope and aspect of each cell, then simulating the sun’s position in the sky and giving a reflectance value to each cell. Thus you get sun facing slopes lighted and the slopes facing away from the sun (in shadow) are darkened.
De seguida clique em r.shaded.relief para abrir o módulo.
You should now have the gtopo30 elevation with its colormap and transparency setting displayed above the grayscale hillshade map. In order to see the visual effects of the hillshading, turn off the gtopo30_shade map, then turn it back on.
Usando a linha de comandos do GRASS
The GRASS plugin in QGIS is designed for users who are new to GRASS, and not familiar with all the modules and options. As such, some modules in the toolbox do not show all the options available, and some modules do not appear at all. The GRASS shell (or console) gives the user access to those additional GRASS modules that do not appear in the toolbox tree, and also to some additional options to the modules that are in the toolbox with the simplest default parameters. This example demonstrates the use of an additional option in the r.shaded.relief module that was shown above.
Figure GRASS module 5:
The module r.shaded.relief can take a parameter zmult which multiplies the elevation values relative to the X-Y coordinate units so that the hillshade effect is even more pronounced.
Figure GRASS module 6:
The next example shows how a GRASS module can aggregate raster data and add columns of statistics for each polygon in a vector map.
Another useful feature inside the GRASS Toolbox is the GRASS LOCATION browser. In figure_grass_module_7 you can see the current working LOCATION with its MAPSETs.
In the left browser windows you can browse through all MAPSETs inside the current LOCATION. The right browser window shows some meta information for selected raster or vector layers, e.g. resolution, bounding box, data source, connected attribute table for vector data and a command history.
Figure GRASS module 7:
The toolbar inside the Browser tab offers following tools to manage the selected LOCATION:
The Rename selected map and Delete selected map only work with maps inside your currently selected MAPSET. All other tools also work with raster and vector layers in another MAPSET.
Nearly all GRASS modules can be added to the GRASS toolbox. A XML interface is provided to parse the pretty simple XML files which configures the modules appearance and parameters inside the toolbox.
A sample XML file for generating the module v.buffer (v.buffer.qgm) looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE qgisgrassmodule SYSTEM "http://mrcc.com/qgisgrassmodule.dtd">
<qgisgrassmodule label="Vector buffer" module="v.buffer">
<option key="input" typeoption="type" layeroption="layer" />
<option key="buffer"/>
<option key="output" />
</qgisgrassmodule>
The parser reads this definition and creates a new tab inside the toolbox when you select the module. A more detailed description for adding new modules, changing the modules group, etc. can be found on the QGIS wiki at http://hub.qgis.org/projects/quantum-gis/wiki/Adding_New_Tools_to_the_GRASS_Toolbox