Ejemplo n.º 1
0
 def create_random_demand(self):
     ''' create random flows'''
     randomTrips.main(
         randomTrips.get_options([
             '--flows',
             str(self.vehicles_count), '-b', '0', '-e', '1', '-n',
             'data/network/net.net.xml', '-o', 'data/demand/demand.xml',
             '--jtrrouter', '--trip-attributes',
             'departPos="random" departSpeed="max"'
         ]))
Ejemplo n.º 2
0
        sumoBinary = checkBinary('sumo-gui')

    net = 'pedcrossing.net.xml'
    # build the multi-modal network from plain xml inputs
    subprocess.call([checkBinary('netconvert'),
                     '-c', os.path.join('data', 'pedcrossing.netccfg'),
                     '--output-file', net],
                    stdout=sys.stdout, stderr=sys.stderr)

    # generate the pedestrians for this simulation
    randomTrips.main(randomTrips.get_options([
        '--net-file', net,
        '--output-trip-file', 'pedestrians.trip.xml',
        '--seed', '42',  # make runs reproducible
        '--pedestrians',
        '--prefix', 'ped',
        # prevent trips that start and end on the same edge
        '--min-distance', '1',
        '--trip-attributes', 'departPos="random" arrivalPos="random"',
        '--binomial', '4',
        '--period', '35']))

    # this is the normal way of using traci. sumo is started as a
    # subprocess and then the python script connects and runs
    sumoProcess = subprocess.Popen([sumoBinary,
                                    '-c', os.path.join('data', 'run.sumocfg'),
                                    '--remote-port', str(PORT)],
                                   stdout=sys.stdout, stderr=sys.stderr)
    run()
    sumoProcess.wait()
Ejemplo n.º 3
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))))
Ejemplo n.º 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])

        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))))
Ejemplo n.º 5
0
        os.path.join(xml_file_path, SUMOCFG_FILE))
    traci_files['tls_adaptation'] = os.path.abspath(
        os.path.join(xml_file_path, TLS_CYCLE_FILE))
    traci_files['sumo_command'] = [
        SUMO_BINARY,
        "-c",
        traci_files['sumocfg_xml'],
        "--additional-files",
        traci_files['additional_xml'] + ',' + traci_files['tls_adaptation'],
        "--no-warnings",
    ]
    return traci_files


if __name__ == "__main__":
    xml_file_path = sys.argv[1]
    SUMO_BINARY = sys.argv[2]
    algorithm_type = sys.argv[3]
    traci_files = gen_traci_files(xml_file_path)
    random_trips_args = [
        '--net-file', traci_files['net_xml'], '--route-file',
        traci_files['rou_xml'], '--fringe-factor', '9.0', '--end', 1000
    ]
    trip_options = randomTrips.get_options(random_trips_args)
    randomTrips.main(trip_options)
    xml_utils.gen_additional_file(traci_files['net_xml'],
                                  traci_files['additional_xml'],
                                  traci_files['entry_exit_logging'])
    optimizer.run_optimizer(traci_files,
                            algorithm_type,
                            num_members_per_generation=5)
Ejemplo n.º 6
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."
Ejemplo n.º 7
0
                u'fringeFactor': 2
            },
            u'taxi': {
                u'count': 2,
                u'fringeFactor': 2
            }
        }
    }

    edges = net.readNet(config.road_map_file_path).getEdges()
    for vehicle, options in data["vehicles"].items():
        route_file_name = '{}/{}.rou.xml'.format(config.base_dir, vehicle)
        trips_file_name = '{}/{}.trips.xml'.format(config.base_dir, vehicle)

        try:
            options = parse_trip_opts(config.road_map_file_path,
                                      float(config.end))
        except ZeroDivisionError:
            continue

        randomTrips.main(randomTrips.get_options(options))

    # start sumo as a sub process
    traci.start([
        checkBinary('sumo') if main_options.nogui else checkBinary('sumo-gui'),
        "-c", "{}/map.sumo.cfg".format(config.base_dir), "-a",
        "{}/newTLS.add.xml".format(config.base_dir)
    ])

    run()