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