PageRenderTime 32ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/django/contrib/gis/gdal/layer.py

https://code.google.com/p/mango-py/
Python | 212 lines | 132 code | 25 blank | 55 comment | 32 complexity | 9e612d749b966925f67e34f3253bc584 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. # Needed ctypes routines
  2. from ctypes import c_double, byref
  3. # Other GDAL imports.
  4. from django.contrib.gis.gdal.base import GDALBase
  5. from django.contrib.gis.gdal.envelope import Envelope, OGREnvelope
  6. from django.contrib.gis.gdal.error import OGRException, OGRIndexError, SRSException
  7. from django.contrib.gis.gdal.feature import Feature
  8. from django.contrib.gis.gdal.field import OGRFieldTypes
  9. from django.contrib.gis.gdal.geomtype import OGRGeomType
  10. from django.contrib.gis.gdal.geometries import OGRGeometry
  11. from django.contrib.gis.gdal.srs import SpatialReference
  12. # GDAL ctypes function prototypes.
  13. from django.contrib.gis.gdal.prototypes import ds as capi, geom as geom_api, srs as srs_api
  14. # For more information, see the OGR C API source code:
  15. # http://www.gdal.org/ogr/ogr__api_8h.html
  16. #
  17. # The OGR_L_* routines are relevant here.
  18. class Layer(GDALBase):
  19. "A class that wraps an OGR Layer, needs to be instantiated from a DataSource object."
  20. #### Python 'magic' routines ####
  21. def __init__(self, layer_ptr, ds):
  22. """
  23. Initializes on an OGR C pointer to the Layer and the `DataSource` object
  24. that owns this layer. The `DataSource` object is required so that a
  25. reference to it is kept with this Layer. This prevents garbage
  26. collection of the `DataSource` while this Layer is still active.
  27. """
  28. if not layer_ptr:
  29. raise OGRException('Cannot create Layer, invalid pointer given')
  30. self.ptr = layer_ptr
  31. self._ds = ds
  32. self._ldefn = capi.get_layer_defn(self._ptr)
  33. # Does the Layer support random reading?
  34. self._random_read = self.test_capability('RandomRead')
  35. def __getitem__(self, index):
  36. "Gets the Feature at the specified index."
  37. if isinstance(index, (int, long)):
  38. # An integer index was given -- we cannot do a check based on the
  39. # number of features because the beginning and ending feature IDs
  40. # are not guaranteed to be 0 and len(layer)-1, respectively.
  41. if index < 0: raise OGRIndexError('Negative indices are not allowed on OGR Layers.')
  42. return self._make_feature(index)
  43. elif isinstance(index, slice):
  44. # A slice was given
  45. start, stop, stride = index.indices(self.num_feat)
  46. return [self._make_feature(fid) for fid in xrange(start, stop, stride)]
  47. else:
  48. raise TypeError('Integers and slices may only be used when indexing OGR Layers.')
  49. def __iter__(self):
  50. "Iterates over each Feature in the Layer."
  51. # ResetReading() must be called before iteration is to begin.
  52. capi.reset_reading(self._ptr)
  53. for i in xrange(self.num_feat):
  54. yield Feature(capi.get_next_feature(self._ptr), self._ldefn)
  55. def __len__(self):
  56. "The length is the number of features."
  57. return self.num_feat
  58. def __str__(self):
  59. "The string name of the layer."
  60. return self.name
  61. def _make_feature(self, feat_id):
  62. """
  63. Helper routine for __getitem__ that constructs a Feature from the given
  64. Feature ID. If the OGR Layer does not support random-access reading,
  65. then each feature of the layer will be incremented through until the
  66. a Feature is found matching the given feature ID.
  67. """
  68. if self._random_read:
  69. # If the Layer supports random reading, return.
  70. try:
  71. return Feature(capi.get_feature(self.ptr, feat_id), self._ldefn)
  72. except OGRException:
  73. pass
  74. else:
  75. # Random access isn't supported, have to increment through
  76. # each feature until the given feature ID is encountered.
  77. for feat in self:
  78. if feat.fid == feat_id: return feat
  79. # Should have returned a Feature, raise an OGRIndexError.
  80. raise OGRIndexError('Invalid feature id: %s.' % feat_id)
  81. #### Layer properties ####
  82. @property
  83. def extent(self):
  84. "Returns the extent (an Envelope) of this layer."
  85. env = OGREnvelope()
  86. capi.get_extent(self.ptr, byref(env), 1)
  87. return Envelope(env)
  88. @property
  89. def name(self):
  90. "Returns the name of this layer in the Data Source."
  91. return capi.get_fd_name(self._ldefn)
  92. @property
  93. def num_feat(self, force=1):
  94. "Returns the number of features in the Layer."
  95. return capi.get_feature_count(self.ptr, force)
  96. @property
  97. def num_fields(self):
  98. "Returns the number of fields in the Layer."
  99. return capi.get_field_count(self._ldefn)
  100. @property
  101. def geom_type(self):
  102. "Returns the geometry type (OGRGeomType) of the Layer."
  103. return OGRGeomType(capi.get_fd_geom_type(self._ldefn))
  104. @property
  105. def srs(self):
  106. "Returns the Spatial Reference used in this Layer."
  107. try:
  108. ptr = capi.get_layer_srs(self.ptr)
  109. return SpatialReference(srs_api.clone_srs(ptr))
  110. except SRSException:
  111. return None
  112. @property
  113. def fields(self):
  114. """
  115. Returns a list of string names corresponding to each of the Fields
  116. available in this Layer.
  117. """
  118. return [capi.get_field_name(capi.get_field_defn(self._ldefn, i))
  119. for i in xrange(self.num_fields) ]
  120. @property
  121. def field_types(self):
  122. """
  123. Returns a list of the types of fields in this Layer. For example,
  124. the list [OFTInteger, OFTReal, OFTString] would be returned for
  125. an OGR layer that had an integer, a floating-point, and string
  126. fields.
  127. """
  128. return [OGRFieldTypes[capi.get_field_type(capi.get_field_defn(self._ldefn, i))]
  129. for i in xrange(self.num_fields)]
  130. @property
  131. def field_widths(self):
  132. "Returns a list of the maximum field widths for the features."
  133. return [capi.get_field_width(capi.get_field_defn(self._ldefn, i))
  134. for i in xrange(self.num_fields)]
  135. @property
  136. def field_precisions(self):
  137. "Returns the field precisions for the features."
  138. return [capi.get_field_precision(capi.get_field_defn(self._ldefn, i))
  139. for i in xrange(self.num_fields)]
  140. def _get_spatial_filter(self):
  141. try:
  142. return OGRGeometry(geom_api.clone_geom(capi.get_spatial_filter(self.ptr)))
  143. except OGRException:
  144. return None
  145. def _set_spatial_filter(self, filter):
  146. if isinstance(filter, OGRGeometry):
  147. capi.set_spatial_filter(self.ptr, filter.ptr)
  148. elif isinstance(filter, (tuple, list)):
  149. if not len(filter) == 4:
  150. raise ValueError('Spatial filter list/tuple must have 4 elements.')
  151. # Map c_double onto params -- if a bad type is passed in it
  152. # will be caught here.
  153. xmin, ymin, xmax, ymax = map(c_double, filter)
  154. capi.set_spatial_filter_rect(self.ptr, xmin, ymin, xmax, ymax)
  155. elif filter is None:
  156. capi.set_spatial_filter(self.ptr, None)
  157. else:
  158. raise TypeError('Spatial filter must be either an OGRGeometry instance, a 4-tuple, or None.')
  159. spatial_filter = property(_get_spatial_filter, _set_spatial_filter)
  160. #### Layer Methods ####
  161. def get_fields(self, field_name):
  162. """
  163. Returns a list containing the given field name for every Feature
  164. in the Layer.
  165. """
  166. if not field_name in self.fields:
  167. raise OGRException('invalid field name: %s' % field_name)
  168. return [feat.get(field_name) for feat in self]
  169. def get_geoms(self, geos=False):
  170. """
  171. Returns a list containing the OGRGeometry for every Feature in
  172. the Layer.
  173. """
  174. if geos:
  175. from django.contrib.gis.geos import GEOSGeometry
  176. return [GEOSGeometry(feat.geom.wkb) for feat in self]
  177. else:
  178. return [feat.geom for feat in self]
  179. def test_capability(self, capability):
  180. """
  181. Returns a bool indicating whether the this Layer supports the given
  182. capability (a string). Valid capability strings include:
  183. 'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter',
  184. 'FastFeatureCount', 'FastGetExtent', 'CreateField', 'Transactions',
  185. 'DeleteFeature', and 'FastSetNextByIndex'.
  186. """
  187. return bool(capi.test_capability(self.ptr, capability))