Skip to content

Instantly share code, notes, and snippets.

@ragnarheidar
Last active February 10, 2016 08:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ragnarheidar/1e8d58187bd35504acf3 to your computer and use it in GitHub Desktop.
Save ragnarheidar/1e8d58187bd35504acf3 to your computer and use it in GitHub Desktop.
Python script that uses the shapefile library to read a polygon shapefile. Output includes parameters, number of vertices in each feature and X and Y coordinates of each vertex for each feature. The output is specific for the avalanche simulation software SAMOS. This script can be used in QGIS as a tool in the Processing toolbox.
""""
Python script tha uses the shapefile library to read
a polygon shapefile. Output includes parameters, number
of vertices in each feature and X and Y coordinates of
each vertex for each feature. The output is specific
for the avalanche simulation software SAMOS.
This script can be used in QGIS as a tool in the Processing toolbox
Author: Icelandic Meteorology Office/Ragnar H. Thrastarson 2015
"""
# documentation - https://github.com/GeospatialPython/pyshp
import shapefile
# Dictionary with all possible shapefile types - https://www.esri.com/library/whitepapers/pdfs/shapefile.pdf
ShapeTypeDict = {0:"NullType",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"}
# path to shapefile and output file
StartingZones = "PATH/TO/SHAPEFILE"
OutputFile = "PATH/TO/OUTPUT.rel"
# samos parameters
SnowDepth = 0.25
SnowDensity = 300
ZoneType = 1
# shapefile reader object
sf = shapefile.Reader(StartingZones)
# call shapes method to read geometry
shapes = sf.shapes()
# read the type of shapefile, returns a number that can be compared to shape type dictionary above
WhatType = shapes[0].shapeType
# define function
def StartingZonesToSamos():
with open(OutputFile, 'w') as f: # open and create output file"
for shape in shapes: # for each feature in shapefile
f.write(str(SnowDepth) + " " + str(SnowDensity) + " " + str(ZoneType) + "\n") # add samos parameters
vert_count = len(shape.points) # count the number of vertices in polygon
f.write(str(vert_count) + "\n") # add the number of vertices
for vertex in shape.points: # for each vertex
f.write (" ".join(map(str, vertex)) + "\n") # add x and y coordinates with space between
print "Done: " + str(len(shapes)) + " starting zones written to " + OutputFile
if WhatType == 5 or WhatType == 13: # if shapefile is Polygon or PolygonZ
StartingZonesToSamos() # run function
else: # shapefile is not a polygon, print message and type of shapefile
print "This shapefile is not a polygon, it's a " + ShapeTypeDict[WhatType]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment