-
Notifications
You must be signed in to change notification settings - Fork 204
/
ogrext.pyx
1699 lines (1370 loc) · 58.7 KB
/
ogrext.pyx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# These are extension functions and classes using the OGR C API.
from __future__ import absolute_import
import datetime
import json
import locale
import logging
import os
import warnings
import math
import uuid
from collections import namedtuple, OrderedDict
from six import integer_types, string_types, text_type
from fiona._shim cimport *
from fiona._geometry cimport (
GeomBuilder, OGRGeomBuilder, geometry_type_code,
normalize_geometry_type_code, base_geometry_type_code)
from fiona._err cimport exc_wrap_int, exc_wrap_pointer, exc_wrap_vsilfile
import fiona
from fiona._env import GDALVersion, get_gdal_version_num
from fiona._err import cpl_errs, FionaNullPointerError, CPLE_BaseError, CPLE_OpenFailedError
from fiona._geometry import GEOMETRY_TYPES
from fiona import compat
from fiona.errors import (
DriverError, DriverIOError, SchemaError, CRSError, FionaValueError,
TransactionError, GeometryTypeValidationError, DatasetDeleteError,
FionaDeprecationWarning)
from fiona.compat import strencode
from fiona.rfc3339 import parse_date, parse_datetime, parse_time
from fiona.rfc3339 import FionaDateType, FionaDateTimeType, FionaTimeType
from fiona.schema import FIELD_TYPES, FIELD_TYPES_MAP, normalize_field_type
from fiona.path import vsi_path
from fiona._shim cimport is_field_null, osr_get_name, osr_set_traditional_axis_mapping_strategy
from libc.stdlib cimport malloc, free
from libc.string cimport strcmp
from cpython cimport PyBytes_FromStringAndSize, PyBytes_AsString
cdef extern from "ogr_api.h" nogil:
ctypedef void * OGRLayerH
ctypedef void * OGRDataSourceH
ctypedef void * OGRSFDriverH
ctypedef void * OGRFieldDefnH
ctypedef void * OGRFeatureDefnH
ctypedef void * OGRFeatureH
ctypedef void * OGRGeometryH
log = logging.getLogger(__name__)
DEFAULT_TRANSACTION_SIZE = 20000
# OGR Driver capability
cdef const char * ODrCCreateDataSource = "CreateDataSource"
cdef const char * ODrCDeleteDataSource = "DeleteDataSource"
# OGR Layer capability
cdef const char * OLC_RANDOMREAD = "RandomRead"
cdef const char * OLC_SEQUENTIALWRITE = "SequentialWrite"
cdef const char * OLC_RANDOMWRITE = "RandomWrite"
cdef const char * OLC_FASTSPATIALFILTER = "FastSpatialFilter"
cdef const char * OLC_FASTFEATURECOUNT = "FastFeatureCount"
cdef const char * OLC_FASTGETEXTENT = "FastGetExtent"
cdef const char * OLC_FASTSETNEXTBYINDEX = "FastSetNextByIndex"
cdef const char * OLC_CREATEFIELD = "CreateField"
cdef const char * OLC_CREATEGEOMFIELD = "CreateGeomField"
cdef const char * OLC_DELETEFIELD = "DeleteField"
cdef const char * OLC_REORDERFIELDS = "ReorderFields"
cdef const char * OLC_ALTERFIELDDEFN = "AlterFieldDefn"
cdef const char * OLC_DELETEFEATURE = "DeleteFeature"
cdef const char * OLC_STRINGSASUTF8 = "StringsAsUTF8"
cdef const char * OLC_TRANSACTIONS = "Transactions"
# OGR integer error types.
OGRERR_NONE = 0
OGRERR_NOT_ENOUGH_DATA = 1 # not enough data to deserialize */
OGRERR_NOT_ENOUGH_MEMORY = 2
OGRERR_UNSUPPORTED_GEOMETRY_TYPE = 3
OGRERR_UNSUPPORTED_OPERATION = 4
OGRERR_CORRUPT_DATA = 5
OGRERR_FAILURE = 6
OGRERR_UNSUPPORTED_SRS = 7
OGRERR_INVALID_HANDLE = 8
def _explode(coords):
"""Explode a GeoJSON geometry's coordinates object and yield
coordinate tuples. As long as the input is conforming, the type of
the geometry doesn't matter."""
for e in coords:
if isinstance(e, (float, int)):
yield coords
break
else:
for f in _explode(e):
yield f
def _bounds(geometry):
"""Bounding box of a GeoJSON geometry"""
try:
xyz = tuple(zip(*list(_explode(geometry['coordinates']))))
return min(xyz[0]), min(xyz[1]), max(xyz[0]), max(xyz[1])
except (KeyError, TypeError):
return None
cdef int GDAL_VERSION_NUM = get_gdal_version_num()
# Feature extension classes and functions follow.
cdef class FeatureBuilder:
"""Build Fiona features from OGR feature pointers.
No OGR objects are allocated by this function and the feature
argument is not destroyed.
"""
cdef build(self, void *feature, encoding='utf-8', bbox=False, driver=None, ignore_fields=None, ignore_geometry=False):
"""Build a Fiona feature object from an OGR feature
Parameters
----------
feature : void *
The OGR feature # TODO: use a real typedef
encoding : str
The encoding of OGR feature attributes
bbox : bool
Not used
driver : str
OGR format driver name like 'GeoJSON'
ignore_fields : sequence
A sequence of field names that will be ignored and omitted
in the Fiona feature properties
ignore_geometry : bool
Flag for whether the OGR geometry field is to be ignored
Returns
-------
dict
"""
cdef void *fdefn = NULL
cdef int i
cdef int y = 0
cdef int m = 0
cdef int d = 0
cdef int hh = 0
cdef int mm = 0
cdef int ss = 0
cdef int tz = 0
cdef unsigned char *data = NULL
cdef int l
cdef int retval
cdef int fieldsubtype
cdef const char *key_c = NULL
# Skeleton of the feature to be returned.
fid = OGR_F_GetFID(feature)
props = OrderedDict()
fiona_feature = {
"type": "Feature",
"id": str(fid),
"properties": props,
}
ignore_fields = set(ignore_fields or [])
# Iterate over the fields of the OGR feature.
for i in range(OGR_F_GetFieldCount(feature)):
fdefn = OGR_F_GetFieldDefnRef(feature, i)
if fdefn == NULL:
raise ValueError("Null feature definition")
key_c = OGR_Fld_GetNameRef(fdefn)
if key_c == NULL:
raise ValueError("Null field name reference")
key_b = key_c
key = key_b.decode(encoding)
if key in ignore_fields:
continue
fieldtypename = FIELD_TYPES[OGR_Fld_GetType(fdefn)]
fieldsubtype = get_field_subtype(fdefn)
if not fieldtypename:
log.warning(
"Skipping field %s: invalid type %s",
key,
OGR_Fld_GetType(fdefn))
continue
# TODO: other types
fieldtype = FIELD_TYPES_MAP[fieldtypename]
if is_field_null(feature, i):
props[key] = None
elif fieldtypename is 'int32':
if fieldsubtype == OFSTBoolean:
props[key] = bool(OGR_F_GetFieldAsInteger(feature, i))
else:
props[key] = OGR_F_GetFieldAsInteger(feature, i)
elif fieldtype is int:
if fieldsubtype == OFSTBoolean:
props[key] = bool(OGR_F_GetFieldAsInteger64(feature, i))
else:
props[key] = OGR_F_GetFieldAsInteger64(feature, i)
elif fieldtype is float:
props[key] = OGR_F_GetFieldAsDouble(feature, i)
elif fieldtype is text_type:
val = OGR_F_GetFieldAsString(feature, i)
try:
val = val.decode(encoding)
except UnicodeDecodeError:
log.warning(
"Failed to decode %s using %s codec", val, encoding)
# Does the text contain a JSON object? Let's check.
# Let's check as cheaply as we can.
if driver == 'GeoJSON' and val.startswith('{'):
try:
val = json.loads(val)
except ValueError as err:
log.warning(str(err))
# Now add to the properties object.
props[key] = val
elif fieldtype in (FionaDateType, FionaTimeType, FionaDateTimeType):
retval = OGR_F_GetFieldAsDateTime(
feature, i, &y, &m, &d, &hh, &mm, &ss, &tz)
try:
if fieldtype is FionaDateType:
props[key] = datetime.date(y, m, d).isoformat()
elif fieldtype is FionaTimeType:
props[key] = datetime.time(hh, mm, ss).isoformat()
else:
props[key] = datetime.datetime(
y, m, d, hh, mm, ss).isoformat()
except ValueError as err:
log.exception(err)
props[key] = None
elif fieldtype is bytes:
data = OGR_F_GetFieldAsBinary(feature, i, &l)
props[key] = data[:l]
else:
props[key] = None
cdef void *cogr_geometry = NULL
cdef void *org_geometry = NULL
if not ignore_geometry:
cogr_geometry = OGR_F_GetGeometryRef(feature)
if cogr_geometry is not NULL:
code = base_geometry_type_code(OGR_G_GetGeometryType(cogr_geometry))
if 8 <= code <= 14: # Curves.
cogr_geometry = get_linear_geometry(cogr_geometry)
geom = GeomBuilder().build(cogr_geometry)
OGR_G_DestroyGeometry(cogr_geometry)
elif 15 <= code <= 17:
# We steal the geometry: the geometry of the in-memory feature is now null
# and we are responsible for cogr_geometry.
org_geometry = OGR_F_StealGeometry(feature)
if code in (15, 16):
cogr_geometry = OGR_G_ForceToMultiPolygon(org_geometry)
elif code == 17:
cogr_geometry = OGR_G_ForceToPolygon(org_geometry)
geom = GeomBuilder().build(cogr_geometry)
OGR_G_DestroyGeometry(cogr_geometry)
else:
geom = GeomBuilder().build(cogr_geometry)
fiona_feature["geometry"] = geom
else:
fiona_feature["geometry"] = None
return fiona_feature
cdef class OGRFeatureBuilder:
"""Builds an OGR Feature from a Fiona feature mapping.
Allocates one OGR Feature which should be destroyed by the caller.
Borrows a layer definition from the collection.
"""
cdef void * build(self, feature, collection) except NULL:
cdef void *cogr_geometry = NULL
cdef const char *string_c = NULL
cdef WritingSession session
session = collection.session
cdef void *cogr_layer = session.cogr_layer
if cogr_layer == NULL:
raise ValueError("Null layer")
cdef void *cogr_featuredefn = OGR_L_GetLayerDefn(cogr_layer)
if cogr_featuredefn == NULL:
raise ValueError("Null feature definition")
cdef void *cogr_feature = OGR_F_Create(cogr_featuredefn)
if cogr_feature == NULL:
raise ValueError("Null feature")
if feature['geometry'] is not None:
cogr_geometry = OGRGeomBuilder().build(
feature['geometry'])
OGR_F_SetGeometryDirectly(cogr_feature, cogr_geometry)
# OGR_F_SetFieldString takes encoded strings ('bytes' in Python 3).
encoding = session._get_internal_encoding()
for key, value in feature['properties'].items():
ogr_key = session._schema_mapping[key]
schema_type = normalize_field_type(collection.schema['properties'][key])
key_bytes = strencode(ogr_key, encoding)
key_c = key_bytes
i = OGR_F_GetFieldIndex(cogr_feature, key_c)
if i < 0:
continue
# Special case: serialize dicts to assist OGR.
if isinstance(value, dict):
value = json.dumps(value)
# Continue over the standard OGR types.
if isinstance(value, integer_types):
if schema_type == 'int32':
OGR_F_SetFieldInteger(cogr_feature, i, value)
else:
OGR_F_SetFieldInteger64(cogr_feature, i, value)
elif isinstance(value, float):
OGR_F_SetFieldDouble(cogr_feature, i, value)
elif (isinstance(value, string_types)
and schema_type in ['date', 'time', 'datetime']):
if schema_type == 'date':
y, m, d, hh, mm, ss, ff = parse_date(value)
elif schema_type == 'time':
y, m, d, hh, mm, ss, ff = parse_time(value)
else:
y, m, d, hh, mm, ss, ff = parse_datetime(value)
OGR_F_SetFieldDateTime(
cogr_feature, i, y, m, d, hh, mm, ss, 0)
elif (isinstance(value, datetime.date)
and schema_type == 'date'):
y, m, d = value.year, value.month, value.day
OGR_F_SetFieldDateTime(
cogr_feature, i, y, m, d, 0, 0, 0, 0)
elif (isinstance(value, datetime.datetime)
and schema_type == 'datetime'):
y, m, d = value.year, value.month, value.day
hh, mm, ss = value.hour, value.minute, value.second
OGR_F_SetFieldDateTime(
cogr_feature, i, y, m, d, hh, mm, ss, 0)
elif (isinstance(value, datetime.time)
and schema_type == 'time'):
hh, mm, ss = value.hour, value.minute, value.second
OGR_F_SetFieldDateTime(
cogr_feature, i, 0, 0, 0, hh, mm, ss, 0)
elif isinstance(value, bytes) and schema_type == "bytes":
string_c = value
OGR_F_SetFieldBinary(cogr_feature, i, len(value),
<unsigned char*>string_c)
elif isinstance(value, string_types):
value_bytes = strencode(value, encoding)
string_c = value_bytes
OGR_F_SetFieldString(cogr_feature, i, string_c)
elif value is None:
set_field_null(cogr_feature, i)
else:
raise ValueError("Invalid field type %s" % type(value))
return cogr_feature
cdef _deleteOgrFeature(void *cogr_feature):
"""Delete an OGR feature"""
if cogr_feature is not NULL:
OGR_F_Destroy(cogr_feature)
cogr_feature = NULL
def featureRT(feature, collection):
# For testing purposes only, leaks the JSON data
cdef void *cogr_feature = OGRFeatureBuilder().build(feature, collection)
cdef void *cogr_geometry = OGR_F_GetGeometryRef(cogr_feature)
if cogr_geometry == NULL:
raise ValueError("Null geometry")
result = FeatureBuilder().build(
cogr_feature,
encoding='utf-8',
bbox=False,
driver=collection.driver
)
_deleteOgrFeature(cogr_feature)
return result
# Collection-related extension classes and functions
cdef class Session:
cdef void *cogr_ds
cdef void *cogr_layer
cdef object _fileencoding
cdef object _encoding
cdef object collection
def __init__(self):
self.cogr_ds = NULL
self.cogr_layer = NULL
self._fileencoding = None
self._encoding = None
def __dealloc__(self):
self.stop()
def start(self, collection, **kwargs):
cdef const char *path_c = NULL
cdef const char *name_c = NULL
cdef void *drv = NULL
cdef void *ds = NULL
cdef char **ignore_fields = NULL
path_b = collection.path.encode('utf-8')
path_c = path_b
self._fileencoding = kwargs.get('encoding') or collection.encoding
# We have two ways of specifying drivers to try. Resolve the
# values into a single set of driver short names.
if collection._driver:
drivers = set([collection._driver])
elif collection.enabled_drivers:
drivers = set(collection.enabled_drivers)
else:
drivers = None
encoding = kwargs.pop('encoding', None)
if encoding:
kwargs['encoding'] = encoding.upper()
self.cogr_ds = gdal_open_vector(path_c, 0, drivers, kwargs)
if isinstance(collection.name, string_types):
name_b = collection.name.encode('utf-8')
name_c = name_b
self.cogr_layer = GDALDatasetGetLayerByName(self.cogr_ds, name_c)
elif isinstance(collection.name, int):
self.cogr_layer = GDALDatasetGetLayer(self.cogr_ds, collection.name)
name_c = OGR_L_GetName(self.cogr_layer)
name_b = name_c
collection.name = name_b.decode('utf-8')
if self.cogr_layer == NULL:
raise ValueError("Null layer: " + repr(collection.name))
encoding = self._get_internal_encoding()
if collection.ignore_fields:
try:
for name in collection.ignore_fields:
try:
name_b = name.encode(encoding)
except AttributeError:
raise TypeError("Ignored field \"{}\" has type \"{}\", expected string".format(name, name.__class__.__name__))
ignore_fields = CSLAddString(ignore_fields, <const char *>name_b)
OGR_L_SetIgnoredFields(self.cogr_layer, <const char**>ignore_fields)
finally:
CSLDestroy(ignore_fields)
self.collection = collection
cpdef stop(self):
self.cogr_layer = NULL
if self.cogr_ds != NULL:
GDALClose(self.cogr_ds)
self.cogr_ds = NULL
def get_fileencoding(self):
"""DEPRECATED"""
warnings.warn("get_fileencoding is deprecated and will be removed in a future version.", FionaDeprecationWarning)
return self._fileencoding
def _get_fallback_encoding(self):
"""Determine a format-specific fallback encoding to use when using OGR_F functions
Parameters
----------
None
Returns
-------
str
"""
if "Shapefile" in self.get_driver():
return 'iso-8859-1'
else:
return locale.getpreferredencoding()
def _get_internal_encoding(self):
"""Determine the encoding to use when use OGR_F functions
Parameters
----------
None
Returns
-------
str
Notes
-----
If the layer implements RFC 23 support for UTF-8, the return
value will be 'utf-8' and callers can be certain that this is
correct. If the layer does not have the OLC_STRINGSASUTF8
capability marker, it is not possible to know exactly what the
internal encoding is and this method returns best guesses. That
means ISO-8859-1 for shapefiles and the locale's preferred
encoding for other formats such as CSV files.
"""
if OGR_L_TestCapability(self.cogr_layer, OLC_STRINGSASUTF8):
return 'utf-8'
else:
return self._fileencoding or self._get_fallback_encoding()
def get_length(self):
if self.cogr_layer == NULL:
raise ValueError("Null layer")
return OGR_L_GetFeatureCount(self.cogr_layer, 0)
def get_driver(self):
cdef void *cogr_driver = GDALGetDatasetDriver(self.cogr_ds)
if cogr_driver == NULL:
raise ValueError("Null driver")
cdef const char *name = OGR_Dr_GetName(cogr_driver)
driver_name = name
return driver_name.decode()
def get_schema(self):
cdef int i
cdef int n
cdef void *cogr_featuredefn = NULL
cdef void *cogr_fielddefn = NULL
cdef const char *key_c
props = []
if self.cogr_layer == NULL:
raise ValueError("Null layer")
if self.collection.ignore_fields:
ignore_fields = self.collection.ignore_fields
else:
ignore_fields = set()
cogr_featuredefn = OGR_L_GetLayerDefn(self.cogr_layer)
if cogr_featuredefn == NULL:
raise ValueError("Null feature definition")
encoding = self._get_internal_encoding()
n = OGR_FD_GetFieldCount(cogr_featuredefn)
for i from 0 <= i < n:
cogr_fielddefn = OGR_FD_GetFieldDefn(cogr_featuredefn, i)
if cogr_fielddefn == NULL:
raise ValueError("Null field definition")
key_c = OGR_Fld_GetNameRef(cogr_fielddefn)
key_b = key_c
if not bool(key_b):
raise ValueError("Invalid field name ref: %s" % key)
key = key_b.decode(encoding)
if key in ignore_fields:
continue
fieldtypename = FIELD_TYPES[OGR_Fld_GetType(cogr_fielddefn)]
if not fieldtypename:
log.warning(
"Skipping field %s: invalid type %s",
key,
OGR_Fld_GetType(cogr_fielddefn))
continue
val = fieldtypename
if fieldtypename == 'float':
fmt = ""
width = OGR_Fld_GetWidth(cogr_fielddefn)
if width: # and width != 24:
fmt = ":%d" % width
precision = OGR_Fld_GetPrecision(cogr_fielddefn)
if precision: # and precision != 15:
fmt += ".%d" % precision
val = "float" + fmt
elif fieldtypename in ('int32', 'int64'):
fmt = ""
width = OGR_Fld_GetWidth(cogr_fielddefn)
if width:
fmt = ":%d" % width
val = 'int' + fmt
elif fieldtypename == 'str':
fmt = ""
width = OGR_Fld_GetWidth(cogr_fielddefn)
if width:
fmt = ":%d" % width
val = fieldtypename + fmt
props.append((key, val))
ret = {"properties": OrderedDict(props)}
if not self.collection.ignore_geometry:
code = normalize_geometry_type_code(
OGR_FD_GetGeomType(cogr_featuredefn))
ret["geometry"] = GEOMETRY_TYPES[code]
return ret
def get_crs(self):
"""Get the layer's CRS
Returns
-------
CRS
"""
cdef char *proj_c = NULL
cdef const char *auth_key = NULL
cdef const char *auth_val = NULL
cdef void *cogr_crs = NULL
if self.cogr_layer == NULL:
raise ValueError("Null layer")
try:
cogr_crs = exc_wrap_pointer(OGR_L_GetSpatialRef(self.cogr_layer))
# TODO: we don't intend to use try/except for flow control
# this is a work around for a GDAL issue.
except FionaNullPointerError:
log.debug("Layer has no coordinate system")
if cogr_crs is not NULL:
log.debug("Got coordinate system")
crs = {}
try:
retval = OSRAutoIdentifyEPSG(cogr_crs)
if retval > 0:
log.info("Failed to auto identify EPSG: %d", retval)
try:
auth_key = <const char *>exc_wrap_pointer(<void *>OSRGetAuthorityName(cogr_crs, NULL))
auth_val = <const char *>exc_wrap_pointer(<void *>OSRGetAuthorityCode(cogr_crs, NULL))
except CPLE_BaseError as exc:
log.debug("{}".format(exc))
if auth_key != NULL and auth_val != NULL:
key_b = auth_key
key = key_b.decode('utf-8')
if key == 'EPSG':
val_b = auth_val
val = val_b.decode('utf-8')
crs['init'] = "epsg:" + val
else:
OSRExportToProj4(cogr_crs, &proj_c)
if proj_c == NULL:
raise ValueError("Null projection")
proj_b = proj_c
log.debug("Params: %s", proj_b)
value = proj_b.decode()
value = value.strip()
for param in value.split():
kv = param.split("=")
if len(kv) == 2:
k, v = kv
try:
v = float(v)
if v % 1 == 0:
v = int(v)
except ValueError:
# Leave v as a string
pass
elif len(kv) == 1:
k, v = kv[0], True
else:
raise ValueError("Unexpected proj parameter %s" % param)
k = k.lstrip("+")
crs[k] = v
finally:
CPLFree(proj_c)
return crs
else:
log.debug("Projection not found (cogr_crs was NULL)")
return {}
def get_crs_wkt(self):
cdef char *proj_c = NULL
cdef void *cogr_crs = NULL
if self.cogr_layer == NULL:
raise ValueError("Null layer")
try:
cogr_crs = exc_wrap_pointer(OGR_L_GetSpatialRef(self.cogr_layer))
# TODO: we don't intend to use try/except for flow control
# this is a work around for a GDAL issue.
except FionaNullPointerError:
log.debug("Layer has no coordinate system")
except fiona._err.CPLE_OpenFailedError as exc:
log.debug("A support file wasn't opened. See the preceding ERROR level message.")
cogr_crs = OGR_L_GetSpatialRef(self.cogr_layer)
log.debug("Called OGR_L_GetSpatialRef() again without error checking.")
if cogr_crs == NULL:
raise exc
if cogr_crs is not NULL:
log.debug("Got coordinate system")
try:
OSRExportToWkt(cogr_crs, &proj_c)
if proj_c == NULL:
raise ValueError("Null projection")
proj_b = proj_c
crs_wkt = proj_b.decode('utf-8')
finally:
CPLFree(proj_c)
return crs_wkt
else:
log.debug("Projection not found (cogr_crs was NULL)")
return ""
def get_extent(self):
cdef OGREnvelope extent
if self.cogr_layer == NULL:
raise ValueError("Null layer")
result = OGR_L_GetExtent(self.cogr_layer, &extent, 1)
return (extent.MinX, extent.MinY, extent.MaxX, extent.MaxY)
def has_feature(self, fid):
"""Provides access to feature data by FID.
Supports Collection.__contains__().
"""
cdef void * cogr_feature
fid = int(fid)
cogr_feature = OGR_L_GetFeature(self.cogr_layer, fid)
if cogr_feature != NULL:
_deleteOgrFeature(cogr_feature)
return True
else:
return False
def get_feature(self, fid):
"""Provides access to feature data by FID.
Supports Collection.__contains__().
"""
cdef void * cogr_feature
fid = int(fid)
cogr_feature = OGR_L_GetFeature(self.cogr_layer, fid)
if cogr_feature != NULL:
feature = FeatureBuilder().build(
cogr_feature,
encoding=self._get_internal_encoding(),
bbox=False,
driver=self.collection.driver,
ignore_fields=self.collection.ignore_fields,
ignore_geometry=self.collection.ignore_geometry,
)
_deleteOgrFeature(cogr_feature)
return feature
else:
raise KeyError("There is no feature with fid {!r}".format(fid))
get = get_feature
# TODO: Make this an alias for get_feature in a future version.
def __getitem__(self, item):
cdef void * cogr_feature
if isinstance(item, slice):
warnings.warn("Collection slicing is deprecated and will be disabled in a future version.", FionaDeprecationWarning)
itr = Iterator(self.collection, item.start, item.stop, item.step)
return list(itr)
elif isinstance(item, int):
index = item
# from the back
if index < 0:
ftcount = OGR_L_GetFeatureCount(self.cogr_layer, 0)
if ftcount == -1:
raise IndexError(
"collection's dataset does not support negative indexes")
index += ftcount
cogr_feature = OGR_L_GetFeature(self.cogr_layer, index)
if cogr_feature == NULL:
return None
feature = FeatureBuilder().build(
cogr_feature,
encoding=self._get_internal_encoding(),
bbox=False,
driver=self.collection.driver,
ignore_fields=self.collection.ignore_fields,
ignore_geometry=self.collection.ignore_geometry,
)
_deleteOgrFeature(cogr_feature)
return feature
def isactive(self):
if self.cogr_layer != NULL and self.cogr_ds != NULL:
return 1
else:
return 0
cdef class WritingSession(Session):
cdef object _schema_mapping
def start(self, collection, **kwargs):
cdef OGRSpatialReferenceH cogr_srs = NULL
cdef char **options = NULL
cdef const char *path_c = NULL
cdef const char *driver_c = NULL
cdef const char *name_c = NULL
cdef const char *proj_c = NULL
cdef const char *fileencoding_c = NULL
cdef OGRFieldSubType field_subtype
cdef int ret
path = collection.path
self.collection = collection
userencoding = kwargs.get('encoding')
if collection.mode == 'a':
if not os.path.exists(path):
raise OSError("No such file or directory %s" % path)
path_b = strencode(path)
path_c = path_b
try:
self.cogr_ds = gdal_open_vector(path_c, 1, None, kwargs)
if isinstance(collection.name, string_types):
name_b = collection.name.encode('utf-8')
name_c = name_b
self.cogr_layer = exc_wrap_pointer(GDALDatasetGetLayerByName(self.cogr_ds, name_c))
elif isinstance(collection.name, int):
self.cogr_layer = exc_wrap_pointer(GDALDatasetGetLayer(self.cogr_ds, collection.name))
except CPLE_BaseError as exc:
OGRReleaseDataSource(self.cogr_ds)
self.cogr_ds = NULL
self.cogr_layer = NULL
raise DriverError(u"{}".format(exc))
else:
self._fileencoding = userencoding or self._get_fallback_encoding()
elif collection.mode == 'w':
path_b = strencode(path)
path_c = path_b
driver_b = collection.driver.encode()
driver_c = driver_b
cogr_driver = exc_wrap_pointer(GDALGetDriverByName(driver_c))
# Our most common use case is the creation of a new data
# file and historically we've assumed that it's a file on
# the local filesystem and queryable via os.path.
#
# TODO: remove the assumption.
if not os.path.exists(path):
log.debug("File doesn't exist. Creating a new one...")
cogr_ds = gdal_create(cogr_driver, path_c, {})
# TODO: revisit the logic in the following blocks when we
# change the assumption above.
else:
if collection.driver == "GeoJSON" and os.path.exists(path):
# manually remove geojson file as GDAL doesn't do this for us
os.unlink(path)
try:
# attempt to open existing dataset in write mode
cogr_ds = gdal_open_vector(path_c, 1, None, kwargs)
except DriverError:
# failed, attempt to create it
cogr_ds = gdal_create(cogr_driver, path_c, kwargs)
else:
# check capability of creating a new layer in the existing dataset
capability = check_capability_create_layer(cogr_ds)
if GDAL_VERSION_NUM < 2000000 and collection.driver == "GeoJSON":
# GeoJSON driver tells lies about it's capability
capability = False
if not capability or collection.name is None:
# unable to use existing dataset, recreate it
GDALClose(cogr_ds)
cogr_ds = NULL
cogr_ds = gdal_create(cogr_driver, path_c, kwargs)
self.cogr_ds = cogr_ds
# Set the spatial reference system from the crs given to the
# collection constructor. We by-pass the crs_wkt
# properties because they aren't accessible until the layer
# is constructed (later).
try:
col_crs = collection._crs_wkt
if col_crs:
cogr_srs = exc_wrap_pointer(OSRNewSpatialReference(NULL))
proj_b = col_crs.encode('utf-8')
proj_c = proj_b
OSRSetFromUserInput(cogr_srs, proj_c)
osr_set_traditional_axis_mapping_strategy(cogr_srs)
except CPLE_BaseError as exc:
OGRReleaseDataSource(self.cogr_ds)
self.cogr_ds = NULL
self.cogr_layer = NULL
raise CRSError(u"{}".format(exc))
# Determine which encoding to use. The encoding parameter given to
# the collection constructor takes highest precedence, then
# 'iso-8859-1' (for shapefiles), then the system's default encoding
# as last resort.
sysencoding = locale.getpreferredencoding()
self._fileencoding = userencoding or ("Shapefile" in collection.driver and 'iso-8859-1') or sysencoding
if "Shapefile" in collection.driver:
if self._fileencoding:
fileencoding_b = self._fileencoding.upper().encode('utf-8')
fileencoding_c = fileencoding_b
options = CSLSetNameValue(options, "ENCODING", fileencoding_c)
# Does the layer exist already? If so, we delete it.
layer_count = GDALDatasetGetLayerCount(self.cogr_ds)
layer_names = []
for i in range(layer_count):
cogr_layer = GDALDatasetGetLayer(cogr_ds, i)
name_c = OGR_L_GetName(cogr_layer)
name_b = name_c
layer_names.append(name_b.decode('utf-8'))
idx = -1
if isinstance(collection.name, string_types):
if collection.name in layer_names:
idx = layer_names.index(collection.name)
elif isinstance(collection.name, int):
if collection.name >= 0 and collection.name < layer_count:
idx = collection.name
if idx >= 0:
log.debug("Deleted pre-existing layer at %s", collection.name)
GDALDatasetDeleteLayer(self.cogr_ds, idx)
# Create the named layer in the datasource.
name_b = collection.name.encode('utf-8')
name_c = name_b
for k, v in kwargs.items():