linestring.py 5.7 KB

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