-
Notifications
You must be signed in to change notification settings - Fork 78
/
shapefile.py
1240 lines (1015 loc) · 32.8 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
"""A Pure Python Shapefile Reader and Writer
This module is self-contained and does not require pysal. It returns and expects
dictionary-based data structures. It should be wrapped into your native data structures.
Contact:
Charles Schmidt
GeoDa Center
Arizona State University
Tempe, AZ
http://geodacenter.asu.edu
"""
__author__ = "Charles R Schmidt <schmidtc@gmail.com>"
from struct import calcsize, unpack, pack
from itertools import islice
import array
import sys
import io
from typing import Union
if sys.byteorder == "little":
SYS_BYTE_ORDER = "<"
else:
SYS_BYTE_ORDER = ">"
STRUCT_ITEMSIZE = {}
STRUCT_ITEMSIZE["i"] = calcsize("i")
STRUCT_ITEMSIZE["d"] = calcsize("d")
__all__ = ["shp_file", "shx_file"]
# SHAPEFILE Globals
def struct2arrayinfo(struct: tuple) -> list:
struct = list(struct)
names = [x[0] for x in struct]
types = [x[1] for x in struct]
orders = [x[2] for x in struct]
lname, ltype, lorder = struct.pop(0)
groups = {}
g = 0
groups[g] = {
"names": [lname],
"size": STRUCT_ITEMSIZE[ltype],
"fmt": ltype,
"order": lorder,
}
while struct:
name, type, order = struct.pop(0)
if order == lorder:
groups[g]["names"].append(name)
groups[g]["size"] += STRUCT_ITEMSIZE[type]
groups[g]["fmt"] += type
else:
g += 1
groups[g] = {
"names": [name],
"size": STRUCT_ITEMSIZE[type],
"fmt": type,
"order": order,
}
lname, ltype, lorder = name, type, order
return [groups[x] for x in range(g + 1)]
HEADERSTRUCT = (
("File Code", "i", ">"),
("Unused0", "i", ">"),
("Unused1", "i", ">"),
("Unused2", "i", ">"),
("Unused3", "i", ">"),
("Unused4", "i", ">"),
("File Length", "i", ">"),
("Version", "i", "<"),
("Shape Type", "i", "<"),
("BBOX Xmin", "d", "<"),
("BBOX Ymin", "d", "<"),
("BBOX Xmax", "d", "<"),
("BBOX Ymax", "d", "<"),
("BBOX Zmin", "d", "<"),
("BBOX Zmax", "d", "<"),
("BBOX Mmin", "d", "<"),
("BBOX Mmax", "d", "<"),
)
UHEADERSTRUCT = struct2arrayinfo(HEADERSTRUCT)
RHEADERSTRUCT = (("Record Number", "i", ">"), ("Content Length", "i", ">"))
URHEADERSTRUCT = struct2arrayinfo(RHEADERSTRUCT)
def noneMax(a: Union[float, None], b: Union[float, None]) -> float:
if a is None:
return b
if b is None:
return a
return max(a, b)
def noneMin(a: Union[float, None], b: Union[float, None]) -> float:
if a is None:
return b
if b is None:
return a
return min(a, b)
def _unpackDict(structure, fileObj):
"""Utility function that requires a tuple of tuples that
describe the element structure.
Parameters
----------
structure : tuple
A tuple of tuples in the form:
``(('FieldName 1','type','byteOrder'),('FieldName 2','type','byteOrder'))``.
fileObj : file
An open file at the correct position.
Returns
-------
d : dict
Dictionary in the form: ``{'FieldName 1': value, 'FieldName 2': value}``.
Notes
-----
The file is at new position.
Examples
--------
>>> import libpysal
>>> _unpackDict(
... UHEADERSTRUCT,
... open(
... libpysal.examples.get_path('10740.shx'), 'rb')
... ) == \
... {
... 'BBOX Xmax': -105.29012,
... 'BBOX Ymax': 36.219799000000002,
... 'BBOX Mmax': 0.0,
... 'BBOX Zmin': 0.0,
... 'BBOX Mmin': 0.0,
... 'File Code': 9994,
... 'BBOX Ymin': 34.259672000000002,
... 'BBOX Xmin': -107.62651,
... 'Unused0': 0,
... 'Unused1': 0,
... 'Unused2': 0,
... 'Unused3': 0,
... 'Unused4': 0,
... 'Version': 1000,
... 'BBOX Zmax': 0.0,
... 'Shape Type': 5,
... 'File Length': 830
... }
True
"""
d = {}
for struct in structure:
items = unpack(struct["order"] + struct["fmt"], fileObj.read(struct["size"]))
for i, name in enumerate(struct["names"]):
d[name] = items[i]
return d
def _unpackDict2(d, structure, fileObj):
"""Utility Function, used arrays instead from struct.
Parameters
----------
d : dict
Dictionary in to be updated.
structure : tuple
A tuple of tuples in the form:
``(('FieldName 1','type','byteOrder'),('FieldName 2','type','byteOrder'))``.
fileObj : file
An open file at the correct position.
Returns
-------
d : dict
The updated dictionary.
"""
for name, dtype, order in structure:
dtype, n = dtype
result = array.array(dtype)
result.frombytes(fileObj.read(result.itemsize * n))
if order != SYS_BYTE_ORDER:
result.byteswap()
d[name] = result.tolist()
return d
def _packDict(structure, d) -> str:
"""Utility Function for packing a dictionary with byte strings.
Parameters
----------
structure : tuple
A tuple of tuples in the form:
``(('FieldName 1','type','byteOrder'),('FieldName 2','type','byteOrder'))``.
d : dict
Dictionary in the form: ``{'FieldName 1': value, 'FieldName 2': value}``.
Examples
--------
>>> s = _packDict(
... (('FieldName 1', 'i', '<'), ('FieldName 2', 'i', '<')),
... {'FieldName 1': 1, 'FieldName 2': 2}
... )
>>> s == pack('<ii', 1, 2)
True
>>> unpack('<ii', s)
(1, 2)
"""
string = b""
for name, dtype, order in structure:
if len(dtype) > 1:
string += pack(order + dtype, *d[name])
else:
string += pack(order + dtype, d[name])
return string
class shp_file:
"""Reads and writes the SHP compenent of a shapefile.
Parameters
----------
filename : str
The name of the file to create.
mode : str
The mode for file interaction, either ``'r'`` (read)
or ``'w'`` (write). Default is ``'r'``.
shape_type : str
Must be one of the following: ``'POINT'``, ``'POINTZ'``, ``'POINTM'``,
``'ARC'``, ``'ARCZ'``, ``'ARCM'``, ``'POLYGON'``, ``'POLYGONZ'``,
``'POLYGONM'``, ``'MULTIPOINT'``, ``'MULTIPOINTZ'``, ``'MULTIPOINTM'``,
``'MULTIPATCH'``. Default is ``None``.
Attributes
----------
header : dict
Contents of the SHP header. For contents see ``HEADERSTRUCT``.
shape : int
See ``SHAPE_TYPES`` and ``TYPE_DISPATCH``.
Examples
--------
>>> import libpysal
>>> shp = shp_file(libpysal.examples.get_path('10740.shp'))
>>> shp.header == {
... 'BBOX Xmax': -105.29012,
... 'BBOX Ymax': 36.219799000000002,
... 'BBOX Mmax': 0.0,
... 'BBOX Zmin': 0.0,
... 'BBOX Mmin': 0.0,
... 'File Code': 9994,
... 'BBOX Ymin': 34.259672000000002,
... 'BBOX Xmin': -107.62651,
... 'Unused0': 0,
... 'Unused1': 0,
... 'Unused2': 0,
... 'Unused3': 0,
... 'Unused4': 0,
... 'Version': 1000,
... 'BBOX Zmax': 0.0,
... 'Shape Type': 5,
... 'File Length': 260534
... }
True
>>> len(shp)
195
Notes
-----
The header of both the SHP and SHX files are indentical.
"""
SHAPE_TYPES = {
"POINT": 1,
"ARC": 3,
"POLYGON": 5,
"MULTIPOINT": 8,
"POINTZ": 11,
"ARCZ": 13,
"POLYGONZ": 15,
"MULTIPOINTZ": 18,
"POINTM": 21,
"ARCM": 23,
"POLYGONM": 25,
"MULTIPOINTM": 28,
"MULTIPATCH": 31,
}
def __iswritable(self) -> bool:
"""
Raises
------
IOError
Raised when a bad file name is passed in.
"""
try:
assert self.__mode == "w"
except AssertionError:
raise IOError("[Errno 9] Bad file descriptor.")
return True
def __isreadable(self) -> bool:
"""
Raises
------
IOError
Raised when a bad file name is passed in.
"""
try:
assert self.__mode == "r"
except AssertionError:
raise IOError("[Errno 9] Bad file descriptor.")
return True
def __init__(self, fileName, mode="r", shape_type=None):
"""
Raises
------
Exception
Raised when an invalid shape type is passed in.
Exception
Raised when an invalid mode is passed in.
"""
self.__mode = mode
if (
fileName.lower().endswith(".shp")
or fileName.lower().endswith(".shx")
or fileName.lower().endswith(".dbf")
):
fileName = fileName[:-4]
self.fileName = fileName
if mode == "r":
self._open_shp_file()
elif mode == "w":
if shape_type not in self.SHAPE_TYPES:
raise Exception("Attempt to create shp/shx file of invalid type.")
self._create_shp_file(shape_type)
else:
raise Exception("Only 'w' and 'r' modes are supported.")
def _open_shp_file(self):
"""Opens a shp/shx file."""
self.__isreadable()
fileName = self.fileName
self.fileObj = open(fileName + ".shp", "rb")
self._shx = shx_file(fileName)
self.header = _unpackDict(UHEADERSTRUCT, self.fileObj)
self.shape = TYPE_DISPATCH[self.header["Shape Type"]]
self.__lastShape = 0
# localizing for convenience
self.__numRecords = self._shx.numRecords
# constructing bounding box from header
h = self.header
self.bbox = [h["BBOX Xmin"], h["BBOX Ymin"], h["BBOX Xmax"], h["BBOX Ymax"]]
self.shapeType = self.header["Shape Type"]
def _create_shp_file(self, shape_type: str):
"""Creates a shp/shx file.
Examples
--------
>>> import libpysal, os
>>> shp = shp_file('test', 'w', 'POINT')
>>> p = shp_file(libpysal.examples.get_path('Point.shp'))
>>> for pt in p:
... shp.add_shape(pt)
>>> shp.close()
>>> open('test.shp','rb').read() == open(
... libpysal.examples.get_path('Point.shp'), 'rb'
... ).read()
True
>>> open('test.shx', 'rb').read() == open(
... libpysal.examples.get_path('Point.shx'), 'rb'
... ).read()
True
>>> os.remove('test.shx')
>>> os.remove('test.shp')
"""
self.__iswritable()
fileName = self.fileName
self.fileObj = open(fileName + ".shp", "wb")
self._shx = shx_file(fileName, "w")
self.header = {}
self.header["Shape Type"] = self.SHAPE_TYPES[shape_type]
self.header["Version"] = 1000
self.header["Unused0"] = 0
self.header["Unused1"] = 0
self.header["Unused2"] = 0
self.header["Unused3"] = 0
self.header["Unused4"] = 0
self.header["File Code"] = 9994
self.__file_Length = 100
self.header["File Length"] = 0
self.header["BBOX Xmax"] = None
self.header["BBOX Ymax"] = None
self.header["BBOX Mmax"] = None
self.header["BBOX Zmax"] = None
self.header["BBOX Xmin"] = None
self.header["BBOX Ymin"] = None
self.header["BBOX Mmin"] = None
self.header["BBOX Zmin"] = None
self.shape = TYPE_DISPATCH[self.header["Shape Type"]]
# self.__numRecords = self._shx.numRecords
def __len__(self) -> int:
return self.__numRecords
def __iter__(self):
return self
def type(self) -> str:
return self.shape.String_Type
def __next__(self) -> int:
"""Returns the next shape in the shapefile.
Raises
------
StopIteration
Raised at the EOF.
Examples
--------
>>> import libpysal
>>> list(shp_file(libpysal.examples.get_path('Point.shp'))) == [
... {
... 'Y': -0.25904661905760773,
... 'X': -0.00068176617532103578,
... 'Shape Type': 1
... },
... {
... 'Y': -0.25630328607387354,
... 'X': 0.11697145363360706,
... 'Shape Type': 1
... },
... {
... 'Y': -0.33930131004366804,
... 'X': 0.05043668122270728,
... 'Shape Type': 1
... },
... {
... 'Y': -0.41266375545851519,
... 'X': -0.041266375545851552,
... 'Shape Type': 1
... },
... {
... 'Y': -0.44017467248908293,
... 'X': -0.011462882096069604,
... 'Shape Type': 1
... },
... {
... 'Y': -0.46080786026200882,
... 'X': 0.027510917030567628,
... 'Shape Type': 1
... },
... {
... 'Y': -0.45851528384279472,
... 'X': 0.075655021834060809,
... 'Shape Type': 1
... },
... {
... 'Y': -0.43558951965065495,
... 'X': 0.11233624454148461,
... 'Shape Type': 1
... },
... {
... 'Y': -0.40578602620087334,
... 'X': 0.13984716157205224,
... 'Shape Type': 1
... }
... ]
True
"""
self.__isreadable()
nextShape = self.__lastShape
if nextShape == self._shx.numRecords:
self.__lastShape = 0
raise StopIteration
else:
self.__lastShape = nextShape + 1
return self.get_shape(nextShape)
def __seek(self, pos: int):
if pos != self.fileObj.tell():
self.fileObj.seek(pos)
def __read(self, pos: int, size: int):
self.__isreadable()
if pos != self.fileObj.tell():
self.fileObj.seek(pos)
return self.fileObj.read(size)
def get_shape(self, shpId: int) -> dict:
self.__isreadable()
if shpId + 1 > self.__numRecords:
raise IndexError
fPosition, byts = self._shx.index[shpId]
self.__seek(fPosition)
# the index does not include the 2 byte record header
# (which contains, Record ID and Content Length)
rec_id, con_len = _unpackDict(URHEADERSTRUCT, self.fileObj)
return self.shape.unpack(io.BytesIO(self.fileObj.read(byts)))
# return self.shape.unpack(self.fileObj.read(bytes))
def __update_bbox(self, s: dict):
h = self.header
if s.get("Shape Type") == 1:
h["BBOX Xmax"] = noneMax(h["BBOX Xmax"], s.get("X"))
h["BBOX Ymax"] = noneMax(h["BBOX Ymax"], s.get("Y"))
h["BBOX Mmax"] = noneMax(h["BBOX Mmax"], s.get("M"))
h["BBOX Zmax"] = noneMax(h["BBOX Zmax"], s.get("Z"))
h["BBOX Xmin"] = noneMin(h["BBOX Xmin"], s.get("X"))
h["BBOX Ymin"] = noneMin(h["BBOX Ymin"], s.get("Y"))
h["BBOX Mmin"] = noneMin(h["BBOX Mmin"], s.get("M"))
h["BBOX Zmin"] = noneMin(h["BBOX Zmin"], s.get("Z"))
else:
h["BBOX Xmax"] = noneMax(h["BBOX Xmax"], s.get("BBOX Xmax"))
h["BBOX Ymax"] = noneMax(h["BBOX Ymax"], s.get("BBOX Ymax"))
h["BBOX Mmax"] = noneMax(h["BBOX Mmax"], s.get("BBOX Mmax"))
h["BBOX Zmax"] = noneMax(h["BBOX Zmax"], s.get("BBOX Zmax"))
h["BBOX Xmin"] = noneMin(h["BBOX Xmin"], s.get("BBOX Xmin"))
h["BBOX Ymin"] = noneMin(h["BBOX Ymin"], s.get("BBOX Ymin"))
h["BBOX Mmin"] = noneMin(h["BBOX Mmin"], s.get("BBOX Mmin"))
h["BBOX Zmin"] = noneMin(h["BBOX Zmin"], s.get("BBOX Zmin"))
if not self.shape.HASM:
self.header["BBOX Mmax"] = 0.0
self.header["BBOX Mmin"] = 0.0
if not self.shape.HASZ:
self.header["BBOX Zmax"] = 0.0
self.header["BBOX Zmin"] = 0.0
def add_shape(self, s: dict):
self.__iswritable()
self.__update_bbox(s)
rec = self.shape.pack(s)
con_len = len(rec)
self.__file_Length += con_len + 8
rec_id, pos = self._shx.add_record(con_len)
self.__seek(pos)
self.fileObj.write(pack(">ii", rec_id, con_len // 2))
self.fileObj.write(rec)
def close(self):
self._shx.close(self.header)
if self.__mode == "w":
self.header["File Length"] = self.__file_Length // 2
self.__seek(0)
self.fileObj.write(_packDict(HEADERSTRUCT, self.header))
self.fileObj.close()
class shx_file:
"""Reads and writes the SHX compenent of a shapefile.
Parameters
----------
filename : str
The name of the file to create. Default is ``None``.
The extension is optional, will remove ``'.dbf'``,
``'.shx'``, ``'.shp'`` and append ``'.shx'``.
mode : str
The mode for file interaction. Must be ``'r'`` (read).
Attributes
----------
index : list
Contains the file offset and length of each recond in the SHP component.
numRecords : int
The number of records.
Examples
--------
>>> import libpysal
>>> shx = shx_file(libpysal.examples.get_path('10740.shx'))
>>> shx._header == {
... 'BBOX Xmax': -105.29012,
... 'BBOX Ymax': 36.219799000000002,
... 'BBOX Mmax': 0.0,
... 'BBOX Zmin': 0.0,
... 'BBOX Mmin': 0.0,
... 'File Code': 9994,
... 'BBOX Ymin': 34.259672000000002,
... 'BBOX Xmin': -107.62651,
... 'Unused0': 0,
... 'Unused1': 0,
... 'Unused2': 0,
... 'Unused3': 0,
... 'Unused4': 0,
... 'Version': 1000,
... 'BBOX Zmax': 0.0,
... 'Shape Type': 5,
... 'File Length': 830
... }
True
>>> len(shx.index)
195
>>> shx = shx_file(libpysal.examples.get_path('Point.shx'))
>>> isinstance(shx, shx_file)
True
"""
def __iswritable(self) -> bool:
"""
Raises
------
IOError
Raised when a bad file name is passed in.
"""
try:
assert self.__mode == "w"
except AssertionError:
raise IOError("[Errno 9] Bad file descriptor.")
return True
def __isreadable(self) -> bool:
"""
Raises
------
IOError
Raised when a bad file name is passed in.
"""
try:
assert self.__mode == "r"
except AssertionError:
raise IOError("[Errno 9] Bad file descriptor.")
return True
def __init__(self, fileName=None, mode="r"):
self.__mode = mode
if (
fileName.endswith(".shp")
or fileName.endswith(".shx")
or fileName.endswith(".dbf")
):
fileName = fileName[:-4]
self.fileName = fileName
if mode == "r":
self._open_shx_file()
elif mode == "w":
self._create_shx_file()
def _open_shx_file(self):
"""Opens the SHX file."""
self.__isreadable()
self.fileObj = open(self.fileName + ".shx", "rb")
self._header = _unpackDict(UHEADERSTRUCT, self.fileObj)
self.numRecords = numRecords = (self._header["File Length"] - 50) // 4
index = {}
fmt = ">%di" % (2 * numRecords)
size = calcsize(fmt)
dat = unpack(fmt, self.fileObj.read(size))
self.index = [(dat[i] * 2, dat[i + 1] * 2) for i in range(0, len(dat), 2)]
def _create_shx_file(self):
"""Creates the SHX file."""
self.__iswritable()
self.fileObj = open(self.fileName + ".shx", "wb")
self.numRecords = 0
self.index = []
# length of header
self.__offset = 100
# record IDs start at 1
self.__next_rid = 1
def add_record(self, size: int):
"""Add a record to the shx index.
Parameters
----------
size : int
The length of the record in bytes NOT including the 8-byte record header.
Returns
-------
rec_id : int
The sequential record ID, 1-based.
pos : int
See ``self.__offset`` in ``_create_shx_file``.
Notes
-----
The SHX records contain (Offset, Length) in 16-bit words.
Examples
--------
>>> import libpysal, os
>>> shx = shx_file(libpysal.examples.get_path('Point.shx'))
>>> shx.index
[(100, 20),
(128, 20),
(156, 20),
(184, 20),
(212, 20),
(240, 20),
(268, 20),
(296, 20),
(324, 20)]
>>> shx2 = shx_file('test', 'w')
>>> [shx2.add_record(rec[1]) for rec in shx.index]
[(1, 100),
(2, 128),
(3, 156),
(4, 184),
(5, 212),
(6, 240),
(7, 268),
(8, 296),
(9, 324)]
>>> shx2.index == shx.index
True
>>> shx2.close(shx._header)
>>> open('test.shx', 'rb').read() == open(
... libpysal.examples.get_path('Point.shx'), 'rb'
... ).read()
True
>>> os.remove('test.shx')
"""
self.__iswritable()
pos = self.__offset
rec_id = self.__next_rid
self.index.append((self.__offset, size))
# the 8-byte record header.
self.__offset += size + 8
self.numRecords += 1
self.__next_rid += 1
return rec_id, pos
def close(self, header: dict):
if self.__mode == "w":
self.__iswritable()
header["File Length"] = (self.numRecords * calcsize(">ii") + 100) // 2
self.fileObj.seek(0)
self.fileObj.write(_packDict(HEADERSTRUCT, header))
fmt = ">%di" % (2 * self.numRecords)
values = []
for off, size in self.index:
values.extend([off // 2, size // 2])
self.fileObj.write(pack(fmt, *values))
self.fileObj.close()
class NullShape:
Shape_Type = 0
STRUCT = ("Shape Type", "i", "<")
def unpack(self) -> None:
return None
def pack(self, x=None) -> str:
return pack("<i", 0)
class Point(object):
"""Packs and unpacks a shapefile Point type.
Examples
--------
>>> import libpysal
>>> shp = shp_file(libpysal.examples.get_path('Point.shp'))
>>> rec = shp.get_shape(0)
>>> rec == {'Y': -0.25904661905760773, 'X': -0.00068176617532103578, 'Shape Type': 1}
True
>>> # +8 byte record header
>>> pos = shp.fileObj.seek(shp._shx.index[0][0] + 8)
>>> dat = shp.fileObj.read(shp._shx.index[0][1])
>>> dat == Point.pack(rec)
True
"""
Shape_Type = 1
String_Type = "POINT"
HASZ = False
HASM = False
STRUCT = (("Shape Type", "i", "<"), ("X", "d", "<"), ("Y", "d", "<"))
USTRUCT = [
{"fmt": "idd", "order": "<", "names": ["Shape Type", "X", "Y"], "size": 20}
]
@classmethod
def unpack(cls, dat) -> dict:
"""
Parameters
----------
dat : file
An open file at the correct position.
"""
return _unpackDict(cls.USTRUCT, dat)
@classmethod
def pack(cls, record: dict) -> str:
rheader = _packDict(cls.STRUCT, record)
return rheader
class PointZ(Point):
Shape_Type = 11
String_Type = "POINTZ"
HASZ = True
HASM = True
STRUCT = (
("Shape Type", "i", "<"),
("X", "d", "<"),
("Y", "d", "<"),
("Z", "d", "<"),
("M", "d", "<"),
)
USTRUCT = [
{
"fmt": "idddd",
"order": "<",
"names": ["Shape Type", "X", "Y", "Z", "M"],
"size": 36,
}
]
class PolyLine:
"""Packs and unpacks a shapefile PolyLine type.
Examples
--------
>>> import libpysal
>>> shp = shp_file(libpysal.examples.get_path('Line.shp'))
>>> rec = shp.get_shape(0)
>>> rec == {
... 'BBOX Ymax': -0.25832280562918325,
... 'NumPoints': 3,
... 'BBOX Ymin': -0.25895877033237352,
... 'NumParts': 1,
... 'Vertices': [
... (-0.0090539248870159517, -0.25832280562918325),
... (0.0074811573959305822, -0.25895877033237352),
... (0.0074811573959305822, -0.25895877033237352)
... ],
... 'BBOX Xmax': 0.0074811573959305822,
... 'BBOX Xmin': -0.0090539248870159517,
... 'Shape Type': 3,
... 'Parts Index': [0]
... }
True
>>> # +8 byte record header
>>> pos = shp.fileObj.seek(shp._shx.index[0][0] + 8)
>>> dat = shp.fileObj.read(shp._shx.index[0][1])
>>> dat == PolyLine.pack(rec)
True
"""
HASZ = False
HASM = False
String_Type = "ARC"
STRUCT = (
("Shape Type", "i", "<"),
("BBOX Xmin", "d", "<"),
("BBOX Ymin", "d", "<"),
("BBOX Xmax", "d", "<"),
("BBOX Ymax", "d", "<"),
("NumParts", "i", "<"),
("NumPoints", "i", "<"),
)
USTRUCT = [
{
"fmt": "iddddii",
"order": "<",
"names": [
"Shape Type",
"BBOX Xmin",
"BBOX Ymin",
"BBOX Xmax",
"BBOX Ymax",
"NumParts",
"NumPoints",
],
"size": 44,
}
]
@classmethod
def unpack(cls, dat) -> dict:
"""
Parameters
----------
dat : file
An open file at the correct position.
"""
record = _unpackDict(cls.USTRUCT, dat)
contentStruct = (
("Parts Index", ("i", record["NumParts"]), "<"),
("Vertices", ("d", 2 * record["NumPoints"]), "<"),
)
_unpackDict2(record, contentStruct, dat)
# record['Vertices'] = [
# (record['Vertices'][i], record['Vertices'][i+1])
# for i in range(0, record['NumPoints']*2, 2)
# ]
verts = record["Vertices"]
# Next line is equivalent to: zip(verts[::2],verts[1::2])
record["Vertices"] = list(
zip(islice(verts, 0, None, 2), islice(verts, 1, None, 2))
)
if not record["Parts Index"]:
record["Parts Index"] = [0]