-
-
Notifications
You must be signed in to change notification settings - Fork 260
/
shapefile.py
2831 lines (2585 loc) · 110 KB
/
shapefile.py
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
"""
shapefile.py
Provides read and write support for ESRI Shapefiles.
authors: jlawhead<at>geospatialpython.com
maintainer: karim.bahgat.norway<at>gmail.com
Compatible with Python versions 2.7-3.x
"""
__version__ = "2.3.1"
import array
import io
import logging
import os
import sys
import tempfile
import time
import zipfile
from datetime import date
from struct import Struct, calcsize, error, pack, unpack
# Create named logger
logger = logging.getLogger(__name__)
# Module settings
VERBOSE = True
# Constants for shape types
NULL = 0
POINT = 1
POLYLINE = 3
POLYGON = 5
MULTIPOINT = 8
POINTZ = 11
POLYLINEZ = 13
POLYGONZ = 15
MULTIPOINTZ = 18
POINTM = 21
POLYLINEM = 23
POLYGONM = 25
MULTIPOINTM = 28
MULTIPATCH = 31
SHAPETYPE_LOOKUP = {
0: "NULL",
1: "POINT",
3: "POLYLINE",
5: "POLYGON",
8: "MULTIPOINT",
11: "POINTZ",
13: "POLYLINEZ",
15: "POLYGONZ",
18: "MULTIPOINTZ",
21: "POINTM",
23: "POLYLINEM",
25: "POLYGONM",
28: "MULTIPOINTM",
31: "MULTIPATCH",
}
TRIANGLE_STRIP = 0
TRIANGLE_FAN = 1
OUTER_RING = 2
INNER_RING = 3
FIRST_RING = 4
RING = 5
PARTTYPE_LOOKUP = {
0: "TRIANGLE_STRIP",
1: "TRIANGLE_FAN",
2: "OUTER_RING",
3: "INNER_RING",
4: "FIRST_RING",
5: "RING",
}
# Python 2-3 handling
PYTHON3 = sys.version_info[0] == 3
if PYTHON3:
xrange = range
izip = zip
from urllib.error import HTTPError
from urllib.parse import urlparse, urlunparse
from urllib.request import Request, urlopen
else:
from itertools import izip
from urllib2 import HTTPError, Request, urlopen
from urlparse import urlparse, urlunparse
# Helpers
MISSING = [None, ""]
NODATA = -10e38 # as per the ESRI shapefile spec, only used for m-values.
if PYTHON3:
def b(v, encoding="utf-8", encodingErrors="strict"):
if isinstance(v, str):
# For python 3 encode str to bytes.
return v.encode(encoding, encodingErrors)
elif isinstance(v, bytes):
# Already bytes.
return v
elif v is None:
# Since we're dealing with text, interpret None as ""
return b""
else:
# Force string representation.
return str(v).encode(encoding, encodingErrors)
def u(v, encoding="utf-8", encodingErrors="strict"):
if isinstance(v, bytes):
# For python 3 decode bytes to str.
return v.decode(encoding, encodingErrors)
elif isinstance(v, str):
# Already str.
return v
elif v is None:
# Since we're dealing with text, interpret None as ""
return ""
else:
# Force string representation.
return bytes(v).decode(encoding, encodingErrors)
def is_string(v):
return isinstance(v, str)
else:
def b(v, encoding="utf-8", encodingErrors="strict"):
if isinstance(v, unicode):
# For python 2 encode unicode to bytes.
return v.encode(encoding, encodingErrors)
elif isinstance(v, bytes):
# Already bytes.
return v
elif v is None:
# Since we're dealing with text, interpret None as ""
return ""
else:
# Force string representation.
return unicode(v).encode(encoding, encodingErrors)
def u(v, encoding="utf-8", encodingErrors="strict"):
if isinstance(v, bytes):
# For python 2 decode bytes to unicode.
return v.decode(encoding, encodingErrors)
elif isinstance(v, unicode):
# Already unicode.
return v
elif v is None:
# Since we're dealing with text, interpret None as ""
return ""
else:
# Force string representation.
return bytes(v).decode(encoding, encodingErrors)
def is_string(v):
return isinstance(v, basestring)
if sys.version_info[0:2] >= (3, 6):
def pathlike_obj(path):
if isinstance(path, os.PathLike):
return os.fsdecode(path)
else:
return path
else:
def pathlike_obj(path):
if is_string(path):
return path
elif hasattr(path, "__fspath__"):
return path.__fspath__()
else:
try:
return str(path)
except:
return path
# Begin
class _Array(array.array):
"""Converts python tuples to lists of the appropriate type.
Used to unpack different shapefile header parts."""
def __repr__(self):
return str(self.tolist())
def signed_area(coords, fast=False):
"""Return the signed area enclosed by a ring using the linear time
algorithm. A value >= 0 indicates a counter-clockwise oriented ring.
A faster version is possible by setting 'fast' to True, which returns
2x the area, e.g. if you're only interested in the sign of the area.
"""
xs, ys = map(list, list(zip(*coords))[:2]) # ignore any z or m values
xs.append(xs[1])
ys.append(ys[1])
area2 = sum(xs[i] * (ys[i + 1] - ys[i - 1]) for i in range(1, len(coords)))
if fast:
return area2
else:
return area2 / 2.0
def is_cw(coords):
"""Returns True if a polygon ring has clockwise orientation, determined
by a negatively signed area.
"""
area2 = signed_area(coords, fast=True)
return area2 < 0
def rewind(coords):
"""Returns the input coords in reversed order."""
return list(reversed(coords))
def ring_bbox(coords):
"""Calculates and returns the bounding box of a ring."""
xs, ys = zip(*coords)
bbox = min(xs), min(ys), max(xs), max(ys)
return bbox
def bbox_overlap(bbox1, bbox2):
"""Tests whether two bounding boxes overlap, returning a boolean"""
xmin1, ymin1, xmax1, ymax1 = bbox1
xmin2, ymin2, xmax2, ymax2 = bbox2
overlap = xmin1 <= xmax2 and xmax1 >= xmin2 and ymin1 <= ymax2 and ymax1 >= ymin2
return overlap
def bbox_contains(bbox1, bbox2):
"""Tests whether bbox1 fully contains bbox2, returning a boolean"""
xmin1, ymin1, xmax1, ymax1 = bbox1
xmin2, ymin2, xmax2, ymax2 = bbox2
contains = xmin1 < xmin2 and xmax1 > xmax2 and ymin1 < ymin2 and ymax1 > ymax2
return contains
def ring_contains_point(coords, p):
"""Fast point-in-polygon crossings algorithm, MacMartin optimization.
Adapted from code by Eric Haynes
http://www.realtimerendering.com/resources/GraphicsGems//gemsiv/ptpoly_haines/ptinpoly.c
Original description:
Shoot a test ray along +X axis. The strategy, from MacMartin, is to
compare vertex Y values to the testing point's Y and quickly discard
edges which are entirely to one side of the test ray.
"""
tx, ty = p
# get initial test bit for above/below X axis
vtx0 = coords[0]
yflag0 = vtx0[1] >= ty
inside_flag = False
for vtx1 in coords[1:]:
yflag1 = vtx1[1] >= ty
# check if endpoints straddle (are on opposite sides) of X axis
# (i.e. the Y's differ); if so, +X ray could intersect this edge.
if yflag0 != yflag1:
xflag0 = vtx0[0] >= tx
# check if endpoints are on same side of the Y axis (i.e. X's
# are the same); if so, it's easy to test if edge hits or misses.
if xflag0 == (vtx1[0] >= tx):
# if edge's X values both right of the point, must hit
if xflag0:
inside_flag = not inside_flag
else:
# compute intersection of pgon segment with +X ray, note
# if >= point's X; if so, the ray hits it.
if (
vtx1[0] - (vtx1[1] - ty) * (vtx0[0] - vtx1[0]) / (vtx0[1] - vtx1[1])
) >= tx:
inside_flag = not inside_flag
# move to next pair of vertices, retaining info as possible
yflag0 = yflag1
vtx0 = vtx1
return inside_flag
def ring_sample(coords, ccw=False):
"""Return a sample point guaranteed to be within a ring, by efficiently
finding the first centroid of a coordinate triplet whose orientation
matches the orientation of the ring and passes the point-in-ring test.
The orientation of the ring is assumed to be clockwise, unless ccw
(counter-clockwise) is set to True.
"""
triplet = []
def itercoords():
# iterate full closed ring
for p in coords:
yield p
# finally, yield the second coordinate to the end to allow checking the last triplet
yield coords[1]
for p in itercoords():
# add point to triplet (but not if duplicate)
if p not in triplet:
triplet.append(p)
# new triplet, try to get sample
if len(triplet) == 3:
# check that triplet does not form a straight line (not a triangle)
is_straight_line = (triplet[0][1] - triplet[1][1]) * (
triplet[0][0] - triplet[2][0]
) == (triplet[0][1] - triplet[2][1]) * (triplet[0][0] - triplet[1][0])
if not is_straight_line:
# get triplet orientation
closed_triplet = triplet + [triplet[0]]
triplet_ccw = not is_cw(closed_triplet)
# check that triplet has the same orientation as the ring (means triangle is inside the ring)
if ccw == triplet_ccw:
# get triplet centroid
xs, ys = zip(*triplet)
xmean, ymean = sum(xs) / 3.0, sum(ys) / 3.0
# check that triplet centroid is truly inside the ring
if ring_contains_point(coords, (xmean, ymean)):
return xmean, ymean
# failed to get sample point from this triplet
# remove oldest triplet coord to allow iterating to next triplet
triplet.pop(0)
else:
raise Exception("Unexpected error: Unable to find a ring sample point.")
def ring_contains_ring(coords1, coords2):
"""Returns True if all vertexes in coords2 are fully inside coords1."""
return all((ring_contains_point(coords1, p2) for p2 in coords2))
def organize_polygon_rings(rings, return_errors=None):
"""Organize a list of coordinate rings into one or more polygons with holes.
Returns a list of polygons, where each polygon is composed of a single exterior
ring, and one or more interior holes. If a return_errors dict is provided (optional),
any errors encountered will be added to it.
Rings must be closed, and cannot intersect each other (non-self-intersecting polygon).
Rings are determined as exteriors if they run in clockwise direction, or interior
holes if they run in counter-clockwise direction. This method is used to construct
GeoJSON (multi)polygons from the shapefile polygon shape type, which does not
explicitly store the structure of the polygons beyond exterior/interior ring orientation.
"""
# first iterate rings and classify as exterior or hole
exteriors = []
holes = []
for ring in rings:
# shapefile format defines a polygon as a sequence of rings
# where exterior rings are clockwise, and holes counterclockwise
if is_cw(ring):
# ring is exterior
exteriors.append(ring)
else:
# ring is a hole
holes.append(ring)
# if only one exterior, then all holes belong to that exterior
if len(exteriors) == 1:
# exit early
poly = [exteriors[0]] + holes
polys = [poly]
return polys
# multiple exteriors, ie multi-polygon, have to group holes with correct exterior
# shapefile format does not specify which holes belong to which exteriors
# so have to do efficient multi-stage checking of hole-to-exterior containment
elif len(exteriors) > 1:
# exit early if no holes
if not holes:
polys = []
for ext in exteriors:
poly = [ext]
polys.append(poly)
return polys
# first determine each hole's candidate exteriors based on simple bbox contains test
hole_exteriors = dict([(hole_i, []) for hole_i in xrange(len(holes))])
exterior_bboxes = [ring_bbox(ring) for ring in exteriors]
for hole_i in hole_exteriors.keys():
hole_bbox = ring_bbox(holes[hole_i])
for ext_i, ext_bbox in enumerate(exterior_bboxes):
if bbox_contains(ext_bbox, hole_bbox):
hole_exteriors[hole_i].append(ext_i)
# then, for holes with still more than one possible exterior, do more detailed hole-in-ring test
for hole_i, exterior_candidates in hole_exteriors.items():
if len(exterior_candidates) > 1:
# get hole sample point
ccw = not is_cw(holes[hole_i])
hole_sample = ring_sample(holes[hole_i], ccw=ccw)
# collect new exterior candidates
new_exterior_candidates = []
for ext_i in exterior_candidates:
# check that hole sample point is inside exterior
hole_in_exterior = ring_contains_point(
exteriors[ext_i], hole_sample
)
if hole_in_exterior:
new_exterior_candidates.append(ext_i)
# set new exterior candidates
hole_exteriors[hole_i] = new_exterior_candidates
# if still holes with more than one possible exterior, means we have an exterior hole nested inside another exterior's hole
for hole_i, exterior_candidates in hole_exteriors.items():
if len(exterior_candidates) > 1:
# exterior candidate with the smallest area is the hole's most immediate parent
ext_i = sorted(
exterior_candidates,
key=lambda x: abs(signed_area(exteriors[x], fast=True)),
)[0]
hole_exteriors[hole_i] = [ext_i]
# separate out holes that are orphaned (not contained by any exterior)
orphan_holes = []
for hole_i, exterior_candidates in list(hole_exteriors.items()):
if not exterior_candidates:
orphan_holes.append(hole_i)
del hole_exteriors[hole_i]
continue
# each hole should now only belong to one exterior, group into exterior-holes polygons
polys = []
for ext_i, ext in enumerate(exteriors):
poly = [ext]
# find relevant holes
poly_holes = []
for hole_i, exterior_candidates in list(hole_exteriors.items()):
# hole is relevant if previously matched with this exterior
if exterior_candidates[0] == ext_i:
poly_holes.append(holes[hole_i])
poly += poly_holes
polys.append(poly)
# add orphan holes as exteriors
for hole_i in orphan_holes:
ext = holes[hole_i]
# add as single exterior without any holes
poly = [ext]
polys.append(poly)
if orphan_holes and return_errors is not None:
return_errors["polygon_orphaned_holes"] = len(orphan_holes)
return polys
# no exteriors, be nice and assume due to incorrect winding order
else:
if return_errors is not None:
return_errors["polygon_only_holes"] = len(holes)
exteriors = holes
# add as single exterior without any holes
polys = [[ext] for ext in exteriors]
return polys
class Shape(object):
def __init__(
self, shapeType=NULL, points=None, parts=None, partTypes=None, oid=None
):
"""Stores the geometry of the different shape types
specified in the Shapefile spec. Shape types are
usually point, polyline, or polygons. Every shape type
except the "Null" type contains points at some level for
example vertices in a polygon. If a shape type has
multiple shapes containing points within a single
geometry record then those shapes are called parts. Parts
are designated by their starting index in geometry record's
list of shapes. For MultiPatch geometry, partTypes designates
the patch type of each of the parts.
"""
self.shapeType = shapeType
self.points = points or []
self.parts = parts or []
if partTypes:
self.partTypes = partTypes
# and a dict to silently record any errors encountered
self._errors = {}
# add oid
if oid is not None:
self.__oid = oid
else:
self.__oid = -1
@property
def __geo_interface__(self):
if self.shapeType in [POINT, POINTM, POINTZ]:
# point
if len(self.points) == 0:
# the shape has no coordinate information, i.e. is 'empty'
# the geojson spec does not define a proper null-geometry type
# however, it does allow geometry types with 'empty' coordinates to be interpreted as null-geometries
return {"type": "Point", "coordinates": tuple()}
else:
return {"type": "Point", "coordinates": tuple(self.points[0])}
elif self.shapeType in [MULTIPOINT, MULTIPOINTM, MULTIPOINTZ]:
if len(self.points) == 0:
# the shape has no coordinate information, i.e. is 'empty'
# the geojson spec does not define a proper null-geometry type
# however, it does allow geometry types with 'empty' coordinates to be interpreted as null-geometries
return {"type": "MultiPoint", "coordinates": []}
else:
# multipoint
return {
"type": "MultiPoint",
"coordinates": [tuple(p) for p in self.points],
}
elif self.shapeType in [POLYLINE, POLYLINEM, POLYLINEZ]:
if len(self.parts) == 0:
# the shape has no coordinate information, i.e. is 'empty'
# the geojson spec does not define a proper null-geometry type
# however, it does allow geometry types with 'empty' coordinates to be interpreted as null-geometries
return {"type": "LineString", "coordinates": []}
elif len(self.parts) == 1:
# linestring
return {
"type": "LineString",
"coordinates": [tuple(p) for p in self.points],
}
else:
# multilinestring
ps = None
coordinates = []
for part in self.parts:
if ps is None:
ps = part
continue
else:
coordinates.append([tuple(p) for p in self.points[ps:part]])
ps = part
else:
coordinates.append([tuple(p) for p in self.points[part:]])
return {"type": "MultiLineString", "coordinates": coordinates}
elif self.shapeType in [POLYGON, POLYGONM, POLYGONZ]:
if len(self.parts) == 0:
# the shape has no coordinate information, i.e. is 'empty'
# the geojson spec does not define a proper null-geometry type
# however, it does allow geometry types with 'empty' coordinates to be interpreted as null-geometries
return {"type": "Polygon", "coordinates": []}
else:
# get all polygon rings
rings = []
for i in xrange(len(self.parts)):
# get indexes of start and end points of the ring
start = self.parts[i]
try:
end = self.parts[i + 1]
except IndexError:
end = len(self.points)
# extract the points that make up the ring
ring = [tuple(p) for p in self.points[start:end]]
rings.append(ring)
# organize rings into list of polygons, where each polygon is defined as list of rings.
# the first ring is the exterior and any remaining rings are holes (same as GeoJSON).
polys = organize_polygon_rings(rings, self._errors)
# if VERBOSE is True, issue detailed warning about any shape errors
# encountered during the Shapefile to GeoJSON conversion
if VERBOSE and self._errors:
header = "Possible issue encountered when converting Shape #{} to GeoJSON: ".format(
self.oid
)
orphans = self._errors.get("polygon_orphaned_holes", None)
if orphans:
msg = (
header
+ "Shapefile format requires that all polygon interior holes be contained by an exterior ring, \
but the Shape contained interior holes (defined by counter-clockwise orientation in the shapefile format) that were \
orphaned, i.e. not contained by any exterior rings. The rings were still included but were \
encoded as GeoJSON exterior rings instead of holes."
)
logger.warning(msg)
only_holes = self._errors.get("polygon_only_holes", None)
if only_holes:
msg = (
header
+ "Shapefile format requires that polygons contain at least one exterior ring, \
but the Shape was entirely made up of interior holes (defined by counter-clockwise orientation in the shapefile format). The rings were \
still included but were encoded as GeoJSON exterior rings instead of holes."
)
logger.warning(msg)
# return as geojson
if len(polys) == 1:
return {"type": "Polygon", "coordinates": polys[0]}
else:
return {"type": "MultiPolygon", "coordinates": polys}
else:
raise Exception(
'Shape type "%s" cannot be represented as GeoJSON.'
% SHAPETYPE_LOOKUP[self.shapeType]
)
@staticmethod
def _from_geojson(geoj):
# create empty shape
shape = Shape()
# set shapeType
geojType = geoj["type"] if geoj else "Null"
if geojType == "Null":
shapeType = NULL
elif geojType == "Point":
shapeType = POINT
elif geojType == "LineString":
shapeType = POLYLINE
elif geojType == "Polygon":
shapeType = POLYGON
elif geojType == "MultiPoint":
shapeType = MULTIPOINT
elif geojType == "MultiLineString":
shapeType = POLYLINE
elif geojType == "MultiPolygon":
shapeType = POLYGON
else:
raise Exception("Cannot create Shape from GeoJSON type '%s'" % geojType)
shape.shapeType = shapeType
# set points and parts
if geojType == "Point":
shape.points = [geoj["coordinates"]]
shape.parts = [0]
elif geojType in ("MultiPoint", "LineString"):
shape.points = geoj["coordinates"]
shape.parts = [0]
elif geojType in ("Polygon"):
points = []
parts = []
index = 0
for i, ext_or_hole in enumerate(geoj["coordinates"]):
# although the latest GeoJSON spec states that exterior rings should have
# counter-clockwise orientation, we explicitly check orientation since older
# GeoJSONs might not enforce this.
if i == 0 and not is_cw(ext_or_hole):
# flip exterior direction
ext_or_hole = rewind(ext_or_hole)
elif i > 0 and is_cw(ext_or_hole):
# flip hole direction
ext_or_hole = rewind(ext_or_hole)
points.extend(ext_or_hole)
parts.append(index)
index += len(ext_or_hole)
shape.points = points
shape.parts = parts
elif geojType in ("MultiLineString"):
points = []
parts = []
index = 0
for linestring in geoj["coordinates"]:
points.extend(linestring)
parts.append(index)
index += len(linestring)
shape.points = points
shape.parts = parts
elif geojType in ("MultiPolygon"):
points = []
parts = []
index = 0
for polygon in geoj["coordinates"]:
for i, ext_or_hole in enumerate(polygon):
# although the latest GeoJSON spec states that exterior rings should have
# counter-clockwise orientation, we explicitly check orientation since older
# GeoJSONs might not enforce this.
if i == 0 and not is_cw(ext_or_hole):
# flip exterior direction
ext_or_hole = rewind(ext_or_hole)
elif i > 0 and is_cw(ext_or_hole):
# flip hole direction
ext_or_hole = rewind(ext_or_hole)
points.extend(ext_or_hole)
parts.append(index)
index += len(ext_or_hole)
shape.points = points
shape.parts = parts
return shape
@property
def oid(self):
"""The index position of the shape in the original shapefile"""
return self.__oid
@property
def shapeTypeName(self):
return SHAPETYPE_LOOKUP[self.shapeType]
def __repr__(self):
return "Shape #{}: {}".format(self.__oid, self.shapeTypeName)
class _Record(list):
"""
A class to hold a record. Subclasses list to ensure compatibility with
former work and to reuse all the optimizations of the builtin list.
In addition to the list interface, the values of the record
can also be retrieved using the field's name. For example if the dbf contains
a field ID at position 0, the ID can be retrieved with the position, the field name
as a key, or the field name as an attribute.
>>> # Create a Record with one field, normally the record is created by the Reader class
>>> r = _Record({'ID': 0}, [0])
>>> print(r[0])
>>> print(r['ID'])
>>> print(r.ID)
"""
def __init__(self, field_positions, values, oid=None):
"""
A Record should be created by the Reader class
:param field_positions: A dict mapping field names to field positions
:param values: A sequence of values
:param oid: The object id, an int (optional)
"""
self.__field_positions = field_positions
if oid is not None:
self.__oid = oid
else:
self.__oid = -1
list.__init__(self, values)
def __getattr__(self, item):
"""
__getattr__ is called if an attribute is used that does
not exist in the normal sense. For example r=Record(...), r.ID
calls r.__getattr__('ID'), but r.index(5) calls list.index(r, 5)
:param item: The field name, used as attribute
:return: Value of the field
:raises: AttributeError, if item is not a field of the shapefile
and IndexError, if the field exists but the field's
corresponding value in the Record does not exist
"""
try:
if item == "__setstate__": # Prevent infinite loop from copy.deepcopy()
raise AttributeError("_Record does not implement __setstate__")
index = self.__field_positions[item]
return list.__getitem__(self, index)
except KeyError:
raise AttributeError("{} is not a field name".format(item))
except IndexError:
raise IndexError(
"{} found as a field but not enough values available.".format(item)
)
def __setattr__(self, key, value):
"""
Sets a value of a field attribute
:param key: The field name
:param value: the value of that field
:return: None
:raises: AttributeError, if key is not a field of the shapefile
"""
if key.startswith("_"): # Prevent infinite loop when setting mangled attribute
return list.__setattr__(self, key, value)
try:
index = self.__field_positions[key]
return list.__setitem__(self, index, value)
except KeyError:
raise AttributeError("{} is not a field name".format(key))
def __getitem__(self, item):
"""
Extends the normal list item access with
access using a fieldname
For example r['ID'], r[0]
:param item: Either the position of the value or the name of a field
:return: the value of the field
"""
try:
return list.__getitem__(self, item)
except TypeError:
try:
index = self.__field_positions[item]
except KeyError:
index = None
if index is not None:
return list.__getitem__(self, index)
else:
raise IndexError('"{}" is not a field name and not an int'.format(item))
def __setitem__(self, key, value):
"""
Extends the normal list item access with
access using a fieldname
For example r['ID']=2, r[0]=2
:param key: Either the position of the value or the name of a field
:param value: the new value of the field
"""
try:
return list.__setitem__(self, key, value)
except TypeError:
index = self.__field_positions.get(key)
if index is not None:
return list.__setitem__(self, index, value)
else:
raise IndexError("{} is not a field name and not an int".format(key))
@property
def oid(self):
"""The index position of the record in the original shapefile"""
return self.__oid
def as_dict(self, date_strings=False):
"""
Returns this Record as a dictionary using the field names as keys
:return: dict
"""
dct = dict((f, self[i]) for f, i in self.__field_positions.items())
if date_strings:
for k, v in dct.items():
if isinstance(v, date):
dct[k] = "{:04d}{:02d}{:02d}".format(v.year, v.month, v.day)
return dct
def __repr__(self):
return "Record #{}: {}".format(self.__oid, list(self))
def __dir__(self):
"""
Helps to show the field names in an interactive environment like IPython.
See: http://ipython.readthedocs.io/en/stable/config/integrating.html
:return: List of method names and fields
"""
default = list(
dir(type(self))
) # default list methods and attributes of this class
fnames = list(
self.__field_positions.keys()
) # plus field names (random order if Python version < 3.6)
return default + fnames
def __eq__(self, other):
if isinstance(other, self.__class__):
if self.__field_positions != other.__field_positions:
return False
return list.__eq__(self, other)
class ShapeRecord(object):
"""A ShapeRecord object containing a shape along with its attributes.
Provides the GeoJSON __geo_interface__ to return a Feature dictionary."""
def __init__(self, shape=None, record=None):
self.shape = shape
self.record = record
@property
def __geo_interface__(self):
return {
"type": "Feature",
"properties": self.record.as_dict(date_strings=True),
"geometry": None
if self.shape.shapeType == NULL
else self.shape.__geo_interface__,
}
class Shapes(list):
"""A class to hold a list of Shape objects. Subclasses list to ensure compatibility with
former work and to reuse all the optimizations of the builtin list.
In addition to the list interface, this also provides the GeoJSON __geo_interface__
to return a GeometryCollection dictionary."""
def __repr__(self):
return "Shapes: {}".format(list(self))
@property
def __geo_interface__(self):
# Note: currently this will fail if any of the shapes are null-geometries
# could be fixed by storing the shapefile shapeType upon init, returning geojson type with empty coords
collection = {
"type": "GeometryCollection",
"geometries": [shape.__geo_interface__ for shape in self],
}
return collection
class ShapeRecords(list):
"""A class to hold a list of ShapeRecord objects. Subclasses list to ensure compatibility with
former work and to reuse all the optimizations of the builtin list.
In addition to the list interface, this also provides the GeoJSON __geo_interface__
to return a FeatureCollection dictionary."""
def __repr__(self):
return "ShapeRecords: {}".format(list(self))
@property
def __geo_interface__(self):
collection = {
"type": "FeatureCollection",
"features": [shaperec.__geo_interface__ for shaperec in self],
}
return collection
class ShapefileException(Exception):
"""An exception to handle shapefile specific problems."""
pass
class Reader(object):
"""Reads the three files of a shapefile as a unit or
separately. If one of the three files (.shp, .shx,
.dbf) is missing no exception is thrown until you try
to call a method that depends on that particular file.
The .shx index file is used if available for efficiency
but is not required to read the geometry from the .shp
file. The "shapefile" argument in the constructor is the
name of the file you want to open, and can be the path
to a shapefile on a local filesystem, inside a zipfile,
or a url.
You can instantiate a Reader without specifying a shapefile
and then specify one later with the load() method.
Only the shapefile headers are read upon loading. Content
within each file is only accessed when required and as
efficiently as possible. Shapefiles are usually not large
but they can be.
"""
def __init__(self, *args, **kwargs):
self.shp = None
self.shx = None
self.dbf = None
self._files_to_close = []
self.shapeName = "Not specified"
self._offsets = []
self.shpLength = None
self.numRecords = None
self.numShapes = None
self.fields = []
self.__dbfHdrLength = 0
self.__fieldLookup = {}
self.encoding = kwargs.pop("encoding", "utf-8")
self.encodingErrors = kwargs.pop("encodingErrors", "strict")
# See if a shapefile name was passed as the first argument
if len(args) > 0:
path = pathlike_obj(args[0])
if is_string(path):
if ".zip" in path:
# Shapefile is inside a zipfile
if path.count(".zip") > 1:
# Multiple nested zipfiles
raise ShapefileException(
"Reading from multiple nested zipfiles is not supported: %s"
% path
)
# Split into zipfile and shapefile paths
if path.endswith(".zip"):
zpath = path
shapefile = None
else:
zpath = path[: path.find(".zip") + 4]
shapefile = path[path.find(".zip") + 4 + 1 :]
# Create a zip file handle
if zpath.startswith("http"):
# Zipfile is from a url
# Download to a temporary url and treat as normal zipfile
req = Request(
zpath,
headers={
"User-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36"
},
)
resp = urlopen(req)
# write zipfile data to a read+write tempfile and use as source, gets deleted when garbage collected
zipfileobj = tempfile.NamedTemporaryFile(
mode="w+b", suffix=".zip", delete=True
)
zipfileobj.write(resp.read())
zipfileobj.seek(0)
else:
# Zipfile is from a file