"""
This script cuts a network according to the first polygon or multilinestring found in the given geojson
"""
import json
import os
import subprocess
import sys
if 'SUMO_HOME' in os.environ:
sys.path.append(os.path.join(os.environ['SUMO_HOME'], 'tools'))
import sumolib
def parse_args():
USAGE = "Usage: " + sys.argv[0] + " -n <net> <options>"
argParser = sumolib.options.ArgumentParser(usage=USAGE)
argParser.add_argument("-n", "--input-net-file", required=True,
category="input", type=argParser.net_file, help="The .net.xml file to cut")
argParser.add_argument("-j", "--geojson", category="input", required=True,
type=argParser.file, help="GeoJSON input file")
argParser.add_argument("-k", "--netconvert-configuration",
category="input", help="Additional netconvert parameter to use")
argParser.add_argument("-o", "--output-file", category="output",
type=argParser.file, help="The network output file name")
argParser.add_argument("-p", "--polygon-output-file", category="output",
type=argParser.file, help="The polygon output file name")
return argParser.parse_known_args()
if __name__ == "__main__":
options, nc_args = parse_args()
with open(options.geojson) as jsonf:
geo = json.load(jsonf)
for feat in geo.get("features", []):
if feat["geometry"]["type"] in ("Polygon", "MultiLineString"):
shape = feat["geometry"]["coordinates"][0]
break
if not options.output_file:
options.output_file = options.input_net_file.replace(".net.xml", "_cut.net.xml")
cmd = [sumolib.checkBinary("netconvert"), "-s", options.input_net_file, "-o", options.output_file,
"--keep-edges.in-geo-boundary", ",".join(["%s,%s" % (lon, lat) for lon, lat in shape])] + nc_args
if options.netconvert_configuration:
cmd += ["-c", options.netconvert_configuration]
subprocess.check_call(cmd)
if options.polygon_output_file:
with open(options.polygon_output_file, 'w') as outf:
sumolib.xml.writeHeader(outf, root="additional")
outf.write(' <poly id="cut" shape="%s" color="blue" geo="true" layer="100"/>\n' %
(" ".join(["%s,%s" % (lon, lat) for lon, lat in shape])))
outf.write('</additional>\n')