django/contrib/gis/geos/collections.py
author Justin Bronn <jbronn@geodjango.org>
Thu Mar 19 13:08:50 2009 -0500 (3 years ago)
branchtrunk
changeset 362 87b34dce202d
parent 360 fd85d0fb4fb5
child 435 d75ff359e306
permissions -rw-r--r--
Added `merged` property to LineString & MultiLineString, which returns the output of the GEOS line merging operation.
     1 """
     2  This module houses the Geometry Collection objects:
     3  GeometryCollection, MultiPoint, MultiLineString, and MultiPolygon
     4 """
     5 from ctypes import c_int, c_uint, byref
     6 from django.contrib.gis.geos.error import GEOSException, GEOSIndexError
     7 from django.contrib.gis.geos.geometry import GEOSGeometry
     8 from django.contrib.gis.geos.libgeos import get_pointer_arr, GEOM_PTR, GEOS_PREPARE
     9 from django.contrib.gis.geos.linestring import LineString, LinearRing
    10 from django.contrib.gis.geos.point import Point
    11 from django.contrib.gis.geos.polygon import Polygon
    12 from django.contrib.gis.geos import prototypes as capi
    13 
    14 class GeometryCollection(GEOSGeometry):
    15     _typeid = 7
    16     _minlength = 1
    17 
    18     def __init__(self, *args, **kwargs):
    19         "Initializes a Geometry Collection from a sequence of Geometry objects."
    20 
    21         # Checking the arguments
    22         if not args:
    23             raise TypeError, 'Must provide at least one Geometry to initialize %s.' % self.__class__.__name__
    24 
    25         if len(args) == 1:
    26             # If only one geometry provided or a list of geometries is provided
    27             #  in the first argument.
    28             if isinstance(args[0], (tuple, list)):
    29                 init_geoms = args[0]
    30             else:
    31                 init_geoms = args
    32         else:
    33             init_geoms = args
    34 
    35         # Ensuring that only the permitted geometries are allowed in this collection
    36         # this is moved to list mixin super class
    37         self._check_allowed(init_geoms)
    38 
    39         # Creating the geometry pointer array.
    40         collection = self._create_collection(len(init_geoms), iter(init_geoms))
    41         super(GeometryCollection, self).__init__(collection, **kwargs)
    42 
    43     def __iter__(self):
    44         "Iterates over each Geometry in the Collection."
    45         for i in xrange(len(self)):
    46             yield self[i]
    47 
    48     def __len__(self):
    49         "Returns the number of geometries in this Collection."
    50         return self.num_geom
    51 
    52     ### Methods for compatibility with ListMixin ###
    53     @classmethod
    54     def _create_collection(cls, length, items):
    55         # Creating the geometry pointer array.
    56         geoms = get_pointer_arr(length)
    57         for i, g in enumerate(items):
    58             # this is a little sloppy, but makes life easier
    59             # allow GEOSGeometry types (python wrappers) or pointer types
    60             geoms[i] = capi.geom_clone(getattr(g, 'ptr', g))
    61 
    62         return capi.create_collection(c_int(cls._typeid), byref(geoms), c_uint(length))
    63 
    64     def _getitem_internal(self, index):
    65         return capi.get_geomn(self.ptr, index)
    66 
    67     def _getitem_external(self, index):
    68         "Returns the Geometry from this Collection at the given index (0-based)."
    69         # Checking the index and returning the corresponding GEOS geometry.
    70         return GEOSGeometry(capi.geom_clone(self._getitem_internal(index)), srid=self.srid)
    71 
    72     def _set_collection(self, length, items):
    73         "Create a new collection, and destroy the contents of the previous pointer."
    74         prev_ptr = self.ptr
    75         srid = self.srid
    76         self.ptr = self._create_collection(length, items)
    77         if srid: self.srid = srid
    78         capi.destroy_geom(prev_ptr)
    79 
    80     # Because GeometryCollections need to be rebuilt upon the changing of a
    81     # component geometry, these routines are set to their counterparts that
    82     # rebuild the entire geometry.
    83     _set_single = GEOSGeometry._set_single_rebuild
    84     _assign_extended_slice = GEOSGeometry._assign_extended_slice_rebuild
    85 
    86     @property
    87     def kml(self):
    88         "Returns the KML for this Geometry Collection."
    89         return '<MultiGeometry>%s</MultiGeometry>' % ''.join([g.kml for g in self])
    90 
    91     @property
    92     def tuple(self):
    93         "Returns a tuple of all the coordinates in this Geometry Collection"
    94         return tuple([g.tuple for g in self])
    95     coords = tuple
    96 
    97 # MultiPoint, MultiLineString, and MultiPolygon class definitions.
    98 class MultiPoint(GeometryCollection):
    99     _allowed = Point
   100     _typeid = 4
   101 
   102 class MultiLineString(GeometryCollection):
   103     _allowed = (LineString, LinearRing)
   104     _typeid = 5
   105 
   106     @property
   107     def merged(self):
   108         """ 
   109         Returns a LineString representing the line merge of this 
   110         MultiLineString.
   111         """ 
   112         return self._topology(capi.geos_linemerge(self.ptr))         
   113 
   114 class MultiPolygon(GeometryCollection):
   115     _allowed = Polygon
   116     _typeid = 6
   117 
   118     @property
   119     def cascaded_union(self):
   120         "Returns a cascaded union of this MultiPolygon."
   121         if GEOS_PREPARE:
   122             return GEOSGeometry(capi.geos_cascaded_union(self.ptr), self.srid)
   123         else:
   124             raise GEOSException('The cascaded union operation requires GEOS 3.1+.')
   125 
   126 # Setting the allowed types here since GeometryCollection is defined before
   127 # its subclasses.
   128 GeometryCollection._allowed = (Point, LineString, LinearRing, Polygon, MultiPoint, MultiLineString, MultiPolygon)