PageRenderTime 45ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/django/contrib/gis/geos/linestring.py

https://code.google.com/p/mango-py/
Python | 152 lines | 99 code | 24 blank | 29 comment | 26 complexity | 59d631ccb59b717bedb326e44263ae5b MD5 | raw file
Possible License(s): BSD-3-Clause
  1. from django.contrib.gis.geos.base import numpy
  2. from django.contrib.gis.geos.coordseq import GEOSCoordSeq
  3. from django.contrib.gis.geos.error import GEOSException
  4. from django.contrib.gis.geos.geometry import GEOSGeometry
  5. from django.contrib.gis.geos.point import Point
  6. from django.contrib.gis.geos import prototypes as capi
  7. class LineString(GEOSGeometry):
  8. _init_func = capi.create_linestring
  9. _minlength = 2
  10. #### Python 'magic' routines ####
  11. def __init__(self, *args, **kwargs):
  12. """
  13. Initializes on the given sequence -- may take lists, tuples, NumPy arrays
  14. of X,Y pairs, or Point objects. If Point objects are used, ownership is
  15. _not_ transferred to the LineString object.
  16. Examples:
  17. ls = LineString((1, 1), (2, 2))
  18. ls = LineString([(1, 1), (2, 2)])
  19. ls = LineString(array([(1, 1), (2, 2)]))
  20. ls = LineString(Point(1, 1), Point(2, 2))
  21. """
  22. # If only one argument provided, set the coords array appropriately
  23. if len(args) == 1: coords = args[0]
  24. else: coords = args
  25. if isinstance(coords, (tuple, list)):
  26. # Getting the number of coords and the number of dimensions -- which
  27. # must stay the same, e.g., no LineString((1, 2), (1, 2, 3)).
  28. ncoords = len(coords)
  29. if coords: ndim = len(coords[0])
  30. else: raise TypeError('Cannot initialize on empty sequence.')
  31. self._checkdim(ndim)
  32. # Incrementing through each of the coordinates and verifying
  33. for i in xrange(1, ncoords):
  34. if not isinstance(coords[i], (tuple, list, Point)):
  35. raise TypeError('each coordinate should be a sequence (list or tuple)')
  36. if len(coords[i]) != ndim: raise TypeError('Dimension mismatch.')
  37. numpy_coords = False
  38. elif numpy and isinstance(coords, numpy.ndarray):
  39. shape = coords.shape # Using numpy's shape.
  40. if len(shape) != 2: raise TypeError('Too many dimensions.')
  41. self._checkdim(shape[1])
  42. ncoords = shape[0]
  43. ndim = shape[1]
  44. numpy_coords = True
  45. else:
  46. raise TypeError('Invalid initialization input for LineStrings.')
  47. # Creating a coordinate sequence object because it is easier to
  48. # set the points using GEOSCoordSeq.__setitem__().
  49. cs = GEOSCoordSeq(capi.create_cs(ncoords, ndim), z=bool(ndim==3))
  50. for i in xrange(ncoords):
  51. if numpy_coords: cs[i] = coords[i,:]
  52. elif isinstance(coords[i], Point): cs[i] = coords[i].tuple
  53. else: cs[i] = coords[i]
  54. # If SRID was passed in with the keyword arguments
  55. srid = kwargs.get('srid', None)
  56. # Calling the base geometry initialization with the returned pointer
  57. # from the function.
  58. super(LineString, self).__init__(self._init_func(cs.ptr), srid=srid)
  59. def __iter__(self):
  60. "Allows iteration over this LineString."
  61. for i in xrange(len(self)):
  62. yield self[i]
  63. def __len__(self):
  64. "Returns the number of points in this LineString."
  65. return len(self._cs)
  66. def _get_single_external(self, index):
  67. return self._cs[index]
  68. _get_single_internal = _get_single_external
  69. def _set_list(self, length, items):
  70. ndim = self._cs.dims #
  71. hasz = self._cs.hasz # I don't understand why these are different
  72. # create a new coordinate sequence and populate accordingly
  73. cs = GEOSCoordSeq(capi.create_cs(length, ndim), z=hasz)
  74. for i, c in enumerate(items):
  75. cs[i] = c
  76. ptr = self._init_func(cs.ptr)
  77. if ptr:
  78. capi.destroy_geom(self.ptr)
  79. self.ptr = ptr
  80. self._post_init(self.srid)
  81. else:
  82. # can this happen?
  83. raise GEOSException('Geometry resulting from slice deletion was invalid.')
  84. def _set_single(self, index, value):
  85. self._checkindex(index)
  86. self._cs[index] = value
  87. def _checkdim(self, dim):
  88. if dim not in (2, 3): raise TypeError('Dimension mismatch.')
  89. #### Sequence Properties ####
  90. @property
  91. def tuple(self):
  92. "Returns a tuple version of the geometry from the coordinate sequence."
  93. return self._cs.tuple
  94. coords = tuple
  95. def _listarr(self, func):
  96. """
  97. Internal routine that returns a sequence (list) corresponding with
  98. the given function. Will return a numpy array if possible.
  99. """
  100. lst = [func(i) for i in xrange(len(self))]
  101. if numpy: return numpy.array(lst) # ARRRR!
  102. else: return lst
  103. @property
  104. def array(self):
  105. "Returns a numpy array for the LineString."
  106. return self._listarr(self._cs.__getitem__)
  107. @property
  108. def merged(self):
  109. "Returns the line merge of this LineString."
  110. return self._topology(capi.geos_linemerge(self.ptr))
  111. @property
  112. def x(self):
  113. "Returns a list or numpy array of the X variable."
  114. return self._listarr(self._cs.getX)
  115. @property
  116. def y(self):
  117. "Returns a list or numpy array of the Y variable."
  118. return self._listarr(self._cs.getY)
  119. @property
  120. def z(self):
  121. "Returns a list or numpy array of the Z variable."
  122. if not self.hasz: return None
  123. else: return self._listarr(self._cs.getZ)
  124. # LinearRings are LineStrings used within Polygons.
  125. class LinearRing(LineString):
  126. _minLength = 4
  127. _init_func = capi.create_linearring