Пример #1
0
def buildNet(outputName, inputFileName=responsePath):
    typemaps = {
        "net":
        os.path.join(typemapPath, "osmNetconvert.typ.xml"),
        "poly":
        os.path.join(typemapPath, "osmPolyconvert.typ.xml"),
        "urban":
        os.path.join(typemapPath, "osmNetconvertUrbanDe.typ.xml"),
        "pedestrians":
        os.path.join(typemapPath, "osmNetconvertPedestrians.typ.xml"),
        "ships":
        os.path.join(typemapPath, "osmNetconvertShips.typ.xml"),
        "bicycles":
        os.path.join(typemapPath, "osmNetconvertBicycle.typ.xml"),
    }

    options = ["-f", inputFileName]
    options += ["-p", outputName]

    typefiles = [typemaps["net"], typemaps["urban"], typemaps["pedestrians"]]
    netconvertOptions = osmBuild.DEFAULT_NETCONVERT_OPTS
    netconvertOptions += ",--tls.default-type,actuated"

    options += ["--netconvert-typemap", ','.join(typefiles)]
    options += ["--netconvert-options", netconvertOptions]

    osmBuild.build(options)
Пример #2
0
def main(options):
    if options.net_file is None:
        osmBuild.build(["-f", options.osm_file])
        net = sumolib.net.readNet("osm.net.xml")
    else:
        net = sumolib.net.readNet(options.net_file)
    count = 0
    fleet_out = io.open(options.fleet_file, "w") if options.fleet_file else None
    if fleet_out:
        sumolib.xml.writeHeader(fleet_out, root="additional")
        print("""     <vType id="taxi" vClass="taxi">
        <param key="has.taxi.device" value="true"/>
    </vType>""", file=fleet_out)
    with io.open(options.output_file, "w") as output:
        sumolib.xml.writeHeader(output, root="additional")
        for n in sumolib.xml.parse(options.osm_file, "node"):
            name = None
            bestLane = None
            point = None
            length = options.length
            if n.tag:
                for t in n.tag:
                    if t.k == "capacity":
                        try:
                            length = max(int(t.v) * VEHICLE_LENGTH, length)
                        except ValueError:
                            pass
                    if t.k == "name":
                        name = t.v
                    if t.k == "amenity" and t.v == "taxi":
                        point = net.convertLonLat2XY(float(n.lon), float(n.lat))
                        for lane, _ in sorted(net.getNeighboringLanes(*point, r=options.radius), key=lambda i: i[1]):
                            if lane.getLength() > options.length and lane.allows(options.vclass):
                                bestLane = lane
                                break
                if bestLane:
                    pos = sumolib.geomhelper.polygonOffsetWithMinimumDistanceToPoint(point, bestLane.getShape())
                    endPos = min(lane.getLength(), max(length, pos + length / 2))
                    nameAttr = 'name="%s" ' % name if name else ""
                    stopID = "%s_%s" % (options.type, count)
                    print('    <%s id="%s" %slane="%s" startPos="%.2f" endPos="%.2f"/>' %
                          (options.type, stopID, nameAttr, bestLane.getID(), endPos - length, endPos),
                          file=output)
                    if fleet_out:
                        for idx in range(int(length / VEHICLE_LENGTH)):
                            print('    <trip id="taxi_%s_%s" type="taxi" depart="0.00"><stop busStop="%s" triggered="person"/></trip>' %  # noqa
                                  (stopID, idx, stopID), file=fleet_out)
                    count += 1
        print(u"</additional>", file=output)
    if fleet_out:
        print(u"</additional>", file=fleet_out)
Пример #3
0
def main(options):
    if options.net_file is None:
        osmBuild.build(["-f", options.osm_file])
        net = sumolib.net.readNet("osm.net.xml")
    else:
        net = sumolib.net.readNet(options.net_file)
    count = 0
    with open(options.output_file, "w") as output:
        sumolib.xml.writeHeader(output, root="additional")
        for n in sumolib.xml.parse(options.osm_file, "node"):
            name = None
            bestLane = None
            point = None
            length = options.length
            if n.tag:
                for t in n.tag:
                    if t.k == "capacity":
                        try:
                            length = max(int(t.v) * 7.5, length)
                        except ValueError:
                            pass
                    if t.k == "name":
                        name = t.v
                    if t.k == "amenity" and t.v == "taxi":
                        point = net.convertLonLat2XY(float(n.lon),
                                                     float(n.lat))
                        for lane, _ in sorted(net.getNeighboringLanes(
                                *point, r=options.radius),
                                              key=lambda i: i[1]):
                            if lane.getLength(
                            ) > options.length and lane.allows(options.vclass):
                                bestLane = lane
                                break
                if bestLane:
                    pos = sumolib.geomhelper.polygonOffsetWithMinimumDistanceToPoint(
                        point, bestLane.getShape())
                    endPos = min(lane.getLength(), max(length,
                                                       pos + length / 2))
                    nameAttr = 'name="%s" ' % name if name else ""
                    print(
                        '    <%s id="%s_%s" %slane="%s" startPos="%.2f" endPos="%.2f"/>'
                        % (options.type, options.type, count, nameAttr,
                           bestLane.getID(), endPos - length, endPos),
                        file=output)
                    count += 1
        print("</additional>", file=output)
Пример #4
0
    def build(self):
        # output name for the osm file, will be used by osmBuild, can be
        # deleted after the process
        self.filename("osm", "_bbox.osm.xml")
        # output name for the net file, will be used by osmBuild, randomTrips and
        # sumo-gui
        self.filename("net", ".net.xml")

        if 'osm' in self.data:
            # testing mode
            shutil.copy(data['osm'], self.files["osm"])
        else:
            self.report("Downloading map data")
            osmGet.get([
                "-b", ",".join(map(str, self.data["coords"])), "-p",
                self.prefix, "-d", self.tmp
            ])

        options = ["-f", self.files["osm"], "-p", self.prefix, "-d", self.tmp]
        self.additionalFiles = []
        self.routenames = []

        if self.data["poly"]:
            # output name for the poly file, will be used by osmBuild and
            # sumo-gui
            self.filename("poly", ".poly.xml")
            options += ["-m", typemaps["poly"]]
            self.additionalFiles.append(self.files["poly"])

        typefiles = [typemaps["net"]]
        netconvertOptions = osmBuild.DEFAULT_NETCONVERT_OPTS
        netconvertOptions += ",--tls.default-type,actuated"
        if "pedestrian" in self.data["vehicles"]:
            # sidewalks are already included via typefile
            netconvertOptions += ",--crossings.guess"
            typefiles.append(typemaps["urban"])
            typefiles.append(typemaps["pedestrians"])
        if "ship" in self.data["vehicles"]:
            typefiles.append(typemaps["ships"])
        if "bicycle" in self.data["vehicles"]:
            typefiles.append(typemaps["bicycles"])
        # special treatment for public transport
        if self.data["publicTransport"]:
            self.filename("stops", "_stops.add.xml")
            netconvertOptions += ",--ptstop-output,%s" % self.files["stops"]
            self.filename("ptlines", "_ptlines.xml")
            self.filename("ptroutes", "_pt.rou.xml")
            netconvertOptions += ",--ptline-output,%s" % self.files["ptlines"]
            self.additionalFiles.append(self.files["stops"])
            self.routenames.append(self.files["ptroutes"])
            netconvertOptions += ",--railway.topology.repair"
        if self.data["leftHand"]:
            netconvertOptions += ",--lefthand"

        options += ["--netconvert-typemap", ','.join(typefiles)]
        options += ["--netconvert-options", netconvertOptions]

        self.report("Converting map data")
        osmBuild.build(options)
        ptOptions = None
        if self.data["publicTransport"]:
            self.report("Generating public transport schedule")
            self.filename("pt_stopinfos", "stopinfos.xml", False)
            self.filename("pt_vehroutes", "vehroutes.xml", False)
            self.filename("pt_trips", "trips.trips.xml", False)
            ptOptions = [
                "-n",
                self.files["net"],
                "-e",
                self.data["duration"],
                "-p",
                "600",
                "--random-begin",
                "--seed",
                "42",
                "--ptstops",
                self.files["stops"],
                "--ptlines",
                self.files["ptlines"],
                "-o",
                self.files["ptroutes"],
                "--ignore-errors",
                # "--no-vtypes",
                "--vtype-prefix",
                "pt_",
                "--stopinfos-file",
                self.files["pt_stopinfos"],
                "--routes-file",
                self.files["pt_vehroutes"],
                "--trips-file",
                self.files["pt_trips"],
                "--verbose",
            ]
            ptlines2flows.main(ptlines2flows.get_options(ptOptions))

        if self.data["vehicles"] or ptOptions:
            # routenames stores all routefiles and will join the items later, will
            # be used by sumo-gui
            randomTripsCalls = []

            self.edges = sumolib.net.readNet(
                os.path.join(self.tmp, self.files["net"])).getEdges()

            for vehicle, options in self.data["vehicles"].items():
                self.report("Processing %s" % vehicleNames[vehicle])

                self.filename("route", ".%s.rou.xml" % vehicle)
                self.filename("trips", ".%s.trips.xml" % vehicle)

                try:
                    options = self.parseTripOpts(vehicle, options,
                                                 self.data["publicTransport"])
                except ZeroDivisionError:
                    continue

                if vehicle == "pedestrian" and self.data["publicTransport"]:
                    options += [
                        "--additional-files",
                        ",".join([self.files["stops"], self.files["ptroutes"]])
                    ]

                randomTrips.main(randomTrips.get_options(options))
                randomTripsCalls.append(options)

                # --validate is not called for pedestrians
                if vehicle == "pedestrian":
                    self.routenames.append(self.files["route"])
                else:
                    self.routenames.append(self.files["trips"])

            # create a batch file for reproducing calls to randomTrips.py
            if os.name == "posix":
                SUMO_HOME_VAR = "$SUMO_HOME"
            else:
                SUMO_HOME_VAR = "%SUMO_HOME%"

            randomTripsPath = os.path.join(SUMO_HOME_VAR, "tools",
                                           "randomTrips.py")
            ptlines2flowsPath = os.path.join(SUMO_HOME_VAR, "tools",
                                             "ptlines2flows.py")

            self.filename("build.bat", "build.bat", False)
            batchFile = self.files["build.bat"]
            with open(batchFile, 'w') as f:
                if os.name == "posix":
                    f.write("#!/bin/bash\n")
                if ptOptions is not None:
                    f.write("python \"%s\" %s\n" %
                            (ptlines2flowsPath, " ".join(
                                map(quoted_str, self.getRelative(ptOptions)))))
                for opts in sorted(randomTripsCalls):
                    f.write("python \"%s\" %s\n" % (randomTripsPath, " ".join(
                        map(quoted_str, self.getRelative(opts)))))
Пример #5
0
print("building Evacuation Site")
prefix = "evacuationArea"
siteFile = "site.poly.xml"
mappedSiteFile = "mappedSite.poly.xml"
mergedPopulationFile = "population.poly.xml"
intersectionFile = "intersections.poly.xml"
if len(sys.argv) > 1:
    buildEvaSite(sys.argv[1], siteFile)
else:
    buildEvaSite("inputLocations.poi.xml", siteFile)
print("osm Get")
osmGet.get(["-x", siteFile])
print("osm Build")
osmOptions = ['-f', 'osm_bbox.osm.xml', '-p', prefix, '--vehicle-classes', 'road',
              '-m', os.path.join(SUMO_HOME, 'data', 'typemap', 'osmPolyconvert.typ.xml')]
osmBuild.build(osmOptions)
print("polyconvert")
sys.stdout.flush()
subprocess.call([sumolib.checkBinary('polyconvert'), '-n', '%s.net.xml' %
                 prefix, '--xml-files', siteFile, '-o', mappedSiteFile])
print("merging")
mergePopulationData("population.csv", 'regions.poly.xml', mergedPopulationFile)
print("extracting population data")
extract(mergedPopulationFile, mappedSiteFile, intersectionFile)
print("generating traffic")
generateTraffic.generate(
    '%s.net.xml' % prefix, mappedSiteFile, intersectionFile, '%s.rou.xml' % prefix)
print("calling sumo")
sys.stdout.flush()
sumo = sumolib.checkBinary('sumo')
sumoOptions = [sumo, '-n', "%s.net.xml" % prefix, '-a', "%s.poly.xml,inputLocations.poi.xml,%s" % (prefix, mappedSiteFile),
Пример #6
0
    def build(self):
        # output name for the osm file, will be used by osmBuild, can be
        # deleted after the process
        self.filename("osm", "_bbox.osm.xml")
        # output name for the net file, will be used by osmBuild, randomTrips and
        # sumo-gui
        self.filename("net", ".net.xml")

        if 'osm' in self.data:
            # testing mode
            shutil.copy(data['osm'], self.files["osm"])
        else:
            self.report("Downloading map data")
            osmGet.get(
                ["-b", ",".join(map(str, self.data["coords"])), "-p", self.prefix])

        options = ["-f", self.files["osm"], "-p", self.prefix, "-d", self.tmp]
        self.additionalFiles = []
        self.routenames = []

        if self.data["poly"]:
            # output name for the poly file, will be used by osmBuild and
            # sumo-gui
            self.filename("poly", ".poly.xml")
            options += ["-m", typemaps["poly"]]
            self.additionalFiles.append(self.files["poly"])

        typefiles = [typemaps["net"]]
        netconvertOptions = osmBuild.DEFAULT_NETCONVERT_OPTS
        netconvertOptions += ",--tls.default-type,actuated"
        if "pedestrian" in self.data["vehicles"]:
            # sidewalks are already included via typefile
            netconvertOptions += ",--crossings.guess"
            typefiles.append(typemaps["urban"])
            typefiles.append(typemaps["pedestrians"])
        if "ship" in self.data["vehicles"]:
            typefiles.append(typemaps["ships"])
        if "bicycle" in self.data["vehicles"]:
            typefiles.append(typemaps["bicycles"])
        # special treatment for public transport
        if self.data["publicTransport"]:
            self.filename("stops", "_stops.add.xml")
            netconvertOptions += ",--ptstop-output,%s" % self.files["stops"]
            self.filename("ptlines", "_ptlines.xml")
            self.filename("ptroutes", "_pt.rou.xml")
            netconvertOptions += ",--ptline-output,%s" % self.files["ptlines"]
            self.additionalFiles.append(self.files["stops"])
            self.routenames.append(self.files["ptroutes"])
            netconvertOptions += ",--railway.topology.repair"
        if self.data["leftHand"]:
            netconvertOptions += ",--lefthand"

        options += ["--netconvert-typemap", ','.join(typefiles)]
        options += ["--netconvert-options", netconvertOptions]

        self.report("Converting map data")
        osmBuild.build(options)
        ptOptions = None
        if self.data["publicTransport"]:
            self.report("Generating public transport schedule")
            ptOptions = [
                "-n", self.files["net"],
                "-e", self.data["duration"],
                "-p", "600",
                "--random-begin",
                "--seed", "42",
                "--ptstops", self.files["stops"],
                "--ptlines", self.files["ptlines"],
                "-o", self.files["ptroutes"],
                "--ignore-errors",
                # "--no-vtypes",
                "--vtype-prefix", "pt_",
                "--verbose",
            ]
            ptlines2flows.main(ptlines2flows.get_options(ptOptions))

        if self.data["vehicles"] or ptOptions:
            # routenames stores all routefiles and will join the items later, will
            # be used by sumo-gui
            randomTripsCalls = []

            self.edges = sumolib.net.readNet(self.files["net"]).getEdges()

            for vehicle, options in self.data["vehicles"].items():
                self.report("Processing %s" % vehicleNames[vehicle])

                self.filename("route", ".%s.rou.xml" % vehicle)
                self.filename("trips", ".%s.trips.xml" % vehicle)

                try:
                    options = self.parseTripOpts(vehicle, options, self.data["publicTransport"])
                except ZeroDivisionError:
                    continue

                if vehicle == "pedestrian" and self.data["publicTransport"]:
                    options += ["--additional-files", ",".join([self.files["stops"], self.files["ptroutes"]])]

                randomTrips.main(randomTrips.get_options(options))
                randomTripsCalls.append(options)

                # --validate is not called for pedestrians
                if vehicle == "pedestrian":
                    self.routenames.append(self.files["route"])
                else:
                    self.routenames.append(self.files["trips"])

            # create a batch file for reproducing calls to randomTrips.py
            if os.name == "posix":
                SUMO_HOME_VAR = "$SUMO_HOME"
            else:
                SUMO_HOME_VAR = "%SUMO_HOME%"

            randomTripsPath = os.path.join(
                SUMO_HOME_VAR, "tools", "randomTrips.py")
            ptlines2flowsPath = os.path.join(
                SUMO_HOME_VAR, "tools", "ptlines2flows.py")
            batchFile = "build.bat"
            with open(batchFile, 'w') as f:
                if os.name == "posix":
                    f.write("#!/bin/bash\n")
                if ptOptions is not None:
                    f.write("python \"%s\" %s\n" %
                            (ptlines2flowsPath, " ".join(map(quoted_str, ptOptions))))
                for opts in sorted(randomTripsCalls):
                    f.write("python \"%s\" %s\n" %
                            (randomTripsPath, " ".join(map(quoted_str, opts))))
Пример #7
0
    def build(self):
        # output name for the osm file, will be used by osmBuild, can be
        # deleted after the process
        self.filename("osm", "_bbox.osm.xml")
        # output name for the net file, will be used by osmBuild, randomTrips and
        # sumo-gui
        self.filename("net", ".net.xml")

        if 'osm' in self.data:
            # testing mode
            shutil.copy(data['osm'], self.files["osm"])
        else:
            self.report("Downloading map data")
            osmGet.get([
                "-b", ",".join(map(str, self.data["coords"])), "-p",
                self.prefix
            ])

        options = ["-f", self.files["osm"], "-p", self.prefix, "-d", self.tmp]
        self.additionalFiles = []

        if self.data["poly"]:
            # output name for the poly file, will be used by osmBuild and
            # sumo-gui
            self.filename("poly", ".poly.xml")
            options += ["-m", typemaps["poly"]]
            self.additionalFiles.append(self.files["poly"])

        typefiles = [typemaps["net"]]
        netconvertOptions = osmBuild.DEFAULT_NETCONVERT_OPTS
        netconvertOptions += ",--tls.default-type,actuated"
        if "pedestrian" in self.data["vehicles"]:
            # sidewalks are already included via typefile
            netconvertOptions += ",--crossings.guess"
            typefiles.append(typemaps["urban"])
            typefiles.append(typemaps["pedestrians"])
        if "ship" in self.data["vehicles"]:
            typefiles.append(typemaps["ships"])
        if "bicycle" in self.data["vehicles"]:
            typefiles.append(typemaps["bicycles"])
        if "bus" in self.data["vehicles"]:
            self.filename("stops", "_stops.add.xml")
            netconvertOptions += ",--ptstop-output,%s" % self.files["stops"]
            netconvertOptions += ",--osm.stop-output.length,25"
            self.additionalFiles.append(self.files["stops"])

        options += ["--netconvert-typemap", ','.join(typefiles)]
        options += ["--netconvert-options", netconvertOptions]

        self.report("Converting map data")
        osmBuild.build(options)

        if self.data["vehicles"]:
            # routenames stores all routefiles and will join the items later, will
            # be used by sumo-gui
            self.routenames = []
            randomTripsCalls = []

            self.edges = sumolib.net.readNet(self.files["net"]).getEdges()

            for vehicle, options in self.data["vehicles"].items():
                self.report("Processing %s" % vehicleNames[vehicle])

                self.filename("route", ".%s.rou.xml" % vehicle)
                self.filename("trips", ".%s.trips.xml" % vehicle)

                try:
                    options = self.parseTripOpts(vehicle, options)
                except ZeroDivisionError:
                    continue

                randomTrips.main(randomTrips.get_options(options))
                randomTripsCalls.append(options)

                # --validate is not called for pedestrians
                if vehicle == "pedestrian":
                    self.routenames.append(self.files["route"])
                else:
                    self.routenames.append(self.files["trips"])

            # create a batch file for reproducing calls to randomTrips.py
            randomTripsPath = os.path.join(SUMO_HOME, "tools",
                                           "randomTrips.py")
            batchFile = "build.bat"
            with open(batchFile, 'w') as f:
                for opts in sorted(randomTripsCalls):
                    f.write("python \"%s\" %s\n" %
                            (randomTripsPath, " ".join(map(quoted_str, opts))))
Пример #8
0
def build(handler, prefix, bbox=False):
    sumo = sumolib.checkBinary('sumo')

    if bbox:
        sumogui = sumolib.checkBinary('sumo-gui')
    else:
        # offline test mode
        sumogui = sumo

    def callSumo(extraopts):
        guisettingsname = prefix + ".view.xml"
        print "Writing gui settings file:", guisettingsname
        with open(guisettingsname, 'w') as f:
            f.write("""
<viewsettings>
    <scheme name="real world"/>
    <delay value="20"/>
</viewsettings>
""")
        configname = prefix + ".sumocfg"
        print "Writing config file:", configname
        opts = [sumo, "-n", netname, "-a", polyname, "--gui-settings-file",
                guisettingsname, "-v", "--no-step-log", "--save-configuration", configname]
        opts += extraopts
        subprocess.call(opts)

        print "Calling SUMO GUI"

        try:
            subprocess.call([sumogui, "-c", configname])
        except:
            print "SUMO GUI canceled"

    if bbox:
        # get the coordinates and cast them to float
        size = map(float, bbox.split(","))
        # calculates the area
        size = (size[0] - size[2]) * (size[3] - size[1])
        areaFactor = abs(size) * 5000
        # to adjust period by the area
        print "Calling osmGet"
        osmGet.get(["-b", bbox, "-p", prefix])
    else:
        # offline test mode
        areaFactor = 1

    print "Calling osmBuild"
    # output name for the osm file, will be used by osmBuild, can be after the
    # process deleted
    osmname = prefix + "_bbox.osm.xml"
    # output name for the net file, will be used by osmBuild, randomTrips and
    # sumo-gui
    netname = prefix + ".net.xml"
    # output name for the poly file, will be used by osmBuild and sumo-gui
    polyname = prefix + ".poly.xml"
    options = ["-f", osmname, "-p", prefix, "-m", polyfile]
    typefiles = [typefile]
    netconvertOptions = osmBuild.DEFAULT_NETCONVERT_OPTS + ",--junctions.corner-detail,5,--output.street-names"
    if handler.pedestrians.enable:  # drop?
        # sidewalks are already included via typefile
        netconvertOptions += ",--crossings.guess"
        typefiles.append(urbantypefile)
        typefiles.append(pedestrianstypefile)
    if handler.ships.enable:
        typefiles.append(shipstypefile)
    options += ["--netconvert-typemap", ','.join(typefiles)]
    options += ["--netconvert-options", netconvertOptions]
    osmBuild.build(options)

    if handler.vehicles.enable or handler.bicycles.enable or handler.pedestrians.enable or handler.rails.enable or handler.ships.enable:
        print "Calling randomTrips"
        # routenames stores all routefiles and will join the items later, will
        # be used by sumo-gui
        routenames = []
        randomTripsCalls = []
        route2TripsCalls = []

        for modeOpts, modeName in [
                (handler.vehicles, "vehicles"),
                (handler.bicycles, "bicycles"),
                (handler.rails, "rails"),
                (handler.ships, "ships")
                ]:
            if modeOpts.enable:
                routename = "%s.%s.rou.xml" % (prefix, modeName)
                tripname = "%s.%s.trips.xml" % (prefix, modeName)
                routenames.append(tripname)
                opts = modeOpts.parseTripOpts(netname, routename, areaFactor)
                randomTrips.main(randomTrips.get_options(opts))
                route2trips.main([routename], outfile=tripname)
                randomTripsCalls.append(opts)
                route2TripsCalls.append([routename, tripname])

        # route2trips is not called for pedestrians
        if handler.pedestrians.enable:
            routename = prefix + ".pedestrians.rou.xml"
            routenames.append(routename)
            opts = handler.pedestrians.parseTripOpts(netname, routename, areaFactor)
            randomTrips.main(randomTrips.get_options(opts))
            randomTripsCalls.append(opts)

        # create a batch file for reproducing calls to randomTrips.py and route2trips
        randomTripsPath = os.path.join(SUMO_HOME, "tools", "randomTrips.py")
        route2TripsPath = os.path.join(SUMO_HOME, "tools", "route2trips.py")
        batchFile = "%s.%s" % (prefix, ("bat" if os.name == "nt" else "sh"))
        with open(batchFile, 'w') as f:
            for opts in randomTripsCalls:
                f.write("python %s %s\n" % (randomTripsPath, " ".join(map(str, opts))))
            for route, trips in route2TripsCalls:
                f.write("python %s %s > %s\n" % (route2TripsPath, route, trips))

        callSumo(["-r", ",".join(routenames), "--ignore-route-errors"])

    else:
        callSumo([])

    print "Done."
Пример #9
0
print("building Evacuation Site")
prefix = "evacuationArea"
siteFile = "site.poly.xml"
mappedSiteFile = "mappedSite.poly.xml"
mergedPopulationFile = "population.poly.xml"
intersectionFile = "intersections.poly.xml"
if len(sys.argv) > 1:
    buildEvaSite(sys.argv[1], siteFile)
else:
    buildEvaSite("inputLocations.poi.xml", siteFile)
print("osm Get")
osmGet.get(["-x", siteFile])
print("osm Build")
osmOptions = ['-f', 'osm_bbox.osm.xml', '-p', prefix, '--vehicle-classes', 'road',
              '-m', os.path.join(SUMO_HOME, 'data', 'typemap', 'osmPolyconvert.typ.xml')]
osmBuild.build(osmOptions)
print("polyconvert")
sys.stdout.flush()
subprocess.call([sumolib.checkBinary('polyconvert'), '-n', '%s.net.xml' %
                 prefix, '--xml-files', siteFile, '-o', mappedSiteFile])
print("merging")
mergePopulationData("population.csv", 'regions.poly.xml', mergedPopulationFile)
print("extracting population data")
extract(mergedPopulationFile, mappedSiteFile, intersectionFile)
print("generating traffic")
generateTraffic.generate(
    '%s.net.xml' % prefix, mappedSiteFile, intersectionFile, '%s.rou.xml' % prefix)
print("calling sumo")
sys.stdout.flush()
sumo = sumolib.checkBinary('sumo')
sumoOptions = [sumo, '-n', "%s.net.xml" % prefix,
Пример #10
0
    def build(self):
        # output name for the osm file, will be used by osmBuild, can be
        # deleted after the process
        self.filename("osm", "_bbox.osm.xml")
        # output name for the net file, will be used by osmBuild, randomTrips and
        # sumo-gui
        self.filename("net", ".net.xml")

        if 'osm' in self.data:
            # testing mode
            shutil.copy(data['osm'], self.files["osm"])
        else:
            self.report("Downloading map data")
            osmGet.get(
                ["-b", ",".join(map(str, self.data["coords"])), "-p", self.prefix])

        options = ["-f", self.files["osm"], "-p", self.prefix, "-d", self.tmp]

        if self.data["poly"]:
            # output name for the poly file, will be used by osmBuild and
            # sumo-gui
            self.filename("poly", ".poly.xml")
            options += ["-m", typemaps["poly"]]

        typefiles = [typemaps["net"]]
        netconvertOptions = osmBuild.DEFAULT_NETCONVERT_OPTS
        if "pedestrian" in self.data["vehicles"]:
            # sidewalks are already included via typefile
            netconvertOptions += ",--crossings.guess"
            typefiles.append(typemaps["urban"])
            typefiles.append(typemaps["pedestrians"])
        if "ship" in self.data["vehicles"]:
            typefiles.append(typemaps["ships"])
        if "bicycle" in self.data["vehicles"]:
            typefiles.append(typemaps["bicycles"])
        options += ["--netconvert-typemap", ','.join(typefiles)]
        options += ["--netconvert-options", netconvertOptions]

        self.report("Converting map data")
        osmBuild.build(options)

        if self.data["vehicles"]:
            # routenames stores all routefiles and will join the items later, will
            # be used by sumo-gui
            self.routenames = []
            randomTripsCalls = []

            self.edges = sumolib.net.readNet(self.files["net"]).getEdges()

            for vehicle, options in self.data["vehicles"].items():
                self.report("Processing %s" % vehicleNames[vehicle])

                self.filename("route", ".%s.rou.xml" % vehicle)
                self.filename("trips", ".%s.trips.xml" % vehicle)

                try:
                    options = self.parseTripOpts(vehicle, options)
                except ZeroDivisionError:
                    continue

                randomTrips.main(randomTrips.get_options(options))
                randomTripsCalls.append(options)

                # --validate is not called for pedestrians
                if vehicle == "pedestrian":
                    self.routenames.append(self.files["route"])
                else:
                    self.routenames.append(self.files["trips"])

            # create a batch file for reproducing calls to randomTrips.py
            randomTripsPath = os.path.join(
                SUMO_HOME, "tools", "randomTrips.py")
            batchFile = "build.bat"
            with open(batchFile, 'w') as f:
                for opts in sorted(randomTripsCalls):
                    f.write("python %s %s\n" %
                            (randomTripsPath, " ".join(map(quoted_str, opts))))
Пример #11
0
    def build(self):
        # output name for the osm file, will be used by osmBuild, can be
        # deleted after the process
        self.filename("osm", "_bbox.osm.xml")
        # output name for the net file, will be used by osmBuild, randomTrips and
        # sumo-gui
        self.filename("net", ".net.xml")

        if 'osm' in self.data:
            # testing mode
            shutil.copy(data['osm'], self.files["osm"])
        else:
            self.report("Downloading map data")
            osmArgs = ["-b=" + (",".join(map(str, self.data["coords"]))), "-p", self.prefix, "-d", self.tmp]
            if 'osmMirror' in self.data:
                osmArgs += ["-u", self.data["osmMirror"]]
            osmGet.get(osmArgs)

        options = ["-f", self.files["osm"], "-p", self.prefix, "-d", self.tmp]
        self.additionalFiles = []
        self.routenames = []

        if self.data["poly"]:
            # output name for the poly file, will be used by osmBuild and sumo-gui
            self.filename("poly", ".poly.xml")
            options += ["-m", typemaps["poly"]]
            self.additionalFiles.append(self.files["poly"])

        typefiles = [typemaps["net"]]
        # leading space ensures that arguments starting with -- are not
        # misinterpreted as options
        netconvertOptions = " " + osmBuild.DEFAULT_NETCONVERT_OPTS
        netconvertOptions += ",--tls.default-type,actuated"
        # netconvertOptions += ",--default.spreadtype,roadCenter"
        if "pedestrian" in self.data["vehicles"]:
            # sidewalks are already included via typefile
            netconvertOptions += ",--crossings.guess"
            netconvertOptions += ",--osm.sidewalks"
            typefiles.append(typemaps["urban"])
            typefiles.append(typemaps["pedestrians"])
        if "ship" in self.data["vehicles"]:
            typefiles.append(typemaps["ships"])
        if "bicycle" in self.data["vehicles"]:
            typefiles.append(typemaps["bicycles"])
            netconvertOptions += ",--osm.bike-access"
        # special treatment for public transport
        if self.data["publicTransport"]:
            self.filename("stops", "_stops.add.xml")
            netconvertOptions += ",--ptstop-output,%s" % self.files["stops"]
            self.filename("ptlines", "_ptlines.xml")
            self.filename("ptroutes", "_pt.rou.xml")
            netconvertOptions += ",--ptline-output,%s" % self.files["ptlines"]
            self.additionalFiles.append(self.files["stops"])
            self.routenames.append(self.files["ptroutes"])
            netconvertOptions += ",--railway.topology.repair"
        if self.data["leftHand"]:
            netconvertOptions += ",--lefthand"
        if self.data["carOnlyNetwork"]:
            if self.data["publicTransport"]:
                options += ["--vehicle-classes", "publicTransport"]
            else:
                options += ["--vehicle-classes", "passenger"]

        options += ["--netconvert-typemap", ','.join(typefiles)]
        options += ["--netconvert-options", netconvertOptions]

        self.report("Converting map data")
        osmBuild.build(options)
        ptOptions = None
        if self.data["publicTransport"]:
            self.report("Generating public transport schedule")
            self.filename("pt_stopinfos", "stopinfos.xml", False)
            self.filename("pt_vehroutes", "vehroutes.xml", False)
            self.filename("pt_trips", "trips.trips.xml", False)
            ptOptions = [
                "-n", self.files["net"],
                "-e", self.data["duration"],
                "-p", "600",
                "--random-begin",
                "--seed", "42",
                "--ptstops", self.files["stops"],
                "--ptlines", self.files["ptlines"],
                "-o", self.files["ptroutes"],
                "--ignore-errors",
                # "--no-vtypes",
                "--vtype-prefix", "pt_",
                "--stopinfos-file", self.files["pt_stopinfos"],
                "--routes-file", self.files["pt_vehroutes"],
                "--trips-file", self.files["pt_trips"],
                "--min-stops", "0",
                "--extend-to-fringe",
                "--verbose",
            ]
            ptlines2flows.main(ptlines2flows.get_options(ptOptions))

        if self.data["decal"]:
            self.report("Downloading background images")
            tileOptions = [
                "-n", self.files["net"],
                "-t", "100",
                "-d", "background_images",
                "-l", "-300",
            ]
            try:
                os.chdir(self.tmp)
                os.mkdir("background_images")
                tileGet.get(tileOptions)
                self.report("Success.")
                self.decalError = False
            except Exception:
                os.chdir(self.tmp)
                shutil.rmtree("background_images", ignore_errors=True)
                self.report("Error while downloading background images")
                self.decalError = True

        if self.data["vehicles"] or ptOptions:
            # routenames stores all routefiles and will join the items later, will
            # be used by sumo-gui
            randomTripsCalls = []

            self.edges = sumolib.net.readNet(os.path.join(self.tmp, self.files["net"])).getEdges()

            for vehicle, options in self.data["vehicles"].items():
                self.report("Processing %s" % vehicleNames[vehicle])

                self.filename("route", ".%s.rou.xml" % vehicle)
                self.filename("trips", ".%s.trips.xml" % vehicle)

                try:
                    options = self.parseTripOpts(vehicle, options, self.data["publicTransport"])
                except ZeroDivisionError:
                    continue

                if vehicle == "pedestrian" and self.data["publicTransport"]:
                    options += ["--additional-files", ",".join([self.files["stops"], self.files["ptroutes"]])]
                    options += ["--persontrip.walk-opposite-factor", "0.8"]

                randomTrips.main(randomTrips.get_options(options))
                randomTripsCalls.append(options)

                # --validate is not called for pedestrians
                if vehicle == "pedestrian":
                    self.routenames.append(self.files["route"])
                else:
                    self.routenames.append(self.files["trips"])

            # create a batch file for reproducing calls to randomTrips.py
            if os.name == "posix":
                SUMO_HOME_VAR = "$SUMO_HOME"
            else:
                SUMO_HOME_VAR = "%SUMO_HOME%"

            randomTripsPath = os.path.join(
                SUMO_HOME_VAR, "tools", "randomTrips.py")
            ptlines2flowsPath = os.path.join(
                SUMO_HOME_VAR, "tools", "ptlines2flows.py")

            self.filename("build.bat", "build.bat", False)
            batchFile = self.files["build.bat"]
            with open(batchFile, 'w') as f:
                if os.name == "posix":
                    f.write("#!/bin/bash\n")
                if ptOptions is not None:
                    f.write('python "%s" %s\n' %
                            (ptlines2flowsPath, " ".join(map(quoted_str, self.getRelative(ptOptions)))))
                for opts in sorted(randomTripsCalls):
                    f.write('python "%s" %s\n' %
                            (randomTripsPath, " ".join(map(quoted_str, self.getRelative(opts)))))
Пример #12
0
def build(handler, prefix, bbox=False):
    sumo = sumolib.checkBinary('sumo')

    if bbox:
        sumogui = sumolib.checkBinary('sumo-gui')
    else:
        # offline test mode
        sumogui = sumo

    def callSumo(extraopts):
        guisettingsname = prefix + ".view.xml"
        print "Writing gui settings file:", guisettingsname
        with open(guisettingsname, 'w') as f:
            f.write("""
<viewsettings>
    <scheme name="real world"/>
    <delay value="20"/>
</viewsettings>
""")
        configname = prefix + ".sumocfg"
        print "Writing config file:", configname
        opts = [sumo, "-n", netname, "-a", polyname, "--gui-settings-file",
                guisettingsname, "-v", "--no-step-log", "--save-configuration", configname]
        opts += extraopts
        subprocess.call(opts)

        print "Calling SUMO GUI"

        try:
            subprocess.call([sumogui, "-c", configname])
        except:
            print "SUMO GUI canceled"

    if bbox:
        # get the coordinates and cast them to float
        size = map(float, bbox.split(","))
        # calculates the area
        size = (size[0] - size[2]) * (size[3] - size[1])
        areaFactor = abs(size) * 5000
        # to adjust period by the area
        print "Calling osmGet"
        osmGet.get(["-b", bbox, "-p", prefix])
    else:
        # offline test mode
        areaFactor = 1

    print "Calling osmBuild"
    # output name for the osm file, will be used by osmBuild, can be after the
    # process deleted
    osmname = prefix + "_bbox.osm.xml"
    # output name for the net file, will be used by osmBuild, randomTrips and
    # sumo-gui
    netname = prefix + ".net.xml"
    # output name for the poly file, will be used by osmBuild and sumo-gui
    polyname = prefix + ".poly.xml"
    options = ["-f", osmname, "-p", prefix, "-m", polyfile]
    typefiles = []
    netconvertOptions = osmBuild.DEFAULT_NETCONVERT_OPTS + ",--junctions.corner-detail,5"
    if handler.pedestrians.enable:  # drop?
        # sidewalks are already included via typefile
        netconvertOptions += ",--crossings.guess"
        typefiles.append(pedestrianstypefile)
    else:
        typefiles.append(typefile)
    if handler.ships.enable:
        typefiles.append(shipstypefile)
    options += ["--netconvert-typemap", ','.join(typefiles)]
    options += ["--netconvert-options", netconvertOptions]
    osmBuild.build(options)

    if handler.vehicles.enable or handler.bicycles.enable or handler.pedestrians.enable or handler.rails.enable or handler.ships.enable:
        print "Calling randomTrips"
        # routenames stores all routefiles and will join the items later, will
        # be used by sumo-gui
        routenames = []

        if handler.vehicles.enable:
            routename = prefix + ".vehicles.rou.xml"
            tripname = prefix + ".vehicles.trips.xml"
            routenames.append(tripname)
            randomTrips.main(randomTrips.get_options(
                handler.vehicles.parseTripOpts(netname, routename, areaFactor)))
            route2trips.main([routename], outfile=tripname)

        if handler.bicycles.enable:
            routename = prefix + ".bicycles.rou.xml"
            tripname = prefix + ".bicycles.trips.xml"
            routenames.append(tripname)
            randomTrips.main(randomTrips.get_options(
                handler.bicycles.parseTripOpts(netname, routename, areaFactor)))
            route2trips.main([routename], outfile=tripname)

        if handler.pedestrians.enable:
            routename = prefix + ".pedestrians.rou.xml"
            routenames.append(routename)
            randomTrips.main(randomTrips.get_options(
                handler.pedestrians.parseTripOpts(netname, routename, areaFactor)))

        if handler.rails.enable:
            routename = prefix + ".rails.rou.xml"
            tripname = prefix + ".rails.trips.xml"
            routenames.append(tripname)
            randomTrips.main(randomTrips.get_options(
                handler.rails.parseTripOpts(netname, routename, areaFactor)))
            route2trips.main([routename], outfile=tripname)

        if handler.ships.enable:
            routename = prefix + ".ships.rou.xml"
            tripname = prefix + ".ships.trips.xml"
            routenames.append(tripname)
            randomTrips.main(randomTrips.get_options(
                handler.ships.parseTripOpts(netname, routename, areaFactor)))
            route2trips.main([routename], outfile=tripname)

        callSumo(["-r", ",".join(routenames), "--ignore-route-errors"])

    else:
        callSumo([])

    print "Done."