layer.py 8.6 KB

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