pygeoif-0.7/0000775000175100017510000000000013102646233015020 5ustar christianchristian00000000000000pygeoif-0.7/pygeoif.egg-info/0000775000175100017510000000000013102646233020154 5ustar christianchristian00000000000000pygeoif-0.7/pygeoif.egg-info/not-zip-safe0000664000175100017510000000000113102646233022402 0ustar christianchristian00000000000000 pygeoif-0.7/pygeoif.egg-info/SOURCES.txt0000664000175100017510000000054113102646233022040 0ustar christianchristian00000000000000MANIFEST.in README.rst setup.py docs/CONTRIBUTORS.txt docs/HISTORY.txt docs/LICENSE.GPL docs/LICENSE.txt pygeoif/__init__.py pygeoif/geometry.py pygeoif/test_main.py pygeoif.egg-info/PKG-INFO pygeoif.egg-info/SOURCES.txt pygeoif.egg-info/dependency_links.txt pygeoif.egg-info/entry_points.txt pygeoif.egg-info/not-zip-safe pygeoif.egg-info/top_level.txtpygeoif-0.7/pygeoif.egg-info/dependency_links.txt0000664000175100017510000000000113102646233024222 0ustar christianchristian00000000000000 pygeoif-0.7/pygeoif.egg-info/entry_points.txt0000664000175100017510000000004513102646233023451 0ustar christianchristian00000000000000 # -*- Entry points: -*- pygeoif-0.7/pygeoif.egg-info/top_level.txt0000664000175100017510000000001013102646233022675 0ustar christianchristian00000000000000pygeoif pygeoif-0.7/pygeoif.egg-info/PKG-INFO0000664000175100017510000003607213102646233021261 0ustar christianchristian00000000000000Metadata-Version: 1.1 Name: pygeoif Version: 0.7 Summary: A basic implementation of the __geo_interface__ Home-page: https://github.com/cleder/pygeoif/ Author: Christian Ledermann Author-email: christian.ledermann@gmail.com License: LGPL Description: Introduction ============ PyGeoIf provides a GeoJSON-like protocol for geo-spatial (GIS) vector data. see https://gist.github.com/2217756 Other Python programs and packages that you may have heard of already implement this protocol: * ArcPy http://help.arcgis.com/en/arcgisdesktop/ * descartes https://bitbucket.org/sgillies/descartes/ * geojson http://pypi.python.org/pypi/geojson/ * PySAL http://pysal.geodacenter.org/ * Shapely https://github.com/Toblerity/Shapely * pyshp https://pypi.python.org/pypi/pyshp So when you want to write your own geospatial library with support for this protocol you may use pygeoif as a starting point and build your functionality on top of it You may think of pygeoif as a 'shapely ultralight' which lets you construct geometries and perform **very** basic operations like reading and writing geometries from/to WKT, constructing line strings out of points, polygons from linear rings, multi polygons from polygons, etc. It was inspired by shapely and implements the geometries in a way that when you are familiar with shapely you feel right at home with pygeoif It was written to provide clean and python only geometries for fastkml_ .. _fastkml: http://pypi.python.org/pypi/fastkml/ PyGeoIf is continually tested with *Travis CI* .. image:: https://api.travis-ci.org/cleder/pygeoif.png :target: https://travis-ci.org/cleder/pygeoif .. image:: https://coveralls.io/repos/cleder/pygeoif/badge.png?branch=master :target: https://coveralls.io/r/cleder/pygeoif?branch=master Example ======== >>> from pygeoif import geometry >>> p = geometry.Point(1,1) >>> p.__geo_interface__ {'type': 'Point', 'coordinates': (1.0, 1.0)} >>> print p POINT (1.0 1.0) >>> p1 = geometry.Point(0,0) >>> l = geometry.LineString([p,p1]) >>> l.bounds (0.0, 0.0, 1.0, 1.0) >>> dir(l) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__geo_interface__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_coordinates', '_geoms', '_type', 'bounds', 'coords', 'geom_type', 'geoms', 'to_wkt'] >>> print l LINESTRING (1.0 1.0, 0.0 0.0) You find more examples in the `test_main.py `_ file which cover every aspect of pygeoif or in fastkml_. Classes ======== All classes implement the attribute: * __geo_interface__: as dicussed above All geometry classes implement the attributes: * geom_type: Returns a string specifying the Geometry Type of the object * bounds: Returns a (minx, miny, maxx, maxy) tuple (float values) that bounds the object. * wkt: Returns the 'Well Known Text' representation of the object and the method: * to_wkt which also prints the object GeoObject ---------- Base class for Geometry, Feature, and FeatureCollection Geometry -------- Base class for geometry objects. Inherits from Geoobject. Point ----- A zero dimensional geometry A point has zero length and zero area. Attributes ~~~~~~~~~~~ x, y, z : float Coordinate values Example ~~~~~~~~ >>> p = Point(1.0, -1.0) >>> print p POINT (1.0000000000000000 -1.0000000000000000) >>> p.y -1.0 >>> p.x 1.0 LineString ----------- A one-dimensional figure comprising one or more line segments A LineString has non-zero length and zero area. It may approximate a curve and need not be straight. Unlike a LinearRing, a LineString is not closed. Attributes ~~~~~~~~~~~ geoms : sequence A sequence of Points LinearRing ----------- A closed one-dimensional geometry comprising one or more line segments A LinearRing that crosses itself or touches itself at a single point is invalid and operations on it may fail. A Linear Ring is self closing Polygon -------- A two-dimensional figure bounded by a linear ring A polygon has a non-zero area. It may have one or more negative-space "holes" which are also bounded by linear rings. If any rings cross each other, the geometry is invalid and operations on it may fail. Attributes ~~~~~~~~~~~ exterior : LinearRing The ring which bounds the positive space of the polygon. interiors : sequence A sequence of rings which bound all existing holes. MultiPoint ---------- A collection of one or more points Attributes ~~~~~~~~~~~ geoms : sequence A sequence of Points MultiLineString ---------------- A collection of one or more line strings A MultiLineString has non-zero length and zero area. Attributes ~~~~~~~~~~~ geoms : sequence A sequence of LineStrings MultiPolygon ------------- A collection of one or more polygons Attributes ~~~~~~~~~~~~~ geoms : sequence A sequence of `Polygon` instances GeometryCollection ------------------- A heterogenous collection of geometries (Points, LineStrings, LinearRings and Polygons) Attributes ~~~~~~~~~~~ geoms : sequence A sequence of geometry instances Please note: GEOMETRYCOLLECTION isn't supported by the Shapefile format. And this sub-class isn't generally supported by ordinary GIS sw (viewers and so on). So it's very rarely used in the real GIS professional world. Example ~~~~~~~~ >>> from pygeoif import geometry >>> p = geometry.Point(1.0, -1.0) >>> p2 = geometry.Point(1.0, -1.0) >>> geoms = [p, p2] >>> c = geometry.GeometryCollection(geoms) >>> c.__geo_interface__ {'type': 'GeometryCollection', 'geometries': [{'type': 'Point', 'coordinates': (1.0, -1.0)},/ {'type': 'Point', 'coordinates': (1.0, -1.0)}]} >>> [geom for geom in geoms] [Point(1.0, -1.0), Point(1.0, -1.0)] Feature ------- Aggregates a geometry instance with associated user-defined properties. Attributes ~~~~~~~~~~~ geometry : object A geometry instance properties : dict A dictionary linking field keys with values associated with with geometry instance Example ~~~~~~~~ >>> p = Point(1.0, -1.0) >>> props = {'Name': 'Sample Point', 'Other': 'Other Data'} >>> a = Feature(p, props) >>> a.properties {'Name': 'Sample Point', 'Other': 'Other Data'} >>> a.properties['Name'] 'Sample Point' FeatureCollection ----------------- A heterogenous collection of Features Attributes ~~~~~~~~~~~ features: sequence A sequence of feature instances Example ~~~~~~~~ >>> from pygeoif import geometry >>> p = geometry.Point(1.0, -1.0) >>> props = {'Name': 'Sample Point', 'Other': 'Other Data'} >>> a = geometry.Feature(p, props) >>> p2 = geometry.Point(1.0, -1.0) >>> props2 = {'Name': 'Sample Point2', 'Other': 'Other Data2'} >>> b = geometry.Feature(p2, props2) >>> features = [a, b] >>> c = geometry.FeatureCollection(features) >>> c.__geo_interface__ {'type': 'FeatureCollection', 'features': [{'geometry': {'type': 'Point', 'coordinates': (1.0, -1.0)},/ 'type': 'Feature', 'properties': {'Other': 'Other Data', 'Name': 'Sample Point'}},/ {'geometry': {'type': 'Point', 'coordinates': (1.0, -1.0)}, 'type': 'Feature',/ 'properties': {'Other': 'Other Data2', 'Name': 'Sample Point2'}}]} >>> [feature for feature in c] [, ] Functions ========= as_shape -------- Create a pygeoif feature from an object that provides the __geo_interface__ >>> from shapely.geometry import Point >>> from pygeoif import geometry >>> geometry.as_shape(Point(0,0)) from_wkt --------- Create a geometry from its WKT representation >>> p = geometry.from_wkt('POINT (0 1)') >>> print p POINT (0.0 1.0) signed_area ------------ Return the signed area enclosed by a ring using the linear time algorithm at http://www.cgafaq.info/wiki/Polygon_Area. A value >= 0 indicates a counter-clockwise oriented ring. orient ------- Returns a copy of the polygon with exterior in counter-clockwise and interiors in clockwise orientation for sign=1.0 and the other way round for sign=-1.0 mapping ------- Returns the __geo_interface__ dictionary Development =========== Installation ------------ You can install PyGeoIf from pypi using pip:: pip install pygeoif Testing ------- In order to provide a Travis-CI like testing of the PyGeoIf package during development, you can use tox (``pip install tox``) to evaluate the tests on all supported Python interpreters which you have installed on your system. You can run the tests with ``tox --skip-missin-interpreters`` and are looking for output similar to the following:: ______________________________________________________ summary ______________________________________________________ SKIPPED: py26: InterpreterNotFound: python2.6 py27: commands succeeded SKIPPED: py32: InterpreterNotFound: python3.2 SKIPPED: py33: InterpreterNotFound: python3.3 py34: commands succeeded SKIPPED: pypy: InterpreterNotFound: pypy SKIPPED: pypy3: InterpreterNotFound: pypy3 congratulations :) You are primarily looking for the ``congratulations :)`` line at the bottom, signifying that the code is working as expected on all configurations available. Changelog ========= 0.7 (2017/05/04) ----------------- - fix broken multipolygon [mindflayer] - add "bbox" to `__geo_interface__` output [jzmiller1] 0.6 (2015/08/04) ----------------- - Add id to feature [jzmiller1] 0.5 (2015/07/13) ----------------- - Add __iter__ method to FeatureCollection and GeometryCollection [jzmiller1]. - add pypy and pypy3 and python 3.4 to travis. - Add tox configuration for performing local testing [Ian Lee]. - Add Travis continuous deployment. 0.4 (2013/10/25) ----------------- - after a year in production promote it to `Development Status :: 5 - Production/Stable` - MultiPolygons return tuples as the __geo_interface__ 0.3.1 (2012/11/15) ------------------ - specify minor python versions tested with Travis CI - fix for signed area 0.3 (2012/11/14) ------------------- - add GeometryCollection - len(Multi*) and len(GeometryCollection) returns the number of contained Geometries - add orient function to get clockwise or counterclockwise oriented poygons - add signed_area function - add _set_orientation method to lineStrings, Polygons and MultiPolygons 0.2.1 (2012/08/02) ------------------- - as_shape also accepts an object that is neither a dictionary nor has a __geo_interface__ but can be converted into a __geo_interface__ compliant dictionary 0.2 (2012/08/01) ----------------- - change license to LGPL - add wkt as a property - as_shape also accepts a __geo_interface__ compliant dictionary - test with python3 0.1 (2012/07/27) ----------------- - initial release Keywords: GIS Spatial WKT Platform: UNKNOWN Classifier: Topic :: Scientific/Engineering :: GIS Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL) Classifier: Development Status :: 5 - Production/Stable Classifier: Operating System :: OS Independent pygeoif-0.7/MANIFEST.in0000664000175100017510000000016613102645124016557 0ustar christianchristian00000000000000include *.rst recursive-include docs *.txt recursive-exclude *.pyc *.pyo include docs/LICENSE.GPL exclude pygeoif/.* pygeoif-0.7/pygeoif/0000775000175100017510000000000013102646233016462 5ustar christianchristian00000000000000pygeoif-0.7/pygeoif/geometry.py0000664000175100017510000011645013102645177020704 0ustar christianchristian00000000000000# -*- coding: utf-8 -*- # # Copyright (C) 2012 Christian Ledermann # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with this library; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA import re class _GeoObject(object): """Base Class for Geometry, Feature, and FeatureCollection""" def __repr__(self): if self._type == 'Point': return("Point({0}, {1})".format(self.x, self.y)) elif self._type == 'LineString': instance = "LineString Instance" qty = len(self.coords) return "<{0} {1} Coords>".format(instance, qty) elif self._type == 'LinearRing': instance = "LinearRing Instance" qty = len(self.coords) return "<{0} {1} Coords>".format(instance, qty) elif self._type == 'Polygon': instance = "Polygon Instance" inter_qty = len(self._interiors) exter_qty = len(self._exterior.coords) return "<{0} {1} Interior {2} Exterior>".format( instance, inter_qty, exter_qty) elif self._type == 'MultiPoint': instance = "MultiPoint Instance" qty = len(self) return "<{0} {1} Points>".format(instance, qty) elif self._type == 'MultiLineString': instance = "MultiLineString Instance" qty = len(self) bounds = self.bounds return "<{0} {1} Lines {2} bbox>".format(instance, qty, bounds) elif self._type == 'MultiPolygon': instance = "MultiPolygon Instance" qty = len(self) bounds = self.bounds return "<{0} {1} Polygons {2} bbox>".format(instance, qty, bounds) elif self._type == 'GeometryCollection': instance = "GeometryCollection Instance" qty = len(self) bounds = self.bounds return "<{0} {1} Geometries {2} bbox>".format( instance, qty, bounds) elif self._type == 'Feature': instance = "Feature Instance" geometry = self._geometry._type properties = len(self._properties) return "<{0} {1} geometry {2} properties>".format(instance, geometry, properties) elif self._type == 'FeatureCollection': instance = 'FeatureCollection Instance' qty = len(self) bounds = self.bounds return '<{0} {1} Features {2} bbox>'.format(instance, qty, bounds) else: return object.__repr__(self) class _Geometry(_GeoObject): """ Base Class for geometry objects. Inherits from GeoObject """ _type = None _coordinates = () @property def __geo_interface__(self): return { 'type': self._type, 'coordinates': tuple(self._coordinates) } def __str__(self): return self.to_wkt() @property def wkt(self): return self.to_wkt() def to_wkt(self): raise NotImplementedError @property def geom_type(self): return self._type @property def bounds(self): raise NotImplementedError class Feature(_GeoObject): """ Aggregates a geometry instance with associated user-defined properties. Attributes ~~~~~~~~~~~ geometry : object A geometry instance properties : dict A dictionary linking field keys with values associated with geometry instance Example ~~~~~~~~ >>> p = Point(1.0, -1.0) >>> props = {'Name': 'Sample Point', 'Other': 'Other Data'} >>> a = Feature(p, props) >>> a.properties {'Name': 'Sample Point', 'Other': 'Other Data'} >>> a.properties['Name'] 'Sample Point' """ _type = 'Feature' _properties = None _geometry = None _feature_id = None def __init__(self, geometry, properties=None, feature_id=None, *kwargs): self._geometry = geometry if properties is None: properties = {} self._properties = properties self._feature_id = feature_id @property def id(self): return self._feature_id @property def geometry(self): return self._geometry @property def properties(self): return self._properties @property def __geo_interface__(self): geo_interface = {'type': self._type, 'bbox': self._geometry.bounds, 'geometry': self._geometry.__geo_interface__, 'properties': self._properties } if self._feature_id is None: return geo_interface else: geo_interface['id'] = self._feature_id return geo_interface class Point(_Geometry): """ A zero dimensional geometry A point has zero length and zero area. Attributes ---------- x, y, z : float Coordinate values Example ------- >>> p = Point(1.0, -1.0) >>> print p POINT (1.0000000000000000 -1.0000000000000000) >>> p.y -1.0 >>> p.x 1.0 """ _type = 'Point' _coordinates = None def __init__(self, *args): """ Parameters ---------- There are 2 cases: 1) 1 parameter: this must satisfy the __geo_interface__ protocol or be a tuple or list of x, y, [z] 2) 2 or 3 parameters: x, y, [z] : float Easting, northing, and elevation. """ self._coordinates = () if len(args) == 1: if hasattr(args[0], '__geo_interface__'): if args[0].__geo_interface__['type'] == 'Point': self._coordinates = list( args[0].__geo_interface__['coordinates'] ) else: raise TypeError else: if isinstance(args[0], (list, tuple)): if 2 <= len(args[0]) <= 3: coords = [float(x) for x in args[0]] self._coordinates = coords else: raise TypeError else: raise TypeError elif 2 <= len(args) <= 3: coords = [float(x) for x in args] self._coordinates = coords else: raise ValueError @property def x(self): """Return x coordinate.""" return self._coordinates[0] @property def y(self): """Return y coordinate.""" return self._coordinates[1] @property def z(self): """Return z coordinate.""" if len(self._coordinates) != 3: raise ValueError("This point has no z coordinate.") return self._coordinates[2] @property def coords(self): return (tuple(self._coordinates),) @coords.setter def coords(self, coordinates): if isinstance(coordinates, (list, tuple)): if 2 <= len(coordinates) <= 3: coords = [float(x) for x in coordinates] self._coordinates = coords else: raise TypeError else: raise TypeError @property def bounds(self): return tuple(self._coordinates + self._coordinates) def to_wkt(self): coords = str(tuple(self._coordinates)).replace(',', '') return self._type.upper() + ' ' + coords class LineString(_Geometry): """ A one-dimensional figure comprising one or more line segments A LineString has non-zero length and zero area. It may approximate a curve and need not be straight. Unlike a LinearRing, a LineString is not closed. Attributes ---------- geoms : sequence A sequence of Points """ _type = 'LineString' _geoms = None @property def __geo_interface__(self): if self._type and self._geoms: return { 'type': self._type, 'bbox': self.bounds, 'coordinates': tuple(self.coords) } def __init__(self, coordinates): """ Parameters ---------- coordinates : sequence A sequence of (x, y [,z]) numeric coordinate pairs or triples or a sequence of Points or an object that provides the __geo_interface__, including another instance of LineString. Example ------- Create a line with two segments >>> a = LineString([[0, 0], [1, 0], [1, 1]]) """ self._geoms = [] if hasattr(coordinates, '__geo_interface__'): gi = coordinates.__geo_interface__ if (gi['type'] == 'LineString') or (gi['type'] == 'LinearRing'): self.coords = gi['coordinates'] elif gi['type'] == 'Polygon': raise TypeError('Use poligon.exterior or polygon.interiors[x]') else: raise TypeError elif isinstance(coordinates, (list, tuple)): geoms = [] for coord in coordinates: p = Point(coord) l = len(p.coords[0]) if geoms: if l != l2: raise ValueError l2 = l geoms.append(p) self._geoms = geoms else: raise TypeError @property def geoms(self): return tuple(self._geoms) @property def coords(self): coordinates = [] for point in self.geoms: coordinates.append(tuple(point.coords[0])) return tuple(coordinates) @coords.setter def coords(self, coordinates): if isinstance(coordinates, (list, tuple)): geoms = [] for coord in coordinates: p = Point(coord) l = len(p.coords[0]) if geoms: if l != l2: raise ValueError l2 = l geoms.append(p) self._geoms = geoms else: raise ValueError def to_wkt(self): wc = [' '.join([str(x) for x in c]) for c in self.coords] return self._type.upper() + ' (' + ', '.join(wc) + ')' @property def bounds(self): if self.coords: minx = self.coords[0][0] miny = self.coords[0][1] maxx = self.coords[0][0] maxy = self.coords[0][1] for coord in self.coords: minx = min(coord[0], minx) miny = min(coord[1], miny) maxx = max(coord[0], maxx) maxy = max(coord[1], maxy) return (minx, miny, maxx, maxy) class LinearRing(LineString): """ A closed one-dimensional geometry comprising one or more line segments A LinearRing that crosses itself or touches itself at a single point is invalid and operations on it may fail. A Linear Ring is self closing """ _type = 'LinearRing' def __init__(self, coordinates=None): super(LinearRing, self).__init__(coordinates) if self._geoms[0].coords != self._geoms[-1].coords: self._geoms.append(self._geoms[0]) @property def coords(self): if self._geoms[0].coords == self._geoms[-1].coords: coordinates = [] for point in self.geoms: coordinates.append(tuple(point.coords[0])) return tuple(coordinates) else: raise ValueError @coords.setter def coords(self, coordinates): LineString.coords.fset(self, coordinates) if self._geoms[0].coords != self._geoms[-1].coords: self._geoms.append(self._geoms[0]) def _set_orientation(self, clockwise=False): """ sets the orientation of the coordinates in clockwise or counterclockwise (default) order""" area = signed_area(self.coords) if (area >= 0) and clockwise: self._geoms = self._geoms[::-1] elif (area < 0) and not clockwise: self._geoms = self._geoms[::-1] class Polygon(_Geometry): """ A two-dimensional figure bounded by a linear ring A polygon has a non-zero area. It may have one or more negative-space "holes" which are also bounded by linear rings. If any rings cross each other, the geometry is invalid and operations on it may fail. Attributes ---------- exterior : LinearRing The ring which bounds the positive space of the polygon. interiors : sequence A sequence of rings which bound all existing holes. """ _type = 'Polygon' _exterior = None _interiors = None @property def __geo_interface__(self): if self._interiors: coords = [self.exterior.coords] for hole in self.interiors: coords.append(hole.coords) return { 'type': self._type, 'bbox': self.bounds, 'coordinates': tuple(coords) } elif self._exterior: return { 'type': self._type, 'bbox': self.bounds, 'coordinates': (self._exterior.coords,) } def __init__(self, shell, holes=None): """ Parameters ---------- shell : sequence A sequence of (x, y [,z]) numeric coordinate pairs or triples or a LinearRing. If a Polygon is passed as shell the holes parameter will be ignored holes : sequence A sequence of objects which satisfy the same requirements as the shell parameters above Example ------- Create a square polygon with no holes >>> coords = ((0., 0.), (0., 1.), (1., 1.), (1., 0.), (0., 0.)) >>> polygon = Polygon(coords) """ if holes: self._interiors = [] for hole in holes: if hasattr(hole, '__geo_interface__'): gi = hole.__geo_interface__ if gi['type'] == 'LinearRing': self._interiors.append(LinearRing(hole)) else: raise TypeError elif isinstance(hole, (list, tuple)): self._interiors.append(LinearRing(hole)) else: self._interiors = [] if hasattr(shell, '__geo_interface__'): gi = shell.__geo_interface__ if gi['type'] == 'LinearRing': self._exterior = LinearRing(shell) elif gi['type'] == 'Polygon': self._exterior = LinearRing(gi['coordinates'][0]) if len(gi['coordinates']) > 1: # XXX should the holes passed if any be ignored # or added to the polygon? self._interiors = [] for hole in gi['coordinates'][1:]: self._interiors.append(LinearRing(hole)) else: raise TypeError elif isinstance(shell, (list, tuple)): assert isinstance(shell[0], (list, tuple)) if isinstance(shell[0][0], (list, tuple)): # we passed shell and holes in the first parameter self._exterior = LinearRing(shell[0]) if len(shell) > 1: for hole in shell[1:]: self._interiors.append(LinearRing(hole)) else: self._exterior = LinearRing(shell) else: raise TypeError @property def exterior(self): if self._exterior is not None: return self._exterior @property def interiors(self): if self._exterior is not None: if self._interiors: for interior in self._interiors: yield interior @property def bounds(self): if self.exterior: return self.exterior.bounds def to_wkt(self): ext = [' '.join([str(x) for x in c]) for c in self.exterior.coords] ec = ('(' + ', '.join(ext) + ')') ic = '' for interior in self.interiors: ic += ',(' + ', '.join( [' '.join([str(x) for x in c]) for c in interior.coords] ) + ')' return self._type.upper() + '(' + ec + ic + ')' def _set_orientation(self, clockwise=False, exterior=True, interiors=True): """ sets the orientation of the coordinates in clockwise or counterclockwise (default) order""" if exterior: self.exterior._set_orientation(clockwise) if interiors: for interior in self.interiors: interior._set_orientation(clockwise) class MultiPoint(_Geometry): """A collection of one or more points Attributes ---------- geoms : sequence A sequence of Points """ _geoms = None _type = 'MultiPoint' @property def __geo_interface__(self): return { 'type': self._type, 'bbox': self.bounds, 'coordinates': tuple([g.coords[0] for g in self._geoms]) } def __init__(self, points): """ Parameters ---------- points : sequence A sequence of (x, y [,z]) numeric coordinate pairs or triples or a sequence of objects that implement the __geo_interface__, including instaces of Point. Example ------- Construct a 2 point collection >>> ob = MultiPoint([[0.0, 0.0], [1.0, 2.0]]) >>> len(ob.geoms) 2 >>> type(ob.geoms[0]) == Point True """ self._geoms = [] if isinstance(points, (list, tuple)): for point in points: if hasattr(point, '__geo_interface__'): self._from_geo_interface(point) elif isinstance(point, (list, tuple)): p = Point(point) self._geoms.append(p) else: raise TypeError elif hasattr(points, '__geo_interface__'): self._from_geo_interface(points) else: raise TypeError def _from_geo_interface(self, point): gi = point.__geo_interface__ if gi['type'] == 'Point': p = Point(point) self._geoms.append(p) elif gi['type'] == 'LinearRing' or gi['type'] == 'LineString': l = LineString(point) for coord in l.coords: p = Point(coord) self._geoms.append(p) elif gi['type'] == 'Polygon': p = Polygon(point) for coord in p.exterior.coords: p1 = Point(coord) self._geoms.append(p1) for interior in p.interiors: for coord in interior.coords: p1 = Point(coord) self._geoms.append(p1) else: raise TypeError @property def geoms(self): return tuple(self._geoms) @property def bounds(self): if self._geoms: minx = self.geoms[0].coords[0][0] miny = self.geoms[0].coords[0][1] maxx = self.geoms[0].coords[0][0] maxy = self.geoms[0].coords[0][1] for geom in self.geoms: minx = min(geom.coords[0][0], minx) miny = min(geom.coords[0][1], miny) maxx = max(geom.coords[0][0], maxx) maxy = max(geom.coords[0][1], maxy) return (minx, miny, maxx, maxy) def unique(self): """ Make Points unique, delete duplicates """ coords = [geom.coords for geom in self.geoms] self._geoms = [Point(coord[0]) for coord in set(coords)] def to_wkt(self): wc = [' '.join([str(x) for x in c.coords[0]]) for c in self.geoms] return self._type.upper() + '(' + ', '.join(wc) + ')' def __len__(self): if self._geoms: return len(self._geoms) else: return 0 class MultiLineString(_Geometry): """ A collection of one or more line strings A MultiLineString has non-zero length and zero area. Attributes ---------- geoms : sequence A sequence of LineStrings """ _geoms = None _type = 'MultiLineString' @property def __geo_interface__(self): return { 'type': self._type, 'bbox': self.bounds, 'coordinates': tuple( tuple(c for c in g.coords) for g in self.geoms ) } def __init__(self, lines): """ Parameters ---------- lines : sequence A sequence of line-like coordinate sequences or objects that provide the __geo_interface__, including instances of LineString. Example ------- Construct a collection containing one line string. >>> lines = MultiLineString( [[[0.0, 0.0], [1.0, 2.0]]] ) """ self._geoms = [] if isinstance(lines, (list, tuple)): for line in lines: l = LineString(line) self._geoms.append(l) elif hasattr(lines, '__geo_interface__'): gi = lines.__geo_interface__ if gi['type'] == 'LinearRing' or gi['type'] == 'LineString': l = LineString(gi['coordinates']) self._geoms.append(l) elif gi['type'] == 'MultiLineString': for line in gi['coordinates']: l = LineString(line) self._geoms.append(l) else: raise TypeError else: raise TypeError @property def geoms(self): return tuple(self._geoms) @property def bounds(self): if self._geoms: minx = self.geoms[0].bounds[0] miny = self.geoms[0].bounds[1] maxx = self.geoms[0].bounds[2] maxy = self.geoms[0].bounds[3] for geom in self.geoms: minx = min(geom.bounds[0], minx) miny = min(geom.bounds[1], miny) maxx = max(geom.bounds[2], maxx) maxy = max(geom.bounds[3], maxy) return (minx, miny, maxx, maxy) def to_wkt(self): wc = '(' + ', '.join( [' '.join([str(x) for x in c]) for c in self.geoms[0].coords] ) + ')' for lx in self.geoms[1:]: wc += ',(' + ', '.join( [' '.join([str(x) for x in c]) for c in lx.coords] ) + ')' return self._type.upper() + '(' + wc + ')' def __len__(self): if self._geoms: return len(self._geoms) else: return 0 class MultiPolygon(_Geometry): """A collection of one or more polygons If component polygons overlap the collection is `invalid` and some operations on it may fail. Attributes ---------- geoms : sequence A sequence of `Polygon` instances """ _geoms = None _type = 'MultiPolygon' @property def __geo_interface__(self): allcoords = [] for geom in self.geoms: coords = [] coords.append(tuple(geom.exterior.coords)) for hole in geom.interiors: coords.append(tuple(hole.coords)) allcoords.append(tuple(coords)) return { 'type': self._type, 'bbox': self.bounds, 'coordinates': tuple(allcoords) } def __init__(self, polygons): """ Parameters ---------- polygons : sequence A sequence of (shell, holes) tuples where shell is the sequence representation of a linear ring (see linearring.py) and holes is a sequence of such linear rings Example ------- Construct a collection from a sequence of coordinate tuples >>> ob = MultiPolygon([ ... ( ... ((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)), ... [((0.1, 0.1), (0.1, 0.2), (0.2, 0.2), (0.2, 0.1))] ...) ...]) >>> len(ob.geoms) 1 >>> type(ob.geoms[0]) == Polygon True """ self._geoms = [] if isinstance(polygons, (list, tuple)): for polygon in polygons: if isinstance(polygon, (list, tuple)): p = Polygon(polygon[0], polygon[1]) self._geoms.append(p) elif hasattr(polygon, '__geo_interface__'): gi = polygon.__geo_interface__ p = Polygon(polygon) self._geoms.append(p) else: raise ValueError elif hasattr(polygons, '__geo_interface__'): gi = polygons.__geo_interface__ if gi['type'] == 'Polygon': p = Polygon(polygons) self._geoms.append(p) elif gi['type'] == 'MultiPolygon': for coords in gi['coordinates']: self._geoms.append(Polygon(coords[0], coords[1:])) else: raise TypeError else: raise ValueError @property def geoms(self): return tuple(self._geoms) @property def bounds(self): if self._geoms: minx = self.geoms[0].bounds[0] miny = self.geoms[0].bounds[1] maxx = self.geoms[0].bounds[2] maxy = self.geoms[0].bounds[3] for geom in self.geoms: minx = min(geom.bounds[0], minx) miny = min(geom.bounds[1], miny) maxx = max(geom.bounds[2], maxx) maxy = max(geom.bounds[3], maxy) return (minx, miny, maxx, maxy) def to_wkt(self): pc = [] for geom in self.geoms: ec = '(' + ', '.join( [' '.join([str(x) for x in c]) for c in geom.exterior.coords] ) + ')' ic = '' for interior in geom.interiors: ic += ',(' + ', '.join( [' '.join([str(x) for x in c]) for c in interior.coords] ) + ')' pc.append('(' + ec + ic + ')') return self._type.upper() + '(' + ','.join(pc) + ')' def _set_orientation(self, clockwise=False, exterior=True, interiors=True): """ sets the orientation of the coordinates in clockwise or counterclockwise (default) order for all contained polygons""" for geom in self.geoms: geom._set_orientation(clockwise, exterior, interiors) def __len__(self): if self._geoms: return len(self._geoms) else: return 0 class GeometryCollection(_Geometry): """A heterogenous collection of geometries (Points, LineStrings, LinearRings, and Polygons) Attributes ---------- geoms : sequence A sequence of geometry instances Please note: GEOMETRYCOLLECTION isn't supported by the Shapefile format. And this sub- class isn't generally supported by ordinary GIS sw (viewers and so on). So it's very rarely used in the real GIS professional world. Example ------- Initialize Geometries and construct a GeometryCollection >>> from pygeoif import geometry >>> p = geometry.Point(1.0, -1.0) >>> p2 = geometry.Point(1.0, -1.0) >>> geoms = [p, p2] >>> c = geometry.GeometryCollection(geoms) >>> c.__geo_interface__ {'type': 'GeometryCollection', 'geometries': [{'type': 'Point', 'coordinates': (1.0, -1.0)}, {'type': 'Point', 'coordinates': (1.0, -1.0)}]} """ _type = 'GeometryCollection' _geoms = None _allowed_geomtries = (Point, LineString, LinearRing, Polygon) @property def __geo_interface__(self): gifs = [] for geom in self._geoms: gifs.append(geom.__geo_interface__) return {'type': self._type, 'geometries': gifs} def __init__(self, geometries): self._geoms = [] if isinstance(geometries, (list, tuple)): for geometry in geometries: if isinstance(geometry, self._allowed_geomtries): self._geoms.append(geometry) elif isinstance(as_shape(geometry), self._allowed_geomtries): self._geoms.append(as_shape(geometry)) else: raise ValueError else: raise TypeError @property def geoms(self): for geom in self._geoms: if isinstance(geom, self._allowed_geomtries): yield geom else: raise ValueError("Illegal geometry type.") @property def bounds(self): if self._geoms: minx = self._geoms[0].bounds[0] miny = self._geoms[0].bounds[1] maxx = self._geoms[0].bounds[2] maxy = self._geoms[0].bounds[3] for geom in self.geoms: minx = min(geom.bounds[0], minx) miny = min(geom.bounds[1], miny) maxx = max(geom.bounds[2], maxx) maxy = max(geom.bounds[3], maxy) return (minx, miny, maxx, maxy) def to_wkt(self): wkts = [] for geom in self.geoms: wkts.append(geom.to_wkt()) return 'GEOMETRYCOLLECTION (%s)' % ', '.join(wkts) def __len__(self): if self._geoms: return len(self._geoms) else: return 0 def __iter__(self): return iter(self._geoms) class FeatureCollection(_GeoObject): """A heterogenous collection of Features Attributes ---------- features : sequence A sequence of feature instances Example ------- >>> from pygeoif import geometry >>> p = geometry.Point(1.0, -1.0) >>> props = {'Name': 'Sample Point', 'Other': 'Other Data'} >>> a = geometry.Feature(p, props) >>> p2 = geometry.Point(1.0, -1.0) >>> props2 = {'Name': 'Sample Point2', 'Other': 'Other Data2'} >>> b = geometry.Feature(p2, props2) >>> features = [a, b] >>> c = geometry.FeatureCollection(features) >>> c.__geo_interface__ {'type': 'FeatureCollection', 'features': [{'geometry': {'type': 'Point', 'coordinates': (1.0, -1.0)}, 'type': 'Feature', 'properties': {'Other': 'Other Data', 'Name': 'Sample Point'}}, {'geometry': {'type': 'Point', 'coordinates': (1.0, -1.0)}, 'type': 'Feature', 'properties': {'Other': 'Other Data2', 'Name': 'Sample Point2'}}]} """ _type = 'FeatureCollection' _features = None @property def __geo_interface__(self): gifs = [] for feature in self._features: gifs.append(feature.__geo_interface__) return {'type': self._type, 'bbox': self.bounds, 'features': gifs} def __init__(self, features): self._features = [] if isinstance(features, (list, tuple)): for feature in features: if isinstance(feature, Feature): self._features.append(feature) else: raise ValueError else: raise TypeError @property def features(self): for feature in self._features: if isinstance(feature, Feature): yield feature else: raise ValueError("Illegal type.") @property def bounds(self): if self._features: minx = self._features[0].geometry.bounds[0] miny = self._features[0].geometry.bounds[1] maxx = self._features[0].geometry.bounds[2] maxy = self._features[0].geometry.bounds[3] for feature in self.features: minx = min(feature.geometry.bounds[0], minx) miny = min(feature.geometry.bounds[1], miny) maxx = max(feature.geometry.bounds[2], maxx) maxy = max(feature.geometry.bounds[3], maxy) return (minx, miny, maxx, maxy) def __len__(self): if self._features: return len(self._features) else: return 0 def __iter__(self): return iter(self._features) def signed_area(coords): """Return the signed area enclosed by a ring using the linear time algorithm at http://www.cgafaq.info/wiki/Polygon_Area. A value >= 0 indicates a counter-clockwise oriented ring. """ if len(coords[0]) == 2: xs, ys = map(list, zip(*coords)) elif len(coords[0]) == 3: xs, ys, zs = map(list, zip(*coords)) else: raise ValueError xs.append(xs[1]) ys.append(ys[1]) return sum(xs[i]*(ys[i+1]-ys[i-1]) for i in range(1, len(coords)))/2.0 def orient(polygon, sign=1.0): s = float(sign) rings = [] ring = polygon.exterior if signed_area(ring.coords)/s >= 0.0: rings.append(ring.coords) else: rings.append(list(ring.coords)[::-1]) for ring in polygon.interiors: if signed_area(ring.coords)/s <= 0.0: rings.append(ring.coords) else: rings.append(list(ring.coords)[::-1]) return Polygon(rings[0], rings[1:]) def as_shape(geometry): """ creates a pygeoif geometry from an object that provides the __geo_interface__ or a dictionary that is __geo_interface__ compatible""" gi = None if isinstance(geometry, dict): is_geometryCollection = geometry['type'] == 'GeometryCollection' is_feature = geometry['type'] == 'Feature' if ('coordinates' in geometry) and ('type' in geometry): gi = geometry elif is_geometryCollection and 'geometries' in geometry: gi = geometry elif is_feature: gi = geometry elif hasattr(geometry, '__geo_interface__'): gi = geometry.__geo_interface__ else: try: # maybe we can convert it into a valid __geo_interface__ dict cdict = dict(geometry) is_geometryCollection = cdict['type'] == 'GeometryCollection' if ('coordinates' in cdict) and ('type' in cdict): gi = cdict elif is_geometryCollection and 'geometries' in cdict: gi = cdict except: pass if gi: ft = gi['type'] if ft == 'GeometryCollection': geometries = [] for fi in gi['geometries']: geometries.append(as_shape(fi)) return GeometryCollection(geometries) if ft == 'Feature': return Feature(as_shape(gi['geometry']), properties=gi.get('properties', {}), feature_id=gi.get('id', None)) if ft == 'FeatureCollection': features = [] for fi in gi['features']: features.append(as_shape(fi)) return FeatureCollection(features) coords = gi['coordinates'] if ft == 'Point': return Point(coords) elif ft == 'LineString': return LineString(coords) elif ft == 'LinearRing': return LinearRing(coords) elif ft == 'Polygon': return Polygon(coords) elif ft == 'MultiPoint': return MultiPoint(coords) elif ft == 'MultiLineString': return MultiLineString(coords) elif ft == 'MultiPolygon': polygons = [] for icoords in coords: polygons.append(Polygon(icoords[0], icoords[1:])) return MultiPolygon(polygons) else: raise NotImplementedError else: raise TypeError('Object does not implement __geo_interface__') wkt_regex = re.compile(r'^(SRID=(?P\d+);)?' r'(?P' r'(?PPOINT|LINESTRING|LINEARRING|POLYGON|' r'MULTIPOINT|MULTILINESTRING|MULTIPOLYGON|' r'GEOMETRYCOLLECTION)' r'[ACEGIMLONPSRUTYZ\d,\.\-\(\) ]+)$', re.I ) gcre = re.compile(r'POINT|LINESTRING|LINEARRING|POLYGON') outer = re.compile("\((.+)\)") inner = re.compile("\([^)]*\)") mpre = re.compile("\(\((.+?)\)\)") def from_wkt(geo_str): """ Create a geometry from its WKT representation """ wkt = geo_str.strip() wkt = ' '.join([l.strip() for l in wkt.splitlines()]) wkt = wkt_regex.match(wkt).group('wkt') ftype = wkt_regex.match(wkt).group('type') outerstr = outer.search(wkt) coordinates = outerstr.group(1) if ftype == 'POINT': coords = coordinates.split() return Point(coords) elif ftype == 'LINESTRING': coords = coordinates.split(',') return LineString([c.split() for c in coords]) elif ftype == 'LINEARRING': coords = coordinates.split(',') return LinearRing([c.split() for c in coords]) elif ftype == 'POLYGON': coords = [] for interior in inner.findall(coordinates): coords.append((interior[1:-1]).split(',')) if len(coords) > 1: # we have a polygon with holes exteriors = [] for ext in coords[1:]: exteriors.append([c.split() for c in ext]) else: exteriors = None return Polygon([c.split() for c in coords[0]], exteriors) elif ftype == 'MULTIPOINT': coords1 = coordinates.split(',') coords = [] for coord in coords1: if '(' in coord: coord = coord[coord.find('(') + 1: coord.rfind(')')] coords.append(coord.strip()) return MultiPoint([c.split() for c in coords]) elif ftype == 'MULTILINESTRING': coords = [] for lines in inner.findall(coordinates): coords.append([c.split() for c in lines[1:-1].split(',')]) return MultiLineString(coords) elif ftype == 'MULTIPOLYGON': polygons = [] m = mpre.split(coordinates) for polygon in m: if len(polygon) < 3: continue coords = [] for interior in inner.findall('(' + polygon + ')'): coords.append((interior[1:-1]).split(',')) if len(coords) > 1: # we have a polygon with holes exteriors = [] for ext in coords[1:]: exteriors.append([c.split() for c in ext]) else: exteriors = None polygons.append(Polygon([c.split() for c in coords[0]], exteriors)) return MultiPolygon(polygons) elif ftype == 'GEOMETRYCOLLECTION': gc_types = gcre.findall(coordinates) gc_coords = gcre.split(coordinates)[1:] assert(len(gc_types) == len(gc_coords)) geometries = [] for (gc_type, gc_coord) in zip(gc_types, gc_coords): gc_wkt = gc_type + gc_coord[:gc_coord.rfind(')') + 1] geometries.append(from_wkt(gc_wkt)) return GeometryCollection(geometries) else: raise NotImplementedError def mapping(ob): return ob.__geo_interface__ pygeoif-0.7/pygeoif/__init__.py0000664000175100017510000000212413102645124020570 0ustar christianchristian00000000000000# -*- coding: utf-8 -*- # # Copyright (C) 2012 Christian Ledermann # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public License # along with this library; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # from .geometry import Point, LineString, LinearRing, Polygon from .geometry import MultiPoint, MultiLineString, MultiPolygon from .geometry import GeometryCollection from .geometry import Feature, FeatureCollection from .geometry import as_shape, from_wkt, mapping, orient, signed_area pygeoif-0.7/pygeoif/test_main.py0000664000175100017510000011563113102645177021034 0ustar christianchristian00000000000000# -*- coding: utf-8 -*- import unittest try: from pygeoif import geometry except ImportError: import geometry class BasicTestCase(unittest.TestCase): def test_Geometry(self): f = geometry._Geometry() self.assertRaises(NotImplementedError, lambda: f.bounds) self.assertRaises(NotImplementedError, f.to_wkt) def test_point(self): self.assertRaises(ValueError, geometry.Point) p = geometry.Point(0, 1) self.assertEqual(p.bounds, (0.0, 1.0, 0.0, 1.0)) self.assertEqual(p.x, 0.0) self.assertEqual(p.y, 1.0) self.assertEqual(p.__geo_interface__, {'type': 'Point', 'coordinates': (0.0, 1.0)}) self.assertRaises(ValueError, lambda: p.z) self.assertEqual(p.coords[0], (0.0, 1.0)) p1 = geometry.Point(0, 1, 2) self.assertEqual(p1.x, 0.0) self.assertEqual(p1.y, 1.0) self.assertEqual(p1.z, 2.0) self.assertEqual(p1.coords[0], (0.0, 1.0, 2.0)) self.assertEqual(p1.__geo_interface__, {'type': 'Point', 'coordinates': (0.0, 1.0, 2.0)}) p2 = geometry.Point([0, 1]) self.assertEqual(p2.x, 0.0) self.assertEqual(p2.y, 1.0) p3 = geometry.Point([0, 1, 2]) self.assertEqual(p3.x, 0.0) self.assertEqual(p3.y, 1.0) self.assertEqual(p3.z, 2.0) p4 = geometry.Point(p) self.assertEqual(p4.x, 0.0) self.assertEqual(p4.y, 1.0) p5 = geometry.Point(p1) self.assertEqual(p5.x, 0.0) self.assertEqual(p5.y, 1.0) self.assertEqual(p5.z, 2.0) self.assertRaises(TypeError, geometry.Point, '1.0, 2.0') self.assertRaises(ValueError, geometry.Point, '1.0', 'a') self.assertRaises(TypeError, geometry.Point, (0, 1, 2, 3, 4)) #you may also pass string values as internally they get converted #into floats, but this is not recommended p6 = geometry.Point('0', '1') self.assertEqual(p.__geo_interface__, p6.__geo_interface__) p6.coords = [0, 1, 2] self.assertEqual(p3.coords, p6.coords) self.assertRaises(TypeError, setattr, p6, 'coords', 0) self.assertRaises(TypeError, setattr, p6, 'coords', [0]) f = geometry._Geometry() self.assertRaises(TypeError, geometry.Point, f) def test_linestring(self): l = geometry.LineString([(0, 0), (1, 1)]) self.assertEqual(l.coords, ((0.0, 0.0), (1.0, 1.0))) self.assertEqual(l.coords[:1], ((0.0, 0.0),)) self.assertEqual(l.bounds, (0.0, 0.0, 1.0, 1.0)) self.assertEqual(l.__geo_interface__, {'type': 'LineString', 'bbox': (0.0, 0.0, 1.0, 1.0), 'coordinates': ((0.0, 0.0), (1.0, 1.0))}) self.assertEqual(l.to_wkt(), 'LINESTRING (0.0 0.0, 1.0 1.0)') p = geometry.Point(0, 0) p1 = geometry.Point(1, 1) p2 = geometry.Point(2, 2) l1 = geometry.LineString([p, p1, p2]) self.assertEqual(l1.coords, ((0.0, 0.0), (1.0, 1.0), (2.0, 2.0))) l2 = geometry.LineString(l1) self.assertEqual(l2.coords, ((0.0, 0.0), (1.0, 1.0), (2.0, 2.0))) l.coords = l2.coords self.assertEqual(l.__geo_interface__, l2.__geo_interface__) self.assertRaises(ValueError, geometry.LineString, [(0, 0, 0), (1, 1)]) ext = [(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)] int_1 = [(0.5, 0.25), (1.5, 0.25), (1.5, 1.25), (0.5, 1.25), (0.5, 0.25)] int_2 = [(0.5, 1.25), (1, 1.25), (1, 1.75), (0.5, 1.75), (0.5, 1.25)] po = geometry.Polygon(ext, [int_1, int_2]) self.assertRaises(TypeError, geometry.LineString, po) pt = geometry.Point(0, 1) self.assertRaises(TypeError, geometry.LineString, pt) self.assertRaises(TypeError, geometry.LineString, 0) self.assertRaises(ValueError, setattr, l2, 'coords', ((0, 0), (1, 1, 1))) self.assertRaises(ValueError, setattr, l2, 'coords', 0) def test_linearring(self): r = geometry.LinearRing([(0, 0), (1, 1), (1, 0), (0, 0)]) self.assertEqual(r.coords, ((0, 0), (1, 1), (1, 0), (0, 0))) self.assertEqual(r.bounds, (0.0, 0.0, 1.0, 1.0)) l = geometry.LineString(r) self.assertEqual(l.coords, ((0, 0), (1, 1), (1, 0), (0, 0))) self.assertEqual(r.__geo_interface__, {'type': 'LinearRing', 'bbox': (0.0, 0.0, 1.0, 1.0), 'coordinates': ((0.0, 0.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0))}) ext = [(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)] int_1 = [(0.5, 0.25), (1.5, 0.25), (1.5, 1.25), (0.5, 1.25), (0.5, 0.25)] int_2 = [(0.5, 1.25), (1, 1.25), (1, 1.75), (0.5, 1.75), (0.5, 1.25)] p = geometry.Polygon(ext, [int_1, int_2]) self.assertRaises(TypeError, geometry.LinearRing, p) # A LinearRing is self closing r2 = geometry.LinearRing([(0, 0), (1, 1), (1, 0)]) self.assertEqual(r.__geo_interface__, r2.__geo_interface__) r3 = geometry.LinearRing(int_1) r3.coords = [(0, 0), (1, 1), (1, 0)] self.assertEqual(r.__geo_interface__, r3.__geo_interface__) def test_polygon(self): p = geometry.Polygon([(0, 0), (1, 1), (1, 0), (0, 0)]) self.assertEqual(p.exterior.coords, ((0.0, 0.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0))) self.assertEqual(list(p.interiors), []) self.assertEqual(p.__geo_interface__, {'type': 'Polygon', 'bbox': (0.0, 0.0, 1.0, 1.0), 'coordinates': (((0.0, 0.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0)),)}) self.assertEqual(p.bounds, (0.0, 0.0, 1.0, 1.0)) r = geometry.LinearRing([(0, 0), (1, 1), (1, 0), (0, 0)]) p1 = geometry.Polygon(r) self.assertEqual(p1.exterior.coords, r.coords) e = [(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)] i = [(1, 0), (0.5, 0.5), (1, 1), (1.5, 0.5), (1, 0)] ph1 = geometry.Polygon(e, [i]) self.assertEqual(ph1.__geo_interface__, geometry.as_shape(ph1).__geo_interface__) self.assertEqual(ph1.exterior.coords, tuple(e)) self.assertEqual(list(ph1.interiors)[0].coords, tuple(i)) self.assertEqual(ph1.__geo_interface__, {'type': 'Polygon', 'bbox': (0.0, 0.0, 2.0, 2.0), 'coordinates': (((0.0, 0.0), (0.0, 2.0), (2.0, 2.0), (2.0, 0.0), (0.0, 0.0)), ((1.0, 0.0), (0.5, 0.5), (1.0, 1.0), (1.5, 0.5), (1.0, 0.0))) } ) ext = [(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)] int_1 = [(0.5, 0.25), (1.5, 0.25), (1.5, 1.25), (0.5, 1.25), (0.5, 0.25)] int_2 = [(0.5, 1.25), (1, 1.25), (1, 1.75), (0.5, 1.75), (0.5, 1.25)] ph2 = geometry.Polygon(ext, [int_1, int_2]) self.assertEqual(ph2.exterior.coords, tuple(ext)) self.assertEqual(list(ph2.interiors)[0].coords, tuple(int_1)) self.assertEqual(list(ph2.interiors)[1].coords, tuple(int_2)) self.assertEqual(ph2.__geo_interface__, {'type': 'Polygon', 'bbox': (0.0, 0.0, 2.0, 2.0), 'coordinates': (((0.0, 0.0), (0.0, 2.0), (2.0, 2.0), (2.0, 0.0), (0.0, 0.0)), ((0.5, 0.25), (1.5, 0.25), (1.5, 1.25), (0.5, 1.25), (0.5, 0.25)), ((0.5, 1.25), (1.0, 1.25), (1.0, 1.75), (0.5, 1.75), (0.5, 1.25))) }) ph3 = geometry.Polygon(ph2) self.assertEqual(ph2.__geo_interface__, ph3.__geo_interface__) # if a polygon is passed as constructor holes will be ignored # XXX or should holes be added to the polygon? ph4 = geometry.Polygon(ph2, [i]) self.assertEqual(ph2.__geo_interface__, ph4.__geo_interface__) coords = ((0., 0.), (0., 1.), (1., 1.), (1., 0.), (0., 0.)) polygon = geometry.Polygon(coords) ph5 = geometry.Polygon( (((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)), ((0.1, 0.1), (0.1, 0.2), (0.2, 0.2), (0.2, 0.1)) )) r1 = geometry.LinearRing([(0, 0), (2, 2), (2, 0), (0, 0)]) r2 = geometry.LinearRing([(0.5, 0.5), (1, 1), (1, 0), (0.5, 0.5)]) p6 = geometry.Polygon(r1, [r2]) pt = geometry.Point(0, 1) self.assertRaises(TypeError, geometry.Polygon, pt) self.assertRaises(TypeError, geometry.Polygon, 0) self.assertRaises(TypeError, geometry.Polygon, pt, [pt]) def test_multipoint(self): p0 = geometry.Point(0, 0) p1 = geometry.Point(1, 1) p2 = geometry.Point(2, 2) p3 = geometry.Point(3, 3) mp = geometry.MultiPoint(p0) self.assertEqual(len(mp.geoms), 1) self.assertEqual(mp.geoms[0].x, 0) mp1 = geometry.MultiPoint([p0, p1, p2]) self.assertEqual(len(mp1.geoms), 3) self.assertEqual(len(mp1), 3) self.assertEqual(mp1.geoms[0].x, 0) self.assertEqual(mp1.geoms[1].x, 1) self.assertEqual(mp1.geoms[2].x, 2) self.assertEqual(mp1.bounds, (0.0, 0.0, 2.0, 2.0)) l1 = geometry.LineString([p0, p1, p2]) mp2 = geometry.MultiPoint(l1) self.assertEqual(len(mp2.geoms), 3) self.assertEqual(mp2.geoms[2].x, 2) mp3 = geometry.MultiPoint([l1, p3]) self.assertEqual(mp3.geoms[3].x, 3) self.assertRaises(TypeError, geometry.MultiPoint, [mp1, mp3]) mp4 = geometry.MultiPoint([p0, p1, p0, p1, p2]) self.assertEqual(len(mp4.geoms), 5) mp4.unique() self.assertEqual(len(mp4.geoms), 3) mp5 = geometry.MultiPoint([[0.0, 0.0], [1.0, 2.0]]) self.assertEqual(len(mp5.geoms), 2) p = geometry.Polygon( (((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)), ((0.1, 0.1), (0.1, 0.2), (0.2, 0.2), (0.2, 0.1)) )) mp6 = geometry.MultiPoint(p) self.assertEqual(mp6.bounds, (0.0, 0.0, 1.0, 1.0)) self.assertRaises(TypeError, geometry.MultiPoint, [0, 0]) self.assertRaises(TypeError, geometry.MultiPoint, 0,) self.assertEqual(mp1.__geo_interface__, {'type': 'MultiPoint', 'bbox': (0.0, 0.0, 2.0, 2.0), 'coordinates': ((0.0, 0.0), (1.0, 1.0), (2.0, 2.0))}) def test_multilinestring(self): ml = geometry.MultiLineString([[[0.0, 0.0], [1.0, 2.0]]]) ml1 = geometry.MultiLineString(ml) self.assertEqual(ml.geoms[0].coords, ((0.0, 0.0), (1.0, 2.0))) self.assertEqual(ml.bounds, (0.0, 0.0, 1.0, 2.0)) l = geometry.LineString([(0, 0), (1, 1)]) l1 = geometry.LineString([(0.0, 0.0), (1.0, 1.0), (2.0, 2.0)]) ml2 = geometry.MultiLineString([l, l1]) self.assertEqual(ml2.geoms[0].coords, ((0.0, 0.0), (1.0, 1.0))) self.assertEqual(ml2.geoms[1].coords, ((0.0, 0.0), (1.0, 1.0), (2.0, 2.0))) self.assertEqual(len(ml2), 2) ml3 = geometry.MultiLineString(l) self.assertEqual(ml3.geoms[0].coords, ((0.0, 0.0), (1.0, 1.0))) pt = geometry.Point(0, 1) self.assertRaises(TypeError, geometry.MultiLineString, pt) self.assertRaises(TypeError, geometry.MultiLineString, 0) def test_multipolygon(self): p = geometry.Polygon([(0, 0), (1, 1), (1, 0), (0, 0)]) e = [(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)] i = [(1, 0), (0.5, 0.5), (1, 1), (1.5, 0.5), (1, 0)] ph1 = geometry.Polygon(e, [i]) mp = geometry.MultiPolygon([p, ph1]) self.assertEqual(len(mp), 2) self.assertTrue(isinstance(mp.geoms[0], geometry.Polygon)) self.assertTrue(isinstance(mp.geoms[1], geometry.Polygon)) self.assertEqual(mp.bounds, (0.0, 0.0, 2.0, 2.0)) mp = geometry.MultiPolygon([(((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)), [((0.1, 0.1), (0.1, 0.2), (0.2, 0.2), (0.2, 0.1))] ) ]) self.assertEqual(mp.__geo_interface__, {'type': 'MultiPolygon', 'bbox': (0.0, 0.0, 1.0, 1.0), 'coordinates': ((((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0) ), ((0.1, 0.1), (0.1, 0.2), (0.2, 0.2), (0.2, 0.1), (0.1, 0.1))),) }) self.assertEqual(len(mp.geoms), 1) self.assertTrue(isinstance(mp.geoms[0], geometry.Polygon)) mp1 = geometry.MultiPolygon(mp) self.assertEqual(mp.__geo_interface__, mp1.__geo_interface__) mp2 = geometry.MultiPolygon(ph1) self.assertRaises(ValueError, geometry.MultiPolygon, 0) self.assertRaises(ValueError, geometry.MultiPolygon, [0, 0]) pt = geometry.Point(0, 1) self.assertRaises(TypeError, geometry.MultiPolygon, pt) def test_geometrycollection(self): self.assertRaises(TypeError, geometry.GeometryCollection) self.assertRaises(TypeError, geometry.GeometryCollection, None) p = geometry.Polygon([(0, 0), (1, 1), (1, 0), (0, 0)]) e = [(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)] i = [(1, 0), (0.5, 0.5), (1, 1), (1.5, 0.5), (1, 0)] ph = geometry.Polygon(e, [i]) p0 = geometry.Point(0, 0) p1 = geometry.Point(-1, -1) r = geometry.LinearRing([(0, 0), (1, 1), (1, 0), (0, 0)]) l = geometry.LineString([(0, 0), (1, 1)]) gc = geometry.GeometryCollection([p, ph, p0, p1, r, l]) self.assertEqual(len(list(gc.geoms)), 6) self.assertEqual(len(gc), 6) self.assertEqual(gc.bounds, (-1.0, -1.0, 2.0, 2.0)) self.assertEqual(gc.__geo_interface__, geometry.as_shape(gc).__geo_interface__) self.assertEqual(gc.__geo_interface__, geometry.as_shape (gc.__geo_interface__).__geo_interface__) f = geometry._Geometry() gc1 = geometry.GeometryCollection([p.__geo_interface__, ph, p0, p1, r, l.__geo_interface__]) self.assertEqual(gc.__geo_interface__,gc1.__geo_interface__) self.assertRaises(NotImplementedError, geometry.GeometryCollection, [p, f]) mp1 = geometry.MultiPoint([p0, p1]) self.assertRaises(ValueError, geometry.GeometryCollection, [p, mp1]) self.assertEqual([p, ph, p0, p1, r, l], [geom for geom in gc]) def test_mapping(self): self.assertEqual(geometry.mapping(geometry.Point(1, 1)), {'type': 'Point', 'coordinates': (1.0, 1.0)}) def test_signed_area(self): a0 = [(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)] a1 = [(0, 0, 1), (0, 2, 2), (2, 2, 3), (2, 0, 4), (0, 0, 1)] self.assertEqual(geometry.signed_area(a0), geometry.signed_area(a1)) a2 = [(0, 0, 1, 3), (0, 2, 2)] self.assertRaises(ValueError, geometry.signed_area, a2) class WKTTestCase(unittest.TestCase): # valid and supported WKTs wkt_ok = ['POINT(6 10)', 'POINT M (1 1 80)', 'LINESTRING(3 4,10 50,20 25)', 'LINESTRING (30 10, 10 30, 40 40)', 'MULTIPOLYGON (((10 10, 10 20, 20 20, 20 15, 10 10)),' '((60 60, 70 70, 80 60, 60 60 )))', '''MULTIPOLYGON (((40 40, 20 45, 45 30, 40 40)), ((20 35, 45 20, 30 5, 10 10, 10 30, 20 35), (30 20, 20 25, 20 15, 30 20)))''', '''MULTIPOLYGON (((30 20, 10 40, 45 40, 30 20)), ((15 5, 40 10, 10 20, 5 10, 15 5)))''', 'MULTIPOLYGON(((0 0,10 0,10 10,0 10,0 0)),' '((5 5,7 5,7 7,5 7, 5 5)))', 'GEOMETRYCOLLECTION(POINT(10 10), POINT(30 30), ' 'LINESTRING(15 15, 20 20))', ] # these are valid WKTs but not supported wkt_fail = ['POINT ZM (1 1 5 60)', 'POINT EMPTY', 'MULTIPOLYGON EMPTY'] def test_point(self): p = geometry.from_wkt('POINT (0.0 1.0)') self.assertEqual(isinstance(p, geometry.Point), True) self.assertEqual(p.x, 0.0) self.assertEqual(p.y, 1.0) self.assertEqual(p.to_wkt(), 'POINT (0.0 1.0)') self.assertEqual(p.to_wkt(), p.wkt) self.assertEqual(str(p), 'POINT (0.0 1.0)') self.assertEqual(p.geom_type, 'Point') def test_linestring(self): l = geometry.from_wkt('LINESTRING(-72.991 46.177,-73.079 46.16,' '-73.146 46.124,-73.177 46.071,-73.164 46.044)') self.assertEqual(l.to_wkt(), 'LINESTRING (-72.991 46.177, ' '-73.079 46.16, -73.146 46.124, ' '-73.177 46.071, -73.164 46.044)') self.assertEqual(isinstance(l, geometry.LineString), True) def test_linearring(self): r = geometry.from_wkt('LINEARRING (0 0,0 1,1 0,0 0)') self.assertEqual(isinstance(r, geometry.LinearRing), True) self.assertEqual(r.to_wkt(), 'LINEARRING (0.0 0.0, 0.0 1.0, ' '1.0 0.0, 0.0 0.0)') def test_polygon(self): p = geometry.from_wkt('POLYGON((-91.611 76.227,-91.543 76.217,' '-91.503 76.222,-91.483 76.221,-91.474 76.211,' '-91.484 76.197,-91.512 76.193,-91.624 76.2,' '-91.638 76.202,-91.647 76.211,-91.648 76.218,' '-91.643 76.221,-91.636 76.222,-91.611 76.227))') self.assertEqual(p.exterior.coords[0][0], -91.611) self.assertEqual(p.exterior.coords[0], p.exterior.coords[-1]) self.assertEqual(len(p.exterior.coords), 14) p = geometry.from_wkt('POLYGON((1 1,5 1,5 5,1 5,1 1),(2 2, 3 2, ' '3 3, 2 3,2 2))') self.assertEqual(p.exterior.coords[0], p.exterior.coords[-1]) self.assertEqual(p.exterior.coords[0], (1.0, 1.0)) self.assertEqual(len(list(p.interiors)), 1) self.assertEqual(list(p.interiors)[0].coords, ((2.0, 2.0), (3.0, 2.0), (3.0, 3.0), (2.0, 3.0), (2.0, 2.0))) self.assertEqual(p.to_wkt(), 'POLYGON((1.0 1.0, 5.0 1.0, 5.0 5.0, ' '1.0 5.0, 1.0 1.0),(2.0 2.0, 3.0 2.0, ' '3.0 3.0, 2.0 3.0, 2.0 2.0))') p = geometry.from_wkt('POLYGON ((30 10, 10 20, 20 40, 40 40, 30 10))') self.assertEqual(p.exterior.coords[0], p.exterior.coords[-1]) p = geometry.from_wkt('''POLYGON ((35 10, 10 20, 15 40, 45 45, 35 10), (20 30, 35 35, 30 20, 20 30))''') self.assertEqual(p.exterior.coords[0], p.exterior.coords[-1]) def test_multipoint(self): p = geometry.from_wkt('MULTIPOINT(3.5 5.6,4.8 10.5)') self.assertEqual(isinstance(p, geometry.MultiPoint), True) self.assertEqual(p.geoms[0].x, 3.5) self.assertEqual(p.geoms[1].y, 10.5) self.assertEqual(p.to_wkt(), 'MULTIPOINT(3.5 5.6, 4.8 10.5)') p = geometry.from_wkt('MULTIPOINT ((10 40), (40 30), ' '(20 20), (30 10))') self.assertEqual(isinstance(p, geometry.MultiPoint), True) self.assertEqual(p.geoms[0].x, 10.0) self.assertEqual(p.geoms[3].y, 10.0) p = geometry.from_wkt('MULTIPOINT (10 40, 40 30, 20 20, 30 10)') self.assertEqual(isinstance(p, geometry.MultiPoint), True) self.assertEqual(p.geoms[0].x, 10.0) self.assertEqual(p.geoms[3].y, 10.0) def test_multilinestring(self): p = geometry.from_wkt('MULTILINESTRING((3 4,10 50,20 25),' '(-5 -8,-10 -8,-15 -4))') self.assertEqual(p.geoms[0].coords, (((3, 4), (10, 50), (20, 25)))) self.assertEqual(p.geoms[1].coords, (((-5, -8), (-10, -8), (-15, -4)))) self.assertEqual(p.to_wkt(), 'MULTILINESTRING((3.0 4.0, 10.0 50.0, ' '20.0 25.0),(-5.0 -8.0, ' '-10.0 -8.0, -15.0 -4.0))') p = geometry.from_wkt('''MULTILINESTRING ((10 10, 20 20, 10 40), (40 40, 30 30, 40 20, 30 10))''') def test_multipolygon(self): p = geometry.from_wkt('MULTIPOLYGON(((0 0,10 20,30 40,0 0),' '(1 1,2 2,3 3,1 1)),' '((100 100,110 110,120 120,100 100)))') #two polygons: the first one has an interior ring self.assertEqual(len(p.geoms), 2) self.assertEqual(p.geoms[0].exterior.coords, ((0.0, 0.0), (10.0, 20.0), (30.0, 40.0), (0.0, 0.0))) self.assertEqual(list(p.geoms[0].interiors)[0].coords, ((1.0, 1.0), (2.0, 2.0), (3.0, 3.0), (1.0, 1.0))) self.assertEqual(p.geoms[1].exterior.coords, ((100.0, 100.0), (110.0, 110.0), (120.0, 120.0), (100.0, 100.0))) self.assertEqual(p.to_wkt(), 'MULTIPOLYGON(((0.0 0.0, 10.0 20.0, ' '30.0 40.0, 0.0 0.0),' '(1.0 1.0, 2.0 2.0, 3.0 3.0, 1.0 1.0)),' '((100.0 100.0, 110.0 110.0,' ' 120.0 120.0, 100.0 100.0)))') p = geometry.from_wkt('MULTIPOLYGON(((1 1,5 1,5 5,1 5,1 1),' '(2 2, 3 2, 3 3, 2 3,2 2)),((3 3,6 2,6 4,3 3)))') self.assertEqual(len(p.geoms), 2) p = geometry.from_wkt("MULTIPOLYGON (((30 20, 10 40, 45 40, 30 20))," "((15 5, 40 10, 10 20, 5 10, 15 5)))") self.assertEqual(p.__geo_interface__, {'type': 'MultiPolygon', 'bbox': (5.0, 5.0, 45.0, 40.0), 'coordinates': ((((30.0, 20.0), (10.0, 40.0), (45.0, 40.0), (30.0, 20.0)),), (((15.0, 5.0), (40.0, 10.0), (10.0, 20.0), (5.0, 10.0), (15.0, 5.0)),))}) def test_geometrycollection(self): gc = geometry.from_wkt('GEOMETRYCOLLECTION(POINT(4 6), ' 'LINESTRING(4 6,7 10))') self.assertEqual(len(list(gc.geoms)), 2) self.assertTrue(isinstance(list(gc.geoms)[0], geometry.Point)) self.assertTrue(isinstance(list(gc.geoms)[1], geometry.LineString)) self.assertEqual(gc.to_wkt(), 'GEOMETRYCOLLECTION (POINT (4.0 6.0), ' 'LINESTRING (4.0 6.0, 7.0 10.0))') def test_wkt_ok(self): for wkt in self.wkt_ok: geometry.from_wkt(wkt) def test_wkt_fail(self): for wkt in self.wkt_fail: self.assertRaises(Exception, geometry.from_wkt, wkt) class AsShapeTestCase(unittest.TestCase): def test_point(self): f = geometry.Point(0, 1) s = geometry.as_shape(f) self.assertEqual(f.__geo_interface__, s.__geo_interface__) def test_linestring(self): f = geometry.LineString([(0, 0), (1, 1)]) s = geometry.as_shape(f) self.assertEqual(f.__geo_interface__, s.__geo_interface__) def test_linearring(self): f = geometry.LinearRing([(0, 0), (1, 1), (1, 0), (0, 0)]) s = geometry.as_shape(f) self.assertEqual(f.__geo_interface__, s.__geo_interface__) def test_polygon(self): f = geometry.Polygon([(0, 0), (1, 1), (1, 0), (0, 0)]) s = geometry.as_shape(f) self.assertEqual(f.__geo_interface__, s.__geo_interface__) e = [(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)] i = [(1, 0), (0.5, 0.5), (1, 1), (1.5, 0.5), (1, 0)] f = geometry.Polygon(e, [i]) s = geometry.as_shape(f) self.assertEqual(f.__geo_interface__, s.__geo_interface__) ext = [(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)] int_1 = [(0.5, 0.25), (1.5, 0.25), (1.5, 1.25), (0.5, 1.25), (0.5, 0.25)] int_2 = [(0.5, 1.25), (1, 1.25), (1, 1.75), (0.5, 1.75), (0.5, 1.25)] f = geometry.Polygon(ext, [int_1, int_2]) s = geometry.as_shape(f) self.assertEqual(f.__geo_interface__, s.__geo_interface__) def test_multipoint(self): f = geometry.MultiPoint([[0.0, 0.0], [1.0, 2.0]]) s = geometry.as_shape(f) self.assertEqual(f.__geo_interface__, s.__geo_interface__) def test_multilinestring(self): f = geometry.MultiLineString([[[0.0, 0.0], [1.0, 2.0]]]) s = geometry.as_shape(f) self.assertEqual(f.__geo_interface__, s.__geo_interface__) self.assertEqual((0, 0, 1, 2), f.bounds) def test_multipolygon(self): f = geometry.MultiPolygon([(((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)), [((0.1, 0.1), (0.1, 0.2), (0.2, 0.2), (0.2, 0.1))]) ]) s = geometry.as_shape(f) self.assertEqual(f.__geo_interface__, s.__geo_interface__) def test_geometrycollection(self): p = geometry.Point(0, 1) l = geometry.LineString([(0, 0), (1, 1)]) f = geometry.GeometryCollection([p, l]) s = geometry.as_shape(f) self.assertEqual(f.__geo_interface__, s.__geo_interface__) self.assertEqual(f.__geo_interface__['geometries'][0], p.__geo_interface__) self.assertEqual(f.__geo_interface__['geometries'][1], l.__geo_interface__) def test_nongeo(self): self.assertRaises(TypeError, geometry.as_shape, 'a') def test_notimplemented(self): f = geometry._Geometry() self.assertRaises(NotImplementedError, geometry.as_shape, f) def test_dict_asshape(self): f = geometry.MultiLineString([[[0.0, 0.0], [1.0, 2.0]]]) s = geometry.as_shape(f.__geo_interface__) self.assertEqual(f.__geo_interface__, s.__geo_interface__) class OrientationTestCase(unittest.TestCase): def test_linearring(self): f = geometry.LinearRing([(0, 0), (1, 1), (1, 0), (0, 0)]) coords = f.coords f._set_orientation(False) self.assertEqual(f.coords, coords[::-1]) f._set_orientation(True) self.assertEqual(f.coords, coords) def test_polygon(self): ext = [(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)] int_1 = [(0.5, 0.25), (1.5, 0.25), (1.5, 1.25), (0.5, 1.25), (0.5, 0.25)] int_2 = [(0.5, 1.25), (1, 1.25), (1, 1.75), (0.5, 1.75), (0.5, 1.25)] p = geometry.Polygon(ext, [int_1, int_2]) self.assertEqual(list(p.exterior.coords), ext) interiors = list(p.interiors) self.assertEqual(list(interiors[0].coords), int_1) self.assertEqual(list(interiors[1].coords), int_2) p._set_orientation(False) self.assertEqual(list(p.exterior.coords), ext[::-1]) interiors = list(p.interiors) self.assertEqual(list(interiors[0].coords), int_1) self.assertEqual(list(interiors[1].coords), int_2) p._set_orientation(True) self.assertEqual(list(p.exterior.coords), ext) interiors = list(p.interiors) self.assertEqual(list(interiors[0].coords), int_1[::-1]) self.assertEqual(list(interiors[1].coords), int_2[::-1]) p._set_orientation(False, interiors=False) self.assertEqual(list(p.exterior.coords), ext[::-1]) interiors = list(p.interiors) self.assertEqual(list(interiors[0].coords), int_1[::-1]) self.assertEqual(list(interiors[1].coords), int_2[::-1]) p._set_orientation(True) p._set_orientation(False, exterior=False) self.assertEqual(list(p.exterior.coords), ext) interiors = list(p.interiors) self.assertEqual(list(interiors[0].coords), int_1) self.assertEqual(list(interiors[1].coords), int_2) def test_multipolygon(self): e0 = ((0.0, 0.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0)) p = geometry.Polygon(e0) e1 = ((0.0, 0.0), (0.0, 2.0), (2.0, 2.0), (2.0, 0.0), (0.0, 0.0)) i1 = ((1.0, 0.0), (0.5, 0.5), (1.0, 1.0), (1.5, 0.5), (1.0, 0.0)) ph1 = geometry.Polygon(e1, [i1]) mp = geometry.MultiPolygon([p, ph1]) self.assertEqual(mp.geoms[0].exterior.coords, e0) self.assertEqual(mp.geoms[1].exterior.coords, e1) self.assertEqual(list(mp.geoms[1].interiors)[0].coords, i1) mp._set_orientation(True) self.assertEqual(mp.geoms[0].exterior.coords, e0) self.assertEqual(mp.geoms[1].exterior.coords, e1) self.assertEqual(list(mp.geoms[1].interiors)[0].coords, i1) mp._set_orientation(False) self.assertEqual(mp.geoms[0].exterior.coords, e0[::-1]) self.assertEqual(mp.geoms[1].exterior.coords, e1[::-1]) self.assertEqual(list(mp.geoms[1].interiors)[0].coords, i1[::-1]) mp._set_orientation(True, exterior=False) self.assertEqual(mp.geoms[0].exterior.coords, e0[::-1]) self.assertEqual(mp.geoms[1].exterior.coords, e1[::-1]) self.assertEqual(list(mp.geoms[1].interiors)[0].coords, i1) mp._set_orientation(False) mp._set_orientation(True, interiors=False) self.assertEqual(list(mp.geoms[1].interiors)[0].coords, i1[::-1]) self.assertEqual(mp.geoms[0].exterior.coords, e0) self.assertEqual(mp.geoms[1].exterior.coords, e1) def test_orient(self): ext = [(0, 0), (0, 2), (2, 2), (2, 0), (0, 0)] int_1 = [(0.5, 0.25), (1.5, 0.25), (1.5, 1.25), (0.5, 1.25), (0.5, 0.25)] int_2 = [(0.5, 1.25), (1, 1.25), (1, 1.75), (0.5, 1.75), (0.5, 1.25)] p = geometry.Polygon(ext, [int_1, int_2]) p1 = geometry.orient(p, 1) self.assertEqual(list(p1.exterior.coords), ext[::-1]) interiors = list(p1.interiors) self.assertEqual(list(interiors[0].coords), int_1[::-1]) self.assertEqual(list(interiors[1].coords), int_2[::-1]) p2 = geometry.orient(p, -1) self.assertEqual(list(p2.exterior.coords), ext) interiors = list(p2.interiors) self.assertEqual(list(interiors[0].coords), int_1) self.assertEqual(list(interiors[1].coords), int_2) class ReprMethodTestCase(unittest.TestCase): def setUp(self): self.geometry = geometry._Geometry() self.point = geometry.Point(0, 1) self.linestring = geometry.LineString([[0, 0], [1, 0], [1, 1]]) self.linearring = geometry.LinearRing([[0, 0], [1, 0], [1, 1], [0, 0]]) self.coords_1 = ((0., 0.), (0., 1.), (1., 1.), (1., 0.), (0., 0.)) self.polygon = geometry.Polygon(self.coords_1) self.multipoint = geometry.MultiPoint([[0.0, 0.0], [1.0, 2.0]]) self.multiline = geometry.MultiLineString([[[0.0, 0.0], [1.0, 2.0]]]) self.multipoly = geometry.MultiPolygon([(((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)), [((0.1, 0.1), (0.1, 0.2), (0.2, 0.2), (0.2, 0.1))])]) self.geo_collect = geometry.GeometryCollection([self.point, self.linestring, self.linearring]) self.feature = geometry.Feature(self.point, {'a': 1, 'b': 2}) self.feature_list = [self.feature, self.feature] self.fc = geometry.FeatureCollection(self.feature_list) def test_repr(self): pointchk = "Point(0.0, 1.0)" l_stringchk = "" l_ringchk = "" polychk = "" m_pointchk = "" ml_stringchk = "".format(self.multiline.bounds) m_polychk = "".format(self.multipoly.bounds) gc_chk = "".format(self.geo_collect.bounds) fc_chk = "".format(self.fc.bounds) self.assertEquals(self.point.__repr__(), pointchk) self.assertEquals(self.linestring.__repr__(), l_stringchk) self.assertEquals(self.linearring.__repr__(), l_ringchk) self.assertEquals(self.polygon.__repr__(), polychk) self.assertEquals(self.multipoint.__repr__(), m_pointchk) self.assertEquals(self.multiline.__repr__(), ml_stringchk) self.assertEquals(self.multipoly.__repr__(), m_polychk) self.assertEquals(self.geo_collect.__repr__(), gc_chk) self.assertEquals(self.geometry.__repr__()[0:34], '') self.assertEquals(self.fc.__repr__(), fc_chk) class FeatureTestCase(unittest.TestCase): def setUp(self): self.a = geometry.Polygon(((0., 0.), (0., 1.), (1., 1.), (1., 0.), (0., 0.))) self.b = geometry.Polygon(((0., 0.), (0., 2.), (2., 1.), (2., 0.), (0., 0.))) self.f1 = geometry.Feature(self.a) self.f2 = geometry.Feature(self.b) self.f3 = geometry.Feature(self.a, feature_id='1') self.fc = geometry.FeatureCollection([self.f1, self.f2]) def test_feature(self): self.assertRaises(TypeError, geometry.Feature) self.assertEqual(self.f1.__geo_interface__, geometry.as_shape(self.f1).__geo_interface__) self.assertEqual(self.f1.__geo_interface__, {'type': 'Feature', 'bbox': (0.0, 0.0, 1.0, 1.0), 'geometry': {'type': 'Polygon', 'bbox': (0.0, 0.0, 1.0, 1.0), 'coordinates': (((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0)),), }, 'properties': {} }) self.f1.properties['coords'] = {} self.f1.properties['coords']['cube'] = (0, 0, 0) self.assertEqual(self.f1.__geo_interface__, {'type': 'Feature', 'bbox': (0.0, 0.0, 1.0, 1.0), 'geometry': {'type': 'Polygon', 'bbox': (0.0, 0.0, 1.0, 1.0), 'coordinates': (((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0)),), }, 'properties': {'coords': {'cube': (0, 0, 0)}} }) self.assertEqual(self.f1.geometry.bounds, (0.0, 0.0, 1.0, 1.0)) del self.f1.properties['coords'] def test_feature_with_id(self): self.assertEqual(self.f3.id, '1') self.assertEqual(self.f3.__geo_interface__, {'type': 'Feature', 'bbox': (0.0, 0.0, 1.0, 1.0), 'geometry': {'type': 'Polygon', 'bbox': (0.0, 0.0, 1.0, 1.0), 'coordinates': (((0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0), (0.0, 0.0)),), }, 'id': '1', 'properties': {} }) self.assertEqual(self.f3.__geo_interface__, geometry.as_shape(self.f3).__geo_interface__) def test_featurecollection(self): self.assertRaises(TypeError, geometry.FeatureCollection) self.assertRaises(TypeError, geometry.FeatureCollection, None) self.assertEqual(len(list(self.fc.features)), 2) self.assertEqual(len(self.fc), 2) self.assertEqual(self.fc.bounds, (0.0, 0.0, 2.0, 2.0)) self.assertEqual(self.fc.__geo_interface__, geometry.as_shape(self.fc).__geo_interface__) self.assertEqual([self.f1, self.f2], [feature for feature in self.fc]) def test_suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(BasicTestCase)) suite.addTest(unittest.makeSuite(WKTTestCase)) suite.addTest(unittest.makeSuite(AsShapeTestCase)) suite.addTest(unittest.makeSuite(OrientationTestCase)) suite.addTest(unittest.makeSuite(ReprMethodTestCase)) suite.addTest(unittest.makeSuite(FeatureTestCase)) return suite if __name__ == '__main__': unittest.main() pygeoif-0.7/setup.py0000664000175100017510000000423013102645124016527 0ustar christianchristian00000000000000from setuptools import setup from setuptools import find_packages from setuptools.command.test import test as TestCommand import sys import os class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): #import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.test_args) sys.exit(errno) version = '0.7' README = open("README.rst").read() HISTORY = open(os.path.join("docs", "HISTORY.txt")).read() setup(name='pygeoif', version=version, description="A basic implementation of the __geo_interface__", long_description=README + "\n" + HISTORY, classifiers=[ "Topic :: Scientific/Engineering :: GIS", "Programming Language :: Python", 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Development Status :: 5 - Production/Stable', 'Operating System :: OS Independent', ], # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers keywords='GIS Spatial WKT', author='Christian Ledermann', author_email='christian.ledermann@gmail.com', url='https://github.com/cleder/pygeoif/', license='LGPL', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, zip_safe=False, tests_require=['pytest'], cmdclass={'test': PyTest}, install_requires=[ # -*- Extra requirements: -*- ], entry_points=""" # -*- Entry points: -*- """, ) pygeoif-0.7/PKG-INFO0000664000175100017510000003607213102646233016125 0ustar christianchristian00000000000000Metadata-Version: 1.1 Name: pygeoif Version: 0.7 Summary: A basic implementation of the __geo_interface__ Home-page: https://github.com/cleder/pygeoif/ Author: Christian Ledermann Author-email: christian.ledermann@gmail.com License: LGPL Description: Introduction ============ PyGeoIf provides a GeoJSON-like protocol for geo-spatial (GIS) vector data. see https://gist.github.com/2217756 Other Python programs and packages that you may have heard of already implement this protocol: * ArcPy http://help.arcgis.com/en/arcgisdesktop/ * descartes https://bitbucket.org/sgillies/descartes/ * geojson http://pypi.python.org/pypi/geojson/ * PySAL http://pysal.geodacenter.org/ * Shapely https://github.com/Toblerity/Shapely * pyshp https://pypi.python.org/pypi/pyshp So when you want to write your own geospatial library with support for this protocol you may use pygeoif as a starting point and build your functionality on top of it You may think of pygeoif as a 'shapely ultralight' which lets you construct geometries and perform **very** basic operations like reading and writing geometries from/to WKT, constructing line strings out of points, polygons from linear rings, multi polygons from polygons, etc. It was inspired by shapely and implements the geometries in a way that when you are familiar with shapely you feel right at home with pygeoif It was written to provide clean and python only geometries for fastkml_ .. _fastkml: http://pypi.python.org/pypi/fastkml/ PyGeoIf is continually tested with *Travis CI* .. image:: https://api.travis-ci.org/cleder/pygeoif.png :target: https://travis-ci.org/cleder/pygeoif .. image:: https://coveralls.io/repos/cleder/pygeoif/badge.png?branch=master :target: https://coveralls.io/r/cleder/pygeoif?branch=master Example ======== >>> from pygeoif import geometry >>> p = geometry.Point(1,1) >>> p.__geo_interface__ {'type': 'Point', 'coordinates': (1.0, 1.0)} >>> print p POINT (1.0 1.0) >>> p1 = geometry.Point(0,0) >>> l = geometry.LineString([p,p1]) >>> l.bounds (0.0, 0.0, 1.0, 1.0) >>> dir(l) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__geo_interface__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_coordinates', '_geoms', '_type', 'bounds', 'coords', 'geom_type', 'geoms', 'to_wkt'] >>> print l LINESTRING (1.0 1.0, 0.0 0.0) You find more examples in the `test_main.py `_ file which cover every aspect of pygeoif or in fastkml_. Classes ======== All classes implement the attribute: * __geo_interface__: as dicussed above All geometry classes implement the attributes: * geom_type: Returns a string specifying the Geometry Type of the object * bounds: Returns a (minx, miny, maxx, maxy) tuple (float values) that bounds the object. * wkt: Returns the 'Well Known Text' representation of the object and the method: * to_wkt which also prints the object GeoObject ---------- Base class for Geometry, Feature, and FeatureCollection Geometry -------- Base class for geometry objects. Inherits from Geoobject. Point ----- A zero dimensional geometry A point has zero length and zero area. Attributes ~~~~~~~~~~~ x, y, z : float Coordinate values Example ~~~~~~~~ >>> p = Point(1.0, -1.0) >>> print p POINT (1.0000000000000000 -1.0000000000000000) >>> p.y -1.0 >>> p.x 1.0 LineString ----------- A one-dimensional figure comprising one or more line segments A LineString has non-zero length and zero area. It may approximate a curve and need not be straight. Unlike a LinearRing, a LineString is not closed. Attributes ~~~~~~~~~~~ geoms : sequence A sequence of Points LinearRing ----------- A closed one-dimensional geometry comprising one or more line segments A LinearRing that crosses itself or touches itself at a single point is invalid and operations on it may fail. A Linear Ring is self closing Polygon -------- A two-dimensional figure bounded by a linear ring A polygon has a non-zero area. It may have one or more negative-space "holes" which are also bounded by linear rings. If any rings cross each other, the geometry is invalid and operations on it may fail. Attributes ~~~~~~~~~~~ exterior : LinearRing The ring which bounds the positive space of the polygon. interiors : sequence A sequence of rings which bound all existing holes. MultiPoint ---------- A collection of one or more points Attributes ~~~~~~~~~~~ geoms : sequence A sequence of Points MultiLineString ---------------- A collection of one or more line strings A MultiLineString has non-zero length and zero area. Attributes ~~~~~~~~~~~ geoms : sequence A sequence of LineStrings MultiPolygon ------------- A collection of one or more polygons Attributes ~~~~~~~~~~~~~ geoms : sequence A sequence of `Polygon` instances GeometryCollection ------------------- A heterogenous collection of geometries (Points, LineStrings, LinearRings and Polygons) Attributes ~~~~~~~~~~~ geoms : sequence A sequence of geometry instances Please note: GEOMETRYCOLLECTION isn't supported by the Shapefile format. And this sub-class isn't generally supported by ordinary GIS sw (viewers and so on). So it's very rarely used in the real GIS professional world. Example ~~~~~~~~ >>> from pygeoif import geometry >>> p = geometry.Point(1.0, -1.0) >>> p2 = geometry.Point(1.0, -1.0) >>> geoms = [p, p2] >>> c = geometry.GeometryCollection(geoms) >>> c.__geo_interface__ {'type': 'GeometryCollection', 'geometries': [{'type': 'Point', 'coordinates': (1.0, -1.0)},/ {'type': 'Point', 'coordinates': (1.0, -1.0)}]} >>> [geom for geom in geoms] [Point(1.0, -1.0), Point(1.0, -1.0)] Feature ------- Aggregates a geometry instance with associated user-defined properties. Attributes ~~~~~~~~~~~ geometry : object A geometry instance properties : dict A dictionary linking field keys with values associated with with geometry instance Example ~~~~~~~~ >>> p = Point(1.0, -1.0) >>> props = {'Name': 'Sample Point', 'Other': 'Other Data'} >>> a = Feature(p, props) >>> a.properties {'Name': 'Sample Point', 'Other': 'Other Data'} >>> a.properties['Name'] 'Sample Point' FeatureCollection ----------------- A heterogenous collection of Features Attributes ~~~~~~~~~~~ features: sequence A sequence of feature instances Example ~~~~~~~~ >>> from pygeoif import geometry >>> p = geometry.Point(1.0, -1.0) >>> props = {'Name': 'Sample Point', 'Other': 'Other Data'} >>> a = geometry.Feature(p, props) >>> p2 = geometry.Point(1.0, -1.0) >>> props2 = {'Name': 'Sample Point2', 'Other': 'Other Data2'} >>> b = geometry.Feature(p2, props2) >>> features = [a, b] >>> c = geometry.FeatureCollection(features) >>> c.__geo_interface__ {'type': 'FeatureCollection', 'features': [{'geometry': {'type': 'Point', 'coordinates': (1.0, -1.0)},/ 'type': 'Feature', 'properties': {'Other': 'Other Data', 'Name': 'Sample Point'}},/ {'geometry': {'type': 'Point', 'coordinates': (1.0, -1.0)}, 'type': 'Feature',/ 'properties': {'Other': 'Other Data2', 'Name': 'Sample Point2'}}]} >>> [feature for feature in c] [, ] Functions ========= as_shape -------- Create a pygeoif feature from an object that provides the __geo_interface__ >>> from shapely.geometry import Point >>> from pygeoif import geometry >>> geometry.as_shape(Point(0,0)) from_wkt --------- Create a geometry from its WKT representation >>> p = geometry.from_wkt('POINT (0 1)') >>> print p POINT (0.0 1.0) signed_area ------------ Return the signed area enclosed by a ring using the linear time algorithm at http://www.cgafaq.info/wiki/Polygon_Area. A value >= 0 indicates a counter-clockwise oriented ring. orient ------- Returns a copy of the polygon with exterior in counter-clockwise and interiors in clockwise orientation for sign=1.0 and the other way round for sign=-1.0 mapping ------- Returns the __geo_interface__ dictionary Development =========== Installation ------------ You can install PyGeoIf from pypi using pip:: pip install pygeoif Testing ------- In order to provide a Travis-CI like testing of the PyGeoIf package during development, you can use tox (``pip install tox``) to evaluate the tests on all supported Python interpreters which you have installed on your system. You can run the tests with ``tox --skip-missin-interpreters`` and are looking for output similar to the following:: ______________________________________________________ summary ______________________________________________________ SKIPPED: py26: InterpreterNotFound: python2.6 py27: commands succeeded SKIPPED: py32: InterpreterNotFound: python3.2 SKIPPED: py33: InterpreterNotFound: python3.3 py34: commands succeeded SKIPPED: pypy: InterpreterNotFound: pypy SKIPPED: pypy3: InterpreterNotFound: pypy3 congratulations :) You are primarily looking for the ``congratulations :)`` line at the bottom, signifying that the code is working as expected on all configurations available. Changelog ========= 0.7 (2017/05/04) ----------------- - fix broken multipolygon [mindflayer] - add "bbox" to `__geo_interface__` output [jzmiller1] 0.6 (2015/08/04) ----------------- - Add id to feature [jzmiller1] 0.5 (2015/07/13) ----------------- - Add __iter__ method to FeatureCollection and GeometryCollection [jzmiller1]. - add pypy and pypy3 and python 3.4 to travis. - Add tox configuration for performing local testing [Ian Lee]. - Add Travis continuous deployment. 0.4 (2013/10/25) ----------------- - after a year in production promote it to `Development Status :: 5 - Production/Stable` - MultiPolygons return tuples as the __geo_interface__ 0.3.1 (2012/11/15) ------------------ - specify minor python versions tested with Travis CI - fix for signed area 0.3 (2012/11/14) ------------------- - add GeometryCollection - len(Multi*) and len(GeometryCollection) returns the number of contained Geometries - add orient function to get clockwise or counterclockwise oriented poygons - add signed_area function - add _set_orientation method to lineStrings, Polygons and MultiPolygons 0.2.1 (2012/08/02) ------------------- - as_shape also accepts an object that is neither a dictionary nor has a __geo_interface__ but can be converted into a __geo_interface__ compliant dictionary 0.2 (2012/08/01) ----------------- - change license to LGPL - add wkt as a property - as_shape also accepts a __geo_interface__ compliant dictionary - test with python3 0.1 (2012/07/27) ----------------- - initial release Keywords: GIS Spatial WKT Platform: UNKNOWN Classifier: Topic :: Scientific/Engineering :: GIS Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL) Classifier: Development Status :: 5 - Production/Stable Classifier: Operating System :: OS Independent pygeoif-0.7/setup.cfg0000664000175100017510000000007313102646233016641 0ustar christianchristian00000000000000[egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 pygeoif-0.7/docs/0000775000175100017510000000000013102646233015750 5ustar christianchristian00000000000000pygeoif-0.7/docs/HISTORY.txt0000664000175100017510000000277613102646203017663 0ustar christianchristian00000000000000Changelog ========= 0.7 (2017/05/04) ----------------- - fix broken multipolygon [mindflayer] - add "bbox" to `__geo_interface__` output [jzmiller1] 0.6 (2015/08/04) ----------------- - Add id to feature [jzmiller1] 0.5 (2015/07/13) ----------------- - Add __iter__ method to FeatureCollection and GeometryCollection [jzmiller1]. - add pypy and pypy3 and python 3.4 to travis. - Add tox configuration for performing local testing [Ian Lee]. - Add Travis continuous deployment. 0.4 (2013/10/25) ----------------- - after a year in production promote it to `Development Status :: 5 - Production/Stable` - MultiPolygons return tuples as the __geo_interface__ 0.3.1 (2012/11/15) ------------------ - specify minor python versions tested with Travis CI - fix for signed area 0.3 (2012/11/14) ------------------- - add GeometryCollection - len(Multi*) and len(GeometryCollection) returns the number of contained Geometries - add orient function to get clockwise or counterclockwise oriented poygons - add signed_area function - add _set_orientation method to lineStrings, Polygons and MultiPolygons 0.2.1 (2012/08/02) ------------------- - as_shape also accepts an object that is neither a dictionary nor has a __geo_interface__ but can be converted into a __geo_interface__ compliant dictionary 0.2 (2012/08/01) ----------------- - change license to LGPL - add wkt as a property - as_shape also accepts a __geo_interface__ compliant dictionary - test with python3 0.1 (2012/07/27) ----------------- - initial release pygeoif-0.7/docs/LICENSE.txt0000664000175100017510000000155513102645124017577 0ustar christianchristian00000000000000 Pygeoif is a basic implementation of the __geo_interface__ in pure Python Copyright (C) 2012 Christian Ledermann This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA pygeoif-0.7/docs/CONTRIBUTORS.txt0000664000175100017510000000024013102646203020437 0ustar christianchristian00000000000000Contributors ============= - Ian Lee - Zac Miller (jzmiller1) - John Dees (johnpdees) - NormWorthington - Giorgio Salluzzo (mindflayer) pygeoif-0.7/docs/LICENSE.GPL0000664000175100017510000006355413102645124017411 0ustar christianchristian00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! pygeoif-0.7/README.rst0000664000175100017510000002217013102645124016507 0ustar christianchristian00000000000000Introduction ============ PyGeoIf provides a GeoJSON-like protocol for geo-spatial (GIS) vector data. see https://gist.github.com/2217756 Other Python programs and packages that you may have heard of already implement this protocol: * ArcPy http://help.arcgis.com/en/arcgisdesktop/ * descartes https://bitbucket.org/sgillies/descartes/ * geojson http://pypi.python.org/pypi/geojson/ * PySAL http://pysal.geodacenter.org/ * Shapely https://github.com/Toblerity/Shapely * pyshp https://pypi.python.org/pypi/pyshp So when you want to write your own geospatial library with support for this protocol you may use pygeoif as a starting point and build your functionality on top of it You may think of pygeoif as a 'shapely ultralight' which lets you construct geometries and perform **very** basic operations like reading and writing geometries from/to WKT, constructing line strings out of points, polygons from linear rings, multi polygons from polygons, etc. It was inspired by shapely and implements the geometries in a way that when you are familiar with shapely you feel right at home with pygeoif It was written to provide clean and python only geometries for fastkml_ .. _fastkml: http://pypi.python.org/pypi/fastkml/ PyGeoIf is continually tested with *Travis CI* .. image:: https://api.travis-ci.org/cleder/pygeoif.png :target: https://travis-ci.org/cleder/pygeoif .. image:: https://coveralls.io/repos/cleder/pygeoif/badge.png?branch=master :target: https://coveralls.io/r/cleder/pygeoif?branch=master Example ======== >>> from pygeoif import geometry >>> p = geometry.Point(1,1) >>> p.__geo_interface__ {'type': 'Point', 'coordinates': (1.0, 1.0)} >>> print p POINT (1.0 1.0) >>> p1 = geometry.Point(0,0) >>> l = geometry.LineString([p,p1]) >>> l.bounds (0.0, 0.0, 1.0, 1.0) >>> dir(l) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__geo_interface__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_coordinates', '_geoms', '_type', 'bounds', 'coords', 'geom_type', 'geoms', 'to_wkt'] >>> print l LINESTRING (1.0 1.0, 0.0 0.0) You find more examples in the `test_main.py `_ file which cover every aspect of pygeoif or in fastkml_. Classes ======== All classes implement the attribute: * __geo_interface__: as dicussed above All geometry classes implement the attributes: * geom_type: Returns a string specifying the Geometry Type of the object * bounds: Returns a (minx, miny, maxx, maxy) tuple (float values) that bounds the object. * wkt: Returns the 'Well Known Text' representation of the object and the method: * to_wkt which also prints the object GeoObject ---------- Base class for Geometry, Feature, and FeatureCollection Geometry -------- Base class for geometry objects. Inherits from Geoobject. Point ----- A zero dimensional geometry A point has zero length and zero area. Attributes ~~~~~~~~~~~ x, y, z : float Coordinate values Example ~~~~~~~~ >>> p = Point(1.0, -1.0) >>> print p POINT (1.0000000000000000 -1.0000000000000000) >>> p.y -1.0 >>> p.x 1.0 LineString ----------- A one-dimensional figure comprising one or more line segments A LineString has non-zero length and zero area. It may approximate a curve and need not be straight. Unlike a LinearRing, a LineString is not closed. Attributes ~~~~~~~~~~~ geoms : sequence A sequence of Points LinearRing ----------- A closed one-dimensional geometry comprising one or more line segments A LinearRing that crosses itself or touches itself at a single point is invalid and operations on it may fail. A Linear Ring is self closing Polygon -------- A two-dimensional figure bounded by a linear ring A polygon has a non-zero area. It may have one or more negative-space "holes" which are also bounded by linear rings. If any rings cross each other, the geometry is invalid and operations on it may fail. Attributes ~~~~~~~~~~~ exterior : LinearRing The ring which bounds the positive space of the polygon. interiors : sequence A sequence of rings which bound all existing holes. MultiPoint ---------- A collection of one or more points Attributes ~~~~~~~~~~~ geoms : sequence A sequence of Points MultiLineString ---------------- A collection of one or more line strings A MultiLineString has non-zero length and zero area. Attributes ~~~~~~~~~~~ geoms : sequence A sequence of LineStrings MultiPolygon ------------- A collection of one or more polygons Attributes ~~~~~~~~~~~~~ geoms : sequence A sequence of `Polygon` instances GeometryCollection ------------------- A heterogenous collection of geometries (Points, LineStrings, LinearRings and Polygons) Attributes ~~~~~~~~~~~ geoms : sequence A sequence of geometry instances Please note: GEOMETRYCOLLECTION isn't supported by the Shapefile format. And this sub-class isn't generally supported by ordinary GIS sw (viewers and so on). So it's very rarely used in the real GIS professional world. Example ~~~~~~~~ >>> from pygeoif import geometry >>> p = geometry.Point(1.0, -1.0) >>> p2 = geometry.Point(1.0, -1.0) >>> geoms = [p, p2] >>> c = geometry.GeometryCollection(geoms) >>> c.__geo_interface__ {'type': 'GeometryCollection', 'geometries': [{'type': 'Point', 'coordinates': (1.0, -1.0)},/ {'type': 'Point', 'coordinates': (1.0, -1.0)}]} >>> [geom for geom in geoms] [Point(1.0, -1.0), Point(1.0, -1.0)] Feature ------- Aggregates a geometry instance with associated user-defined properties. Attributes ~~~~~~~~~~~ geometry : object A geometry instance properties : dict A dictionary linking field keys with values associated with with geometry instance Example ~~~~~~~~ >>> p = Point(1.0, -1.0) >>> props = {'Name': 'Sample Point', 'Other': 'Other Data'} >>> a = Feature(p, props) >>> a.properties {'Name': 'Sample Point', 'Other': 'Other Data'} >>> a.properties['Name'] 'Sample Point' FeatureCollection ----------------- A heterogenous collection of Features Attributes ~~~~~~~~~~~ features: sequence A sequence of feature instances Example ~~~~~~~~ >>> from pygeoif import geometry >>> p = geometry.Point(1.0, -1.0) >>> props = {'Name': 'Sample Point', 'Other': 'Other Data'} >>> a = geometry.Feature(p, props) >>> p2 = geometry.Point(1.0, -1.0) >>> props2 = {'Name': 'Sample Point2', 'Other': 'Other Data2'} >>> b = geometry.Feature(p2, props2) >>> features = [a, b] >>> c = geometry.FeatureCollection(features) >>> c.__geo_interface__ {'type': 'FeatureCollection', 'features': [{'geometry': {'type': 'Point', 'coordinates': (1.0, -1.0)},/ 'type': 'Feature', 'properties': {'Other': 'Other Data', 'Name': 'Sample Point'}},/ {'geometry': {'type': 'Point', 'coordinates': (1.0, -1.0)}, 'type': 'Feature',/ 'properties': {'Other': 'Other Data2', 'Name': 'Sample Point2'}}]} >>> [feature for feature in c] [, ] Functions ========= as_shape -------- Create a pygeoif feature from an object that provides the __geo_interface__ >>> from shapely.geometry import Point >>> from pygeoif import geometry >>> geometry.as_shape(Point(0,0)) from_wkt --------- Create a geometry from its WKT representation >>> p = geometry.from_wkt('POINT (0 1)') >>> print p POINT (0.0 1.0) signed_area ------------ Return the signed area enclosed by a ring using the linear time algorithm at http://www.cgafaq.info/wiki/Polygon_Area. A value >= 0 indicates a counter-clockwise oriented ring. orient ------- Returns a copy of the polygon with exterior in counter-clockwise and interiors in clockwise orientation for sign=1.0 and the other way round for sign=-1.0 mapping ------- Returns the __geo_interface__ dictionary Development =========== Installation ------------ You can install PyGeoIf from pypi using pip:: pip install pygeoif Testing ------- In order to provide a Travis-CI like testing of the PyGeoIf package during development, you can use tox (``pip install tox``) to evaluate the tests on all supported Python interpreters which you have installed on your system. You can run the tests with ``tox --skip-missin-interpreters`` and are looking for output similar to the following:: ______________________________________________________ summary ______________________________________________________ SKIPPED: py26: InterpreterNotFound: python2.6 py27: commands succeeded SKIPPED: py32: InterpreterNotFound: python3.2 SKIPPED: py33: InterpreterNotFound: python3.3 py34: commands succeeded SKIPPED: pypy: InterpreterNotFound: pypy SKIPPED: pypy3: InterpreterNotFound: pypy3 congratulations :) You are primarily looking for the ``congratulations :)`` line at the bottom, signifying that the code is working as expected on all configurations available.