예제 #1
0
def generate(netFile, mappedSiteFile, intersectionFile, tripFile):
    # EdgesInDistricts
    # evakuierungsbereich
    options = OptionParser()
    options.maxspeed = 1000.
    options.minspeed = 0.
    options.complete = False
    options.internal = False
    options.vclass = None
    options.assign_from = True
    options.verbose = False
    options.weighted = False
    options.shapeinfo = False
    options.output = "edgesInIntersections.taz.xml"
    net = sumolib.net.readNet(netFile)
    reader = EID.DistrictEdgeComputer(net)
    polyReader = sumolib.shapes.polygon.PolygonReader(True)
    parse(intersectionFile, polyReader)
    reader.computeWithin(polyReader.getPolygons(), options)
    reader.writeResults(options)

    # Evakuierungsziele
    options.output = "evacuationsiteEdges.taz.xml"
    reader = EID.DistrictEdgeComputer(net)
    polyReader = sumolib.shapes.polygon.PolygonReader(True)
    parse(mappedSiteFile, polyReader)
    reader.computeWithin(polyReader.getPolygons(), options)
    reader.writeResults(options)
    print("EdgesInDistricts - done")

    # O/D Matrix
    import xml.etree.cElementTree as ET
    Districts = ET.ElementTree(file=intersectionFile)
    root = Districts.getroot()
    EVA = ET.ElementTree(file='evacuationsiteEdges.taz.xml')
    EV = EVA.getroot()
    EV.remove(EV[0])
    with open('ODMatrix.fma', 'w') as odm:
        odm.write('$OR \n* From-Tome To-Time \n1.00 2.00\n* Factor \n1.00\n')
        for elem in root.findall("./poly"):
            for ESite in EV.findall("./*"):
                CarAmount = str(
                    int(
                        float(elem.attrib["inhabitants"]) /
                        float(3 * (len(EV.findall("./*")) - 1))))
                odm.write(elem.attrib["id"] + '\t' + ESite.attrib["id"] +
                          '\t' + CarAmount + '\n')
    print("OD Matrix - done")

    # OD2TRIPS
    od2t = sumolib.checkBinary('od2trips')
    od2tOptions = [
        od2t, '--no-step-log', '-d', odm.name, '-n',
        'edgesInIntersections.taz.xml,evacuationsiteEdges.taz.xml', '-o',
        tripFile
    ]
    subprocess.call(od2tOptions)
예제 #2
0
    def handleAffectedArea(self, area):
        affectedTLSList = []
        affectedEdgeList = []

        # currently only consider one polygon for each area
        shape = [
            self._net.convertLonLat2XY(*point)
            for point in area["area"]["coordinates"][0][0]
        ]
        polygons = [sumolib.shapes.polygon.Polygon(area["id"], shape=shape)]

        reader = edgesInDistricts.DistrictEdgeComputer(self._net)
        optParser = OptionParser()
        edgesInDistricts.fillOptions(optParser)
        edgeOptions, _ = optParser.parse_args([])
        reader.computeWithin(polygons, edgeOptions)

        # get the affected edges
        result = list(reader._districtEdges.values())
        if result:
            affectedEdgeList = result[0]  # there is only one district

        if area["trafficLightsBroken"]:
            affectedIntersections = set()
            for n in self._net.getNodes():
                x, y = n.getCoord()
                for poly in polygons:
                    if checkWithin(
                            poly, x,
                            y) and n.getType() == "traffic_light" and n.getID(
                            ) not in affectedIntersections:
                        affectedIntersections.add(n.getID())
            # get the affected TLS
            for tls in self._net.getTrafficLights():
                if tls.getID() not in affectedTLSList:
                    for c in tls.getConnections():
                        for n in (c[0].getEdge().getFromNode(),
                                  c[0].getEdge().getToNode(),
                                  c[1].getEdge().getToNode()):
                            if n.getID() in affectedIntersections:
                                affectedTLSList.append(tls.getID())
                                break
        begin = self._simTime + self._deltaT if area[
            "begin"] <= self._simTime else area["begin"]
        self._affected.append(
            AffectedArea(begin, area["end"], polygons, affectedEdgeList,
                         affectedTLSList, area["restriction"].split()))
예제 #3
0
def handleAreaData(net, area, config, step):
    affectedIntersectionList = []
    affectedTLSList = []
    affectedEdgeList = []
    
    # currently only consider one polygon for each area
    polyObj = Polygon(area["id"], shape=area["area"]["coordinates"][0][0])
    polygons.append(polyObj)
    
    reader = edgesInDistricts.DistrictEdgeComputer(net)
    optParser = OptionParser()
    edgesInDistricts.fillOptions(optParser)
    edgeOptions, _ = optParser.parse_args([])
    reader.computeWithin(polygons, edgeOptions)
    
    # get the affected edges
    for idx, (district, edges) in enumerate(reader._districtEdges.items()):
        affectedEdgeList = edges  # there is only one district
        
    # get the affected intersections
    if area["trafficLightsBroken"]:
        for n in net._getNodes():
            x, y = n._coord  # check
            for poly in polygons:
                if checkWithin(poly,x,y) and n._type = "traffic_light" and n._id not in affectedIntersectionList:
                    affectedIntersectionList.append(n._id)

        # get the affected TLS
        tlsList = net.getTrafficLights()
        
        for tls in tlsList:
            if tls._id not in affectedTLSList:
                for c in tls.getConnections():
                    for n in (c[0].getEdge()._from(), c[0].getEdge()._to(), c[1].getEdge()._to()):
                        if n._id in affectedIntersectionList:
                            affectedTLSList.append(tls._id)
                            break
예제 #4
0
def create_template_folder(scenario_name, options):
    # create (template) subfolder in scenarios for the 'selected scenarios'
    if options.verbose:
        print("creating template dir for", scenario_name)
    # check if the directory is existing (which means there is old data)
    scenario_pre_dir = os.path.join(options.pre, scenario_name)
    scenario_template_dir = os.path.join(options.templates, scenario_name)
    if os.path.isdir(scenario_template_dir):
        print("Warning! Folder '%s' does exist and may contain old data." %
              scenario_name)
    else:
        # make a new template folder
        os.makedirs(scenario_template_dir)

    # copy static input such as vehicle types, edge lists and processing
    # scripts
    scriptable = False
    for ff in sorted(listdir_skip_hidden(scenario_pre_dir)):
        if ff[-3:] in ['xml', '.py', 'cfg'
                       ] and ff[:12] != 'template_gen' and ff != 'setup.py':
            print("copying %s" % ff)
            shutil.copyfile(os.path.join(scenario_pre_dir, ff),
                            os.path.join(scenario_template_dir, ff))
        if ff == "__init__.py":
            scriptable = True

    net_name = 'net.net.xml'
    net_path = os.path.join(scenario_template_dir, net_name)
    if not options.no_network:
        # check for navteq-dlr or osm data
        navteq_dlr_dir = os.path.join(scenario_pre_dir, 'navteq-dlr')
        osm_dir = os.path.join(scenario_pre_dir, 'osm')

        if os.path.isfile(navteq_dlr_dir):
            # emulate symlink
            navteq_dlr_dir = os.path.join(options.pre,
                                          open(navteq_dlr_dir).read().strip())
        if os.path.isdir(navteq_dlr_dir) or os.path.isdir(osm_dir):
            # make temporary output folder
            tmp_output_dir = os.path.join(scenario_template_dir, 'tmp_output')
            if os.path.exists(tmp_output_dir):
                shutil.rmtree(tmp_output_dir)
            os.mkdir(tmp_output_dir)

            if os.path.isdir(navteq_dlr_dir):
                # get the zip file containing the network
                zip_list = [
                    ff for ff in listdir_skip_hidden(navteq_dlr_dir)
                    if ff[-4:] == '.zip'
                ]
                if len(zip_list) != 1:
                    print('could not determine which .zip file to use')
                    print(navteq_dlr_dir, ":  ",
                          listdir_skip_hidden(navteq_dlr_dir))
                    return scriptable
                navteq_dlr_zip = os.path.join(navteq_dlr_dir, zip_list[0])

                print("starting to import navteq ...")
                configs = sorted(
                    glob.glob(
                        os.path.join(options.pre, scenario_name,
                                     'template_gen*.netccfg')))
                importOptions = import_navteq.get_options([
                    '-c', ",".join(configs), '-o', tmp_output_dir, '-v',
                    navteq_dlr_zip
                ])
                import_navteq.importNavteq(importOptions)

            if os.path.isdir(osm_dir):
                print("starting to import osm ...")

                # build net
                netconvert = sumolib.checkBinary('netconvert')
                config = os.path.join(options.pre, scenario_name,
                                      'template_gen.netccfg')
                netconvert_call = [
                    netconvert, '-c', config, '-o',
                    os.path.join(tmp_output_dir, net_name), '-v'
                ]
                subprocess.call(netconvert_call)

                poly_config = os.path.join(options.pre, scenario_name,
                                           'template_gen.polycfg')
                if os.path.isfile(poly_config):
                    # build polygons
                    polyconvert = sumolib.checkBinary('polyconvert')
                    polyconvertCmd = [
                        polyconvert, '-c', poly_config, '-o',
                        os.path.join(tmp_output_dir, "shapes.xml"), '-v'
                    ]
                    if options.verbose:
                        print(polyconvertCmd)
                        sys.stdout.flush()
                    subprocess.call(polyconvertCmd)

            # find netfile
            for root, _, files in os.walk(tmp_output_dir):
                if net_name in files:
                    os.rename(os.path.join(root, net_name), net_path)
                    break

            shutil.rmtree(tmp_output_dir)
    setup_file = os.path.join(scenario_pre_dir, 'setup.py')
    if os.path.exists(setup_file):
        subprocess.call(
            ["python", setup_file, scenario_pre_dir, scenario_template_dir])
    if not os.path.exists(net_path):
        print("could not find network data for %s" % scenario_name)

    net = None
    bidi_path = os.path.join(scenario_template_dir, "bidi.taz.xml")
    if not os.path.exists(bidi_path) or os.path.getmtime(
            bidi_path) < os.path.getmtime(net_path):
        if options.verbose:
            print("calling generateBidiDistricts.main %s, %s" %
                  (net_path, bidi_path))
        net = generateBidiDistricts.main(net_path, bidi_path, 20., 500., True)
    add = bidi_path

    # check for shapes folder and import from shapes
    shapes_dir = os.path.join(scenario_pre_dir, 'shapes')
    if os.path.isfile(shapes_dir):
        # emulate symlink
        shapes_dir = os.path.join(options.pre, open(shapes_dir).read().strip())
    if os.path.isdir(shapes_dir):
        polyconvert = sumolib.checkBinary('polyconvert')
        idCol = dict(
            [e.split(":") for e in options.shape_id_column.split(",")])
        for dbf in glob.glob(os.path.join(shapes_dir, "*.dbf")):
            prefix = os.path.basename(dbf)[:-4]
            tazFile = os.path.join(scenario_template_dir, "districts.taz.xml")
            if prefix in idCol:
                tazFile = os.path.join(scenario_template_dir,
                                       prefix + ".taz.xml")
            if options.verbose:
                print("generating taz file %s" % tazFile)
            if not os.path.exists(tazFile) or os.path.getmtime(
                    tazFile) < os.path.getmtime(net_path):
                if options.verbose:
                    print("importing shapes from %s ..." % dbf)
                polyReader = sumolib.shapes.polygon.PolygonReader(True)
                polyFile = os.path.join(scenario_template_dir,
                                        prefix + ".poly.xml")
                subprocess.call([
                    polyconvert, "-n", net_path, "-o", polyFile,
                    "--shapefile-prefixes",
                    os.path.join(shapes_dir, prefix), "--shapefile.add-param",
                    "--shapefile.id-column",
                    idCol.get(prefix, idCol["*"])
                ])
                if options.verbose:
                    print("calculating contained edges for %s ..." % polyFile)
                parse(polyFile, polyReader)
                polys = polyReader.getPolygons()
                if net is None:
                    net = sumolib.net.readNet(net_path,
                                              withConnections=False,
                                              withFoes=False)
                eIDoptions, _ = edgesInDistricts.parse_args(
                    ["--assign-from", "--output", tazFile])
                reader = edgesInDistricts.DistrictEdgeComputer(net)
                reader.computeWithin(polys, eIDoptions)
                reader.writeResults(eIDoptions)
        if options.suburb_taz:
            tazFile = os.path.join(scenario_template_dir,
                                   options.suburb_taz + ".taz.xml")
            if not os.path.exists(tazFile) or os.path.getmtime(
                    tazFile) < os.path.getmtime(net_path):
                if options.verbose:
                    print("generating taz file %s" % tazFile)
                polys = []
                if net is None:
                    net = sumolib.net.readNet(net_path,
                                              withConnections=False,
                                              withFoes=False)
                for tazid, shapes in get_germany_taz.get_polys(options,
                                                               net=net):
                    for idx, shape in enumerate(shapes):
                        polys.append(
                            sumolib.shapes.polygon.Polygon("%s:%s" %
                                                           (tazid, idx),
                                                           shape=shape))
                eIDoptions, _ = edgesInDistricts.parse_args([
                    "--assign-from", "--output", tazFile, "--merge-separator",
                    ":"
                ])
                reader = edgesInDistricts.DistrictEdgeComputer(net)
                reader.computeWithin(polys, eIDoptions)
                reader.writeResults(eIDoptions)
            add += "," + tazFile
    lm = os.path.join(scenario_pre_dir, options.landmarks)
    if os.path.isfile(lm):
        if options.verbose:
            print("generating landmark file %s" % lm)
        duarouter = sumolib.checkBinary('duarouter')
        landmarkFile = os.path.join(scenario_template_dir, "landmarks.csv")
        if options.verbose:
            print("generating landmark file %s" % landmarkFile)
        subprocess.call([
            duarouter, "-n", net_path, "-a", add, "--astar.landmark-distances",
            lm, "--astar.save-landmark-distances", landmarkFile,
            "--routing-threads", "24", "-v", "-o", "NUL", "--ignore-errors",
            "--aggregate-warnings", "5"
        ])
    else:
        print("could not find landmark data for %s" % scenario_name)
    return scriptable