[25065] | 1 | try:
|
---|
| 2 | import shapefile
|
---|
| 3 | except ImportError:
|
---|
| 4 | print("could not import shapefile, PyShp has not been installed, no shapefile reading capabilities enabled")
|
---|
| 5 |
|
---|
[25163] | 6 |
|
---|
[25065] | 7 | def shpwrite(shp, filename): #{{{
|
---|
| 8 | '''
|
---|
| 9 | SHPREAD - write a shape file from a contour structure
|
---|
| 10 |
|
---|
| 11 | The current implementation of shpwrite depends on PyShp.
|
---|
| 12 |
|
---|
| 13 | Usage:
|
---|
| 14 | shpwrite(shp, filename)
|
---|
| 15 |
|
---|
| 16 | Example:
|
---|
| 17 | shpwrite(shp, 'domainoutline.shp')
|
---|
| 18 |
|
---|
| 19 | See also SHPREAD
|
---|
| 20 |
|
---|
| 21 | Sources:
|
---|
| 22 | - https://github.com/GeospatialPython/pyshp
|
---|
| 23 |
|
---|
| 24 | TODO:
|
---|
[27035] | 25 | - Should we check if there is only one element (see how MATLAB's shaperead
|
---|
[25065] | 26 | and shapewrite handle single shapes versus multiple shapes)?
|
---|
| 27 | '''
|
---|
| 28 |
|
---|
| 29 | # Sanity checks
|
---|
| 30 | for shape in shp:
|
---|
| 31 | print(shape)
|
---|
| 32 |
|
---|
| 33 | if shp[0].Geometry == 'Point':
|
---|
| 34 | shapeType = 1
|
---|
| 35 | elif shp[0].Geometry == 'Line':
|
---|
| 36 | shapeType = 3
|
---|
| 37 | elif shp[0].Geometry == 'Polygon':
|
---|
| 38 | shapeType = 5
|
---|
| 39 | else:
|
---|
| 40 | raise Exception('shpwrite error: geometry \'{}\' is not currently supported'.format(shp[0].Geometry))
|
---|
| 41 |
|
---|
| 42 | sf = shapefile.Writer(filename, shapeType=shapeType)
|
---|
| 43 |
|
---|
| 44 | for i in range(len(shp)):
|
---|
[27035] | 45 | sf.field('name', 'C') # TODO: Allow shape ids/names to be passed through
|
---|
[25065] | 46 | if shapeType == 1: # POINT
|
---|
| 47 | sf.point(shp[i].x, shp[i].y)
|
---|
| 48 | elif shapeType == 3: # POLYLINE
|
---|
| 49 | points = []
|
---|
| 50 | for j in range(len(shp[i].x)):
|
---|
| 51 | points.append([shp[i].x[j], shp[i].y[j]])
|
---|
| 52 | sf.line(line)
|
---|
[27035] | 53 | elif shapeType == 5: # POLYGON
|
---|
[25065] | 54 | points = []
|
---|
| 55 | for j in range(len(shp[i].x)):
|
---|
| 56 | points.append([shp[i].x[j], shp[i].y[j]])
|
---|
| 57 | sf.poly(points)
|
---|
| 58 | sf.null()
|
---|
| 59 | sf.record(str(i))
|
---|
| 60 | sf.close()
|
---|
| 61 | #}}}
|
---|