- Location:
- /trunk/workshop-foss4g
- Files:
-
- 29 edited
Legend:
- Unmodified
- Added
- Removed
-
/trunk/workshop-foss4g/projection.rst
r61 r1 1 1 .. _projection: 2 2 3 Partie 15 : Projections des données 4 =========================== ========3 Section 15: Projecting Data 4 =========================== 5 5 6 La Terre n'est pas plate et il n'y a pas de moyen simple de la poser à plat sur une carte en papier (ou l'écran d'un ordinateur). Certaines projections préservent les aires, donc tout les objets ont des tailles relatives aux autres, d'autre projections conservent les angles (conformes) comme la projection Mercator. Certaines projections tentent de minimiser la distorsion des différents paramÚtres. Le point commun entre toutes les projections est qu'elles transforment le monde (sphérique) en un systÚme plat de coordonnées cartésiennes, et le choix de la projection dépend de ce que vous souhaitez faire avec vos données.6 The earth is not flat, and there is no simple way of putting it down on a flat paper map (or computer screen), so people have come up with all sorts of ingenious solutions, each with pros and cons. Some projections preserve area, so all objects have a relative size to each other; other projections preserve angles (conformal) like the Mercator projection; some projections try to find a good intermediate mix with only little distortion on several parameters. Common to all projections is that they transform the (spherical) world onto a flat cartesian coordinate system, and which projection to choose depends on how you will be using the data. 7 7 8 Nous avons déjà recontrer des projections, lorsque nous avons charger les données de la ville de Ney York .Rappelez-vous qu'elles utilisaient le SRID 26918. Parfois, vous aurez malgré tout besoin de transformer et de reprojeter vos données d'un systÚme de projection à un autre, en utilisant la fonction :command:`ST_Transform(geometry, srid)`. Pour manipuler les identifiant de systÚmes de références spatiales à partir d'une géométrie, PostGIS fournit les fonctions :command:`ST_SRID(geometry)` et :command:`ST_SetSRID(geometry, srid)`.8 We've already encountered projections when we :ref:`loaded our nyc data <loading_data>`. (Recall that pesky SRID 26918). Sometimes, however, you need to transform and re-project between spatial reference systems. PostGIS includes built-in support for changing the projection of data, using the :command:`ST_Transform(geometry, srid)` function. For managing the spatial reference identifiers on geometries, PostGIS provides the :command:`ST_SRID(geometry)` and :command:`ST_SetSRID(geometry, srid)` functions. 9 9 10 Nous pouvons vérifier le SRID de nos données avec la commande :command:`ST_SRID`:10 We can confirm the SRID of our data with the :command:`ST_SRID` command: 11 11 12 12 .. code-block:: sql … … 18 18 26918 19 19 20 Et quelle est la définition du "26918" ? Comme nous l'avons vu lors de la partie ":ref:`chargement des données`", la définition se trouve dans la table ``spatial_ref_sys``. En fait, **deux** définitions sont présentes. La définition au format :term:`WKT` dans la colonne ``srtext`` 20 And what is definition of "26918"? As we saw in ":ref:`loading data section <loading_data>`", the definition is contained in the ``spatial_ref_sys`` table. In fact, **two** definitions are there. The "well-known text" (:term:`WKT`) definition is in the ``srtext`` column, and there is a second definition in "proj.4" format in the ``proj4text`` column. 21 21 22 22 .. code-block:: sql … … 24 24 SELECT * FROM spatial_ref_sys WHERE srid = 26918; 25 25 26 En fait, pour les calculs internes de re-projection, c'est le contenu de la colonne ``proj4text`` qui est utilisé. Pour notre projection 26918, voici la définition au format proj.4:26 In fact, for the internal PostGIS re-projection calculations, it is the contents of the ``proj4text`` column that are used. For our 26918 projection, here is the proj.4 text: 27 27 28 28 .. code-block:: sql … … 34 34 +proj=utm +zone=18 +ellps=GRS80 +datum=NAD83 +units=m +no_defs 35 35 36 En pratique, les deux colonnes ``srtext`` et ``proj4text`` sont importantes : la colonne ``srtext`` est utilisée par les applications externes comme `GeoServer <http://geoserver.org>`_, uDig <udig.refractions.net>`_, `FME <http://www.safe.com/>`_ et autres, alors que la colonne ``proj4text`` est principalement utilisée par PostGIS en interne.36 In practice, both the ``srtext`` and the ``proj4text`` columns are important: the ``srtext`` column is used by external programs like `GeoServer <http://geoserver.org>`_, `uDig <udig.refractions.net>`_, and `FME <http://www.safe.com/>`_ and others; the ``proj4text`` column is used internally. 37 37 38 Compar aison de données39 -------------- --------38 Comparing Data 39 -------------- 40 40 41 Combinés, une coordonnée et un SRID définissent une position sur le globe. Sans le SRID, une coordonnée est juste une notion abstraite. Un systÚme de coordonnées "cartésiennes" est définit comme un systÚme de coordonnées "plat" sur la surface de la Terre. Puisque les fonctions de PostGIS utilisent cette surface plane, les opérations de comparaison nécessitent que l'ensemble des objets géométriques soient représentés dans le même systÚme, ayant le même SRID.41 Taken together, a coordinate and an SRID define a location on the globe. Without an SRID, a coordinate is just an abstract notion. A âCartesianâ coordinate plane is defined as a âflatâ coordinate system placed on the surface of Earth. Because PostGIS functions work on such a plane, comparison operations require that both geometries be represented in the same SRID. 42 42 43 Si vous utilisé des géométries avec différents SRID vous obtiendrez une erreur comme celle-ci:43 If you feed in geometries with differing SRIDs you will just get an error: 44 44 45 45 .. code-block:: sql … … 58 58 .. note:: 59 59 60 Faites attention de pas utiliser la transformation à la volée à l'aide de :command:`ST_Transform` trop souvent. Les indexes spatiaux sont construits en utilisant le SRID inclu dans les géométries. Si la comparaison est faite avec un SRID différent, les indexes spatiaux ne seront pas (la plupart du temps) utilisés. Il est reconnu qu'il vaut mieux choisir **un SRID** pour toutes les tables de votre base de données. N'utilisez la fonction de tranformation que lorsque vous lisez ou écrivez les données depuis une application externe.60 Be careful of getting too happy with using :command:`ST_Transform` for on-the-fly conversion. Spatial indexes are built using SRID of the stored geometries. If comparison are done in a different SRID, spatial indexes are (often) not used. It is best practice to choose **one SRID** for all the tables in your database. Only use the transformation function when you are reading or writing data to external applications. 61 61 62 62 63 Transform er les données64 ----------------- ------63 Transforming Data 64 ----------------- 65 65 66 Si vous retournez à la définition au format proj4 du SRID 26918, vous pouvez voir que notre projectioin actuelle est de type UTM zone 18 (Universal Transvers Mercator), avec le mÚtre comme unité de mesure.66 If we return to our proj4 definition for SRID 26918, we can see that our working projection is UTM (Universal Transverse Mercator) of zone 18, with meters as the unit of measurement. 67 67 68 68 :: … … 70 70 +proj=utm +zone=18 +ellps=GRS80 +datum=NAD83 +units=m +no_defs 71 71 72 Essayons de convertir certaines données de notre systÚme de projection dans un systÚme de coordonnées géographiques connu comme "longitude/latitude". 72 Let's convert some data from our working projection to geographic coordinates -- also known as "longitude/latitude". 73 73 74 Pour convertir les données d'un SRID à l'autre, nous devons dans un premier temps vérifier que nos géométries ont un SRID valide. une fois que nous avons vérifié cela, nous devons ensuite trouver le SRID dans le lequel nous souhaitons re-projeter. En d'autre terme, quel est le SRID des coordonnées géographiques?74 To convert data from one SRID to another, you must first verify that your geometry has a valid SRID. Since we have already confirmed a valid SRID, we next need the SRID of the projection to transform into. In other words, what is the SRID of geographic coordinates? 75 75 76 Le SRID le plus connu pour les coordonnées géographiques est le 4326, qui correspond au couple "longitude/latitude sur la sphéroïde WGS84". Vous pouvez voir sa définition sur le site spatialreference.org. 76 The most common SRID for geographic coordinates is 4326, which corresponds to "longitude/latitude on the WGS84 spheroid". You can see the definition at the spatialreference.org site: 77 77 78 78 http://spatialreference.org/ref/epsg/4326/ 79 79 80 Vous pouvez aussi récupérer les définitions dans la table ``spatial_ref_sys``:80 You can also pull the definitions from the ``spatial_ref_sys`` table: 81 81 82 82 .. code-block:: sql … … 94 94 AUTHORITY["EPSG","4326"]] 95 95 96 Essayons de convertir les cordonnées de la station 'Broad St':96 Let's convert the coordinates of the 'Broad St' subway station into geographics: 97 97 98 98 .. code-block:: sql … … 106 106 POINT(-74.0106714688735 40.7071048155841) 107 107 108 Si vous chargez les données ou créez une nouvelle géométrie sans spécifier de SRID, la valeur du SRID prendra alors la valeur -1. Rapellez-vous que dans les :ref:`geometries`, lorsque nous avons créé nos tables géométriques nous n'avions pas spécifié un SRID. Si nous interrogeons la base, nous devons nous attendre à ce que toutes les tables préfixées par ``nyc_`` aient le SRID 26918, alors que la table ``geometries`` aura la valeur -1 par défaut.108 If you load data or create a new geometry without specifying an SRID, the SRID value will be -1. Recall in :ref:`geometries`, that when we created our ``geoemetries`` table we didn't specify an SRID. If we query our database, we should expect all the ``nyc_`` tables to have an SRID of 26918, while the ``geometries`` table defaulted to an SRID of -1. 109 109 110 Pour visualiser la table d'assignation des SRID, interroger la table ``geometry_columns`` de la base de données.110 To view a table's SRID assignment, query the database's ``geometry_columns`` table. 111 111 112 112 .. code-block:: sql … … 126 126 127 127 128 Néanmoins, si vous connaissez le SRID de vos données, vous pouvez l'affecter par la suite en utilisant la fonction :command:`ST_SetSRID` sur les géométries. Ensuite vous pourrez les tranformer dans d'autres systÚmes de projections.128 However, if you know what the SRID of the coordinates is supposed to be, you can set it post-facto, using :command:`ST_SetSRID` on the geometry. Then you will be able to transform the geometry into other systems. 129 129 130 130 .. code-block:: sql … … 137 137 FROM geometries; 138 138 139 Liste des fonctions 140 ------------------- 139 Function List 140 ------------- 141 `ST_AsText <http://postgis.org/docs/ST_AsText.html>`_: Returns the Well-Known Text (WKT) representation of the geometry/geography without SRID metadata. 141 142 142 `ST_ AsText <http://postgis.org/docs/ST_AsText.html>`_: retourne la représentation au format Well-Known Text (WKT) sans la métadonnée SRID.143 `ST_SetSRID(geometry, srid) <http://postgis.org/docs/ST_SetSRID.html>`_: Sets the SRID on a geometry to a particular integer value. 143 144 144 `ST_S etSRID(geometry, srid) <http://postgis.org/docs/ST_SetSRID.html>`_: affecte une valeur au SRID d'une géométrie.145 `ST_SRID(geometry) <http://postgis.org/docs/ST_SRID.html>`_: Returns the spatial reference identifier for the ST_Geometry as defined in spatial_ref_sys table. 145 146 146 `ST_SRID(geometry) <http://postgis.org/docs/ST_SRID.html>`_: retourne l'indentifiant du systÚme de références spatialesd'un objet ST_Geometry comme définit dans la table spatial_ref_sys. 147 148 `ST_Transform(geometry, srid) <http://postgis.org/docs/ST_Transform.html>`_: retourne une nouvelle géométrie aprÚs avoi re-projeté les données dans le systÚme correspondant au SRID passé en paramÚtre. 147 `ST_Transform(geometry, srid) <http://postgis.org/docs/ST_Transform.html>`_: Returns a new geometry with its coordinates transformed to the SRID referenced by the integer parameter. -
/trunk/workshop-foss4g/introduction.rst
r61 r1 1 1 .. _introduction: 2 2 3 Partie 1 : Introduction 3 Partie 1 : Introduction 4 4 ************************ 5 5 … … 7 7 ============================================ 8 8 9 PostGIS est une base de données spatiale . Oracle Spatial et SQL Server 2008 sont aussi des bases de données spatiales. Mais qu'est-ce que cela signifie? Qu'est-ce qui différencie un serveur de base de données spatiales d'un serveur de base de donnéesnon spatiale ?9 PostGIS est une base de données spatiales. Oracle Spatial et SQL Server 2008 sont aussi des bases de données spatiales. Mais qu'est-ce que cela signifie, qu'est-ce qui différentie un serveur de base de données spatiales d'un non spatiale ? 10 10 11 11 La réponse courte, est ... 12 12 13 **Les base s de données spatiales permettent le stockage et la manipulation des objets spatiaux comme les autres objets de la base de données.**14 15 Ce qui suit présente briÚvement l'évolution des base sde données spatiales, puis les liens16 entre les données spatiales et la base de données (types de données, index et fonctions).17 18 #. **Types de données spatiales** fait référence aux géométries de type point, ligne et polygone; 19 #. L'**indexation spatiale** est utilisée pour améliorer les performance sd'exécution des opérations spatiales;20 #. Les **fonctions spatiales**, au sens :term:`SQL`, sont util isées pour accéder à des propriétés ou Ãdes relations spatiales.21 22 Utilisés de maniÚre combinée, les types de données spatiales, les index et les fonctions fournissent une structure flexible pour optimiser les performanceset les analyses.13 **Les base de données spatiales permettent les stocage et la manipulation des objets spatiaux comme les autres objets de la base de données.** 14 15 Ce qui suit présente briÚvement l'évolution des base de données spatiales, puis les liens 16 entre les données spatiales et la base de données (types de données, indexes et fonctions). 17 18 #. **Types de données spatiales** fait référence aux géométries de type point, ligne et polygone; 19 #. L'**indexation spatiale** est utilisée pour améliorer les performance d'exécution des opérations spatiales; 20 #. Les **fonctions spatiales**, au sens :term:`SQL`, sont utilsées pour accéder à des propriétées ou des relations spatiales. 21 22 Conbiné, les types de données spatiales, les indexes et les fonctions fournissent une structure flexible pour optimiser les performance et les analyses. 23 23 24 24 Au commencement 25 25 ---------------- 26 26 27 Dans les premiÚres implémentations :term:`SIG`, toutes les données spatiales étaient stockées sous la forme de fichiers plats et certaines applications :term:`SIG` spécifiques étaient nécessaires pour les interpréter et les manipuler. Ces outils de gestion de premiÚre génération avaient été conçus pour répondre aux besoins des utilisateurs pour lesquels toutes les données étaient localisées au sein de leur agence. Ces outils propriétaires étaient des systÚmes specifiquement créés pour gérer les données spatiales. 28 29 La seconde génération des systÚmes de gestion de données spatiales stockait certaines données dans une base de données relationelle (habituellement les "attributs" ou autres parties non spatiales) mais ne fournissaient pas encore la flexibilité offerte par une intégration complÚte des données spatiales. 30 31 **Effectivement, les bases de données spatiales sont nées lorsque les gens ont commencé à considérer les objet spatiaux comme les autres objets d'une base de données .** 32 33 Les bases de données spatiales intÚgrent les données spatiales sous forme d'objets de la base de données relationnelle. Le changement opéré passe d'une vision centrée sur le SIG à une vision centrée sur les bases de données. 27 Dans les premiÚres implémentations :term:`SIG` historiques, toutes les données 28 spatiales étaient stoquées sous la forme de fichiers plats et certaines applications 29 :term:`SIG` spécifiques étaient nécessaires pour interpréter et manipuler les données. 30 Ces outils de gestion de premiÚre génération, avaient été conçu pour répondre aux 31 besoins des utilisateurs pour lesquels toute les données étaient localisé au sein de leur 32 agence. C'est outils étaient propriétaire, des systÚme specifiquement créé pour gérer les 33 données spatiales. 34 35 La seconde génération des systÚmes de gestion de données spatiales stoque certaines données dans une base de données relationelle 36 37 Second-generation spatial systems store some data in relational databases (usually the "attribute" or non-spatial parts) but still lack the flexibility afforded with direct integration. 38 39 **Effectivement, les bases de données spatiales sont nés lorsque les gens ont commencé à considérer les objet spatiaux comme des objets de base de données.** 40 41 Spatial databases fully integrate spatial data with an object relational database. The orientation changes from GIS-centric to database-centric. 34 42 35 43 .. image:: ./introduction/beginning.png 36 44 37 .. note:: Un systÚme de gestion de base de données peut être utilisé dans d'autres cadres que celui des SIG. Les bases de données spatiales sont utilisées dans divers domaines : l'anatomie humaine, les circuits intégrés de grandes envergures, les structures moléculaires, les champs electro-magnétiques et bien d'autres encore.38 39 40 Les types de données spatiales41 ------------------ ------------42 43 Une base de données classique propose par exemple les types chaînes de caractÚres et date. Une base de données spatiales ajoute les types de données (spatiales) pour représenter les **entités géographiques**. Ces types de données spatiales permettent d'accéder à des propriétés de l'entité géographique comme ses contours ou sa dimension. Pour bien des aspects, les types de données spatiales peuvent être vus simplement comme des formes. 45 .. note:: A spatial database management system may be used in applications besides the geographic world. Spatial databases are used to manage data related to the anatomy of the human body, large-scale integrated circuits, molecular structures, and electro-magnetic fields, among others. 46 47 48 Spatial Data Types 49 ------------------ 50 51 An ordinary database has strings, numbers, and dates. A spatial database adds additional (spatial) types for representing **geographic features**. These spatial data types abstract and encapsulate spatial structures such as boundary and dimension. In many respects, spatial data types can be understood simply as shapes. 44 52 45 53 .. image:: ./introduction/hierarchy.png 46 54 :align: center 47 55 48 Les types de données spatiales sont organisés par une hiérarchie de type. Chaque sous-type hérite de la structure (les attributs) et du comportement (les méthodes et fonctions) de son type supérieur dans la hierarchie. 49 50 51 Index spatiaux et étendue 52 --------------------------- 53 54 Une base de données ordinaire fournit des "méthodes d'accÚs" -- connues sous le nom d'**index** -- pour permettre un accÚs efficace et non séquentiel à un sous ensemble de données. L'indexation des types non géographiques (nombre, chaînes de caractÚres, dates) est habituellement faite à l'aide des index de type `arbres binaires <http://en.wikipedia.org/wiki/B-tree>`__. Un arbre binaire est un partitionnement des données utilisant l'ordre naturel pour stocker les données hiérarchiquement.55 56 L'ordre naturel des nombres, des chaînes de caractÚres et des dates est assez simple à déterminer -- chaque valeur est inférieure, plus grande ou égale à toutes les autres valeurs. Mais, étant donné que les polygones peuvent se chevaucher, peuvent être contenus dans un autre et sont représentés par un tableau en deux dimensions (ou plus), un arbre binaire ne convient pas pour indexer les valeurs. Les vraies bases de données spatiales fournissent un "index spatial" qui répond plutÃŽt à la question : "quel objet se trouve dans une étendue spécifique ?" 57 58 Une **étendue** correspond au rectangle de plus petite taille capable de contenir un objet géographique. 56 Spatial data types are organized in a type hierarchy. Each sub-type inherits the structure (attributes) and the behavior (methods or functions) of its super-type. 57 58 59 Spatial Indexes and Bounding Boxes 60 ---------------------------------- 61 62 An ordinary database provides "access methods" -- commonly known as **indexes** -- to allow for fast and random access to subsets of data. Indexing for standard types (numbers, strings, dates) is usually done with `B-tree <http://en.wikipedia.org/wiki/B-tree>`_ indexes. A B-tree partitions the data using the natural sort order to put the data into a hierarchical tree. 63 64 The natural sort order of numbers, strings, and dates is simple to determine -- every value is less than, greater than or equal to every other value. But because polygons can overlap, can be contained in one another, and are arrayed in a two-dimensional (or more) space, a B-tree cannot be used to efficiently index them. Real spatial databases provide a "spatial index" that instead answers the question "which objects are within this particular bounding box?". 65 66 A **bounding box** is the smallest size rectangle capable of containing a given feature. 59 67 60 68 .. image:: ./introduction/boundingbox.png 61 69 :align: center 62 70 63 Les étendues sont utilisées car répondre à la question : "est-ce que A se trouve à l'intérieur de B ? " est une opération coûteuse pour les polygones mais rapide dans le cas ou ce sont des rectangles. Même des polygones et des lignes complexes peuvent être représentés par une simple étendue. 64 65 Les index spatiaux doivent réaliser leur ordonnancement rapidement afin d'être utiles. Donc au lieu de fournir des résultats exacts, comme le font les arbres binaires, les index spatiaux fournissent des résultats approximatifs. La question "quelles lignes sont à l'intérieur de ce polygone" sera interprétée par un index spatial comme : "quelles lignes ont une étendue qui est contenue dans l'étendue de ce polygone ?" 66 67 Les incréments spatiaux réels mis en application par diverses bases de données varient considérablement. 68 Les index spatiaux actuellement utilisés par les différents systÚmes de gestion de bases de données varient aussi considérablement. L'implémentation la plus commune est l'`arbre R <http://en.wikipedia.org/wiki/R-tree>`_ (utilisé dans PostGIS), mais il existe aussi des implémentations de type `Quadtrees <http://en.wikipedia.org/wiki/Quadtree>`_, et des `index basés sur une grille <http://en.wikipedia.org/wiki/Grid_(spatial_index)>`_. 69 70 Les fonctions spatiales 71 Bounding boxes are used because answering the question "is A inside B?" is very computationally intensive for polygons but very fast in the case of rectangles. Even the most complex polygons and linestrings can be represented by a simple bounding box. 72 73 Indexes have to perform quickly in order to be useful. So instead of providing exact results, as B-trees do, spatial indexes provide approximate results. The question "what lines are inside this polygon?" will be instead interpreted by a spatial index as "what lines have bounding boxes that are contained inside this polygon's bounding box?" 74 75 The actual spatial indexes implemented by various databases vary widely. The most common implementation is the `R-tree <http://en.wikipedia.org/wiki/R-tree>`_ (used in PostGIS), but there are also implementations of `Quadtrees <http://en.wikipedia.org/wiki/Quadtree>`_, and `grid-based indexes <http://en.wikipedia.org/wiki/Grid_(spatial_index)>`_ in shipping spatial databases. 76 77 Spatial Functions 78 ----------------- 79 80 For manipulating data during a query, an ordinary database provides **functions** such as concatenating strings, performing hash operations on strings, doing mathematics on numbers, and extracting information from dates. A spatial database provides a complete set of functions for analyzing geometric components, determining spatial relationships, and manipulating geometries. These spatial functions serve as the building block for any spatial project. 81 82 The majority of all spatial functions can be grouped into one of the following five categories: 83 84 #. **Conversion**: Functions that *convert* between geometries and external data formats. 85 #. **Management**: Functions that *manage* information about spatial tables and PostGIS administration. 86 #. **Retrieval**: Functions that *retrieve* properties and measurements of a Geometry. 87 #. **Comparison**: Functions that *compare* two geometries with respect to their spatial relation. 88 #. **Generation**: Functions that *generate* new geometries from others. 89 90 The list of possible functions is very large, but a common set of functions is defined by the :term:`OGC` :term:`SFSQL` and implemented (along with additional useful functions) by PostGIS. 91 92 What is PostGIS? 93 ================ 94 95 PostGIS turns the `PostgreSQL <http://www.postgresql.org/>`_ Database Management System into a spatial database by adding adding support for the three features: spatial types, indexes, and functions. Because it is built on PostgreSQL, PostGIS automatically inherits important "enterprise" features as well as open standards for implementation 96 97 But what is PostgreSQL? 71 98 ----------------------- 72 99 73 Pour manipuler les données lors d'une requête, une base de données classique fournit des **fonctions** comme la concaténation de chaînes de caractÚres, le calcul de la clef md5 d'une chaîne, la réalisation d'opérations mathématiques sur les nombres ou l'extraction d'informations spécifiques sur une date. Une base de données spatiales fournit un ensemble complet de fonctions pour analyser les composants géographiques, déterminer les relations spatiales et manipuler les objets géographiques. Ces fonctions spatiales sont utilisées comme des piÚces de Lego pour de nombreux projets SIG. 74 75 La majorité des fonctions spatiales peuvent être regroupées dans l'une des cinq catégories suivantes : 76 77 #. **Conversion**: fonctions qui *convertissent* les données géographiques dans un format externe. 78 #. **Gestion**: fonctions qui permettent de *gérer* les informations relatives aux tables spatiales et l'administration de PostGIS. 79 #. **Récupération**: fonctions qui permettent de *récupérer* les propriétés et les mesures d'une géométrie. 80 #. **Comparaison**: fonctions qui permettent de *comparer* deux géométries en respectant leurs relations spatiales. 81 #. **Contruction**: fonctions qui permettent de *construire* de nouvelles géométries à partir d'autres. 82 83 La liste des fonctions possibles est trÚs vaste, mais un ensemble commun à l'ensemble des implémentations est défini par la spécification term:`OGC` :term:`SFSQL`. Cet ensemble commun (avec d'autres fonctions supplémentaires) est implémenté dans PostGIS. 84 85 86 Qu'est-ce que PostGIS ? 87 ======================= 88 89 PostGIS confÚre au `systÚme de gestion de base de données PostgreSQL <http://www.postgresql.org/>`_ le statut de base de données spatiales en ajoutant les trois supports suivants : les types de données spatiales, les index et les fonctions. Ãtant donné qu'il est basé sur PostgreSQL, PostGIS bénéficie automatiquement des capacités orientées "entreprise" ainsi que le respect des standards de cette implémentation. 90 91 Mais qu'est-ce que PostgreSQL ? 92 ------------------------------- 93 94 PostgreSQL est un puissant systÚme de gestion de données relationnel à objets (SGBDRO). Il a été publié sous la licence de style BSD et est donc un logiciel libre. Comme avec beaucoup de logiciels libres, PostgreSQL n'est pas contrÃŽlé par une société unique mais par une communauté de développeurs et de sociétés qui le développe. 95 96 PostgreSQL a été conçu depuis le début en conservant à l'esprit qu'il serait potentiellement nécessaire de l'étendre à l'aide d'extensions particuliÚres -- la possibilité d'ajouter de nouveaux types, des nouvelles fonctions et des méthodes d'accÚs à chaud. Grâce à cela, une extension de PostgreSQL peut être développée par une équipe de développement indépendante, bien que le lien soit trÚs fortement lié au coeur de la base de données PostgreSQL. 97 98 Pourquoi choisir PostgreSQL ? 99 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 100 101 Une question que se posent souvent les gens déja familiarisés avec les bases de données libres est : "Pourquoi PostGIS n'a pas été basé sur MySQL ?" 102 103 PostgreSQL a: 104 105 * prouvé sa fiabilité et son respect de l'intégrité des données (propriétés ACID) 106 * un support soigneux des standard SQL (respecte la norme SQL92) 107 * un support pour le développement d'extensions et de nouvelles fonctions 108 * un modÚle de développement communautaire 109 * pas de limite sur la taille des colonne (les tuples peuvent être "TOAST"és) pour supporter des objets géographiques 110 * un structure d'index générique (GiST) permettant l'indexation à l'aide d'arbres R 111 * une facilité d'ajout de fonctions personalisées 112 113 Tout ceci combiné, PostgreSQL permet un cheminement simple du développement nécessaire à l'ajout des types spatiaux. Dans le monde propriétaire, seul Illustra (maintenant Informix Universal Server) permet une extension aussi simple. Ceci n'est pas une coïncidence, Illustra est une version propriétaire modifiée du code original de PostgreSQL publié dans les années 1980. 114 115 Puisque le cheminement du développement nécessaire à l'ajout de types à PostgreSQL est direct, il semblait naturel de commencer par là . Lorsque MySQL a publié des types de données spatiaux de base dans sa version 4.1, l'équipe de PostGIS a jeté un coup d'oeil dans leur code source et cela a confirmé le choix initial d'utiliser PostgreSQL. Puisque les objets géographiques de MySQL doivent être considérés comme un cas particulier de chaînes de caractÚres, le code de MySQL a été diffus dans l'intégralité du code de base. Le développement de PostGIS version 0.1 a pris un mois. Réaliser un projet "MyGIS" 0.1 aurait pris beaucoup plus de temps, c'est sans doute pourquoi il n'a jamais vu le jour. 116 117 Pourquoi pas des fichiers Shapefile ? 118 ------------------------------------- 119 120 Les fichiers `shapefile <http://en.wikipedia.org/wiki/Shapefile>`_ (et les autres formats) ont été la maniÚre standard de stocker et d'interagir avec les données spatiales depuis l'origine des SIG. Néanmoins, ces fichiers "plats" ont les inconvénients suivants : 121 122 * **Les fichier au formats SIG requiÚrent un logiciel spécifique pour les lire et les écrire.** Le langage SQL est une abstraction de l'accÚs aléatoire aux données et à leur analyse. Sans cette abstraction, vous devrez développer l'accÚs et l'analyse par vos propre moyens. 123 * **L'accÚs concurrent aux données peut parfois entraîner un stockage de données corrompues.** Alors qu'il est possible d'écrire du code supplémentaire afin de garantir la cohérence des données, une fois ce problÚme solutionné et celui de la performance associée, vous aurez re-écrit la partie la plus importante d'un systÚme de base de données. Pourquoi ne pas simplement utiliser une base de données standard dans ce cas ? 124 * **Les questions compliquées nécessitent des logiciels compliqués pour y répondre.** Les question intéressantes et compliquées (jointures spatiales, aggrégations, etc) qui sont exprimables en une ligne de SQL grâce à la base de données, nécessitent une centaine de lignes de code spécifiques pour y répondre dans le cas de fichiers. 125 126 La plupart des utilisateurs de PostGIS ont mis en place des systÚmes où diverses applications sont susceptibles d'accéder aux données, et donc d'avoir les méthodes d'accÚs SQL standard, qui simplifient le déploiement et le développement. Certains utilisateurs travaillent avec de grands jeux de données sous forme de fichiers, qui peuvent être segmentés en plusieurs fichiers, mais dans une base de données ces données peuvent être stockées dans une seule grande table. 127 128 En résumé, la combinaison du support de l'accÚs concurrent, des requêtes complexes spécifiques et de la performance sur de grands jeux de données différencient les bases de données spatiales des systÚmes utilisant des fichiers. 129 130 Un bref historique de PostGIS 131 ------------------------------ 132 133 En mai 2001, la société `Refractions Research <http://www.refractions.net/>`_ publie la premiÚre version de PostGIS. PostGIS 0.1 fournissait les objets, les index et des fonctions utiles. Le résultat était une base de données permettant le stockage et l'accÚs mais pas encore l'analyse. 134 135 Comme le nombre de fonctions augmentait, le besoin d'un principe d'organisation devint clair. La spécification "Simple Features for SQL" (:term:`SFSQL`) publiée par l'Open Geospatial Consortium fournit une telle structure avec des indications pour le nommage des fonctions et les pré-requis. 136 137 Avec le support dans PostGIS de simples fonctions d'analyses et de jointures spatiales, 138 `Mapserver <http://mapserver.org/>`_ devint la premiÚre application externe permettant de visualiser les données de la base de données. 139 140 Au cours de ces derniÚres années, le nombre de fonctions fournies par PostGIS grandissait, mais leur puissance restait limitée. La plupart des fonctions intéressantes (ex : ST_Intersects(), ST_Buffer(), ST_Union()) étaient difficiles à implémenter. Les écrire en repartant du début promettait des années de travail. 141 142 Heureusement un second projet, nommé "Geometry Engine, Open Source" ou `GEOS <http://trac.osgeo.org/geos>`_ vit le jour. Cette librairie fournit l'ensemble des algorithmes nécessaires à l'implémentation de la spécification :term:`SFSQL` . En se liant à GEOS, PostGIS fournit alors le support complet de la :term:`SFSQL` depuis la version 0.8. 143 144 Alors que les capacités de PostGIS grandissaient, un autre problÚme fit surface : la représentation utilisée pour stocker les géométries n'était pas assez efficace. Pour de petits objets comme les points ou de courtes lignes, les métadonnées dans la représentation occupaient plus de 300% supplémentaires. Pour des raisons de performances, il fut nécessaire de faire faire un régime à la représentation. En réduisant l'entête des métadonnées et les dimensions requises, l'espace supplémentaire fut réduit drastiquement. Dans PostGIS 1.0, cette nouvelle représentation plus rapide et plus légÚre devint la représentation par défaut. 145 146 Les mises à jour récentes de PostGIS ont permis d'étendre la compatibilité avec les standards, d'ajouter les géométries courbes et les signatures de fonctions spécifiées dans la norme ISO :term:`SQL/MM`. Dans un soucis de performance, PostGIS 1.4 a aussi augmenté considérablement la rapidité d'exécution des fonctions de tests sur les géométries. 147 148 Qui utilise PostGIS ? 149 --------------------- 150 151 Pour une liste complÚte des cas d'utilisation, consultez la page web : `Cas d'utilisations de PostGIS (en anglais) <http://www.postgis.org/documentation/casestudies/>`_. 152 153 Institut Géographique National, France 100 PostgreSQL is a powerful, object-relational database management system (ORDBMS). It is released under a BSD-style license and is thus free and open source software. As with many other open source programs, PostgreSQL is not controlled by any single company, but has a global community of developers and companies to develop it. 101 102 PostgreSQL was designed from the very start with type extension in mind -- the ability to add new data types, functions and access methods at run-time. Because of this, the PostGIS extension can be developed by a separate development team, yet still integrate very tightly into the core PostgreSQL database. 103 104 Why choose PostgreSQL? 105 ~~~~~~~~~~~~~~~~~~~~~~ 106 107 A common question from people familiar with open source databases is, "Why wasn't PostGIS built on MySQL?". 108 109 PostgreSQL has: 110 111 * Proven reliability and transactional integrity by default (ACID) 112 * Careful support for SQL standards (full SQL92) 113 * Pluggable type extension and function extension 114 * Community-oriented development model 115 * No limit on column sizes ("TOAST"able tuples) to support big GIS objects 116 * Generic index structure (GiST) to allow R-Tree index 117 * Easy to add custom functions 118 119 Combined, PostgreSQL provides a very easy development path to add new spatial types. In the proprietary world, only Illustra (now Informix Universal Server) allows such easy extension. This is no coincidence; Illustra is a proprietary re-working of the original PostgreSQL code base from the 1980's. 120 121 Because the development path for adding types to PostgreSQL was so straightforward, it made sense to start there. When MySQL released basic spatial types in version 4.1, the PostGIS team took a look at their code, and the exercise reinforced the original decision to use PostgreSQL. Because MySQL spatial objects had to be hacked on top of the string type as a special case, the MySQL code was spread over the entire code base. Development of PostGIS 0.1 took under a month. Doing a "MyGIS" 0.1 would have taken a lot longer, and as such, might never have seen the light of day. 122 123 Why not Shapefiles? 124 ------------------- 125 126 The `shapefile <http://en.wikipedia.org/wiki/Shapefile>`_ (and other file formats) have been the standard way of storing and interacting with spatial data since GIS software was first written. However, these "flat" files have the following disadvantages: 127 128 * **Files require special software to read and write.** SQL is an abstraction for random data access and analysis. Without that abstraction, you will need to write all the access and analysis code yourself. 129 * **Concurrent users can cause corruption.** While it's possible to write extra code to ensure that multiple writes to the same file do not corrupt the data, by the time you have solved the problem and also solved the associated performance problem, you will have written the better part of a database system. Why not just use a standard database? 130 * **Complicated questions require complicated software to answer.** Complicated and interesting questions (spatial joins, aggregations, etc) that are expressible in one line of SQL in the database take hundreds of lines of specialized code to answer when programming against files. 131 132 Most users of PostGIS are setting up systems where multiple applications will be expected to access the data, so having a standard SQL access method simplifies deployment and development. Some users are working with large data sets; with files, they might be segmented into multiple files, but in a database they can be stored as a single large table. 133 134 In summation, the combination of support for multiple users, complex ad hoc queries, and performance on large data sets are what sets spatial databases apart from file-based systems. 135 136 A brief history of PostGIS 137 -------------------------- 138 139 In the May of 2001, `Refractions Research <http://www.refractions.net/>`_ released the first version of PostGIS. PostGIS 0.1 had objects, indexes and a handful of functions. The result was a database suitable for storage and retrieval, but not analysis. 140 141 As the number of functions increased, the need for an organizing principle became clear. The "Simple Features for SQL" (:term:`SFSQL`) specification from the Open Geospatial Consortium provided such structure with guidelines for function naming and requirements. 142 143 With PostGIS support for simple analysis and spatial joins, `Mapserver <http://mapserver.org/>`_ became the first external application to provide visualization of data in the database. 144 145 Over the next several years the number of PostGIS functions grew, but its power remained limited. Many of the most interesting functions (e.g., ST_Intersects(), ST_Buffer(), ST_Union()) were very difficult to code. Writing them from scratch promised years of work. 146 147 Fortunately a second project, the "Geometry Engine, Open Source" or `GEOS <http://trac.osgeo.org/geos>`_, came along. The GEOS library provides the necessary algorithms for implementing the :term:`SFSQL` specification. By linking in GEOS, PostGIS provided complete support for :term:`SFSQL` by version 0.8. 148 149 As PostGIS data capacity grew, another issue surfaced: the representation used to store geometry proved relatively inefficient. For small objects like points and short lines, the metadata in the representation had as much as a 300% overhead. For performance reasons, it was necessary to put the representation on a diet. By shrinking the metadata header and required dimensions, overhead greatly reduced. In PostGIS 1.0, this new, faster, lightweight representation became the default. 150 151 Recent updates of PostGIS have worked on expanding standards compliance, adding support for curve-based geometries and function signatures specified in the ISO :term:`SQL/MM` standard. Through a continued focus on performance, PostGIS 1.4 significantly improved the speed of geometry testing routines. 152 153 Who uses PostGIS? 154 ----------------- 155 156 For a complete list of case studies, see the `PostGIS case studies <http://www.postgis.org/documentation/casestudies/>`_ page. 157 158 Institut Geographique National, France 154 159 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 155 160 156 L'IGN utilise PostGIS pour stocker des cartes topographiques de grande résolution de la France : la "BDUni". La BDUni a plus de 100 millions d'entités, et est maintenue par une équipe de 100 personnes qui vérifie les observations et ajoute quotidiennement de nouvelles données à la base. L'installation de l'IGN utilise le systÚme transactionnel de la base de données pour assurer la consistance durant les phases de mises à jour et utilise un `serveur de warm-standby par transfert de journaux <http://docs.postgresql.fr/9.1/warm-standby.html>`_ afin de conserver un état cohérent en cas de défaillance du systÚme.161 IGN is the national mapping agency of France, and uses PostGIS to store the high resolution topographic map of the country, "BDUni". BDUni has more than 100 million features, and is maintained by a staff of over 100 field staff who verify observations and add new mapping to the database daily. The IGN installation uses the database transactional system to ensure consistency during update processes, and a `warm standby system <http://developer.postgresql.org/pgdocs/postgres/warm-standby.html>`_ to maintain uptime in the event of a system failure. 157 162 158 163 GlobeXplorer 159 164 ~~~~~~~~~~~~ 160 165 161 GlobeXplorer est un service web fournissant un accÚs en ligne à une imagerie satellite et photos aériennes de plusieurs petabytes. GlobeXplorer utilise PostGIS pour gérer les métadonnées associées avec le catalogue d'images. Les requêtes pour accéder aux images recherchent d'abord dans le catalogue PostGIS pour récupérer la localisation des images demandées, puis récupÚrent ces images et les retournent au client. Lors du proccessus de mise en place de leur systÚme, GlobeXplorer a essayé d'autres systÚmes de base de données spatiales mais a conservé PostGIS à cause de la combinaison du prix et de la performance qu'il offre.162 163 Quest-ce qu'une application qui supporte PostGIS?164 ---------------------------------- ----------------165 166 PostGIS est devenu une base de données spatiale communément utilisée, et le nombre d'applications tierces qui supportent le stockage ou la récupération des données n'a cessé d'augmenter. `Les application qui supportent PostGIS <http://trac.osgeo.org/postgis/wiki/UsersWikiToolsSupportPostgis>`_ contiennent à la fois des applications libres et des application propriétaires tournant sur un serveur ou localement depuis votre bureau.167 168 La table suivante propose une liste des logiciels qui tirent profit de PostGIS:166 GlobeXplorer is a web-based service providing online access to petabytes of global satellite and aerial imagery. GlobeXplorer uses PostGIS to manage the metadata associated with the imagery catalogue, so queries for imagery first search the PostGIS catalogue to find the location of the relevant images, then pull the images from storage and return them to the client. In building their system, GlobeXplorer tried other spatial databases but eventually settled on PostGIS because of the great combination of price and performance it offers. 167 168 What applications support PostGIS? 169 ---------------------------------- 170 171 PostGIS has become a widely used spatial database, and the number of third-party programs that support storing and retrieving data using it has increased as well. The `programs that support PostGIS <http://trac.osgeo.org/postgis/wiki/UsersWikiToolsSupportPostgis>`_ include both open source and proprietary software on both server and desktop systems. 172 173 The following table shows a list of some of the software that leverages PostGIS: 169 174 170 175 +-------------------------------------------------+----------------------------------------------+ 171 | Libre/Gratuit | Fermé/Propriétaire|176 | Open/Free | Closed/Proprietary | 172 177 +=================================================+==============================================+ 173 | | | 174 | * Chargement/Extraction | * Chargement/Extraction |175 | | | 176 | * Shp2Pgsql | * Safe FME Desktop Translator/Converter | 177 | * ogr2ogr | | 178 | * Dxf2PostGIS | | 179 | | * Basé sur le web |180 | * Basé sur le web | |181 | | * Ionic Red Spider (now ERDAS) | 182 | * Mapserver | * Cadcorp GeognoSIS | 183 | * GeoServer (Java-based WFS / WMS -server ) | * Iwan Mapserver | 184 | * SharpMap SDK - for ASP.NET 2.0 | * MapDotNet Server | 185 | * MapGuide Open Source (using FDO) | * MapGuide Enterprise (using FDO) | 186 | | * ESRI ArcGIS Server 9.3+ | 187 | * Logiciels bureautiques | |188 | | * Logiciels bureautiques |189 | * uDig | | 190 | * QGIS | * Cadcorp SIS | 191 | * mezoGIS | * Microimages TNTmips GIS | 192 | * OpenJUMP | * ESRI ArcGIS 9.3+ | 193 | * OpenEV | * Manifold | 194 | * SharpMap SDK for Microsoft.NET 2.0 | * GeoConcept | 195 | * ZigGIS for ArcGIS/ArcObjects.NET | * MapInfo (v10) | 196 | * GvSIG | * AutoCAD Map 3D (using FDO) | 197 | * GRASS | | 198 | | | 178 | | | 179 | * Loading/Extracting | * Loading/Extracting | 180 | | | 181 | * Shp2Pgsql | * Safe FME Desktop Translator/Converter | 182 | * ogr2ogr | | 183 | * Dxf2PostGIS | | 184 | | * Web-Based | 185 | * Web-Based | | 186 | | * Ionic Red Spider (now ERDAS) | 187 | * Mapserver | * Cadcorp GeognoSIS | 188 | * GeoServer (Java-based WFS / WMS -server ) | * Iwan Mapserver | 189 | * SharpMap SDK - for ASP.NET 2.0 | * MapDotNet Server | 190 | * MapGuide Open Source (using FDO) | * MapGuide Enterprise (using FDO) | 191 | | * ESRI ArcGIS Server 9.3+ | 192 | * Desktop | | 193 | | * Desktop | 194 | * uDig | | 195 | * QGIS | * Cadcorp SIS | 196 | * mezoGIS | * Microimages TNTmips GIS | 197 | * OpenJUMP | * ESRI ArcGIS 9.3+ | 198 | * OpenEV | * Manifold | 199 | * SharpMap SDK for Microsoft.NET 2.0 | * GeoConcept | 200 | * ZigGIS for ArcGIS/ArcObjects.NET | * MapInfo (v10) | 201 | * GvSIG | * AutoCAD Map 3D (using FDO) | 202 | * GRASS | | 203 | | | 199 204 +-------------------------------------------------+----------------------------------------------+ 200 205 -
/trunk/workshop-foss4g/geography.rst
r61 r1 1 1 .. _geography: 2 2 3 Partie 17 : Coordonnées géographiques 4 ===================== ================5 6 I l est trÚs fréquent de manipuler des données à coordonnées "géographiques" ou de "longitude/latitude".7 8 Au contraire des coordonnées de type Mercator, UTM ou Stateplane, les coordonnées géographiques ne représentent pas une distance linéaire depuis une origine, tel que dans un plan. Elles décrivent la distance angulaire entre l'équateur et les pÃŽles. Dans les sytÚmes de coordonnées sphériques, un point est spécifié par son rayon (distance à l'origine), son angle de rotation par rapport au méridien plan, et son angle par rapport à l'axe pÃŽlaire. 3 Section 17: Geography 4 ===================== 5 6 It is very common to have data in which the coordinate are "geographics" or "latitude/longitude". 7 8 Unlike coordinates in Mercator, UTM, or Stateplane, geographic coordinates are **not cartesian coordinates**. Geographic coordinates do not represent a linear distance from an origin as plotted on a plane. Rather, these **spherical coordinates** describe the angular distance between the equator and the poles. In spherical coordinates a point is specified by the distance from the origin (the radius), the angle of rotation from the initial meridian plane, and the angle from the polar axis (analogous to a vector from the origin through the North Pole). 9 9 10 10 .. image:: ./geography/cartesian_spherical.jpg 11 11 12 13 Vous pouvez continuer à utiliser des coordonnées géographiques comme des coordonnées cartésiennes approximatives pour vos analyses spatiales. Par contre les mesures de distances, d'aires et de longueur seront éronées. Etant donné que les coordonnées spériques mesurent des angles, l'unité est le dégré. Par exemple, les résultats cartésien approximatifs de tests tels que 'intersects' et 'contains' peuvent s'avérer terriblement faux. Par ailleurs, plus une zone est située prÚs du pÃŽle ou de la ligne de date internationale, plus la distance entre les points est agrandie. 14 15 16 Voici par exemple les coordonnées des villes de Los Angeles et Paris. 12 You can treat geographic coordinates as approximate cartesian coordinates and continue to do spatial calculations. However, measurements of distance, length and area will be nonsensical. Since spherical coordinates measure **angular** distance, the units are in "degrees." Further, the approximate results from indexes and true/false tests like intersects and contains can become terribly wrong. The distance between points get larger as problem areas like the poles or the international dateline are approached. 13 14 For example, here are the coordinates of Los Angeles and Paris. 17 15 18 16 * Los Angeles: ``POINT(-118.4079 33.9434)`` 19 17 * Paris: ``POINT(2.3490 48.8533)`` 20 18 21 La requête suivante calcule la distance entre Los Angeles et Paris en utilisant le systÚme cartésien standard de PostGIS :command:`ST_Distance(geometry, geometry)`. Notez que le SRID 4326 déclare un systÚme de références spatiales géographiques.19 The following calculates the distance between Los Angeles and Paris using the standard PostGIS cartesian :command:`ST_Distance(geometry, geometry)`. Note that the SRID of 4326 declares a geographic spatial reference system. 22 20 23 21 .. code-block:: sql … … 32 30 121.898285970107 33 31 34 Aha! 121! Mais, que veut dire cela ? 35 36 L'unité pour SRID 4326 est le degré. Donc la réponse signifie 121 degrés. Sur une sphÚre, la taille d'un degré "au carré" est assez variable. Elle devient plsu petite au fur et à mesure que l'on s'éloigne de l'équateur. Pensez par exemple aux méridiens sur le globe qui se ressÚrent entre eux au niveau des pÃŽles. Donc une distance de 121 degrés ne veut rien dire ! 37 38 Pour calculer une distance ayant du sens, nous devons traiter les coordonnées géographiques non pas come des coordonnées cartésiennes approximatives, mais plutÃŽt comme de réelles coordonnées sphériques. Nous devons mesurer les distances entre les points comme de vrais chemins par dessus uen sphÚre, comme une portion d'un grand cercle. 39 40 Depuis sa version 1.5, PostGIS fournit cette fonctionnalité avec le type ``geography``. 32 Aha! 121! But, what does that mean? 33 34 The units for spatial reference 4326 are degrees. So our answer is 121 degrees. But (again), what does that mean? 35 36 On a sphere, the size of one "degree square" is quite variable, becoming smaller as you move away from the equator. Think of the meridians (vertical lines) on the globe getting closer to each other as you go towards the poles. So, a distance of 121 degrees doesn't *mean* anything. It is a nonsense number. 37 38 In order to calculate a meaningful distance, we must treat geographic coordinates not as approximate cartesian coordinates but rather as true spherical coordinates. We must measure the distances between points as true paths over a sphere -- a portion of a great circle. 39 40 Starting with version 1.5, PostGIS provides this functionality through the ``geography`` type. 41 41 42 42 .. note:: 43 43 44 Diff érentes bases de données spatiales développent différentes approches pour manipuler les coordonnées géographiques.45 46 * Oracle essaye de mettre à jour la différence de maniÚre transparente en lanacant des calculs lorsuqe le SRID est géographique.47 * SQL Server u tilise deux types spatiaux, "STGeometry" pour les coordonnées cartésiens et STGeography" pour les coordonnées géographqiues.48 * Informix Spatial est une pure extension cartésienne d'Informix, alors qu'Informix Geodetic est une pure extension géographique.49 * Comme SQL Server, PostGIS utilise deux types: "geometry" et"geography".50 51 En utilisant le type ``geography`` plutot que ``geometry``, essayon sà nouveau de mesurer la distance entre Los Angeles et Paris. Au lieu de la commande :command:`ST_GeometryFromText(text)`, nous utiliserons cette fois:command:`ST_GeographyFromText(text)`.44 Different spatial databases have different approaches for "handling geographics" 45 46 * Oracle attempts to paper over the differences by transparently doing geographic calculations when the SRID is geographic. 47 * SQL Server uses two spatial types, "STGeometry" for cartesian data and "STGeography" for geographics. 48 * Informix Spatial is a pure cartesian extension to Informix, while Informix Geodetic is a pure geographic extension. 49 * Similar to SQL Server, PostGIS uses two types, "geometry" and "geography". 50 51 Using the ``geography`` instead of ``geometry`` type, let's try again to measure the distance between Los Angeles and Paris. Instead of :command:`ST_GeometryFromText(text)`, we will use :command:`ST_GeographyFromText(text)`. 52 52 53 53 .. code-block:: sql … … 62 62 9124665.26917268 63 63 64 Toutes les valeurs retournées étant en mÚtres, notre réponse est donc 9124 kilomÚtres. 65 66 Les versions plus anciennes de PostGIS supportaient uniquement des calculs sur sphÚre trÚs basiques comme la fonction :command:`ST_Distance_Spheroid(point, point, measurement)`. Celle-ci est trÚs limitée et ne fonctionne uniquement sur des points. Elle ne supporte pas non plus l'indexation au niveau des pÃŽles ou de la ligne de date internationale.67 68 Le besoin du support des autres types de géométries se fit ressentir lorsqu'il s'agissait de répondre à des questions du type "A quelle distance la ligne de vol d'un avion Los Angeles/Paris passe-t-elle de l'Islande?"64 A big number! All return values from ``geography`` calculations are in meters, so our answer is 9124km. 65 66 Older versions of PostGIS supported very basic calculations over the sphere using the :command:`ST_Distance_Spheroid(point, point, measurement)` function. However, :command:`ST_Distance_Spheroid` is substantially limited. The function only works on points and provides no support for indexing across the poles or international dateline. 67 68 The need to support non-point geometries becomes very clear when posing a question like "How close will a flight from Los Angeles to Paris come to Iceland?" 69 69 70 70 .. image:: ./geography/lax_cdg.jpg 71 71 72 Répondre à cette question en travaillant avec un plan cartésien fournit une trÚs mauvaise réponse en effet ! En utilisant la ligne rouge, nou sobtenon sune bien meilleure réponse. Si nous convertissons notre vol LAX-CDG en une ligne et que nous calculons la distance à un point en Islande, nous obtiendrons la réponse exacte, en mÚtres. 72 Working with geographic coordinates on a cartesian plane (the purple line) yields a *very* wrong answer indeed! Using great circle routes (the red lines) gives the right answer. If we convert our LAX-CDG flight into a line string and calculate the distance to a point in Iceland using ``geography`` we'll get the right answer (recall) in meters. 73 73 74 74 .. code-block:: sql … … 83 83 531773.757079116 84 84 85 Donc le point le plu sproche de l'Islande pendant le vol LAX-CDG est de 532 kilomÚtres.S 86 87 L'approche cartésienne pour manipuler les coordonnées géographiques pert tout son sens pour les objets situées au dessus de la ligne de date internationale. La route "sphérique" la plus courte entre Los-Angeles et Tokyo traverse l'océan Pacifique. La route "cartésienne" la plus courte traverse quant à elle les océans Atlantique et Indien. 85 So the closest approach to Iceland on the LAX-CDG route is a relatively small 532km. 86 87 The cartesian approach to handling geographic coordinates breaks down entirely for features that cross the international dateline. The shortest great-circle route from Los Angeles to Tokyo crosses the Pacific Ocean. The shortest cartesian route crosses the Atlantic and Indian Oceans. 88 88 89 89 .. image:: ./geography/lax_nrt.png … … 107 107 108 108 109 U tiliser le type 'Geography'110 --------------- -------------111 112 Afin d'importer des données dans une table de type geography, les objets géographiques doivent d'avord être projetées dans le systÚme EPSG:4326 (longitude/latitude), ensuite elles doivent être converties en objets de type géographies. La fonction :command:`ST_Transform(geometry,srid)` convertie les coordonnées en géographies et la fonction :command:`Geography(geometry)` change le type ("cast") de géométrie à géographie.109 Using Geography 110 --------------- 111 112 In order to load geometry data into a geography table, the geometry first needs to be projected into EPSG:4326 (longitude/latitude), then it needs to be changed into geography. The :command:`ST_Transform(geometry,srid)` function converts coordinates to geographics and the :command:`Geography(geometry)` function "casts" them from geometry to geography. 113 113 114 114 .. code-block:: sql … … 121 121 FROM nyc_subway_stations; 122 122 123 La construction d'une indexation spatiale sur une table stockant des objets de type géographie est exactement identique à la méthode employée pour les géométries : 123 Building a spatial index on a geography table is exactly the same as for geometry: 124 124 125 125 .. code-block:: sql … … 128 128 ON nyc_subway_stations_geog USING GIST (geog); 129 129 130 La différence est camouflé : l'indexation des objets de type géographie gére correctement les requêtes qui recouvrent les pÃŽles ou traverses les fuseaux horraires, alors que les géométries ne le supporteront pas.131 132 Il n'y a qu'un petit nombre de fonctions disponibles pour le type géographie : 133 134 * :command:`ST_AsText(geography)` ret ourne la représentation ``textuelle``135 * :command:`ST_GeographyFromText(text)` ret ourne un objet de type``geography``136 * :command:`ST_AsBinary(geography)` ret ourne la représentation binaire``bytea``137 * :command:`ST_GeogFromWKB(bytea)` ret ourne un objet de type``geography``138 * :command:`ST_AsSVG(geography)` ret ourne``text``139 * :command:`ST_AsGML(geography)` ret ourne``text``140 * :command:`ST_AsKML(geography)` ret ourne``text``141 * :command:`ST_AsGeoJson(geography)` ret ourne``text``142 * :command:`ST_Distance(geography, geography)` ret ourne``double``143 * :command:`ST_DWithin(geography, geography, float8)` ret ourne``boolean``144 * :command:`ST_Area(geography)` ret ourne``double``145 * :command:`ST_Length(geography)` ret ourne``double``146 * :command:`ST_Covers(geography, geography)` ret ourne``boolean``147 * :command:`ST_CoveredBy(geography, geography)` ret ourne``boolean``148 * :command:`ST_Intersects(geography, geography)` ret ourne``boolean``149 * :command:`ST_Buffer(geography, float8)` ret ourne``geography`` [#Casting_note]_150 * :command:`ST_Intersection(geography, geography)` ret ourne``geography`` [#Casting_note]_151 152 Cr éation d'une table stockant des géograhpies153 -------------------------- -------------------154 155 Le code SQL permettant la création d'une nouvelle table avec une colonne de type géographie ressemble à la création d'une table stockant des géométries. Cependant, les objets de type géographie permettent de spécifier directement le type d'objet géographique à la création de la table. Par exemple:130 The difference is under the covers: the geography index will correctly handle queries that cover the poles or the international date-line, while the geometry one will not. 131 132 There are only a small number of native functions for the geography type: 133 134 * :command:`ST_AsText(geography)` returns ``text`` 135 * :command:`ST_GeographyFromText(text)` returns ``geography`` 136 * :command:`ST_AsBinary(geography)` returns ``bytea`` 137 * :command:`ST_GeogFromWKB(bytea)` returns ``geography`` 138 * :command:`ST_AsSVG(geography)` returns ``text`` 139 * :command:`ST_AsGML(geography)` returns ``text`` 140 * :command:`ST_AsKML(geography)` returns ``text`` 141 * :command:`ST_AsGeoJson(geography)` returns ``text`` 142 * :command:`ST_Distance(geography, geography)` returns ``double`` 143 * :command:`ST_DWithin(geography, geography, float8)` returns ``boolean`` 144 * :command:`ST_Area(geography)` returns ``double`` 145 * :command:`ST_Length(geography)` returns ``double`` 146 * :command:`ST_Covers(geography, geography)` returns ``boolean`` 147 * :command:`ST_CoveredBy(geography, geography)` returns ``boolean`` 148 * :command:`ST_Intersects(geography, geography)` returns ``boolean`` 149 * :command:`ST_Buffer(geography, float8)` returns ``geography`` [#Casting_note]_ 150 * :command:`ST_Intersection(geography, geography)` returns ``geography`` [#Casting_note]_ 151 152 Creating a Geography Table 153 -------------------------- 154 155 The SQL for creating a new table with a geography column is much like that for creating a geometry table. However, geography includes the ability to specify the object type directly at the time of table creation. For example: 156 156 157 157 .. code-block:: sql … … 166 166 INSERT INTO airports VALUES ('REK', 'POINT(-21.8628 64.1286)'); 167 167 168 Lors de la définitionn le type ``GEOGRAPHY(Point)`` spécifie que nos airoports sont des points. Les nouveau champs géographie n'est pas référencé dans la table ``geometry_columns``. Le stockage des métadonnées relatives aux données de type géograhpie sont stockées dans une vue appellée ``geography_columns`` qui est maintenue à jour automatiquement sans avoir besoin d'utiliser des fonctions comme ``geography_columns``.168 In the table definition, the ``GEOGRAPHY(Point)`` specifies our airport data type as points. The new geography fields don't get registered in the ``geometry_columns``. Instead, they are registered in a new view called ``geography_columns`` that is automatically kept up to date without need for an :command:`AddGeom...` like functions. 169 169 170 170 .. code-block:: sql … … 181 181 .. note:: 182 182 183 La possibilité de définir les types et le SRID lors de la création de la table (requête ``CREATE``), et la mise à jour automatique des métadonnées ``geometry_columns`` sont des fonctionalités qui seront adaptées pour le type géométrie pour la version 2.0 de PostGIS. 184 185 Conversion de type 183 The ability to define geometry types and SRIDs inside the table ``CREATE`` statement, and the automatic update of the ``geometry_columns`` metadata are features that have been prototyped with ``geography`` and will be added to the ``geometry`` type for PostGIS 2.0. 184 185 186 Casting to Geometry 186 187 ------------------- 187 188 188 Bien que les fonctions de bases qui s'appliquent au type géographie peuvent être utilisées dans un grand nombre de cas d'utilisation, il est parfois nécessaire d'accéder aux autres fonctions qui ne supportent que le type géométrie. Heureusement, il est possible de convertir des objets de type géométries en des objets de types géographies et inversement.189 190 La syntaxe habituelle de PostgreSQL pour les conversion de type consiste à ajouter à la valeur la chaîne suivante ``::typename``. Donc, ``2::text`` convertie la valeur numérique deux en une chaîne de caractÚres '2'. La commande : ``'POINT(0 0)'::geometry`` convertira la représentation textuelle d'un point en une point géométrique.191 192 La fonction :command:`ST_X(point)` supporte seulement le type géométrique. Comment lire la coordonée X d'une de nos géographie?189 While the basic functions for geography types can handle many use cases, there are times when you might need access to other functions only supported by the geometry type. Fortunately, you can convert objects back and forth from geography to geometry. 190 191 The PostgreSQL syntax convention for casting is to append ``::typename`` to the end of the value you wish to cast. So, ``2::text`` with convert a numeric two to a text string '2'. And ``'POINT(0 0)'::geometry`` will convert the text representation of point into a geometry point. 192 193 The :command:`ST_X(point)` function only supports the geometry type. How can we read the X coordinate from our geographies? 193 194 194 195 .. code-block:: sql … … 204 205 REK | -21.8628 205 206 206 En ajoutant la chaîne ``::geometry`` à notre valeur géographique, nous la convertissons en une géographie ayant le SRID : 4326. à partir de maintenant, nous pouvons utiliser autemps de fonctions s'appliquant au géométries que nous le souhaitons. Mais, souvenez-vous - maintenant que nos objets sont des géométries, leur coordonnées seront interprétées comme des coordonnées cartésiennes, non pas sphériques.207 208 209 Pourquoi (ne pas) utiliser les géographies 210 ----------------------- -------------------211 212 Les géographies ont des coordonnées universellement acceptées - chacun peut comprendre que représente la latitue et la longitude, mais peut de personne comprennent ce que les coordonnées UTM signifient. Pourquoi ne pas tout le temps utiliser des géographies?213 214 * PremiÚrement, comme indiqué précédemment, il n'y a que quelques fonctions qui supportent ce type de données. Vous risquer de perdre beaucoup de temps à contourner les problÚmes liés à la non-disponibilité de certaines fonctions.215 * DeuxiÚmement, les calculs sur une sphÚre sont plus consomateurs en ressource que les mêmes calculs dans un systÚme cartésien. Par exemple, la formule de calcul de distance (Pythagore) entraine un seul appÚle à la fonction racine carré (sqrt()). La formule de calcul de distance sphérique (Haversine) utilise deux appÚle à la fonction racine carré, et un appÚle à arctan(), quatre appÚle à sin() et deux à cos(). Les fonctions trigonométriques sont trÚs couteuses, et les calculs sphériques les utilisent massivement.216 217 Quel conclusion en tirer?218 219 Si vos données sont géograhpiquement compact (contenu à l'intérieur d'un état, d'un pays ou d'une ville), utilisez le type ``geometry`` avec une projection cartésienne qui est pertinent pour votre localisation. Consultez le site http://spatialreference.org et tapez le nom de votre région pour visualiser la liste des systÚme de projection applicables dans votre cas.220 221 Si, d'un autre coté, vous avez besoin de calculer des distances qui est géographiquement éparse (recouvrant la plupart du monde), utiliser le type ``geography``. La compléxité de l'application que vous éviterait en travaillant avec des objets de type ``geography`` dépassera les problÚmes de performances. La conversion de type en géométrie permettra de dépasser les limites des fonctionnalités proposé pour ce type.222 223 Liste des fonctions 224 ------------- ------225 226 `ST_Distance(geometry, geometry) <http://postgis.org/docs/ST_Distance.html>`_: Pour le type géométrie, renvoit la distance cartésienne, pour les géographies la distance sphérique en métres.227 228 `ST_GeographyFromText(text) <http://postgis.org/docs/ST_GeographyFromText.html>`_: Ret ourne la valeur géographique à partir d'une représentation en WKT ou EWKT.229 230 `ST_Transform(geometry, srid) <http://postgis.org/docs/ST_Transform.html>`_: Ret ourne une nouvelle géométrie avec ses coordonnées reprojetées dans le systÚme de référence spatial référencé par le SRID fournit.231 232 `ST_X(point) <http://postgis.org/docs/ST_X.html>`_: Ret ourne la coordonnée X d'un point, ou NULL si non disponible. La valeur passée doit être unpoint.207 By appending ``::geometry`` to our geography value, we convert the object to a geometry with an SRID of 4326. From there we can use as many geometry functions as strike our fancy. But, remember -- now that our object is a geometry, the coordinates will be interpretted as cartesian coordinates, not spherical ones. 208 209 210 Why (Not) Use Geography 211 ----------------------- 212 213 Geographics are universally accepted coordinates -- everyone understands what latitude/longitude mean, but very few people understand what UTM coordinates mean. Why not use geography all the time? 214 215 * First, as noted earlier, there are far fewer functions available (right now) that directly support the geography type. You may spend a lot of time working around geography type limitations. 216 * Second, the calculations on a sphere are computationally far more expensive than cartesian calculations. For example, the cartesian formula for distance (Pythagoras) involves one call to sqrt(). The spherical formula for distance (Haversine) involves two sqrt() calls, an arctan() call, four sin() calls and two cos() calls. Trigonometric functions are very costly, and spherical calculations involve a lot of them. 217 218 The conclusion? 219 220 If your data is geographically compact (contained within a state, county or city), use the ``geometry`` type with a cartesian projection that makes sense with your data. See the http://spatialreference.org site and type in the name of your region for a selection of possible reference systems. 221 222 If, on the other hand, you need to measure distance with a dataset that is geographically dispersed (covering much of the world), use the ``geography`` type. The application complexity you save by working in ``geography`` will offset any performance issues. And, casting to ``geometry`` can offset most functionality limitations. 223 224 Function List 225 ------------- 226 227 `ST_Distance(geometry, geometry) <http://postgis.org/docs/ST_Distance.html>`_: For geometry type Returns the 2-dimensional cartesian minimum distance (based on spatial ref) between two geometries in projected units. For geography type defaults to return spheroidal minimum distance between two geographies in meters. 228 229 `ST_GeographyFromText(text) <http://postgis.org/docs/ST_GeographyFromText.html>`_: Returns a specified geography value from Well-Known Text representation or extended (WKT). 230 231 `ST_Transform(geometry, srid) <http://postgis.org/docs/ST_Transform.html>`_: Returns a new geometry with its coordinates transformed to the SRID referenced by the integer parameter. 232 233 `ST_X(point) <http://postgis.org/docs/ST_X.html>`_: Returns the X coordinate of the point, or NULL if not available. Input must be a point. 233 234 234 235 235 236 .. rubric:: Footnotes 236 237 237 .. [#Casting_note] Les fonctions buffer et intersection sont actuellement construite sur le principe de conversion de type en géométries, et ne sont pas actuellement capable de gérer des coordonnées sphariques. Il en résulte qu'elles peuvent ne pas parvenir à retourner un résultat correcte pour des objets ayant une grande étendue qui ne peut être représenté correctement avec une représentation planaire.238 239 Par exemple, la fonction :command:`ST_Buffer(geography,distance)` transforme les objets géographiques dans la "meilleure" projection, crée la zone tampon, puis les transforme à nouveau en des géographies. S'il n'y a pas de "meilleure" projection (l'objet est trop vaste), l'opération peut ne pas réussir à retourner une valeur correct ou retourner une one tampon mal formée.240 238 .. [#Casting_note] The buffer and intersection functions are actually wrappers on top of a cast to geometry, and are not carried out natively in spherical coordinates. As a result, they may fail to return correct results for objects with very large extents that cannot be cleanly converted to a planar representation. 239 240 For example, the :command:`ST_Buffer(geography,distance)` function transforms the geography object into a "best" projection, buffers it, and then transforms it back to geographics. If there is no "best" projection (the object is too large), the operation can fail or return a malformed buffer. 241 -
/trunk/workshop-foss4g/validity.rst
r61 r1 1 1 .. _validity: 2 2 3 Partie 20 : Validité 3 Section 20: Validity 4 4 ==================== 5 5 6 Dans 90% des cas la réponse à la question "pourquoi mes requêtes me renvoit un message d'erreur du type 'TopologyException' error"" est : "un ou plusieurs des arguments passés sont invalides". Ce qui nous conduit à nous demander : que signifie invalide et pourquoi est-ce important?6 In 90% of the cases the answer to the question, "why is my query giving me a 'TopologyException' error" is "one or more of the inputs are invalid". Which begs the question: what does it mean to be invalid, and why should we care? 7 7 8 Qu'est-ce que la validité ? 9 ---------------- -----------8 What is Validity 9 ---------------- 10 10 11 La validité est surtout importante pour les polygones, qui définissent des aires et requiÚrent une bonne structuration. Les lignes sont vraiment simples et ne peuvent pas être invalides ainsi que lespoints.11 Validity is most important for polygons, which define bounded areas and require a good deal of structure. Lines are very simple and cannot be invalid, nor can points. 12 12 13 Certaines des rÚgles de validation des polygones semble évidentes, et d'autre semblent arbitraires (et le sont vraiment).13 Some of the rules of polygon validity feel obvious, and others feel arbitrary (and in fact, are arbitrary). 14 14 15 * Les contours des Polygon doivent être fermés.16 * Les contours qui définissent des trous doivent être inclus dans la zone définit par le coutour extérieur.17 * Les contours ne doivent pas s'intersecter (ils ne doivent ni se croiser ni se toucher).18 * Les contours ne doivent pas toucher les autres contours, sauf en un point unique.15 * Polygon rings must close. 16 * Rings that define holes should be inside rings that define exterior boundaries. 17 * Rings may not self-intersect (they may neither touch nor cross one another). 18 * Rings may not touch other rings, except at a point. 19 19 20 Les deux derniÚres rÚgles font partie de la catégorie arbitraires. Il y a d'autre moyen de définir des poygones qui sont consistent mais les rÚgles ci-dessus sont celles utilisées dans le standard :term:`OGC` :term:`SFSQL` que respecte PostGIS.20 The last two rules are in the arbitrary category. There are other ways to define polygons that are equally self-consistent but the rules above are the ones used by the :term:`OGC` :term:`SFSQL` standard that PostGIS conforms to. 21 21 22 La raison pour laquelle ces rÚgles sont importants est que les algorythmes de calcul dépendent de cette structuration consistante des arguments. Il est possible de construire des algorythmes qui n'utilise pas cette structuration, mais ces fonctions tendents à être trÚs lentes, étant donné que la premiÚre étape consistera à "analyser et construire des strcuture à l'intérieur des données".22 The reason the rules are important is because algorithms for geometry calculations depend on consistent structure in the inputs. It is possible to build algorithms that have no structural assumptions, but those routines tend to be very slow, because the first step in any structure-free routine is to *analyze the inputs and build structure into them*. 23 23 24 Voici un exemple de pourquoi cette structuration est importante. Ce polygone n'est pas valide:24 Here's an example of why structure matters. This polygon is invalid: 25 25 26 26 :: … … 28 28 POLYGON((0 0, 0 1, 2 1, 2 2, 1 2, 1 0, 0 0)); 29 29 30 Vous pouvez comprendre ce qui n'est pas valide en regardant cette figure:30 You can see the invalidity a little more clearly in this diagram: 31 31 32 32 .. image:: ./validity/figure_eight.png 33 33 34 Le contour externe est exactement en forme en 8 avec une intersection au milieux. Notez que la fonction de rendu graphique est tout de même capable d'en afficher l'intérieur, don visuellement cela ressemble bien à une "aire" : deux unités quarré, donc une aire couplant ces deux unités.34 The outer ring is actually a figure-eight, with a self-intersection in the middle. Note that the graphic routines successfully render the polygon fill, so that visually it is appears to be an "area": two one-unit squares, so a total area of two units of area. 35 35 36 Essayons maintenant de voir ce que pense la base de données de notre polygone:36 Let's see what the database thinks the area of our polygon is: 37 37 38 38 .. code-block:: sql … … 46 46 0 47 47 48 Que ce passe-t-il ici ? L'algorythme qui calcule l'aire suppose que les contours ne s'intersectent pas. Un contours normal devra toujours avoir une aire qui est bornée (l'intérieur) dans un sens de la ligne du contour (peu importe quelle sens, juste *un* sens). Néanmoins, dans notre figure en 8, le contour externe est à droite de la ligne pour un lobe et à gauche pour l'autre. Cela entraine que les aire qui sont calculées pour chaque lobe annulent la précédente (l'une vaut 1 et l'autre -1) donc le résultat est une "aire de zéro".48 What's going on here? The algorithm that calculates area assumes that rings to not self-intersect. A well-behaved ring will always have the area that is bounded (the interior) on one side of the bounding line (it doesn't matter which side, just that it is on *one* side). However, in our (poorly behaved) figure-eight, the bounded area is to the right of the line for one lobe and to the left for the other. This causes the areas calculated for each lobe to cancel out (one comes out as 1, the other as -1) hence the "zero area" result. 49 49 50 50 51 D étecter la validité52 ------------------ --51 Detecting Validity 52 ------------------ 53 53 54 Dans l'exemple précédent nous avions un polygone que nous **savions** non-valide. Comment déterminer les géométries non valides dans une tables d'un million d'enregistrements ? Avec la fonction :command:`ST_IsValid(geometry)`. Utilisé avec notre polygone précédent, nous abtenons rapidement la réponse:54 In the previous example we had one polygon that we **knew** was invalid. How do we detect invalidity in a table with millions of geometries? With the :command:`ST_IsValid(geometry)` function. Used against our figure-eight, we get a quick answer: 55 55 56 56 .. code-block:: sql … … 62 62 f 63 63 64 Maintenant nous savons que l'entité est non-valide mais nous ne savons pas pourquoi. Nous pouvons utilier la fonction :command:`ST_IsValidReason(geometry)` pour trtouver la cause de non validité:64 Now we know that the feature is invalid, but we don't know why. We can use the :command:`ST_IsValidReason(geometry)` function to find out the source of the invalidity: 65 65 66 66 .. code-block:: sql … … 72 72 Self-intersection[1 1] 73 73 74 Vous remarquerez qu'en plus de la raison (intersection) la localisation de la non validité (coordonnée (1 1)) est aussi renvoyée.74 Note that in addition to the reason (self-intersection) the location of the invalidity (coordinate (1 1)) is also returned. 75 75 76 Nous pouvons aussi utiiliser la fonction :command:`ST_IsValid(geometry)` pour tester nos tables : 76 We can use the :command:`ST_IsValid(geometry)` function to test our tables too: 77 77 78 78 .. code-block:: sql 79 79 80 -- Trouver tout les polygones non valides et leur problÚme80 -- Find all the invalid polygons and what their problem is 81 81 SELECT name, boroname, ST_IsValidReason(the_geom) 82 82 FROM nyc_neighborhoods … … 94 94 95 95 96 R éparer les invalides97 -------------------- -96 Repairing Invalidity 97 -------------------- 98 98 99 Commençons par la mauvaise nouvelle : il n'y a aucune garantie de pouvoir corriger une géométrie non valide. Dans le pire des scénarios, vous pouvez utiliser la fonction :command:`ST_IsValid(geometry)` pour identifier les entités non valides, les déplacer dans une autre table, exporter cette table et les réparer à l'aide d'un outils extérieur.99 First the bad news: there is no guaranteed way to fix invalid geometries. The worst case scenario is identifying them with the :command:`ST_IsValid(geometry)` function, moving them to a side table, exporting that table, and repairing them externally. 100 100 101 Voici un exemple de requête SQL qui déplacent les géométries non valides hors de la table principale dans une table à part pour les exporter vers un programme de réparation.101 Here's an example of SQL to move invalid geometries out of the main table into a side table suitable for dumping to an external cleaning process. 102 102 103 103 .. code-block:: sql 104 104 105 -- Table à part des géométries non-valide105 -- Side table of invalids 106 106 CREATE TABLE nyc_neighborhoods_invalid AS 107 107 SELECT * FROM nyc_neighborhoods 108 108 WHERE NOT ST_IsValid(the_geom); 109 109 110 -- Suppression de la table principale110 -- Remove them from the main table 111 111 DELETE FROM nyc_neighborhoods 112 112 WHERE NOT ST_IsValid(the_geom); 113 113 114 Un bon outils pour réparer visuellemen des géométries non valide est OpenJump (http://openjump.org) qui contient un outils de validation depuis le menu**Tools->QA->Validate Selected Layers**.114 A good tool for visually repairing invalid geometry is OpenJump (http://openjump.org) which includes a validation routine under **Tools->QA->Validate Selected Layers**. 115 115 116 Maintenant, la bonne nouvelle : un grand nombre de non-validités **peuvent être résolues dans la base de données** en utilisant la fonction : :command:`ST_Buffer`.116 Now the good news: a large proportion of invalidities **can be fixed inside the database** using the :command:`ST_Buffer` function. 117 117 118 Le coup du Buffer tire avantafe de la maniÚre dont les buffers sont construit : une géométrie bufferisée est une nouvelle géométrie, construite en déplaçant les lignes de la géométrie d'origine. Si vous déplacez les lignes originales par *rien* (zero) alors la nouvelle géométrie aura une structure identique à l'originale, mais puisqu'elle utilise les rÚgles topologiques de l':term:`OGC, elle sera valide.118 The buffer trick takes advantage of the way buffers are built: a buffered geometry is a brand new geometry, constructed by offsetting lines from the original geometry. If you offset the original lines by **nothing** (zero) then the new geometry will be structurally identical to the original one, but because it is built using the :term:`OGC` topology rules, it will be valid. 119 119 120 Par exemple, voici un cas classique de non-validité - le "polygone de la banane" - un seul contour que crée une zone mais se touche, laissant un "trou" qui n'en est pas un.120 For example, here's a classic invalidity -- the "banana polygon" -- a single ring that encloses an area but bends around to touch itself, leaving a "hole" which is not actually a hole. 121 121 122 122 :: … … 126 126 .. image:: ./validity/banana.png 127 127 128 En créant un buffer de zero sur le polygone retourne un polygone :term:`OGC` valide, le contour externe et un contour interne qui touche l'autre en un seulpoint.128 Running the zero-offset buffer on the polygon returns a valid :term:`OGC` polygon, consisting of an outer and inner ring that touch at one point. 129 129 130 130 .. code-block:: sql … … 143 143 .. note:: 144 144 145 Le "polygone banane" (ou "coquillage inversé") est un cas où le modÚle topologique de l':term:`OGC` et de ESRI diffÚrent. Le model ESRI considÚre que les contours que se touchent sont non valides et préfÚre la forme de banane pour ce cas de figure. Le modÚle de l'OGC est l'inverse.145 The "banana polygon" (or "inverted shell") is a case where the :term:`OGC` topology model for valid geometry and the model used internally by ESRI differ. The ESRI model considers rings that touch to be invalid, and prefers the banana form for this kind of shape. The OGC model is the reverse. 146 146 -
/trunk/workshop-foss4g/projection_exercises.rst
r61 r1 1 1 .. _projection_exercises: 2 2 3 Partie 16 : Exercices sur les projections4 ================================ =========3 Section 16: Projection Exercises 4 ================================ 5 5 6 Voici un rappel de certaines fonctions que nous avons vu. Elles seront utiles pour les exercices ! 7 8 * :command:`sum(expression)` agrégation qui retourne la somme d'un ensemble de valeurs 9 * :command:`ST_Length(linestring)` retourne la longueur d'une ligne 10 * :command:`ST_SRID(geometry, srid)` retourne le SRID d'une géométrie 11 * :command:`ST_Transform(geometry, srid)` reprojette des géométries dans un autre systÚme de références spatiales 12 * :command:`ST_GeomFromText(text)` retourne un objet ``geometry`` 13 * :command:`ST_AsText(geometry)` retourne le WKT (``text``) 14 * :command:`ST_AsGML(geometry)` retourne le GML (``text``) 6 Here's a reminder of some of the functions we have seen. Hint: they should be useful for the exercises! 15 7 16 Rappelez-vous les resssources en ligne : 8 * :command:`sum(expression)` aggregate to return a sum for a set of records 9 * :command:`ST_Length(linestring)` returns the length of the linestring 10 * :command:`ST_SRID(geometry, srid)` returns the SRID of the geometry 11 * :command:`ST_Transform(geometry, srid)` converts geometries into different spatial reference systems 12 * :command:`ST_GeomFromText(text)` returns ``geometry`` 13 * :command:`ST_AsText(geometry)` returns WKT ``text`` 14 * :command:`ST_AsGML(geometry)` returns GML ``text`` 15 16 Remember the online resources that are available to you: 17 17 18 18 * http://spatialreference.org 19 19 * http://prj2epsg.org 20 20 21 Et les tables disponibles:21 Also remember the tables we have available: 22 22 23 23 * ``nyc_census_blocks`` … … 37 37 * name, boroname, the_geom 38 38 39 Exerci ces39 Exercises 40 40 --------- 41 41 42 * **" Quelle est la longueur des rue de New York, mesurée en UTM 18?"**42 * **"What is the length of all streets in New York, as measured in UTM 18?"** 43 43 44 44 .. code-block:: sql … … 51 51 10418904.7172 52 52 53 * **" Quelle est la définition du SRID 2831?"**53 * **"What is the WKT definition of SRID 2831?"** 54 54 55 55 .. code-block:: sql … … 58 58 WHERE SRID = 2831; 59 59 60 O u, via `prj2epsg <http://prj2epsg.org/epsg/2831>`_60 Or, via `prj2epsg <http://prj2epsg.org/epsg/2831>`_ 61 61 62 62 :: … … 87 87 88 88 89 * **" Quelle est la longueur des rue de New York, mesuré en utilisant le SRID 2831?"**89 * **"What is the length of all streets in New York, as measured in SRID 2831?"** 90 90 91 91 .. code-block:: sql … … 100 100 .. note:: 101 101 102 La différence entre les mesure en UTM 18 et en Stateplane Long Island est de (10421993 - 10418904)/10418904, soit 0.02%. Calculé sur la sphéroïde en utilissant en :ref:`geography`, le total des longueurs des route est 10421999, ce qui est proche de la valeur dans l'autre systÚme de projection (Stateplane Long Island). Ce dernier est précisément calibré pour une petite zone géographique (la ville de New York) alors que le systÚme UTM 18 doit fournir un résultat raisonable pour une zone régionale beaucoup plus large.102 The difference between the UTM 18 and the Stateplane Long Island measurements is (10421993 - 10418904)/10418904, or 0.02%. Calculated on the spheroid using :ref:`geography` the total street length is 10421999, which is closer to the Stateplane value. This is not surprising, since the Stateplane Long Island projection is precisely calibrated for a very small area (New York City) while UTM 18 has to provide reasonable results for a large regional area. 103 103 104 * **" Quelle est la représentation KML du point de la station de métris 'Broad St'?"**104 * **"What is the KML representation of the point at 'Broad St' subway station?"** 105 105 106 106 .. code-block:: sql … … 114 114 <Point><coordinates>-74.010671468873468,40.707104815584088</coordinates></Point> 115 115 116 H é ! les coordonnées sont géographiques bien que nous n'ayons pas fait appel à la fonction :command:`ST_Transform`, mais pourquoi ? Parce que le standard KML spécifie que toutes les coordonnées *doivent* être géographiques (en fait, dans le systÚme EPSG:4326), donc la fonction :command:`ST_AsKML` réalise la transformation automatiquement.116 Hey! The coordinates are in geographics even though we didn't call :command:`ST_Transform`, why? Because the KML standard dictates that all coordinates *must* be in geographics (ESPG:4326, in fact) so the :command:`ST_AsKML` function does the transformation automatically. -
/trunk/workshop-foss4g/geometry_returning.rst
r61 r1 1 1 .. _geometry_returning: 2 2 3 Partie 18 : Fonctions de construction de géométries4 =========================================== =========3 Section 18: Geometry Constructing Functions 4 =========================================== 5 5 6 Toute les fonctions que nous avons vu jusqu'à présent traitent les géométries "comme elles sont" et retournent: 6 All the functions we have seen so far work with geometries "as they are" and returns 7 7 8 * une analyse des objets (:command:`ST_Length(geometry)`, :command:`ST_Area(geometry)`),9 * une sérialisation des objets (:command:`ST_AsText(geometry)`, :command:`ST_AsGML(geometry)`),10 * une partie de l'objet (:command:`ST_RingN(geometry,n)`) ou11 * un résultat vrai/faux(:command:`ST_Contains(geometry,geometry)`, :command:`ST_Intersects(geometry,geometry)`).8 * analyses of the objects (:command:`ST_Length(geometry)`, :command:`ST_Area(geometry)`), 9 * serializations of the objects (:command:`ST_AsText(geometry)`, :command:`ST_AsGML(geometry)`), 10 * parts of the object (:command:`ST_RingN(geometry,n)`) or 11 * true/false tests (:command:`ST_Contains(geometry,geometry)`, :command:`ST_Intersects(geometry,geometry)`). 12 12 13 Les "fonctions de construction de géométries" prennent des géométries en entrée et retourne de nouvelles formes.13 "Geometry constructing functions" take geometries as inputs and output new shapes. 14 14 15 15 … … 17 17 ------------------------------- 18 18 19 Un besoin commun lors de la création de requêtes spatiales est de remplacer une entité polygonale par un point représentant cette entité. Cela esr utile pour les jointures spatiales (comme indiqué ici : :ref:`polypolyjoins`) car utiliser :command:`ST_Intersects(geometry,geometry)` avec deux polygones impliquera un double comptage : un polygone pour le contour externe intersectera dans les deux senses; le replacer par un point le forcera à être dans un seul sens, pas les deux.19 A common need when composing a spatial query is to replace a polygon feature with a point representation of the feature. This is useful for spatial joins (as discussed in :ref:`polypolyjoins`) because using :command:`ST_Intersects(geometry,geometry)` on two polygon layers often results in double-counting: a polygon on a boundary will intersect an object on both sides; replacing it with a point forces it to be on one side or the other, not both. 20 20 21 * :command:`ST_Centroid(geometry)` ret ourne le point qui est approximativement au centre de la masse de la géométrie passé en paramÚtre. C'est un calcul simle et rapide, mais parfois non proftable, car le point retourné peut se trouver à l'extérieur de l'entité elle-même. Si l'entité fournie est convee (imaginez la lettre 'C') le centroïde renvoyé pourrait ne pas être à l'intérieur du polygone.22 * :command:`ST_PointOnSurface(geometry)` ret ourne un point qui est obligatoirement dans l'entité passée en paramÚtre. Cette fonction coûte plus cher en ressource que le calcul du centroïd.21 * :command:`ST_Centroid(geometry)` returns a point that is approximately on the center of mass of the input argument. This simple calculation is very fast, but sometimes not desirable, because the returned point is not necessarily in the feature itself. If the input feature has a convexity (imagine the letter 'C') the returned centroid might not be in the interior of the feature. 22 * :command:`ST_PointOnSurface(geometry)` returns a point that is guaranteed to be inside the input argument. It is substantially more computationally expensive than the centroid operation. 23 23 24 24 .. image:: ./geometry_returning/centroid.jpg … … 28 28 --------- 29 29 30 L'opération de zone tampon est souvent disponible dans les outils SIG, il est aussi disponible dans PostGIS. La fonction :command:`ST_Buffer(geometry,distance)` prend en paramÚtre une géométrie et une distance et retourne une zone tampon dont le contour est à une distance données de la géométrie d'origine. 30 The buffering operation is common in GIS workflows, and is also available in PostGIS. :command:`ST_Buffer(geometry,distance)` takes in a buffer distance and geometry type and outputs a polygon with a boundary the buffer distance away from the input geometry. 31 31 32 32 .. image:: ./geometry_returning/st_buffer.png 33 33 34 Par exemple, si les services des parks américains souhaitaient renforcer la zone du traffique maritime autour de l'île 'Liberty', ils pourraient construire une zone tampon de 500 mÚtres autour de l'île. L'île de 'Liiberty' est représenté par un seul bloque dans notre table ``nyc_census_blocks`, nous pouvons donc facilement réaliser ce calcul. 34 For example, if the US Park Service wanted to enforce a marine traffic zone around Liberty Island, they might build a 500 meter buffer polygon around the island. Liberty Island is a single census block in our ``nyc_census_blocks`` table, so we can easily extract and buffer it. 35 35 36 36 .. code-block:: sql 37 37 38 -- Création d'une nouvelle table avec une zone tampon de 500 m autour de 'Liberty Island'38 -- Make a new table with a Liberty Island 500m buffer zone 39 39 CREATE TABLE libery_island_zone AS 40 40 SELECT ST_Buffer(the_geom,500) AS the_geom … … 42 42 WHERE blkid = '360610001009000'; 43 43 44 -- Mise à jour de la table geometry_columns44 -- Update the geometry_columns table 45 45 SELECT Populate_Geometry_Columns(); 46 46 47 47 .. image:: ./geometry_returning/liberty_positive.jpg 48 48 49 La fonction :command:`ST_Buffer` permet aussi d'utiliser des valeur négative pour le paramÚtre distance et construit un polygone inclue dans celui passé en paramÚtre. Pour les points et les lignes vous obtiendrez simplement un résultat vide.49 The :command:`ST_Buffer` function also accepts negative distances and builds inscribed polygons within polygonal inputs. For lines and points you will just get an empty return. 50 50 51 51 .. image:: ./geometry_returning/liberty_negative.jpg … … 55 55 --------------- 56 56 57 Une autre opération classique présente dans les SIGS - le chevauchement - crée une nouvelle entité en calculant la zone correpondant à l'intersection de deux polygones supperposés. Le résultat à la propriété de permettre de reconstruire les entité de base à l'aide de ce résultat.57 Another classic GIS operation -- the "overlay" -- creates a new coverage by calculating the intersection of two superimposed polygons. The resultant has the property that any polygon in either of the parents can be built by merging polygons in the resultant. 58 58 59 La fonction :command:`ST_Intersection(geometry A, geometry B)` retourne la zone géographique (ou une ligne, ou un point) que les deux géométries on en commun. Si les géométries sont disjointes, la fontion retourne une géométrie vide.59 The :command:`ST_Intersection(geometry A, geometry B)` function returns the spatial area (or line, or point) that both arguments have in common. If the arguments are disjoint, the function returns an empty geometry. 60 60 61 61 .. code-block:: sql 62 62 63 -- Quelle est l'aire que ces deux cercles ont en commun?64 -- U tilisons la fonction ST_Buffer pour créer ces cercles!63 -- What is the area these two circles have in common? 64 -- Using ST_Buffer to make the circles! 65 65 66 66 SELECT ST_AsText(ST_Intersection( … … 76 76 -------- 77 77 78 Dans l'exemple précédent nous intersections des géométries, créant une nouvelle géométrie unique à partir de deux entités. La commade :command:`ST_Union` fait l'inverse, elle prend en paramÚtre des géométries et supprime les parties communes. Il y a deux versions possibles de la fonction :command:`ST_Union`:78 In the previous example we intersected geometries, creating a new geometry that had lines from both the inputs. The :command:`ST_Union` does the reverse; it takes inputs and removes common lines. There are two forms of the :command:`ST_Union` function: 79 79 80 * :command:`ST_Union(geometry, geometry)`: une version avec deux paramÚtres qui prend les géométries et rentourne l'union des deux. Par exemple, nos deux cercles ressemble à ce qui suit si nous utilisons l'opération union plutÃŽt que l'intersection.80 * :command:`ST_Union(geometry, geometry)`: A two-argument version that takes in two geometries and returns the merged union. For example, our two-circle example from the previous section looks like this when you replace the intersection with a union. 81 81 82 82 .. code-block:: sql 83 83 84 -- Quelle est l'aire totale des ces deux cercles?85 -- U tilisons ST_Buffer pour créer les cercles!84 -- What is the total area these two circles cover? 85 -- Using ST_Buffer to make the circles! 86 86 87 87 SELECT ST_AsText(ST_Union( … … 93 93 94 94 95 * :command:`ST_Union([geometry])`: une version agrégée qui prendre un ensemble de géométries et retourne une géométrie contenant l'ensemble des géométries rassemblées. La fonction égrégée ST_Union peut être utilisé grâce au SQL ``GROUP BY`` our créer un ensemble rassemblant des sous-ensembles de géométries basiques. Cela est trÚs puissant, 96 97 Par exemple la fonction d'agrégation :command:`ST_Union`, considÚrons notre table ``nyc_census_blocks``. 95 * :command:`ST_Union([geometry])`: An aggregate version that takes in a set of geometries and returns the merged geometry for the entire group. The aggregate ST_Union can be used with the ``GROUP BY`` SQL statement to create carefully merged subsets of basic geometries. It is very powerful, 96 98 97 As an example of :command:`ST_Union` aggregation, consider our ``nyc_census_blocks`` table. Census geography is carefully constructed so that larger geographies can be built up from smaller ones. So, we can create a census tracts map by merging the blocks that form each tract (as we do later in :ref:`creatingtractstable`). Or, we can create a county map by merging blocks that fall within each county. 99 98 … … 114 113 .. code-block:: sql 115 114 116 -- Cr éation d'une table nyc_census_counties en regroupant les bloques115 -- Create a nyc_census_counties table by merging census blocks 117 116 CREATE TABLE nyc_census_counties AS 118 117 SELECT … … 122 121 GROUP BY countyid; 123 122 124 -- Mise à jour de la table geometry_columns123 -- Update the geometry_columns table 125 124 SELECT Populate_Geometry_Columns(); 126 125 … … 145 144 36085 | 149806077.958252 146 145 147 Ensuite nous calculons l'aire de chaque zone de nos nouveaux polygones de régions de la table count:146 Then we calculate the area of each of our new county polygons from the county table: 148 147 149 148 .. code-block:: sql … … 162 161 36085 | 149806077.958252 163 162 164 La même réponse ! Nous avons construit avec succÚs une table des régions de NYC à partir de nos données initiales.163 The same answer! We have successfully built an NYC county table from our census blocks data. 165 164 166 Liste des fonctions 167 ------------- ------165 Function List 166 ------------- 168 167 169 `ST_AsText(text) <http://postgis.org/docs/ST_AsText.html>`_: retourne la représentation Well-Known Text (WKT) de la geometry/geography sans métadonnée SRID.168 `ST_AsText(text) <http://postgis.org/docs/ST_AsText.html>`_: Returns the Well-Known Text (WKT) representation of the geometry/geography without SRID metadata. 170 169 171 170 `ST_Buffer(geometry, distance) <http://postgis.org/docs/ST_Buffer.html>`_: For geometry: Returns a geometry that represents all points whose distance from this Geometry is less than or equal to distance. Calculations are in the Spatial Reference System of this Geometry. For geography: Uses a planar transform wrapper. -
/trunk/workshop-foss4g/equality.rst
r61 r1 1 1 .. _equality: 2 2 3 Partie 22 : Ãgalité 3 Section 22: Equality 4 4 ================================= 5 5 6 Ãgalité 6 Equality 7 7 -------- 8 8 9 Ãtre en mesure de déterminer si deux geométries sont égales peut être compliqué. PostGIS met à votre disposition différentes fonctions permettant de juger de l'égalité à différents niveaux, bien que pour des raison de simplicité nous nuos contenterons ici de la définition fournie plus bas. Pour illustrer ces fonctions, nous utiliseront les polygones suivants.9 Determining equality when dealing with geometries can be tricky. PostGIS supports three different functions that can be used to determine different levels of equality, though for clarity we will use the definitions below. To illustrate these functions, we will use the following polygons. 10 10 11 11 .. image:: ./equality/polygon-table.png 12 12 13 Ces polygones sont charger à l'aide des commandes suivantes.13 These polygons are loaded using the following commands. 14 14 15 15 .. code-block:: sql … … 34 34 .. image:: ./equality/start13.png 35 35 36 Exact ement égaux37 ^^^^^^^^^^^^^ ^^^^^36 Exactly Equal 37 ^^^^^^^^^^^^^ 38 38 39 L'égalité exacte est déterminée en comparant deux géométries, sommets par sommets, dans l'ordre, pour s'assurer que chacun est à une position identique. Les exemples suivant montrent comment cette méthode peut être limitée dans son éfficacité.39 Exact equality is determined by comparing two geometries, vertex by vertex, in order, to ensure they are identical in position. The following examples show how this method can be limited in its effectiveness. 40 40 41 41 .. code-block:: sql … … 47 47 .. image:: ./equality/start14.png 48 48 49 Dans cette exemple, les polygones sont seulement égaux à eux-même, mais jamais avec un des autres polygones (dans notre exemple les polygones de 1 à 3). Dans le cas des polygones 1, 2 et 3, les sommets sont à des position identiques mais sont définies dans un ordre différent. Le polygone 4 a des sommets en double causant la non-égalité avec le polygone1.49 In this example, the polygons are only equal to themselves, not to other seemingly equivalent polygons (as in the case of Polygons 1 through 3). In the case of Polygons 1, 2, and 3, the vertices are in identical positions but are defined in differing orders. Polygon 4 has colinear (and thus redundant) vertices on the hexagon edges causing inequality with Polygon 1. 50 50 51 Spatiall ement égaux51 Spatially Equal 52 52 ^^^^^^^^^^^^^^^ 53 53 54 Comme nous l'avons précédemment, l'égalité exacte ne prend pas en compte la nature spatiale des géométries. Il y a une fonction, nommée :command:`ST_Equals`, permettant de tester l'égalité spatiale ou l'équivalent des géométries.54 As we saw above, exact equality does not take into account the spatial nature of the geometries. There is an function, aptly named :command:`ST_Equals`, available to test the spatial equality or equivalence of geometries. 55 55 56 56 .. code-block:: sql … … 62 62 .. image:: ./equality/start15.png 63 63 64 Ces résultats sont plus proches de notre compréhension intuitive de l'égalité. Les polygones de 1 à 4 sont cosidérés comme égaux, puisque qu'elles recouvrent la même zone. Notez que ni la direction despolygones n'est considérée, le point de départ pour la définition du polygone, ni le nombre de points. Ce qui importe c'est que la zone géographique représentée est la même. 64 These results are more in line with our intuitive understanding of equality. Polygons 1 through 4 are considered equal, since they enclose the same area. Note that neither the direction of the polygon is drawn, the starting point for defining the polygon, nor the number of points used are important here. What is important is that the polygons contain the same space. 65 65 66 Ãgalité des étendues67 ^^^^^^^^^^^^ ^^^^^^^^^66 Equal Bounds 67 ^^^^^^^^^^^^ 68 68 69 L'égalité exacte nécessite, dans le pire des cas, de comparer chaqu'un des sommets d'une géométrie pour déterminé l'égalité. Ceci peut être trÚs lent, et s'avérer innaproprié pour comparer un grand nombre de géométries. Pour permettre de rendre plus rapide ces comparaison, l'opération d'égalité des étendue est fournit : :command:`=`. Cet opérateur utilise uniquement les étendues (cadre limite rectangulaire), assurant que les géométries occupent le même espace dans un repÚre cartésien en deux dimensions, mais ne représente pas nécessairement le même espace.69 Exact equality requires, in the worst case, comparison of each and every vertex in the geometry to determine equality. This can be slow, and may not be appropriate for comparing huge numbers of geometries. To allow for speedier comparison, the equal bounds operator, :command:`=`, is provided. This operates only on the bounding box (rectangle), ensuring that the geometries occupy the same two dimensional extent, but not necessarily the same space. 70 70 71 71 .. code-block:: sql … … 77 77 .. image:: ./equality/start17.png 78 78 79 Comme vous pouvez le constater, toutes les géométries égales ont aussi une étendue égales. Malheureusement, le polygone 5 est aussi retourné comme étant égal avec ce test, puisqu'il partage la même étendue que les autres géométries. Mais alors, pourquoi est-ce utile ? Bien que cela soit traité en détail plus tard, la réponse courte est que cela permet l'utilisation d'indexation spatiales qui peuvent réduire drastiquement les ensembles de géométries à comparrer en utilisant des filtres utilisant cette égalité d'étendues.79 As you can see, all of our spatially equal geometries also have equal bounds. Unfortunately, Polygon 5 is also returned as equal under this test, because it shares the same bounding box as the other geometries. Why is this useful, then? Although this will be covered in detail later, the shot answer is that this enables the use of spatial indexing that can quickly reduce huge comparison sets into more manageable blocks when joining or filtering data. 80 80 -
/trunk/workshop-foss4g/spatial_relationships.rst
r61 r1 1 1 .. _spatial_relationships: 2 2 3 Partie 10 : Les relations spatiales3 Section 10: Spatial Relationships 4 4 ================================= 5 5 6 Jusqu'à présent, nous avons utilisé uniquement des fonctions qui permettent de mesurer (:command:`ST_Area`, :command:`ST_Length`), de sérialiser (:command:`ST_GeomFromText`) ou désérialiser (:command:`ST_AsGML`) des géométries. Ces fonctions sont toutes utilisées sur une géométrie à la fois.6 So far we have only used spatial functions that measure (:command:`ST_Area`, :command:`ST_Length`), serialize (:command:`ST_GeomFromText`) or deserialize (:command:`ST_AsGML`) geometries. What these functions have in common is that they only work on one geometry at a time. 7 7 8 Les base de données spatiales sont puissantes car elle ne se contentent pas de stocker les géométries, elle peuvent aussi vérifier les *relations entre les géométries*. 8 Spatial databases are powerful because they not only store geometry, they also have the ability to compare *relationships between geometries*. 9 9 10 Pour les questions comme "Quel est le plus proche garage à vélo prêt du parc ?" ou "Ou est l'intersection du métro avec telle rue ?", nous devrons comparer les géométries représentant les garage à vélo, les rues et les lignes de métro.10 Questions like âWhich are the closet bike racks to a park?â or âWhere are the intersections of subway lines and streets?â can only be answered by comparing geometries representing the bike racks, streets, and subway lines. 11 11 12 Le standard de l'OGC définit l'ensemble de fonctions suivant pour comparer les géométries.12 The OGC standard defines the following set of methods to compare geometries. 13 13 14 14 ST_Equals 15 15 --------- 16 16 17 :command:`ST_Equals(geometry A, geometry B)` test e l'égalité spatiale de deux géométries.17 :command:`ST_Equals(geometry A, geometry B)` tests the spatial equality of two geometries. 18 18 19 19 .. figure:: ./spatial_relationships/st_equals.png 20 20 :align: center 21 21 22 ST_Equals ret ourne TRUE si les deux géométries sont du même type et ont des coordonnées x.y identiques.22 ST_Equals returns TRUE if two geometries of the same type have identical x,y coordinate values, i.e. if the secondary shape is equal (identical) to the primary shape object. 23 23 24 PremiÚrement, essayons de récupérer la représentation d'un point de notre table ``nyc_subway_stations``. Nous ne prendrons que l'entrée :'Broad St'.24 First, let's retrieve a representation of a point from our ``nyc_subway_stations`` table. We'll take just the entry for 'Broad St'. 25 25 26 26 .. code-block:: sql … … 36 36 Broad St | 0101000020266900000EEBD4CF27CF2141BC17D69516315141 | POINT(583571 4506714) 37 37 38 Maintenant, copiez / collez la valeur affichée pour tester la fonction :command:`ST_Equals`:38 Then, plug the geometry representation back into an :command:`ST_Equals` test: 39 39 40 40 .. code-block:: sql … … 50 50 .. note:: 51 51 52 La représentation du point n'est pas vraiment compréhensible (``0101000020266900000EEBD4CF27CF2141BC17D69516315141``) mais c'est exactement la représentation des coordonnées. Pour tester l'égalité, l'utilisation de ce format est nécessaire.52 The representation of the point was not very human readable (``0101000020266900000EEBD4CF27CF2141BC17D69516315141``) but it was an exact representation of the coordinate values. For a test like equality, using the exact coordinates in necessary. 53 53 54 54 55 ST_Intersects, ST_Disjoint, ST_Crosses etST_Overlaps55 ST_Intersects, ST_Disjoint, ST_Crosses and ST_Overlaps 56 56 ------------------------------------------------------ 57 57 58 :command:`ST_Intersects`, :command:`ST_Crosses`, et :command:`ST_Overlaps` teste si l'intérieur des géométries s'intersecte, se croise ou se chevauche.58 :command:`ST_Intersects`, :command:`ST_Crosses`, and :command:`ST_Overlaps` test whether the interiors of the geometries intersect. 59 59 60 60 .. figure:: ./spatial_relationships/st_intersects.png 61 61 :align: center 62 62 63 :command:`ST_Intersects(geometry A, geometry B)` ret ourne t (TRUE) si l'intersection ne renvoit pas un ensemble vide de résultats. Intersects retourne le résultat exactement inverse de la fonctiondisjoint.63 :command:`ST_Intersects(geometry A, geometry B)` returns t (TRUE) if the intersection does not result in an empty set. Intersects returns the exact opposite result of disjoint. 64 64 65 65 .. figure:: ./spatial_relationships/st_disjoint.png 66 66 :align: center 67 67 68 L'opposé de ST_Intersects est :command:`ST_Disjoint(geometry A , geometry B)`. Si deux géométries sont disjointes, elle ne s'intersectent pas et vice-versa. En fait, il est souvent plus éfficace de tester si deux géométries ne s'intersectent pas que de tester si elles sont dijointes du fait que le test d'intersection peut être spatialement indexé alors que le test disjoint ne le peut pas.68 The opposite of ST_Intersects is :command:`ST_Disjoint(geometry A , geometry B)`. If two geometries are disjoint, they do not intersect, and vice-versa. In fact, it is often more efficient to test "not intersects" than to test "disjoint" because the intersects tests can be spatially indexed, while the disjoint test cannot. 69 69 70 70 .. figure:: ./spatial_relationships/st_crosses.png 71 71 :align: center 72 72 73 Pour les comparaisons de couples de types multipoint/polygon, multipoint/linestring, linestring/linestring, linestring/polygon, et linestring/multipolygon, :command:`ST_Crosses(geometry A, geometry B)` retourne t (TRUE) si les résultats de l'intersection sont à l'intérieur des deux géométries.73 For multipoint/polygon, multipoint/linestring, linestring/linestring, linestring/polygon, and linestring/multipolygon comparisons, :command:`ST_Crosses(geometry A, geometry B)` returns t (TRUE) if the intersection results in a geometry whose dimension is one less than the maximum dimension of the two source geometries and the intersection set is interior to both source geometries. 74 74 75 75 .. figure:: ./spatial_relationships/st_overlaps.png 76 76 :align: center 77 77 78 :command:`ST_Overlaps(geometry A, geometry B)` compare deux géométries de même dimension et retourne TRUE si leur intersection est une géométrie différente des deux fournies mais de même dimension.78 :command:`ST_Overlaps(geometry A, geometry B)` compares two geometries of the same dimension and returns TRUE if their intersection set results in a geometry different from both but of the same dimension. 79 79 80 Essayons de prendre la station de métro de Broad Street et de déterminer sont voisinage en utilisant la fonction :command:`ST_Intersects`:80 Let's take our Broad Street subway station and determine its neighborhood using the :command:`ST_Intersects` function: 81 81 82 82 .. code-block:: sql … … 97 97 ---------- 98 98 99 :command:`ST_Touches` test e si deux géométries se touchent en leur contours extérieurs, mais leur contours intérieurs ne s'intersectent pas99 :command:`ST_Touches` tests whether two geometries touch at their boundaries, but do not intersect in their interiors 100 100 101 101 .. figure:: ./spatial_relationships/st_touches.png 102 102 :align: center 103 103 104 :command:`ST_Touches(geometry A, geometry B)` ret ourn TRUE soit si les contours des géométries s'intersectent ou si l'un des contours intérieurs de l'une intersecte le contour extérieur de l'autre.104 :command:`ST_Touches(geometry A, geometry B)` returns TRUE if either of the geometries' boundaries intersect or if only one of the geometry's interiors intersects the other's boundary. 105 105 106 ST_Within etST_Contains106 ST_Within and ST_Contains 107 107 ------------------------- 108 108 109 :command:`ST_Within` et :command:`ST_Contains` test si une géométrie est totalement incluse dans l'autre.109 :command:`ST_Within` and :command:`ST_Contains` test whether one geometry is fully within the other. 110 110 111 111 .. figure:: ./spatial_relationships/st_within.png 112 112 :align: center 113 113 114 :command:`ST_Within(geometry A , geometry B)` ret ourne TRUE si la premiÚre géométrie est complÚtement contenue dans l'autre. ST_Within test l'exact opposé au résultat deST_Contains.114 :command:`ST_Within(geometry A , geometry B)` returns TRUE if the first geometry is completely within the second geometry. ST_Within tests for the exact opposite result of ST_Contains. 115 115 116 :command:`ST_Contains(geometry A, geometry B)` ret ourne TRUE si la seconde géométrie est complÚtement contenue dans la premiÚre géométrie.116 :command:`ST_Contains(geometry A, geometry B)` returns TRUE if the second geometry is completely contained by the first geometry. 117 117 118 118 119 ST_Distance etST_DWithin119 ST_Distance and ST_DWithin 120 120 -------------------------- 121 121 122 Une question fréquente dans le domaine du SIG est "trouver tout les éléments qui se trouvent à une distance X de cet autre élément". 122 An extremely common GIS question is "find all the stuff within distance X of this other stuff". 123 123 124 La fonction :command:`ST_Distance(geometry A, geometry B)` calcule la *plus courte* distance entre deux géométries. Cela est pratique pour récupérer la distance entre les objets.124 The :command:`ST_Distance(geometry A, geometry B)` calculates the *shortest* distance between two geometries and returns it as a float. This is useful for actually reporting back the distance between objects. 125 125 126 126 .. code-block:: sql … … 134 134 3 135 135 136 Pour tester si deux objets sont à la même distance d'un autre, la fonction :command:`ST_DWithin` fournit un test tirant profit des indexes. Cela est trÚs utile pour répondre a une question telle que: "Combien d'arbre se situent dans un buffer de 500 mÚtres autour de cette route ?". Vous n'avez pas à calculer le buffer, vous avez simplement besoin de tester la distance entre les géométries.136 For testing whether two objects are within a distance of one another, the :command:`ST_DWithin` function provides an index-accelerated true/false test. This is useful for questions like "how many trees are within a 500 meter buffer of the road?". You don't have to calculate an actual buffer, you just have to test the distance relationship. 137 137 138 138 .. figure:: ./spatial_relationships/st_dwithin.png 139 139 :align: center 140 140 141 En utilisant de nouveau notre station de métro Broad Street, nous pouvons trouver les rues voisines (à 10 mÚtres de) de la station:141 Using our Broad Street subway station again, we can find the streets nearby (within 10 meters of) the subway stop: 142 142 143 143 .. code-block:: sql … … 159 159 Nassau St 160 160 161 Nous pouvons vérifier la réponse sur une carte. La station Broad St est actuellement à l'intersection des rues Wall, Broad et Nassau. 161 And we can verify the answer on a map. The Broad St station is actually at the intersection of Wall, Broad and Nassau Streets. 162 162 163 163 .. image:: ./spatial_relationships/broad_st.jpg 164 164 165 Liste des fonctions 166 ------------- ------165 Function List 166 ------------- 167 167 168 `ST_Contains(geometry A, geometry B) <http://postgis.org/docs/ST_Contains.html>`_ : retourne TRUE si aucun des points de B n'est à l'extérieur de A, et au moins un point de l'intérieur de B est à l'intérieur deA.168 `ST_Contains(geometry A, geometry B) <http://postgis.org/docs/ST_Contains.html>`_: Returns true if and only if no points of B lie in the exterior of A, and at least one point of the interior of B lies in the interior of A. 169 169 170 `ST_Crosses(geometry A, geometry B) <http://postgis.org/docs/ST_Crosses.html>`_ : retourne TRUE si la géométrie A a certains, mais pas la totalité, de ses points à l'intérieur de B.170 `ST_Crosses(geometry A, geometry B) <http://postgis.org/docs/ST_Crosses.html>`_: Returns TRUE if the supplied geometries have some, but not all, interior points in common. 171 171 172 `ST_Disjoint(geometry A , geometry B) <http://postgis.org/docs/ST_Disjoint.html>`_ : retourne TRUE si les gémétries nes s'intersectent pas - elles n'ont aucun point en commun.172 `ST_Disjoint(geometry A , geometry B) <http://postgis.org/docs/ST_Disjoint.html>`_: Returns TRUE if the Geometries do not "spatially intersect" - if they do not share any space together. 173 173 174 `ST_Distance(geometry A, geometry B) <http://postgis.org/docs/ST_Distance.html>`_ : retourne la distance cartésienne en 2 dimensions minimum entre deux géométries dans l'unité de la projection.174 `ST_Distance(geometry A, geometry B) <http://postgis.org/docs/ST_Distance.html>`_: Returns the 2-dimensional cartesian minimum distance (based on spatial ref) between two geometries in projected units. 175 175 176 `ST_DWithin(geometry A, geometry B, radius) <http://postgis.org/docs/ST_DWithin.html>`_ : retourne TRUE si les géométries sont distante (radius) l'une de l'autre.176 `ST_DWithin(geometry A, geometry B, radius) <http://postgis.org/docs/ST_DWithin.html>`_: Returns true if the geometries are within the specified distance (radius) of one another. 177 177 178 `ST_Equals(geometry A, geometry B) <http://postgis.org/docs/ST_Equals.html>`_ : retourn TRUE si les géométries fournis représentent la même géométrie. L'ordre des entités n'est pas prit en compte.178 `ST_Equals(geometry A, geometry B) <http://postgis.org/docs/ST_Equals.html>`_: Returns true if the given geometries represent the same geometry. Directionality is ignored. 179 179 180 `ST_Intersects(geometry A, geometry B) <http://postgis.org/docs/ST_Intersects.html>`_ : retourne TRUE si les géométries s'intersectent - (ont un espace en commun) et FALSE si elles n'en ont pas (elles sont disjointes).180 `ST_Intersects(geometry A, geometry B) <http://postgis.org/docs/ST_Intersects.html>`_: Returns TRUE if the Geometries/Geography "spatially intersect" - (share any portion of space) and FALSE if they don't (they are Disjoint). 181 181 182 `ST_Overlaps(geometry A, geometry B) <http://postgis.org/docs/ST_Overlaps.html>`_ : retourne TRUE si les géométries ont un espace en commun, sont de la même dimension, mais ne sont pas complÚtement contenues l'une dans l'autre.182 `ST_Overlaps(geometry A, geometry B) <http://postgis.org/docs/ST_Overlaps.html>`_: Returns TRUE if the Geometries share space, are of the same dimension, but are not completely contained by each other. 183 183 184 `ST_Touches(geometry A, geometry B) <http://postgis.org/docs/ST_Touches.html>`_ : retourne TRUE si les géométries ont au moins un point en commun, mais leur intérieurs ne s'intersectent pas.184 `ST_Touches(geometry A, geometry B) <http://postgis.org/docs/ST_Touches.html>`_: Returns TRUE if the geometries have at least one point in common, but their interiors do not intersect. 185 185 186 `ST_Within(geometry A , geometry B) <http://postgis.org/docs/ST_Within.html>`_ : retourne TRUE si la géométrie A est complÚtement à l'intérieur deB186 `ST_Within(geometry A , geometry B) <http://postgis.org/docs/ST_Within.html>`_: Returns true if the geometry A is completely inside geometry B 187 187 188 188 -
/trunk/workshop-foss4g/geometries.rst
r61 r1 1 1 .. _geometries: 2 2 3 Partie 8 : Les géometries3 Section 8: Geometries 4 4 ===================== 5 5 … … 7 7 ------------ 8 8 9 Dans :ref:`une partie précédente<loading_data>` nous avons charger différentes données. Avant de commencer à jouer avec, commençons par regarder quelques exemples simples. Depuis pgAdmin, choisissez de nouveau la base de donnée **nyc** et ouvrez l'outil de requêtage SQL. Copiez cette exemple de code SQL (aprÚs avoir supprimer le contenu présent par défaut si nécessaire) puis exécutez-le.9 In the previous :ref:`section <loading_data>`, we loaded a variety of data. Before we start playing with our data lets have a look at some simpler examples. In pgAdmin, once again select the **nyc** database and open the SQL query tool. Paste this example SQL code into the pgAdmin SQL Editor window (removing any text that may be there by default) and then execute. 10 10 11 11 .. code-block:: sql … … 26 26 .. image:: ./geometries/start01.png 27 27 28 L'exemple ci-dessus créé une table (**geometries**) puis y insert cinq géométries : un point, une ligne, un polygone, un polygone avec un trou, et une collection. Les lignes insérées sont sélectionnées et affichées dans le tableau de sortie.29 30 Les tables de métadonnées31 --------------- ----------32 33 Dans le respect de la spécification Simple Features for SQL (:term:`SFSQL`), PostGIS fournit deux tables pour récupérer et s'informer sur les types de géométries disponibles dans une base de données spécifique. 34 35 * La premiÚre table, ``spatial_ref_sys``, définit tout les systÚmes de projection connus de la base de données et sera décrite plus en détails plus tard.36 * La seconde table, ``geometry_columns``, fournit une liste de toutes les "entités" (définit comme un objet avec un attribut géométrique) et les détails de base relatives à ces entités.28 The above example CREATEs a table (**geometries**) then INSERTs five geometries: a point, a line, a polygon, a polygon with a hole, and a collection. Finally, the inserted rows are SELECTed and displayed in the Output pane. 29 30 Metadata Tables 31 --------------- 32 33 In conformance with the Simple Features for SQL (:term:`SFSQL`) specification, PostGIS provides two tables to track and report on the geometry types available in a given database. 34 35 * The first table, ``spatial_ref_sys``, defines all the spatial reference systems known to the database and will be described in greater detail later. 36 * The second table, ``geometry_columns``, provides a listing of all "features" (defined as an object with geometric attributes), and the basic details of those features. 37 37 38 38 .. image:: ./geometries/table01.png 39 39 40 Dans l'exemple founit en introduction, la fonction :command:`Populate_Geometry_Columns()` détecte toute les colonnes de la base de données qui contiennent des géométries et met à jour la table ``geometry_columns`` pour y inclure leurs références. 41 42 Regardons maintenant la table ``geometry_columns`` de notre base de données. Copiez cette commande dans la fenêtre de requêtage : 43 40 In our introductory example, the :command:`Populate_Geometry_Columns()` function finds all the columns in the database that contain geometry and updates the ``geometry_columns`` table to include references to them. 41 42 Lets have a look at the ``geometry_columns`` table in our database. Paste this command in the Query Tool as before: 44 43 45 44 .. code-block:: sql … … 49 48 .. image:: ./geometries/start08.png 50 49 51 * ``f_table_catalog``, ``f_table_schema``, et ``f_table_name`` fournissent le nom complet de la table contenant une géométrie donnée. Ãtant donné que PostgreSQL n'utilise pas de catalogues, ``f_table_catalog`` est toujouts vide.52 * ``f_geometry_column`` est le nom de la colonne qui contient la géométrie -- pour les tables ayant plusieurs colonnes géométriques, il y a un enregistrement dans cette table pour chacune.53 * ``coord_dimension`` et ``srid`` définissent respectivement la dimension de la géométrie (en 2-, 3- or 4-dimensions) et le systÚme de références spatiales qui fait référence à la table ``spatial_ref_sys``.54 * La colonne ``type`` définit le type de géométrie comme décrit plus tÃŽt, nous avons déjà vu les points et les lignes.55 56 En interrogeant cette table, les clients SIG et les libraires peuvent déterminer quoi attendre lors de la récupération des données et peuvent réaliser les opération de reprojection, transformation ou rendu sans avoir à inspecter chaque géométrie.57 58 R éprésenter des objets du monde réel59 ------------------------------- ----60 61 La spécification Simple Features for SQL (:term:`SFSQL`), le standard ayant guidé le développement de PostGIS, définit comment les objets du monde réel doivent être représentés. En considérant une forme continue à une seule résolution fixe, nous obtenons une piÚtre représentation des objets. SFSQL considÚre uniquement les représentations en 2 dimensions. PostGIS a étendu cela en ajoutant les représentation en 3 et 4 dimensions. Plus récemment, la spécification SQL-Multimedia Part 3 (:term:`SQL/MM`) a officiellement définit sa propre représentation. 62 63 Notre table exemple contient différents types de géométries. Nous pouvons récupérer les informations de chaque objet en utilisant les fonctions qui lisent les métadonnées de la géométrie.64 65 * :command:`ST_GeometryType(geometry)` ret ourne le type de la géométrie66 * :command:`ST_NDims(geometry)` ret ourne le nombre de dimensions d'une géométrie67 * :command:`ST_SRID(geometry)` ret ourne l'identifiant de référence spatiale de la géométrie50 * ``f_table_catalog``, ``f_table_schema``, and ``f_table_name`` provide the fully qualified name of the feature table containing a given geometry. Because PostgreSQL doesn't make use of catalogs, ``f_table_catalog`` will tend to be empty. 51 * ``f_geometry_column`` is the name of the column that geometry containing column -- for feature tables with multiple geometry columns, there will be one record for each. 52 * ``coord_dimension`` and ``srid`` define the the dimension of the geometry (2-, 3- or 4-dimensional) and the Spatial Reference system identifier that refers to the ``spatial_ref_sys`` table respectively. 53 * The ``type`` column defines the type of geometry as described below; we've seen Point and Linestring types so far. 54 55 By querying this table, GIS clients and libraries can determine what to expect when retrieving data and can perform any necessary projection, processing or rendering without needing to inspect each geometry. 56 57 Representing Real World Objects 58 ------------------------------- 59 60 The Simple Features for SQL (:term:`SFSQL`) specification, the original guiding standard for PostGIS development, defines how a real world object is represented. By taking a continuous shape and digitizing it at a fixed resolution we achieve a passable representation of the object. SFSQL only handled 2-dimensional representations. PostGIS has extended that to include 3- and 4-dimensional representations; more recently the SQL-Multimedia Part 3 (:term:`SQL/MM`) specification has officially defined their own representation. 61 62 Our example table contains a mixture of different geometry types. We can collect general information about each object using functions that read the geometry metadata. 63 64 * :command:`ST_GeometryType(geometry)` returns the type of the geometry 65 * :command:`ST_NDims(geometry)` returns the number of dimensions of the geometry 66 * :command:`ST_SRID(geometry)` returns the spatial reference identifier number of the geometry 68 67 69 68 .. code-block:: sql … … 84 83 85 84 86 Les points87 ~~~~~~ ~~~~~85 Points 86 ~~~~~~ 88 87 89 88 .. image:: ./introduction/points.png 90 89 :align: center 91 90 92 Un **point** représente une localisation unique sur la Terre. Ce point est représenté par une seule coordonnée (incluant soit 2, 3 ou 4 dimensions). Les points sont utilisés pour représenter des objets lorsque le détail exact du contour n'est pas important à une échelle donnée. Par exemple, les villes sur une carte du monde peuvent être décrite sous la forme de points alors qu'une carte régionale utiliserait une représentation polygonale des villes. 91 A spatial **point** represents a single location on the Earth. This point is represented by a single coordinate (including either 2-, 3- or 4-dimensions). Points are used to represent objects when the exact details, such as shape and size, are not important at the target scale. For example, cities on a map of the world can be described as points, while a map of a single state might represent cities as polygons. 93 92 94 93 .. code-block:: sql … … 102 101 POINT(0 0) 103 102 104 Certaines des fonctions spécifiques pour travailler avec les points sont:105 106 * :command:`ST_X(geometry)` ret ourne la composante X107 * :command:`ST_Y(geometry)` ret ourne la composante Y108 109 Donc, nous pouvons lire les coordonnées d'un point de la maniÚre suivante:103 Some of the specific spatial functions for working with points are: 104 105 * :command:`ST_X(geometry)` returns the X ordinate 106 * :command:`ST_Y(geometry)` returns the Y ordinate 107 108 So, we can read the ordinates from a point like this: 110 109 111 110 .. code-block:: sql … … 115 114 WHERE name = 'Point'; 116 115 117 La table des stations de métro de la ville de New York (``nyc_subway_stations``) est un ensemble de données représenté sous la forme de points. La requête SQL suivante renverra la géométrie associée à un point (dans la colonne :command:`ST_AsText`).116 The New York City subway stations (``nyc_subway_stations``) table is a data set represented as points. The following SQL query will return the geometry associated with one point (in the :command:`ST_AsText` column). 118 117 119 118 .. code-block:: sql … … 124 123 125 124 126 L es lignes125 Linestrings 127 126 ~~~~~~~~~~~ 128 127 … … 130 129 :align: center 131 130 132 Une **ligne** est un chemin entre plusieurs points. Elle prend la forme d'un tableau ordonné composé de deux (ou plusieurs) points. Les routes et les riviÚres sont typiquement représentés sous la forme de lignes. Une ligne est dite **fermée** si elle commence et fini en un même point. Elle est dite **simple** si elle ne se coupe pas ou ne se touche pas elle-même (sauf à ses extrémités si elle est fermée). Une ligne peut être à la fois **fermée** et**simple**.133 134 Le réseau des rues de New York (``nyc_streets``) a été chargé auparavant. Cet ensemble de données contient les détails comme le nom et le type des rues. Une rue du monde réel pourrait être constituée de plusieurs lignes, chacune représentant une file avec différents attributs.135 136 La requête SQL suivante retourne la géométrie associée à une ligne (dans la colonne :command:`ST_AsText`) : 131 A **linestring** is a path between locations. It takes the form of an ordered series of two or more points. Roads and rivers are typically represented as linestrings. A linestring is said to be **closed** if it starts and ends on the same point. It is said to be **simple** if it does not cross or touch itself (except at its endpoints if it is closed). A linestring can be both **closed** and **simple**. 132 133 The street network for New York (``nyc_streets``) was loaded earlier in the workshop. This dataset contains details such as name, and type. A single real world street may consist of many linestrings, each representing a segment of road with different attributes. 134 135 The following SQL query will return the geometry associated with one linestring (in the :command:`ST_AsText` column). 137 136 138 137 .. code-block:: sql … … 146 145 LINESTRING(0 0, 1 1, 2 1, 2 2) 147 146 148 Les fonctions spatiales permettant de travailler avec les lignes sont les suivantes:149 150 * :command:`ST_Length(geometry)` ret ourne la longueur d'une ligne151 * :command:`ST_StartPoint(geometry)` ret ourne le premier point d'une ligne152 * :command:`ST_EndPoint(geometry)` ret ourne le denier point d'une ligne153 * :command:`ST_NPoints(geometry)` ret ourne le nombre de points dans une ligne154 155 Donc, la longueur de notre ligne est:147 Some of the specific spatial functions for working with linestrings are: 148 149 * :command:`ST_Length(geometry)` returns the length of the linestring 150 * :command:`ST_StartPoint(geometry)` returns the first coordinate as a point 151 * :command:`ST_EndPoint(geometry)` returns the last coordinate as a point 152 * :command:`ST_NPoints(geometry)` returns the number of coordinates in the linestring 153 154 So, the length of our linestring is: 156 155 157 156 .. code-block:: sql … … 166 165 167 166 168 Les polygones169 ~~~~~~~~ ~~~~~~167 Polygons 168 ~~~~~~~~ 170 169 171 170 .. image:: ./introduction/polygons.png 172 171 :align: center 173 172 174 Un polygone est représenté comme une zone. Le contour externe du polygone est représenté par une ligne simple et fermée. Les trous sont représenté de la même maniÚre.175 176 Les polygones sont utilisés pour représenter les objets dont les tailles et la forme sont importants. Les limites de villes, les parcs, les bâtiments ou les cours d'eau sont habituellement représenté par des polygones lorsque l'échelle est suffisament élevée pour voir distinguer leurs zones. Les routes et les riviÚres peuvent parfois être représenté comme des polygones.177 178 La requête SQL suivante retournera la géométrie associée à un polygone (dans la colonne :command:`ST_AsText`).173 A polygon is a representation of an area. The outer boundary of the polygon is represented by a ring. This ring is a linestring that is both closed and simple as defined above. Holes within the polygon are also represented by rings. 174 175 Polygons are used to represent objects whose size and shape are important. City limits, parks, building footprints or bodies of water are all commonly represented as polygons when the scale is sufficiently high to see their area. Roads and rivers can sometimes be represented as polygons. 176 177 The following SQL query will return the geometry associated with one linestring (in the :command:`ST_AsText` column). 179 178 180 179 .. code-block:: sql … … 186 185 .. note:: 187 186 188 PlutÃŽt que d'utiliser le signe ``=`` dans notre clause ``WHERE``, nous avons utilisé l'opérateur ``LIKE`` pour pouvoir définir notre comparaison. Vous auriez sans doute voulu utiliser le symbole ``*`` pour exprimer "n'importe quelle valeur" mais en SQL vous devez utiliser : ``%`` et l'opérateur ``LIKE`` pour informer le systÚme que cette comparaison doit être possible.187 Rather than using an ``=`` sign in our ``WHERE`` clause, we are using the ``LIKE`` operator to carry out a string matching operation. You may be used to the ``*`` symbol as a "glob" for pattern matching, but in SQL the ``%`` symbol is used, along with the ``LIKE`` operator to tell the system to do globbing. 189 188 190 189 :: … … 193 192 POLYGON((0 0, 10 0, 10 10, 0 10, 0 0),(1 1, 1 2, 2 2, 2 1, 1 1)) 194 193 195 Le premier polygone a seulement une ligne. Le second a un "trou". La plupart des systÚmes de rendu graphique supportent le concept de "polygone", mais les systÚmes SIG sont les seuls à accepter que les polygones puissent contenir des trous.194 The first polygon has only one ring. The second one has an interior "hole". Most graphics systems include the concept of a "polygon", but GIS systems are relatively unique in allowing polygons to explicitly have holes. 196 195 197 196 .. image:: ./screenshots/polygons.png 198 197 199 Certaines des fonctions spatiales spécifiques de traitement des polygones sont:200 201 * :command:`ST_Area(geometry)` ret ourne l'aire d'un polygone202 * :command:`ST_NRings(geometry)` ret ourne le nombre de contours (habituellement 1, plus lorsqu'il y a des trous)203 * :command:`ST_ExteriorRing(geometry)` ret ourne le contour extérieur204 * :command:`ST_InteriorRingN(geometry,n)` ret ourne le contour intérieur numéro n205 * :command:`ST_Perimeter(geometry)` ret ourne la longueur de tout les contours206 207 Nous pouvons calculer l'aire de nos polygones en utilisant la fonction area:198 Some of the specific spatial functions for working with polygons are: 199 200 * :command:`ST_Area(geometry)` returns the area of the polygons 201 * :command:`ST_NRings(geometry)` returns the number of rings (usually 1, more of there are holes) 202 * :command:`ST_ExteriorRing(geometry)` returns the outer ring as a linestring 203 * :command:`ST_InteriorRingN(geometry,n)` returns a specified interior ring as a linestring 204 * :command:`ST_Perimeter(geometry)` returns the length of all the rings 205 206 We can calculate the area of our polygons using the area function: 208 207 209 208 .. code-block:: sql … … 218 217 PolygonWithHole 99 219 218 220 Remarquez que le polygone contenant un trou a une aire égale à l'aire du contour externe (un carré de 10 sur 10) moins l'aire du trou (un carré de 1 sur 1).221 222 Les collections223 ~~~~~~~~~~~ ~~~~~224 225 Il y a quatre types de collections, qui regroupe ensemble plusieurs géométries simples. 226 227 * **MultiPoint**, une collection depoints228 * **MultiLineString**, une collection de lignes229 * **MultiPolygon**, une collection de polygones230 * **GeometryCollection**, une collection hétérogÚne de n'importe quelle géométrie (dont d'autrecollections)231 232 Les collections sont un concept présents dans les logiciels SIG plus que dans les applications de rendu graphique génériques. Elles sont utiles pour directement modeler les objets du monde réel comme des objet spatiaux. Par exemple, comment modéliser une parcelle qui a été coupée par un chemin ? Comme un **MultiPolygon**, ayant une partie de chaque coté du chemin.219 Note that the polygon with a hole has an area that is the area of the outer shell (a 10x10 square) minus the area of the hole (a 1x1 square). 220 221 Collections 222 ~~~~~~~~~~~ 223 224 There are four collection types, which group multiple simple geometries into sets. 225 226 * **MultiPoint**, a collection of points 227 * **MultiLineString**, a collection of linestrings 228 * **MultiPolygon**, a collection of polygons 229 * **GeometryCollection**, a heterogeneous collection of any geometry (including other collections) 230 231 Collections are another concept that shows up in GIS software more than in generic graphics software. They are useful for directly modeling real world objects as spatial objects. For example, how to model a lot that is split by a right-of-way? As a **MultiPolygon**, with a part on either side of the right-of-way. 233 232 234 233 .. image:: ./screenshots/collection2.png 235 234 236 Notre collection exemple contient un polygone et un point:235 Our example collection contains a polygon and a point: 237 236 238 237 .. code-block:: sql … … 248 247 .. image:: ./screenshots/collection.png 249 248 250 Certaines des fonctions spatiales spécifiques à la manipulation des collections sont : 251 252 * :command:`ST_NumGeometries(geometry)` retourne le nombre de composantes d'une collection 253 * :command:`ST_GeometryN(geometry,n)` retourne une composante spécifique 254 * :command:`ST_Area(geometry)` retourne l'aire totale des composantes de types polygones 255 * :command:`ST_Length(geometry)` retourne la longueur totale des composantes de types lignes 256 257 Entré / Sortie des géométries 258 ----------------------------- 259 260 Dans la base de données, les géométries sont stockées dans un format utilisé uniquement par le programme PostGIS. Afin que des programmes externes puissent insérer et récupérer les données utiles, elles ont besoin d'être converties dans un format compris par l'application. Heureusement, PostGIS supporte un grand nombre de formats en entrée et en sortie : 261 262 * Format texte bien connu (Well-known text :term:`WKT`) 263 264 * :command:`ST_GeomFromText(text)` retourne une ``geometry`` 265 * :command:`ST_AsText(geometry)` retourne le ``texte`` 266 * :command:`ST_AsEWKT(geometry)` retourne le ``texte`` 267 268 * Format binaire bien connu (Well-known binary :term:`WKB`) 269 270 * :command:`ST_GeomFromWKB(bytea)` retourne ``geometry`` 271 * :command:`ST_AsBinary(geometry)` retourne ``bytea`` 272 * :command:`ST_AsEWKB(geometry)` retourne ``bytea`` 249 Some of the specific spatial functions for working with collections are: 250 251 * :command:`ST_NumGeometries(geometry)` returns the number of parts in the collection 252 * :command:`ST_GeometryN(geometry,n)` returns the specified part 253 * :command:`ST_Area(geometry)` returns the total area of all polygonal parts 254 * :command:`ST_Length(geometry)` returns the total length of all linear parts 255 256 257 258 Geometry Input and Output 259 ------------------------- 260 261 Within the database, geometries are stored on disk in a format only used by the PostGIS program. In order for external programs to insert and retrieve useful geometries, they need to be converted into a format that other applications can understand. Fortunately, PostGIS supports emitting and consuming geometries in a large number of formats: 262 263 * Well-known text (:term:`WKT`) 264 265 * :command:`ST_GeomFromText(text)` returns ``geometry`` 266 * :command:`ST_AsText(geometry)` returns ``text`` 267 * :command:`ST_AsEWKT(geometry)` returns ``text`` 268 269 * Well-known binary (:term:`WKB`) 270 271 * :command:`ST_GeomFromWKB(bytea)` returns ``geometry`` 272 * :command:`ST_AsBinary(geometry)` returns ``bytea`` 273 * :command:`ST_AsEWKB(geometry)` returns ``bytea`` 273 274 274 275 * Geographic Mark-up Language (:term:`GML`) 275 276 276 * :command:`ST_GeomFromGML(text)` ret ourne``geometry``277 * :command:`ST_AsGML(geometry)` ret ourne``text``277 * :command:`ST_GeomFromGML(text)` returns ``geometry`` 278 * :command:`ST_AsGML(geometry)` returns ``text`` 278 279 279 280 * Keyhole Mark-up Language (:term:`KML`) 280 281 281 * :command:`ST_GeomFromKML(text)` ret ourne``geometry``282 * :command:`ST_AsKML(geometry)` ret ourne``text``282 * :command:`ST_GeomFromKML(text)` returns ``geometry`` 283 * :command:`ST_AsKML(geometry)` returns ``text`` 283 284 284 285 * :term:`GeoJSON` 285 286 286 * :command:`ST_AsGeoJSON(geometry)` ret ourne``text``287 * :command:`ST_AsGeoJSON(geometry)` returns ``text`` 287 288 288 289 * Scalable Vector Graphics (:term:`SVG`) 289 290 290 * :command:`ST_AsSVG(geometry)` ret ourne``text``291 292 La requête SQL suivante montre un exemple de représentation en :term:`WKB` (l'appel à :command:`encode()` est requis pour convertir le format binaire en ASCII pour l'afficher):291 * :command:`ST_AsSVG(geometry)` returns ``text`` 292 293 The following SQL query shows an example of :term:`WKB` representation (the call to :command:`encode()` is required to convert the binary output into an ASCII form for printing): 293 294 294 295 .. code-block:: sql … … 300 301 .. image:: ./geometries/represent-04.png 301 302 302 Dans le reste de ces travaux pratiques, nous utiliserons principalement le format WKT pour que vous puissiez lire et comprendre les géométries que nous voyons. Néanmoins, pour la plupart des traitement actuels, comme la visualisation des données dans une application SIG, le transfert de données à des services web, ou l'exécution distante de traitements, le format WKB est un format de choix. 303 304 Puisque le WKT et le WKB sont définit dans la spécification :term:`SFSQL`, elles ne prennent pas en compte les géométries à 3 ou 4 dimensions. C'est pour cette raison que PostGIS définit les formats Extended Well Known Text (EWKT) et Extended Well Known Binary (EWKB). Cela permet de gérer de façon similaire aux formats WKT et WKB les dimensions ajoutées.305 306 Voici un exemple de ligne 3D au format WKT:303 For the purposes of this workshop we will continue to use WKT to ensure you can read and understand the geometries we're viewing. However, most actual processes, such as viewing data in a GIS application, transferring data to a web service, or processing data remotely, WKB is the format of choice. 304 305 Since WKT and WKB were defined in the :term:`SFSQL` specification, they do not handle 3- or 4-dimensional geometries. For these cases PostGIS has defined the Extended Well Known Text (EWKT) and Extended Well Known Binary (EWKB) formats. These provide the same formatting capabilities of WKT and WKB with the added dimensionality. 306 307 Here is an example of a 3D linestring in WKT: 307 308 308 309 .. code-block:: sql … … 319 320 .. image:: ./geometries/represent-06.png 320 321 321 En plus de pouvoir générer les différents formats en sortie (WKT, WKB, GML, KML, JSON, SVG), PostGIS permet aussi de lire 4 de ces formats (WKT, WKB, GML, KML). La plupart des applications utilisent des fonctions créant des géométries à l'aide du format WKT ou WKB, mais les autres marchent aussi. Voici un exemple qui lit du GML et retourne du JSON:322 In addition to emitters for the various forms (WKT, WKB, GML, KML, JSON, SVG), PostGIS also has consumers for four (WKT, WKB, GML, KML). Most applications use the WKT or WKB geometry creation functions, but the others work too. Here's an example that consumes GML and output JSON: 322 323 323 324 .. code-block:: sql … … 327 328 .. image:: ./geometries/represent-07.png 328 329 329 Liste des fonctions 330 ------------------- 331 332 `Populate_Geometry_Columns <http://postgis.org/docs/Populate_Geometry_Columns.html>`_: s'assure que les colonnes géométriques on les contraintes spatiales appropriées et qu'elles sont présentes dans la table geometry_columns. 333 334 `ST_Area <http://postgis.org/docs/ST_Area.html>`_: retourne l'aire de la surface si c'est un polygon ou un multi-polygone. Pour le type "geometry" l'aire est dans l'unité du SRID. Pour les "geography" l'aire est en mÚtres carrés. 335 336 `ST_AsText <http://postgis.org/docs/ST_AsText.html>`_: retourne la représentation de la geometry/geography au format Well-Known Text (WKT) sans metadonnée correspondant au SRID. 337 338 `ST_AsBinary <http://postgis.org/docs/ST_AsBinary.html>`_: retourne la représentation de la geometry/geography au format Well-Known Binary (WKB) sans metadonnée correspondant u SRID. 339 340 `ST_EndPoint <http://postgis.org/docs/ST_EndPoint.html>`_: retourne le dernier point d'une ligne. 341 342 `ST_AsEWKB <http://postgis.org/docs/ST_AsEWKB.html>`_: retourne la représentation de la geometrie au format Well-Known Binary (WKB) avec la métadonnée SRID. 343 344 `ST_AsEWKT <http://postgis.org/docs/ST_AsEWKT.html>`_: retourne la représentation de la geometrie au format Well-Known Text (WKT) avec la métadonnée SRID. 345 346 `ST_AsGeoJSON <http://postgis.org/docs/ST_AsGeoJSON.html>`_: retourne la géométrie au format GeoJSON. 347 348 `ST_AsGML <http://postgis.org/docs/ST_AsGML.html>`_: retourne la géométrie au format GML version 2 ou 3. 349 350 `ST_AsKML <http://postgis.org/docs/ST_AsKML.html>`_: retourne la géométrie au format KML. Nombreuses variantes. Par défaut : version=2 et precision=15. 351 352 `ST_AsSVG <http://postgis.org/docs/ST_AsSVG.html>`_: retourne la géométrie au format SVG. 353 354 `ST_ExteriorRing <http://postgis.org/docs/ST_ExteriorRing.html>`_: retourne une ligne représentant le contour extérieur du polygone. Retourne NULL si la géométrie n'est pas un polygone. Ne fonctionne pas avec les multi-polygone. 355 356 `ST_GeometryN <http://postgis.org/docs/ST_GeometryN.html>`_: retourne niÚme composante si la géométrie est du type GEOMETRYCOLLECTION, MULTIPOINT, MULTILINESTRING, MULTICURVE ou MULTIPOLYGON. Sinon, retourne NULL. 357 358 `ST_GeomFromGML <http://postgis.org/docs/ST_GeomFromGML.html>`_: prend en entrée une représentation GML de la géométrie et retourne un object PostGIS de type geometry. 359 360 `ST_GeomFromKML <http://postgis.org/docs/ST_GeomFromKML.html>`_: prend en entrée une représentation KML de la géométrie et retourne un object PostGIS de type geometry. 361 362 `ST_GeomFromText <http://postgis.org/docs/ST_GeomFromText.html>`_: retourne une valeur de type ST_Geometry à partir d'une représentation au format Well-Known Text (WKT). 363 364 `ST_GeomFromWKB <http://postgis.org/docs/ST_GeomFromWKB.html>`_: retourne une valeur de type ST_Geometry à partir d'une représenattion au format Well-Known Binary (WKB). 365 366 `ST_GeometryType <http://postgis.org/docs/ST_GeometryType.html>`_: retourne le type de géométrie de la valeur de type ST_Geometry. 367 368 `ST_InteriorRingN <http://postgis.org/docs/ST_InteriorRingN.html>`_: retourne le niÚme contour intérieur d'un polygone. Retourne NULL si la géométrie n'est pas un polygone ou si N est hors des limites. 369 370 `ST_Length <http://postgis.org/docs/ST_Length.html>`_: retourne la longueur en 2-dimensions si c'est une ligne ou une multi-lignes. Les objets de type geometry sont dans l'unité du systÚme de références spatiales et les objet de type geography sont en metres (sphéroïde par défaut). 371 372 `ST_NDims <http://postgis.org/docs/ST_NDims.html>`_: retourne le nombre de dimensions d'une géométrie. Les valeurs possibles sont : 2,3 ou 4. 373 374 `ST_NPoints <http://postgis.org/docs/ST_NPoints.html>`_: retourne le nombre de points dans une géométrie. 375 376 `ST_NRings <http://postgis.org/docs/ST_NRings.html>`_: si la géométrie est un polygone ou un multi-polygone, retourne le nombre de contours. 377 378 `ST_NumGeometries <http://postgis.org/docs/ST_NumGeometries.html>`_: si la géométrie est du type GEOMETRYCOLLECTION (ou MULTI*) retourne le nombre de géométries, sinon retourne NULL. 379 380 `ST_Perimeter <http://postgis.org/docs/ST_Perimeter.html>`_: retourne la longueur du contours extérieur d'une valeur de type ST_Surface ou ST_MultiSurface (polygone, multi-polygone). 381 382 `ST_SRID <http://postgis.org/docs/ST_SRID.html>`_: retourne l'identifiant du systÚme de référence spatiale définit dans la table spatial_ref_sys d'un objet de type ST_Geometry. 383 384 `ST_StartPoint <http://postgis.org/docs/ST_StartPoint.html>`_: retourne le premier point d'une ligne. 385 386 `ST_X <http://postgis.org/docs/ST_X.html>`_: retourne la coordonnée X d'un point, ou NULL si non présent. L'argument passé doit être un point. 387 388 `ST_Y <http://postgis.org/docs/ST_Y.html>`_: retourne la coordonnée Y d'un point, ou NULL si non présent. L'argument passé doit être un point. 389 330 Function List 331 ------------- 332 333 `Populate_Geometry_Columns <http://postgis.org/docs/Populate_Geometry_Columns.html>`_: Ensures geometry columns have appropriate spatial constraints and exist in the geometry_columns table.. 334 335 `ST_Area <http://postgis.org/docs/ST_Area.html>`_: Returns the area of the surface if it is a polygon or multi-polygon. For "geometry" type area is in SRID units. For "geography" area is in square meters. 336 337 `ST_AsText <http://postgis.org/docs/ST_AsText.html>`_: Returns the Well-Known Text (WKT) representation of the geometry/geography without SRID metadata. 338 339 `ST_AsBinary <http://postgis.org/docs/ST_AsBinary.html>`_: Returns the Well-Known Binary (WKB) representation of the geometry/geography without SRID meta data. 340 341 `ST_EndPoint <http://postgis.org/docs/ST_EndPoint.html>`_: Returns the last point of a LINESTRING geometry as a POINT. 342 343 `ST_AsEWKB <http://postgis.org/docs/ST_AsEWKB.html>`_: Returns the Well-Known Binary (WKB) representation of the geometry with SRID meta data. 344 345 `ST_AsEWKT <http://postgis.org/docs/ST_AsEWKT.html>`_: Returns the Well-Known Text (WKT) representation of the geometry with SRID meta data. 346 347 `ST_AsGeoJSON <http://postgis.org/docs/ST_AsGeoJSON.html>`_: Returns the geometry as a GeoJSON element. 348 349 `ST_AsGML <http://postgis.org/docs/ST_AsGML.html>`_: Returns the geometry as a GML version 2 or 3 element. 350 351 `ST_AsKML <http://postgis.org/docs/ST_AsKML.html>`_: Returns the geometry as a KML element. Several variants. Default version=2, default precision=15. 352 353 `ST_AsSVG <http://postgis.org/docs/ST_AsSVG.html>`_: Returns a Geometry in SVG path data given a geometry or geography object. 354 355 `ST_ExteriorRing <http://postgis.org/docs/ST_ExteriorRing.html>`_: Returns a line string representing the exterior ring of the POLYGON geometry. Return NULL if the geometry is not a polygon. Will not work with MULTIPOLYGON 356 357 `ST_GeometryN <http://postgis.org/docs/ST_GeometryN.html>`_: Returns the 1-based Nth geometry if the geometry is a GEOMETRYCOLLECTION, MULTIPOINT, MULTILINESTRING, MULTICURVE or MULTIPOLYGON. Otherwise, return NULL. 358 359 `ST_GeomFromGML <http://postgis.org/docs/ST_GeomFromGML.html>`_: Takes as input GML representation of geometry and outputs a PostGIS geometry object. 360 361 `ST_GeomFromKML <http://postgis.org/docs/ST_GeomFromKML.html>`_: Takes as input KML representation of geometry and outputs a PostGIS geometry object 362 363 `ST_GeomFromText <http://postgis.org/docs/ST_GeomFromText.html>`_: Returns a specified ST_Geometry value from Well-Known Text representation (WKT). 364 365 `ST_GeomFromWKB <http://postgis.org/docs/ST_GeomFromWKB.html>`_: Creates a geometry instance from a Well-Known Binary geometry representation (WKB) and optional SRID. 366 367 `ST_GeometryType <http://postgis.org/docs/ST_GeometryType.html>`_: Returns the geometry type of the ST_Geometry value. 368 369 `ST_InteriorRingN <http://postgis.org/docs/ST_InteriorRingN.html>`_: Returns the Nth interior linestring ring of the polygon geometry. Return NULL if the geometry is not a polygon or the given N is out of range. 370 371 `ST_Length <http://postgis.org/docs/ST_Length.html>`_: Returns the 2d length of the geometry if it is a linestring or multilinestring. geometry are in units of spatial reference and geography are in meters (default spheroid) 372 373 `ST_NDims <http://postgis.org/docs/ST_NDims.html>`_: Returns coordinate dimension of the geometry as a small int. Values are: 2,3 or 4. 374 375 `ST_NPoints <http://postgis.org/docs/ST_NPoints.html>`_: Returns the number of points (vertexes) in a geometry. 376 377 `ST_NRings <http://postgis.org/docs/ST_NRings.html>`_: If the geometry is a polygon or multi-polygon returns the number of rings. 378 379 `ST_NumGeometries <http://postgis.org/docs/ST_NumGeometries.html>`_: If geometry is a GEOMETRYCOLLECTION (or MULTI*) returns the number of geometries, otherwise return NULL. 380 381 `ST_Perimeter <http://postgis.org/docs/ST_Perimeter.html>`_: Returns the length measurement of the boundary of an ST_Surface or ST_MultiSurface value. (Polygon, Multipolygon) 382 383 `ST_SRID <http://postgis.org/docs/ST_SRID.html>`_: Returns the spatial reference identifier for the ST_Geometry as defined in spatial_ref_sys table. 384 385 `ST_StartPoint <http://postgis.org/docs/ST_StartPoint.html>`_: Returns the first point of a LINESTRING geometry as a POINT. 386 387 `ST_X <http://postgis.org/docs/ST_X.html>`_: Returns the X coordinate of the point, or NULL if not available. Input must be a point. 388 389 `ST_Y <http://postgis.org/docs/ST_Y.html>`_: Returns the Y coordinate of the point, or NULL if not available. Input must be a point. 390 391 -
/trunk/workshop-foss4g/indexing.rst
r61 r1 1 1 .. _indexing: 2 2 3 Partie 14 : L'indexation spatiale 4 ============================ =====3 Section 14: Spatial Indexing 4 ============================ 5 5 6 R apellez-vous que l'indexation spatiale est l'une des trois fonctionnalités clés d'une base de données spatiales. Les indexes permettent l'utilisation de grandes quantités de données dans une base. Sans l'indexation, chaque recherche d'entité nécessitera d'accéder séquentiellement à tout les enregistrements de la base de données. L'indexation accélÚres les recherche en organisant les données dans des arbres de recherche qui peuvent être parcouru efficacement pour retrouver une entité particuliÚre.6 Recall that spatial index is one of the three key features of a spatial database. Indexes are what make using a spatial database for large data sets possible. Without indexing, any search for a feature would require a âsequential scanâ of every record in the database. Indexing speeds up searching by organizing the data into a search tree which can be quickly traversed to find a particular record. 7 7 8 L'indexation spatiale l'un des plus grands atouts de PostGIS. Dans les exemples précédents, nous avons construit nos jointures spatiales en comparant la totalité des tables. Ceci peut parfois s'averrer trÚs coûteux : Réaliser la jointure de deux tables de 10000 enregistrements sans indexation nécessitera de comparer 100000000 valeurs, les comparaisons requises ne seront plus que 20000 avec l'indexation.8 Spatial indices are one of the greatest assets of PostGIS. In the previous example building spatial joins requires comparing whole tables with each other. This can get very costly: joining two tables of 10,000 records each without indexes would require 100,000,000 comparisons; with indexes the cost could be as low as 20,000 comparisons. 9 9 10 Lorsque nous avons chargé la table ``nyc_census_blocks``, l'outils pgShapeLoader crée automatiquement un indexe spatial appelé ``nyc_census_blocks_the_geom_gist``. 10 When we loaded the ``nyc_census_blocks`` table, the pgShapeLoader automatically created a spatial index called ``nyc_census_blocks_the_geom_gist`` 11 11 12 Pour démontrer combien il est important d'indexer ses données pour la performance des requêtes, essayons de requêter notre table ``nyc_census_blocks`` **sans** utiliser notre indexe. 12 To demonstrate how important indexes are for performance, let's search ``nyc_census_blocks`` **without** our spatial index. 13 13 14 La premiÚre étape consiste à supprimer l'index.14 Our first step is to remove the index. 15 15 16 16 .. code-block:: sql … … 20 20 .. note:: 21 21 22 La commande ``DROP INDEX`` supprime un index existant de la base de données. Pour de plus amples informations à ce sujet, consultez la `documentation officielle de PostgreSQL <http://docs.postgresql.fr/9.1/sql-dropindex.html>`_.22 The ``DROP INDEX`` statement drops an existing index from the database system. For more information, see the PostgreSQL `documentation <http://www.postgresql.org/docs/7.4/interactive/sql-dropindex.html>`_. 23 23 24 Maintenant, regardons le temps d'exécution dans le coin en bas à droite de l'interface de requêtage de pgAdmin, puis lançons la commande suivante. Notre requête recherche les blocs de la rue Broad.24 Now, watch the "Timing" meter at the lower right-hand corner of the pgAdmin query window and run the following. Our query searches through every single census block in order to identify the Broad Street entry. 25 25 26 26 .. code-block:: sql … … 38 38 360610007003006 39 39 40 La table ``nyc_census_blocks`` est trÚs petite (seulement quelque millier d'enregistrements) donc même sans l'index, la requête prends **55 ms** sur l'ordinateur de test.40 The ``nyc_census_blocks`` table is very small (only a few thousand records) so even without an index, the query only takes **55 ms** on my test computer. 41 41 42 Maintenant remettons en place l'index et lançons de nouveau la requête. 42 Now add the spatial index back in and run the query again. 43 43 44 44 .. code-block:: sql … … 46 46 CREATE INDEX nyc_census_blocks_the_geom_gist ON nyc_census_blocks USING GIST (the_geom); 47 47 48 .. note:: l'utilisation de la clause ``USING GIST`` spécifie à PostgreSQL de créer une structure (GIST) pour cet index. Si vous recevez un message d'erreur ressemblant à ``ERROR: index row requires 11340 bytes, maximum size is 8191`` lors de la création, cela signifie sans doute que vous avez omis la clause ``USING GIST``.48 .. note:: The ``USING GIST`` clause tells PostgreSQL to use the generic index structure (GIST) when building the index. If you receive an error that looks like ``ERROR: index row requires 11340 bytes, maximum size is 8191`` when creating your index, you have likely neglected to add the ``USING GIST`` clause. 49 49 50 Sur l'rdinateur de test le temps d'exécution se réduit à **9 ms**. Plus votre table est grande, plus la différence de temps d'exécution pour une requête utilisant les indexes augmentera.50 On my test computer the time drops to **9 ms**. The larger your table, the larger the relative speed improvement of an indexed query will be. 51 51 52 Comment les indexes spatiaux fonctionnent 53 ------------------------ -----------------52 How Spatial Indexes Work 53 ------------------------ 54 54 55 Les indexes des base de données standards créent des arbres hierarchiques basés sur les valeurs des colonnes à indexer. Les indexes spatiaux sont un peu différents - ils ne sont pas capables d'indexer des entités géométriques elles-même mais indexe leur étendues.55 Standard database indexes create a hierarchical tree based on the values of the column being indexed. Spatial indexes are a little different -- they are unable to index the geometric features themselves and instead index the bounding boxes of the features. 56 56 57 57 .. image:: ./indexing/bbox.png 58 58 59 Dans la figure ci-dessus, le nombre de lignes qui intersectent l'étoile jaune est *unique*, la ligne rouge. Mais l'étendue des entités qui intersectent la boîte jaune sont *deux*, la boîte rouge et la boîte bleue. 59 In the figure above, the number of lines that intersect the yellow star is **one**, the red line. But the bounding boxes of features that intersect the yellow box is **two**, the red and blue ones. 60 60 61 La maniÚre dont les bases de données répondent de maniÚre efficace à la question "Quelles lignes intersectent l'étoile jaune ?" correspond premiÚrement à répondre à la question "Quelle étendue intersecte l'étendue jaune" en utilisant les indexes (ce qui est trÚs rapide) puis à calculer le résultat exact de la question "Quelles lignes intersectent l'étoile jaune ?" **seulement en utilisant les entités retourné par le premier test**. 61 The way the database efficiently answers the question "what lines intersect the yellow star" is to first answer the question "what boxes intersect the yellow box" using the index (which is very fast) and then do an exact calculation of "what lines intersect the yellow star" **only for those features returned by the first test**. 62 62 63 Pour de grandes tables, il y a un systÚme en "deux étapes" d'évaluation en utilisant dans un premier temps l'approximation à l'aide d'indexes, puis en réalisant le test exact sur une quantité bien moins importante de données ce qui réduit drastiquement le temps de calcul nécessaire à cette deuxiÚme étape.63 For a large table, this "two pass" system of evaluating the approximate index first, then carrying out an exact test can radically reduce the amount of calculations necessary to answer a query. 64 64 65 PotGIS et Oracle Spatial partage la même notion d'index structuré sous la forme "d'arbres R" [#RTree]_. Les arbres R classent les données sous forme de rectangles, de sous-rectangles etc. Cette structure d'index gÚre automatiquement la densité et la taille des objets.65 Both PostGIS and Oracle Spatial share the same "R-Tree" [#RTree]_ spatial index structure. R-Trees break up data into rectangles, and sub-rectangles, and sub-sub rectangles, etc. It is a self-tuning index structure that automatically handles variable data density and object size. 66 66 67 67 .. image:: ./indexing/index-01.png 68 68 69 Requête avec seulement des indexes70 ------------------ ----------------69 Index-Only Queries 70 ------------------ 71 71 72 La plupart des fonctions utilisées par PostGIS (:command:`ST_Contains`, :command:`ST_Intersects`, :command:`ST_DWithin`, etc) prennent en compte les indexes automatiquement. Mais certaines fonctions (comme par exemple : :command:`ST_Relate`) ne les utilisent pas.72 Most of the commonly used functions in PostGIS (:command:`ST_Contains`, :command:`ST_Intersects`, :command:`ST_DWithin`, etc) include an index filter automatically. But some functions (e.g., :command:`ST_Relate`) do not include and index filter. 73 73 74 Pour utiliser une recherche par étendue utilisant les indexes (et pas de filtres), vous pouvez utiliser l'opérateur :command:`&&`. Pour les géométries, l'opérateur :command:`&&` signifie "l'étendue recouvre ou touche" de la même maniÚre que l'opérateur :command:`=` sur des entiers signifie que les valeurs sont égales.74 To do a bounding-box search using the index (and no filtering), make use of the :command:`&&` operator. For geometries, the :command:`&&` operator means "bounding boxes overlap or touch" in the same way that for number the :command:`=` operator means "values are the same". 75 75 76 Essayons de comparer une requête avec seulement un indexe pour la population du quartier 'West Village'. En utilisant la commande :command:`&&` notre requête ressemble à cela:76 Let's compare an index-only query for the population of the 'West Village' to a more exact query. Using :command:`&&` our index-only query looks like the following: 77 77 78 78 .. code-block:: sql … … 88 88 50325 89 89 90 Maintenant essayons la même requête en utilisant la fonction plus précise :command:`ST_Intersects`.90 Now let's do the same query using the more exact :command:`ST_Intersects` function. 91 91 92 92 .. code-block:: sql … … 102 102 27141 103 103 104 Un plus faible nombre de résultats ! La premiÚre requête nous renvoit tout les blocs qui intersectent l'étendue du quartier, la seconde nous renvoit seulement les blocs qui intersectent le quartier lui-même.104 A much lower answer! The first query summed up every block that intersected the neighborhood's bounding box; the second query only summed up those blocks that intersected the neighborhood itself. 105 105 106 Analy se106 Analyzing 107 107 --------- 108 108 109 Le plannificateur de requête de PostgreSQL choisit intelligemment d'utiliser ou non les indexes pour réaliser une requête. Il n'est pas toujours plus rapide d'utiliser un index pour réaliser une recherche : si la recherche doit renvoyer l'ensemble des enregistrements d'une table, parcourir l'index pour récupérer chaque valeur sera plus lent que de parcourir linéairement l'ensemble de la table.109 The PostgreSQL query planner intelligently chooses when to use or not to use indexes to evaluate a query. Counter-intuitively, it is not always faster to do an index search: if the search is going to return every record in the table, traversing the index tree to get each record will actually be slower than just linearly reading the whole table from the start. 110 110 111 Afin de savoir dans quelle situation il est nécessaire d'utiliser les idexes (lire une petite partie de la table plutÃŽt qu'une grande partie), PostgreSQL conserve des statistiques relatives à la distribution des données dans chaque colonne indexée. Par défaut, PostgreSQL rassemble les statistiques sur une base réguliÚre. Nénamoins, si vous changez dramatiquement le contenu de vos tables dans une période courte, les statisuqes ne seront alors plus à jour.111 In order to figure out what situation it is dealing with (reading a small part of the table versus reading a large portion of the table), PostgreSQL keeps statistics about the distribution of data in each indexed table column. By default, PostgreSQL gathers statistics on a regular basis. However, if you dramatically change the make-up of your table within a short period of time, the statistics will not be up-to-date. 112 112 113 Pour vous assurez que les statistiques correspondent bien au contenu de la table actuelle, il est courrant d'utiliser la commande ``ANALYZE`` aprÚs un grand nombre de modifications ou de suppression de vos données. Cela force le systÚme de gestion des statistiques à récupérer l'ensemble des données des colonnes indexées.113 To ensure your statistics match your table contents, it is wise the to run the ``ANALYZE`` command after bulk data loads and deletes in your tables. This force the statistics system to gather data for all your indexed columns. 114 114 115 La commande ``ANALYZE`` demande à PostgreSQL de parcourir la table et de mettre à jour les statistiques utilisées par le plannificateur de requêtes (la plannification des requêtes sera traité utiltérieurement). 115 The ``ANALYZE`` command asks PostgreSQL to traverse the table and update its internal statistics used for query plan estimation (query plan analysis will be discussed later). 116 116 117 117 .. code-block:: sql … … 119 119 ANALYZE nyc_census_blocks; 120 120 121 Néttoyage 121 Vacuuming 122 122 --------- 123 123 124 I l est souvent stressant de constater que la simple création d'un indexe n'est pas suffisant pour que PostgreSQL l'utilise efficacement. Le nettoyage doit être réalisé aprÚs qu'un indexe soit créé ou aprÚs un grand nombre de requêtes UDATE, INSERT ou DELETE est été réalisé sur une table. La commande ``VACUUM`` demande à PostgreSQL de récupérer chaque espace non utilisé dans les pages de la table qui sont laissé en l'état lors des requêtes UPDATE ou DELETE à cause du modÚle d'estapillage multi-versions.124 It's worth stressing that just creating an index is not enough to allow PostgreSQL to use it effectively. VACUUMing must be performed whenever a new index is created or after a large number of UPDATEs, INSERTs or DELETEs are issued against a table. The ``VACUUM`` command asks PostgreSQL to reclaim any unused space in the table pages left by updates or deletes to records. 125 125 126 Le nettoyage des données est tellement important pour une utilisation efficace du serveur de base de données PostgreSQL qu'il existe maintenant une option "autovacuum".126 Vacuuming is so critical for the efficient running of the database that PostgreSQL provides an "autovacuum" option. 127 127 128 Activée par défaut, le processus autovacuum nettoie (récupÚre l'espace libre) et analyse (met à jour les statistiques) vos tables suivant un interval donné déterminé par l'activité des bases de données. Bien que cela fonctionne avec les bases de données hautement transactionnelles, il n'est pas supportable de devoir attendre que le processus autovacuum se lance lors de la mise à jour ou la suppression massive de données. Dans ce cas, il faut lancer la commande ``VACUUM`` manuellement.128 Enabled by default, autovacuum both vacuums (recovers space) and analyzes (updates statistics) on your tables at sensible intervals determined by the level of activity. While this is essential for highly transactional databases, it is not advisable to wait for an autovacuum run after adding indices or bulk-loading data. If a large batch update is performed, you should manually run ``VACUUM``. 129 129 130 Le nettoyage et l'analyse de la base de données peut être réalisé séparément si nécessaire. Utiliser la commande ``VACUUM`` ne mettra pas à jour les statistiques alors que lancer la commande ``ANALYZE`` ne récupÚrera pas l'espace libre des lignes d'une table. Chacune de ces commandes peut être lancée sur l'intégralité de la base de données, sur une table ou sur une seule colonne.130 Vacuuming and analyzing the database can be performed separately as needed. Issuing ``VACUUM`` command will not update the database statistics; likewise issuing an ``ANALYZE`` command will not recover unused table rows. Both commands can be run against the entire database, a single table, or a single column. 131 131 132 132 .. code-block:: sql … … 134 134 VACUUM ANALYZE nyc_census_blocks; 135 135 136 Liste des fonctions 137 ------------- ------136 Function List 137 ------------- 138 138 139 `geometry_a && geometry_b <http://postgis.org/docs/ST_Geometry_Overlap.html>`_: retourne TRUE si l'étendue de A cheuvauche celle de B.139 `geometry_a && geometry_b <http://postgis.org/docs/ST_Geometry_Overlap.html>`_: Returns TRUE if A's bounding box overlaps B's. 140 140 141 `geometry_a = geometry_b <http://postgis.org/docs/ST_Geometry_EQ.html>`_: retourne TRUE si l'étendue de A est la même que celle de B.141 `geometry_a = geometry_b <http://postgis.org/docs/ST_Geometry_EQ.html>`_: Returns TRUE if A's bounding box is the same as B's. 142 142 143 `ST_Intersects(geometry_a, geometry_b) <http://postgis.org/docs/ST_Intersects.html>`_: retourne TRUE si l'objet Geometrie/Geography "intersecte spatiallement" - (ont une partie en commun) et FALSE sinon (elles sont dijointes).143 `ST_Intersects(geometry_a, geometry_b) <http://postgis.org/docs/ST_Intersects.html>`_: Returns TRUE if the Geometries/Geography "spatially intersect" - (share any portion of space) and FALSE if they don't (they are Disjoint). 144 144 145 145 .. rubric:: Footnotes -
/trunk/workshop-foss4g/conf.py
r61 r1 33 33 34 34 # General substitutions. 35 project = u'Introduction ÃPostGIS'35 project = u'Introduction to PostGIS' 36 36 copyright = u'2010, Paul Ramsey, OpenGeo | Mark Leslie, LISAsoft' 37 37 -
/trunk/workshop-foss4g/loading_data.rst
r61 r1 1 1 .. _loading_data: 2 2 3 Partie 4 : Charger des données spatiales 4 =============================== ==========3 Section 4: Loading spatial data 4 =============================== 5 5 6 Support é par une grande variété de librairies et d'applications, PostGIS fournit de nombreux outils pour charger des données. Cette partie traitera uniquement du chargement basique de données, c'est à dire le chargement de fichiers Shapefile (.shp) en utilisant l'outil dédié de PostGIS.6 Supported by a wide variety of libraries and applications, PostGIS provides many options for loading data. This section will focus on the basics -- loading shapefiles using the PostGIS shapefile loading tool. 7 7 8 #. PremiÚrement, retournez sur le Dashboard et cliquez sur le lien **Import shapefiles** de la section PostGIS. L'interface d'import de données Shapefile pgShapeLoader se lance.8 #. First, return to the Dashboard, and click on the **Import shapefiles** link in the PostGIS section. The GUI shapefile importer pgShapeLoader will launch. 9 9 10 10 .. image:: ./screenshots/pgshapeloader_01.png 11 11 12 #. Ensuite, ouvrez le navigateur de fichier *Shape File* puis dans le répertoire file:`\\postgisintro\\data` sélectionnez le fichier :file:`nyc_census_blocks.shp`.12 #. Next, open the *Shape File* browser and navigate to the data directory, file:`\\postgisintro\\data`. Select the :file:`nyc_census_blocks.shp` file. 13 13 14 #. Saisissez les détails de la section *connexion PostGIS* et cliquez sur le bouton **Test Connection...**.14 #. Fill in the details for the *PostGIS Connection* section and click on the **Test Connection...** button. 15 15 16 16 .. list-table:: … … 25 25 - ``nyc`` 26 26 27 .. note:: 27 .. note:: 28 29 Setting the port number to **54321** is very important! The OpenGeo PostGIS runs on port 54321, not the default PostgreSQL port of 5432. 28 30 29 Affecter le numéro de port **54321** est trÚs important ! Le serveur PostGIS d'OpenGeo utilise ce port et non le port par défaut (5432). 30 31 #. Saisissez les détails de la section *Configuration*. 31 #. Fill in the details for the *Configuration* section. 32 32 33 33 .. list-table:: … … 42 42 - ``the_geom`` 43 43 44 #. Cli quez sur le bouton **Options** et sélectionnez "Load data using COPY rather than INSERT." Ce qui implique que le chargement des données sera plus rapide.44 #. Click the **Options** button and select "Load data using COPY rather than INSERT." This will make the data load process a little faster. 45 45 46 46 .. image:: ./screenshots/pgshapeloader_02.png 47 47 48 #. Pour finir, cliquez sur le bouton **Import** et regardez l'importation s'exécuter. Cela peut prendre plusieurs minutes pour charger, mais ce fichier est le plus gros que nous aurons à charger.48 #. Finally, click the **Import** button and watch the import process. It may take a few minutes to load, but this is the largest file in our test set. 49 49 50 #. Rep étez la méthode afin d'importer les autres données présentes dans le répertoire data. Hormis le nom du fichier et le nom de la table de sortie, les autres paramÚtres de pgShapeLoader devrait rester les mêmes:50 #. Repeat the import process for the remaining shapefiles in the data directory. Except for the input file and output table name, all the other fields in pgShapeLoader should remain the same: 51 51 52 52 * ``nyc_streets.shp`` 53 53 * ``nyc_neighborhoods.shp`` 54 54 * ``nyc_subway_stations.shp`` 55 56 #. Lorsque tous les fichiers sont chargés, cliquez sur le bouton "Refresh" de pgAdmin pour mettre à jour l'arbre affiché. Vous devriez voir vos quatre nouvellles tables affichées dans la section **Tables** de l'arbre.55 56 #. When all the files are loaded, click the "Refresh" button in pgAdmin to update the tree view. You should see your four tables show up in the **Tables** section of the tree. 57 57 58 58 .. image:: ./screenshots/refresh.png 59 60 61 Shapefiles? What's that? 62 ------------------------ 63 64 You may be asking yourself -- "What's this shapefile thing?" A "shapefile" commonly refers to a collection of files with ``.shp``, ``.shx``, ``.dbf``, and other extensions on a common prefix name (e.g., nyc_census_blocks). The actual shapefile relates specifically to files with the ``.shp`` extension. However, the ``.shp`` file alone is incomplete for distribution without the required supporting files. 65 66 Mandatory files: 67 68 * ``.shp`` â shape format; the feature geometry itself 69 * ``.shx`` â shape index format; a positional index of the feature geometry 70 * ``.dbf`` â attribute format; columnar attributes for each shape, in dBase III 71 72 Optional files include: 73 74 * ``.prj`` â projection format; the coordinate system and projection information, a plain text file describing the projection using well-known text format 75 76 In order to analyze a shapefile in PostGIS, you need to convert a shapefile into a series SQL commands. By running pgShapeLoader, a shapefile converts into a table that PostgreSQL can understand. 59 77 60 78 61 S hapefile ? Qu'est-ce que c'est?62 ----------------------------- ----79 SRID 26918? What's with that? 80 ----------------------------- 63 81 64 Il est possible que vous vous demandiez "Qu'est-ce que c'est ce shapefile ?" On utilise communément le terme "Shapefile" pour parler d'un ensemble de fichiers d'extension ``.shp``, ``.shx``, ``.dbf``, ou autre ayant un nom commun (ex: nyc_census_blocks). Le fichier Shapefile est en réalité le fichier d'extension ``.shp``, mais ce fichier seul n'est pas complet sans ses fichiers associés.82 Most of the import process is self-explanatory, but even experienced GIS professionals can trip over an **SRID**. 65 83 66 Fichiers obligatoires : 84 An "SRID" stands for "Spatial Reference IDentifier." It defines all the parameters of our data's geographic coordinate system and projection. An SRID is convenient because it packs all the information about a map projection (which can be quite complex) into a single number. 67 85 68 * ``.shp`` â les formes; les entités géographiques elle-mêmes 69 * ``.shx`` â l'index de formes; un index basé sur les positions des entités géographiques 70 * ``.dbf`` â les attributs; les données attributaires associées à chaque forme, au format dBase III 71 72 Les fichiers optionnels possibles: 73 74 * ``.prj`` â la projection; le systÚme de coordonnées et l'information de projection, un fichier texte décrivant la projection utilisant le format texte bien connu (WKT) 75 76 Afin d'utiliser un fichier Shapefile dans PostGIS, vous devez le convertir en une série de requêtes SQL. En utilisant pgShapeLoader, un Shapefile est converti en une table que PostgreSQL peut comprendre. 77 78 79 SRID 26918 ? Qu'est que c'est ? 80 ------------------------------- 81 82 La plupart des paramÚtres de l'importation de données sont explicites mais même les professionnels du SIG peuvent rencontrer des difficulté à propos du **SRID**. 83 84 "SRID" signifie "IDentifiant de Référence Spatiale". Il définit tous les paramÚtres de nos données, telles les coordonnées géographiques et la projection. Un SRID est pratique car il encapsule sous la forme d'un nombre toutes les informations à propos de la projection de la carte (ce qui peut être trÚs compliqué). 85 86 Vou pouvez consulter la définition de la projection de la carte en consultant la base de données en ligne suivante : 86 You can see the definition of our workshop map projection by looking it up either in an online database, 87 87 88 88 http://spatialreference.org/ref/epsg/26918/ 89 89 90 o u directement depuis PostGIS en interrogeant la table ``spatial_ref_sys``.90 or directly inside PostGIS with a query to the ``spatial_ref_sys`` table. 91 91 92 92 .. code-block:: sql 93 93 94 94 SELECT srtext FROM spatial_ref_sys WHERE srid = 26918; 95 96 .. note:: 95 97 96 .. note:: 97 La table ``spatial_ref_sys`` de PostGIS est une table standard OGC qui définit tous les systÚmes de référence spatiale connus par la base de données. Les données livrées avec PostGIS, contiennent 3000 systÚmes de référence spatiale et précisent les informations nécessaires à la transformation ou la reprojection. 98 99 Dans les deux cas, vous obtiendrez une représentation du systÚme de référence spatiale **26918** (affichée sur plusieurs lignes ici pour plus de clarté). 98 The PostGIS ``spatial_ref_sys`` table is an OGC-standard table that defines all the spatial reference systems known to the database. The data shipped with PostGIS, lists over 3000 known spatial reference systems and details needed to transform/re-project between them. 99 100 In both cases, you see a textual representation of the **26918** spatial reference system (pretty-printed here for clarity): 100 101 101 102 :: … … 120 121 AXIS["Northing",NORTH]] 121 122 122 Si vous ouvrez le fichier ``nyc_neighborhoods.prj`` du répertoire data, vous verrez la même définition. 123 If you open up the ``nyc_neighborhoods.prj`` file from the data directory, you'll see the same projection definition. 123 124 124 Un problÚme auquel se confronte la plupart des débutants en PostGIS est de savoir quel SRID il doit utiliser pour ses données. Tout ce qu'ils ont c'est un fichier ``.prj``. Mais comment un humain peut-il reconnaitre le numéro de SRID correct en lisant le contenu du fichier ``.prj``?125 A common problem for people getting started with PostGIS is figuring out what SRID number to use for their data. All they have is a ``.prj`` file. But how do humans translate a ``.prj`` file into the correct SRID number? 125 126 126 La réponse simple est d'utiliser un ordinateur. Copiez le contenu du fichier ``.prj`` dans le formulaire du site http://prj2epsg.org. Cela vous donnera le nombre (ou la liste de nombres) qui correspond le plus à votre définition de projection. Il n'y a pas de nombre pour *toutes* les projections de cartes existantes dans le monde, mais les plus courants sont disponibles dans la base de données de prj2epsg.127 The easy answer is to use a computer. Plug the contents of the ``.prj`` file into http://prj2epsg.org. This will give you the number (or a list of numbers) that most closely match your projection definition. There aren't numbers for *every* map projection in the world, but most common ones are contained within the prj2epsg database of standard numbers. 127 128 128 129 .. image:: ./screenshots/prj2epsg_01.png 129 130 130 Les données que vous recevez des agences locales de l'Etat - comme la ville de New York - utilisent la plupart du temps des projections locales notées "state plane" ou "UTM". Dans notre cas, la projection est "Universal Transverse Mercator (UTM) Zone 18 North" soit EPSG:26918. 131 Data you receive from local agencies -- such as New York City -- will usually be in a local projection noted by "state plane" or "UTM". Our projection is "Universal Transverse Mercator (UTM) Zone 18 North" or EPSG:26918. 131 132 132 133 133 Les choses à essayer : rendre spatiale une base de données existante134 ---------------------------------------------------- ----------------134 Things to Try: Spatially Enable an Existing Database 135 ---------------------------------------------------- 135 136 136 Vous avez déjà vu comment créer une base de données en utilisant le modÚle ``postgis_template`` depuis pgAdmin. Néanmoins, lorsque vous installé depuis les sources ou que vous ajoutez le module PostGIS à une base existante, il n'est pas toujours approprié de créer une nouvelle base de données en utilisant le modÚle PostGIS.137 You have already seen how to create a database using the ``postgis_template`` in pgAdmin. However when installing from source or adding PostGIS functionality to an existing database, it is not always appropriate to create a fresh database from the PostGIS template. 137 138 138 Votre tâche consiste dans cette section à créer une base de données et à ajouter les types et les fonctions PostGIS ensuite. Les script SQL nécessaires - :file:`postgis.sql` et :file:`spatial_ref_sys.sql` - se trouvent dans le répertoire :file:`contrib` de votre installation de PostgreSQL. Pour vous guider, vous pouvez consulter la documentation PostGIS expliquant comment installer PostGIS[#PostGIS_Install]_.139 Your task in this section is to create a database and add PostGIS types and functions after the fact. The SQL scripts needed -- :file:`postgis.sql` and :file:`spatial_ref_sys.sql` -- can be found in the :file:`contrib` directory of your PostgreSQL install. For guidance, refer to the PostGIS documentation on installing from source [#PostGIS_Install]_. 139 140 140 141 .. note:: 141 142 142 N'oubliez pas saisir le nom de l'utilisateur et le numéro de port lorsque vous créez une base de données en ligne de commande. 143 Remember to include your username and port number when creating a database from the command line. 144 145 Things to Try: View data using uDig 146 ----------------------------------- 143 147 144 Les choses à essayer : visualiser des données avec uDig 145 ------------------------------------------------------- 148 `uDig <http://udig.refractions.org>`_, (User-friendly Desktop Internet GIS), is a desktop GIS viewer/editor for quickly looking at data. You can view a number of data formats including flat shapefiles and a PostGIS database. Its graphical interface allows for easy exploration of your data, as well as simple testing and fast styling. 146 149 147 `uDig <http://udig.refractions.org>`_, (User-friendly Desktop Internet GIS) est un outil bureautique de visualisation/édition SIG permettant de visualiser rapidement ses données. Vous pouvez visualiser un grand nombre de formats différents dont les Shapefiles et les bases de données PostGIS. Son interface graphique vous permet d'explorer vos données facilement mais aussi de les tester et les styler rapidement.150 Use this software to connect your PostGIS database. The application is included in the ``software`` folder. 148 151 149 Utilisez cette application pour vous connecter à votre base de données PostGIS. L'application est contenue dans le répertoire ``software``. 152 .. rubric:: Footnotes 150 153 151 .. rubric:: Notes de bas de page154 .. [#PostGIS_Install] "Chapter 2.5. Installation" PostGIS Documentation. May 2010 <http://postgis.org/documentation/manual-1.5/ch02.html#id2786223> 152 155 153 .. [#PostGIS_Install] "Chapter 2.5. Installation" PostGIS Documentation. Mai 2010 <http://postgis.org/documentation/manual-1.5/ch02.html#id2786223>154 -
/trunk/workshop-foss4g/Makefile
r61 r1 3 3 4 4 # You can set these variables from the command line. 5 SPHINXOPTS = -Dlanguage=fr6 SPHINXBUILD = sphinx-build 5 SPHINXOPTS = 6 SPHINXBUILD = sphinx-build 7 7 PAPER = 8 8 -
/trunk/workshop-foss4g/index.rst
r61 r1 2 2 3 3 Introduction à PostGIS 4 ====================== 4 ======================= 5 5 6 Ten ez vous prêt6 Tennez vous prêt 7 7 --------------- 8 8 9 9 * Ce document utilise une archive contenant des applications et des données : http://s3.opengeo.org/postgisintro-2010-2.zip 10 * Télécharger l'archive et décompressez-l a dans le répertoire de votre choix.10 * Télécharger l'archive et décompressez-le dans le répetoire de votre choix. 11 11 12 12 Contenu de l'archive 13 ------------------ --13 ------------------ 14 14 15 15 Dans l'archive liée à ce document, vous trouverez: 16 16 17 **workshop/** 17 **workshop/** 18 18 un répertoire contenant ce document au format HTML 19 19 20 **software/** 20 **software/** 21 21 un répertoire contenant tout les logiciels que nous installerons 22 22 23 **data/** 23 **data/** 24 24 un répertoire contenant les fichier au format Shapefiles que nous utiliserons 25 25 26 L'ensemble des données présentes dans cette archive sont du domaine public et librement redistribuables. Toute les applications de l'archive sont des logiciels libres, et librement redistribuables. Le document est publié sous licence Creative Commons 27 "`share alike with attribution <http://creativecommons.org/licenses/by-sa/3.0/us/>`_", 28 et est librement redistribuable en respectant les termes de cette license. 26 L'ensemble des données présentes dans cette archive sont du domaine publique et 27 librement redistribuables. Toute les applications de l'archive sont des logiciels libres, et 28 librement redistribuables. The document est publié sous licence Creative Commons 29 "`share alike with attribution <http://creativecommons.org/licenses/by-sa/3.0/us/>`_", 30 et est librement redisctribuable en respectant les termes de cette license. 29 31 30 32 Table des matiÚres 31 ---------------- --33 ---------------- 32 34 33 35 .. toctree:: 34 36 :maxdepth: 1 35 37 36 welcome 38 welcome 37 39 introduction 38 40 installation … … 50 52 indexing 51 53 projection 52 projection_exercises 54 projection_exercises 53 55 geography 54 56 geometry_returning … … 62 64 63 65 64 L es liens à garder sous la main65 --------------------- ----------66 Links to have on hand 67 --------------------- 66 68 67 * PostGIS - http://postgis.org/ 69 * PostGIS - http://postgis.org/ 68 70 69 - Doc umentation- http://postgis.org/docs/71 - Docs - http://postgis.org/docs/ 70 72 71 * PostgreSQL - http://www.postgresl.org/ 73 * PostgreSQL - http://www.postgresl.org/ 72 74 73 - Téléchargement- http://www.postgresql.org/download/74 - Doc umentation- http://www.postgresql.org/docs/75 - Downloads - http://www.postgresql.org/download/ 76 - Docs - http://www.postgresql.org/docs/ 75 77 - JDBC Driver - http://jdbc.postgresql.org/ 76 78 - .Net Driver - http://npgsql.projects.postgresql.org/ … … 78 80 - C/C++ Driver - http://www.postgresql.org/docs/8.4/static/libpq.html 79 81 80 * PgAdmin III - http://www.pgadmin.org/ 82 * PgAdmin III - http://www.pgadmin.org/ 81 83 82 * Clients bureautiques Open Source84 * Open Source Desktop Clients 83 85 84 86 - uDig - http://udig.refractions.net/ -
/trunk/workshop-foss4g/joins_advanced.rst
r61 r1 1 1 .. _joins_advanced: 2 2 3 Partie 19 : Plus de jointures spatiales4 ============================== =========5 6 Dans la partie précédente nous avons vu les fonctions :command:`ST_Centroid(geometry)` et :command:`ST_Union([geometry])` ainsi que quelques exemples simples. Dans cette partie nous réaliseront des choses plus éllaborées.3 Section 19: More Spatial Joins 4 ============================== 5 6 In the last section we saw the :command:`ST_Centroid(geometry)` and :command:`ST_Union([geometry])` functions, and some simple examples. In this section we will do some more elaborate things with them. 7 7 8 8 .. _creatingtractstable: 9 9 10 Cr éation de la table de traçage des recensements11 ------------------------------ ------------------12 13 Dans le répertoire ``\data\`` des travaux pratiques, il y a un fichier qui contient des données attributaires, mais pas de géométries, ce fichier est nommé ``nyc_census_sociodata.sql``. La table contient des données sociaux-économiques interressantes à propos de New York : revenus financiers, éducation .... Il y a juste un problÚme, les données sont rassemblé en "trace de recensement" et nous n'avons pas de données spatiales associées ! 14 15 Dans cette partie nous allons 16 17 * Charger la table ``nyc_census_sociodata.sql``18 * Cr éer une table spatiale pour les traces de recensement19 * Join dre les données attributaires à nos données spatiales20 * Réaliser certaines analises sur nos nouvelles données21 22 Chargement du fichiernyc_census_sociodata.sql23 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~24 25 #. O uvrez la fenêtre de requêtage SQL depuisPgAdmin26 #. Select ionnez **File->Open** depuis le menu et naviguez jusqu'au fichier ``nyc_census_sociodata.sql``27 #. Cliquez sur le bouton "Run Query"28 #. Si vous cliquez sur le bouton "Refresh" depuis PgAdmin, la liste des table devrait contenir votre nouvelle table ``nyc_census_sociodata``29 30 Cr éation de la table traces de recensement31 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~32 33 Comme nous l'avons dans la partie précédente, nous pouvons construire des géométries de niveau suppérieur en utilisant nos blocks de base en utilisant une partie de la clef ``blkid``. Afin de calculer les traces de recensement, nous avons besoin de regrouper les blocks en uitlisant les 11 premiers caractÚres de la colonne ``blkid``. 10 Creating a Census Tracts Table 11 ------------------------------ 12 13 In the workshop ``\data\`` directory, is a file that includes attribute data, but no geometry, ``nyc_census_sociodata.sql``. The table includes interesting socioeconomic data about New York: commute times, incomes, and education attainment. There is just one problem. The data are summarized by "census tract" and we have no census tract spatial data! 14 15 In this section we will 16 17 * Load the ``nyc_census_sociodata.sql`` table 18 * Create a spatial table for census tracts 19 * Join the attribute data to the spatial data 20 * Carry out some analysis using our new data 21 22 Loading nyc_census_sociodata.sql 23 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 24 25 #. Open the SQL query window in PgAdmin 26 #. Select **File->Open** from the menu and browse to the ``nyc_census_sociodata.sql`` file 27 #. Press the "Run Query" button 28 #. If you press the "Refresh" button in PgAdmin, the list of tables should now include at ``nyc_census_sociodata`` table 29 30 Creating a Census Tracts Table 31 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 32 33 As we saw in the previous section, we can build up higher level geometries from the census block by summarizing on substrings of the ``blkid`` key. In order to get census tracts, we need to summarize grouping on the first 11 characters of the ``blkid``. 34 34 35 35 :: … … 43 43 000 = Census Block 44 44 45 Cr éation de la nouvelle table en utilisant la fonction d'agrégation :command:`ST_Union`:45 Create the new table using the :command:`ST_Union` aggregate: 46 46 47 47 .. code-block:: sql 48 48 49 -- Création de latable49 -- Make the tracts table 50 50 CREATE TABLE nyc_census_tract_geoms AS 51 51 SELECT … … 55 55 GROUP BY tractid; 56 56 57 -- Index ation du champtractid57 -- Index the tractid 58 58 CREATE INDEX nyc_census_tract_geoms_tractid_idx ON nyc_census_tract_geoms (tractid); 59 59 60 -- Mise à jour de la table geometry_columns60 -- Update the geometry_columns table 61 61 SELECT Populate_Geometry_Columns(); 62 62 63 Regrouper les données attributaires et spatiales 64 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~65 66 L'objectif est ici de regrouper les données spatiales que nous avons créé avec les donées attributaires que nous avions chargé initialement. 67 68 .. code-block:: sql 69 70 -- Création de latable63 Join the Attributes to the Spatial Data 64 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 65 66 Join the table of tract geometries to the table of tract attributes with a standard attribute join 67 68 .. code-block:: sql 69 70 -- Make the tracts table 71 71 CREATE TABLE nyc_census_tracts AS 72 72 SELECT … … 77 77 ON g.tractid = a.tractid; 78 78 79 -- Index ation des géométries79 -- Index the geometries 80 80 CREATE INDEX nyc_census_tract_gidx ON nyc_census_tracts USING GIST (the_geom); 81 81 82 -- Mise à jour de la table geometry_columns82 -- Update the geometry_columns table 83 83 SELECT Populate_Geometry_Columns(); 84 84 85 85 .. _interestingquestion: 86 86 87 Répondre à une question interressante 88 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~87 Answer an Interesting Question 88 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 89 89 90 Répondre à une question interressante ! "Lister les 10 meilleurs quartiers ordonnées par la proportion de personne ayant acquis un diplome". 90 Answer an interesting question! "List top 10 New York neighborhoods ordered by the proportion of people who have graduate degrees." 91 91 92 92 .. code-block:: sql … … 103 103 LIMIT 10; 104 104 105 Nous sommons les statistiques qui nous interressent, nous les divisons ensuite à la fin. Afin d'aviter l'erreur de non-division par zero, nous ne prennons pas en compte les quartiers qui n'ont aucune personne ayant obtenu un diplome.105 We sum up the statistics we are interested, then divide them together at the end. In order to avoid divide-by-zero errors, we don't bother bringing in tracts that have a population count of zero. 106 106 107 107 :: … … 123 123 .. _polypolyjoins: 124 124 125 Polygon es/Jointures de polygones126 --------------------- ------------127 128 Dans notre requête interressante (dans :ref:`interestingquestion`) nous avons utilisé la fonction :command:`ST_Intersects(geometry_a, geometry_b)` pour déterminer quelle entité polygonale à inclure dans chaque groupe de quartier. Ce qui nous conduit à la question : que ce passe-t-il si une entité tombe ntre deux quartier ? Il intersectera chacun d'entre eux et ainsi sera inclu dans **chacun** des résultats. 125 Polygon/Polygon Joins 126 --------------------- 127 128 In our interesting query (in :ref:`interestingquestion`) we used the :command:`ST_Intersects(geometry_a, geometry_b)` function to determine which census tract polygons to include in each neighborhood summary. Which leads to the question: what if a tract falls on the border between two neighborhoods? It will intersect both, and so will be included in the summary statistics for **both**. 129 129 130 130 .. image:: ./screenshots/centroid_neighborhood.png 131 131 132 Pour éviter ce cas de double comptage il existe trois méthodes:133 134 * La méthode simple consiste a s'assurer que chaque entité ne se retrouve que dans **un** seul groupe géograhique (en utilisant:command:`ST_Centroid(geometry)`)135 * La méthode complexe consiste à disviser les parties qui se croisent en utilisant les bordures (en utilisant:command:`ST_Intersection(geometry,geometry)`)136 137 Voici un exemple d'utilisation de la méthode simple pour éviter le double comptage dans notre requête précédente:132 To avoid this kind of double counting there are two methods: 133 134 * The simple method is to ensure that each tract only falls in **one** summary area (using :command:`ST_Centroid(geometry)`) 135 * The complex method is to divide crossing tracts at the borders (using :command:`ST_Intersection(geometry,geometry)`) 136 137 Here is an example of using the simple method to avoid double counting in our graduate education query: 138 138 139 139 .. code-block:: sql … … 150 150 LIMIT 10; 151 151 152 Remarquez que la requête prend plus de temps à s'exécuter, puisque la fonction :command:`ST_Centroid` doit être effectuée pour chaque entité.152 Note that the query takes longer to run now, because the :command:`ST_Centroid` function has to be run on every census tract. 153 153 154 154 :: … … 167 167 28.4 | Cobble Hill | Brooklyn 168 168 169 Ãviter le double comptage change le résultat ! 169 Avoiding double counting changes the results! 170 170 171 171 172 172 .. _largeradiusjoins: 173 173 174 Jointures utilisant un large rayon de distance 175 --------------------------- -------------------176 177 Une requête qu'il est sympat de demander est : "Comment les temps de permutation des gens proches (dans un rayon de 500 metres ) des stations de métros diffÚrent de ceuxqui en vive loin ?"178 179 Néanmoins, la question rencontre les même problÚme de double comptage : plusieurs personnes seront dans un rayon de 500 metres de plusieurs stations de métros différentes. Coparons la population de New York:174 Large Radius Distance Joins 175 --------------------------- 176 177 A query that is fun to ask is "How do the commute times of people near (within 500 meters) subway stations differ from those of people far away from subway stations?" 178 179 However, the question runs into some problems of double counting: many people will be within 500 meters of multiple subway stations. Compare the population of New York: 180 180 181 181 .. code-block:: sql … … 188 188 8008278 189 189 190 Avec la population des gens de New York dans un rayon de 500 metres d'une station de métros:190 With the population of the people in New York within 500 meters of a subway station: 191 191 192 192 .. code-block:: sql … … 201 201 10556898 202 202 203 Il y a plus de personnes proches du métro qu'il y a de peronnes ! Clairement, notre requête SQL simple rencontre un gros problÚme de double comptage. Vous pouvez voir le problÚme en regardant l'image des zones tampons créées pour les stations.203 There's more people close to the subway than there are people! Clearly, our simple SQL is making a big double-counting error. You can see the problem looking at the picture of the buffered subways. 204 204 205 205 .. image:: ./screenshots/subways_buffered.png 206 206 207 La solution est de s'assurer que nous avons seulement des blocks distincts avant de les les regrouper. Nou spouvons réaliser cela en cassant notre requête en sous-requêtes qui récupÚre les blocks distincts, regroupé ensuite pour retrouner notre réponse:207 The solution is to ensure that we have only distinct census blocks before passing them into the summarization portion of the query. We can do that by breaking our query up into a subquery that finds the distinct blocks, wrapped in a summarization query that returns our answer: 208 208 209 209 .. code-block:: sql … … 221 221 4953599 222 222 223 C'est mieux ! Donc un peu plus de 50 % de la population de New York vit à proximité (50m environ 5 à 7 minutes de marche) du métro.224 225 226 223 That's better! So a bit over half the population of New York is within 500m (about a 5-7 minute walk) of the subway. 224 225 226 -
/trunk/workshop-foss4g/simple_sql.rst
r61 r1 1 1 .. _simple_sql: 2 2 3 Partie 6 : Requêtes SQL simples 4 ===================== ==========3 Section 6: Simple SQL 4 ===================== 5 5 6 :term:`SQL`, pour "Structured Query Language", définit la maniÚre d'importer et d'interroger des données dans une base. Vous avez déjà rédigé du SQL lorsque nous avons créer notre premiÚre base de données. Rappel:6 :term:`SQL`, or "Structured Query Language", is a means of asking questions of, and updating data in, relational databases. You have already seen SQL when we created our first database. Recall: 7 7 8 8 .. code-block:: sql … … 10 10 SELECT postgis_full_version(); 11 11 12 Maintenant que nous avons charger des données dans notre base, essayons d'utiliser SQL pour les interroger. Par exemple,12 But that was a question about the database. Now that we've loaded data into our database, let's use SQL to ask questions of the data! For example, 13 13 14 " Quel sont les noms des quartiers de la ville de New York?"14 "What are the names of all the neighborhoods in New York City?" 15 15 16 O uvrez une fenêtre SQL depuis pgAdmin en cliquant sur le bouton SQL16 Open up the SQL query window in pgAdmin by clicking the SQL button 17 17 18 18 .. image:: ./screenshots/pgadmin_05.png 19 19 20 Puis saisissez la requête suivante dans la fenêtre 20 then enter the following query in to the query window 21 21 22 22 .. code-block:: sql … … 24 24 SELECT name FROM nyc_neighborhoods; 25 25 26 et cliquez sur le bouton **Execute Query** (le triangle vert).26 and click the **Execute Query** button (the green triangle). 27 27 28 28 .. image:: ./screenshots/pgadmin_08.png 29 29 30 La requête s'exécutera pendant quelques (mili)secondes et retournera 129 résultats.30 The query will run for a few (mili)seconds and return the 129 results. 31 31 32 32 .. image:: ./screenshots/pgadmin_09.png 33 33 34 Mais que c'est-il exactement passé ici ? Pour le comprendre, commençons par présenter les quatre types de requêtes du SQL : 34 But what exactly happened here? To understand, let's begin with the four "verbs" of SQL, 35 35 36 * ``SELECT``, ret ourne des lignes en réponse à une requête37 * ``INSERT``, a joute des lignes dans unetable38 * ``UPDATE``, modifie des lignes existantes d'unetable39 * ``DELETE``, supprime des lignes d'unetable36 * ``SELECT``, returns rows in response to a query 37 * ``INSERT``, adds new rows to a table 38 * ``UPDATE``, alters existing rows in a table 39 * ``DELETE``, removes rows from a table 40 40 41 Nous travaillerons principalement avec des requêtes de type ``SELECT``afin d'interroger les tables en utilisant des fonctions spatiales.41 We will be working almost exclusively with ``SELECT`` in order to ask questions of tables using spatial functions. 42 42 43 Requête de type SELECT 44 -------------- --------43 SELECT queries 44 -------------- 45 45 46 Une requête de type Select est généralement de la forme:46 A select query is generally of the form: 47 47 48 SELECT colonnes FROM données WHERE conditions;48 SELECT some_columns FROM some_data_source WHERE some_condition; 49 49 50 50 .. note:: 51 51 52 Pour une description exhaustive des paramÚtres possible d'une requête ``SELECT``, consultez la `documentaton de PostgresSQL<http://www.postgresql.org/docs/8.1/interactive/sql-select.html>`_.52 For a synopsis of all ``SELECT`` parameters, see the PostgresSQL `documentation <http://www.postgresql.org/docs/8.1/interactive/sql-select.html>`_. 53 53 54 The ``some_columns`` are either column names or functions of column values. The ``some_data_source`` is either a single table, or a composite table created by joining two tables on a key or condition. The ``some_condition`` is a filter that restricts the number of rows to be returned. 54 55 55 Les ``colonnes`` sont soit des noms de colonnes, soit des fonctions utilisant les valeurs des colonnes. Les ``données`` sont soit une table seule, soit plusieures tables reliées ensemble en réalisant une jointure sur une clef ou une autre condition. Les ``conditions`` représentent le filtre qui restreint le nombre de lignes à retourner. 56 "What are the names of all the neighborhoods in Brooklyn?" 56 57 57 "Quel sont les noms des quartiers de Brooklyn ?" 58 59 Nous retournons à notre table ``nyc_neighborhoods`` avec le filtre en main. La table contient tout les quartiers de New York et nous voulons uniquement ceux de Brooklyn. 58 We return to our ``nyc_neighborhoods`` table with a filter in hand. The table contains all the neighborhoods in New York, but we only want the ones in Brooklyn. 60 59 61 60 .. code-block:: sql … … 65 64 WHERE boroname = 'Brooklyn'; 66 65 67 La requête prendra à nouveau quelque (mili)secondes et retournera les 23 éléments résultants.66 The query will run for even fewer (mili)seconds and return the 23 results. 68 67 69 Parfois nous aurons besoin d'appliquer des fonctions sur le résultats d'une de nos requêtes. Par exemple,68 Sometimes we will need to apply a function to the results of our query. For example, 70 69 71 " Quel est le nombre de lettres dans les noms des quartiers de Brooklyn?"70 "What is the number of letters in the names of all the neighborhoods in Brooklyn?" 72 71 73 Heureusement PostgreSQL fournit une fonction calculant la longueur d'une chaîne de caractÚres ::command:`char_length(string)`.72 Fortunately, PostgreSQL has a string length function, :command:`char_length(string)`. 74 73 75 74 .. code-block:: sql … … 79 78 WHERE boroname = 'Brooklyn'; 80 79 81 Bien souvent nous sommes moins interressés par une ligne particuliÚre mais plus par un calcul statistique sur l'ensemble résultant. Donc, connaitre la longueur des noms de quartiers est moins interressant que de calculer la moyenne des ces longueurs. Les fonctions qui renvoit un résultat unique en utilisant un ensemble de valeurs sont appelée des "fonctions d'aggrégations". 80 Often, we are less interested in the individual rows than in a statistic that applies to all of them. So knowing the lengths of the neighborhood names might be less interesting than knowing the average length of the names. Functions that take in multiple rows and return a single result are called "aggregate" functions. 82 81 83 PostgreSQL fournit un ensemble de fonctions d'aggrégations, parmis lesquelles :command:`avg()` pour calculer la moyenne, and :command:`stddev()` pour l'écart type.82 PostgreSQL has a series of built-in aggregate functions, including the general purpose :command:`avg()` for average values and :command:`stddev()` for standard deviations. 84 83 85 " Quel est le nombre moyen et l'écart type du nombre de lettre dans le noms des quartier de Brooklyn?"84 "What is the average number of letters and standard deviation of number of letters in the names of all the neighborhoods in Brooklyn?" 86 85 87 86 .. code-block:: sql … … 97 96 11.7391304347826087 | 3.9105613559407395 98 97 99 Les fonctions d'agrégation dans notre dernier exemple sont appliquées à chaque ligne de l'ensemble des résultats. Comment faire si nous voulons rassembler des données ? Pour cela nous utilisons la clause ``GROUP BY``. Les fonctions d'agrégation ont souvent besoin d'une clause ``GROUP BY`` pour regrouper les éléments en utilisant une ou plusieures colonnes. 98 The aggregate functions in our last example were applied to every row in the result set. What if we want the summaries to be carried out over smaller groups within the overall result set? For that we add a ``GROUP BY`` clause. Aggregate functions often need an added ``GROUP BY`` statement to group the result-set by one or more columns. 100 99 101 " Quel est la moyenne des les noms de quartier de New York, renvoyer par quartiers?"100 "What is the average number of letters in the names of all the neighborhoods in New York City, reported by borough?" 102 101 103 102 .. code-block:: sql … … 107 106 GROUP BY boroname; 108 107 109 110 Nous ajoutons la colonne ``boroname`` dans le résultat afin de pouvoir déterminer quelle valeur statistique s'applique à quel quartier. Dans une requête agrégée, vous pouvez seulement retourner les colonnes qui sont (a) membre de la clause de regroupement ou (b) des fonctions d'agrégation. 108 We include the ``boroname`` column in the output result so we can determine which statistic applies to which borough. In an aggregate query, you can only output columns that are either (a) members of the grouping clause or (b) aggregate functions. 111 109 112 110 :: … … 120 118 Staten Island | 12.2916666666666667 | 5.2043390480959474 121 119 122 Liste de fonctions 123 ------------- -----120 Function List 121 ------------- 124 122 125 `avg(expression) <http://www.postgresql.org/docs/current/static/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE>`_: fonction d'agrégation de PostgreSQL qui retourne la valeur moyenne d'une colonne.123 `avg(expression) <http://www.postgresql.org/docs/current/static/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE>`_: PostgreSQL aggregate function that returns the average value of a numeric column. 126 124 127 `char_length(string) <http://www.postgresql.org/docs/current/static/functions-string.html>`_: fonction s'applicant aux chaînes de caractÚre de PostgreSQL qui retourne le nombre de lettres dans une chaîne.125 `char_length(string) <http://www.postgresql.org/docs/current/static/functions-string.html>`_: PostgreSQL string function that returns the number of character in a string. 128 126 129 `stddev(expression) <http://www.postgresql.org/docs/current/static/functions-aggregate.html#FUNCTIONS-AGGREGATE-STATISTICS-TABLE>`_: fonction d'aggrégation de PostgreSQL qui retourne l'écart type d'un ensemble de valeurs.127 `stddev(expression) <http://www.postgresql.org/docs/current/static/functions-aggregate.html#FUNCTIONS-AGGREGATE-STATISTICS-TABLE>`_: PostgreSQL aggregate function that returns the standard deviation of input values. 130 128 131 129 -
/trunk/workshop-foss4g/spatial_relationships_exercises.rst
r61 r1 1 1 .. _spatial_relationships_exercises: 2 2 3 Partie 11 : Exercises sur les relations spatiales3 Section 11: Spatial Relationships Exercises 4 4 =========================================== 5 5 6 Voici un rappel des fonctions que nous avons vu dans les parties précédentes. Elles seront utiles pour les exercices!6 Here's a reminder of the functions we saw in the last section. They should be useful for the exercises! 7 7 8 * :command:`sum(expression)` agrégation retournant la somme d'un ensemble 9 * :command:`count(expression)` agrégation retournant le nombre d'éléments d'un ensemble 10 * :command:`ST_Contains(geometry A, geometry B)` ret ourne vrai si la géométrie A contient la géométrieB11 * :command:`ST_Crosses(geometry A, geometry B)` ret ourne vrai si la géométrie A croise la géométrieB12 * :command:`ST_Disjoint(geometry A , geometry B)` ret ourne vrai si les géométrie ne s'intersectent pas13 * :command:`ST_Distance(geometry A, geometry B)` ret ourne la distance minimum entre deux géométries14 * :command:`ST_DWithin(geometry A, geometry B, radius)` ret ourne vrai si la A est distante d'au plus radius deB15 * :command:`ST_Equals(geometry A, geometry B)` ret ourne vrai si A est la même géométrie queB16 * :command:`ST_Intersects(geometry A, geometry B)` ret ourne vrai si A intersecteB17 * :command:`ST_Overlaps(geometry A, geometry B)` ret ourne vrai si A et B on un espace en commun, mais ne sont pas complétement inclus l'un dans l'autre.18 * :command:`ST_Touches(geometry A, geometry B)` ret ourne vrai si le contour extérieur de A toucheB19 * :command:`ST_Within(geometry A, geometry B)` ret ourne vrai si A est hors deB8 * :command:`sum(expression)` aggregate to return a sum for a set of records 9 * :command:`count(expression)` aggregate to return the size of a set of records 10 * :command:`ST_Contains(geometry A, geometry B)` returns true if geometry A contains geometry B 11 * :command:`ST_Crosses(geometry A, geometry B)` returns true if geometry A crosses geometry B 12 * :command:`ST_Disjoint(geometry A , geometry B)` returns true if the geometries do not "spatially intersect" 13 * :command:`ST_Distance(geometry A, geometry B)` returns the minimum distance between geometry A and geometry B 14 * :command:`ST_DWithin(geometry A, geometry B, radius)` returns true if geometry A is radius distance or less from geometry B 15 * :command:`ST_Equals(geometry A, geometry B)` returns true if geometry A is the same as geometry B 16 * :command:`ST_Intersects(geometry A, geometry B)` returns true if geometry A intersects geometry B 17 * :command:`ST_Overlaps(geometry A, geometry B)` returns true if geometry A and geometry B share space, but are not completely contained by each other. 18 * :command:`ST_Touches(geometry A, geometry B)` returns true if the boundary of geometry A touches geometry B 19 * :command:`ST_Within(geometry A, geometry B)` returns true if geometry A is within geometry B 20 20 21 Souvenez-vous les tables à votre disposition:21 Also remember the tables we have available: 22 22 23 23 * ``nyc_census_blocks`` … … 37 37 * name, boroname, the_geom 38 38 39 Exerci ces39 Exercises 40 40 --------- 41 41 42 * **" Quel est la valeur géométrique de la rue nommée 'Atlantic Commons'?"**42 * **"What is the geometry value for the street named 'Atlantic Commons'?"** 43 43 44 44 .. code-block:: sql … … 52 52 01050000202669000001000000010200000002000000093235673BE82141F319CD89A22E514170E30E0ADFE82141CB2D3EFFA52E5141 53 53 54 * **" Quel sont les quartiers et villes qui sont dans Atlantic Commons?"**54 * **"What neighborhood and borough is Atlantic Commons in?"** 55 55 56 56 .. code-block:: sql … … 70 70 71 71 72 * **" Quelles rues touchent Atlantic Commons?"**72 * **"What streets does Atlantic Commons touch?"** 73 73 74 74 .. code-block:: sql … … 91 91 92 92 93 * **"Approximat ivement combien de personnes vivent dans (ou dans une zone de 50 metres autour d') Atlantic Commons?"**93 * **"Approximately how many people live on (within 50 meters of) Atlantic Commons?"** 94 94 95 95 .. code-block:: sql -
/trunk/workshop-foss4g/geometries_exercises.rst
r61 r1 1 1 .. _geometries_exercises: 2 2 3 Partie 9 : Exercices sur les géométries4 ============================= =========5 6 Voici un petit rappel de toutes les fonction que nous avons abordé jusqu'à présent. Elles devraient être utiles pour les exercices!7 8 * :command:`sum(expression)` ag régation retournant la somme d'un ensemble9 * :command:`count(expression)` ag régation retournant le nombre d'éléments d'un ensemble10 * :command:`ST_GeometryType(geometry)` ret ourne le type de la géométrie11 * :command:`ST_NDims(geometry)` ret ourne le nombre de dimensions12 * :command:`ST_SRID(geometry)` ret ourne l'identifiant du systÚme de références spatiales13 * :command:`ST_X(point)` ret ourne la coordonnée X14 * :command:`ST_Y(point)` ret ourne la coordonnée Y15 * :command:`ST_Length(linestring)` ret ourne la longueur d'une ligne16 * :command:`ST_StartPoint(geometry)` ret ourne le premier point d'une ligne17 * :command:`ST_EndPoint(geometry)` ret ourne le dernier point d'une ligne18 * :command:`ST_NPoints(geometry)` ret ourne le nombre de points d'une ligne19 * :command:`ST_Area(geometry)` ret ourne l'aire d'un polygone20 * :command:`ST_NRings(geometry)` ret ourne le nombre de contours (1 ou plus si il y a des trous)21 * :command:`ST_ExteriorRing(polygon)` ret ourne le contour exterieur (ligne) d'un polygon22 * :command:`ST_InteriorRingN(polygon, integer)` ret ourne le contour intérieur (ligne) d'un polygone23 * :command:`ST_Perimeter(geometry)` ret ourne la longueur de tout les contours24 * :command:`ST_NumGeometries(multi/geomcollection)` ret ourne le nombre de composantes dans une collection25 * :command:`ST_GeometryN(geometry, integer)` ret ourne la niÚme entité de lacollection26 * :command:`ST_GeomFromText(text)` ret ourne``geometry``27 * :command:`ST_AsText(geometry)` ret ourneWKT ``text``28 * :command:`ST_AsEWKT(geometry)` ret ourneEWKT ``text``29 * :command:`ST_GeomFromWKB(bytea)` ret ourne``geometry``30 * :command:`ST_AsBinary(geometry)` ret ourneWKB ``bytea``31 * :command:`ST_AsEWKB(geometry)` ret ourneEWKB ``bytea``32 * :command:`ST_GeomFromGML(text)` ret ourne``geometry``33 * :command:`ST_AsGML(geometry)` ret ourneGML ``text``34 * :command:`ST_GeomFromKML(text)` ret ourne``geometry``35 * :command:`ST_AsKML(geometry)` ret ourneKML ``text``36 * :command:`ST_AsGeoJSON(geometry)` ret ourneJSON ``text``37 * :command:`ST_AsSVG(geometry)` ret ourneSVG ``text``38 39 Souvenez-vous aussi des tables disponibles:3 Section 9: Geometry Exercises 4 ============================= 5 6 Here's a reminder of all the functions we have seen so far. They should be useful for the exercises! 7 8 * :command:`sum(expression)` aggregate to return a sum for a set of records 9 * :command:`count(expression)` aggregate to return the size of a set of records 10 * :command:`ST_GeometryType(geometry)` returns the type of the geometry 11 * :command:`ST_NDims(geometry)` returns the number of dimensions of the geometry 12 * :command:`ST_SRID(geometry)` returns the spatial reference identifier number of the geometry 13 * :command:`ST_X(point)` returns the X ordinate 14 * :command:`ST_Y(point)` returns the Y ordinate 15 * :command:`ST_Length(linestring)` returns the length of the linestring 16 * :command:`ST_StartPoint(geometry)` returns the first coordinate as a point 17 * :command:`ST_EndPoint(geometry)` returns the last coordinate as a point 18 * :command:`ST_NPoints(geometry)` returns the number of coordinates in the linestring 19 * :command:`ST_Area(geometry)` returns the area of the polygons 20 * :command:`ST_NRings(geometry)` returns the number of rings (usually 1, more if there are holes) 21 * :command:`ST_ExteriorRing(polygon)` returns the outer ring as a linestring 22 * :command:`ST_InteriorRingN(polygon, integer)` returns a specified interior ring as a linestring 23 * :command:`ST_Perimeter(geometry)` returns the length of all the rings 24 * :command:`ST_NumGeometries(multi/geomcollection)` returns the number of parts in the collection 25 * :command:`ST_GeometryN(geometry, integer)` returns the specified part of the collection 26 * :command:`ST_GeomFromText(text)` returns ``geometry`` 27 * :command:`ST_AsText(geometry)` returns WKT ``text`` 28 * :command:`ST_AsEWKT(geometry)` returns EWKT ``text`` 29 * :command:`ST_GeomFromWKB(bytea)` returns ``geometry`` 30 * :command:`ST_AsBinary(geometry)` returns WKB ``bytea`` 31 * :command:`ST_AsEWKB(geometry)` returns EWKB ``bytea`` 32 * :command:`ST_GeomFromGML(text)` returns ``geometry`` 33 * :command:`ST_AsGML(geometry)` returns GML ``text`` 34 * :command:`ST_GeomFromKML(text)` returns ``geometry`` 35 * :command:`ST_AsKML(geometry)` returns KML ``text`` 36 * :command:`ST_AsGeoJSON(geometry)` returns JSON ``text`` 37 * :command:`ST_AsSVG(geometry)` returns SVG ``text`` 38 39 Also remember the tables we have available: 40 40 41 41 * ``nyc_census_blocks`` … … 55 55 * name, boroname, the_geom 56 56 57 Exerci ces57 Exercises 58 58 --------- 59 59 60 * **" Quelle est l'aire du quartier 'West Village'?"**60 * **"What is the area of the 'West Village' neighborhood?"** 61 61 62 62 .. code-block:: sql … … 72 72 .. note:: 73 73 74 L'aire est donnée en metres carrés. Pour obtenir l'aire en hectare, divisez par 10000. Pour obrenir l'aire en acres, divisez par4047.75 76 * **" Quelle est l'aire de Manhattan en acres ?"** (Astuce: ``nyc_census_blocks`` et ``nyc_neighborhoods`` on toutes deux le champ ``boroname``.)74 The area is given in square meters. To get an area in hectares, divide by 10000. To get an area in acres, divide by 4047. 75 76 * **"What is the area of Manhattan in acres?"** (Hint: both ``nyc_census_blocks`` and ``nyc_neighborhoods`` have a ``boroname`` in them.) 77 77 78 78 .. code-block:: sql … … 99 99 100 100 101 * **" Combien de blocs de la ville de New York ont des trous?"**101 * **"How many census blocks in New York City have a hole in them?"** 102 102 103 103 .. code-block:: sql … … 111 111 66 112 112 113 * **" Quel est la longueur totale des rues (en kilomÚtres) dans la ville de New York ?"** (Astuce: l'unité de mesure des données spatiales est le mÚtre, il y a 1000 mÚtres dans un kilomÚtre.)113 * **"What is the total length of streets (in kilometers) in New York City?"** (Hint: The units of measurement of the spatial data are meters, there are 1000 meters in a kilometer.) 114 114 115 115 .. code-block:: sql … … 122 122 10418.9047172 123 123 124 * **" Quelle est la longueur de 'Columbus Cir' (Columbus Circle) ?"**124 * **"How long is 'Columbus Cir' (Columbus Circle)?** 125 125 126 126 .. code-block:: sql … … 134 134 308.34199 135 135 136 * **" Quelle est le contour de 'West Village' au format JSON?"**136 * **"What is the JSON representation of the boundary of the 'West Village'?"** 137 137 138 138 .. code-block:: sql … … 149 149 [583263.2776595836,4509242.6260239873]]]]} 150 150 151 La géométrie de type "MultiPolygon", interressant!151 The geometry type is "MultiPolygon", interesting! 152 152 153 153 154 * **" Combien de polygones sont dans le multi-polygone 'West Village'?"**154 * **"How many polygons are in the 'West Village' multipolygon?"** 155 155 156 156 .. code-block:: sql … … 166 166 .. note:: 167 167 168 I l n'est pas rare de trouver des éléments de type multi-polygone ne contenant qu'un seul polygone dans des tables. L'utilisation du type multi-polygone permet d'utiliser une seule table pour y stocker des géométries simples et multiples sans mélanger lestypes.169 170 171 * **" Quel est la longueur des rues de la ville de New York, suivant leur type?"**168 It is not uncommon to find single-element MultiPolygons in spatial tables. Using MultiPolygons allows a table with only one geometry type to store both single- and multi-geometries without using mixed types. 169 170 171 * **"What is the length of streets in New York City, summarized by type?"** 172 172 173 173 .. code-block:: sql … … 207 207 .. note:: 208 208 209 La clause ``ORDER BY length DESC`` ordonne le résultat par la valeur des longueurs dans l'ordre décroissant. Le résultat avec la plus grande valeur se retrouve au début la liste de résultats.209 The ``ORDER BY length DESC`` clause sorts the result by length in descending order. The result is that most prevalent types are first in the list. 210 210 211 211 -
/trunk/workshop-foss4g/joins.rst
r61 r1 1 1 .. _joins: 2 2 3 Partie 12 : Les jointures spatiales4 ========================= ==========5 6 Les jointures spatiales sont la cerise sur le gâteau des base de données spatiales. Elles vous pemettent de combiner les informations de plusieures tables en utilisant une relation spatiale comme clause de jointure. La plupart des "analyses SIG standards" peuvent être exprimées à l'aide de jointure spatiales.7 8 Dans la partie précédente, nous avons utilisé les relations spatiales en utilisant deux étapes dans nos requêtes : nous avons dans un premier temps extrait la station de métro "Broad St" puis nous avons utilisé ce résultat dans nos autres requêtes pour répondre aux questions comme "dans quel quartier se situe la station 'Broad St'?"9 10 En utilisant les jointures spatiales, nous pouvons répondre aux questions en une seule étape, récupérant les informations relatives à la station de métro et le quartier la contenant : 3 Section 12: Spatial Joins 4 ========================= 5 6 Spatial joins are the bread-and-butter of spatial databases. They allow you to combine information from different tables by using spatial relationships as the join key. Much of what we think of as "standard GIS analysis" can be expressed as spatial joins. 7 8 In the previous section, we explored spatial relationships using a two-step process: first we extracted a subway station point for 'Broad St'; then, we used that point to ask further questions such as "what neighborhood is the 'Broad St' station in?" 9 10 Using a spatial join, we can answer the question in one step, retrieving information about the subway station and the neighborhood that contains it: 11 11 12 12 .. code-block:: sql … … 27 27 Broad St | Financial District | Manhattan 28 28 29 Nous avons pu regrouper chaque station de métro avec le quartier auquel elle appartient, mais dans ce cas nous n'en voulions qu'une. Chaque fonction qui envoit un résultat du type vrai/faux peut être utilisée pour joindre spatialement deux tables, mais la plupart du temps on utilise : :command:`ST_Intersects`, :command:`ST_Contains`, et:command:`ST_DWithin`.30 31 Join ture et regroupement32 ------------------ ------33 34 La combinaison de ``JOIN`` avec ``GROUP BY`` fournit le type d'analyse qui est couramment utilisé dans les systÚmes SIG.35 36 Par exemple : **Quelle est la population et la répartition raciale du quartier de Manhattan ?** Ici nous avons une question qui combine les informations relatives à la population recensée et les contours des quartiers, or nous ne voulons qu'un seul quartier, celui deManhattan.29 We could have joined every subway station to its containing neighborhood, but in this case we wanted information about just one. Any function that provides a true/false relationship between two tables can be used to drive a spatial join, but the most commonly used ones are: :command:`ST_Intersects`, :command:`ST_Contains`, and :command:`ST_DWithin`. 30 31 Join and Summarize 32 ------------------ 33 34 The combination of a ``JOIN`` with a ``GROUP BY`` provides the kind of analysis that is usually done in a GIS system. 35 36 For example: **"What is the population and racial make-up of the neighborhoods of Manhattan?"** Here we have a question that combines information from about population from the census with the boundaries of neighborhoods, with a restriction to just one borough of Manhattan. 37 37 38 38 .. code-block:: sql … … 84 84 85 85 86 Que ce passe-t-il ici ? Voici ce qui se passe (l'ordre d'évaluation est optimisé par la base de données):87 88 #. La clause ``JOIN`` crée une table virtuelle qui contient les colonnes à la fois des quartiers et des recensements (tables neighborhoods et census).89 #. La clause ``WHERE`` filtre la table virtuelle pour ne conserver que la ligne correspondant ÃManhattan.90 #. Les lignes restantes sont regroupées par le nom du quartier et sont utilisées par la fonction d'agrégation : :command:`Sum()` pour réaliser la somme des valeurs de la populations.91 #. A prÚs un peu d'arythmétique et de formatage (ex: ``GROUP BY``, ``ORDER BY``)) sur le nombres finaux, notre requête calcul les pourcentages.86 What's going on here? Notionally (the actual evaluation order is optimized under the covers by the database) this is what happens: 87 88 #. The ``JOIN`` clause creates a virtual table that includes columns from both the neighborhoods and census tables. 89 #. The ``WHERE`` clause filters our virtual table to just rows in Manhattan. 90 #. The remaining rows are grouped by the neighborhood name and fed through the aggregation function to :command:`Sum()` the population values. 91 #. After a little arithmetic and formatting (e.g., ``GROUP BY``, ``ORDER BY``) on the final numbers, our query spits out the percentages. 92 92 93 93 .. note:: 94 94 95 La clause ``JOIN`` combine deux parties ``FROM``. Par défaut, nous utilisons un jointure du type :``INNER JOIN``, mais il existe quatres autres types de jointures. Pour de plus amples informations à ce sujet, consultez la partie `type_jointure <http://docs.postgresql.fr/9.1/sql-select.html>`_ de la page de la documentation officielle de PostgreSQL.96 97 Nous pouvons aussi utiliser le test de la distance dans notre clef de jointure, pour créer une regroupement de "tout les éléments dans un certain rayon". Essayons d'analyser la géographie raciale de New York en utilisant les requêtes de distance.98 99 PremiÚrement, essayons d'obtenir la répartition raciale de la ville.95 The ``JOIN`` clause combines two ``FROM`` items. By default, we are using an ``INNER JOIN``, but there are four other types of joins. For further information see the `join_type <http://www.postgresql.org/docs/8.1/interactive/sql-select.html>`_ definition in the PostgreSQL documentation. 96 97 We can also use distance tests as a join key, to create summarized "all items within a radius" queries. Let's explore the racial geography of New York using distance queries. 98 99 First, let's get the baseline racial make-up of the city. 100 100 101 101 .. code-block:: sql … … 114 114 115 115 116 Donc, 8M de personnes dans New York, environ 44% sont "blancs" et 26% sont "noirs". 117 118 Duke Ellington chantait que "You / must take the A-train / To / go to Sugar Hill way up in Harlem." Comme nous l'avons vu précédemment, Harlem est de trÚs loin le quartier ou se trouve la plus grande concentration d'africains-américains de Manhattan (80.5%). Est-il toujours vrai qu'il faut prendre le train A dont Duke parlait dans sa chanson?119 120 PremiÚrement, le contenu du champ ``routes`` de la table ``nyc_subway_stations`` va nous servir à récupérer le train A. Les valeurs de ce champs sont un peu complexes.116 So, of the 8M people in New York, about 44% are "white" and 26% are "black". 117 118 Duke Ellington once sang that "You / must take the A-train / To / go to Sugar Hill way up in Harlem." As we saw earlier, Harlem has far and away the highest African-American population in Manhattan (80.5%). Is the same true of Duke's A-train? 119 120 First, note that the contents of the ``nyc_subway_stations`` table ``routes`` field is what we are interested in to find the A-train. The values in there are a little complex. 121 121 122 122 .. code-block:: sql … … 136 136 .. note:: 137 137 138 Le mot clef ``DISTINCT`` permet d'éliminer les répétitions de lignes de notre résultat. Dans ce mot clef, notre requête renverrait 491 résultats au lieu de73.138 The ``DISTINCT`` keyword eliminates duplicate rows from the result. Without the ``DISTINCT`` keyword, the query above identifies 491 results instead of 73. 139 139 140 Donc pour trouver le train A, nous allons demander toutes les lignes ayant pour ``routes`` la valeur 'A'. Nous pouvons faire cela de différentes maniÚres, mais nous utiliserons aujourd'hui le fait que la fonction :command:`strpos(routes,'A')` retourne un entier différent de 0 si la lettre 'A' se trouve dans la valeur du champs route.140 So to find the A-train, we will want any row in ``routes`` that has an 'A' in it. We can do this a number of ways, but today we will use the fact that :command:`strpos(routes,'A')` will return a non-zero number if 'A' is in the routes field. 141 141 142 142 .. code-block:: sql … … 158 158 A,C,E 159 159 160 Essayons de regrouper la répartition raciale dans un rayon de 200 mÚtres de la ligne du train A.160 Let's summarize the racial make-up of within 200 meters of the A-train line. 161 161 162 162 .. code-block:: sql … … 177 177 42.0805466940877366 | 23.0936148851067964 | 185259 178 178 179 La répartition raciale le long de la ligne du train A n'est pas radicallement différente de la répartition générale de la ville de New York. 180 181 Jointures avancées 182 ------------- -----183 184 Dans la derniÚre partie nous avons vu que le train A n'est pas utilisé par des populations si éloignées de la répartition totale du reste de la ville. Y-a-t-il des train qui passent par des parties de la ville qui ne sont pas dans la moyenne de la répartition raciale?185 186 Pour répondre à cette question, nous ajouterons une nouvelle jointure à notre requête, de telle maniÚre que nous puissions calculer simultanément la répartition raciale de plusieures lignes de métro à la fois. Pour faire ceci, nous créerons une table qui permettra d'énumérer toutes les lignes que nous voulons regrouper.179 So the racial make-up along the A-train isn't radically different from the make-up of New York City as a whole. 180 181 Advanced Join 182 ------------- 183 184 In the last section we saw that the A-train didn't serve a population that differed much from the racial make-up of the rest of the city. Are there any trains that have a non-average racial make-up? 185 186 To answer that question, we'll add another join to our query, so that we can simultaneously calculate the make-up of many subway lines at once. To do that, we'll need to create a new table that enumerates all the lines we want to summarize. 187 187 188 188 .. code-block:: sql … … 195 195 ('7'); 196 196 197 Maintenant nous pouvons joindre les tables des lignes de métros à notre requête précédente.197 Now we can join the table of subway lines onto our original query. 198 198 199 199 .. code-block:: sql … … 239 239 240 240 241 Comme précédemment, les jointures créent une table virtuelle de toutes les combinaisons possibles et disponibles à l'aide des contraintes de type ``JOIN ON`. Ces lignes sont ensuite utilisées dans le regroupement ``GROUP``. La magie spatiale tiend dans l'utilisation de la fonction ``ST_DWithin`` qui s'assure que les blocs sont suffisamment proches des lignes de métros inclues dans le calcul.242 243 Liste de fonctions 244 ------------- -----245 246 `ST_Contains(geometry A, geometry B) <http://postgis.org/docs/ST_Contains.html>`_: retourne TRUE si et seulement si aucun point de B est à l'extérieur de A, et si au moins un point à l'intérieur de B est à l'intérieur deA.247 248 `ST_DWithin(geometry A, geometry B, radius) <http://postgis.org/docs/ST_DWithin.html>`_: retourne TRUE si les géométries sont distantes du rayon donné.249 250 `ST_Intersects(geometry A, geometry B) <http://postgis.org/docs/ST_Intersects.html>`_: retourne TRUE si les géométries/géographies "s'intersectent spatialement" (partage une portiond de l'espace) et FALSE sinon (elles sont dijointes).251 252 `round(v numeric, s integer) <http://www.postgresql.org/docs/7.4/interactive/functions-math.html>`_: fonction de PostgreSQL qui arrondit à s décimales.253 254 `strpos( chaîne, sous-chaîne) <http://www.postgresql.org/docs/current/static/functions-string.html>`_: fonction de chaîne de caractÚres de PostgreSQL qui retourne la position de la sous-chaine.255 256 `sum(expression) <http://www.postgresql.org/docs/8.2/static/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE>`_: fonction d'agrégation de PostgreSQL qui retourne la somme d'un ensemble de valeurs.241 As before, the joins create a virtual table of all the possible combinations available within the constraints of the ``JOIN ON`` restrictions, and those rows are then fed into a ``GROUP`` summary. The spatial magic is in the ``ST_DWithin`` function, that ensures only census blocks close to the appropriate subway stations are included in the calculation. 242 243 Function List 244 ------------- 245 246 `ST_Contains(geometry A, geometry B) <http://postgis.org/docs/ST_Contains.html>`_: Returns true if and only if no points of B lie in the exterior of A, and at least one point of the interior of B lies in the interior of A. 247 248 `ST_DWithin(geometry A, geometry B, radius) <http://postgis.org/docs/ST_DWithin.html>`_: Returns true if the geometries are within the specified distance of one another. 249 250 `ST_Intersects(geometry A, geometry B) <http://postgis.org/docs/ST_Intersects.html>`_: Returns TRUE if the Geometries/Geography "spatially intersect" - (share any portion of space) and FALSE if they don't (they are Disjoint). 251 252 `round(v numeric, s integer) <http://www.postgresql.org/docs/7.4/interactive/functions-math.html>`_: PostgreSQL math function that rounds to s decimal places 253 254 `strpos(string, substring) <http://www.postgresql.org/docs/current/static/functions-string.html>`_: PostgreSQL string function that returns an integer location of a specified substring. 255 256 `sum(expression) <http://www.postgresql.org/docs/8.2/static/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE>`_: PostgreSQL aggregate function that returns the sum of records in a set of records. 257 257 258 258 .. rubric:: Footnotes -
/trunk/workshop-foss4g/license.rst
r61 r1 1 1 .. _license: 2 2 3 A nnexes C: License3 Appendix C: License 4 4 =================== 5 5 6 Ce contenu est publié sous licence Creative Commons 7 "`share alike with attribution <http://creativecommons.org/licenses/by-sa/3.0/us/>`_", 8 et est librement redistribuable en respectant les termes de cette license. 6 This work is licensed under the Creative Commons Attribution-Share Alike, United States License. To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/us/ or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA. 9 7 10 Vous devez conserver l'ensemble des copyrights présents dans ce document.8 Our attribution requirement is that you retain the visible copyright notices in all materials. -
/trunk/workshop-foss4g/simple_sql_exercises.rst
r61 r1 1 1 .. _simple_sql_exercises: 2 2 3 Partie 7 : Exercices simples de SQL 4 =============================== ====3 Section 7: Simple SQL Exercises 4 =============================== 5 5 6 En utilisant la table ``nyc_census_blocks``, répondez au questions suivantes (et n'allez pas directement aux réponses !).6 Using the ``nyc_census_blocks`` table, answer the following questions (don't peak at the answers!). 7 7 8 Vous trouverez ci-dessous des informations utiles pour commencer. Référez-vous à la partie :ref:`à propos des nos données` pour la définition de notre table ``nyc_census_blocks``.8 Here is some helpful information to get started. Recall from the :ref:`About Our Data <about_data>` section our ``nyc_census_blocks`` table definition. 9 9 10 10 .. list-table:: … … 12 12 13 13 * - **blkid** 14 - Un code à 15 chiffres qui définit de maniÚre unique chaque **bloc** ressencé . Ex: 36005000100900014 - A 15-digit code that uniquely identifies every census **block**. Eg: 360050001009000 15 15 * - **popn_total** 16 - Nombre total de personnes dans un bloc ressensé16 - Total number of people in the census block 17 17 * - **popn_white** 18 - N ombre de personnes se déclarant "blancs"18 - Number of people self-identifying as "white" in the block 19 19 * - **popn_black** 20 - N ombre de personnes se déclarant "noirs"20 - Number of people self-identifying as "black" in the block 21 21 * - **popn_nativ** 22 - N ombre de personnes se déclarant comme "nés aux états-unis"22 - Number of people self-identifying as "native american" in the block 23 23 * - **popn_asian** 24 - N ombre de personne se déclarant comme "asiatiques"24 - Number of people self-identifying as "asias" in the block 25 25 * - **popn_other** 26 - N ombre de personne se déclarant d'une autre catégorie26 - Number of people self-identifying with other categories in the block 27 27 * - **hous_total** 28 - N ombre de piÚces appartements28 - Number of housing units in the block 29 29 * - **hous_own** 30 - N ombre de propriétaires occupant les appartements30 - Number of owner-occupied housing units in the block 31 31 * - **hous_rent** 32 - N ombre de locations disponibles32 - Number of renter-occupied housing units in the block 33 33 * - **boroname** 34 - N om du quartier de New York. Manhattan, The Bronx, Brooklyn, Staten Island, Queens34 - Name of the New York borough. Manhattan, The Bronx, Brooklyn, Staten Island, Queens 35 35 * - **the_geom** 36 - Polygon e délimitant le bloc36 - Polygon boundary of the block 37 37 38 Ici se trouvent certaines des fonctions d'aggrégation qui vous seront utiles pour répondre aux questions:38 And, here are some common SQL aggregation functions you might find useful: 39 39 40 * avg() - la moyenne des vlauers dans un ensemble d'enregistrements41 * sum() - la somme des valeurs d'un ensembe d'enregistrements42 * count() - le nombre d'élément contenu dans un ensembe d'enregistrements.40 * avg() - the average (mean) of the values in a set of records 41 * sum() - the sum of the values in a set of records 42 * count() - the number of records in a set of records 43 43 44 Maintenant les questions:44 Now the questions: 45 45 46 * **" Quelle est la population de la ville de New York?"**46 * **"What is the population of the City of New York?"** 47 47 48 48 .. code-block:: sql … … 57 57 .. note:: 58 58 59 Qu'est-ce que ce ``AS`` dans la requête ? vous pouvez donner un nom à une table ou a des colonnes en utilisant un alias. Les alias permettent de rendre les requêtes plus simple à écrire et à lire. Donc au lieu que notre colonne résultat soit nommée ``sum`` nous utilisons le **AS** pour la renommer en``population``.59 What is this ``AS``? You can give a table or a column another name by using an alias. Aliases can make queries easier to both write and to read. So instead of our outputted column name as ``sum`` we write it **AS** the more readable ``population``. 60 60 61 * **" Quelle est la population du Bronx?"**61 * **"What is the population of the Bronx?"** 62 62 63 63 .. code-block:: sql … … 71 71 1332650 72 72 73 * **" Quelle est en moyenne le nombre de personne vivant dans chaque appartement de la ville de New York?"**73 * **"What is the average number of people living in each housing unit in New York City?"** 74 74 75 75 .. code-block:: sql … … 82 82 2.6503540522400804 83 83 84 * **" Pour chaque quartier, quel est le pourcentage de population blanche?"**84 * **"For each borough, what percentage of the population is white?"** 85 85 86 86 .. code-block:: sql … … 102 102 Staten Island | 77.5968611401579346 103 103 104 Liste des fonctions 105 ------------- ------104 Function List 105 ------------- 106 106 107 `avg(expression) <http://www.postgresql.org/docs/8.2/static/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE>`_: fonction d'aggrégation de PostgreSQL qui renvoit la moyenne d'un esemble de nombres.107 `avg(expression) <http://www.postgresql.org/docs/8.2/static/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE>`_: PostgreSQL aggregate function that returns the average value of a numeric column. 108 108 109 `count(expression) <http://www.postgresql.org/docs/8.2/static/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE>`_: une fonction d'aggrégation de PostgreSQL qui retourne le nombre d'éléments dans un esemble.109 `count(expression) <http://www.postgresql.org/docs/8.2/static/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE>`_: PostgreSQL aggregate function that returns the number of records in a set of records. 110 110 111 `sum(expression) <http://www.postgresql.org/docs/8.2/static/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE>`_: une fonction d'aggrégation de PostgreSQL qui retourne la somme des valeurs numériques d'un ensemble.111 `sum(expression) <http://www.postgresql.org/docs/8.2/static/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE>`_: PostgreSQL aggregate function that returns the sum of records in a set of records. -
/trunk/workshop-foss4g/welcome.rst
r61 r1 1 1 .. _welcome: 2 2 3 Bienvenu e4 ******** *3 Bienvenu 4 ******** 5 5 6 Conventions d'écriture 7 ============= =========6 About OpenGeo 7 ============= 8 8 9 Cette section présente les différentes conventions d'écriture qui seront utilisées dans ce 10 document afin d'en faciliter la lecture. 9 `OpenGeo <http://opengeo.org/>`_ is bringing the best practices of open source software to governments and other organizations around the world. 10 11 * We provide enterprises with supported, tested, and integrated open source solutions to help open government. 12 * We support open source communities by employing key developers for PostGIS, GeoServer, GeoWebCache, GeoExt, and OpenLayers. 13 * We have an eight year history of providing successful consulting services and products to clients like MassGIS, Tri-Met, Landgate, Google, The Work Bank, and the Open Geospatial Consortium. 14 * We believe open and accessible information empowers people to effect real change. OpenGeo's goal is to make geospatial information more open: publicly available, accessible on compelling platforms that people want to use. 15 * We strive to build software that meets and exceeds the desires of clients, because our market success proves the value of our work. 16 17 OpenGeo is the geospatial division of `OpenPlans <http://openplans.org/>`_, a New York-based 501(c)(3) non-profit which informs and engages communities through journalism and open source software. 18 19 Conventions 20 =========== 21 22 Cette section présente les différentes conventions qui seront utilisées dans ce document 23 afin d'en faciliter la lecture. 11 24 12 25 Indications 13 26 ----------- 14 27 15 Les indications pour vous, lecteurs de ce document, seront noté esen **gras**.28 Les indications pour vous, lecteurs de ce document, seront noté en **gras**. 16 29 17 30 Par exemple: … … 22 35 ---- 23 36 24 Les exemples de requêtes SQL seront affiché s de la maniÚre suivante :37 Les exemples de requêtes SQL seront affichées de la maniÚre suivante 25 38 26 39 .. code-block:: sql … … 28 41 SELECT postgis_full_version(); 29 42 30 Cet exemple peut être saisi dans la fenêtre de requêtage ou depuis l'interface en ligne de commande.43 Cette exemple peut être saisi dans la fenêtre de requêtage ou depuis l'interface en ligne de commande. 31 44 32 45 Notes 33 46 ----- 34 47 35 Les notes sont utilisées pour fournir une information utile mais non critique pour la 36 compréhension globale du sujet traité. 48 Les notes sont utilisées pour fournir une information utile mais non critique pour la compréhension globale du sujet traité. 37 49 38 .. note:: Si vous n'avez pas mangé une pomme aujourd'hui, le docteur devrait se 39 mettre en route. 50 .. note:: Si vous n'avez pas manger une pomme aujourd'hui, le docteur devrait se mettre en route. 40 51 41 52 Fonctions 42 53 --------- 43 54 44 Lorsque les noms de fonctions s ont contenus dans une phrase, ils sont affichésen :command:`gras`.55 Lorsque les noms de fonctions seront contenu dans une phrase, ils seront affiché en :command:`gras`. 45 56 46 57 Par exemple: 47 58 48 :command:`ST_Touches(geometry A, geometry B)` retourne vrai si un des contours de géométrie intersecte l'autre contour de géométrie59 :command:`ST_Touches(geometry A, geometry B)` retourne vrai si un des contours des géométries s'interectent 49 60 50 61 Fichiers, Tables et nom de colonne 51 62 ---------------------------------- 52 63 53 Les nom s de fichiers, les chemins, le noms de tables et les noms de colonnes seront affichéscomme suit64 Les nom de fichier, les chemin, le noms de tables et les noms de colones seront affiché comme suit 54 65 55 66 Select the ``name`` column in the ``nyc_streets`` table. 56 67 57 Menus et formulaires68 Menus and Form elements 58 69 ----------------------- 59 70 60 Les menus et les éléments de formulaire comme les champs ou les boîte s à cocher ainsi61 que les autre objets sontaffichés en *italique*.71 Les menus et les éléments de formulaire comme les champs ou les boîte à cocher ainsi 72 que les autre objets affichés en *italique*. 62 73 63 Par exemple:74 For example: 64 75 65 76 Cliquez sur *Fichier > Nouveau*. Cochez la case qui contient *Confirmer*. 66 77 67 Organisation 68 -------- ----78 Workflow 79 -------- 69 80 70 Les différentes sections de ce document permette nt d'évoluer progressivement. Chaque71 section suppose que vous a yez terminé et compris les sections précédentes.81 Les différentes sections de ce document permette d'évoluer progressivement. Chaque 82 section suppose que vous avez terminé et compris les section précédente 72 83 73 Certaines sections fournissent des exemples fonctionnels ainsi que des exercices. Dans certains cas, il y a aussi des sections "Les choses à essayer" pour les curieux. Ces tâches contiennent des problÚmes plus complexes que dans les exercices. 74 84 Sections are designed to be progressive. Each section will start with the assumption that you have completed and understood the previous section in the series and will build on that knowledge. A single section will progress through a handful of ideas and provide working examples wherever possible. At the end of a section, where appropriate, we have included a handful of exercises to allow you to try out the ideas we've presented. In some cases the section will include "Things To Try". These tasks contain more complex problems than the exercises and is designed to challenge participants with advanced knowledge. -
/trunk/workshop-foss4g/joins_exercises.rst
r61 r1 1 1 .. _joins_exercises: 2 2 3 Partie 13 : Exercices sur jointures spatiales4 =================================== ==========3 Section 13: Spatial Joins Exercises 4 =================================== 5 5 6 Voici un petit rappel de certaines des fonctions vues précédemment. Elles seront utiles pour les exercices!6 Here's a reminder of some of the functions we have seen. Hint: they should be useful for the exercises! 7 7 8 * :command:`sum(expression)` agrégation retournant la somme d'un ensemble 9 * :command:`count(expression)` agrégation retournant le nombre d'éléments d'un ensemble 10 * :command:`ST_Area(geometry)` ret ourbe l'aire d'un polygone8 * :command:`sum(expression)`: aggregate to return a sum for a set of records 9 * :command:`count(expression)`: aggregate to return the size of a set of records 10 * :command:`ST_Area(geometry)` returns the area of the polygons 11 11 * :command:`ST_AsText(geometry)` returns WKT ``text`` 12 * :command:`ST_Contains(geometry A, geometry B)` ret ourne vrai si la géométrie A contient la géométrieB13 * :command:`ST_Distance(geometry A, geometry B)` ret ourne la distance minimum entre deux géométries14 * :command:`ST_DWithin(geometry A, geometry B, radius)` ret ourne vrai si la A est distante d'au plus radius deB12 * :command:`ST_Contains(geometry A, geometry B)` returns the true if geometry A contains geometry B 13 * :command:`ST_Distance(geometry A, geometry B)` returns the minimum distance between geometry A and geometry B 14 * :command:`ST_DWithin(geometry A, geometry B, radius)` returns the true if geometry A is radius distance or less from geometry B 15 15 * :command:`ST_GeomFromText(text)` returns ``geometry`` 16 16 * :command:`ST_Intersects(geometry A, geometry B)` returns the true if geometry A intersects geometry B 17 * :command:`ST_Length(linestring)` ret ourne la longueur d'une linestring18 * :command:`ST_Touches(geometry A, geometry B)` ret ourne vrai si le contour extérieur de A toucheB19 * :command:`ST_Within(geometry A, geometry B)` ret ourne vrai si A est hors deB20 21 Souvenez-vous aussi des tables à votre disposition : 17 * :command:`ST_Length(linestring)` returns the length of the linestring 18 * :command:`ST_Touches(geometry A, geometry B)` returns the true if the boundary of geometry A touches geometry B 19 * :command:`ST_Within(geometry A, geometry B)` returns the true if geometry A is within geometry B 20 21 Also remember the tables we have available: 22 22 23 23 * ``nyc_census_blocks`` … … 37 37 * name, boroname, the_geom 38 38 39 Exerci ces39 Exercises 40 40 --------- 41 41 42 * **" Quelle station de métros se situe dans le quartier 'Little Italy' ? Quelle est l'itinéraire de métro à emprunter?"**42 * **"What subway station is in 'Little Italy'? What subway route is it on?"** 43 43 44 44 .. code-block:: sql … … 56 56 Spring St | 6 57 57 58 * **" Quels sont les quartiers desservis pas le train numéro 6 ?"** (Astuce: la colonne ``routes`` de la table ``nyc_subway_stations`` dispose des valeurs suivantes: 'B,D,6,V' et'C,6')58 * **"What are all the neighborhoods served by the 6-train?"** (Hint: The ``routes`` column in the ``nyc_subway_stations`` table has values like 'B,D,6,V' and 'C,6') 59 59 60 60 .. code-block:: sql … … 88 88 .. note:: 89 89 90 Nous avons utilisé le mot clef ``DISTINCT`` pour supprimer les répétitions dans notre ensemble de résultats où il y avait plus d'une seule station de métro dans le quartier.91 92 * **"A prÚs le 11 septembre, le quartier de 'Battery Park' était interdit d'accÚs pendant plusieurs jours. Combien de personnes ont dû être évacuées?"**90 We used the ``DISTINCT`` keyword to remove duplicate values from our result set where there were more than one subway station in a neighborhood. 91 92 * **"After 9/11, the 'Battery Park' neighborhood was off limits for several days. How many people had to be evacuated?"** 93 93 94 94 .. code-block:: sql … … 104 104 9928 105 105 106 * **" Quelle est la densité de population (personne / km^2) des quartiers de 'Upper West Side' et de 'Upper East Side' ?"** (Astuce: il y a 1000000 m^2 dans unkm^2.)106 * **"What are the population density (people / km^2) of the 'Upper West Side' and 'Upper East Side'?"** (Hint: There are 1000000 m^2 in one km^2.) 107 107 108 108 .. code-block:: sql -
/trunk/workshop-foss4g/postgis-functions.rst
r61 r1 1 1 .. _postgis-functions: 2 2 3 A nnexes A : Fonctions PostGIS3 Appendix A: PostGIS Functions 4 4 ============================= 5 5 6 Construct eurs6 Constructors 7 7 ------------ 8 8 9 9 :command:`ST_MakePoint(Longitude, Latitude)` 10 Ret ourne un nouveau point. Note : ordre des coordonées (longitude puislatitude).10 Returns a new point. Note the order of the coordinates (longitude then latitude). 11 11 12 12 :command:`ST_GeomFromText(WellKnownText, srid)` 13 Ret ourne une nouvelle géométrie à partir d'un représentation au format WKT et un SRID.13 Returns a new geometry from a standard WKT string and srid. 14 14 15 15 :command:`ST_SetSRID(geometry, srid)` 16 Met à jour le SRID d'une géométrie. Retourne la même géométrie. Cela ne modifie pas les coordonnées de la géométrie, cela met simplement à jour le SRID. Cette fonction est utile pour reconditionner les géométries sans SRID.16 Updates the srid on a geometry. Returns the same geometry. This does not alter the coordinates of the geometry, it just updates the srid. This function is useful for conditioning geometries created without an srid. 17 17 18 18 :command:`ST_Expand(geometry, Radius)` 19 Ret ourne une nouvelle géométrie qui est une extension de l'étendue de la géométrie passé en argument. Cette fonction est utile pour créer des envelopes pour des recherches utilisants les indexations.19 Returns a new geometry that is an expanded bounding box of the input geometry. This function is useful for creating envelopes for use in indexed searches. 20 20 21 Srotie 21 Outputs 22 22 ------- 23 23 24 24 :command:`ST_AsText(geometry)` 25 Ret ourne une géométrie au format WKT.25 Returns a geometry in a human-readable text format. 26 26 27 27 :command:`ST_AsGML(geometry)` 28 Ret ourne la géométrie au format standard OGC :term:`GML`.28 Returns a geometry in standard OGC :term:`GML` format. 29 29 30 30 :command:`ST_AsGeoJSON(geometry)` 31 Ret ourne une géométrie au format "standard" `GeoJSON <http://geojson.org>`_.31 Returns a geometry to a standard `GeoJSON <http://geojson.org>`_ format. 32 32 33 Measure s33 Measurements 34 34 ------------ 35 35 36 36 :command:`ST_Area(geometry)` 37 Ret ourne l'aire d'une géométrie dans l'unité du systÚme de références spatiales.37 Returns the area of the geometry in the units of the spatial reference system. 38 38 39 39 :command:`ST_Length(geometry)` 40 Ret ourne la longueur de la géométrie dans l'unité du systÚme de références spatiales.40 Returns the length of the geometry in the units of the spatial reference system. 41 41 42 42 :command:`ST_Perimeter(geometry)` 43 Ret ourne le périmétre de la géométrie dans l'unité du systÚme de références spatiales.43 Returns the perimeter of the geometry in the units of the spatial reference system. 44 44 45 45 :command:`ST_NumPoints(linestring)` 46 Ret ourne le nombre de sommets dans une ligne.46 Returns the number of vertices in a linestring. 47 47 48 48 :command:`ST_NumRings(polygon)` 49 Ret ourne le nombre de contours dans un polygone.49 Returns the number of rings in a polygon. 50 50 51 51 :command:`ST_NumGeometries(geometry)` 52 Ret ourne le nombre de géométries dans une collections de géométries.52 Returns the number of geometries in a geometry collection. 53 53 54 Relations 54 Relationships 55 55 ------------- 56 56 57 57 :command:`ST_Distance(geometry, geometry)` 58 Ret ourne la distance entre deux géométries dans l'unité du systÚme de références spatiales.58 Returns the distance between two geometries in the units of the spatial reference system. 59 59 60 60 :command:`ST_DWithin(geometry, geometry, radius)` 61 Ret ourne vrai si les géométries sont distant d'un rayon de l'autre, sinon faux.61 Returns true if the geometries are within the radius distance of one another, otherwise false. 62 62 63 63 :command:`ST_Intersects(geometry, geometry)` 64 Ret ourne vrai si les géométries sont disjointes, sinon faux.64 Returns true if the geometries are not disjoint, otherwise false. 65 65 66 66 :command:`ST_Contains(geometry, geometry)` 67 Ret ourne vrai si la premiÚre géométrie est totalement contenu dans la seconde, sinon faux.67 Returns true if the first geometry fully contains the second geometry, otherwise false. 68 68 69 69 :command:`ST_Crosses(geometry, geometry)` 70 Ret ourne vrai si une ligne ou les contours d'un polygone croisent une ligne ou un contour de polygone, sinon faux.70 Returns true if a line or polygon boundary crosses another line or polygon boundary, otherwise false. -
/trunk/workshop-foss4g/installation.rst
r61 r1 1 1 .. _installation: 2 2 3 Partie 2: Installation3 Section 2: Installation 4 4 ======================= 5 5 6 Nous utiliserons OpenGeo Suite comme application d'installation, car celle-ci contient PostGIS/PostgreSQL dans un seul outil d'installation pour Windows, Apple OS/X et Linux. La suite contient aussi GeoServer, OpenLayers et d'autres outils de visualisations sur le web.6 We will be using the OpenGeo Suite as our software package, as it includes PostGIS/PostgreSQL in a single fast installation for Windows, Apple OS/X, and Linux. The Suite also includes GeoServer, OpenLayers, and a number of web visualization utilities. 7 7 8 8 .. note:: 9 9 10 Si vous souhaitez installer simplement PostgreSQL, cela peut se faire en téléchargeant directement le code source ou les binaires de PostgreSQL sur le site du projet http://postgresql.org/download/. AprÚs avoir installé PostgreSQL, utilisez l'outil "StackBuilder" pour ajouter l'extension PostGIS à votre installation.10 If you want to install just PostgreSQL, it can also be downloaded directly as source code or binary from the PostgreSQL project site: http://postgresql.org/download/. After installing PostgreSQL, use the "StackBuilder" utility to add the PostGIS extension. 11 11 12 .. note:: 12 .. note:: 13 13 14 Les indications précises de ce document sont propre à Windows, mais l'installation sous OS/X est largement similaire. Une fois la Suite installée, les instructions relatives au systÚme d'exploitation devraient être identiques.14 The precise directions in this document are for Windows, but for OS/X the installation is largely the same. Once the Suite is installed, the directions for both operating systems should be almost identical. 15 15 16 #. Dans le répertoire :file:`postgisintro\\software\\` vous trouverez l'installeur de OpenGeo Suite nommé : :file:`opengeosuite-2.4.3.exe` (sur OS/X, :file:`opengeosuite-2.4.3.dmg`). Double cliquez sur cet exécutable pour le lancer.16 #. In the directory :file:`postgisintro\\software\\` you will find the OpenGeo Suite installer entitled :file:`opengeosuite-2.4.3.exe` (on OS/X, :file:`opengeosuite-2.4.3.dmg`). Double click to execute. 17 17 18 #. Appréciez le message de courtoisie d'OpenGeo, puis cliquez sur**Next**.18 #. Enjoy the warm welcome, courtesy of OpenGeo, then click **Next**. 19 19 20 20 .. image:: ./screenshots/install_01.png 21 21 22 22 23 #. OpenGeo Suite est publiée sous licence GPL, ce qui est précisé dans la fenêtre de license. Cliquez sur**I Agree**.23 #. The OpenGeo Suite is licensed under the GNU GPL, which is reproduced on the licensing page. Click **I Agree**. 24 24 25 25 .. image:: ./screenshots/install_02.png 26 26 27 27 28 #. Le répertoire où OpenGeo Suite sera installé est généralement le répertoire ``C:\Program Files\``. Les données seront placées dans le répertoire personnel de votre utilisateur, dans le répertoire :file:`.opengeo`. Cliquez sur**Next**.28 #. The directory where the OpenGeo Suite will reside is the usual ``C:\Program Files\`` location. The data will be placed in your home directory, under the :file:`.opengeo` directory. Click **Next**. 29 29 30 30 .. image:: ./screenshots/install_03.png 31 31 32 32 33 #. L'installeur créera un certain nombre de raccourcis dans le répertoire OpenGeo du menu Démarrer. Cliquez sur**Next**.33 #. The installer will create a number of shortcuts in the OpenGeo folder in the Start Menu. Click **Next**. 34 34 35 35 .. image:: ./screenshots/install_04.png 36 36 37 37 38 #. Tous les composants de la Suite sont obligatoires à ce niveau. Cliquez sur**Next**.38 #. All the components of the Suite are mandatory at this point. Click **Next**. 39 39 40 40 .. image:: ./screenshots/install_05.png 41 41 42 42 43 #. Prêt à installer ! Cliquez sur**Install**.43 #. Ready for install! Click **Install**. 44 44 45 45 .. image:: ./screenshots/install_06.png 46 46 47 47 48 #. Le processus d'installation prendra quelquesminutes.48 #. The installation process will run for a couple of minutes. 49 49 50 50 .. image:: ./screenshots/install_07.png 51 51 52 52 53 #. Lorsque l'installation est terminée, lancez le Dashboard pour commencer la partie suivante de ces travaux pratiques ! Cliquez sur**Finish**.53 #. When the installation is complete, launch the Dashboard to start the next section of the workshop! Click **Finish**. 54 54 55 55 .. image:: ./screenshots/install_08.png 56 56 57 -
/trunk/workshop-foss4g/creating_db.rst
r61 r1 1 1 .. _creating_db: 2 2 3 Partie 3 : Créer une base de données spatiales 4 ====================================== =========3 Section 3: Creating a Spatial Database 4 ====================================== 5 5 6 Le Dashboard etPgAdmin7 ----------------------- 6 The Dashboard and PgAdmin 7 ------------------------- 8 8 9 Le "Dashboard" est une application centralisant les accÚs aux différentes parties de l'openGeo Suite.9 The "Dashboard" is the central application to access all portions of the OpenGeo Suite. 10 10 11 Lorsque vous démarrez le dashboard pour la premiÚre fois, il vous fournit une indication quand au mot de passe par défaut pour accéder ÃGeoServer.11 When you first start the dashboard, it provides a reminder about the default password for accessing GeoServer. 12 12 13 13 .. image:: ./screenshots/dashboard_01.png … … 15 15 .. note:: 16 16 17 La base de données PostGIS a été installée sans la moindre restriction d'accÚs pour les utilisateurs locaux (les utilisateurs se connectant sur la même machine que celle faisant tourner le serveur de base de données). Cela signifie qu'il acceptera *tout* les mots de passe que vous fournirez. Si vous devez vous connecter depuis un ordinateur distant, le mot de passe pour l'utilisateur ``postgres`` a utiliser est :``postgres``.17 The PostGIS database has been installed with unrestricted access for local users (users connecting from the same machine as the database is running). That means that it will accept *any* password you provide. If you need to connect from a remote computer, the password for the ``postgres`` user has been set to ``postgres``. 18 18 19 Pour ces travaux pratiques, nous n'utilserons que les parties de la section "PostGIS" du Dashboard.19 For this workshop, we will be using the entries under the "PostGIS" section of the Dashboard almost exclusively. 20 20 21 #. PremiÚrement, nous devons démarrer le serveur de base de données PostGIS. Cliquez sur le bouton vert **Start** en haut à droite de la fenêtre duDashboard.21 #. First, we need to start up PostGIS. Click the green **Start** button at the top right corner of the Dashboard. 22 22 23 #. La premiÚre fois que la Suite se démarre, elle initialise un espace de données et met en place des modÚles de bases de données. Ceci peut prendre quelques minutes. Une fois la Suite lancée, vous pouvez cliquer sur l'option **Manage** dans le composant *PostGIS* pour lancer l'outil pgAdmin.23 #. The first time the Suite starts, it initializes a data area and sets up template databases. This can take a couple minutes. Once the Suite has started, you can click the **Manage** option under the *PostGIS* component to start the pgAdmin utility. 24 24 25 25 .. image:: ./screenshots/dashboard_02.png 26 27 .. note:: 28 29 PostgreSQL has a number of administrative front-ends. The primary is `psql <http://www.postgresql.org/docs/8.1/static/app-psql.html>`_ a command-line tool for entering SQL queries. Another popular PostgreSQL front-end is the free and open source graphical tool `pgAdmin <http://www.pgadmin.org/>`_. All queries done in pgAdmin can also be done on the command line with psql. 26 30 27 .. note:: 28 29 PostgreSQL dispose de nombreux outils d'administration différents. Le premier est `psql <http://www.postgresql.org/docs/8.1/static/app-psql.html>`_ un outil en ligne de commande permettant de saisir des requêtes SQL. Un autre outil d'administation populaire est l'outil graphique libre et gratuit `pgAdmin <http://www.pgadmin.org/>`_. Toutes les requêtes exécutées depuis pgAdmin peuvent aussi être utilisées depuis la ligne de commande avec psql. 30 31 #. Si c'est la premiÚre fois que vous lancez pgAdmin, vous devriez avoir une entrée du type **PostGIS (localhost:54321)** déjà configurée dans pgAdmin. Double cliquez sur cet élément, et entrez le mot de passe de votre choix pour vous connecter au serveur. 31 #. If this is the first time you have run pgAdmin, you should have a server entry for **PostGIS (localhost:54321)** already configured in pgAdmin. Double click the entry, and enter anything you like at the password prompt to connect to the database. 32 32 33 33 .. image:: ./screenshots/pgadmin_01.png … … 35 35 .. note:: 36 36 37 Si vous aviez déjà une installation pgAdmin sur votre ordinateur, vous n'aurez pas l'entrée **(localhost:54321)**. Vous devrez donc créer une nouvelle connexion. Allez dans *File > Add Server*, puis enregistrez un nouveau serveur pour **localhost** avec le port **54321** (notez que numéro de port n'est pas standard) afin de vous connecter au serveur PostGIS installé à l'aide de l'OpenGeo Suite.37 If you have a previous installation of PgAdmin on your computer, you will not have an entry for **(localhost:54321)**. You will need to create a new connection. Go to *File > Add Server*, and register a new server at **localhost** and port **54321** (note the non-standard port number) in order to connect to the PostGIS bundled with the OpenGeo Suite. 38 38 39 Créer une base de données 40 ------------------------- 39 Creating a Database 40 ------------------- 41 PostgreSQL has the notion of a **template database** that can be used to initialize a new database. The new database automatically gets a copy of everything from the template. When you installed PostGIS, a spatially enabled database called ``template_postgis`` was created. If we use ``template_postgis`` as a template when creating our new database, the new database will be spatially enabled. 41 42 42 PostgreSQL fournit ce que l'on appelle des modÚles de bases de données qui peuvent être utilisés lors de la création d'une nouvelle base. Cette nouvelle base contiendra alors une copie de tout ce qui est présent dans le modÚle. Lorsque vous installez PostGIS, une base de données appelée ``template_postgis`` a été crée. Si nous utilisons ``template_postgis`` comme modÚle lors de la création de notre nouvelle base, la nouvelle base sera une base de données spatiales.43 #. Open the Databases tree item and have a look at the available databases. The ``postgres`` database is the user database for the default postgres user and is not too interesting to us. The ``template_postgis`` database is what we are going to use to create spatial databases. 43 44 44 #. Ouvrez l'arbre des bases de données et regardez quelles sont les bases de données disponibles. La base ``postgres`` est la base de l'utilisateur (par défaut l'utilisateur postgres, donc pas trÚs intéressante pour nous). La base ``template_postgis`` est celle que nous utiliserons pour créer des bases de données spatiales. 45 46 #. Cliquez avec le clic droit sur l'élément ``Databases`` et sélectionnez ``New Database``. 45 #. Right-click on the ``Databases`` item and select ``New Database``. 47 46 48 47 .. image:: ./screenshots/pgadmin_02.png 49 48 50 .. note:: Si vous recevez un message d'erreur indiquant que la base de données (``template_postgis``) est utilisée par d'autre utilisateurs, cela signifie que vous l'avez activé par inadvertance. Utilisez alors le clic droit sur l'élément ``PostGIS (localhost:54321)`` puis sélectionnez ``Disconnect``. Double cliquez sur le même élément pour vous reconnecter et essayez à nouveau.49 .. note:: If you receive an error indicating that the source database (``template_postgis``) is being accessed by other users, this is likely because you still have it selected. Right-click on the ``PostGIS (localhost:54321)`` item and select ``Disconnect``. Double-click the same item to reconnect and try again. 51 50 52 #. Remplissez le formulaire ``New Database`` puis cliquez sur **OK**.51 #. Fill in the ``New Database`` form as shown below and click **OK**. 53 52 54 53 .. list-table:: … … 65 64 .. image:: ./screenshots/pgadmin_03.png 66 65 67 #. S électionnez la nouvelle base de données ``nyc`` et ouvrez-la pour consulter son contenu. Vous verrez le schéma ``public``, et sous cela un ensemble de tables de métadonnées spécifiques à PostGIS -- ``geometry_columns`` et``spatial_ref_sys``.66 #. Select the new ``nyc`` database and open it up to display the tree of objects. You'll see the ``public`` schema, and under that a couple of PostGIS-specific metadata tables -- ``geometry_columns`` and ``spatial_ref_sys``. 68 67 69 68 .. image:: ./screenshots/pgadmin_04.png 70 69 71 #. Cli quez sur le bouton SQL query comme présenté ci-dessous (ou allez dans*Tools > Query Tool*).70 #. Click on the SQL query button indicated below (or go to *Tools > Query Tool*). 72 71 73 72 .. image:: ./screenshots/pgadmin_05.png 74 73 75 #. Saisissez la requête suivante dans le champ prévu à cet effet:74 #. Enter the following query into the query text field: 76 75 77 76 .. code-block:: sql … … 80 79 81 80 .. note:: 82 C'est notre premiÚre requête SQL. ``postgis_full_version()`` est une fonction d'administration qui renvoie le numéro de version et les options de configuration utilisées lors de la compilation. 83 84 #. Cliquez sur le bouton **Play** dans la barre d'outils (ou utilisez la touche **F5**) pour "exécuter la requête." La requête retournera la chaîne de caractÚres suivante, confirmant que PostGIS est correctement activé dans la base de données. 81 82 This is our first SQL query. ``postgis_full_version()`` is management function that returns version and build configuration. 83 84 #. Click the **Play** button in the toolbar (or press **F5**) to "Execute the query." The query will return the following string, confirming that PostGIS is properly enabled in the database. 85 85 86 86 .. image:: ./screenshots/pgadmin_06.png 87 88 You have successfully created a PostGIS spatial database!! 87 89 88 Vous venez de créer une base de données PostGIS avec succÚs ! 90 Function List 91 ------------- 89 92 90 Liste des fonctions 91 ------------------- 92 93 `PostGIS_Full_Version <http://postgis.org/documentation/manual-svn/PostGIS_Full_Version.html>`_: Retourne les informations complÚtes relatives à la version et aux options de compilation de PostGIS. 94 93 `PostGIS_Full_Version <http://postgis.org/documentation/manual-svn/PostGIS_Full_Version.html>`_: Reports full postgis version and build configuration info. -
/trunk/workshop-foss4g/about_data.rst
r61 r1 1 1 .. _about_data: 2 2 3 Partie 5 : A propos de nos données 4 ========================= =========3 Section 5: About our data 4 ========================= 5 5 6 Les données utilisées dans ces travaux pratiques sont quatre shapefiles de la ville de New York, et une table attributaire des variables socio-démographiques de la ville. Nous les avons charger sous forme de tables PostGIS et nous ajouterons les données socio-démographiques plus tard.6 The data for this workshop is four shapefiles for New York City, and one attribute table of sociodemographic variables. We've loaded our shapefiles as PostGIS tables and will add sociodemographic data later in the workshop. 7 7 8 Cette partie fournit le nombre d'enregistrements et les attributs de chacun de nos ensembles de données. Ces valeurs attributaires et les relations sont essentielles pour nos futures analyses. 8 The following describes the number of records and table attributes for each of our datasets. These attribute values and relationships are fundamental to our future analysis. 9 9 10 Pour visualiser la nature de vos tables depuis pgAdmin, cliquez avec le bouton droit sur une table et sélectionnez **Properties**. Vous trouverez un résumé des propriétés de la table, incluant la liste des attributs d'une table dans l'onglet **Columns**.10 To explore the nature of your tables in pgAdmin, right-click a highlighted table and select **Properties**. You will find a summary of table properties, including a list of table attributes within the **Columns** tab. 11 11 12 12 nyc_census_blocks 13 13 ----------------- 14 14 15 Un bloc ressencé est la plus petite entité géographique pour laquelle un ressencement est raporté. Toutes les couches représentant les niveaux suppérieurs (régions, zones de métro, comtés) peuvent être contruites à partir de ces blocs. Nous avons attaché des données démographiques aux blocs.15 A census block is the smallest geography for which census data is reported. All higher level census geographies (block groups, tracts, metro areas, counties, etc) can be built from unions of census blocks. We have attached some demographic data to our collection of blocks. 16 16 17 N ombre d'enregistrements: 3659217 Number of records: 36592 18 18 19 19 .. list-table:: … … 21 21 22 22 * - **blkid** 23 - Un code à 15 chiffres qui permet d'identifier de maniÚre unique chaque bloc**block**. Eg: 36005000100900023 - A 15-digit code that uniquely identifies every census **block**. Eg: 360050001009000 24 24 * - **popn_total** 25 - Nombre total de personnes dans le bloc25 - Total number of people in the census block 26 26 * - **popn_white** 27 - N ombre de personnes se déclarant comme de couleur blanche27 - Number of people self-identifying as "White" in the block 28 28 * - **popn_black** 29 - N ombre de personnes se déclarant comme de couleur noire29 - Number of people self-identifying as "Black" in the block 30 30 * - **popn_nativ** 31 - N ombre de personnes se déclarant comme natif d'amérique du nord31 - Number of people self-identifying as "Native American" in the block 32 32 * - **popn_asian** 33 - N ombre de personnes se déclarant comme asiatique33 - Number of people self-identifying as "Asian" in the block 34 34 * - **popn_other** 35 - N ombre de personnes se déclarant comme faisant partie d'une autre catégorie35 - Number of people self-identifying with other categories in the block 36 36 * - **hous_total** 37 - N ombre de piÚces dans le bloc37 - Number of housing units in the block 38 38 * - **hous_own** 39 - N ombre de propriétaires occupant le bloc39 - Number of owner-occupied housing units in the block 40 40 * - **hous_rent** 41 - N ombre de locataires occupant le bloc41 - Number of renter-occupied housing units in the block 42 42 * - **boroname** 43 - N om du quartier (Manhattan, The Bronx, Brooklyn, Staten Island, Queens)43 - Name of the New York borough. Manhattan, The Bronx, Brooklyn, Staten Island, Queens 44 44 * - **the_geom** 45 - Polygon e représentant les contours d'un bloc45 - Polygon boundary of the block 46 46 47 47 .. figure:: ./screenshots/nyc_census_blocks.png 48 48 49 * Pourcentage de la population qui est de couleur noire*49 *Black population as a percentage of Total Population* 50 50 51 51 .. note:: 52 52 53 Pour disposer des données d'un recensement dans votre SIG, vous avez besoin de joindre deux informations: Les données socio-démographiques et les limites géographiques des blocs/quartiers. Il existe plusieurs moyen de se les procurer, dans notre cas elles ont été récupérées sur le site Internet duCensus Bureau's `American FactFinder <http://factfinder.census.gov>`_.53 To get census data into GIS, you need to join two pieces of information: the actual data (text), and the boundary files (spatial). There are many options for getting the data, including downloading data and boundaries from the Census Bureau's `American FactFinder <http://factfinder.census.gov>`_. 54 54 55 55 nyc_neighborhoods 56 56 ----------------- 57 57 58 Les quartiers de New York58 New York has a rich history of neighborhood names and extent. Neighborhoods are social constructs that do not follow lines laid down by the government. For example, the Brooklyn neighborhoods of Carroll Gardens, Red Hook, and Cobble Hill were once collectively known as "South Brooklyn." And now, depending on which real estate agent you talk to, the same four blocks in the-neighborhood-formerly-known-as-Red-Hook can be referred to as Columbia Heights, Carroll Gardens West, or Red Hook! 59 59 60 N ombre d'enregistrements: 12960 Number of records: 129 61 61 62 62 .. list-table:: … … 64 64 65 65 * - **name** 66 - N om du quartier66 - Name of the neighborhood 67 67 * - **boroname** 68 - Name de la section dans New York (Manhattan, The Bronx, Brooklyn, Staten Island, Queens)68 - Name of the New York borough. Manhattan, The Bronx, Brooklyn, Staten Island, Queens 69 69 * - **the_geom** 70 - Limite polygonale du quartier70 - Polygon boundary of the neighborhood 71 71 72 72 .. figure:: ./screenshots/nyc_neighborhoods.png 73 73 74 * Les quartiers de New York*74 *The neighborhoods of New York City* 75 75 76 76 nyc_streets 77 77 ----------- 78 78 79 Les rues de New York 79 The street centerlines form the transportation network of the city. These streets have been flagged with types in order to distinguish between such thoroughfares as back alleys, arterial streets, freeways, and smaller streets. Desirable areas to live might be on residential streets rather than next to a freeway. 80 80 81 N ombre d'enregistrements: 1909181 Number of records: 19091 82 82 83 83 .. list-table:: … … 85 85 86 86 * - **name** 87 - N om de la rue87 - Name of the street 88 88 * - **oneway** 89 - Est-ce que la rue est à sens unique? "yes" = yes, "" = no89 - Is the street one-way? "yes" = yes, "" = no 90 90 * - **type** 91 - Type de voie (Cf: primary, secondary, residential, motorway)91 - Road type. Eg. primary, secondary, residential, motorway 92 92 * - **the_geom** 93 - Li gne du centre de la rue.93 - Linear centerline of the street 94 94 95 95 .. figure:: ./screenshots/nyc_streets.png 96 96 97 * Les rues de New York (les rues principales apparaissent en rouge)*97 *The streets of New York City. Major roads are in red.* 98 98 99 99 … … 101 101 ------------------- 102 102 103 Les stations de métro de New York 103 The subway stations link the upper world where people live to the invisible network of subways beneath. As portals to the public transportation system, station locations help determine how easy it is for different people to enter the subway system. 104 104 105 N ombre d'enregistrements: 491105 Number of records: 491 106 106 107 107 .. list-table:: … … 109 109 110 110 * - **name** 111 - N om de lastation111 - Name of the station 112 112 * - **borough** 113 - N om de la section dans New York (Manhattan, The Bronx, Brooklyn, Staten Island, Queens)113 - Name of the New York borough. Manhattan, The Bronx, Brooklyn, Staten Island, Queens 114 114 * - **routes** 115 - Lignes de métro passant par cettestation115 - Subway lines that run through this station 116 116 * - **transfers** 117 - Li gnes de métro accessibles depuis cettestation117 - Lines you can transfer to via this station 118 118 * - **express** 119 - Stations ou le train express s'arrête, "express" = yes, "" = no119 - Stations where express trains stop, "express" = yes, "" = no 120 120 * - **the_geom** 121 - Localisation ponctuelle de lastation121 - Point location of the station 122 122 123 123 .. figure:: ./screenshots/nyc_subway_stations.png 124 124 125 * Localisation ponctuelle des stations de métro de New York*125 *Point locations for New York City subway stations* 126 126 127 127 nyc_census_sociodata 128 128 -------------------- 129 129 130 Données socio-démographiques de la ville de New York 130 There is a rich collection of social-economic data collected during the census process, but only at the larger geography level of census tract. Census blocks combine to form census tracts (and block groups). We have collected some social-economic at a census tract level to answer some of these more interesting questions about New York City. 131 131 132 132 .. note:: 133 133 134 La donnée ``nyc_census_sociodata`` est une table attributaire. Nous devrons nous connecter aux géométries correspondant à la zone du recenssement avant de conduire toute analyse spatiale .135 134 The ``nyc_census_sociodata`` is a data table. We will need to connect it to Census geographies before conducting any spatial analysis. 135 136 136 .. list-table:: 137 137 :widths: 20 80 138 138 139 139 * - **tractid** 140 - Un code à 11 chiffre qui identifie chaque secteur de recessement.**tract**. Eg: 36005000100140 - An 11-digit code that uniquely identifies every census **tract**. Eg: 36005000100 141 141 * - **transit_total** 142 - N ombre de travailleurs dans le secteur142 - Number of workers in the tract 143 143 * - **transit_public** 144 - N ombre de travailleurs dans le secteur utilisant les transports en commun144 - Number of workers in the tract who take public transit 145 145 * - **transit_private** 146 - N ombre de travailleurs dans le secteur utilisant un véhicule privé146 - Number of workers in the tract who use private automobiles / motorcycles 147 147 * - **transit_other** 148 - N ombre de travailleurs dans le secteur utilisant un autre moyen de transport148 - Number of workers in the tract who use other forms like walking / biking 149 149 * - **transit_time_mins** 150 - Nombre total de minutes passées dans les transports par l'ensemble des travailleurs du secteur(minutes)150 - Total number of minutes spent in transit by all workers in the tract (minutes) 151 151 * - **family_count** 152 - N ombre de familles dans le secteur152 - Number of familes in the tract 153 153 * - **family_income_median** 154 - Revenu médiant par famille du secteur(dollars)154 - Median family income in the tract (dollars) 155 155 * - **family_income_aggregate** 156 - Revenu total de toutes les familles du secteur(dollars)156 - Total income of all families in the tract (dollars) 157 157 * - **edu_total** 158 - N ombre de personnes ayant un parcours scolaire158 - Number of people with educational history 159 159 * - **edu_no_highschool_dipl** 160 - N ombre de personnes n'ayant pas de diplÃŽme d'éducation secondaire160 - Number of people with no highschool diploma 161 161 * - **edu_highschool_dipl** 162 - N ombre de personnes ayant un diplÃŽme d'éducation secondaire162 - Number of people with highschool diploma and no further education 163 163 * - **edu_college_dipl** 164 - N ombre de personnes ayant un diplÃŽme de lycée164 - Number of people with college diploma and no further education 165 165 * - **edu_graduate_dipl** 166 - N ombre de personnes ayant un diplÃŽme de collÚge166 - Number of people with graduate school diploma 167 167 -
/trunk/workshop-foss4g/glossary.rst
r61 r1 1 1 .. _glossary: 2 2 3 A nnexes B : Glossaire3 Appendix B: Glossary 4 4 ==================== 5 5 … … 7 7 8 8 CRS 9 Un "systÚme de références spatiales". La combinaison d'un systÚme de coordonnée géographiques et un systÚme de projection.9 A "coordinate reference system". The combination of a geographic coordinate system and a projected coordinate system. 10 10 11 11 GDAL 12 `Geospatial Data Abstraction Library <http://gdal.org>`_, prono ncé "GéDAL", une bibliothÚque open source permettant d'accéder aux données rasters supportant un grand nombre de formats, utilisé largement à la fois dans les applications open source et propriétaires.12 `Geospatial Data Abstraction Library <http://gdal.org>`_, pronounced "GOO-duhl", an open source raster access library with support for a large number of formats, used widely in both open source and proprietary software. 13 13 14 14 GeoJSON 15 "Javascript Object Notation", un format texte qui est trÚs rapide et qui permet de représenter des objet JavaScript. En spatial, la spécification étendue `GeoJSON <http://geojson.org>`_ est courramment utilisée.15 "Javascript Object Notation", a text format that is very fast to parse in Javascript virtual machines. In spatial, the extended specification for `GeoJSON <http://geojson.org>`_ is commonly used. 16 16 17 SIG18 ` SystÚme d'Information Géographique <http://en.wikipedia.org/wiki/Geographic_information_system>`_ capture, stock, analyse, gÚre, et présente les données qui sont reliées à la zone géographique.17 GIS 18 `Geographic information system <http://en.wikipedia.org/wiki/Geographic_information_system>`_ or geographical information system captures, stores, analyzes, manages, and presents data that is linked to location. 19 19 20 20 GML 21 `Geography Markup Language <http://www.opengeospatial.org/standards/gml>`_. Le GML est un format standard XML :term:`OGC` pour représenter les données géographiques.21 `Geography Markup Language <http://www.opengeospatial.org/standards/gml>`_. GML is the :term:`OGC` standard XML format for representing spatial feature information. 22 22 23 23 JSON 24 "Javascript Object Notation", un format text qui est trÚs rapide permettant de stocker les objets JavaScript. Au niveau spatial, la spécification étendu `GeoJSON <http://geojson.org>`_ est courramment utilisé.24 "Javascript Object Notation", a text format that is very fast to parse in Javascript virtual machines. In spatial, the extended specification for `GeoJSON <http://geojson.org>`_ is commonly used. 25 25 26 26 JSTL 27 "JavaServer Page Template Library", est une bibliothÚque pour :term:`JSP` qui encapsule plusieurs fonctionalités de bases géré en JSP (requête de bases de données, itération, conditionnel) dans un syntaxe tiÚrce.27 "JavaServer Page Template Library", a tag library for :term:`JSP` that encapsulates many of the standard functions handled in JSP (database queries, iteration, conditionals) into a terse syntax. 28 28 29 29 JSP 30 "JavaServer Pages" est un systÚme de script pour les serveur d'applications Java qui permet de mixer du code XML et du code Java.30 "JavaServer Pages" a scripting system for Java server applications that allows the interleaving of markup and Java procedural code. 31 31 32 32 KML 33 "Keyhole Markup Language", le format XML utilisé par Google Earth. Google Earth. Il fût à l'origine développé par la société "Keyhole", ce qui expliqe sa présence (maintenant obscure) dans le nom du format.33 "Keyhole Markup Language", the spatial XML format used by Google Earth. Google Earth was originally written by a company named "Keyhole", hence the (now obscure) reference in the name. 34 34 35 35 OGC 36 Open Geospatial Consortium <http://opengeospatial.org/> (OGC) est une organisation qui développent des spécifications pour les services spatiaux.36 The Open Geospatial Consortium <http://opengeospatial.org/> (OGC) is a standards organization that develops specifications for geospatial services. 37 37 38 38 OSGeo 39 Open Source Geospatial Foundation <http://osgeo.org> (OSGeo) est une association à but non lucratif dédié à la promotion et au support des logiciels cartographiques open source.39 The Open Source Geospatial Foundation <http://osgeo.org> (OSGeo) is a non-profit foundation dedicated to the promotion and support of open source geospatial software. 40 40 41 41 SFSQL 42 La spécification `Simple Features for SQL <http://www.opengeospatial.org/standards/sfs>`_ (SFSQL) de l':term:`OGC` définit les types et les fonctions qui doivent être disponibles dans une base de données spatiales.42 The `Simple Features for SQL <http://www.opengeospatial.org/standards/sfs>`_ (SFSQL) specification from the :term:`OGC` defines the types and functions that make up a standard spatial database. 43 43 44 44 SLD 45 Les spécifications `Styled Layer Descriptor <http://www.opengeospatial.org/standards/sld>`_ (SLD) de l':term:`OGC` définissent un format permettant de décrire la maniÚre d'afficher des donnéesvectorielles.45 The `Styled Layer Descriptor <http://www.opengeospatial.org/standards/sld>`_ (SLD) specification from the :term:`OGC` defines an format for describing cartographic rendering of vector features. 46 46 47 47 SRID 48 "Spatial reference ID" est un identifiant unique assigné à un systÚme de coordonnées géographique particulier. La table PostGIS **spatial_ref_sys** contient un loarge collection de valeurs de SRID connus.48 "Spatial reference ID" a unique number assigned to a particular "coordinate reference system". The PostGIS table **spatial_ref_sys** contains a large collection of well-known srid values and text representations of the coordinate reference systems. 49 49 50 50 SQL 51 "Structured query language" est un standard permettant de requêter les bases de données relationnelle. Référence http://en.wikipedia.org/wiki/SQL.51 "Structured query language" is the standard means for querying relational databases. See http://en.wikipedia.org/wiki/SQL. 52 52 53 53 SQL/MM … … 55 55 56 56 SVG 57 "Scalable vector graphics" est une famille de spécifications basé sur le format XML pour décrire des objet graphiques en 2 dimensions, aussi bien statiques que dynamiques (par exemple interactive ou animé). Réference :http://en.wikipedia.org/wiki/Scalable_Vector_Graphics.57 "Scalable vector graphics" is a family of specifications of an XML-based file format for describing two-dimensional vector graphics, both static and dynamic (i.e. interactive or animated). See http://en.wikipedia.org/wiki/Scalable_Vector_Graphics. 58 58 59 59 WFS 60 Les spécifications `Web Feature Service <http://www.opengeospatial.org/standards/wfs>`_ (WFS) de l':term:`OGC` définit une interface pour lire et écrire des données géographiques à travers internet.60 The `Web Feature Service <http://www.opengeospatial.org/standards/wfs>`_ (WFS) specification from the :term:`OGC` defines an interface for reading and writing geographic features across the web. 61 61 62 62 WMS 63 Les spécifications `Web Map Service <http://www.opengeospatial.org/standards/wms>`_ (WMS) de l':term:`OGC` définit une interface pour requêter une carte à travers internet.63 The `Web Map Service <http://www.opengeospatial.org/standards/wms>`_ (WMS) specification from the :term:`OGC` defines an interface for requesting rendered map images across the web. 64 64 65 65 WKB 66 "Well-known binary". Fait référence à la représentation binaire desgéométries comme décrit dans les spécifications Simple Features for SQL(:term:`SFSQL`).66 "Well-known binary". Refers to the binary representation of geometries described in the Simple Features for SQL specification (:term:`SFSQL`). 67 67 68 68 WKT 69 "Well-known text". Fait référence à la représentation textuelle de géométries, avec des chaînes commençant par "POINT", "LINESTRING", "POLYGON", etc. Il peut aussi faire référence à la représentation textuelle d'un :term:`CRS`, avec une chaîne commençant par "PROJCS", "GEOGCS", etc. Les représentations au format Well-known text sont des standards de l':term:`OGC`, mais n'ont pas leur propres documents de spécifications. La premiÚre description du WKT (pour les géométries et pour les CRS) apparaissent dans les spécifications :term:`SFSQL` 1.0.69 "Well-known text". Can refer either to the text representation of geometries, with strings starting "POINT", "LINESTRING", "POLYGON", etc. Or can refer to the text representation of a :term:`CRS`, with strings starting "PROJCS", "GEOGCS", etc. Well-known text representations are :term:`OGC` standards, but do not have their own specification documents. The first descriptions of WKT (for geometries and for CRS) appeared in the :term:`SFSQL` 1.0 specification. 70 70 71 71 -
/trunk/workshop-foss4g/tuning.rst
r61 r1 1 1 .. _tuning: 2 2 3 Partie 21 : Paramétrer PostgreSQL pour le spatial4 ========================================= ========3 Section 21: Tuning PostgreSQL for Spatial 4 ========================================= 5 5 6 PostgreSQL est une base de données trÚs versatile, capable de tourner dans des environnements ayant des ressources trÚs limités et partageant ces ressources avec un grand nombre d'autres applications. Afin d'assurer qu'il tournera convenablement dans ces environnements, la configuration par défaut est trÚs peu consomatrice de ressource mais terriblement innadapaté pour des bases de données hautes-performances en production. Ajoutez à cela le fait que les base de données spatiales ont différent type d'utilisation, et que les données sont généralement plus grandes que les autres types de données, vous en arriverez à la conclusion que les parÚtres par défaut ne sont pas approprié pour notre utilisasion.6 PostgreSQL is a very versatile database system, capable of running efficiently in very low-resource environments and environments shared with a variety of other applications. In order to ensure it will run properly for many different environments, the default configuration is very conservative and not terribly appropriate for a high-performance production database. Add the fact that geospatial databases have different usage patterns, and the data tend to consist of fewer, much larger records than non-geospatial databases, and you can see that the default configuration will not be totally appropriate for our purposes. 7 7 8 Tout ces paramÚtres de configuration peuvent être édités dans le fichier de configuration de la base de données : :file:`C:\\Documents and Settings\\%USER\\.opengeo\\pgdata\\%USER`. Le contenu du fichier est du texte et il peut donc être ouvert avec l'outils d'édition de fichiers de votre choix (Notepad par exemple). Les modifications apportées à ce fichier ne seront effectives que lors du redémarrage du serveur.8 All of these configuration parameters can edited in the database configuration file, :file:`C:\\Documents and Settings\\%USER\\.opengeo\\pgdata\\%USER`. This is a regular text file and can be edited using Notepad or any other text editor. The changes will not take effect until the server is restarted. 9 9 10 10 .. image:: ./tuning/conf01.png 11 11 12 Une façon simple d'éditer ce fichier de configuration est d'utiliser l'outils nommé : "Backend Configuration Editor". Depuis pgAdmin, allez dans *File > Open postgresql.conf...*. Il vous sera demandé le chemin du fichier, naviguez dans votre arborescence jusqu'au fichier:file:`C:\\Documents and Settings\\%USER\\.opengeo\\pgdata\\%USER`.12 An easier way of editing this configuration is by using the built-in "Backend Configuration Editor". In pgAdmin, go to *File > Open postgresql.conf...*. It will ask for the location of the file, and navigate to :file:`C:\\Documents and Settings\\%USER\\.opengeo\\pgdata\\%USER`. 13 13 14 14 .. image:: ./tuning/conf02.png … … 16 16 .. image:: ./tuning/conf03.png 17 17 18 Cette partie décrit certains des paramÚtres de configuration qui doivent être modifiés pour la mise ne place d'une base de données spatiale en production. Pour chaque partie, trouvez le bon paramÚtres dans la liste et double cliquez dessus pour l'éditer. Changez le champs *Value* par la valeur que nous recommendons, assurez-vous que le champs est bien activé pui cliquez sur**OK**.18 This section describes some of the configuration parameters that should be adjusted for a production-ready geospatial database. For each section, find the appropriate item in the list, double-click on the line to edit the configuration. Change the *Value* to the recommended value as described, make sure the item is *Enabled*, the click **OK**. 19 19 20 .. note:: Ces valeurs sont seulement celles que nous recommendons, chaque environnement differera et tester les différents paramétrages est toujours nécessaire pour s'assurer d'utiliser la configuration optimale. Mais dans cette partie nous vous fournissons un bon point de départ.20 .. note:: These values are recommendations only; each environment will differ and testing is required to determine the optimal configuration. But this section should get you off to a good start. 21 21 22 22 shared_buffers 23 23 -------------- 24 24 25 Alloue la quantité de mémoire que le serveur de bases de données utilise pour ses segments de mémoires partagées. Cela est partagé par tout les processus serveur, comme sont nom l'indique. La valeur par défaut est affligeante et inadaptée pour une base de données en production.25 Sets the amount of memory the database server uses for shared memory buffers. These are shared amongst the back-end processes, as the name suggests. The default values are typically woefully inadequate for production databases. 26 26 27 * Valeur par défaut* : typiquement32MB27 *Default value*: typically 32MB 28 28 29 * Valeur recommandée* : 75% de la mémoire de la base de données(500MB)29 *Recommended value*: 75% of database memory (500MB) 30 30 31 31 .. image:: ./tuning/conf04.png … … 34 34 -------- 35 35 36 D éfinit la quantité de mémoire que les opération interne d'ordonnancement et les tables de hachages peuvent consommer avec le serveur passe à des fichiers sur le disque. Cette valeur définit la mémoire disponible pour chaque opération complexe, les requêtes complexes peuvent avoir plusieurs ordres ou opération de hachage tournant en parallÚle, et chaque client s connecté peut exécuter une requête.36 Defines the amount of memory that internal sorting operations and hash tables can consume before the database switches to on-disk files. This value defines the available memory for each operation; complex queries may have several sort or hash operations running in parallel, and each connected session may be executing a query. 37 37 38 Vous devez donc considérer combient de connexions et quel complexité est attendu dans les requêtes avant d'augmenter cette valeur. Le bénéfice acquis par l'augmentation de cette valeur est que la plupart des opération de classification,dont les clause ORDER BY et DISTINCT, les jointures, les agrégation basé sur les hachages et l'exécution de requête imbriquées, pourront être réalisé sans avoir à passer par un stockage sur disque.38 As such you must consider how many connections and the complexity of expected queries before increasing this value. The benefit to increasing is that the processing of more of these operations, including ORDER BY, and DISTINCT clauses, merge and hash joins, hash-based aggregation and hash-based processing of subqueries, can be accomplished without incurring disk writes. 39 39 40 * Valeur par défaut*: 1MB40 *Default value*: 1MB 41 41 42 * Valeur recommandée*: 16MB42 *Recommended value*: 16MB 43 43 44 44 .. image:: ./tuning/conf05.png … … 47 47 -------------------- 48 48 49 D éfinit la quantité de mémoire utilisé pour les opération de maintenances, dont le néttoyage (VACUUM), les indexes et la création de clef étrangÚres. Comme ces opération sont courremment utilisées, la valeur par défaut devrait être acceptable. Ce paramÚtre peut être augmenté dynamiquement à l'exécution depuis une connexion au serveur avant l'exécution d'un grand nombre d'appels à :command:`CREATE INDEX` ou :command:`VACUUM` comme le montre la commande suivante.49 Defines the amount of memory used for maintenance operations, including vacuuming, index and foreign key creation. As these operations are not terribly common, the default value may be acceptable. This parameter can alternately be increased for a single session before the execution of a number of :command:`CREATE INDEX` or :command:`VACUUM` calls as shown below. 50 50 51 51 .. code-block:: sql … … 55 55 SET maintenance_work_mem TO '16MB'; 56 56 57 * Valeur par défaut*: 16MB57 *Default value*: 16MB 58 58 59 * Valeur recommendée*: 128MB59 *Recommended value*: 128MB 60 60 61 61 .. image:: ./tuning/conf06.png … … 64 64 ----------- 65 65 66 Définit la quantité de mémoire utilisé pour l'écriture des données dans le journal respectant la rÚgle du défaire (WAL). Elle indique que les informations pour annuler les effets d'une opération sur un objet doivent être écrites dans le journal en mémoire stable avant que l'objet modifié ne migre sur le disque. Cette rÚgle permet d'assurer l'intégrité des données lors d'une reprise aprÚs défaillance. En effet,il suffiré de lire le journal pour retrouver l'état de la base lors de sont arrêt brutal.66 Sets the amount of memory used for write-ahead log (WAL) data. Write-ahead logs provide a high-performance mechanism for insuring data-integrity. During each change command, the effects of the changes are written first to the WAL files and flushed to disk. Only once the WAL files have been flushed will the changes be written to the data files themselves. This allows the data files to be written to disk in an optimal and asynchronous manner while ensuring that, in the event of a crash, all data changes can be recovered from the WAL. 67 67 68 La taille de ce tampon nécessite simplement d'être suffisament grand pour stoquer les données WAL pour une seule transaction. Alors que la valeur par défaut est généralement siffisante, les données spatiales tendent à être plus large. Il est donc recommendé d'augmenter la taille spécifiée dans ce paramÚtre.68 The size of this buffer only needs to be large enough to hold WAL data for a single typical transaction. While the default value is often sufficient for most data, geospatial data tends to be much larger. Therefore, it is recommended to increase the size of this parameter. 69 69 70 * Valeur par défaut*: 64kB70 *Default value*: 64kB 71 71 72 * Valeur recommendée*: 1MB72 *Recommended value*: 1MB 73 73 74 74 .. image:: ./tuning/conf07.png … … 77 77 ------------------- 78 78 79 Cette valeur définit le nombre maximum de segements des journaux (typiquement 16MB) qui doit être remplit entre chaque point de reprises WAL. Un point de reprise WAL est une partie d'une séquence de transactions pour lequel on garanti que les fichiers de données ont été mis à jour avec toutes les requêtes précédent ce point. à ce moment-là toutes les pages sont punaisées sur le disque et les point de reprises sont écrit dans le fichier de journal. Cela permet au precessus de reprise aprÚs défaillance de trouver les dernierspoints de reprises et applique toute les lignes suivantes pour récupérer l'état des données avant la défaillance.79 This value sets the maximum number of log file segments (typically 16MB) that can be filled between automatic WAL checkpoints. A WAL checkpoint is a point in the sequence of WAL transactions at which it is guaranteed that the data files have been updated with all information before the checkpoint. At this time all dirty data pages are flushed to disk and a checkpoint record is written to the log file. This allows the crash recovery process to find the latest checkpoint record and apply all following log segments to complete the data recovery. 80 80 81 Ãtant donnée que les point de reprises nécessitent un punaisage de toutes le pages ayant été modifiée sur le disque, cela va créer une charge d'entrées/sorties significative. Le même arguement que précédemment s'applique ici, les données spatiales sont assez grandes pour contrebalancer l'optimisation de données non spatiales. Augmenter cette valeur limitera le nombre de points de reprise, mais impliquera un plus redémarrage en cas de défaillance.81 Because the checkpoint process requires the flushing of all dirty data pages to disk, it creates a significant I/O load. The same argument from above applies; geospatial data is large enough to unbalance non-geospatial optimizations. Increasing this value will prevent excessive checkpoints, though it may cause the server to restart more slowly in the event of a crash. 82 82 83 * Valeur par défaut*: 383 *Default value*: 3 84 84 85 * Valauer recommendée*: 685 *Recommended value*: 6 86 86 87 87 .. image:: ./tuning/conf08.png … … 90 90 ---------------- 91 91 92 Cette valeur sans unité représente le coût d'accÚs alléatoire au page du disque. Cete valeur est relative au autres paramÚtres de coût notemment l'accÚs séquentiel au pages, et le coût des opération processeur. Bien qu'il n'y ai pas de valeur magique ici, la valeur par défaut est généralement trop faible. Cette valeur peut être affectée dynamiquement par session en utilisant la commande ``SET random_page_cost TO 2.0``.92 This is a unit-less value that represents the cost of a random page access from disk. This value is relative to a number of other cost parameters including sequential page access, and cpu operation costs. While there is no magic bullet for this value, the default is generally conservative. This value can be set on a per-session basis using the ``SET random_page_cost TO 2.0`` command. 93 93 94 * Valeur par défaut*: 4.094 *Default value*: 4.0 95 95 96 * Valeur recommandée*: 2.096 *Recommended value*: 2.0 97 97 98 98 .. image:: ./tuning/conf09.png 99 99 100 100 seq_page_cost 101 101 ------------- 102 102 103 C'est une paramÚtre qui controle le coût des accÚs séquentiel au pages. Il n'est généralement pas nécessaire de modifier cette valeur maus la différence entre cette valeur et la valeurs ``random_page_cost`` affecte drastiquement le choix fait par le plannificateur de requêtes. Cette valeur peut aussi être affectée depuis une session.103 This is the parameter that controls the cost of a sequential page access. This value does not generally require adjustment but the difference between this value and ``random_page_cost`` greatly affects the choices made by the query planner. This value can also be set on a per-session basis. 104 104 105 * Valeur par défaut*: 1.0105 *Default value*: 1.0 106 106 107 * Valeur recommandée*: 1.0107 *Recommended value*: 1.0 108 108 109 109 .. image:: ./tuning/conf10.png 110 110 111 Re charger laconfiguration112 -------------------- ------111 Reload configuration 112 -------------------- 113 113 114 A prÚs avoir réalisé ces changements mentioné dans cette partie sauvez-les puis rechargez la configuration.114 After these changes are made, save changes and reload the configuration. 115 115 116 * Ceci se fait en cliquant avec le bouton droit sur le nom du serveur (``PostgreSQL 8.4 on localhost:54321``) depuis pgAdmin, selectionnez*Disconnect*.117 * Cli quez sur le bouton *Shutdown* depuis le Dashboard OpenGeo, puis cliquez sur*Start*.118 * Pour finir reconnectez-vous au serveur depuis pgAdmin (cliquez avec le bouton droit sur le serveur puis sélectionnez*Connect*).116 * This is done by right-clicking on the server (``PostgreSQL 8.4 on localhost:54321``) in pgAdmin, selecting to *Disconnect*. 117 * Clicking *Shutdown* in the OpenGeo Dashboard, then clicking *Start*. 118 * Finally reconnecting to the server in pgAdmin (right-click on the server and select *Connect*). 119 119 120 120
Note: See TracChangeset
for help on using the changeset viewer.