Chapter 9. Topologia

Table of Contents

Os tipos e as funções de topologia do PostGIS são usados para administrar objetos como: faces, bordas e nodos.

Sandro Santilli's presentation at PostGIS Day Paris 2011 conference gives a good synopsis of PostGIS Topology and where it is headed Topology with PostGIS 2.0 slide deck.

Vincent Picavet provides a good synopsis and overview of what is Topology, how is it used, and various FOSS4G tools that support it in PostGIS Topology PGConf EU 2012.

Um exemplo de um banco de dados GIS baseado topologicamente é o banco de dados US Census Topologically Integrated Geographic Encoding and Referencing System (TIGER). Se você quiser experimentar com a topologia POstGIS e precisa de alguns dados, confira Topology_Load_Tiger.

O módulo PostGIS Topologia existiu em versões anteriores, mas nunca foi parte da documentação Oficial do PostGIS. A maior limpeza PostGIS 2.0.0, vai remover todas as funções menores, consertar problemas de usabilidade, vai documentar melhor as características e funções e melhorar a conformidade com os padrões SQL-MM.

Detalhes deste projeto podem ser encontrados em PostGIS Topology Wiki

Todas as funções e tables associadas com este módulo estão instaladas em um esquema nomeado topology.

Funções que são definidas no padrão SQL/MM estão prefixadas com ST_ e funções específicas para o POstGIS não estão prefixadas.

Topology support is build by default starting with PostGIS 2.0, and can be disabled specifying --without-topology configure option at build time as described in Chapter 2, Instalação do PostGIS

9.1. Tipos de topologia

Abstract

Essa seção lista os tipos de dados PostgreSQL instalados pela topologia PostGIS. Note que descrevemos o comportamento de distribuição de papeis desses, que são bastante importantes quando desenvolvem suas próprias funções.

  • getfaceedges_returntype — A composite type that consists of a sequence number and an edge number.
  • TopoGeometry — A composite type representing a topologically defined geometry.
  • validatetopology_returntype — A composite type that consists of an error message and id1 and id2 to denote location of error. This is the return type for ValidateTopology.

9.2. Domínios de Topologia

Abstract

Esta seção lista os domínios do PostgreSQL instalados pela Topologia PostGIS. Os domínios podem ser usados como tipos objetos de funções ou table columns. A distinção entre um domínio e um tipo é que o domínio é um tipo existente com uma restrição verificada ligada a ele.

  • TopoElement — Um arranjo de 2 inteiros geralmente usado para identificar um componente TopoGeometry.
  • TopoElementArray — An array of TopoElement objects.

9.3. Gerenciamento de Topologia e TopoGeometria

Abstract

Esta seção lista as funções da Topologia para construir novos esquemas de Topologia, validando topologias e gerenciar Colunas TopoGeometrias

  • AddTopoGeometryColumn — Adiciona uma coluna topogeometria a uma table, registra essa coluna nova como uma camada topology.layer e retorna a nova layer_id.
  • RenameTopoGeometryColumn — Renames a topogeometry column
  • DropTopology — Cuidado ao usar: Derruba um esquema topologia e deleta sua referência da table topology.topology e referências para tables naquele esquema da table geometry_columns.
  • RenameTopology — Renames a topology
  • DropTopoGeometryColumn — Derruba a coluna topogeometria da table nomeada table_name no esquema schema_name e tira os registros da
  • Populate_Topology_Layer — Adds missing entries to topology.layer table by reading metadata from topo tables.
  • TopologySummary — Takes a topology name and provides summary totals of types of objects in topology.
  • ValidateTopology — Returns a set of validatetopology_returntype objects detailing issues with topology.
  • ValidateTopologyRelation — Returns info about invalid topology relation records
  • FindTopology — Returns a topology record by different means.
  • FindLayer — Returns a topology.layer record by different means.

9.4. Topology Statistics Management

Abstract

This section discusses management of database statistics during topology building.

Adding elements to a topology triggers many database queries for finding existing edges that will be split, adding nodes and updating edges that will node with the new linework. For this reason it is useful that statistics about the data in the topology tables are up-to-date.

PostGIS Topology population and editing functions do not automatically update the statistics because a updating stats after each and every change in a topology would be overkill, so it is the caller's duty to take care of that.

[Note]

That the statistics updated by autovacuum will NOT be visible to transactions which started before autovacuum process completed, so long-running transactions will need to run ANALYZE themselves, to use updated statistics.

9.5. Construtores de topologia

Abstract

Esta seção cobre as funções da topologia para criar novas topologias.

  • CreateTopology — Creates a new topology schema and registers it in the topology.topology table.
  • CopyTopology — Makes a copy of a topology (nodes, edges, faces, layers and TopoGeometries) into a new schema
  • ST_InitTopoGeo — Creates a new topology schema and registers it in the topology.topology table.
  • ST_CreateTopoGeo — Adiciona uma coleção de geometrias para uma dada topologia vazia e retorna uma mensagem detalhando sucesso.
  • TopoGeo_AddPoint — Adiciona um ponto a uma topologia usando uma tolerância e possivelmente dividindo um limite existente.
  • TopoGeo_AddLineString — Adds a linestring to an existing topology using a tolerance and possibly splitting existing edges/faces. Returns edge identifiers.
  • TopoGeo_AddPolygon — Adds a polygon to an existing topology using a tolerance and possibly splitting existing edges/faces. Returns face identifiers.
  • TopoGeo_LoadGeometry — Load a geometry into an existing topology, snapping and splitting as needed.

9.6. Editores de Topologia

Abstract

Esta seção cobre as funções da topologia para adicionar, mover, deletar e dividir limites, faces e nós. Todas essas funções são definidas pelo

  • ST_AddIsoNode — Adiciona um nó isolado a uma face em uma topologia e retorna a id do novo nó. Se a face é nula, o nó continua sendo criado.
  • ST_AddIsoEdge — Adiciona um limite isolado definido pela geometria alinestring a uma topologia conectando dois nós isoladosanode e anothernode e retorna a nova id do novo limite.
  • ST_AddEdgeNewFaces — Adiciona um novo limite e, se uma face for dividida, deleta a face original e substitui por duas novas faces.
  • ST_AddEdgeModFace — Adiciona um novo limite e, se uma face for dividida, modifica a face original e adiciona uma nova face.
  • ST_RemEdgeNewFace — Remove um limite e, se o limite removido separava duas faces, deleta as faces originais e as substitui por uma nova face.
  • ST_RemEdgeModFace — Removes an edge, and if the edge separates two faces deletes one face and modifies the other face to cover the space of both.
  • ST_ChangeEdgeGeom — Modifica a forma de um limite sem afetar a estrutura da topologia.
  • ST_ModEdgeSplit — Divide um limite criando um novo nó junto de um limite existente, modificando o limite original e adicionando um novo limite.
  • ST_ModEdgeHeal — Heals two edges by deleting the node connecting them, modifying the first edge and deleting the second edge. Returns the id of the deleted node.
  • ST_NewEdgeHeal — Heals two edges by deleting the node connecting them, deleting both edges, and replacing them with an edge whose direction is the same as the first edge provided.
  • ST_MoveIsoNode — Moves an isolated node in a topology from one point to another. If new apoint geometry exists as a node an error is thrown. Returns description of move.
  • ST_NewEdgesSplit — Divide um limite criando um novo nó ao longo do limite existente, deletando o limite original e substituindo-o por dois novos. Retorna a id do novo nó criado que integra os novos limites.
  • ST_RemoveIsoNode — Remove um nó isolado e retorna descrição de ação. Se o nó não for isolado (for começo ou fim de um limite), então, uma exceção é lançada.
  • ST_RemoveIsoEdge — Removes an isolated edge and returns description of action. If the edge is not isolated, then an exception is thrown.

9.7. Assessores de Topologia

  • GetEdgeByPoint — Finds the edge-id of an edge that intersects a given point.
  • GetFaceByPoint — Finds face intersecting a given point.
  • GetFaceContainingPoint — Finds the face containing a point.
  • GetNodeByPoint — Finds the node-id of a node at a point location.
  • GetTopologyID — Retorna a id de uma topologia na table topology.topology dado o nome da topologia.
  • GetTopologySRID — Retorna o SRID de uma topologia na table topology.topology dado o nome da topologia.
  • GetTopologyName — Retorna o nome de uma topologia (esquema) dada a id da topologia.
  • ST_GetFaceEdges — Retorna um conjunto de limites ordenados que amarram aface.
  • ST_GetFaceGeometry — Retorna o polígono na topologia dada com a id de face especificada.
  • GetRingEdges — Retorna o conjunto ordenado de identificadores de limites assinados, conhecidos caminhando em um lado da beirada.
  • GetNodeEdges — Retorna um conjunto ordenado de limites incidentes no dado nó.

9.8. Processamento de Topologia

Abstract

Esta seção cobre as funções para processar topologias de maneiras não padronizadas.

  • Polygonize — Finds and registers all faces defined by topology edges.
  • AddNode — Adiciona um ponto nó na table nó no esquema topológico específico e retorna a nodeid do novo nó. Se o ponto já existe, a nodeid é retornada.
  • AddEdge — Adiciona uma linestring limite à edge table e os pontos de início e fim associados à table ponto nó do esquema de topologia especificado usando a linestring geometria específica e retorna a bordaid da nova borda (ou da borda já existente).
  • AddFace — Registra uma face primitiva a uma topologia e pega seu identificador.
  • ST_Simplify — Retorna uma versão "simplificada" da geometria da dada TopoGeometria usando o algorítimo Douglas-Peucker.
  • RemoveUnusedPrimitives — Removes topology primitives which not needed to define existing TopoGeometry objects.

9.9. Construtores de TopoGeometria

Abstract

Esta seção cobre as funções da topologia para criar novas topogeometrias.

  • CreateTopoGeom — Cria uma novo objeto de topo geometria de um arranjo topo elemento - tg_type: 1:[multi]point, 2:[multi]line, 3:[multi]poly, 4:collection
  • toTopoGeom — Converts a simple Geometry into a topo geometry.
  • TopoElementArray_Agg — Returns a topoelementarray for a set of element_id, type arrays (topoelements).
  • TopoElement — Converts a topogeometry to a topoelement.

9.10. Editores de TopoGeometria

Abstract

Esta seção cobre as funções da topologia para editar topogeometrias existentes.

9.11. Assessores de TopoGeometria

  • GetTopoGeomElementArray — Returns a topoelementarray (an array of topoelements) containing the topological elements and type of the given TopoGeometry (primitive elements).
  • GetTopoGeomElements — Returns a set of topoelement objects containing the topological element_id,element_type of the given TopoGeometry (primitive elements).
  • ST_SRID — Returns the spatial reference identifier for a topogeometry.

9.12. TopoGeometry Outputs

  • AsGML — Retorna a representação GML de uma topogeometria.
  • AsTopoJSON — Retorna a representação TopoJSON de uma topogeometria.

9.13. Relações de Topologia Espacial

Abstract

Esta seção lista as funções Topológicas usadas para verificar as relações entre topogeometrias e topologias primitivas

  • Equals — Retorna verdade se duas topogeometrias forem compostas da mesma topologia primitiva
  • Intersects — Retorna verdade se algum par de primitivos das duas topologias se intersectar.

9.14. Importing and exporting Topologies

Once you have created topologies, and maybe associated topological layers, you might want to export them into a file-based format for backup or transfer into another database.

Using the standard dump/restore tools of PostgreSQL is problematic because topologies are composed by a set of tables (4 for primitives, an arbitrary number for layers) and records in metadata tables (topology.topology and topology.layer). Additionally, topology identifiers are not univoque across databases so that parameter of your topology will need to be changes upon restoring it.

In order to simplify export/restore of topologies a pair of executables are provided: pgtopo_export and pgtopo_import. Example usage:

pgtopo_export dev_db topo1 | pgtopo_import topo1 | psql staging_db

9.14.1. Using the Topology exporter

The pgtopo_export script takes the name of a database and a topology and outputs a dump file which can be used to import the topology (and associated layers) into a new database.

By default pgtopo_export writes the dump file to the standard output so that it can be piped to pgtopo_import or redirected to a file (refusing to write to terminal). You can optionally specify an output filename with the -f commandline switch.

By default pgtopo_export includes a dump of all layers defined against the given topology. This may be more data than you need, or may be non-working (in case your layer tables have complex dependencies) in which case you can request skipping the layers with the --skip-layers switch and deal with those separately.

Invoking pgtopo_export with the --help (or -h for short) switch will always print short usage string.

The dump file format is a compressed tar archive of a pgtopo_export directory containing at least a pgtopo_dump_version file with format version info. As of version 1 the directory contains tab-delimited CSV files with data of the topology primitive tables (node, edge_data, face, relation), the topology and layer records associated with it and (unless --skip-layers is given) a custom-format PostgreSQL dump of tables reported as being layers of the given topology.

9.14.2. Using the Topology importer

The pgtopo_import script takes a pgtopo_export format topology dump and a name to give to the topology to be created and outputs an SQL script reconstructing the topology and associated layers.

The generated SQL file will contain statements that create a topology with the given name, load primitive data in it, restores and registers all topology layers by properly linking all TopoGeometry values to their correct topology.

By default pgtopo_import reads the dump from the standard input so that it can be used in conjuction with pgtopo_export in a pipeline. You can optionally specify an input filename with the -f commandline switch.

By default pgtopo_import includes in the output SQL file the code to restore all layers found in the dump.

This may be unwanted or non-working in case your target database already have tables with the same name as the ones in the dump. In that case you can request skipping the layers with the --skip-layers switch and deal with those separately (or later).

SQL to only load and link layers to a named topology can be generated using the --only-layers switch. This can be useful to load layers AFTER resolving the naming conflicts or to link layers to a different topology (say a spatially-simplified version of the starting topology).