You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

layer.py 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. from ctypes import byref, c_double
  2. from django.contrib.gis.gdal.base import GDALBase
  3. from django.contrib.gis.gdal.envelope import Envelope, OGREnvelope
  4. from django.contrib.gis.gdal.error import GDALException, SRSException
  5. from django.contrib.gis.gdal.feature import Feature
  6. from django.contrib.gis.gdal.field import OGRFieldTypes
  7. from django.contrib.gis.gdal.geometries import OGRGeometry
  8. from django.contrib.gis.gdal.geomtype import OGRGeomType
  9. from django.contrib.gis.gdal.prototypes import (
  10. ds as capi, geom as geom_api, srs as srs_api,
  11. )
  12. from django.contrib.gis.gdal.srs import SpatialReference
  13. from django.utils.encoding import force_bytes, force_text
  14. # For more information, see the OGR C API source code:
  15. # https://www.gdal.org/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. def __init__(self, layer_ptr, ds):
  21. """
  22. Initialize on an OGR C pointer to the Layer and the `DataSource` object
  23. that owns this layer. The `DataSource` object is required so that a
  24. reference to it is kept with this Layer. This prevents garbage
  25. collection of the `DataSource` while this Layer is still active.
  26. """
  27. if not layer_ptr:
  28. raise GDALException('Cannot create Layer, invalid pointer given')
  29. self.ptr = layer_ptr
  30. self._ds = ds
  31. self._ldefn = capi.get_layer_defn(self._ptr)
  32. # Does the Layer support random reading?
  33. self._random_read = self.test_capability(b'RandomRead')
  34. def __getitem__(self, index):
  35. "Get the Feature at the specified index."
  36. if isinstance(index, int):
  37. # An integer index was given -- we cannot do a check based on the
  38. # number of features because the beginning and ending feature IDs
  39. # are not guaranteed to be 0 and len(layer)-1, respectively.
  40. if index < 0:
  41. raise IndexError('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 range(start, stop, stride)]
  47. else:
  48. raise TypeError('Integers and slices may only be used when indexing OGR Layers.')
  49. def __iter__(self):
  50. "Iterate 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 range(self.num_feat):
  54. yield Feature(capi.get_next_feature(self._ptr), self)
  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)
  72. except GDALException:
  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:
  79. return feat
  80. # Should have returned a Feature, raise an IndexError.
  81. raise IndexError('Invalid feature id: %s.' % feat_id)
  82. # #### Layer properties ####
  83. @property
  84. def extent(self):
  85. "Return the extent (an Envelope) of this layer."
  86. env = OGREnvelope()
  87. capi.get_extent(self.ptr, byref(env), 1)
  88. return Envelope(env)
  89. @property
  90. def name(self):
  91. "Return the name of this layer in the Data Source."
  92. name = capi.get_fd_name(self._ldefn)
  93. return force_text(name, self._ds.encoding, strings_only=True)
  94. @property
  95. def num_feat(self, force=1):
  96. "Return the number of features in the Layer."
  97. return capi.get_feature_count(self.ptr, force)
  98. @property
  99. def num_fields(self):
  100. "Return the number of fields in the Layer."
  101. return capi.get_field_count(self._ldefn)
  102. @property
  103. def geom_type(self):
  104. "Return the geometry type (OGRGeomType) of the Layer."
  105. return OGRGeomType(capi.get_fd_geom_type(self._ldefn))
  106. @property
  107. def srs(self):
  108. "Return the Spatial Reference used in this Layer."
  109. try:
  110. ptr = capi.get_layer_srs(self.ptr)
  111. return SpatialReference(srs_api.clone_srs(ptr))
  112. except SRSException:
  113. return None
  114. @property
  115. def fields(self):
  116. """
  117. Return a list of string names corresponding to each of the Fields
  118. available in this Layer.
  119. """
  120. return [force_text(capi.get_field_name(capi.get_field_defn(self._ldefn, i)),
  121. self._ds.encoding, strings_only=True)
  122. for i in range(self.num_fields)]
  123. @property
  124. def field_types(self):
  125. """
  126. Return a list of the types of fields in this Layer. For example,
  127. return the list [OFTInteger, OFTReal, OFTString] for an OGR layer that
  128. has an integer, a floating-point, and string fields.
  129. """
  130. return [OGRFieldTypes[capi.get_field_type(capi.get_field_defn(self._ldefn, i))]
  131. for i in range(self.num_fields)]
  132. @property
  133. def field_widths(self):
  134. "Return a list of the maximum field widths for the features."
  135. return [capi.get_field_width(capi.get_field_defn(self._ldefn, i))
  136. for i in range(self.num_fields)]
  137. @property
  138. def field_precisions(self):
  139. "Return the field precisions for the features."
  140. return [capi.get_field_precision(capi.get_field_defn(self._ldefn, i))
  141. for i in range(self.num_fields)]
  142. def _get_spatial_filter(self):
  143. try:
  144. return OGRGeometry(geom_api.clone_geom(capi.get_spatial_filter(self.ptr)))
  145. except GDALException:
  146. return None
  147. def _set_spatial_filter(self, filter):
  148. if isinstance(filter, OGRGeometry):
  149. capi.set_spatial_filter(self.ptr, filter.ptr)
  150. elif isinstance(filter, (tuple, list)):
  151. if not len(filter) == 4:
  152. raise ValueError('Spatial filter list/tuple must have 4 elements.')
  153. # Map c_double onto params -- if a bad type is passed in it
  154. # will be caught here.
  155. xmin, ymin, xmax, ymax = map(c_double, filter)
  156. capi.set_spatial_filter_rect(self.ptr, xmin, ymin, xmax, ymax)
  157. elif filter is None:
  158. capi.set_spatial_filter(self.ptr, None)
  159. else:
  160. raise TypeError('Spatial filter must be either an OGRGeometry instance, a 4-tuple, or None.')
  161. spatial_filter = property(_get_spatial_filter, _set_spatial_filter)
  162. # #### Layer Methods ####
  163. def get_fields(self, field_name):
  164. """
  165. Return a list containing the given field name for every Feature
  166. in the Layer.
  167. """
  168. if field_name not in self.fields:
  169. raise GDALException('invalid field name: %s' % field_name)
  170. return [feat.get(field_name) for feat in self]
  171. def get_geoms(self, geos=False):
  172. """
  173. Return a list containing the OGRGeometry for every Feature in
  174. the Layer.
  175. """
  176. if geos:
  177. from django.contrib.gis.geos import GEOSGeometry
  178. return [GEOSGeometry(feat.geom.wkb) for feat in self]
  179. else:
  180. return [feat.geom for feat in self]
  181. def test_capability(self, capability):
  182. """
  183. Return a bool indicating whether the this Layer supports the given
  184. capability (a string). Valid capability strings include:
  185. 'RandomRead', 'SequentialWrite', 'RandomWrite', 'FastSpatialFilter',
  186. 'FastFeatureCount', 'FastGetExtent', 'CreateField', 'Transactions',
  187. 'DeleteFeature', and 'FastSetNextByIndex'.
  188. """
  189. return bool(capi.test_capability(self.ptr, force_bytes(capability)))