82 lines
2.4 KiB
Python
82 lines
2.4 KiB
Python
"""
|
|
Extract polygons from SMS map file.
|
|
|
|
Run this script with --help to see available options and an example.
|
|
|
|
Example:
|
|
$ python extract_sms_polygons.py --input data/ModelCoast.map --output Polygon.txt
|
|
"""
|
|
|
|
import argparse
|
|
|
|
|
|
def read_polygons(file_name):
|
|
nodes = {}
|
|
polygons = []
|
|
|
|
with open(file_name, "r") as f:
|
|
while True:
|
|
try:
|
|
line = next(f)
|
|
|
|
# read nodes
|
|
if line.startswith("XY "):
|
|
_, x, y, _ = line.split()
|
|
_, node_id = next(f).split()
|
|
nodes[node_id] = (float(x), float(y))
|
|
|
|
# read arcs: arcs are vertices between nodes
|
|
# result polygon will start and end with the arc vertices
|
|
if line.startswith("NODES "):
|
|
_, a, b = line.split()
|
|
polygon = []
|
|
polygon.append(nodes[a])
|
|
following_line = next(f)
|
|
# if the following line is END, then there is no arc
|
|
# between vertices
|
|
if not following_line.startswith("END"):
|
|
_, i = following_line.split()
|
|
num_arc_vertices = int(i)
|
|
for _ in range(num_arc_vertices):
|
|
x, y, _ = map(float, next(f).split())
|
|
polygon.append((x, y))
|
|
polygon.append(nodes[b])
|
|
polygons.append(polygon)
|
|
|
|
except StopIteration:
|
|
break
|
|
|
|
return polygons
|
|
|
|
|
|
def write_polygons(polygons, file_name):
|
|
with open(file_name, "w") as f:
|
|
f.write("COAST\n")
|
|
f.write(f"{len(polygons)}\n")
|
|
for polygon in polygons:
|
|
f.write(f"{len(polygon)} 1\n")
|
|
for x, y in polygon:
|
|
f.write(f"{x} {y}\n")
|
|
|
|
|
|
def parse_arguments():
|
|
parser = argparse.ArgumentParser(
|
|
description="Extract polygons from SMS map file.",
|
|
epilog="Example: $ python extract_sms_polygons.py --input data/ModelCoast.map --output Polygon.txt",
|
|
)
|
|
|
|
parser.add_argument("--input", required=True, help="Path to SMS map file (input)")
|
|
parser.add_argument("--output", required=True, help="Path to the output file")
|
|
|
|
return parser.parse_args()
|
|
|
|
|
|
def main():
|
|
args = parse_arguments()
|
|
polygons = read_polygons(args.input)
|
|
write_polygons(polygons, args.output)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|