summaryrefslogtreecommitdiff
path: root/lib/python2.7/site-packages/django/contrib/gis/geos
diff options
context:
space:
mode:
Diffstat (limited to 'lib/python2.7/site-packages/django/contrib/gis/geos')
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/__init__.py20
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/base.py51
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/collections.py124
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/coordseq.py157
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/error.py20
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/factory.py35
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/geometry.py715
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/io.py20
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/libgeos.py155
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/linestring.py153
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/mutable_list.py328
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/point.py137
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/polygon.py170
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/prepared.py35
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/__init__.py30
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/coordseq.py83
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/errcheck.py95
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/geom.py119
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/io.py265
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/misc.py40
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/predicates.py44
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/prepared.py25
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/threadsafe.py86
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/topology.py64
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/tests/__init__.py0
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/tests/test_geos.py1108
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/tests/test_geos_mutation.py134
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/tests/test_io.py116
-rw-r--r--lib/python2.7/site-packages/django/contrib/gis/geos/tests/test_mutable_list.py397
29 files changed, 4726 insertions, 0 deletions
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/__init__.py b/lib/python2.7/site-packages/django/contrib/gis/geos/__init__.py
new file mode 100644
index 0000000..945f561
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/__init__.py
@@ -0,0 +1,20 @@
+"""
+The GeoDjango GEOS module. Please consult the GeoDjango documentation
+for more details:
+ http://geodjango.org/docs/geos.html
+"""
+try:
+ from .libgeos import geos_version, geos_version_info, GEOS_PREPARE
+ HAS_GEOS = True
+except ImportError:
+ HAS_GEOS = False
+
+if HAS_GEOS:
+ from .geometry import GEOSGeometry, wkt_regex, hex_regex
+ from .point import Point
+ from .linestring import LineString, LinearRing
+ from .polygon import Polygon
+ from .collections import GeometryCollection, MultiPoint, MultiLineString, MultiPolygon
+ from .error import GEOSException, GEOSIndexError
+ from .io import WKTReader, WKTWriter, WKBReader, WKBWriter
+ from .factory import fromfile, fromstr
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/base.py b/lib/python2.7/site-packages/django/contrib/gis/geos/base.py
new file mode 100644
index 0000000..fd2693e
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/base.py
@@ -0,0 +1,51 @@
+from ctypes import c_void_p
+
+from django.contrib.gis.geos.error import GEOSException
+
+# Trying to import GDAL libraries, if available. Have to place in
+# try/except since this package may be used outside GeoDjango.
+try:
+ from django.contrib.gis import gdal
+except ImportError:
+ # A 'dummy' gdal module.
+ class GDALInfo(object):
+ HAS_GDAL = False
+ gdal = GDALInfo()
+
+# NumPy supported?
+try:
+ import numpy
+except ImportError:
+ numpy = False
+
+class GEOSBase(object):
+ """
+ Base object for GEOS objects that has a pointer access property
+ that controls access to the underlying C pointer.
+ """
+ # Initially the pointer is NULL.
+ _ptr = None
+
+ # Default allowed pointer type.
+ ptr_type = c_void_p
+
+ # Pointer access property.
+ def _get_ptr(self):
+ # Raise an exception if the pointer isn't valid don't
+ # want to be passing NULL pointers to routines --
+ # that's very bad.
+ if self._ptr: return self._ptr
+ else: raise GEOSException('NULL GEOS %s pointer encountered.' % self.__class__.__name__)
+
+ def _set_ptr(self, ptr):
+ # Only allow the pointer to be set with pointers of the
+ # compatible type or None (NULL).
+ if ptr is None or isinstance(ptr, self.ptr_type):
+ self._ptr = ptr
+ else:
+ raise TypeError('Incompatible pointer type')
+
+ # Property for controlling access to the GEOS object pointers. Using
+ # this raises an exception when the pointer is NULL, thus preventing
+ # the C library from attempting to access an invalid memory location.
+ ptr = property(_get_ptr, _set_ptr)
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/collections.py b/lib/python2.7/site-packages/django/contrib/gis/geos/collections.py
new file mode 100644
index 0000000..2b62bce
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/collections.py
@@ -0,0 +1,124 @@
+"""
+ This module houses the Geometry Collection objects:
+ GeometryCollection, MultiPoint, MultiLineString, and MultiPolygon
+"""
+from ctypes import c_int, c_uint, byref
+from django.contrib.gis.geos.error import GEOSException
+from django.contrib.gis.geos.geometry import GEOSGeometry
+from django.contrib.gis.geos.libgeos import get_pointer_arr, GEOS_PREPARE
+from django.contrib.gis.geos.linestring import LineString, LinearRing
+from django.contrib.gis.geos.point import Point
+from django.contrib.gis.geos.polygon import Polygon
+from django.contrib.gis.geos import prototypes as capi
+from django.utils.six.moves import xrange
+
+class GeometryCollection(GEOSGeometry):
+ _typeid = 7
+
+ def __init__(self, *args, **kwargs):
+ "Initializes a Geometry Collection from a sequence of Geometry objects."
+
+ # Checking the arguments
+ if not args:
+ raise TypeError('Must provide at least one Geometry to initialize %s.' % self.__class__.__name__)
+
+ if len(args) == 1:
+ # If only one geometry provided or a list of geometries is provided
+ # in the first argument.
+ if isinstance(args[0], (tuple, list)):
+ init_geoms = args[0]
+ else:
+ init_geoms = args
+ else:
+ init_geoms = args
+
+ # Ensuring that only the permitted geometries are allowed in this collection
+ # this is moved to list mixin super class
+ self._check_allowed(init_geoms)
+
+ # Creating the geometry pointer array.
+ collection = self._create_collection(len(init_geoms), iter(init_geoms))
+ super(GeometryCollection, self).__init__(collection, **kwargs)
+
+ def __iter__(self):
+ "Iterates over each Geometry in the Collection."
+ for i in xrange(len(self)):
+ yield self[i]
+
+ def __len__(self):
+ "Returns the number of geometries in this Collection."
+ return self.num_geom
+
+ ### Methods for compatibility with ListMixin ###
+ def _create_collection(self, length, items):
+ # Creating the geometry pointer array.
+ geoms = get_pointer_arr(length)
+ for i, g in enumerate(items):
+ # this is a little sloppy, but makes life easier
+ # allow GEOSGeometry types (python wrappers) or pointer types
+ geoms[i] = capi.geom_clone(getattr(g, 'ptr', g))
+
+ return capi.create_collection(c_int(self._typeid), byref(geoms), c_uint(length))
+
+ def _get_single_internal(self, index):
+ return capi.get_geomn(self.ptr, index)
+
+ def _get_single_external(self, index):
+ "Returns the Geometry from this Collection at the given index (0-based)."
+ # Checking the index and returning the corresponding GEOS geometry.
+ return GEOSGeometry(capi.geom_clone(self._get_single_internal(index)), srid=self.srid)
+
+ def _set_list(self, length, items):
+ "Create a new collection, and destroy the contents of the previous pointer."
+ prev_ptr = self.ptr
+ srid = self.srid
+ self.ptr = self._create_collection(length, items)
+ if srid: self.srid = srid
+ capi.destroy_geom(prev_ptr)
+
+ _set_single = GEOSGeometry._set_single_rebuild
+ _assign_extended_slice = GEOSGeometry._assign_extended_slice_rebuild
+
+ @property
+ def kml(self):
+ "Returns the KML for this Geometry Collection."
+ return '<MultiGeometry>%s</MultiGeometry>' % ''.join([g.kml for g in self])
+
+ @property
+ def tuple(self):
+ "Returns a tuple of all the coordinates in this Geometry Collection"
+ return tuple([g.tuple for g in self])
+ coords = tuple
+
+# MultiPoint, MultiLineString, and MultiPolygon class definitions.
+class MultiPoint(GeometryCollection):
+ _allowed = Point
+ _typeid = 4
+
+class MultiLineString(GeometryCollection):
+ _allowed = (LineString, LinearRing)
+ _typeid = 5
+
+ @property
+ def merged(self):
+ """
+ Returns a LineString representing the line merge of this
+ MultiLineString.
+ """
+ return self._topology(capi.geos_linemerge(self.ptr))
+
+class MultiPolygon(GeometryCollection):
+ _allowed = Polygon
+ _typeid = 6
+
+ @property
+ def cascaded_union(self):
+ "Returns a cascaded union of this MultiPolygon."
+ if GEOS_PREPARE:
+ return GEOSGeometry(capi.geos_cascaded_union(self.ptr), self.srid)
+ else:
+ raise GEOSException('The cascaded union operation requires GEOS 3.1+.')
+
+# Setting the allowed types here since GeometryCollection is defined before
+# its subclasses.
+GeometryCollection._allowed = (Point, LineString, LinearRing, Polygon, MultiPoint, MultiLineString, MultiPolygon)
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/coordseq.py b/lib/python2.7/site-packages/django/contrib/gis/geos/coordseq.py
new file mode 100644
index 0000000..acf34f7
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/coordseq.py
@@ -0,0 +1,157 @@
+"""
+ This module houses the GEOSCoordSeq object, which is used internally
+ by GEOSGeometry to house the actual coordinates of the Point,
+ LineString, and LinearRing geometries.
+"""
+from ctypes import c_double, c_uint, byref
+from django.contrib.gis.geos.base import GEOSBase, numpy
+from django.contrib.gis.geos.error import GEOSException, GEOSIndexError
+from django.contrib.gis.geos.libgeos import CS_PTR
+from django.contrib.gis.geos import prototypes as capi
+from django.utils.six.moves import xrange
+
+class GEOSCoordSeq(GEOSBase):
+ "The internal representation of a list of coordinates inside a Geometry."
+
+ ptr_type = CS_PTR
+
+ #### Python 'magic' routines ####
+ def __init__(self, ptr, z=False):
+ "Initializes from a GEOS pointer."
+ if not isinstance(ptr, CS_PTR):
+ raise TypeError('Coordinate sequence should initialize with a CS_PTR.')
+ self._ptr = ptr
+ self._z = z
+
+ def __iter__(self):
+ "Iterates over each point in the coordinate sequence."
+ for i in xrange(self.size):
+ yield self[i]
+
+ def __len__(self):
+ "Returns the number of points in the coordinate sequence."
+ return int(self.size)
+
+ def __str__(self):
+ "Returns the string representation of the coordinate sequence."
+ return str(self.tuple)
+
+ def __getitem__(self, index):
+ "Returns the coordinate sequence value at the given index."
+ coords = [self.getX(index), self.getY(index)]
+ if self.dims == 3 and self._z:
+ coords.append(self.getZ(index))
+ return tuple(coords)
+
+ def __setitem__(self, index, value):
+ "Sets the coordinate sequence value at the given index."
+ # Checking the input value
+ if isinstance(value, (list, tuple)):
+ pass
+ elif numpy and isinstance(value, numpy.ndarray):
+ pass
+ else:
+ raise TypeError('Must set coordinate with a sequence (list, tuple, or numpy array).')
+ # Checking the dims of the input
+ if self.dims == 3 and self._z:
+ n_args = 3
+ set_3d = True
+ else:
+ n_args = 2
+ set_3d = False
+ if len(value) != n_args:
+ raise TypeError('Dimension of value does not match.')
+ # Setting the X, Y, Z
+ self.setX(index, value[0])
+ self.setY(index, value[1])
+ if set_3d: self.setZ(index, value[2])
+
+ #### Internal Routines ####
+ def _checkindex(self, index):
+ "Checks the given index."
+ sz = self.size
+ if (sz < 1) or (index < 0) or (index >= sz):
+ raise GEOSIndexError('invalid GEOS Geometry index: %s' % str(index))
+
+ def _checkdim(self, dim):
+ "Checks the given dimension."
+ if dim < 0 or dim > 2:
+ raise GEOSException('invalid ordinate dimension "%d"' % dim)
+
+ #### Ordinate getting and setting routines ####
+ def getOrdinate(self, dimension, index):
+ "Returns the value for the given dimension and index."
+ self._checkindex(index)
+ self._checkdim(dimension)
+ return capi.cs_getordinate(self.ptr, index, dimension, byref(c_double()))
+
+ def setOrdinate(self, dimension, index, value):
+ "Sets the value for the given dimension and index."
+ self._checkindex(index)
+ self._checkdim(dimension)
+ capi.cs_setordinate(self.ptr, index, dimension, value)
+
+ def getX(self, index):
+ "Get the X value at the index."
+ return self.getOrdinate(0, index)
+
+ def setX(self, index, value):
+ "Set X with the value at the given index."
+ self.setOrdinate(0, index, value)
+
+ def getY(self, index):
+ "Get the Y value at the given index."
+ return self.getOrdinate(1, index)
+
+ def setY(self, index, value):
+ "Set Y with the value at the given index."
+ self.setOrdinate(1, index, value)
+
+ def getZ(self, index):
+ "Get Z with the value at the given index."
+ return self.getOrdinate(2, index)
+
+ def setZ(self, index, value):
+ "Set Z with the value at the given index."
+ self.setOrdinate(2, index, value)
+
+ ### Dimensions ###
+ @property
+ def size(self):
+ "Returns the size of this coordinate sequence."
+ return capi.cs_getsize(self.ptr, byref(c_uint()))
+
+ @property
+ def dims(self):
+ "Returns the dimensions of this coordinate sequence."
+ return capi.cs_getdims(self.ptr, byref(c_uint()))
+
+ @property
+ def hasz(self):
+ """
+ Returns whether this coordinate sequence is 3D. This property value is
+ inherited from the parent Geometry.
+ """
+ return self._z
+
+ ### Other Methods ###
+ def clone(self):
+ "Clones this coordinate sequence."
+ return GEOSCoordSeq(capi.cs_clone(self.ptr), self.hasz)
+
+ @property
+ def kml(self):
+ "Returns the KML representation for the coordinates."
+ # Getting the substitution string depending on whether the coordinates have
+ # a Z dimension.
+ if self.hasz: substr = '%s,%s,%s '
+ else: substr = '%s,%s,0 '
+ return '<coordinates>%s</coordinates>' % \
+ ''.join([substr % self[i] for i in xrange(len(self))]).strip()
+
+ @property
+ def tuple(self):
+ "Returns a tuple version of this coordinate sequence."
+ n = self.size
+ if n == 1: return self[0]
+ else: return tuple([self[i] for i in xrange(n)])
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/error.py b/lib/python2.7/site-packages/django/contrib/gis/geos/error.py
new file mode 100644
index 0000000..46bdfe6
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/error.py
@@ -0,0 +1,20 @@
+"""
+ This module houses the GEOS exceptions, specifically, GEOSException and
+ GEOSGeometryIndexError.
+"""
+
+class GEOSException(Exception):
+ "The base GEOS exception, indicates a GEOS-related error."
+ pass
+
+class GEOSIndexError(GEOSException, KeyError):
+ """
+ This exception is raised when an invalid index is encountered, and has
+ the 'silent_variable_feature' attribute set to true. This ensures that
+ django's templates proceed to use the next lookup type gracefully when
+ an Exception is raised. Fixes ticket #4740.
+ """
+ # "If, during the method lookup, a method raises an exception, the exception
+ # will be propagated, unless the exception has an attribute
+ # `silent_variable_failure` whose value is True." -- Django template docs.
+ silent_variable_failure = True
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/factory.py b/lib/python2.7/site-packages/django/contrib/gis/geos/factory.py
new file mode 100644
index 0000000..2e5fa4f
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/factory.py
@@ -0,0 +1,35 @@
+from django.contrib.gis import memoryview
+from django.contrib.gis.geos.geometry import GEOSGeometry, wkt_regex, hex_regex
+
+from django.utils import six
+
+
+def fromfile(file_h):
+ """
+ Given a string file name, returns a GEOSGeometry. The file may contain WKB,
+ WKT, or HEX.
+ """
+ # If given a file name, get a real handle.
+ if isinstance(file_h, six.string_types):
+ with open(file_h, 'rb') as file_h:
+ buf = file_h.read()
+ else:
+ buf = file_h.read()
+
+ # If we get WKB need to wrap in memoryview(), so run through regexes.
+ if isinstance(buf, bytes):
+ try:
+ decoded = buf.decode()
+ if wkt_regex.match(decoded) or hex_regex.match(decoded):
+ return GEOSGeometry(decoded)
+ except UnicodeDecodeError:
+ pass
+ else:
+ return GEOSGeometry(buf)
+
+ return GEOSGeometry(memoryview(buf))
+
+
+def fromstr(string, **kwargs):
+ "Given a string value, returns a GEOSGeometry object."
+ return GEOSGeometry(string, **kwargs)
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/geometry.py b/lib/python2.7/site-packages/django/contrib/gis/geos/geometry.py
new file mode 100644
index 0000000..b088ec2
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/geometry.py
@@ -0,0 +1,715 @@
+"""
+ This module contains the 'base' GEOSGeometry object -- all GEOS Geometries
+ inherit from this object.
+"""
+from __future__ import unicode_literals
+
+# Python, ctypes and types dependencies.
+from ctypes import addressof, byref, c_double
+
+from django.contrib.gis import memoryview
+# super-class for mutable list behavior
+from django.contrib.gis.geos.mutable_list import ListMixin
+
+from django.contrib.gis.gdal.error import SRSException
+
+# GEOS-related dependencies.
+from django.contrib.gis.geos.base import GEOSBase, gdal
+from django.contrib.gis.geos.coordseq import GEOSCoordSeq
+from django.contrib.gis.geos.error import GEOSException, GEOSIndexError
+from django.contrib.gis.geos.libgeos import GEOM_PTR, GEOS_PREPARE
+from django.contrib.gis.geos.mutable_list import ListMixin
+
+# All other functions in this module come from the ctypes
+# prototypes module -- which handles all interaction with
+# the underlying GEOS library.
+from django.contrib.gis.geos import prototypes as capi
+
+# These functions provide access to a thread-local instance
+# of their corresponding GEOS I/O class.
+from django.contrib.gis.geos.prototypes.io import wkt_r, wkt_w, wkb_r, wkb_w, ewkb_w
+
+# For recognizing geometry input.
+from django.contrib.gis.geometry.regex import hex_regex, wkt_regex, json_regex
+
+from django.utils import six
+from django.utils.encoding import force_bytes, force_text
+
+
+class GEOSGeometry(GEOSBase, ListMixin):
+ "A class that, generally, encapsulates a GEOS geometry."
+
+ # Raise GEOSIndexError instead of plain IndexError
+ # (see ticket #4740 and GEOSIndexError docstring)
+ _IndexError = GEOSIndexError
+
+ ptr_type = GEOM_PTR
+
+ #### Python 'magic' routines ####
+ def __init__(self, geo_input, srid=None):
+ """
+ The base constructor for GEOS geometry objects, and may take the
+ following inputs:
+
+ * strings:
+ - WKT
+ - HEXEWKB (a PostGIS-specific canonical form)
+ - GeoJSON (requires GDAL)
+ * buffer:
+ - WKB
+
+ The `srid` keyword is used to specify the Source Reference Identifier
+ (SRID) number for this Geometry. If not set, the SRID will be None.
+ """
+ if isinstance(geo_input, bytes):
+ geo_input = force_text(geo_input)
+ if isinstance(geo_input, six.string_types):
+ wkt_m = wkt_regex.match(geo_input)
+ if wkt_m:
+ # Handling WKT input.
+ if wkt_m.group('srid'): srid = int(wkt_m.group('srid'))
+ g = wkt_r().read(force_bytes(wkt_m.group('wkt')))
+ elif hex_regex.match(geo_input):
+ # Handling HEXEWKB input.
+ g = wkb_r().read(force_bytes(geo_input))
+ elif gdal.HAS_GDAL and json_regex.match(geo_input):
+ # Handling GeoJSON input.
+ g = wkb_r().read(gdal.OGRGeometry(geo_input).wkb)
+ else:
+ raise ValueError('String or unicode input unrecognized as WKT EWKT, and HEXEWKB.')
+ elif isinstance(geo_input, GEOM_PTR):
+ # When the input is a pointer to a geomtry (GEOM_PTR).
+ g = geo_input
+ elif isinstance(geo_input, memoryview):
+ # When the input is a buffer (WKB).
+ g = wkb_r().read(geo_input)
+ elif isinstance(geo_input, GEOSGeometry):
+ g = capi.geom_clone(geo_input.ptr)
+ else:
+ # Invalid geometry type.
+ raise TypeError('Improper geometry input type: %s' % str(type(geo_input)))
+
+ if bool(g):
+ # Setting the pointer object with a valid pointer.
+ self.ptr = g
+ else:
+ raise GEOSException('Could not initialize GEOS Geometry with given input.')
+
+ # Post-initialization setup.
+ self._post_init(srid)
+
+ def _post_init(self, srid):
+ "Helper routine for performing post-initialization setup."
+ # Setting the SRID, if given.
+ if srid and isinstance(srid, int): self.srid = srid
+
+ # Setting the class type (e.g., Point, Polygon, etc.)
+ self.__class__ = GEOS_CLASSES[self.geom_typeid]
+
+ # Setting the coordinate sequence for the geometry (will be None on
+ # geometries that do not have coordinate sequences)
+ self._set_cs()
+
+ def __del__(self):
+ """
+ Destroys this Geometry; in other words, frees the memory used by the
+ GEOS C++ object.
+ """
+ if self._ptr: capi.destroy_geom(self._ptr)
+
+ def __copy__(self):
+ """
+ Returns a clone because the copy of a GEOSGeometry may contain an
+ invalid pointer location if the original is garbage collected.
+ """
+ return self.clone()
+
+ def __deepcopy__(self, memodict):
+ """
+ The `deepcopy` routine is used by the `Node` class of django.utils.tree;
+ thus, the protocol routine needs to be implemented to return correct
+ copies (clones) of these GEOS objects, which use C pointers.
+ """
+ return self.clone()
+
+ def __str__(self):
+ "WKT is used for the string representation."
+ return self.wkt
+
+ def __repr__(self):
+ "Short-hand representation because WKT may be very large."
+ return '<%s object at %s>' % (self.geom_type, hex(addressof(self.ptr)))
+
+ # Pickling support
+ def __getstate__(self):
+ # The pickled state is simply a tuple of the WKB (in string form)
+ # and the SRID.
+ return bytes(self.wkb), self.srid
+
+ def __setstate__(self, state):
+ # Instantiating from the tuple state that was pickled.
+ wkb, srid = state
+ ptr = wkb_r().read(memoryview(wkb))
+ if not ptr: raise GEOSException('Invalid Geometry loaded from pickled state.')
+ self.ptr = ptr
+ self._post_init(srid)
+
+ # Comparison operators
+ def __eq__(self, other):
+ """
+ Equivalence testing, a Geometry may be compared with another Geometry
+ or a WKT representation.
+ """
+ if isinstance(other, six.string_types):
+ return self.wkt == other
+ elif isinstance(other, GEOSGeometry):
+ return self.equals_exact(other)
+ else:
+ return False
+
+ def __ne__(self, other):
+ "The not equals operator."
+ return not (self == other)
+
+ ### Geometry set-like operations ###
+ # Thanks to Sean Gillies for inspiration:
+ # http://lists.gispython.org/pipermail/community/2007-July/001034.html
+ # g = g1 | g2
+ def __or__(self, other):
+ "Returns the union of this Geometry and the other."
+ return self.union(other)
+
+ # g = g1 & g2
+ def __and__(self, other):
+ "Returns the intersection of this Geometry and the other."
+ return self.intersection(other)
+
+ # g = g1 - g2
+ def __sub__(self, other):
+ "Return the difference this Geometry and the other."
+ return self.difference(other)
+
+ # g = g1 ^ g2
+ def __xor__(self, other):
+ "Return the symmetric difference of this Geometry and the other."
+ return self.sym_difference(other)
+
+ #### Coordinate Sequence Routines ####
+ @property
+ def has_cs(self):
+ "Returns True if this Geometry has a coordinate sequence, False if not."
+ # Only these geometries are allowed to have coordinate sequences.
+ if isinstance(self, (Point, LineString, LinearRing)):
+ return True
+ else:
+ return False
+
+ def _set_cs(self):
+ "Sets the coordinate sequence for this Geometry."
+ if self.has_cs:
+ self._cs = GEOSCoordSeq(capi.get_cs(self.ptr), self.hasz)
+ else:
+ self._cs = None
+
+ @property
+ def coord_seq(self):
+ "Returns a clone of the coordinate sequence for this Geometry."
+ if self.has_cs:
+ return self._cs.clone()
+
+ #### Geometry Info ####
+ @property
+ def geom_type(self):
+ "Returns a string representing the Geometry type, e.g. 'Polygon'"
+ return capi.geos_type(self.ptr).decode()
+
+ @property
+ def geom_typeid(self):
+ "Returns an integer representing the Geometry type."
+ return capi.geos_typeid(self.ptr)
+
+ @property
+ def num_geom(self):
+ "Returns the number of geometries in the Geometry."
+ return capi.get_num_geoms(self.ptr)
+
+ @property
+ def num_coords(self):
+ "Returns the number of coordinates in the Geometry."
+ return capi.get_num_coords(self.ptr)
+
+ @property
+ def num_points(self):
+ "Returns the number points, or coordinates, in the Geometry."
+ return self.num_coords
+
+ @property
+ def dims(self):
+ "Returns the dimension of this Geometry (0=point, 1=line, 2=surface)."
+ return capi.get_dims(self.ptr)
+
+ def normalize(self):
+ "Converts this Geometry to normal form (or canonical form)."
+ return capi.geos_normalize(self.ptr)
+
+ #### Unary predicates ####
+ @property
+ def empty(self):
+ """
+ Returns a boolean indicating whether the set of points in this Geometry
+ are empty.
+ """
+ return capi.geos_isempty(self.ptr)
+
+ @property
+ def hasz(self):
+ "Returns whether the geometry has a 3D dimension."
+ return capi.geos_hasz(self.ptr)
+
+ @property
+ def ring(self):
+ "Returns whether or not the geometry is a ring."
+ return capi.geos_isring(self.ptr)
+
+ @property
+ def simple(self):
+ "Returns false if the Geometry not simple."
+ return capi.geos_issimple(self.ptr)
+
+ @property
+ def valid(self):
+ "This property tests the validity of this Geometry."
+ return capi.geos_isvalid(self.ptr)
+
+ @property
+ def valid_reason(self):
+ """
+ Returns a string containing the reason for any invalidity.
+ """
+ if not GEOS_PREPARE:
+ raise GEOSException('Upgrade GEOS to 3.1 to get validity reason.')
+ return capi.geos_isvalidreason(self.ptr).decode()
+
+ #### Binary predicates. ####
+ def contains(self, other):
+ "Returns true if other.within(this) returns true."
+ return capi.geos_contains(self.ptr, other.ptr)
+
+ def crosses(self, other):
+ """
+ Returns true if the DE-9IM intersection matrix for the two Geometries
+ is T*T****** (for a point and a curve,a point and an area or a line and
+ an area) 0******** (for two curves).
+ """
+ return capi.geos_crosses(self.ptr, other.ptr)
+
+ def disjoint(self, other):
+ """
+ Returns true if the DE-9IM intersection matrix for the two Geometries
+ is FF*FF****.
+ """
+ return capi.geos_disjoint(self.ptr, other.ptr)
+
+ def equals(self, other):
+ """
+ Returns true if the DE-9IM intersection matrix for the two Geometries
+ is T*F**FFF*.
+ """
+ return capi.geos_equals(self.ptr, other.ptr)
+
+ def equals_exact(self, other, tolerance=0):
+ """
+ Returns true if the two Geometries are exactly equal, up to a
+ specified tolerance.
+ """
+ return capi.geos_equalsexact(self.ptr, other.ptr, float(tolerance))
+
+ def intersects(self, other):
+ "Returns true if disjoint returns false."
+ return capi.geos_intersects(self.ptr, other.ptr)
+
+ def overlaps(self, other):
+ """
+ Returns true if the DE-9IM intersection matrix for the two Geometries
+ is T*T***T** (for two points or two surfaces) 1*T***T** (for two curves).
+ """
+ return capi.geos_overlaps(self.ptr, other.ptr)
+
+ def relate_pattern(self, other, pattern):
+ """
+ Returns true if the elements in the DE-9IM intersection matrix for the
+ two Geometries match the elements in pattern.
+ """
+ if not isinstance(pattern, six.string_types) or len(pattern) > 9:
+ raise GEOSException('invalid intersection matrix pattern')
+ return capi.geos_relatepattern(self.ptr, other.ptr, force_bytes(pattern))
+
+ def touches(self, other):
+ """
+ Returns true if the DE-9IM intersection matrix for the two Geometries
+ is FT*******, F**T***** or F***T****.
+ """
+ return capi.geos_touches(self.ptr, other.ptr)
+
+ def within(self, other):
+ """
+ Returns true if the DE-9IM intersection matrix for the two Geometries
+ is T*F**F***.
+ """
+ return capi.geos_within(self.ptr, other.ptr)
+
+ #### SRID Routines ####
+ def get_srid(self):
+ "Gets the SRID for the geometry, returns None if no SRID is set."
+ s = capi.geos_get_srid(self.ptr)
+ if s == 0: return None
+ else: return s
+
+ def set_srid(self, srid):
+ "Sets the SRID for the geometry."
+ capi.geos_set_srid(self.ptr, srid)
+ srid = property(get_srid, set_srid)
+
+ #### Output Routines ####
+ @property
+ def ewkt(self):
+ """
+ Returns the EWKT (WKT + SRID) of the Geometry. Note that Z values
+ are *not* included in this representation because GEOS does not yet
+ support serializing them.
+ """
+ if self.get_srid(): return 'SRID=%s;%s' % (self.srid, self.wkt)
+ else: return self.wkt
+
+ @property
+ def wkt(self):
+ "Returns the WKT (Well-Known Text) representation of this Geometry."
+ return wkt_w(3 if self.hasz else 2).write(self).decode()
+
+ @property
+ def hex(self):
+ """
+ Returns the WKB of this Geometry in hexadecimal form. Please note
+ that the SRID is not included in this representation because it is not
+ a part of the OGC specification (use the `hexewkb` property instead).
+ """
+ # A possible faster, all-python, implementation:
+ # str(self.wkb).encode('hex')
+ return wkb_w(3 if self.hasz else 2).write_hex(self)
+
+ @property
+ def hexewkb(self):
+ """
+ Returns the EWKB of this Geometry in hexadecimal form. This is an
+ extension of the WKB specification that includes SRID value that are
+ a part of this geometry.
+ """
+ if self.hasz and not GEOS_PREPARE:
+ # See: http://trac.osgeo.org/geos/ticket/216
+ raise GEOSException('Upgrade GEOS to 3.1 to get valid 3D HEXEWKB.')
+ return ewkb_w(3 if self.hasz else 2).write_hex(self)
+
+ @property
+ def json(self):
+ """
+ Returns GeoJSON representation of this Geometry if GDAL is installed.
+ """
+ if gdal.HAS_GDAL:
+ return self.ogr.json
+ else:
+ raise GEOSException('GeoJSON output only supported when GDAL is installed.')
+ geojson = json
+
+ @property
+ def wkb(self):
+ """
+ Returns the WKB (Well-Known Binary) representation of this Geometry
+ as a Python buffer. SRID and Z values are not included, use the
+ `ewkb` property instead.
+ """
+ return wkb_w(3 if self.hasz else 2).write(self)
+
+ @property
+ def ewkb(self):
+ """
+ Return the EWKB representation of this Geometry as a Python buffer.
+ This is an extension of the WKB specification that includes any SRID
+ value that are a part of this geometry.
+ """
+ if self.hasz and not GEOS_PREPARE:
+ # See: http://trac.osgeo.org/geos/ticket/216
+ raise GEOSException('Upgrade GEOS to 3.1 to get valid 3D EWKB.')
+ return ewkb_w(3 if self.hasz else 2).write(self)
+
+ @property
+ def kml(self):
+ "Returns the KML representation of this Geometry."
+ gtype = self.geom_type
+ return '<%s>%s</%s>' % (gtype, self.coord_seq.kml, gtype)
+
+ @property
+ def prepared(self):
+ """
+ Returns a PreparedGeometry corresponding to this geometry -- it is
+ optimized for the contains, intersects, and covers operations.
+ """
+ if GEOS_PREPARE:
+ return PreparedGeometry(self)
+ else:
+ raise GEOSException('GEOS 3.1+ required for prepared geometry support.')
+
+ #### GDAL-specific output routines ####
+ @property
+ def ogr(self):
+ "Returns the OGR Geometry for this Geometry."
+ if not gdal.HAS_GDAL:
+ raise GEOSException('GDAL required to convert to an OGRGeometry.')
+ if self.srid:
+ try:
+ return gdal.OGRGeometry(self.wkb, self.srid)
+ except SRSException:
+ pass
+ return gdal.OGRGeometry(self.wkb)
+
+ @property
+ def srs(self):
+ "Returns the OSR SpatialReference for SRID of this Geometry."
+ if not gdal.HAS_GDAL:
+ raise GEOSException('GDAL required to return a SpatialReference object.')
+ if self.srid:
+ try:
+ return gdal.SpatialReference(self.srid)
+ except SRSException:
+ pass
+ return None
+
+ @property
+ def crs(self):
+ "Alias for `srs` property."
+ return self.srs
+
+ def transform(self, ct, clone=False):
+ """
+ Requires GDAL. Transforms the geometry according to the given
+ transformation object, which may be an integer SRID, and WKT or
+ PROJ.4 string. By default, the geometry is transformed in-place and
+ nothing is returned. However if the `clone` keyword is set, then this
+ geometry will not be modified and a transformed clone will be returned
+ instead.
+ """
+ srid = self.srid
+
+ if ct == srid:
+ # short-circuit where source & dest SRIDs match
+ if clone:
+ return self.clone()
+ else:
+ return
+
+ if (srid is None) or (srid < 0):
+ raise GEOSException("Calling transform() with no SRID set is not supported")
+
+ if not gdal.HAS_GDAL:
+ raise GEOSException("GDAL library is not available to transform() geometry.")
+
+ # Creating an OGR Geometry, which is then transformed.
+ g = self.ogr
+ g.transform(ct)
+ # Getting a new GEOS pointer
+ ptr = wkb_r().read(g.wkb)
+ if clone:
+ # User wants a cloned transformed geometry returned.
+ return GEOSGeometry(ptr, srid=g.srid)
+ if ptr:
+ # Reassigning pointer, and performing post-initialization setup
+ # again due to the reassignment.
+ capi.destroy_geom(self.ptr)
+ self.ptr = ptr
+ self._post_init(g.srid)
+ else:
+ raise GEOSException('Transformed WKB was invalid.')
+
+ #### Topology Routines ####
+ def _topology(self, gptr):
+ "Helper routine to return Geometry from the given pointer."
+ return GEOSGeometry(gptr, srid=self.srid)
+
+ @property
+ def boundary(self):
+ "Returns the boundary as a newly allocated Geometry object."
+ return self._topology(capi.geos_boundary(self.ptr))
+
+ def buffer(self, width, quadsegs=8):
+ """
+ Returns a geometry that represents all points whose distance from this
+ Geometry is less than or equal to distance. Calculations are in the
+ Spatial Reference System of this Geometry. The optional third parameter sets
+ the number of segment used to approximate a quarter circle (defaults to 8).
+ (Text from PostGIS documentation at ch. 6.1.3)
+ """
+ return self._topology(capi.geos_buffer(self.ptr, width, quadsegs))
+
+ @property
+ def centroid(self):
+ """
+ The centroid is equal to the centroid of the set of component Geometries
+ of highest dimension (since the lower-dimension geometries contribute zero
+ "weight" to the centroid).
+ """
+ return self._topology(capi.geos_centroid(self.ptr))
+
+ @property
+ def convex_hull(self):
+ """
+ Returns the smallest convex Polygon that contains all the points
+ in the Geometry.
+ """
+ return self._topology(capi.geos_convexhull(self.ptr))
+
+ def difference(self, other):
+ """
+ Returns a Geometry representing the points making up this Geometry
+ that do not make up other.
+ """
+ return self._topology(capi.geos_difference(self.ptr, other.ptr))
+
+ @property
+ def envelope(self):
+ "Return the envelope for this geometry (a polygon)."
+ return self._topology(capi.geos_envelope(self.ptr))
+
+ def interpolate(self, distance):
+ if not isinstance(self, (LineString, MultiLineString)):
+ raise TypeError('interpolate only works on LineString and MultiLineString geometries')
+ if not hasattr(capi, 'geos_interpolate'):
+ raise NotImplementedError('interpolate requires GEOS 3.2+')
+ return self._topology(capi.geos_interpolate(self.ptr, distance))
+
+ def interpolate_normalized(self, distance):
+ if not isinstance(self, (LineString, MultiLineString)):
+ raise TypeError('interpolate only works on LineString and MultiLineString geometries')
+ if not hasattr(capi, 'geos_interpolate_normalized'):
+ raise NotImplementedError('interpolate_normalized requires GEOS 3.2+')
+ return self._topology(capi.geos_interpolate_normalized(self.ptr, distance))
+
+ def intersection(self, other):
+ "Returns a Geometry representing the points shared by this Geometry and other."
+ return self._topology(capi.geos_intersection(self.ptr, other.ptr))
+
+ @property
+ def point_on_surface(self):
+ "Computes an interior point of this Geometry."
+ return self._topology(capi.geos_pointonsurface(self.ptr))
+
+ def project(self, point):
+ if not isinstance(point, Point):
+ raise TypeError('locate_point argument must be a Point')
+ if not isinstance(self, (LineString, MultiLineString)):
+ raise TypeError('locate_point only works on LineString and MultiLineString geometries')
+ if not hasattr(capi, 'geos_project'):
+ raise NotImplementedError('geos_project requires GEOS 3.2+')
+ return capi.geos_project(self.ptr, point.ptr)
+
+ def project_normalized(self, point):
+ if not isinstance(point, Point):
+ raise TypeError('locate_point argument must be a Point')
+ if not isinstance(self, (LineString, MultiLineString)):
+ raise TypeError('locate_point only works on LineString and MultiLineString geometries')
+ if not hasattr(capi, 'geos_project_normalized'):
+ raise NotImplementedError('project_normalized requires GEOS 3.2+')
+ return capi.geos_project_normalized(self.ptr, point.ptr)
+
+ def relate(self, other):
+ "Returns the DE-9IM intersection matrix for this Geometry and the other."
+ return capi.geos_relate(self.ptr, other.ptr).decode()
+
+ def simplify(self, tolerance=0.0, preserve_topology=False):
+ """
+ Returns the Geometry, simplified using the Douglas-Peucker algorithm
+ to the specified tolerance (higher tolerance => less points). If no
+ tolerance provided, defaults to 0.
+
+ By default, this function does not preserve topology - e.g. polygons can
+ be split, collapse to lines or disappear holes can be created or
+ disappear, and lines can cross. By specifying preserve_topology=True,
+ the result will have the same dimension and number of components as the
+ input. This is significantly slower.
+ """
+ if preserve_topology:
+ return self._topology(capi.geos_preservesimplify(self.ptr, tolerance))
+ else:
+ return self._topology(capi.geos_simplify(self.ptr, tolerance))
+
+ def sym_difference(self, other):
+ """
+ Returns a set combining the points in this Geometry not in other,
+ and the points in other not in this Geometry.
+ """
+ return self._topology(capi.geos_symdifference(self.ptr, other.ptr))
+
+ def union(self, other):
+ "Returns a Geometry representing all the points in this Geometry and other."
+ return self._topology(capi.geos_union(self.ptr, other.ptr))
+
+ #### Other Routines ####
+ @property
+ def area(self):
+ "Returns the area of the Geometry."
+ return capi.geos_area(self.ptr, byref(c_double()))
+
+ def distance(self, other):
+ """
+ Returns the distance between the closest points on this Geometry
+ and the other. Units will be in those of the coordinate system of
+ the Geometry.
+ """
+ if not isinstance(other, GEOSGeometry):
+ raise TypeError('distance() works only on other GEOS Geometries.')
+ return capi.geos_distance(self.ptr, other.ptr, byref(c_double()))
+
+ @property
+ def extent(self):
+ """
+ Returns the extent of this geometry as a 4-tuple, consisting of
+ (xmin, ymin, xmax, ymax).
+ """
+ env = self.envelope
+ if isinstance(env, Point):
+ xmin, ymin = env.tuple
+ xmax, ymax = xmin, ymin
+ else:
+ xmin, ymin = env[0][0]
+ xmax, ymax = env[0][2]
+ return (xmin, ymin, xmax, ymax)
+
+ @property
+ def length(self):
+ """
+ Returns the length of this Geometry (e.g., 0 for point, or the
+ circumfrence of a Polygon).
+ """
+ return capi.geos_length(self.ptr, byref(c_double()))
+
+ def clone(self):
+ "Clones this Geometry."
+ return GEOSGeometry(capi.geom_clone(self.ptr), srid=self.srid)
+
+# Class mapping dictionary. Has to be at the end to avoid import
+# conflicts with GEOSGeometry.
+from django.contrib.gis.geos.linestring import LineString, LinearRing
+from django.contrib.gis.geos.point import Point
+from django.contrib.gis.geos.polygon import Polygon
+from django.contrib.gis.geos.collections import GeometryCollection, MultiPoint, MultiLineString, MultiPolygon
+GEOS_CLASSES = {0 : Point,
+ 1 : LineString,
+ 2 : LinearRing,
+ 3 : Polygon,
+ 4 : MultiPoint,
+ 5 : MultiLineString,
+ 6 : MultiPolygon,
+ 7 : GeometryCollection,
+ }
+
+# If supported, import the PreparedGeometry class.
+if GEOS_PREPARE:
+ from django.contrib.gis.geos.prepared import PreparedGeometry
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/io.py b/lib/python2.7/site-packages/django/contrib/gis/geos/io.py
new file mode 100644
index 0000000..54ba6b4
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/io.py
@@ -0,0 +1,20 @@
+"""
+Module that holds classes for performing I/O operations on GEOS geometry
+objects. Specifically, this has Python implementations of WKB/WKT
+reader and writer classes.
+"""
+from django.contrib.gis.geos.geometry import GEOSGeometry
+from django.contrib.gis.geos.prototypes.io import _WKTReader, _WKBReader, WKBWriter, WKTWriter
+
+# Public classes for (WKB|WKT)Reader, which return GEOSGeometry
+class WKBReader(_WKBReader):
+ def read(self, wkb):
+ "Returns a GEOSGeometry for the given WKB buffer."
+ return GEOSGeometry(super(WKBReader, self).read(wkb))
+
+class WKTReader(_WKTReader):
+ def read(self, wkt):
+ "Returns a GEOSGeometry for the given WKT string."
+ return GEOSGeometry(super(WKTReader, self).read(wkt))
+
+
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/libgeos.py b/lib/python2.7/site-packages/django/contrib/gis/geos/libgeos.py
new file mode 100644
index 0000000..6963b78
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/libgeos.py
@@ -0,0 +1,155 @@
+"""
+ This module houses the ctypes initialization procedures, as well
+ as the notice and error handler function callbacks (get called
+ when an error occurs in GEOS).
+
+ This module also houses GEOS Pointer utilities, including
+ get_pointer_arr(), and GEOM_PTR.
+"""
+import logging
+import os
+import re
+from ctypes import c_char_p, Structure, CDLL, CFUNCTYPE, POINTER
+from ctypes.util import find_library
+
+from django.contrib.gis.geos.error import GEOSException
+from django.core.exceptions import ImproperlyConfigured
+
+logger = logging.getLogger('django.contrib.gis')
+
+# Custom library path set?
+try:
+ from django.conf import settings
+ lib_path = settings.GEOS_LIBRARY_PATH
+except (AttributeError, EnvironmentError,
+ ImportError, ImproperlyConfigured):
+ lib_path = None
+
+# Setting the appropriate names for the GEOS-C library.
+if lib_path:
+ lib_names = None
+elif os.name == 'nt':
+ # Windows NT libraries
+ lib_names = ['geos_c', 'libgeos_c-1']
+elif os.name == 'posix':
+ # *NIX libraries
+ lib_names = ['geos_c', 'GEOS']
+else:
+ raise ImportError('Unsupported OS "%s"' % os.name)
+
+# Using the ctypes `find_library` utility to find the path to the GEOS
+# shared library. This is better than manually specifiying each library name
+# and extension (e.g., libgeos_c.[so|so.1|dylib].).
+if lib_names:
+ for lib_name in lib_names:
+ lib_path = find_library(lib_name)
+ if not lib_path is None: break
+
+# No GEOS library could be found.
+if lib_path is None:
+ raise ImportError('Could not find the GEOS library (tried "%s"). '
+ 'Try setting GEOS_LIBRARY_PATH in your settings.' %
+ '", "'.join(lib_names))
+
+# Getting the GEOS C library. The C interface (CDLL) is used for
+# both *NIX and Windows.
+# See the GEOS C API source code for more details on the library function calls:
+# http://geos.refractions.net/ro/doxygen_docs/html/geos__c_8h-source.html
+lgeos = CDLL(lib_path)
+
+# The notice and error handler C function callback definitions.
+# Supposed to mimic the GEOS message handler (C below):
+# typedef void (*GEOSMessageHandler)(const char *fmt, ...);
+NOTICEFUNC = CFUNCTYPE(None, c_char_p, c_char_p)
+def notice_h(fmt, lst):
+ fmt, lst = fmt.decode(), lst.decode()
+ try:
+ warn_msg = fmt % lst
+ except:
+ warn_msg = fmt
+ logger.warning('GEOS_NOTICE: %s\n' % warn_msg)
+notice_h = NOTICEFUNC(notice_h)
+
+ERRORFUNC = CFUNCTYPE(None, c_char_p, c_char_p)
+def error_h(fmt, lst):
+ fmt, lst = fmt.decode(), lst.decode()
+ try:
+ err_msg = fmt % lst
+ except:
+ err_msg = fmt
+ logger.error('GEOS_ERROR: %s\n' % err_msg)
+error_h = ERRORFUNC(error_h)
+
+#### GEOS Geometry C data structures, and utility functions. ####
+
+# Opaque GEOS geometry structures, used for GEOM_PTR and CS_PTR
+class GEOSGeom_t(Structure): pass
+class GEOSPrepGeom_t(Structure): pass
+class GEOSCoordSeq_t(Structure): pass
+class GEOSContextHandle_t(Structure): pass
+
+# Pointers to opaque GEOS geometry structures.
+GEOM_PTR = POINTER(GEOSGeom_t)
+PREPGEOM_PTR = POINTER(GEOSPrepGeom_t)
+CS_PTR = POINTER(GEOSCoordSeq_t)
+CONTEXT_PTR = POINTER(GEOSContextHandle_t)
+
+# Used specifically by the GEOSGeom_createPolygon and GEOSGeom_createCollection
+# GEOS routines
+def get_pointer_arr(n):
+ "Gets a ctypes pointer array (of length `n`) for GEOSGeom_t opaque pointer."
+ GeomArr = GEOM_PTR * n
+ return GeomArr()
+
+# Returns the string version of the GEOS library. Have to set the restype
+# explicitly to c_char_p to ensure compatibility accross 32 and 64-bit platforms.
+geos_version = lgeos.GEOSversion
+geos_version.argtypes = None
+geos_version.restype = c_char_p
+
+# Regular expression should be able to parse version strings such as
+# '3.0.0rc4-CAPI-1.3.3', '3.0.0-CAPI-1.4.1', '3.4.0dev-CAPI-1.8.0' or '3.4.0dev-CAPI-1.8.0 r0'
+version_regex = re.compile(
+ r'^(?P<version>(?P<major>\d+)\.(?P<minor>\d+)\.(?P<subminor>\d+))'
+ r'((rc(?P<release_candidate>\d+))|dev)?-CAPI-(?P<capi_version>\d+\.\d+\.\d+)( r\d+)?$'
+)
+def geos_version_info():
+ """
+ Returns a dictionary containing the various version metadata parsed from
+ the GEOS version string, including the version number, whether the version
+ is a release candidate (and what number release candidate), and the C API
+ version.
+ """
+ ver = geos_version().decode()
+ m = version_regex.match(ver)
+ if not m:
+ raise GEOSException('Could not parse version info string "%s"' % ver)
+ return dict((key, m.group(key)) for key in (
+ 'version', 'release_candidate', 'capi_version', 'major', 'minor', 'subminor'))
+
+# Version numbers and whether or not prepared geometry support is available.
+_verinfo = geos_version_info()
+GEOS_MAJOR_VERSION = int(_verinfo['major'])
+GEOS_MINOR_VERSION = int(_verinfo['minor'])
+GEOS_SUBMINOR_VERSION = int(_verinfo['subminor'])
+del _verinfo
+GEOS_VERSION = (GEOS_MAJOR_VERSION, GEOS_MINOR_VERSION, GEOS_SUBMINOR_VERSION)
+GEOS_PREPARE = GEOS_VERSION >= (3, 1, 0)
+
+if GEOS_PREPARE:
+ # Here we set up the prototypes for the initGEOS_r and finishGEOS_r
+ # routines. These functions aren't actually called until they are
+ # attached to a GEOS context handle -- this actually occurs in
+ # geos/prototypes/threadsafe.py.
+ lgeos.initGEOS_r.restype = CONTEXT_PTR
+ lgeos.finishGEOS_r.argtypes = [CONTEXT_PTR]
+else:
+ # When thread-safety isn't available, the initGEOS routine must be called
+ # first. This function takes the notice and error functions, defined
+ # as Python callbacks above, as parameters. Here is the C code that is
+ # wrapped:
+ # extern void GEOS_DLL initGEOS(GEOSMessageHandler notice_function, GEOSMessageHandler error_function);
+ lgeos.initGEOS(notice_h, error_h)
+ # Calling finishGEOS() upon exit of the interpreter.
+ import atexit
+ atexit.register(lgeos.finishGEOS)
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/linestring.py b/lib/python2.7/site-packages/django/contrib/gis/geos/linestring.py
new file mode 100644
index 0000000..4784ea7
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/linestring.py
@@ -0,0 +1,153 @@
+from django.contrib.gis.geos.base import numpy
+from django.contrib.gis.geos.coordseq import GEOSCoordSeq
+from django.contrib.gis.geos.error import GEOSException
+from django.contrib.gis.geos.geometry import GEOSGeometry
+from django.contrib.gis.geos.point import Point
+from django.contrib.gis.geos import prototypes as capi
+from django.utils.six.moves import xrange
+
+class LineString(GEOSGeometry):
+ _init_func = capi.create_linestring
+ _minlength = 2
+
+ #### Python 'magic' routines ####
+ def __init__(self, *args, **kwargs):
+ """
+ Initializes on the given sequence -- may take lists, tuples, NumPy arrays
+ of X,Y pairs, or Point objects. If Point objects are used, ownership is
+ _not_ transferred to the LineString object.
+
+ Examples:
+ ls = LineString((1, 1), (2, 2))
+ ls = LineString([(1, 1), (2, 2)])
+ ls = LineString(array([(1, 1), (2, 2)]))
+ ls = LineString(Point(1, 1), Point(2, 2))
+ """
+ # If only one argument provided, set the coords array appropriately
+ if len(args) == 1: coords = args[0]
+ else: coords = args
+
+ if isinstance(coords, (tuple, list)):
+ # Getting the number of coords and the number of dimensions -- which
+ # must stay the same, e.g., no LineString((1, 2), (1, 2, 3)).
+ ncoords = len(coords)
+ if coords: ndim = len(coords[0])
+ else: raise TypeError('Cannot initialize on empty sequence.')
+ self._checkdim(ndim)
+ # Incrementing through each of the coordinates and verifying
+ for i in xrange(1, ncoords):
+ if not isinstance(coords[i], (tuple, list, Point)):
+ raise TypeError('each coordinate should be a sequence (list or tuple)')
+ if len(coords[i]) != ndim: raise TypeError('Dimension mismatch.')
+ numpy_coords = False
+ elif numpy and isinstance(coords, numpy.ndarray):
+ shape = coords.shape # Using numpy's shape.
+ if len(shape) != 2: raise TypeError('Too many dimensions.')
+ self._checkdim(shape[1])
+ ncoords = shape[0]
+ ndim = shape[1]
+ numpy_coords = True
+ else:
+ raise TypeError('Invalid initialization input for LineStrings.')
+
+ # Creating a coordinate sequence object because it is easier to
+ # set the points using GEOSCoordSeq.__setitem__().
+ cs = GEOSCoordSeq(capi.create_cs(ncoords, ndim), z=bool(ndim==3))
+
+ for i in xrange(ncoords):
+ if numpy_coords: cs[i] = coords[i,:]
+ elif isinstance(coords[i], Point): cs[i] = coords[i].tuple
+ else: cs[i] = coords[i]
+
+ # If SRID was passed in with the keyword arguments
+ srid = kwargs.get('srid', None)
+
+ # Calling the base geometry initialization with the returned pointer
+ # from the function.
+ super(LineString, self).__init__(self._init_func(cs.ptr), srid=srid)
+
+ def __iter__(self):
+ "Allows iteration over this LineString."
+ for i in xrange(len(self)):
+ yield self[i]
+
+ def __len__(self):
+ "Returns the number of points in this LineString."
+ return len(self._cs)
+
+ def _get_single_external(self, index):
+ return self._cs[index]
+
+ _get_single_internal = _get_single_external
+
+ def _set_list(self, length, items):
+ ndim = self._cs.dims #
+ hasz = self._cs.hasz # I don't understand why these are different
+
+ # create a new coordinate sequence and populate accordingly
+ cs = GEOSCoordSeq(capi.create_cs(length, ndim), z=hasz)
+ for i, c in enumerate(items):
+ cs[i] = c
+
+ ptr = self._init_func(cs.ptr)
+ if ptr:
+ capi.destroy_geom(self.ptr)
+ self.ptr = ptr
+ self._post_init(self.srid)
+ else:
+ # can this happen?
+ raise GEOSException('Geometry resulting from slice deletion was invalid.')
+
+ def _set_single(self, index, value):
+ self._checkindex(index)
+ self._cs[index] = value
+
+ def _checkdim(self, dim):
+ if dim not in (2, 3): raise TypeError('Dimension mismatch.')
+
+ #### Sequence Properties ####
+ @property
+ def tuple(self):
+ "Returns a tuple version of the geometry from the coordinate sequence."
+ return self._cs.tuple
+ coords = tuple
+
+ def _listarr(self, func):
+ """
+ Internal routine that returns a sequence (list) corresponding with
+ the given function. Will return a numpy array if possible.
+ """
+ lst = [func(i) for i in xrange(len(self))]
+ if numpy: return numpy.array(lst) # ARRRR!
+ else: return lst
+
+ @property
+ def array(self):
+ "Returns a numpy array for the LineString."
+ return self._listarr(self._cs.__getitem__)
+
+ @property
+ def merged(self):
+ "Returns the line merge of this LineString."
+ return self._topology(capi.geos_linemerge(self.ptr))
+
+ @property
+ def x(self):
+ "Returns a list or numpy array of the X variable."
+ return self._listarr(self._cs.getX)
+
+ @property
+ def y(self):
+ "Returns a list or numpy array of the Y variable."
+ return self._listarr(self._cs.getY)
+
+ @property
+ def z(self):
+ "Returns a list or numpy array of the Z variable."
+ if not self.hasz: return None
+ else: return self._listarr(self._cs.getZ)
+
+# LinearRings are LineStrings used within Polygons.
+class LinearRing(LineString):
+ _minLength = 4
+ _init_func = capi.create_linearring
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/mutable_list.py b/lib/python2.7/site-packages/django/contrib/gis/geos/mutable_list.py
new file mode 100644
index 0000000..0418282
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/mutable_list.py
@@ -0,0 +1,328 @@
+# Copyright (c) 2008-2009 Aryeh Leib Taurog, all rights reserved.
+# Released under the New BSD license.
+"""
+This module contains a base type which provides list-style mutations
+without specific data storage methods.
+
+See also http://www.aryehleib.com/MutableLists.html
+
+Author: Aryeh Leib Taurog.
+"""
+from django.utils.functional import total_ordering
+from django.utils import six
+from django.utils.six.moves import xrange
+
+@total_ordering
+class ListMixin(object):
+ """
+ A base class which provides complete list interface.
+ Derived classes must call ListMixin's __init__() function
+ and implement the following:
+
+ function _get_single_external(self, i):
+ Return single item with index i for general use.
+ The index i will always satisfy 0 <= i < len(self).
+
+ function _get_single_internal(self, i):
+ Same as above, but for use within the class [Optional]
+ Note that if _get_single_internal and _get_single_internal return
+ different types of objects, _set_list must distinguish
+ between the two and handle each appropriately.
+
+ function _set_list(self, length, items):
+ Recreate the entire object.
+
+ NOTE: items may be a generator which calls _get_single_internal.
+ Therefore, it is necessary to cache the values in a temporary:
+ temp = list(items)
+ before clobbering the original storage.
+
+ function _set_single(self, i, value):
+ Set the single item at index i to value [Optional]
+ If left undefined, all mutations will result in rebuilding
+ the object using _set_list.
+
+ function __len__(self):
+ Return the length
+
+ int _minlength:
+ The minimum legal length [Optional]
+
+ int _maxlength:
+ The maximum legal length [Optional]
+
+ type or tuple _allowed:
+ A type or tuple of allowed item types [Optional]
+
+ class _IndexError:
+ The type of exception to be raise on invalid index [Optional]
+ """
+
+ _minlength = 0
+ _maxlength = None
+ _IndexError = IndexError
+
+ ### Python initialization and special list interface methods ###
+
+ def __init__(self, *args, **kwargs):
+ if not hasattr(self, '_get_single_internal'):
+ self._get_single_internal = self._get_single_external
+
+ if not hasattr(self, '_set_single'):
+ self._set_single = self._set_single_rebuild
+ self._assign_extended_slice = self._assign_extended_slice_rebuild
+
+ super(ListMixin, self).__init__(*args, **kwargs)
+
+ def __getitem__(self, index):
+ "Get the item(s) at the specified index/slice."
+ if isinstance(index, slice):
+ return [self._get_single_external(i) for i in xrange(*index.indices(len(self)))]
+ else:
+ index = self._checkindex(index)
+ return self._get_single_external(index)
+
+ def __delitem__(self, index):
+ "Delete the item(s) at the specified index/slice."
+ if not isinstance(index, six.integer_types + (slice,)):
+ raise TypeError("%s is not a legal index" % index)
+
+ # calculate new length and dimensions
+ origLen = len(self)
+ if isinstance(index, six.integer_types):
+ index = self._checkindex(index)
+ indexRange = [index]
+ else:
+ indexRange = range(*index.indices(origLen))
+
+ newLen = origLen - len(indexRange)
+ newItems = ( self._get_single_internal(i)
+ for i in xrange(origLen)
+ if i not in indexRange )
+
+ self._rebuild(newLen, newItems)
+
+ def __setitem__(self, index, val):
+ "Set the item(s) at the specified index/slice."
+ if isinstance(index, slice):
+ self._set_slice(index, val)
+ else:
+ index = self._checkindex(index)
+ self._check_allowed((val,))
+ self._set_single(index, val)
+
+ def __iter__(self):
+ "Iterate over the items in the list"
+ for i in xrange(len(self)):
+ yield self[i]
+
+ ### Special methods for arithmetic operations ###
+ def __add__(self, other):
+ 'add another list-like object'
+ return self.__class__(list(self) + list(other))
+
+ def __radd__(self, other):
+ 'add to another list-like object'
+ return other.__class__(list(other) + list(self))
+
+ def __iadd__(self, other):
+ 'add another list-like object to self'
+ self.extend(list(other))
+ return self
+
+ def __mul__(self, n):
+ 'multiply'
+ return self.__class__(list(self) * n)
+
+ def __rmul__(self, n):
+ 'multiply'
+ return self.__class__(list(self) * n)
+
+ def __imul__(self, n):
+ 'multiply'
+ if n <= 0:
+ del self[:]
+ else:
+ cache = list(self)
+ for i in range(n-1):
+ self.extend(cache)
+ return self
+
+ def __eq__(self, other):
+ olen = len(other)
+ for i in range(olen):
+ try:
+ c = self[i] == other[i]
+ except self._IndexError:
+ # self must be shorter
+ return False
+ if not c:
+ return False
+ return len(self) == olen
+
+ def __lt__(self, other):
+ olen = len(other)
+ for i in range(olen):
+ try:
+ c = self[i] < other[i]
+ except self._IndexError:
+ # self must be shorter
+ return True
+ if c:
+ return c
+ elif other[i] < self[i]:
+ return False
+ return len(self) < olen
+
+ ### Public list interface Methods ###
+ ## Non-mutating ##
+ def count(self, val):
+ "Standard list count method"
+ count = 0
+ for i in self:
+ if val == i: count += 1
+ return count
+
+ def index(self, val):
+ "Standard list index method"
+ for i in xrange(0, len(self)):
+ if self[i] == val: return i
+ raise ValueError('%s not found in object' % str(val))
+
+ ## Mutating ##
+ def append(self, val):
+ "Standard list append method"
+ self[len(self):] = [val]
+
+ def extend(self, vals):
+ "Standard list extend method"
+ self[len(self):] = vals
+
+ def insert(self, index, val):
+ "Standard list insert method"
+ if not isinstance(index, six.integer_types):
+ raise TypeError("%s is not a legal index" % index)
+ self[index:index] = [val]
+
+ def pop(self, index=-1):
+ "Standard list pop method"
+ result = self[index]
+ del self[index]
+ return result
+
+ def remove(self, val):
+ "Standard list remove method"
+ del self[self.index(val)]
+
+ def reverse(self):
+ "Standard list reverse method"
+ self[:] = self[-1::-1]
+
+ def sort(self, cmp=None, key=None, reverse=False):
+ "Standard list sort method"
+ if key:
+ temp = [(key(v),v) for v in self]
+ temp.sort(key=lambda x: x[0], reverse=reverse)
+ self[:] = [v[1] for v in temp]
+ else:
+ temp = list(self)
+ if cmp is not None:
+ temp.sort(cmp=cmp, reverse=reverse)
+ else:
+ temp.sort(reverse=reverse)
+ self[:] = temp
+
+ ### Private routines ###
+ def _rebuild(self, newLen, newItems):
+ if newLen < self._minlength:
+ raise ValueError('Must have at least %d items' % self._minlength)
+ if self._maxlength is not None and newLen > self._maxlength:
+ raise ValueError('Cannot have more than %d items' % self._maxlength)
+
+ self._set_list(newLen, newItems)
+
+ def _set_single_rebuild(self, index, value):
+ self._set_slice(slice(index, index + 1, 1), [value])
+
+ def _checkindex(self, index, correct=True):
+ length = len(self)
+ if 0 <= index < length:
+ return index
+ if correct and -length <= index < 0:
+ return index + length
+ raise self._IndexError('invalid index: %s' % str(index))
+
+ def _check_allowed(self, items):
+ if hasattr(self, '_allowed'):
+ if False in [isinstance(val, self._allowed) for val in items]:
+ raise TypeError('Invalid type encountered in the arguments.')
+
+ def _set_slice(self, index, values):
+ "Assign values to a slice of the object"
+ try:
+ iter(values)
+ except TypeError:
+ raise TypeError('can only assign an iterable to a slice')
+
+ self._check_allowed(values)
+
+ origLen = len(self)
+ valueList = list(values)
+ start, stop, step = index.indices(origLen)
+
+ # CAREFUL: index.step and step are not the same!
+ # step will never be None
+ if index.step is None:
+ self._assign_simple_slice(start, stop, valueList)
+ else:
+ self._assign_extended_slice(start, stop, step, valueList)
+
+ def _assign_extended_slice_rebuild(self, start, stop, step, valueList):
+ 'Assign an extended slice by rebuilding entire list'
+ indexList = range(start, stop, step)
+ # extended slice, only allow assigning slice of same size
+ if len(valueList) != len(indexList):
+ raise ValueError('attempt to assign sequence of size %d '
+ 'to extended slice of size %d'
+ % (len(valueList), len(indexList)))
+
+ # we're not changing the length of the sequence
+ newLen = len(self)
+ newVals = dict(zip(indexList, valueList))
+ def newItems():
+ for i in xrange(newLen):
+ if i in newVals:
+ yield newVals[i]
+ else:
+ yield self._get_single_internal(i)
+
+ self._rebuild(newLen, newItems())
+
+ def _assign_extended_slice(self, start, stop, step, valueList):
+ 'Assign an extended slice by re-assigning individual items'
+ indexList = range(start, stop, step)
+ # extended slice, only allow assigning slice of same size
+ if len(valueList) != len(indexList):
+ raise ValueError('attempt to assign sequence of size %d '
+ 'to extended slice of size %d'
+ % (len(valueList), len(indexList)))
+
+ for i, val in zip(indexList, valueList):
+ self._set_single(i, val)
+
+ def _assign_simple_slice(self, start, stop, valueList):
+ 'Assign a simple slice; Can assign slice of any length'
+ origLen = len(self)
+ stop = max(start, stop)
+ newLen = origLen - stop + start + len(valueList)
+ def newItems():
+ for i in xrange(origLen + 1):
+ if i == start:
+ for val in valueList:
+ yield val
+
+ if i < origLen:
+ if i < start or i >= stop:
+ yield self._get_single_internal(i)
+
+ self._rebuild(newLen, newItems())
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/point.py b/lib/python2.7/site-packages/django/contrib/gis/geos/point.py
new file mode 100644
index 0000000..907347d
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/point.py
@@ -0,0 +1,137 @@
+from ctypes import c_uint
+from django.contrib.gis.geos.error import GEOSException
+from django.contrib.gis.geos.geometry import GEOSGeometry
+from django.contrib.gis.geos import prototypes as capi
+from django.utils import six
+from django.utils.six.moves import xrange
+
+class Point(GEOSGeometry):
+ _minlength = 2
+ _maxlength = 3
+
+ def __init__(self, x, y=None, z=None, srid=None):
+ """
+ The Point object may be initialized with either a tuple, or individual
+ parameters.
+
+ For Example:
+ >>> p = Point((5, 23)) # 2D point, passed in as a tuple
+ >>> p = Point(5, 23, 8) # 3D point, passed in with individual parameters
+ """
+ if isinstance(x, (tuple, list)):
+ # Here a tuple or list was passed in under the `x` parameter.
+ ndim = len(x)
+ coords = x
+ elif isinstance(x, six.integer_types + (float,)) and isinstance(y, six.integer_types + (float,)):
+ # Here X, Y, and (optionally) Z were passed in individually, as parameters.
+ if isinstance(z, six.integer_types + (float,)):
+ ndim = 3
+ coords = [x, y, z]
+ else:
+ ndim = 2
+ coords = [x, y]
+ else:
+ raise TypeError('Invalid parameters given for Point initialization.')
+
+ point = self._create_point(ndim, coords)
+
+ # Initializing using the address returned from the GEOS
+ # createPoint factory.
+ super(Point, self).__init__(point, srid=srid)
+
+ def _create_point(self, ndim, coords):
+ """
+ Create a coordinate sequence, set X, Y, [Z], and create point
+ """
+ if ndim < 2 or ndim > 3:
+ raise TypeError('Invalid point dimension: %s' % str(ndim))
+
+ cs = capi.create_cs(c_uint(1), c_uint(ndim))
+ i = iter(coords)
+ capi.cs_setx(cs, 0, next(i))
+ capi.cs_sety(cs, 0, next(i))
+ if ndim == 3: capi.cs_setz(cs, 0, next(i))
+
+ return capi.create_point(cs)
+
+ def _set_list(self, length, items):
+ ptr = self._create_point(length, items)
+ if ptr:
+ capi.destroy_geom(self.ptr)
+ self._ptr = ptr
+ self._set_cs()
+ else:
+ # can this happen?
+ raise GEOSException('Geometry resulting from slice deletion was invalid.')
+
+ def _set_single(self, index, value):
+ self._cs.setOrdinate(index, 0, value)
+
+ def __iter__(self):
+ "Allows iteration over coordinates of this Point."
+ for i in xrange(len(self)):
+ yield self[i]
+
+ def __len__(self):
+ "Returns the number of dimensions for this Point (either 0, 2 or 3)."
+ if self.empty: return 0
+ if self.hasz: return 3
+ else: return 2
+
+ def _get_single_external(self, index):
+ if index == 0:
+ return self.x
+ elif index == 1:
+ return self.y
+ elif index == 2:
+ return self.z
+
+ _get_single_internal = _get_single_external
+
+ def get_x(self):
+ "Returns the X component of the Point."
+ return self._cs.getOrdinate(0, 0)
+
+ def set_x(self, value):
+ "Sets the X component of the Point."
+ self._cs.setOrdinate(0, 0, value)
+
+ def get_y(self):
+ "Returns the Y component of the Point."
+ return self._cs.getOrdinate(1, 0)
+
+ def set_y(self, value):
+ "Sets the Y component of the Point."
+ self._cs.setOrdinate(1, 0, value)
+
+ def get_z(self):
+ "Returns the Z component of the Point."
+ if self.hasz:
+ return self._cs.getOrdinate(2, 0)
+ else:
+ return None
+
+ def set_z(self, value):
+ "Sets the Z component of the Point."
+ if self.hasz:
+ self._cs.setOrdinate(2, 0, value)
+ else:
+ raise GEOSException('Cannot set Z on 2D Point.')
+
+ # X, Y, Z properties
+ x = property(get_x, set_x)
+ y = property(get_y, set_y)
+ z = property(get_z, set_z)
+
+ ### Tuple setting and retrieval routines. ###
+ def get_coords(self):
+ "Returns a tuple of the point."
+ return self._cs.tuple
+
+ def set_coords(self, tup):
+ "Sets the coordinates of the point with the given tuple."
+ self._cs[0] = tup
+
+ # The tuple and coords properties
+ tuple = property(get_coords, set_coords)
+ coords = tuple
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/polygon.py b/lib/python2.7/site-packages/django/contrib/gis/geos/polygon.py
new file mode 100644
index 0000000..c50f549
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/polygon.py
@@ -0,0 +1,170 @@
+from ctypes import c_uint, byref
+from django.contrib.gis.geos.geometry import GEOSGeometry
+from django.contrib.gis.geos.libgeos import get_pointer_arr, GEOM_PTR
+from django.contrib.gis.geos.linestring import LinearRing
+from django.contrib.gis.geos import prototypes as capi
+from django.utils import six
+from django.utils.six.moves import xrange
+
+class Polygon(GEOSGeometry):
+ _minlength = 1
+
+ def __init__(self, *args, **kwargs):
+ """
+ Initializes on an exterior ring and a sequence of holes (both
+ instances may be either LinearRing instances, or a tuple/list
+ that may be constructed into a LinearRing).
+
+ Examples of initialization, where shell, hole1, and hole2 are
+ valid LinearRing geometries:
+ >>> poly = Polygon(shell, hole1, hole2)
+ >>> poly = Polygon(shell, (hole1, hole2))
+
+ Example where a tuple parameters are used:
+ >>> poly = Polygon(((0, 0), (0, 10), (10, 10), (0, 10), (0, 0)),
+ ((4, 4), (4, 6), (6, 6), (6, 4), (4, 4)))
+ """
+ if not args:
+ raise TypeError('Must provide at least one LinearRing, or a tuple, to initialize a Polygon.')
+
+ # Getting the ext_ring and init_holes parameters from the argument list
+ ext_ring = args[0]
+ init_holes = args[1:]
+ n_holes = len(init_holes)
+
+ # If initialized as Polygon(shell, (LinearRing, LinearRing)) [for backward-compatibility]
+ if n_holes == 1 and isinstance(init_holes[0], (tuple, list)):
+ if len(init_holes[0]) == 0:
+ init_holes = ()
+ n_holes = 0
+ elif isinstance(init_holes[0][0], LinearRing):
+ init_holes = init_holes[0]
+ n_holes = len(init_holes)
+
+ polygon = self._create_polygon(n_holes + 1, (ext_ring,) + init_holes)
+ super(Polygon, self).__init__(polygon, **kwargs)
+
+ def __iter__(self):
+ "Iterates over each ring in the polygon."
+ for i in xrange(len(self)):
+ yield self[i]
+
+ def __len__(self):
+ "Returns the number of rings in this Polygon."
+ return self.num_interior_rings + 1
+
+ @classmethod
+ def from_bbox(cls, bbox):
+ "Constructs a Polygon from a bounding box (4-tuple)."
+ x0, y0, x1, y1 = bbox
+ for z in bbox:
+ if not isinstance(z, six.integer_types + (float,)):
+ return GEOSGeometry('POLYGON((%s %s, %s %s, %s %s, %s %s, %s %s))' %
+ (x0, y0, x0, y1, x1, y1, x1, y0, x0, y0))
+ return Polygon(((x0, y0), (x0, y1), (x1, y1), (x1, y0), (x0, y0)))
+
+ ### These routines are needed for list-like operation w/ListMixin ###
+ def _create_polygon(self, length, items):
+ # Instantiate LinearRing objects if necessary, but don't clone them yet
+ # _construct_ring will throw a TypeError if a parameter isn't a valid ring
+ # If we cloned the pointers here, we wouldn't be able to clean up
+ # in case of error.
+ rings = []
+ for r in items:
+ if isinstance(r, GEOM_PTR):
+ rings.append(r)
+ else:
+ rings.append(self._construct_ring(r))
+
+ shell = self._clone(rings.pop(0))
+
+ n_holes = length - 1
+ if n_holes:
+ holes = get_pointer_arr(n_holes)
+ for i, r in enumerate(rings):
+ holes[i] = self._clone(r)
+ holes_param = byref(holes)
+ else:
+ holes_param = None
+
+ return capi.create_polygon(shell, holes_param, c_uint(n_holes))
+
+ def _clone(self, g):
+ if isinstance(g, GEOM_PTR):
+ return capi.geom_clone(g)
+ else:
+ return capi.geom_clone(g.ptr)
+
+ def _construct_ring(self, param, msg='Parameter must be a sequence of LinearRings or objects that can initialize to LinearRings'):
+ "Helper routine for trying to construct a ring from the given parameter."
+ if isinstance(param, LinearRing): return param
+ try:
+ ring = LinearRing(param)
+ return ring
+ except TypeError:
+ raise TypeError(msg)
+
+ def _set_list(self, length, items):
+ # Getting the current pointer, replacing with the newly constructed
+ # geometry, and destroying the old geometry.
+ prev_ptr = self.ptr
+ srid = self.srid
+ self.ptr = self._create_polygon(length, items)
+ if srid: self.srid = srid
+ capi.destroy_geom(prev_ptr)
+
+ def _get_single_internal(self, index):
+ """
+ Returns the ring at the specified index. The first index, 0, will
+ always return the exterior ring. Indices > 0 will return the
+ interior ring at the given index (e.g., poly[1] and poly[2] would
+ return the first and second interior ring, respectively).
+
+ CAREFUL: Internal/External are not the same as Interior/Exterior!
+ _get_single_internal returns a pointer from the existing geometries for use
+ internally by the object's methods. _get_single_external returns a clone
+ of the same geometry for use by external code.
+ """
+ if index == 0:
+ return capi.get_extring(self.ptr)
+ else:
+ # Getting the interior ring, have to subtract 1 from the index.
+ return capi.get_intring(self.ptr, index-1)
+
+ def _get_single_external(self, index):
+ return GEOSGeometry(capi.geom_clone(self._get_single_internal(index)), srid=self.srid)
+
+ _set_single = GEOSGeometry._set_single_rebuild
+ _assign_extended_slice = GEOSGeometry._assign_extended_slice_rebuild
+
+ #### Polygon Properties ####
+ @property
+ def num_interior_rings(self):
+ "Returns the number of interior rings."
+ # Getting the number of rings
+ return capi.get_nrings(self.ptr)
+
+ def _get_ext_ring(self):
+ "Gets the exterior ring of the Polygon."
+ return self[0]
+
+ def _set_ext_ring(self, ring):
+ "Sets the exterior ring of the Polygon."
+ self[0] = ring
+
+ # Properties for the exterior ring/shell.
+ exterior_ring = property(_get_ext_ring, _set_ext_ring)
+ shell = exterior_ring
+
+ @property
+ def tuple(self):
+ "Gets the tuple for each ring in this Polygon."
+ return tuple([self[i].tuple for i in xrange(len(self))])
+ coords = tuple
+
+ @property
+ def kml(self):
+ "Returns the KML representation of this Polygon."
+ inner_kml = ''.join(["<innerBoundaryIs>%s</innerBoundaryIs>" % self[i+1].kml
+ for i in xrange(self.num_interior_rings)])
+ return "<Polygon><outerBoundaryIs>%s</outerBoundaryIs>%s</Polygon>" % (self[0].kml, inner_kml)
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/prepared.py b/lib/python2.7/site-packages/django/contrib/gis/geos/prepared.py
new file mode 100644
index 0000000..ae2548f
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/prepared.py
@@ -0,0 +1,35 @@
+from django.contrib.gis.geos.base import GEOSBase
+from django.contrib.gis.geos.geometry import GEOSGeometry
+from django.contrib.gis.geos.prototypes import prepared as capi
+
+class PreparedGeometry(GEOSBase):
+ """
+ A geometry that is prepared for performing certain operations.
+ At the moment this includes the contains covers, and intersects
+ operations.
+ """
+ ptr_type = capi.PREPGEOM_PTR
+
+ def __init__(self, geom):
+ # Keeping a reference to the original geometry object to prevent it
+ # from being garbage collected which could then crash the prepared one
+ # See #21662
+ self._base_geom = geom
+ if not isinstance(geom, GEOSGeometry):
+ raise TypeError
+ self.ptr = capi.geos_prepare(geom.ptr)
+
+ def __del__(self):
+ if self._ptr: capi.prepared_destroy(self._ptr)
+
+ def contains(self, other):
+ return capi.prepared_contains(self.ptr, other.ptr)
+
+ def contains_properly(self, other):
+ return capi.prepared_contains_properly(self.ptr, other.ptr)
+
+ def covers(self, other):
+ return capi.prepared_covers(self.ptr, other.ptr)
+
+ def intersects(self, other):
+ return capi.prepared_intersects(self.ptr, other.ptr)
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/__init__.py b/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/__init__.py
new file mode 100644
index 0000000..89b96c0
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/__init__.py
@@ -0,0 +1,30 @@
+"""
+ This module contains all of the GEOS ctypes function prototypes. Each
+ prototype handles the interaction between the GEOS library and Python
+ via ctypes.
+"""
+
+# Coordinate sequence routines.
+from django.contrib.gis.geos.prototypes.coordseq import (create_cs, get_cs,
+ cs_clone, cs_getordinate, cs_setordinate, cs_getx, cs_gety, cs_getz,
+ cs_setx, cs_sety, cs_setz, cs_getsize, cs_getdims)
+
+# Geometry routines.
+from django.contrib.gis.geos.prototypes.geom import (from_hex, from_wkb, from_wkt,
+ create_point, create_linestring, create_linearring, create_polygon, create_collection,
+ destroy_geom, get_extring, get_intring, get_nrings, get_geomn, geom_clone,
+ geos_normalize, geos_type, geos_typeid, geos_get_srid, geos_set_srid,
+ get_dims, get_num_coords, get_num_geoms,
+ to_hex, to_wkb, to_wkt)
+
+# Miscellaneous routines.
+from django.contrib.gis.geos.prototypes.misc import *
+
+# Predicates
+from django.contrib.gis.geos.prototypes.predicates import (geos_hasz, geos_isempty,
+ geos_isring, geos_issimple, geos_isvalid, geos_contains, geos_crosses,
+ geos_disjoint, geos_equals, geos_equalsexact, geos_intersects,
+ geos_intersects, geos_overlaps, geos_relatepattern, geos_touches, geos_within)
+
+# Topology routines
+from django.contrib.gis.geos.prototypes.topology import *
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/coordseq.py b/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/coordseq.py
new file mode 100644
index 0000000..68b9480
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/coordseq.py
@@ -0,0 +1,83 @@
+from ctypes import c_double, c_int, c_uint, POINTER
+from django.contrib.gis.geos.libgeos import GEOM_PTR, CS_PTR
+from django.contrib.gis.geos.prototypes.errcheck import last_arg_byref, GEOSException
+from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc
+
+## Error-checking routines specific to coordinate sequences. ##
+def check_cs_ptr(result, func, cargs):
+ "Error checking on routines that return Geometries."
+ if not result:
+ raise GEOSException('Error encountered checking Coordinate Sequence returned from GEOS C function "%s".' % func.__name__)
+ return result
+
+def check_cs_op(result, func, cargs):
+ "Checks the status code of a coordinate sequence operation."
+ if result == 0:
+ raise GEOSException('Could not set value on coordinate sequence')
+ else:
+ return result
+
+def check_cs_get(result, func, cargs):
+ "Checking the coordinate sequence retrieval."
+ check_cs_op(result, func, cargs)
+ # Object in by reference, return its value.
+ return last_arg_byref(cargs)
+
+## Coordinate sequence prototype generation functions. ##
+def cs_int(func):
+ "For coordinate sequence routines that return an integer."
+ func.argtypes = [CS_PTR, POINTER(c_uint)]
+ func.restype = c_int
+ func.errcheck = check_cs_get
+ return func
+
+def cs_operation(func, ordinate=False, get=False):
+ "For coordinate sequence operations."
+ if get:
+ # Get routines get double parameter passed-in by reference.
+ func.errcheck = check_cs_get
+ dbl_param = POINTER(c_double)
+ else:
+ func.errcheck = check_cs_op
+ dbl_param = c_double
+
+ if ordinate:
+ # Get/Set ordinate routines have an extra uint parameter.
+ func.argtypes = [CS_PTR, c_uint, c_uint, dbl_param]
+ else:
+ func.argtypes = [CS_PTR, c_uint, dbl_param]
+
+ func.restype = c_int
+ return func
+
+def cs_output(func, argtypes):
+ "For routines that return a coordinate sequence."
+ func.argtypes = argtypes
+ func.restype = CS_PTR
+ func.errcheck = check_cs_ptr
+ return func
+
+## Coordinate Sequence ctypes prototypes ##
+
+# Coordinate Sequence constructors & cloning.
+cs_clone = cs_output(GEOSFunc('GEOSCoordSeq_clone'), [CS_PTR])
+create_cs = cs_output(GEOSFunc('GEOSCoordSeq_create'), [c_uint, c_uint])
+get_cs = cs_output(GEOSFunc('GEOSGeom_getCoordSeq'), [GEOM_PTR])
+
+# Getting, setting ordinate
+cs_getordinate = cs_operation(GEOSFunc('GEOSCoordSeq_getOrdinate'), ordinate=True, get=True)
+cs_setordinate = cs_operation(GEOSFunc('GEOSCoordSeq_setOrdinate'), ordinate=True)
+
+# For getting, x, y, z
+cs_getx = cs_operation(GEOSFunc('GEOSCoordSeq_getX'), get=True)
+cs_gety = cs_operation(GEOSFunc('GEOSCoordSeq_getY'), get=True)
+cs_getz = cs_operation(GEOSFunc('GEOSCoordSeq_getZ'), get=True)
+
+# For setting, x, y, z
+cs_setx = cs_operation(GEOSFunc('GEOSCoordSeq_setX'))
+cs_sety = cs_operation(GEOSFunc('GEOSCoordSeq_setY'))
+cs_setz = cs_operation(GEOSFunc('GEOSCoordSeq_setZ'))
+
+# These routines return size & dimensions.
+cs_getsize = cs_int(GEOSFunc('GEOSCoordSeq_getSize'))
+cs_getdims = cs_int(GEOSFunc('GEOSCoordSeq_getDimensions'))
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/errcheck.py b/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/errcheck.py
new file mode 100644
index 0000000..97fcd21
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/errcheck.py
@@ -0,0 +1,95 @@
+"""
+ Error checking functions for GEOS ctypes prototype functions.
+"""
+import os
+from ctypes import c_void_p, string_at, CDLL
+from django.contrib.gis.geos.error import GEOSException
+from django.contrib.gis.geos.libgeos import GEOS_VERSION
+from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc
+
+# Getting the `free` routine used to free the memory allocated for
+# string pointers returned by GEOS.
+if GEOS_VERSION >= (3, 1, 1):
+ # In versions 3.1.1 and above, `GEOSFree` was added to the C API
+ # because `free` isn't always available on all platforms.
+ free = GEOSFunc('GEOSFree')
+ free.argtypes = [c_void_p]
+ free.restype = None
+else:
+ # Getting the `free` routine from the C library of the platform.
+ if os.name == 'nt':
+ # On NT, use the MS C library.
+ libc = CDLL('msvcrt')
+ else:
+ # On POSIX platforms C library is obtained by passing None into `CDLL`.
+ libc = CDLL(None)
+ free = libc.free
+
+### ctypes error checking routines ###
+def last_arg_byref(args):
+ "Returns the last C argument's value by reference."
+ return args[-1]._obj.value
+
+def check_dbl(result, func, cargs):
+ "Checks the status code and returns the double value passed in by reference."
+ # Checking the status code
+ if result != 1: return None
+ # Double passed in by reference, return its value.
+ return last_arg_byref(cargs)
+
+def check_geom(result, func, cargs):
+ "Error checking on routines that return Geometries."
+ if not result:
+ raise GEOSException('Error encountered checking Geometry returned from GEOS C function "%s".' % func.__name__)
+ return result
+
+def check_minus_one(result, func, cargs):
+ "Error checking on routines that should not return -1."
+ if result == -1:
+ raise GEOSException('Error encountered in GEOS C function "%s".' % func.__name__)
+ else:
+ return result
+
+def check_predicate(result, func, cargs):
+ "Error checking for unary/binary predicate functions."
+ val = ord(result) # getting the ordinal from the character
+ if val == 1: return True
+ elif val == 0: return False
+ else:
+ raise GEOSException('Error encountered on GEOS C predicate function "%s".' % func.__name__)
+
+def check_sized_string(result, func, cargs):
+ """
+ Error checking for routines that return explicitly sized strings.
+
+ This frees the memory allocated by GEOS at the result pointer.
+ """
+ if not result:
+ raise GEOSException('Invalid string pointer returned by GEOS C function "%s"' % func.__name__)
+ # A c_size_t object is passed in by reference for the second
+ # argument on these routines, and its needed to determine the
+ # correct size.
+ s = string_at(result, last_arg_byref(cargs))
+ # Freeing the memory allocated within GEOS
+ free(result)
+ return s
+
+def check_string(result, func, cargs):
+ """
+ Error checking for routines that return strings.
+
+ This frees the memory allocated by GEOS at the result pointer.
+ """
+ if not result: raise GEOSException('Error encountered checking string return value in GEOS C function "%s".' % func.__name__)
+ # Getting the string value at the pointer address.
+ s = string_at(result)
+ # Freeing the memory allocated within GEOS
+ free(result)
+ return s
+
+def check_zero(result, func, cargs):
+ "Error checking on routines that should not return 0."
+ if result == 0:
+ raise GEOSException('Error encountered in GEOS C function "%s".' % func.__name__)
+ else:
+ return result
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/geom.py b/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/geom.py
new file mode 100644
index 0000000..2683c2e
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/geom.py
@@ -0,0 +1,119 @@
+from ctypes import c_char_p, c_int, c_size_t, c_ubyte, POINTER
+from django.contrib.gis.geos.libgeos import CS_PTR, GEOM_PTR
+from django.contrib.gis.geos.prototypes.errcheck import (
+ check_geom, check_minus_one, check_sized_string, check_string, check_zero)
+from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc
+
+# This is the return type used by binary output (WKB, HEX) routines.
+c_uchar_p = POINTER(c_ubyte)
+
+# We create a simple subclass of c_char_p here because when the response
+# type is set to c_char_p, you get a _Python_ string and there's no way
+# to access the string's address inside the error checking function.
+# In other words, you can't free the memory allocated inside GEOS. Previously,
+# the return type would just be omitted and the integer address would be
+# used -- but this allows us to be specific in the function definition and
+# keeps the reference so it may be free'd.
+class geos_char_p(c_char_p):
+ pass
+
+### ctypes generation functions ###
+def bin_constructor(func):
+ "Generates a prototype for binary construction (HEX, WKB) GEOS routines."
+ func.argtypes = [c_char_p, c_size_t]
+ func.restype = GEOM_PTR
+ func.errcheck = check_geom
+ return func
+
+# HEX & WKB output
+def bin_output(func):
+ "Generates a prototype for the routines that return a sized string."
+ func.argtypes = [GEOM_PTR, POINTER(c_size_t)]
+ func.errcheck = check_sized_string
+ func.restype = c_uchar_p
+ return func
+
+def geom_output(func, argtypes):
+ "For GEOS routines that return a geometry."
+ if argtypes: func.argtypes = argtypes
+ func.restype = GEOM_PTR
+ func.errcheck = check_geom
+ return func
+
+def geom_index(func):
+ "For GEOS routines that return geometries from an index."
+ return geom_output(func, [GEOM_PTR, c_int])
+
+def int_from_geom(func, zero=False):
+ "Argument is a geometry, return type is an integer."
+ func.argtypes = [GEOM_PTR]
+ func.restype = c_int
+ if zero:
+ func.errcheck = check_zero
+ else:
+ func.errcheck = check_minus_one
+ return func
+
+def string_from_geom(func):
+ "Argument is a Geometry, return type is a string."
+ func.argtypes = [GEOM_PTR]
+ func.restype = geos_char_p
+ func.errcheck = check_string
+ return func
+
+### ctypes prototypes ###
+
+# Deprecated creation routines from WKB, HEX, WKT
+from_hex = bin_constructor(GEOSFunc('GEOSGeomFromHEX_buf'))
+from_wkb = bin_constructor(GEOSFunc('GEOSGeomFromWKB_buf'))
+from_wkt = geom_output(GEOSFunc('GEOSGeomFromWKT'), [c_char_p])
+
+# Deprecated output routines
+to_hex = bin_output(GEOSFunc('GEOSGeomToHEX_buf'))
+to_wkb = bin_output(GEOSFunc('GEOSGeomToWKB_buf'))
+to_wkt = string_from_geom(GEOSFunc('GEOSGeomToWKT'))
+
+# The GEOS geometry type, typeid, num_coordites and number of geometries
+geos_normalize = int_from_geom(GEOSFunc('GEOSNormalize'))
+geos_type = string_from_geom(GEOSFunc('GEOSGeomType'))
+geos_typeid = int_from_geom(GEOSFunc('GEOSGeomTypeId'))
+get_dims = int_from_geom(GEOSFunc('GEOSGeom_getDimensions'), zero=True)
+get_num_coords = int_from_geom(GEOSFunc('GEOSGetNumCoordinates'))
+get_num_geoms = int_from_geom(GEOSFunc('GEOSGetNumGeometries'))
+
+# Geometry creation factories
+create_point = geom_output(GEOSFunc('GEOSGeom_createPoint'), [CS_PTR])
+create_linestring = geom_output(GEOSFunc('GEOSGeom_createLineString'), [CS_PTR])
+create_linearring = geom_output(GEOSFunc('GEOSGeom_createLinearRing'), [CS_PTR])
+
+# Polygon and collection creation routines are special and will not
+# have their argument types defined.
+create_polygon = geom_output(GEOSFunc('GEOSGeom_createPolygon'), None)
+create_collection = geom_output(GEOSFunc('GEOSGeom_createCollection'), None)
+
+# Ring routines
+get_extring = geom_output(GEOSFunc('GEOSGetExteriorRing'), [GEOM_PTR])
+get_intring = geom_index(GEOSFunc('GEOSGetInteriorRingN'))
+get_nrings = int_from_geom(GEOSFunc('GEOSGetNumInteriorRings'))
+
+# Collection Routines
+get_geomn = geom_index(GEOSFunc('GEOSGetGeometryN'))
+
+# Cloning
+geom_clone = GEOSFunc('GEOSGeom_clone')
+geom_clone.argtypes = [GEOM_PTR]
+geom_clone.restype = GEOM_PTR
+
+# Destruction routine.
+destroy_geom = GEOSFunc('GEOSGeom_destroy')
+destroy_geom.argtypes = [GEOM_PTR]
+destroy_geom.restype = None
+
+# SRID routines
+geos_get_srid = GEOSFunc('GEOSGetSRID')
+geos_get_srid.argtypes = [GEOM_PTR]
+geos_get_srid.restype = c_int
+
+geos_set_srid = GEOSFunc('GEOSSetSRID')
+geos_set_srid.argtypes = [GEOM_PTR, c_int]
+geos_set_srid.restype = None
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/io.py b/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/io.py
new file mode 100644
index 0000000..1e80351
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/io.py
@@ -0,0 +1,265 @@
+import threading
+from ctypes import byref, c_char_p, c_int, c_char, c_size_t, Structure, POINTER
+from django.contrib.gis import memoryview
+from django.contrib.gis.geos.base import GEOSBase
+from django.contrib.gis.geos.libgeos import GEOM_PTR
+from django.contrib.gis.geos.prototypes.errcheck import check_geom, check_string, check_sized_string
+from django.contrib.gis.geos.prototypes.geom import c_uchar_p, geos_char_p
+from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc
+
+from django.utils import six
+from django.utils.encoding import force_bytes
+
+### The WKB/WKT Reader/Writer structures and pointers ###
+class WKTReader_st(Structure): pass
+class WKTWriter_st(Structure): pass
+class WKBReader_st(Structure): pass
+class WKBWriter_st(Structure): pass
+
+WKT_READ_PTR = POINTER(WKTReader_st)
+WKT_WRITE_PTR = POINTER(WKTWriter_st)
+WKB_READ_PTR = POINTER(WKBReader_st)
+WKB_WRITE_PTR = POINTER(WKBReader_st)
+
+### WKTReader routines ###
+wkt_reader_create = GEOSFunc('GEOSWKTReader_create')
+wkt_reader_create.restype = WKT_READ_PTR
+
+wkt_reader_destroy = GEOSFunc('GEOSWKTReader_destroy')
+wkt_reader_destroy.argtypes = [WKT_READ_PTR]
+
+wkt_reader_read = GEOSFunc('GEOSWKTReader_read')
+wkt_reader_read.argtypes = [WKT_READ_PTR, c_char_p]
+wkt_reader_read.restype = GEOM_PTR
+wkt_reader_read.errcheck = check_geom
+
+### WKTWriter routines ###
+wkt_writer_create = GEOSFunc('GEOSWKTWriter_create')
+wkt_writer_create.restype = WKT_WRITE_PTR
+
+wkt_writer_destroy = GEOSFunc('GEOSWKTWriter_destroy')
+wkt_writer_destroy.argtypes = [WKT_WRITE_PTR]
+
+wkt_writer_write = GEOSFunc('GEOSWKTWriter_write')
+wkt_writer_write.argtypes = [WKT_WRITE_PTR, GEOM_PTR]
+wkt_writer_write.restype = geos_char_p
+wkt_writer_write.errcheck = check_string
+
+try:
+ wkt_writer_get_outdim = GEOSFunc('GEOSWKTWriter_getOutputDimension')
+ wkt_writer_get_outdim.argtypes = [WKT_WRITE_PTR]
+ wkt_writer_get_outdim.restype = c_int
+ wkt_writer_set_outdim = GEOSFunc('GEOSWKTWriter_setOutputDimension')
+ wkt_writer_set_outdim.argtypes = [WKT_WRITE_PTR, c_int]
+except AttributeError:
+ # GEOSWKTWriter_get/setOutputDimension has been introduced in GEOS 3.3.0
+ # Always return 2 if not available
+ wkt_writer_get_outdim = lambda ptr: 2
+ wkt_writer_set_outdim = lambda ptr, dim: None
+
+### WKBReader routines ###
+wkb_reader_create = GEOSFunc('GEOSWKBReader_create')
+wkb_reader_create.restype = WKB_READ_PTR
+
+wkb_reader_destroy = GEOSFunc('GEOSWKBReader_destroy')
+wkb_reader_destroy.argtypes = [WKB_READ_PTR]
+
+def wkb_read_func(func):
+ # Although the function definitions take `const unsigned char *`
+ # as their parameter, we use c_char_p here so the function may
+ # take Python strings directly as parameters. Inside Python there
+ # is not a difference between signed and unsigned characters, so
+ # it is not a problem.
+ func.argtypes = [WKB_READ_PTR, c_char_p, c_size_t]
+ func.restype = GEOM_PTR
+ func.errcheck = check_geom
+ return func
+
+wkb_reader_read = wkb_read_func(GEOSFunc('GEOSWKBReader_read'))
+wkb_reader_read_hex = wkb_read_func(GEOSFunc('GEOSWKBReader_readHEX'))
+
+### WKBWriter routines ###
+wkb_writer_create = GEOSFunc('GEOSWKBWriter_create')
+wkb_writer_create.restype = WKB_WRITE_PTR
+
+wkb_writer_destroy = GEOSFunc('GEOSWKBWriter_destroy')
+wkb_writer_destroy.argtypes = [WKB_WRITE_PTR]
+
+# WKB Writing prototypes.
+def wkb_write_func(func):
+ func.argtypes = [WKB_WRITE_PTR, GEOM_PTR, POINTER(c_size_t)]
+ func.restype = c_uchar_p
+ func.errcheck = check_sized_string
+ return func
+
+wkb_writer_write = wkb_write_func(GEOSFunc('GEOSWKBWriter_write'))
+wkb_writer_write_hex = wkb_write_func(GEOSFunc('GEOSWKBWriter_writeHEX'))
+
+# WKBWriter property getter/setter prototypes.
+def wkb_writer_get(func, restype=c_int):
+ func.argtypes = [WKB_WRITE_PTR]
+ func.restype = restype
+ return func
+
+def wkb_writer_set(func, argtype=c_int):
+ func.argtypes = [WKB_WRITE_PTR, argtype]
+ return func
+
+wkb_writer_get_byteorder = wkb_writer_get(GEOSFunc('GEOSWKBWriter_getByteOrder'))
+wkb_writer_set_byteorder = wkb_writer_set(GEOSFunc('GEOSWKBWriter_setByteOrder'))
+wkb_writer_get_outdim = wkb_writer_get(GEOSFunc('GEOSWKBWriter_getOutputDimension'))
+wkb_writer_set_outdim = wkb_writer_set(GEOSFunc('GEOSWKBWriter_setOutputDimension'))
+wkb_writer_get_include_srid = wkb_writer_get(GEOSFunc('GEOSWKBWriter_getIncludeSRID'), restype=c_char)
+wkb_writer_set_include_srid = wkb_writer_set(GEOSFunc('GEOSWKBWriter_setIncludeSRID'), argtype=c_char)
+
+### Base I/O Class ###
+class IOBase(GEOSBase):
+ "Base class for GEOS I/O objects."
+ def __init__(self):
+ # Getting the pointer with the constructor.
+ self.ptr = self._constructor()
+
+ def __del__(self):
+ # Cleaning up with the appropriate destructor.
+ if self._ptr: self._destructor(self._ptr)
+
+### Base WKB/WKT Reading and Writing objects ###
+
+# Non-public WKB/WKT reader classes for internal use because
+# their `read` methods return _pointers_ instead of GEOSGeometry
+# objects.
+class _WKTReader(IOBase):
+ _constructor = wkt_reader_create
+ _destructor = wkt_reader_destroy
+ ptr_type = WKT_READ_PTR
+
+ def read(self, wkt):
+ if not isinstance(wkt, (bytes, six.string_types)):
+ raise TypeError
+ return wkt_reader_read(self.ptr, force_bytes(wkt))
+
+class _WKBReader(IOBase):
+ _constructor = wkb_reader_create
+ _destructor = wkb_reader_destroy
+ ptr_type = WKB_READ_PTR
+
+ def read(self, wkb):
+ "Returns a _pointer_ to C GEOS Geometry object from the given WKB."
+ if isinstance(wkb, memoryview):
+ wkb_s = bytes(wkb)
+ return wkb_reader_read(self.ptr, wkb_s, len(wkb_s))
+ elif isinstance(wkb, (bytes, six.string_types)):
+ return wkb_reader_read_hex(self.ptr, wkb, len(wkb))
+ else:
+ raise TypeError
+
+### WKB/WKT Writer Classes ###
+class WKTWriter(IOBase):
+ _constructor = wkt_writer_create
+ _destructor = wkt_writer_destroy
+ ptr_type = WKT_WRITE_PTR
+
+ def write(self, geom):
+ "Returns the WKT representation of the given geometry."
+ return wkt_writer_write(self.ptr, geom.ptr)
+
+ @property
+ def outdim(self):
+ return wkt_writer_get_outdim(self.ptr)
+
+ @outdim.setter
+ def outdim(self, new_dim):
+ if not new_dim in (2, 3):
+ raise ValueError('WKT output dimension must be 2 or 3')
+ wkt_writer_set_outdim(self.ptr, new_dim)
+
+
+class WKBWriter(IOBase):
+ _constructor = wkb_writer_create
+ _destructor = wkb_writer_destroy
+ ptr_type = WKB_WRITE_PTR
+
+ def write(self, geom):
+ "Returns the WKB representation of the given geometry."
+ return memoryview(wkb_writer_write(self.ptr, geom.ptr, byref(c_size_t())))
+
+ def write_hex(self, geom):
+ "Returns the HEXEWKB representation of the given geometry."
+ return wkb_writer_write_hex(self.ptr, geom.ptr, byref(c_size_t()))
+
+ ### WKBWriter Properties ###
+
+ # Property for getting/setting the byteorder.
+ def _get_byteorder(self):
+ return wkb_writer_get_byteorder(self.ptr)
+
+ def _set_byteorder(self, order):
+ if not order in (0, 1): raise ValueError('Byte order parameter must be 0 (Big Endian) or 1 (Little Endian).')
+ wkb_writer_set_byteorder(self.ptr, order)
+
+ byteorder = property(_get_byteorder, _set_byteorder)
+
+ # Property for getting/setting the output dimension.
+ def _get_outdim(self):
+ return wkb_writer_get_outdim(self.ptr)
+
+ def _set_outdim(self, new_dim):
+ if not new_dim in (2, 3): raise ValueError('WKB output dimension must be 2 or 3')
+ wkb_writer_set_outdim(self.ptr, new_dim)
+
+ outdim = property(_get_outdim, _set_outdim)
+
+ # Property for getting/setting the include srid flag.
+ def _get_include_srid(self):
+ return bool(ord(wkb_writer_get_include_srid(self.ptr)))
+
+ def _set_include_srid(self, include):
+ if bool(include): flag = b'\x01'
+ else: flag = b'\x00'
+ wkb_writer_set_include_srid(self.ptr, flag)
+
+ srid = property(_get_include_srid, _set_include_srid)
+
+# `ThreadLocalIO` object holds instances of the WKT and WKB reader/writer
+# objects that are local to the thread. The `GEOSGeometry` internals
+# access these instances by calling the module-level functions, defined
+# below.
+class ThreadLocalIO(threading.local):
+ wkt_r = None
+ wkt_w = None
+ wkb_r = None
+ wkb_w = None
+ ewkb_w = None
+
+thread_context = ThreadLocalIO()
+
+# These module-level routines return the I/O object that is local to the
+# thread. If the I/O object does not exist yet it will be initialized.
+def wkt_r():
+ if not thread_context.wkt_r:
+ thread_context.wkt_r = _WKTReader()
+ return thread_context.wkt_r
+
+def wkt_w(dim=2):
+ if not thread_context.wkt_w:
+ thread_context.wkt_w = WKTWriter()
+ thread_context.wkt_w.outdim = dim
+ return thread_context.wkt_w
+
+def wkb_r():
+ if not thread_context.wkb_r:
+ thread_context.wkb_r = _WKBReader()
+ return thread_context.wkb_r
+
+def wkb_w(dim=2):
+ if not thread_context.wkb_w:
+ thread_context.wkb_w = WKBWriter()
+ thread_context.wkb_w.outdim = dim
+ return thread_context.wkb_w
+
+def ewkb_w(dim=2):
+ if not thread_context.ewkb_w:
+ thread_context.ewkb_w = WKBWriter()
+ thread_context.ewkb_w.srid = True
+ thread_context.ewkb_w.outdim = dim
+ return thread_context.ewkb_w
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/misc.py b/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/misc.py
new file mode 100644
index 0000000..5a9b555
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/misc.py
@@ -0,0 +1,40 @@
+"""
+ This module is for the miscellaneous GEOS routines, particularly the
+ ones that return the area, distance, and length.
+"""
+from ctypes import c_int, c_double, POINTER
+from django.contrib.gis.geos.libgeos import GEOM_PTR, GEOS_PREPARE
+from django.contrib.gis.geos.prototypes.errcheck import check_dbl, check_string
+from django.contrib.gis.geos.prototypes.geom import geos_char_p
+from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc
+from django.utils.six.moves import xrange
+
+__all__ = ['geos_area', 'geos_distance', 'geos_length']
+
+### ctypes generator function ###
+def dbl_from_geom(func, num_geom=1):
+ """
+ Argument is a Geometry, return type is double that is passed
+ in by reference as the last argument.
+ """
+ argtypes = [GEOM_PTR for i in xrange(num_geom)]
+ argtypes += [POINTER(c_double)]
+ func.argtypes = argtypes
+ func.restype = c_int # Status code returned
+ func.errcheck = check_dbl
+ return func
+
+### ctypes prototypes ###
+
+# Area, distance, and length prototypes.
+geos_area = dbl_from_geom(GEOSFunc('GEOSArea'))
+geos_distance = dbl_from_geom(GEOSFunc('GEOSDistance'), num_geom=2)
+geos_length = dbl_from_geom(GEOSFunc('GEOSLength'))
+
+# Validity reason; only in GEOS 3.1+
+if GEOS_PREPARE:
+ geos_isvalidreason = GEOSFunc('GEOSisValidReason')
+ geos_isvalidreason.argtypes = [GEOM_PTR]
+ geos_isvalidreason.restype = geos_char_p
+ geos_isvalidreason.errcheck = check_string
+ __all__.append('geos_isvalidreason')
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/predicates.py b/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/predicates.py
new file mode 100644
index 0000000..bf69bb1
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/predicates.py
@@ -0,0 +1,44 @@
+"""
+ This module houses the GEOS ctypes prototype functions for the
+ unary and binary predicate operations on geometries.
+"""
+from ctypes import c_char, c_char_p, c_double
+from django.contrib.gis.geos.libgeos import GEOM_PTR
+from django.contrib.gis.geos.prototypes.errcheck import check_predicate
+from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc
+
+## Binary & unary predicate functions ##
+def binary_predicate(func, *args):
+ "For GEOS binary predicate functions."
+ argtypes = [GEOM_PTR, GEOM_PTR]
+ if args: argtypes += args
+ func.argtypes = argtypes
+ func.restype = c_char
+ func.errcheck = check_predicate
+ return func
+
+def unary_predicate(func):
+ "For GEOS unary predicate functions."
+ func.argtypes = [GEOM_PTR]
+ func.restype = c_char
+ func.errcheck = check_predicate
+ return func
+
+## Unary Predicates ##
+geos_hasz = unary_predicate(GEOSFunc('GEOSHasZ'))
+geos_isempty = unary_predicate(GEOSFunc('GEOSisEmpty'))
+geos_isring = unary_predicate(GEOSFunc('GEOSisRing'))
+geos_issimple = unary_predicate(GEOSFunc('GEOSisSimple'))
+geos_isvalid = unary_predicate(GEOSFunc('GEOSisValid'))
+
+## Binary Predicates ##
+geos_contains = binary_predicate(GEOSFunc('GEOSContains'))
+geos_crosses = binary_predicate(GEOSFunc('GEOSCrosses'))
+geos_disjoint = binary_predicate(GEOSFunc('GEOSDisjoint'))
+geos_equals = binary_predicate(GEOSFunc('GEOSEquals'))
+geos_equalsexact = binary_predicate(GEOSFunc('GEOSEqualsExact'), c_double)
+geos_intersects = binary_predicate(GEOSFunc('GEOSIntersects'))
+geos_overlaps = binary_predicate(GEOSFunc('GEOSOverlaps'))
+geos_relatepattern = binary_predicate(GEOSFunc('GEOSRelatePattern'), c_char_p)
+geos_touches = binary_predicate(GEOSFunc('GEOSTouches'))
+geos_within = binary_predicate(GEOSFunc('GEOSWithin'))
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/prepared.py b/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/prepared.py
new file mode 100644
index 0000000..7342d7d
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/prepared.py
@@ -0,0 +1,25 @@
+from ctypes import c_char
+from django.contrib.gis.geos.libgeos import GEOM_PTR, PREPGEOM_PTR
+from django.contrib.gis.geos.prototypes.errcheck import check_predicate
+from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc
+
+# Prepared geometry constructor and destructors.
+geos_prepare = GEOSFunc('GEOSPrepare')
+geos_prepare.argtypes = [GEOM_PTR]
+geos_prepare.restype = PREPGEOM_PTR
+
+prepared_destroy = GEOSFunc('GEOSPreparedGeom_destroy')
+prepared_destroy.argtpes = [PREPGEOM_PTR]
+prepared_destroy.restype = None
+
+# Prepared geometry binary predicate support.
+def prepared_predicate(func):
+ func.argtypes= [PREPGEOM_PTR, GEOM_PTR]
+ func.restype = c_char
+ func.errcheck = check_predicate
+ return func
+
+prepared_contains = prepared_predicate(GEOSFunc('GEOSPreparedContains'))
+prepared_contains_properly = prepared_predicate(GEOSFunc('GEOSPreparedContainsProperly'))
+prepared_covers = prepared_predicate(GEOSFunc('GEOSPreparedCovers'))
+prepared_intersects = prepared_predicate(GEOSFunc('GEOSPreparedIntersects'))
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/threadsafe.py b/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/threadsafe.py
new file mode 100644
index 0000000..2c9d25e
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/threadsafe.py
@@ -0,0 +1,86 @@
+import threading
+from django.contrib.gis.geos.libgeos import lgeos, notice_h, error_h, CONTEXT_PTR
+
+class GEOSContextHandle(object):
+ """
+ Python object representing a GEOS context handle.
+ """
+ def __init__(self):
+ # Initializing the context handler for this thread with
+ # the notice and error handler.
+ self.ptr = lgeos.initGEOS_r(notice_h, error_h)
+
+ def __del__(self):
+ if self.ptr: lgeos.finishGEOS_r(self.ptr)
+
+# Defining a thread-local object and creating an instance
+# to hold a reference to GEOSContextHandle for this thread.
+class GEOSContext(threading.local):
+ handle = None
+
+thread_context = GEOSContext()
+
+class GEOSFunc(object):
+ """
+ Class that serves as a wrapper for GEOS C Functions, and will
+ use thread-safe function variants when available.
+ """
+ def __init__(self, func_name):
+ try:
+ # GEOS thread-safe function signatures end with '_r', and
+ # take an additional context handle parameter.
+ self.cfunc = getattr(lgeos, func_name + '_r')
+ self.threaded = True
+ # Create a reference here to thread_context so it's not
+ # garbage-collected before an attempt to call this object.
+ self.thread_context = thread_context
+ except AttributeError:
+ # Otherwise, use usual function.
+ self.cfunc = getattr(lgeos, func_name)
+ self.threaded = False
+
+ def __call__(self, *args):
+ if self.threaded:
+ # If a context handle does not exist for this thread, initialize one.
+ if not self.thread_context.handle:
+ self.thread_context.handle = GEOSContextHandle()
+ # Call the threaded GEOS routine with pointer of the context handle
+ # as the first argument.
+ return self.cfunc(self.thread_context.handle.ptr, *args)
+ else:
+ return self.cfunc(*args)
+
+ def __str__(self):
+ return self.cfunc.__name__
+
+ # argtypes property
+ def _get_argtypes(self):
+ return self.cfunc.argtypes
+
+ def _set_argtypes(self, argtypes):
+ if self.threaded:
+ new_argtypes = [CONTEXT_PTR]
+ new_argtypes.extend(argtypes)
+ self.cfunc.argtypes = new_argtypes
+ else:
+ self.cfunc.argtypes = argtypes
+
+ argtypes = property(_get_argtypes, _set_argtypes)
+
+ # restype property
+ def _get_restype(self):
+ return self.cfunc.restype
+
+ def _set_restype(self, restype):
+ self.cfunc.restype = restype
+
+ restype = property(_get_restype, _set_restype)
+
+ # errcheck property
+ def _get_errcheck(self):
+ return self.cfunc.errcheck
+
+ def _set_errcheck(self, errcheck):
+ self.cfunc.errcheck = errcheck
+
+ errcheck = property(_get_errcheck, _set_errcheck)
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/topology.py b/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/topology.py
new file mode 100644
index 0000000..dfea3e9
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/prototypes/topology.py
@@ -0,0 +1,64 @@
+"""
+ This module houses the GEOS ctypes prototype functions for the
+ topological operations on geometries.
+"""
+__all__ = ['geos_boundary', 'geos_buffer', 'geos_centroid', 'geos_convexhull',
+ 'geos_difference', 'geos_envelope', 'geos_intersection',
+ 'geos_linemerge', 'geos_pointonsurface', 'geos_preservesimplify',
+ 'geos_simplify', 'geos_symdifference', 'geos_union', 'geos_relate']
+
+from ctypes import c_double, c_int
+from django.contrib.gis.geos.libgeos import geos_version_info, GEOM_PTR, GEOS_PREPARE
+from django.contrib.gis.geos.prototypes.errcheck import check_geom, check_minus_one, check_string
+from django.contrib.gis.geos.prototypes.geom import geos_char_p
+from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc
+
+def topology(func, *args, **kwargs):
+ "For GEOS unary topology functions."
+ argtypes = [GEOM_PTR]
+ if args: argtypes += args
+ func.argtypes = argtypes
+ func.restype = kwargs.get('restype', GEOM_PTR)
+ func.errcheck = kwargs.get('errcheck', check_geom)
+ return func
+
+### Topology Routines ###
+geos_boundary = topology(GEOSFunc('GEOSBoundary'))
+geos_buffer = topology(GEOSFunc('GEOSBuffer'), c_double, c_int)
+geos_centroid = topology(GEOSFunc('GEOSGetCentroid'))
+geos_convexhull = topology(GEOSFunc('GEOSConvexHull'))
+geos_difference = topology(GEOSFunc('GEOSDifference'), GEOM_PTR)
+geos_envelope = topology(GEOSFunc('GEOSEnvelope'))
+geos_intersection = topology(GEOSFunc('GEOSIntersection'), GEOM_PTR)
+geos_linemerge = topology(GEOSFunc('GEOSLineMerge'))
+geos_pointonsurface = topology(GEOSFunc('GEOSPointOnSurface'))
+geos_preservesimplify = topology(GEOSFunc('GEOSTopologyPreserveSimplify'), c_double)
+geos_simplify = topology(GEOSFunc('GEOSSimplify'), c_double)
+geos_symdifference = topology(GEOSFunc('GEOSSymDifference'), GEOM_PTR)
+geos_union = topology(GEOSFunc('GEOSUnion'), GEOM_PTR)
+
+# GEOSRelate returns a string, not a geometry.
+geos_relate = GEOSFunc('GEOSRelate')
+geos_relate.argtypes = [GEOM_PTR, GEOM_PTR]
+geos_relate.restype = geos_char_p
+geos_relate.errcheck = check_string
+
+# Routines only in GEOS 3.1+
+if GEOS_PREPARE:
+ geos_cascaded_union = GEOSFunc('GEOSUnionCascaded')
+ geos_cascaded_union.argtypes = [GEOM_PTR]
+ geos_cascaded_union.restype = GEOM_PTR
+ __all__.append('geos_cascaded_union')
+
+# Linear referencing routines
+info = geos_version_info()
+if info['version'] >= '3.2.0':
+ geos_project = topology(GEOSFunc('GEOSProject'), GEOM_PTR,
+ restype=c_double, errcheck=check_minus_one)
+ geos_interpolate = topology(GEOSFunc('GEOSInterpolate'), c_double)
+
+ geos_project_normalized = topology(GEOSFunc('GEOSProjectNormalized'),
+ GEOM_PTR, restype=c_double, errcheck=check_minus_one)
+ geos_interpolate_normalized = topology(GEOSFunc('GEOSInterpolateNormalized'), c_double)
+ __all__.extend(['geos_project', 'geos_interpolate',
+ 'geos_project_normalized', 'geos_interpolate_normalized'])
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/tests/__init__.py b/lib/python2.7/site-packages/django/contrib/gis/geos/tests/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/tests/__init__.py
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/tests/test_geos.py b/lib/python2.7/site-packages/django/contrib/gis/geos/tests/test_geos.py
new file mode 100644
index 0000000..c8e064b
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/tests/test_geos.py
@@ -0,0 +1,1108 @@
+from __future__ import unicode_literals
+
+import ctypes
+import json
+import random
+from binascii import a2b_hex, b2a_hex
+from io import BytesIO
+
+from django.contrib.gis.gdal import HAS_GDAL
+
+from django.contrib.gis import memoryview
+from django.contrib.gis.geometry.test_data import TestDataMixin
+
+from django.utils.encoding import force_bytes
+from django.utils import six
+from django.utils.six.moves import xrange
+from django.utils import unittest
+from django.utils.unittest import skipUnless
+
+from .. import HAS_GEOS
+
+if HAS_GEOS:
+ from .. import (GEOSException, GEOSIndexError, GEOSGeometry,
+ GeometryCollection, Point, MultiPoint, Polygon, MultiPolygon, LinearRing,
+ LineString, MultiLineString, fromfile, fromstr, geos_version_info,
+ GEOS_PREPARE)
+ from ..base import gdal, numpy, GEOSBase
+
+
+@skipUnless(HAS_GEOS, "Geos is required.")
+class GEOSTest(unittest.TestCase, TestDataMixin):
+
+ @property
+ def null_srid(self):
+ """
+ Returns the proper null SRID depending on the GEOS version.
+ See the comments in `test_srid` for more details.
+ """
+ info = geos_version_info()
+ if info['version'] == '3.0.0' and info['release_candidate']:
+ return -1
+ else:
+ return None
+
+ def test_base(self):
+ "Tests out the GEOSBase class."
+ # Testing out GEOSBase class, which provides a `ptr` property
+ # that abstracts out access to underlying C pointers.
+ class FakeGeom1(GEOSBase):
+ pass
+
+ # This one only accepts pointers to floats
+ c_float_p = ctypes.POINTER(ctypes.c_float)
+ class FakeGeom2(GEOSBase):
+ ptr_type = c_float_p
+
+ # Default ptr_type is `c_void_p`.
+ fg1 = FakeGeom1()
+ # Default ptr_type is C float pointer
+ fg2 = FakeGeom2()
+
+ # These assignments are OK -- None is allowed because
+ # it's equivalent to the NULL pointer.
+ fg1.ptr = ctypes.c_void_p()
+ fg1.ptr = None
+ fg2.ptr = c_float_p(ctypes.c_float(5.23))
+ fg2.ptr = None
+
+ # Because pointers have been set to NULL, an exception should be
+ # raised when we try to access it. Raising an exception is
+ # preferrable to a segmentation fault that commonly occurs when
+ # a C method is given a NULL memory reference.
+ for fg in (fg1, fg2):
+ # Equivalent to `fg.ptr`
+ self.assertRaises(GEOSException, fg._get_ptr)
+
+ # Anything that is either not None or the acceptable pointer type will
+ # result in a TypeError when trying to assign it to the `ptr` property.
+ # Thus, memmory addresses (integers) and pointers of the incorrect type
+ # (in `bad_ptrs`) will not be allowed.
+ bad_ptrs = (5, ctypes.c_char_p(b'foobar'))
+ for bad_ptr in bad_ptrs:
+ # Equivalent to `fg.ptr = bad_ptr`
+ self.assertRaises(TypeError, fg1._set_ptr, bad_ptr)
+ self.assertRaises(TypeError, fg2._set_ptr, bad_ptr)
+
+ def test_wkt(self):
+ "Testing WKT output."
+ for g in self.geometries.wkt_out:
+ geom = fromstr(g.wkt)
+ if geom.hasz and geos_version_info()['version'] >= '3.3.0':
+ self.assertEqual(g.ewkt, geom.wkt)
+
+ def test_hex(self):
+ "Testing HEX output."
+ for g in self.geometries.hex_wkt:
+ geom = fromstr(g.wkt)
+ self.assertEqual(g.hex, geom.hex.decode())
+
+ def test_hexewkb(self):
+ "Testing (HEX)EWKB output."
+ # For testing HEX(EWKB).
+ ogc_hex = b'01010000000000000000000000000000000000F03F'
+ ogc_hex_3d = b'01010000800000000000000000000000000000F03F0000000000000040'
+ # `SELECT ST_AsHEXEWKB(ST_GeomFromText('POINT(0 1)', 4326));`
+ hexewkb_2d = b'0101000020E61000000000000000000000000000000000F03F'
+ # `SELECT ST_AsHEXEWKB(ST_GeomFromEWKT('SRID=4326;POINT(0 1 2)'));`
+ hexewkb_3d = b'01010000A0E61000000000000000000000000000000000F03F0000000000000040'
+
+ pnt_2d = Point(0, 1, srid=4326)
+ pnt_3d = Point(0, 1, 2, srid=4326)
+
+ # OGC-compliant HEX will not have SRID value.
+ self.assertEqual(ogc_hex, pnt_2d.hex)
+ self.assertEqual(ogc_hex_3d, pnt_3d.hex)
+
+ # HEXEWKB should be appropriate for its dimension -- have to use an
+ # a WKBWriter w/dimension set accordingly, else GEOS will insert
+ # garbage into 3D coordinate if there is none. Also, GEOS has a
+ # a bug in versions prior to 3.1 that puts the X coordinate in
+ # place of Z; an exception should be raised on those versions.
+ self.assertEqual(hexewkb_2d, pnt_2d.hexewkb)
+ if GEOS_PREPARE:
+ self.assertEqual(hexewkb_3d, pnt_3d.hexewkb)
+ self.assertEqual(True, GEOSGeometry(hexewkb_3d).hasz)
+ else:
+ try:
+ hexewkb = pnt_3d.hexewkb
+ except GEOSException:
+ pass
+ else:
+ self.fail('Should have raised GEOSException.')
+
+ # Same for EWKB.
+ self.assertEqual(memoryview(a2b_hex(hexewkb_2d)), pnt_2d.ewkb)
+ if GEOS_PREPARE:
+ self.assertEqual(memoryview(a2b_hex(hexewkb_3d)), pnt_3d.ewkb)
+ else:
+ try:
+ ewkb = pnt_3d.ewkb
+ except GEOSException:
+ pass
+ else:
+ self.fail('Should have raised GEOSException')
+
+ # Redundant sanity check.
+ self.assertEqual(4326, GEOSGeometry(hexewkb_2d).srid)
+
+ def test_kml(self):
+ "Testing KML output."
+ for tg in self.geometries.wkt_out:
+ geom = fromstr(tg.wkt)
+ kml = getattr(tg, 'kml', False)
+ if kml: self.assertEqual(kml, geom.kml)
+
+ def test_errors(self):
+ "Testing the Error handlers."
+ # string-based
+ for err in self.geometries.errors:
+ with self.assertRaises((GEOSException, ValueError)):
+ _ = fromstr(err.wkt)
+
+ # Bad WKB
+ self.assertRaises(GEOSException, GEOSGeometry, memoryview(b'0'))
+
+ class NotAGeometry(object):
+ pass
+
+ # Some other object
+ self.assertRaises(TypeError, GEOSGeometry, NotAGeometry())
+ # None
+ self.assertRaises(TypeError, GEOSGeometry, None)
+
+ def test_wkb(self):
+ "Testing WKB output."
+ for g in self.geometries.hex_wkt:
+ geom = fromstr(g.wkt)
+ wkb = geom.wkb
+ self.assertEqual(b2a_hex(wkb).decode().upper(), g.hex)
+
+ def test_create_hex(self):
+ "Testing creation from HEX."
+ for g in self.geometries.hex_wkt:
+ geom_h = GEOSGeometry(g.hex)
+ # we need to do this so decimal places get normalised
+ geom_t = fromstr(g.wkt)
+ self.assertEqual(geom_t.wkt, geom_h.wkt)
+
+ def test_create_wkb(self):
+ "Testing creation from WKB."
+ for g in self.geometries.hex_wkt:
+ wkb = memoryview(a2b_hex(g.hex.encode()))
+ geom_h = GEOSGeometry(wkb)
+ # we need to do this so decimal places get normalised
+ geom_t = fromstr(g.wkt)
+ self.assertEqual(geom_t.wkt, geom_h.wkt)
+
+ def test_ewkt(self):
+ "Testing EWKT."
+ srids = (-1, 32140)
+ for srid in srids:
+ for p in self.geometries.polygons:
+ ewkt = 'SRID=%d;%s' % (srid, p.wkt)
+ poly = fromstr(ewkt)
+ self.assertEqual(srid, poly.srid)
+ self.assertEqual(srid, poly.shell.srid)
+ self.assertEqual(srid, fromstr(poly.ewkt).srid) # Checking export
+
+ @skipUnless(HAS_GDAL, "GDAL is required.")
+ def test_json(self):
+ "Testing GeoJSON input/output (via GDAL)."
+ for g in self.geometries.json_geoms:
+ geom = GEOSGeometry(g.wkt)
+ if not hasattr(g, 'not_equal'):
+ # Loading jsons to prevent decimal differences
+ self.assertEqual(json.loads(g.json), json.loads(geom.json))
+ self.assertEqual(json.loads(g.json), json.loads(geom.geojson))
+ self.assertEqual(GEOSGeometry(g.wkt), GEOSGeometry(geom.json))
+
+ def test_fromfile(self):
+ "Testing the fromfile() factory."
+ ref_pnt = GEOSGeometry('POINT(5 23)')
+
+ wkt_f = BytesIO()
+ wkt_f.write(force_bytes(ref_pnt.wkt))
+ wkb_f = BytesIO()
+ wkb_f.write(bytes(ref_pnt.wkb))
+
+ # Other tests use `fromfile()` on string filenames so those
+ # aren't tested here.
+ for fh in (wkt_f, wkb_f):
+ fh.seek(0)
+ pnt = fromfile(fh)
+ self.assertEqual(ref_pnt, pnt)
+
+ def test_eq(self):
+ "Testing equivalence."
+ p = fromstr('POINT(5 23)')
+ self.assertEqual(p, p.wkt)
+ self.assertNotEqual(p, 'foo')
+ ls = fromstr('LINESTRING(0 0, 1 1, 5 5)')
+ self.assertEqual(ls, ls.wkt)
+ self.assertNotEqual(p, 'bar')
+ # Error shouldn't be raise on equivalence testing with
+ # an invalid type.
+ for g in (p, ls):
+ self.assertNotEqual(g, None)
+ self.assertNotEqual(g, {'foo' : 'bar'})
+ self.assertNotEqual(g, False)
+
+ def test_points(self):
+ "Testing Point objects."
+ prev = fromstr('POINT(0 0)')
+ for p in self.geometries.points:
+ # Creating the point from the WKT
+ pnt = fromstr(p.wkt)
+ self.assertEqual(pnt.geom_type, 'Point')
+ self.assertEqual(pnt.geom_typeid, 0)
+ self.assertEqual(p.x, pnt.x)
+ self.assertEqual(p.y, pnt.y)
+ self.assertEqual(True, pnt == fromstr(p.wkt))
+ self.assertEqual(False, pnt == prev)
+
+ # Making sure that the point's X, Y components are what we expect
+ self.assertAlmostEqual(p.x, pnt.tuple[0], 9)
+ self.assertAlmostEqual(p.y, pnt.tuple[1], 9)
+
+ # Testing the third dimension, and getting the tuple arguments
+ if hasattr(p, 'z'):
+ self.assertEqual(True, pnt.hasz)
+ self.assertEqual(p.z, pnt.z)
+ self.assertEqual(p.z, pnt.tuple[2], 9)
+ tup_args = (p.x, p.y, p.z)
+ set_tup1 = (2.71, 3.14, 5.23)
+ set_tup2 = (5.23, 2.71, 3.14)
+ else:
+ self.assertEqual(False, pnt.hasz)
+ self.assertEqual(None, pnt.z)
+ tup_args = (p.x, p.y)
+ set_tup1 = (2.71, 3.14)
+ set_tup2 = (3.14, 2.71)
+
+ # Centroid operation on point should be point itself
+ self.assertEqual(p.centroid, pnt.centroid.tuple)
+
+ # Now testing the different constructors
+ pnt2 = Point(tup_args) # e.g., Point((1, 2))
+ pnt3 = Point(*tup_args) # e.g., Point(1, 2)
+ self.assertEqual(True, pnt == pnt2)
+ self.assertEqual(True, pnt == pnt3)
+
+ # Now testing setting the x and y
+ pnt.y = 3.14
+ pnt.x = 2.71
+ self.assertEqual(3.14, pnt.y)
+ self.assertEqual(2.71, pnt.x)
+
+ # Setting via the tuple/coords property
+ pnt.tuple = set_tup1
+ self.assertEqual(set_tup1, pnt.tuple)
+ pnt.coords = set_tup2
+ self.assertEqual(set_tup2, pnt.coords)
+
+ prev = pnt # setting the previous geometry
+
+ def test_multipoints(self):
+ "Testing MultiPoint objects."
+ for mp in self.geometries.multipoints:
+ mpnt = fromstr(mp.wkt)
+ self.assertEqual(mpnt.geom_type, 'MultiPoint')
+ self.assertEqual(mpnt.geom_typeid, 4)
+
+ self.assertAlmostEqual(mp.centroid[0], mpnt.centroid.tuple[0], 9)
+ self.assertAlmostEqual(mp.centroid[1], mpnt.centroid.tuple[1], 9)
+
+ self.assertRaises(GEOSIndexError, mpnt.__getitem__, len(mpnt))
+ self.assertEqual(mp.centroid, mpnt.centroid.tuple)
+ self.assertEqual(mp.coords, tuple(m.tuple for m in mpnt))
+ for p in mpnt:
+ self.assertEqual(p.geom_type, 'Point')
+ self.assertEqual(p.geom_typeid, 0)
+ self.assertEqual(p.empty, False)
+ self.assertEqual(p.valid, True)
+
+ def test_linestring(self):
+ "Testing LineString objects."
+ prev = fromstr('POINT(0 0)')
+ for l in self.geometries.linestrings:
+ ls = fromstr(l.wkt)
+ self.assertEqual(ls.geom_type, 'LineString')
+ self.assertEqual(ls.geom_typeid, 1)
+ self.assertEqual(ls.empty, False)
+ self.assertEqual(ls.ring, False)
+ if hasattr(l, 'centroid'):
+ self.assertEqual(l.centroid, ls.centroid.tuple)
+ if hasattr(l, 'tup'):
+ self.assertEqual(l.tup, ls.tuple)
+
+ self.assertEqual(True, ls == fromstr(l.wkt))
+ self.assertEqual(False, ls == prev)
+ self.assertRaises(GEOSIndexError, ls.__getitem__, len(ls))
+ prev = ls
+
+ # Creating a LineString from a tuple, list, and numpy array
+ self.assertEqual(ls, LineString(ls.tuple)) # tuple
+ self.assertEqual(ls, LineString(*ls.tuple)) # as individual arguments
+ self.assertEqual(ls, LineString([list(tup) for tup in ls.tuple])) # as list
+ self.assertEqual(ls.wkt, LineString(*tuple(Point(tup) for tup in ls.tuple)).wkt) # Point individual arguments
+ if numpy: self.assertEqual(ls, LineString(numpy.array(ls.tuple))) # as numpy array
+
+ def test_multilinestring(self):
+ "Testing MultiLineString objects."
+ prev = fromstr('POINT(0 0)')
+ for l in self.geometries.multilinestrings:
+ ml = fromstr(l.wkt)
+ self.assertEqual(ml.geom_type, 'MultiLineString')
+ self.assertEqual(ml.geom_typeid, 5)
+
+ self.assertAlmostEqual(l.centroid[0], ml.centroid.x, 9)
+ self.assertAlmostEqual(l.centroid[1], ml.centroid.y, 9)
+
+ self.assertEqual(True, ml == fromstr(l.wkt))
+ self.assertEqual(False, ml == prev)
+ prev = ml
+
+ for ls in ml:
+ self.assertEqual(ls.geom_type, 'LineString')
+ self.assertEqual(ls.geom_typeid, 1)
+ self.assertEqual(ls.empty, False)
+
+ self.assertRaises(GEOSIndexError, ml.__getitem__, len(ml))
+ self.assertEqual(ml.wkt, MultiLineString(*tuple(s.clone() for s in ml)).wkt)
+ self.assertEqual(ml, MultiLineString(*tuple(LineString(s.tuple) for s in ml)))
+
+ def test_linearring(self):
+ "Testing LinearRing objects."
+ for rr in self.geometries.linearrings:
+ lr = fromstr(rr.wkt)
+ self.assertEqual(lr.geom_type, 'LinearRing')
+ self.assertEqual(lr.geom_typeid, 2)
+ self.assertEqual(rr.n_p, len(lr))
+ self.assertEqual(True, lr.valid)
+ self.assertEqual(False, lr.empty)
+
+ # Creating a LinearRing from a tuple, list, and numpy array
+ self.assertEqual(lr, LinearRing(lr.tuple))
+ self.assertEqual(lr, LinearRing(*lr.tuple))
+ self.assertEqual(lr, LinearRing([list(tup) for tup in lr.tuple]))
+ if numpy: self.assertEqual(lr, LinearRing(numpy.array(lr.tuple)))
+
+ def test_polygons_from_bbox(self):
+ "Testing `from_bbox` class method."
+ bbox = (-180, -90, 180, 90)
+ p = Polygon.from_bbox(bbox)
+ self.assertEqual(bbox, p.extent)
+
+ # Testing numerical precision
+ x = 3.14159265358979323
+ bbox = (0, 0, 1, x)
+ p = Polygon.from_bbox(bbox)
+ y = p.extent[-1]
+ self.assertEqual(format(x, '.13f'), format(y, '.13f'))
+
+ def test_polygons(self):
+ "Testing Polygon objects."
+
+ prev = fromstr('POINT(0 0)')
+ for p in self.geometries.polygons:
+ # Creating the Polygon, testing its properties.
+ poly = fromstr(p.wkt)
+ self.assertEqual(poly.geom_type, 'Polygon')
+ self.assertEqual(poly.geom_typeid, 3)
+ self.assertEqual(poly.empty, False)
+ self.assertEqual(poly.ring, False)
+ self.assertEqual(p.n_i, poly.num_interior_rings)
+ self.assertEqual(p.n_i + 1, len(poly)) # Testing __len__
+ self.assertEqual(p.n_p, poly.num_points)
+
+ # Area & Centroid
+ self.assertAlmostEqual(p.area, poly.area, 9)
+ self.assertAlmostEqual(p.centroid[0], poly.centroid.tuple[0], 9)
+ self.assertAlmostEqual(p.centroid[1], poly.centroid.tuple[1], 9)
+
+ # Testing the geometry equivalence
+ self.assertEqual(True, poly == fromstr(p.wkt))
+ self.assertEqual(False, poly == prev) # Should not be equal to previous geometry
+ self.assertEqual(True, poly != prev)
+
+ # Testing the exterior ring
+ ring = poly.exterior_ring
+ self.assertEqual(ring.geom_type, 'LinearRing')
+ self.assertEqual(ring.geom_typeid, 2)
+ if p.ext_ring_cs:
+ self.assertEqual(p.ext_ring_cs, ring.tuple)
+ self.assertEqual(p.ext_ring_cs, poly[0].tuple) # Testing __getitem__
+
+ # Testing __getitem__ and __setitem__ on invalid indices
+ self.assertRaises(GEOSIndexError, poly.__getitem__, len(poly))
+ self.assertRaises(GEOSIndexError, poly.__setitem__, len(poly), False)
+ self.assertRaises(GEOSIndexError, poly.__getitem__, -1 * len(poly) - 1)
+
+ # Testing __iter__
+ for r in poly:
+ self.assertEqual(r.geom_type, 'LinearRing')
+ self.assertEqual(r.geom_typeid, 2)
+
+ # Testing polygon construction.
+ self.assertRaises(TypeError, Polygon, 0, [1, 2, 3])
+ self.assertRaises(TypeError, Polygon, 'foo')
+
+ # Polygon(shell, (hole1, ... holeN))
+ rings = tuple(r for r in poly)
+ self.assertEqual(poly, Polygon(rings[0], rings[1:]))
+
+ # Polygon(shell_tuple, hole_tuple1, ... , hole_tupleN)
+ ring_tuples = tuple(r.tuple for r in poly)
+ self.assertEqual(poly, Polygon(*ring_tuples))
+
+ # Constructing with tuples of LinearRings.
+ self.assertEqual(poly.wkt, Polygon(*tuple(r for r in poly)).wkt)
+ self.assertEqual(poly.wkt, Polygon(*tuple(LinearRing(r.tuple) for r in poly)).wkt)
+
+ def test_polygon_comparison(self):
+ p1 = Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)))
+ p2 = Polygon(((0, 0), (0, 1), (1, 0), (0, 0)))
+ self.assertTrue(p1 > p2)
+ self.assertFalse(p1 < p2)
+ self.assertFalse(p2 > p1)
+ self.assertTrue(p2 < p1)
+
+ p3 = Polygon(((0, 0), (0, 1), (1, 1), (2, 0), (0, 0)))
+ p4 = Polygon(((0, 0), (0, 1), (2, 2), (1, 0), (0, 0)))
+ self.assertFalse(p4 < p3)
+ self.assertTrue(p3 < p4)
+ self.assertTrue(p4 > p3)
+ self.assertFalse(p3 > p4)
+
+ def test_multipolygons(self):
+ "Testing MultiPolygon objects."
+ prev = fromstr('POINT (0 0)')
+ for mp in self.geometries.multipolygons:
+ mpoly = fromstr(mp.wkt)
+ self.assertEqual(mpoly.geom_type, 'MultiPolygon')
+ self.assertEqual(mpoly.geom_typeid, 6)
+ self.assertEqual(mp.valid, mpoly.valid)
+
+ if mp.valid:
+ self.assertEqual(mp.num_geom, mpoly.num_geom)
+ self.assertEqual(mp.n_p, mpoly.num_coords)
+ self.assertEqual(mp.num_geom, len(mpoly))
+ self.assertRaises(GEOSIndexError, mpoly.__getitem__, len(mpoly))
+ for p in mpoly:
+ self.assertEqual(p.geom_type, 'Polygon')
+ self.assertEqual(p.geom_typeid, 3)
+ self.assertEqual(p.valid, True)
+ self.assertEqual(mpoly.wkt, MultiPolygon(*tuple(poly.clone() for poly in mpoly)).wkt)
+
+ def test_memory_hijinks(self):
+ "Testing Geometry __del__() on rings and polygons."
+ #### Memory issues with rings and polygons
+
+ # These tests are needed to ensure sanity with writable geometries.
+
+ # Getting a polygon with interior rings, and pulling out the interior rings
+ poly = fromstr(self.geometries.polygons[1].wkt)
+ ring1 = poly[0]
+ ring2 = poly[1]
+
+ # These deletes should be 'harmless' since they are done on child geometries
+ del ring1
+ del ring2
+ ring1 = poly[0]
+ ring2 = poly[1]
+
+ # Deleting the polygon
+ del poly
+
+ # Access to these rings is OK since they are clones.
+ s1, s2 = str(ring1), str(ring2)
+
+ def test_coord_seq(self):
+ "Testing Coordinate Sequence objects."
+ for p in self.geometries.polygons:
+ if p.ext_ring_cs:
+ # Constructing the polygon and getting the coordinate sequence
+ poly = fromstr(p.wkt)
+ cs = poly.exterior_ring.coord_seq
+
+ self.assertEqual(p.ext_ring_cs, cs.tuple) # done in the Polygon test too.
+ self.assertEqual(len(p.ext_ring_cs), len(cs)) # Making sure __len__ works
+
+ # Checks __getitem__ and __setitem__
+ for i in xrange(len(p.ext_ring_cs)):
+ c1 = p.ext_ring_cs[i] # Expected value
+ c2 = cs[i] # Value from coordseq
+ self.assertEqual(c1, c2)
+
+ # Constructing the test value to set the coordinate sequence with
+ if len(c1) == 2: tset = (5, 23)
+ else: tset = (5, 23, 8)
+ cs[i] = tset
+
+ # Making sure every set point matches what we expect
+ for j in range(len(tset)):
+ cs[i] = tset
+ self.assertEqual(tset[j], cs[i][j])
+
+ def test_relate_pattern(self):
+ "Testing relate() and relate_pattern()."
+ g = fromstr('POINT (0 0)')
+ self.assertRaises(GEOSException, g.relate_pattern, 0, 'invalid pattern, yo')
+ for rg in self.geometries.relate_geoms:
+ a = fromstr(rg.wkt_a)
+ b = fromstr(rg.wkt_b)
+ self.assertEqual(rg.result, a.relate_pattern(b, rg.pattern))
+ self.assertEqual(rg.pattern, a.relate(b))
+
+ def test_intersection(self):
+ "Testing intersects() and intersection()."
+ for i in xrange(len(self.geometries.topology_geoms)):
+ a = fromstr(self.geometries.topology_geoms[i].wkt_a)
+ b = fromstr(self.geometries.topology_geoms[i].wkt_b)
+ i1 = fromstr(self.geometries.intersect_geoms[i].wkt)
+ self.assertEqual(True, a.intersects(b))
+ i2 = a.intersection(b)
+ self.assertEqual(i1, i2)
+ self.assertEqual(i1, a & b) # __and__ is intersection operator
+ a &= b # testing __iand__
+ self.assertEqual(i1, a)
+
+ def test_union(self):
+ "Testing union()."
+ for i in xrange(len(self.geometries.topology_geoms)):
+ a = fromstr(self.geometries.topology_geoms[i].wkt_a)
+ b = fromstr(self.geometries.topology_geoms[i].wkt_b)
+ u1 = fromstr(self.geometries.union_geoms[i].wkt)
+ u2 = a.union(b)
+ self.assertEqual(u1, u2)
+ self.assertEqual(u1, a | b) # __or__ is union operator
+ a |= b # testing __ior__
+ self.assertEqual(u1, a)
+
+ def test_difference(self):
+ "Testing difference()."
+ for i in xrange(len(self.geometries.topology_geoms)):
+ a = fromstr(self.geometries.topology_geoms[i].wkt_a)
+ b = fromstr(self.geometries.topology_geoms[i].wkt_b)
+ d1 = fromstr(self.geometries.diff_geoms[i].wkt)
+ d2 = a.difference(b)
+ self.assertEqual(d1, d2)
+ self.assertEqual(d1, a - b) # __sub__ is difference operator
+ a -= b # testing __isub__
+ self.assertEqual(d1, a)
+
+ def test_symdifference(self):
+ "Testing sym_difference()."
+ for i in xrange(len(self.geometries.topology_geoms)):
+ a = fromstr(self.geometries.topology_geoms[i].wkt_a)
+ b = fromstr(self.geometries.topology_geoms[i].wkt_b)
+ d1 = fromstr(self.geometries.sdiff_geoms[i].wkt)
+ d2 = a.sym_difference(b)
+ self.assertEqual(d1, d2)
+ self.assertEqual(d1, a ^ b) # __xor__ is symmetric difference operator
+ a ^= b # testing __ixor__
+ self.assertEqual(d1, a)
+
+ def test_buffer(self):
+ "Testing buffer()."
+ for bg in self.geometries.buffer_geoms:
+ g = fromstr(bg.wkt)
+
+ # The buffer we expect
+ exp_buf = fromstr(bg.buffer_wkt)
+ quadsegs = bg.quadsegs
+ width = bg.width
+
+ # Can't use a floating-point for the number of quadsegs.
+ self.assertRaises(ctypes.ArgumentError, g.buffer, width, float(quadsegs))
+
+ # Constructing our buffer
+ buf = g.buffer(width, quadsegs)
+ self.assertEqual(exp_buf.num_coords, buf.num_coords)
+ self.assertEqual(len(exp_buf), len(buf))
+
+ # Now assuring that each point in the buffer is almost equal
+ for j in xrange(len(exp_buf)):
+ exp_ring = exp_buf[j]
+ buf_ring = buf[j]
+ self.assertEqual(len(exp_ring), len(buf_ring))
+ for k in xrange(len(exp_ring)):
+ # Asserting the X, Y of each point are almost equal (due to floating point imprecision)
+ self.assertAlmostEqual(exp_ring[k][0], buf_ring[k][0], 9)
+ self.assertAlmostEqual(exp_ring[k][1], buf_ring[k][1], 9)
+
+ def test_srid(self):
+ "Testing the SRID property and keyword."
+ # Testing SRID keyword on Point
+ pnt = Point(5, 23, srid=4326)
+ self.assertEqual(4326, pnt.srid)
+ pnt.srid = 3084
+ self.assertEqual(3084, pnt.srid)
+ self.assertRaises(ctypes.ArgumentError, pnt.set_srid, '4326')
+
+ # Testing SRID keyword on fromstr(), and on Polygon rings.
+ poly = fromstr(self.geometries.polygons[1].wkt, srid=4269)
+ self.assertEqual(4269, poly.srid)
+ for ring in poly: self.assertEqual(4269, ring.srid)
+ poly.srid = 4326
+ self.assertEqual(4326, poly.shell.srid)
+
+ # Testing SRID keyword on GeometryCollection
+ gc = GeometryCollection(Point(5, 23), LineString((0, 0), (1.5, 1.5), (3, 3)), srid=32021)
+ self.assertEqual(32021, gc.srid)
+ for i in range(len(gc)): self.assertEqual(32021, gc[i].srid)
+
+ # GEOS may get the SRID from HEXEWKB
+ # 'POINT(5 23)' at SRID=4326 in hex form -- obtained from PostGIS
+ # using `SELECT GeomFromText('POINT (5 23)', 4326);`.
+ hex = '0101000020E610000000000000000014400000000000003740'
+ p1 = fromstr(hex)
+ self.assertEqual(4326, p1.srid)
+
+ # In GEOS 3.0.0rc1-4 when the EWKB and/or HEXEWKB is exported,
+ # the SRID information is lost and set to -1 -- this is not a
+ # problem on the 3.0.0 version (another reason to upgrade).
+ exp_srid = self.null_srid
+
+ p2 = fromstr(p1.hex)
+ self.assertEqual(exp_srid, p2.srid)
+ p3 = fromstr(p1.hex, srid=-1) # -1 is intended.
+ self.assertEqual(-1, p3.srid)
+
+ @skipUnless(HAS_GDAL, "GDAL is required.")
+ def test_custom_srid(self):
+ """ Test with a srid unknown from GDAL """
+ pnt = Point(111200, 220900, srid=999999)
+ self.assertTrue(pnt.ewkt.startswith("SRID=999999;POINT (111200.0"))
+ self.assertIsInstance(pnt.ogr, gdal.OGRGeometry)
+ self.assertIsNone(pnt.srs)
+
+ # Test conversion from custom to a known srid
+ c2w = gdal.CoordTransform(
+ gdal.SpatialReference('+proj=mill +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +R_A +ellps=WGS84 +datum=WGS84 +units=m +no_defs'),
+ gdal.SpatialReference(4326))
+ new_pnt = pnt.transform(c2w, clone=True)
+ self.assertEqual(new_pnt.srid, 4326)
+ self.assertAlmostEqual(new_pnt.x, 1, 3)
+ self.assertAlmostEqual(new_pnt.y, 2, 3)
+
+ def test_mutable_geometries(self):
+ "Testing the mutability of Polygons and Geometry Collections."
+ ### Testing the mutability of Polygons ###
+ for p in self.geometries.polygons:
+ poly = fromstr(p.wkt)
+
+ # Should only be able to use __setitem__ with LinearRing geometries.
+ self.assertRaises(TypeError, poly.__setitem__, 0, LineString((1, 1), (2, 2)))
+
+ # Constructing the new shell by adding 500 to every point in the old shell.
+ shell_tup = poly.shell.tuple
+ new_coords = []
+ for point in shell_tup: new_coords.append((point[0] + 500., point[1] + 500.))
+ new_shell = LinearRing(*tuple(new_coords))
+
+ # Assigning polygon's exterior ring w/the new shell
+ poly.exterior_ring = new_shell
+ s = str(new_shell) # new shell is still accessible
+ self.assertEqual(poly.exterior_ring, new_shell)
+ self.assertEqual(poly[0], new_shell)
+
+ ### Testing the mutability of Geometry Collections
+ for tg in self.geometries.multipoints:
+ mp = fromstr(tg.wkt)
+ for i in range(len(mp)):
+ # Creating a random point.
+ pnt = mp[i]
+ new = Point(random.randint(21, 100), random.randint(21, 100))
+ # Testing the assignment
+ mp[i] = new
+ s = str(new) # what was used for the assignment is still accessible
+ self.assertEqual(mp[i], new)
+ self.assertEqual(mp[i].wkt, new.wkt)
+ self.assertNotEqual(pnt, mp[i])
+
+ # MultiPolygons involve much more memory management because each
+ # Polygon w/in the collection has its own rings.
+ for tg in self.geometries.multipolygons:
+ mpoly = fromstr(tg.wkt)
+ for i in xrange(len(mpoly)):
+ poly = mpoly[i]
+ old_poly = mpoly[i]
+ # Offsetting the each ring in the polygon by 500.
+ for j in xrange(len(poly)):
+ r = poly[j]
+ for k in xrange(len(r)): r[k] = (r[k][0] + 500., r[k][1] + 500.)
+ poly[j] = r
+
+ self.assertNotEqual(mpoly[i], poly)
+ # Testing the assignment
+ mpoly[i] = poly
+ s = str(poly) # Still accessible
+ self.assertEqual(mpoly[i], poly)
+ self.assertNotEqual(mpoly[i], old_poly)
+
+ # Extreme (!!) __setitem__ -- no longer works, have to detect
+ # in the first object that __setitem__ is called in the subsequent
+ # objects -- maybe mpoly[0, 0, 0] = (3.14, 2.71)?
+ #mpoly[0][0][0] = (3.14, 2.71)
+ #self.assertEqual((3.14, 2.71), mpoly[0][0][0])
+ # Doing it more slowly..
+ #self.assertEqual((3.14, 2.71), mpoly[0].shell[0])
+ #del mpoly
+
+ def test_threed(self):
+ "Testing three-dimensional geometries."
+ # Testing a 3D Point
+ pnt = Point(2, 3, 8)
+ self.assertEqual((2.,3.,8.), pnt.coords)
+ self.assertRaises(TypeError, pnt.set_coords, (1.,2.))
+ pnt.coords = (1.,2.,3.)
+ self.assertEqual((1.,2.,3.), pnt.coords)
+
+ # Testing a 3D LineString
+ ls = LineString((2., 3., 8.), (50., 250., -117.))
+ self.assertEqual(((2.,3.,8.), (50.,250.,-117.)), ls.tuple)
+ self.assertRaises(TypeError, ls.__setitem__, 0, (1.,2.))
+ ls[0] = (1.,2.,3.)
+ self.assertEqual((1.,2.,3.), ls[0])
+
+ def test_distance(self):
+ "Testing the distance() function."
+ # Distance to self should be 0.
+ pnt = Point(0, 0)
+ self.assertEqual(0.0, pnt.distance(Point(0, 0)))
+
+ # Distance should be 1
+ self.assertEqual(1.0, pnt.distance(Point(0, 1)))
+
+ # Distance should be ~ sqrt(2)
+ self.assertAlmostEqual(1.41421356237, pnt.distance(Point(1, 1)), 11)
+
+ # Distances are from the closest vertex in each geometry --
+ # should be 3 (distance from (2, 2) to (5, 2)).
+ ls1 = LineString((0, 0), (1, 1), (2, 2))
+ ls2 = LineString((5, 2), (6, 1), (7, 0))
+ self.assertEqual(3, ls1.distance(ls2))
+
+ def test_length(self):
+ "Testing the length property."
+ # Points have 0 length.
+ pnt = Point(0, 0)
+ self.assertEqual(0.0, pnt.length)
+
+ # Should be ~ sqrt(2)
+ ls = LineString((0, 0), (1, 1))
+ self.assertAlmostEqual(1.41421356237, ls.length, 11)
+
+ # Should be circumfrence of Polygon
+ poly = Polygon(LinearRing((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)))
+ self.assertEqual(4.0, poly.length)
+
+ # Should be sum of each element's length in collection.
+ mpoly = MultiPolygon(poly.clone(), poly)
+ self.assertEqual(8.0, mpoly.length)
+
+ def test_emptyCollections(self):
+ "Testing empty geometries and collections."
+ gc1 = GeometryCollection([])
+ gc2 = fromstr('GEOMETRYCOLLECTION EMPTY')
+ pnt = fromstr('POINT EMPTY')
+ ls = fromstr('LINESTRING EMPTY')
+ poly = fromstr('POLYGON EMPTY')
+ mls = fromstr('MULTILINESTRING EMPTY')
+ mpoly1 = fromstr('MULTIPOLYGON EMPTY')
+ mpoly2 = MultiPolygon(())
+
+ for g in [gc1, gc2, pnt, ls, poly, mls, mpoly1, mpoly2]:
+ self.assertEqual(True, g.empty)
+
+ # Testing len() and num_geom.
+ if isinstance(g, Polygon):
+ self.assertEqual(1, len(g)) # Has one empty linear ring
+ self.assertEqual(1, g.num_geom)
+ self.assertEqual(0, len(g[0]))
+ elif isinstance(g, (Point, LineString)):
+ self.assertEqual(1, g.num_geom)
+ self.assertEqual(0, len(g))
+ else:
+ self.assertEqual(0, g.num_geom)
+ self.assertEqual(0, len(g))
+
+ # Testing __getitem__ (doesn't work on Point or Polygon)
+ if isinstance(g, Point):
+ self.assertRaises(GEOSIndexError, g.get_x)
+ elif isinstance(g, Polygon):
+ lr = g.shell
+ self.assertEqual('LINEARRING EMPTY', lr.wkt)
+ self.assertEqual(0, len(lr))
+ self.assertEqual(True, lr.empty)
+ self.assertRaises(GEOSIndexError, lr.__getitem__, 0)
+ else:
+ self.assertRaises(GEOSIndexError, g.__getitem__, 0)
+
+ def test_collections_of_collections(self):
+ "Testing GeometryCollection handling of other collections."
+ # Creating a GeometryCollection WKT string composed of other
+ # collections and polygons.
+ coll = [mp.wkt for mp in self.geometries.multipolygons if mp.valid]
+ coll.extend([mls.wkt for mls in self.geometries.multilinestrings])
+ coll.extend([p.wkt for p in self.geometries.polygons])
+ coll.extend([mp.wkt for mp in self.geometries.multipoints])
+ gc_wkt = 'GEOMETRYCOLLECTION(%s)' % ','.join(coll)
+
+ # Should construct ok from WKT
+ gc1 = GEOSGeometry(gc_wkt)
+
+ # Should also construct ok from individual geometry arguments.
+ gc2 = GeometryCollection(*tuple(g for g in gc1))
+
+ # And, they should be equal.
+ self.assertEqual(gc1, gc2)
+
+ @skipUnless(HAS_GDAL, "GDAL is required.")
+ def test_gdal(self):
+ "Testing `ogr` and `srs` properties."
+ g1 = fromstr('POINT(5 23)')
+ self.assertIsInstance(g1.ogr, gdal.OGRGeometry)
+ self.assertIsNone(g1.srs)
+
+ if GEOS_PREPARE:
+ g1_3d = fromstr('POINT(5 23 8)')
+ self.assertIsInstance(g1_3d.ogr, gdal.OGRGeometry)
+ self.assertEqual(g1_3d.ogr.z, 8)
+
+ g2 = fromstr('LINESTRING(0 0, 5 5, 23 23)', srid=4326)
+ self.assertIsInstance(g2.ogr, gdal.OGRGeometry)
+ self.assertIsInstance(g2.srs, gdal.SpatialReference)
+ self.assertEqual(g2.hex, g2.ogr.hex)
+ self.assertEqual('WGS 84', g2.srs.name)
+
+ def test_copy(self):
+ "Testing use with the Python `copy` module."
+ import copy
+ poly = GEOSGeometry('POLYGON((0 0, 0 23, 23 23, 23 0, 0 0), (5 5, 5 10, 10 10, 10 5, 5 5))')
+ cpy1 = copy.copy(poly)
+ cpy2 = copy.deepcopy(poly)
+ self.assertNotEqual(poly._ptr, cpy1._ptr)
+ self.assertNotEqual(poly._ptr, cpy2._ptr)
+
+ @skipUnless(HAS_GDAL, "GDAL is required to transform geometries")
+ def test_transform(self):
+ "Testing `transform` method."
+ orig = GEOSGeometry('POINT (-104.609 38.255)', 4326)
+ trans = GEOSGeometry('POINT (992385.4472045 481455.4944650)', 2774)
+
+ # Using a srid, a SpatialReference object, and a CoordTransform object
+ # for transformations.
+ t1, t2, t3 = orig.clone(), orig.clone(), orig.clone()
+ t1.transform(trans.srid)
+ t2.transform(gdal.SpatialReference('EPSG:2774'))
+ ct = gdal.CoordTransform(gdal.SpatialReference('WGS84'), gdal.SpatialReference(2774))
+ t3.transform(ct)
+
+ # Testing use of the `clone` keyword.
+ k1 = orig.clone()
+ k2 = k1.transform(trans.srid, clone=True)
+ self.assertEqual(k1, orig)
+ self.assertNotEqual(k1, k2)
+
+ prec = 3
+ for p in (t1, t2, t3, k2):
+ self.assertAlmostEqual(trans.x, p.x, prec)
+ self.assertAlmostEqual(trans.y, p.y, prec)
+
+ @skipUnless(HAS_GDAL, "GDAL is required to transform geometries")
+ def test_transform_3d(self):
+ p3d = GEOSGeometry('POINT (5 23 100)', 4326)
+ p3d.transform(2774)
+ if GEOS_PREPARE:
+ self.assertEqual(p3d.z, 100)
+ else:
+ self.assertIsNone(p3d.z)
+
+ @skipUnless(HAS_GDAL, "GDAL is required.")
+ def test_transform_noop(self):
+ """ Testing `transform` method (SRID match) """
+ # transform() should no-op if source & dest SRIDs match,
+ # regardless of whether GDAL is available.
+ if gdal.HAS_GDAL:
+ g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
+ gt = g.tuple
+ g.transform(4326)
+ self.assertEqual(g.tuple, gt)
+ self.assertEqual(g.srid, 4326)
+
+ g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
+ g1 = g.transform(4326, clone=True)
+ self.assertEqual(g1.tuple, g.tuple)
+ self.assertEqual(g1.srid, 4326)
+ self.assertTrue(g1 is not g, "Clone didn't happen")
+
+ old_has_gdal = gdal.HAS_GDAL
+ try:
+ gdal.HAS_GDAL = False
+
+ g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
+ gt = g.tuple
+ g.transform(4326)
+ self.assertEqual(g.tuple, gt)
+ self.assertEqual(g.srid, 4326)
+
+ g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
+ g1 = g.transform(4326, clone=True)
+ self.assertEqual(g1.tuple, g.tuple)
+ self.assertEqual(g1.srid, 4326)
+ self.assertTrue(g1 is not g, "Clone didn't happen")
+ finally:
+ gdal.HAS_GDAL = old_has_gdal
+
+ def test_transform_nosrid(self):
+ """ Testing `transform` method (no SRID or negative SRID) """
+
+ g = GEOSGeometry('POINT (-104.609 38.255)', srid=None)
+ self.assertRaises(GEOSException, g.transform, 2774)
+
+ g = GEOSGeometry('POINT (-104.609 38.255)', srid=None)
+ self.assertRaises(GEOSException, g.transform, 2774, clone=True)
+
+ g = GEOSGeometry('POINT (-104.609 38.255)', srid=-1)
+ self.assertRaises(GEOSException, g.transform, 2774)
+
+ g = GEOSGeometry('POINT (-104.609 38.255)', srid=-1)
+ self.assertRaises(GEOSException, g.transform, 2774, clone=True)
+
+ @skipUnless(HAS_GDAL, "GDAL is required.")
+ def test_transform_nogdal(self):
+ """ Testing `transform` method (GDAL not available) """
+ old_has_gdal = gdal.HAS_GDAL
+ try:
+ gdal.HAS_GDAL = False
+
+ g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
+ self.assertRaises(GEOSException, g.transform, 2774)
+
+ g = GEOSGeometry('POINT (-104.609 38.255)', 4326)
+ self.assertRaises(GEOSException, g.transform, 2774, clone=True)
+ finally:
+ gdal.HAS_GDAL = old_has_gdal
+
+ def test_extent(self):
+ "Testing `extent` method."
+ # The xmin, ymin, xmax, ymax of the MultiPoint should be returned.
+ mp = MultiPoint(Point(5, 23), Point(0, 0), Point(10, 50))
+ self.assertEqual((0.0, 0.0, 10.0, 50.0), mp.extent)
+ pnt = Point(5.23, 17.8)
+ # Extent of points is just the point itself repeated.
+ self.assertEqual((5.23, 17.8, 5.23, 17.8), pnt.extent)
+ # Testing on the 'real world' Polygon.
+ poly = fromstr(self.geometries.polygons[3].wkt)
+ ring = poly.shell
+ x, y = ring.x, ring.y
+ xmin, ymin = min(x), min(y)
+ xmax, ymax = max(x), max(y)
+ self.assertEqual((xmin, ymin, xmax, ymax), poly.extent)
+
+ def test_pickle(self):
+ "Testing pickling and unpickling support."
+ # Using both pickle and cPickle -- just 'cause.
+ from django.utils.six.moves import cPickle
+ import pickle
+
+ # Creating a list of test geometries for pickling,
+ # and setting the SRID on some of them.
+ def get_geoms(lst, srid=None):
+ return [GEOSGeometry(tg.wkt, srid) for tg in lst]
+ tgeoms = get_geoms(self.geometries.points)
+ tgeoms.extend(get_geoms(self.geometries.multilinestrings, 4326))
+ tgeoms.extend(get_geoms(self.geometries.polygons, 3084))
+ tgeoms.extend(get_geoms(self.geometries.multipolygons, 900913))
+
+ # The SRID won't be exported in GEOS 3.0 release candidates.
+ no_srid = self.null_srid == -1
+ for geom in tgeoms:
+ s1, s2 = cPickle.dumps(geom), pickle.dumps(geom)
+ g1, g2 = cPickle.loads(s1), pickle.loads(s2)
+ for tmpg in (g1, g2):
+ self.assertEqual(geom, tmpg)
+ if not no_srid: self.assertEqual(geom.srid, tmpg.srid)
+
+ @skipUnless(HAS_GEOS and GEOS_PREPARE, "geos >= 3.1.0 is required")
+ def test_prepared(self):
+ "Testing PreparedGeometry support."
+ # Creating a simple multipolygon and getting a prepared version.
+ mpoly = GEOSGeometry('MULTIPOLYGON(((0 0,0 5,5 5,5 0,0 0)),((5 5,5 10,10 10,10 5,5 5)))')
+ prep = mpoly.prepared
+
+ # A set of test points.
+ pnts = [Point(5, 5), Point(7.5, 7.5), Point(2.5, 7.5)]
+ covers = [True, True, False] # No `covers` op for regular GEOS geoms.
+ for pnt, c in zip(pnts, covers):
+ # Results should be the same (but faster)
+ self.assertEqual(mpoly.contains(pnt), prep.contains(pnt))
+ self.assertEqual(mpoly.intersects(pnt), prep.intersects(pnt))
+ self.assertEqual(c, prep.covers(pnt))
+
+ # Original geometry deletion should not crash the prepared one (#21662)
+ del mpoly
+ self.assertTrue(prep.covers(Point(5, 5)))
+
+ def test_line_merge(self):
+ "Testing line merge support"
+ ref_geoms = (fromstr('LINESTRING(1 1, 1 1, 3 3)'),
+ fromstr('MULTILINESTRING((1 1, 3 3), (3 3, 4 2))'),
+ )
+ ref_merged = (fromstr('LINESTRING(1 1, 3 3)'),
+ fromstr('LINESTRING (1 1, 3 3, 4 2)'),
+ )
+ for geom, merged in zip(ref_geoms, ref_merged):
+ self.assertEqual(merged, geom.merged)
+
+ @skipUnless(HAS_GEOS and GEOS_PREPARE, "geos >= 3.1.0 is required")
+ def test_valid_reason(self):
+ "Testing IsValidReason support"
+
+ g = GEOSGeometry("POINT(0 0)")
+ self.assertTrue(g.valid)
+ self.assertIsInstance(g.valid_reason, six.string_types)
+ self.assertEqual(g.valid_reason, "Valid Geometry")
+
+ g = GEOSGeometry("LINESTRING(0 0, 0 0)")
+
+ self.assertFalse(g.valid)
+ self.assertIsInstance(g.valid_reason, six.string_types)
+ self.assertTrue(g.valid_reason.startswith("Too few points in geometry component"))
+
+ @skipUnless(HAS_GEOS and geos_version_info()['version'] >= '3.2.0', "geos >= 3.2.0 is required")
+ def test_linearref(self):
+ "Testing linear referencing"
+
+ ls = fromstr('LINESTRING(0 0, 0 10, 10 10, 10 0)')
+ mls = fromstr('MULTILINESTRING((0 0, 0 10), (10 0, 10 10))')
+
+ self.assertEqual(ls.project(Point(0, 20)), 10.0)
+ self.assertEqual(ls.project(Point(7, 6)), 24)
+ self.assertEqual(ls.project_normalized(Point(0, 20)), 1.0/3)
+
+ self.assertEqual(ls.interpolate(10), Point(0, 10))
+ self.assertEqual(ls.interpolate(24), Point(10, 6))
+ self.assertEqual(ls.interpolate_normalized(1.0/3), Point(0, 10))
+
+ self.assertEqual(mls.project(Point(0, 20)), 10)
+ self.assertEqual(mls.project(Point(7, 6)), 16)
+
+ self.assertEqual(mls.interpolate(9), Point(0, 9))
+ self.assertEqual(mls.interpolate(17), Point(10, 7))
+
+ def test_geos_version(self):
+ """Testing the GEOS version regular expression."""
+ from django.contrib.gis.geos.libgeos import version_regex
+ versions = [('3.0.0rc4-CAPI-1.3.3', '3.0.0', '1.3.3'),
+ ('3.0.0-CAPI-1.4.1', '3.0.0', '1.4.1'),
+ ('3.4.0dev-CAPI-1.8.0', '3.4.0', '1.8.0'),
+ ('3.4.0dev-CAPI-1.8.0 r0', '3.4.0', '1.8.0')]
+ for v_init, v_geos, v_capi in versions:
+ m = version_regex.match(v_init)
+ self.assertTrue(m, msg="Unable to parse the version string '%s'" % v_init)
+ self.assertEqual(m.group('version'), v_geos)
+ self.assertEqual(m.group('capi_version'), v_capi)
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/tests/test_geos_mutation.py b/lib/python2.7/site-packages/django/contrib/gis/geos/tests/test_geos_mutation.py
new file mode 100644
index 0000000..40b708a
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/tests/test_geos_mutation.py
@@ -0,0 +1,134 @@
+# Copyright (c) 2008-2009 Aryeh Leib Taurog, all rights reserved.
+# Modified from original contribution by Aryeh Leib Taurog, which was
+# released under the New BSD license.
+
+from django.utils import unittest
+from django.utils.unittest import skipUnless
+
+from .. import HAS_GEOS
+
+if HAS_GEOS:
+ from .. import *
+ from ..error import GEOSIndexError
+
+
+def getItem(o,i): return o[i]
+def delItem(o,i): del o[i]
+def setItem(o,i,v): o[i] = v
+
+if HAS_GEOS:
+ def api_get_distance(x): return x.distance(Point(-200,-200))
+
+def api_get_buffer(x): return x.buffer(10)
+def api_get_geom_typeid(x): return x.geom_typeid
+def api_get_num_coords(x): return x.num_coords
+def api_get_centroid(x): return x.centroid
+def api_get_empty(x): return x.empty
+def api_get_valid(x): return x.valid
+def api_get_simple(x): return x.simple
+def api_get_ring(x): return x.ring
+def api_get_boundary(x): return x.boundary
+def api_get_convex_hull(x): return x.convex_hull
+def api_get_extent(x): return x.extent
+def api_get_area(x): return x.area
+def api_get_length(x): return x.length
+
+geos_function_tests = [ val for name, val in vars().items()
+ if hasattr(val, '__call__')
+ and name.startswith('api_get_') ]
+
+
+@skipUnless(HAS_GEOS, "Geos is required.")
+class GEOSMutationTest(unittest.TestCase):
+ """
+ Tests Pythonic Mutability of Python GEOS geometry wrappers
+ get/set/delitem on a slice, normal list methods
+ """
+
+ def test00_GEOSIndexException(self):
+ 'Testing Geometry GEOSIndexError'
+ p = Point(1,2)
+ for i in range(-2,2): p._checkindex(i)
+ self.assertRaises(GEOSIndexError, p._checkindex, 2)
+ self.assertRaises(GEOSIndexError, p._checkindex, -3)
+
+ def test01_PointMutations(self):
+ 'Testing Point mutations'
+ for p in (Point(1,2,3), fromstr('POINT (1 2 3)')):
+ self.assertEqual(p._get_single_external(1), 2.0, 'Point _get_single_external')
+
+ # _set_single
+ p._set_single(0,100)
+ self.assertEqual(p.coords, (100.0,2.0,3.0), 'Point _set_single')
+
+ # _set_list
+ p._set_list(2,(50,3141))
+ self.assertEqual(p.coords, (50.0,3141.0), 'Point _set_list')
+
+ def test02_PointExceptions(self):
+ 'Testing Point exceptions'
+ self.assertRaises(TypeError, Point, range(1))
+ self.assertRaises(TypeError, Point, range(4))
+
+ def test03_PointApi(self):
+ 'Testing Point API'
+ q = Point(4,5,3)
+ for p in (Point(1,2,3), fromstr('POINT (1 2 3)')):
+ p[0:2] = [4,5]
+ for f in geos_function_tests:
+ self.assertEqual(f(q), f(p), 'Point ' + f.__name__)
+
+ def test04_LineStringMutations(self):
+ 'Testing LineString mutations'
+ for ls in (LineString((1,0),(4,1),(6,-1)),
+ fromstr('LINESTRING (1 0,4 1,6 -1)')):
+ self.assertEqual(ls._get_single_external(1), (4.0,1.0), 'LineString _get_single_external')
+
+ # _set_single
+ ls._set_single(0,(-50,25))
+ self.assertEqual(ls.coords, ((-50.0,25.0),(4.0,1.0),(6.0,-1.0)), 'LineString _set_single')
+
+ # _set_list
+ ls._set_list(2, ((-50.0,25.0),(6.0,-1.0)))
+ self.assertEqual(ls.coords, ((-50.0,25.0),(6.0,-1.0)), 'LineString _set_list')
+
+ lsa = LineString(ls.coords)
+ for f in geos_function_tests:
+ self.assertEqual(f(lsa), f(ls), 'LineString ' + f.__name__)
+
+ def test05_Polygon(self):
+ 'Testing Polygon mutations'
+ for pg in (Polygon(((1,0),(4,1),(6,-1),(8,10),(1,0)),
+ ((5,4),(6,4),(6,3),(5,4))),
+ fromstr('POLYGON ((1 0,4 1,6 -1,8 10,1 0),(5 4,6 4,6 3,5 4))')):
+ self.assertEqual(pg._get_single_external(0),
+ LinearRing((1,0),(4,1),(6,-1),(8,10),(1,0)),
+ 'Polygon _get_single_external(0)')
+ self.assertEqual(pg._get_single_external(1),
+ LinearRing((5,4),(6,4),(6,3),(5,4)),
+ 'Polygon _get_single_external(1)')
+
+ # _set_list
+ pg._set_list(2, (((1,2),(10,0),(12,9),(-1,15),(1,2)),
+ ((4,2),(5,2),(5,3),(4,2))))
+ self.assertEqual(pg.coords,
+ (((1.0,2.0),(10.0,0.0),(12.0,9.0),(-1.0,15.0),(1.0,2.0)),
+ ((4.0,2.0),(5.0,2.0),(5.0,3.0),(4.0,2.0))),
+ 'Polygon _set_list')
+
+ lsa = Polygon(*pg.coords)
+ for f in geos_function_tests:
+ self.assertEqual(f(lsa), f(pg), 'Polygon ' + f.__name__)
+
+ def test06_Collection(self):
+ 'Testing Collection mutations'
+ for mp in (MultiPoint(*map(Point,((3,4),(-1,2),(5,-4),(2,8)))),
+ fromstr('MULTIPOINT (3 4,-1 2,5 -4,2 8)')):
+ self.assertEqual(mp._get_single_external(2), Point(5,-4), 'Collection _get_single_external')
+
+ mp._set_list(3, map(Point,((5,5),(3,-2),(8,1))))
+ self.assertEqual(mp.coords, ((5.0,5.0),(3.0,-2.0),(8.0,1.0)), 'Collection _set_list')
+
+ lsa = MultiPoint(*map(Point,((5,5),(3,-2),(8,1))))
+ for f in geos_function_tests:
+ self.assertEqual(f(lsa), f(mp), 'MultiPoint ' + f.__name__)
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/tests/test_io.py b/lib/python2.7/site-packages/django/contrib/gis/geos/tests/test_io.py
new file mode 100644
index 0000000..34eeaf9
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/tests/test_io.py
@@ -0,0 +1,116 @@
+from __future__ import unicode_literals
+
+import binascii
+import unittest
+
+from django.contrib.gis import memoryview
+from django.utils.unittest import skipUnless
+
+from ..import HAS_GEOS
+
+if HAS_GEOS:
+ from .. import GEOSGeometry, WKTReader, WKTWriter, WKBReader, WKBWriter, geos_version_info
+
+
+@skipUnless(HAS_GEOS, "Geos is required.")
+class GEOSIOTest(unittest.TestCase):
+
+ def test01_wktreader(self):
+ # Creating a WKTReader instance
+ wkt_r = WKTReader()
+ wkt = 'POINT (5 23)'
+
+ # read() should return a GEOSGeometry
+ ref = GEOSGeometry(wkt)
+ g1 = wkt_r.read(wkt.encode())
+ g2 = wkt_r.read(wkt)
+
+ for geom in (g1, g2):
+ self.assertEqual(ref, geom)
+
+ # Should only accept six.string_types objects.
+ self.assertRaises(TypeError, wkt_r.read, 1)
+ self.assertRaises(TypeError, wkt_r.read, memoryview(b'foo'))
+
+ def test02_wktwriter(self):
+ # Creating a WKTWriter instance, testing its ptr property.
+ wkt_w = WKTWriter()
+ self.assertRaises(TypeError, wkt_w._set_ptr, WKTReader.ptr_type())
+
+ ref = GEOSGeometry('POINT (5 23)')
+ ref_wkt = 'POINT (5.0000000000000000 23.0000000000000000)'
+ self.assertEqual(ref_wkt, wkt_w.write(ref).decode())
+
+ def test03_wkbreader(self):
+ # Creating a WKBReader instance
+ wkb_r = WKBReader()
+
+ hex = b'000000000140140000000000004037000000000000'
+ wkb = memoryview(binascii.a2b_hex(hex))
+ ref = GEOSGeometry(hex)
+
+ # read() should return a GEOSGeometry on either a hex string or
+ # a WKB buffer.
+ g1 = wkb_r.read(wkb)
+ g2 = wkb_r.read(hex)
+ for geom in (g1, g2):
+ self.assertEqual(ref, geom)
+
+ bad_input = (1, 5.23, None, False)
+ for bad_wkb in bad_input:
+ self.assertRaises(TypeError, wkb_r.read, bad_wkb)
+
+ def test04_wkbwriter(self):
+ wkb_w = WKBWriter()
+
+ # Representations of 'POINT (5 23)' in hex -- one normal and
+ # the other with the byte order changed.
+ g = GEOSGeometry('POINT (5 23)')
+ hex1 = b'010100000000000000000014400000000000003740'
+ wkb1 = memoryview(binascii.a2b_hex(hex1))
+ hex2 = b'000000000140140000000000004037000000000000'
+ wkb2 = memoryview(binascii.a2b_hex(hex2))
+
+ self.assertEqual(hex1, wkb_w.write_hex(g))
+ self.assertEqual(wkb1, wkb_w.write(g))
+
+ # Ensuring bad byteorders are not accepted.
+ for bad_byteorder in (-1, 2, 523, 'foo', None):
+ # Equivalent of `wkb_w.byteorder = bad_byteorder`
+ self.assertRaises(ValueError, wkb_w._set_byteorder, bad_byteorder)
+
+ # Setting the byteorder to 0 (for Big Endian)
+ wkb_w.byteorder = 0
+ self.assertEqual(hex2, wkb_w.write_hex(g))
+ self.assertEqual(wkb2, wkb_w.write(g))
+
+ # Back to Little Endian
+ wkb_w.byteorder = 1
+
+ # Now, trying out the 3D and SRID flags.
+ g = GEOSGeometry('POINT (5 23 17)')
+ g.srid = 4326
+
+ hex3d = b'0101000080000000000000144000000000000037400000000000003140'
+ wkb3d = memoryview(binascii.a2b_hex(hex3d))
+ hex3d_srid = b'01010000A0E6100000000000000000144000000000000037400000000000003140'
+ wkb3d_srid = memoryview(binascii.a2b_hex(hex3d_srid))
+
+ # Ensuring bad output dimensions are not accepted
+ for bad_outdim in (-1, 0, 1, 4, 423, 'foo', None):
+ # Equivalent of `wkb_w.outdim = bad_outdim`
+ self.assertRaises(ValueError, wkb_w._set_outdim, bad_outdim)
+
+ # These tests will fail on 3.0.0 because of a bug that was fixed in 3.1:
+ # http://trac.osgeo.org/geos/ticket/216
+ if not geos_version_info()['version'].startswith('3.0.'):
+ # Now setting the output dimensions to be 3
+ wkb_w.outdim = 3
+
+ self.assertEqual(hex3d, wkb_w.write_hex(g))
+ self.assertEqual(wkb3d, wkb_w.write(g))
+
+ # Telling the WKBWriter to include the srid in the representation.
+ wkb_w.srid = True
+ self.assertEqual(hex3d_srid, wkb_w.write_hex(g))
+ self.assertEqual(wkb3d_srid, wkb_w.write(g))
diff --git a/lib/python2.7/site-packages/django/contrib/gis/geos/tests/test_mutable_list.py b/lib/python2.7/site-packages/django/contrib/gis/geos/tests/test_mutable_list.py
new file mode 100644
index 0000000..a4a56f2
--- /dev/null
+++ b/lib/python2.7/site-packages/django/contrib/gis/geos/tests/test_mutable_list.py
@@ -0,0 +1,397 @@
+# Copyright (c) 2008-2009 Aryeh Leib Taurog, http://www.aryehleib.com
+# All rights reserved.
+#
+# Modified from original contribution by Aryeh Leib Taurog, which was
+# released under the New BSD license.
+from django.contrib.gis.geos.mutable_list import ListMixin
+from django.utils import six
+from django.utils import unittest
+
+
+class UserListA(ListMixin):
+ _mytype = tuple
+ def __init__(self, i_list, *args, **kwargs):
+ self._list = self._mytype(i_list)
+ super(UserListA, self).__init__(*args, **kwargs)
+
+ def __len__(self): return len(self._list)
+
+ def __str__(self): return str(self._list)
+
+ def __repr__(self): return repr(self._list)
+
+ def _set_list(self, length, items):
+ # this would work:
+ # self._list = self._mytype(items)
+ # but then we wouldn't be testing length parameter
+ itemList = ['x'] * length
+ for i, v in enumerate(items):
+ itemList[i] = v
+
+ self._list = self._mytype(itemList)
+
+ def _get_single_external(self, index):
+ return self._list[index]
+
+class UserListB(UserListA):
+ _mytype = list
+
+ def _set_single(self, index, value):
+ self._list[index] = value
+
+def nextRange(length):
+ nextRange.start += 100
+ return range(nextRange.start, nextRange.start + length)
+
+nextRange.start = 0
+
+class ListMixinTest(unittest.TestCase):
+ """
+ Tests base class ListMixin by comparing a list clone which is
+ a ListMixin subclass with a real Python list.
+ """
+ limit = 3
+ listType = UserListA
+
+ def lists_of_len(self, length=None):
+ if length is None: length = self.limit
+ pl = list(range(length))
+ return pl, self.listType(pl)
+
+ def limits_plus(self, b):
+ return range(-self.limit - b, self.limit + b)
+
+ def step_range(self):
+ return list(range(-1 - self.limit, 0)) + list(range(1, 1 + self.limit))
+
+ def test01_getslice(self):
+ 'Slice retrieval'
+ pl, ul = self.lists_of_len()
+ for i in self.limits_plus(1):
+ self.assertEqual(pl[i:], ul[i:], 'slice [%d:]' % (i))
+ self.assertEqual(pl[:i], ul[:i], 'slice [:%d]' % (i))
+
+ for j in self.limits_plus(1):
+ self.assertEqual(pl[i:j], ul[i:j], 'slice [%d:%d]' % (i,j))
+ for k in self.step_range():
+ self.assertEqual(pl[i:j:k], ul[i:j:k], 'slice [%d:%d:%d]' % (i,j,k))
+
+ for k in self.step_range():
+ self.assertEqual(pl[i::k], ul[i::k], 'slice [%d::%d]' % (i,k))
+ self.assertEqual(pl[:i:k], ul[:i:k], 'slice [:%d:%d]' % (i,k))
+
+ for k in self.step_range():
+ self.assertEqual(pl[::k], ul[::k], 'slice [::%d]' % (k))
+
+ def test02_setslice(self):
+ 'Slice assignment'
+ def setfcn(x,i,j,k,L): x[i:j:k] = range(L)
+ pl, ul = self.lists_of_len()
+ for slen in range(self.limit + 1):
+ ssl = nextRange(slen)
+ ul[:] = ssl
+ pl[:] = ssl
+ self.assertEqual(pl, ul[:], 'set slice [:]')
+
+ for i in self.limits_plus(1):
+ ssl = nextRange(slen)
+ ul[i:] = ssl
+ pl[i:] = ssl
+ self.assertEqual(pl, ul[:], 'set slice [%d:]' % (i))
+
+ ssl = nextRange(slen)
+ ul[:i] = ssl
+ pl[:i] = ssl
+ self.assertEqual(pl, ul[:], 'set slice [:%d]' % (i))
+
+ for j in self.limits_plus(1):
+ ssl = nextRange(slen)
+ ul[i:j] = ssl
+ pl[i:j] = ssl
+ self.assertEqual(pl, ul[:], 'set slice [%d:%d]' % (i, j))
+
+ for k in self.step_range():
+ ssl = nextRange( len(ul[i:j:k]) )
+ ul[i:j:k] = ssl
+ pl[i:j:k] = ssl
+ self.assertEqual(pl, ul[:], 'set slice [%d:%d:%d]' % (i, j, k))
+
+ sliceLen = len(ul[i:j:k])
+ self.assertRaises(ValueError, setfcn, ul, i, j, k, sliceLen + 1)
+ if sliceLen > 2:
+ self.assertRaises(ValueError, setfcn, ul, i, j, k, sliceLen - 1)
+
+ for k in self.step_range():
+ ssl = nextRange( len(ul[i::k]) )
+ ul[i::k] = ssl
+ pl[i::k] = ssl
+ self.assertEqual(pl, ul[:], 'set slice [%d::%d]' % (i, k))
+
+ ssl = nextRange( len(ul[:i:k]) )
+ ul[:i:k] = ssl
+ pl[:i:k] = ssl
+ self.assertEqual(pl, ul[:], 'set slice [:%d:%d]' % (i, k))
+
+ for k in self.step_range():
+ ssl = nextRange(len(ul[::k]))
+ ul[::k] = ssl
+ pl[::k] = ssl
+ self.assertEqual(pl, ul[:], 'set slice [::%d]' % (k))
+
+
+ def test03_delslice(self):
+ 'Delete slice'
+ for Len in range(self.limit):
+ pl, ul = self.lists_of_len(Len)
+ del pl[:]
+ del ul[:]
+ self.assertEqual(pl[:], ul[:], 'del slice [:]')
+ for i in range(-Len - 1, Len + 1):
+ pl, ul = self.lists_of_len(Len)
+ del pl[i:]
+ del ul[i:]
+ self.assertEqual(pl[:], ul[:], 'del slice [%d:]' % (i))
+ pl, ul = self.lists_of_len(Len)
+ del pl[:i]
+ del ul[:i]
+ self.assertEqual(pl[:], ul[:], 'del slice [:%d]' % (i))
+ for j in range(-Len - 1, Len + 1):
+ pl, ul = self.lists_of_len(Len)
+ del pl[i:j]
+ del ul[i:j]
+ self.assertEqual(pl[:], ul[:], 'del slice [%d:%d]' % (i,j))
+ for k in list(range(-Len - 1, 0)) + list(range(1, Len)):
+ pl, ul = self.lists_of_len(Len)
+ del pl[i:j:k]
+ del ul[i:j:k]
+ self.assertEqual(pl[:], ul[:], 'del slice [%d:%d:%d]' % (i,j,k))
+
+ for k in list(range(-Len - 1, 0)) + list(range(1, Len)):
+ pl, ul = self.lists_of_len(Len)
+ del pl[:i:k]
+ del ul[:i:k]
+ self.assertEqual(pl[:], ul[:], 'del slice [:%d:%d]' % (i,k))
+
+ pl, ul = self.lists_of_len(Len)
+ del pl[i::k]
+ del ul[i::k]
+ self.assertEqual(pl[:], ul[:], 'del slice [%d::%d]' % (i,k))
+
+ for k in list(range(-Len - 1, 0)) + list(range(1, Len)):
+ pl, ul = self.lists_of_len(Len)
+ del pl[::k]
+ del ul[::k]
+ self.assertEqual(pl[:], ul[:], 'del slice [::%d]' % (k))
+
+ def test04_get_set_del_single(self):
+ 'Get/set/delete single item'
+ pl, ul = self.lists_of_len()
+ for i in self.limits_plus(0):
+ self.assertEqual(pl[i], ul[i], 'get single item [%d]' % i)
+
+ for i in self.limits_plus(0):
+ pl, ul = self.lists_of_len()
+ pl[i] = 100
+ ul[i] = 100
+ self.assertEqual(pl[:], ul[:], 'set single item [%d]' % i)
+
+ for i in self.limits_plus(0):
+ pl, ul = self.lists_of_len()
+ del pl[i]
+ del ul[i]
+ self.assertEqual(pl[:], ul[:], 'del single item [%d]' % i)
+
+ def test05_out_of_range_exceptions(self):
+ 'Out of range exceptions'
+ def setfcn(x, i): x[i] = 20
+ def getfcn(x, i): return x[i]
+ def delfcn(x, i): del x[i]
+ pl, ul = self.lists_of_len()
+ for i in (-1 - self.limit, self.limit):
+ self.assertRaises(IndexError, setfcn, ul, i) # 'set index %d' % i)
+ self.assertRaises(IndexError, getfcn, ul, i) # 'get index %d' % i)
+ self.assertRaises(IndexError, delfcn, ul, i) # 'del index %d' % i)
+
+ def test06_list_methods(self):
+ 'List methods'
+ pl, ul = self.lists_of_len()
+ pl.append(40)
+ ul.append(40)
+ self.assertEqual(pl[:], ul[:], 'append')
+
+ pl.extend(range(50,55))
+ ul.extend(range(50,55))
+ self.assertEqual(pl[:], ul[:], 'extend')
+
+ pl.reverse()
+ ul.reverse()
+ self.assertEqual(pl[:], ul[:], 'reverse')
+
+ for i in self.limits_plus(1):
+ pl, ul = self.lists_of_len()
+ pl.insert(i,50)
+ ul.insert(i,50)
+ self.assertEqual(pl[:], ul[:], 'insert at %d' % i)
+
+ for i in self.limits_plus(0):
+ pl, ul = self.lists_of_len()
+ self.assertEqual(pl.pop(i), ul.pop(i), 'popped value at %d' % i)
+ self.assertEqual(pl[:], ul[:], 'after pop at %d' % i)
+
+ pl, ul = self.lists_of_len()
+ self.assertEqual(pl.pop(), ul.pop(i), 'popped value')
+ self.assertEqual(pl[:], ul[:], 'after pop')
+
+ pl, ul = self.lists_of_len()
+ def popfcn(x, i): x.pop(i)
+ self.assertRaises(IndexError, popfcn, ul, self.limit)
+ self.assertRaises(IndexError, popfcn, ul, -1 - self.limit)
+
+ pl, ul = self.lists_of_len()
+ for val in range(self.limit):
+ self.assertEqual(pl.index(val), ul.index(val), 'index of %d' % val)
+
+ for val in self.limits_plus(2):
+ self.assertEqual(pl.count(val), ul.count(val), 'count %d' % val)
+
+ for val in range(self.limit):
+ pl, ul = self.lists_of_len()
+ pl.remove(val)
+ ul.remove(val)
+ self.assertEqual(pl[:], ul[:], 'after remove val %d' % val)
+
+ def indexfcn(x, v): return x.index(v)
+ def removefcn(x, v): return x.remove(v)
+ self.assertRaises(ValueError, indexfcn, ul, 40)
+ self.assertRaises(ValueError, removefcn, ul, 40)
+
+ def test07_allowed_types(self):
+ 'Type-restricted list'
+ pl, ul = self.lists_of_len()
+ ul._allowed = six.integer_types
+ ul[1] = 50
+ ul[:2] = [60, 70, 80]
+ def setfcn(x, i, v): x[i] = v
+ self.assertRaises(TypeError, setfcn, ul, 2, 'hello')
+ self.assertRaises(TypeError, setfcn, ul, slice(0,3,2), ('hello','goodbye'))
+
+ def test08_min_length(self):
+ 'Length limits'
+ pl, ul = self.lists_of_len()
+ ul._minlength = 1
+ def delfcn(x,i): del x[:i]
+ def setfcn(x,i): x[:i] = []
+ for i in range(self.limit - ul._minlength + 1, self.limit + 1):
+ self.assertRaises(ValueError, delfcn, ul, i)
+ self.assertRaises(ValueError, setfcn, ul, i)
+ del ul[:ul._minlength]
+
+ ul._maxlength = 4
+ for i in range(0, ul._maxlength - len(ul)):
+ ul.append(i)
+ self.assertRaises(ValueError, ul.append, 10)
+
+ def test09_iterable_check(self):
+ 'Error on assigning non-iterable to slice'
+ pl, ul = self.lists_of_len(self.limit + 1)
+ def setfcn(x, i, v): x[i] = v
+ self.assertRaises(TypeError, setfcn, ul, slice(0,3,2), 2)
+
+ def test10_checkindex(self):
+ 'Index check'
+ pl, ul = self.lists_of_len()
+ for i in self.limits_plus(0):
+ if i < 0:
+ self.assertEqual(ul._checkindex(i), i + self.limit, '_checkindex(neg index)')
+ else:
+ self.assertEqual(ul._checkindex(i), i, '_checkindex(pos index)')
+
+ for i in (-self.limit - 1, self.limit):
+ self.assertRaises(IndexError, ul._checkindex, i)
+
+ ul._IndexError = TypeError
+ self.assertRaises(TypeError, ul._checkindex, -self.limit - 1)
+
+ def test_11_sorting(self):
+ 'Sorting'
+ pl, ul = self.lists_of_len()
+ pl.insert(0, pl.pop())
+ ul.insert(0, ul.pop())
+ pl.sort()
+ ul.sort()
+ self.assertEqual(pl[:], ul[:], 'sort')
+ mid = pl[len(pl) // 2]
+ pl.sort(key=lambda x: (mid-x)**2)
+ ul.sort(key=lambda x: (mid-x)**2)
+ self.assertEqual(pl[:], ul[:], 'sort w/ key')
+
+ pl.insert(0, pl.pop())
+ ul.insert(0, ul.pop())
+ pl.sort(reverse=True)
+ ul.sort(reverse=True)
+ self.assertEqual(pl[:], ul[:], 'sort w/ reverse')
+ mid = pl[len(pl) // 2]
+ pl.sort(key=lambda x: (mid-x)**2)
+ ul.sort(key=lambda x: (mid-x)**2)
+ self.assertEqual(pl[:], ul[:], 'sort w/ key')
+
+ def test_12_arithmetic(self):
+ 'Arithmetic'
+ pl, ul = self.lists_of_len()
+ al = list(range(10,14))
+ self.assertEqual(list(pl + al), list(ul + al), 'add')
+ self.assertEqual(type(ul), type(ul + al), 'type of add result')
+ self.assertEqual(list(al + pl), list(al + ul), 'radd')
+ self.assertEqual(type(al), type(al + ul), 'type of radd result')
+ objid = id(ul)
+ pl += al
+ ul += al
+ self.assertEqual(pl[:], ul[:], 'in-place add')
+ self.assertEqual(objid, id(ul), 'in-place add id')
+
+ for n in (-1,0,1,3):
+ pl, ul = self.lists_of_len()
+ self.assertEqual(list(pl * n), list(ul * n), 'mul by %d' % n)
+ self.assertEqual(type(ul), type(ul * n), 'type of mul by %d result' % n)
+ self.assertEqual(list(n * pl), list(n * ul), 'rmul by %d' % n)
+ self.assertEqual(type(ul), type(n * ul), 'type of rmul by %d result' % n)
+ objid = id(ul)
+ pl *= n
+ ul *= n
+ self.assertEqual(pl[:], ul[:], 'in-place mul by %d' % n)
+ self.assertEqual(objid, id(ul), 'in-place mul by %d id' % n)
+
+ pl, ul = self.lists_of_len()
+ self.assertEqual(pl, ul, 'cmp for equal')
+ self.assertFalse(ul == pl + [2], 'cmp for not equal')
+ self.assertTrue(pl >= ul, 'cmp for gte self')
+ self.assertTrue(pl <= ul, 'cmp for lte self')
+ self.assertTrue(ul >= pl, 'cmp for self gte')
+ self.assertTrue(ul <= pl, 'cmp for self lte')
+
+ self.assertTrue(pl + [5] > ul, 'cmp')
+ self.assertTrue(pl + [5] >= ul, 'cmp')
+ self.assertTrue(pl < ul + [2], 'cmp')
+ self.assertTrue(pl <= ul + [2], 'cmp')
+ self.assertTrue(ul + [5] > pl, 'cmp')
+ self.assertTrue(ul + [5] >= pl, 'cmp')
+ self.assertTrue(ul < pl + [2], 'cmp')
+ self.assertTrue(ul <= pl + [2], 'cmp')
+
+ # Also works with a custom IndexError
+ ul_longer = ul + [2]
+ ul_longer._IndexError = TypeError
+ ul._IndexError = TypeError
+ self.assertFalse(ul_longer == pl)
+ self.assertFalse(ul == ul_longer)
+ self.assertTrue(ul_longer > ul)
+
+ pl[1] = 20
+ self.assertTrue(pl > ul, 'cmp for gt self')
+ self.assertTrue(ul < pl, 'cmp for self lt')
+ pl[1] = -20
+ self.assertTrue(pl < ul, 'cmp for lt self')
+ self.assertTrue(pl < ul, 'cmp for lt self')
+
+class ListMixinTestSingle(ListMixinTest):
+ listType = UserListB