Exemplo n.º 1
0
    def create_trips(type_class):

        pre_fix = type_class[:3]
        route_file = '%s/%s.%s.rou.xml' % (SUMO.OUTPUTDIR, SUMO.PREFIX_FILE,
                                           type_class)
        trip_file = '%s/%s.%s.trips.xml' % (SUMO.OUTPUTDIR, SUMO.PREFIX_FILE,
                                            type_class)
        net_file = '%s/%s' % (SUMO.OUTPUTDIR, SUMO.NET_FILE)
        fringe_factor = int(SUMO.FRINGE_FACTOR[type_class])
        end_time = int(SUMO.ENDTIME[type_class])
        period = int(SUMO.PERIOD[type_class])

        if os.path.isfile(net_file):

            if type_class == "pedestrian":

                cl = '--seed %d  --pedestrians --max-distance 3000 --fringe-factor %d  --prefix %s -n %s -r %s -p %d -e %d -o %s' % (
                    SUMO.SEED, fringe_factor, pre_fix, net_file, route_file,
                    period, end_time, trip_file)

            else:

                cl = '--seed %d  --vehicle-class %s --min-distance 1000 --fringe-factor %d  --prefix %s -n %s -r %s -p %d -e %d -o %s' % (
                    SUMO.SEED, type_class, fringe_factor, pre_fix, net_file,
                    route_file, period, end_time, trip_file)

            args = shlex.split(cl)

            randomTrips.main(randomTrips.get_options(args))
            '''
            if type_class ==  "pedestrian" :

                cl = '%s/randomTrips.py --seed %d  --pedestrians --max-distance 3000 --fringe-factor %d  --prefix %s -n %s -r %s -p %d -e %d -o %s' % (SUMO.TOOLDIR,SUMO.SEED,fringe_factor,pre_fix,net_file,route_file,period,end_time,trip_file)

            else :

                cl = '%s/randomTrips.py --seed %d  --vehicle-class %s --min-distance 1000 --fringe-factor %d  --prefix %s -n %s -r %s -p %d -e %d -o %s'  % (SUMO.TOOLDIR,SUMO.SEED,type_class,fringe_factor,pre_fix,net_file,route_file,period,end_time,trip_file)
            
            args = shlex.split(cl)

            process = subprocess.Popen(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
            
            stdout, erro = process.communicate()

            if stdout :
                click.echo(stdout)
                click.echo("Rotas[%s]: %s %s) - done" % (type_class,route_file,trip_file))

            if erro :
                click.echo(erro)
                click.echo("ERROR: Falha na criação das rotas para %s / arquivo  %s " % (type_class,route_file))

            '''
        else:
            click.echo(
                "ERROR: Não encontrado o arquivo %s para criação das rotas" %
                net_file)
Exemplo n.º 2
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"'
         ]))
    def _generate_route_file(self, seed):
        """
        Generates vehicles for each possible route in the scenario and writes
        them to file. Returns the location of the sumocfg file.
        """

        valid_route_generation_methods = ['legacy', 'randomTrips.py', 'activitygen']

        route_name = str(self._port) + '_routes.rou.xml'
        route_file = os.path.join(self.scenario_path, route_name)
        net_file = os.path.join(self.scenario_path, self._net_file)

        assert self.parameters['route_generation_method'] in valid_route_generation_methods

        if self.parameters['route_generation_method'] == 'randomTrips.py':
            logging.debug('Using sumo/tools/randomTrips.py to generate trips')

            params = ['-n', net_file, '-o', route_file, '--validate']

            if seed is not None:
                params += ['--seed', str(seed)]

            randomTrips.main(randomTrips.get_options(self.parameters['trips_generate_options'] + params))

        elif self.parameters['route_generation_method'] == 'activitygen':
            logging.debug('Using activitygen and duarouter to generate trips based on stat-file')

            # Get the path of the sumotools activitygen binary
            ACTIVITYGEN = sumolib.checkBinary('activitygen')

            activitygen_args = [ACTIVITYGEN, '--net-file', net_file,
                                '--output-file', route_file]

            # Add passed through arguments

            activitygen_args += self.parameters['activitygen_options']

            if '--stat-file' not in self.parameters['activitygen_options']:
                found_stat_file = self.get_stat_file(scenario_path=self.scenario_path)
                activitygen_args += ['--stat-file', found_stat_file]

            if seed is not None:
                activitygen_args += ['--seed', str(seed)]
            else:
                activitygen_args += ['--random']

            subprocess.call(activitygen_args)

        elif self.parameters['route_generation_method'] == 'legacy':
            self._generate_route_file_manual(seed=seed, route_file=route_file)
        else:
            raise Exception(f"self.parameters['route_generation_method'] "
                            f"was {self.parameters['route_generation_method']} instead of one of "
                            f"{valid_route_generation_methods}")
Exemplo n.º 4
0
def prepare_trips(base_dir, road_map_file_path, edge_lengths_per_vehicle_type, trip_settings):
    data = {u'vehicles': {u'passenger': {u'count': trip_settings.passenger_count, u'fringeFactor': 5},
                          u'motorcycle': {u'count': trip_settings.motorcycle_count, u'fringeFactor': 2},
                          u'bus': {u'count': trip_settings.bus_count, u'fringeFactor': 2},
                          u'taxi': {u'count': trip_settings.taxi_count, u'fringeFactor': 2}}}

    for vehicle, vehicle_options in data["vehicles"].items():
        route_file_name = '{}/{}.rou.xml'.format(base_dir, vehicle)
        trips_file_name = '{}/{}.trips.xml'.format(base_dir, vehicle)

        try:
            vehicle_options = parse_trip_opts(road_map_file_path, route_file_name, trips_file_name,
                                              edge_lengths_per_vehicle_type, vehicle, vehicle_options, trip_settings)
        except ZeroDivisionError:
            continue

        randomTrips.main(randomTrips.get_options(vehicle_options))
Exemplo n.º 5
0
 def generate(self, scn):
     randomTrips.main(
         randomTrips.get_options([
             "-n",
             scn.get("net_file"),
             # "-o", scenario_dir + "/data/model.trip.xml",
             "-o",
             scn.get("demand_file"),
             "--route-file",
             os.path.join(scn.get("dir"),
                          scn.get("demand_type") + ".rou.xml"),
             "--prefix",
             scn.get("prefix"),
             "--fringe-factor",
             "100",
             "--validate"
         ]))
     print("DM/RT/generate")
Exemplo n.º 6
0
    def build_routes_from_densities(self, sumo_net, net_xml, routes_dir,
                                    densities, duration):
        self.additionalFiles = []
        self.routenames = []
        publicTransport = False

        vehicles = {
            type_: {
                'count': count,
                'fringeFactor': 15
            }
            for type_, count in densities.items()
        }

        # This code is extracted from SUMO/tools/osmWebWizard.py lin 226
        # Note the pedestrian and publicTransport code is present but not supported/tested
        self.edges = sumo_net.getEdges()

        for vehicle, options in vehicles.items():
            print("Processing vehicle %s" % vehicle)

            self.files["route"] = "%sosm.%s.rou.xml" % (routes_dir, vehicle)
            self.files["trips"] = "%sosm.%s.trips.xml" % (routes_dir, vehicle)
            self.files["detour"] = "%sdetour.xml" % (routes_dir)

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

            #if vehicle == "pedestrian" and publicTransport:
            #    options += ["--additional-files", ",".join([self.files["stops"], self.files["ptroutes"]])]
            if os.path.isfile(self.files["detour"]):
                options += [
                    "--additional-files", ",".join([self.files["detour"]])
                ]
            randomTrips.main(randomTrips.get_options(options))

            # --validate is not called for pedestrians
            if vehicle == "pedestrian":
                self.routenames.append(self.files["route"])
            else:
                self.routenames.append(self.files["trips"])
Exemplo n.º 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))))
Exemplo n.º 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."
 def createRandomTrips(self):
     randomTrips.main(
         randomTrips.get_options([
             '--net-file', self.net, '--output-trip-file',
             'TempData/Rou/ped.trip.xml', '--prefix', 'ped',
             '--persontrips', '-e', '4000', '-p', '1.93', '--random',
             '--validate'
         ]))
     randomTrips.main(
         randomTrips.get_options([
             '--net-file', self.net, '--output-trip-file',
             'TempData/Rou/pCar.trip.xml', '--prefix', 'pCar',
             '--persontrips', '--trip-attributes', 'modes="public car"',
             '-e', '4000', '-p', '0.91', '--random', '--validate'
         ]))
     randomTrips.main(
         randomTrips.get_options([
             '--net-file', self.net, '-o', 'TempData/Rou/vehicle.trip.xml',
             '--prefix', 'veh', '--trip-attributes', 'personNumber="2"',
             '-e', '4000', '-p', '1.88', '--random', '--validate'
         ]))
     randomTrips.main(
         randomTrips.get_options([
             '--net-file', self.net, '-o', 'TempData/Rou/truck.trip.xml',
             '--prefix', 'truck', '--vehicle-class', 'truck', '-e', '5000',
             '-p', '20', '--random', '--validate'
         ]))
     randomTrips.main(
         randomTrips.get_options([
             '--net-file', self.net, '-o', 'TempData/Rou/lorry.trip.xml',
             '--prefix', 'trailer', '--vehicle-class', 'trailer', '-e',
             '5000', '-p', '100', '--random', '--validate'
         ]))
     randomTrips.main(
         randomTrips.get_options([
             '--net-file', self.net, '-o',
             'TempData/Rou/motorcycle.trip.xml', '--prefix', 'motorcycle',
             '--vehicle-class', 'motorcycle', '-e', '5000', '-p', '25',
             '--random', '--validate'
         ]))
     randomTrips.main(
         randomTrips.get_options([
             '--net-file', self.net, '-o', 'TempData/Rou/moped.trip.xml',
             '--prefix', 'moped', '--vehicle-class', 'moped', '-e', '5000',
             '-p', '30', '--random', '--validate'
         ]))
     randomTrips.main(
         randomTrips.get_options([
             '--net-file', self.net, '-o', 'TempData/Rou/bike.trip.xml',
             '--prefix', 'bik', '--vehicle-class', 'bicycle', '-e', '5000',
             '-p', '30', '--random', '--validate'
         ]))
Exemplo n.º 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))))
Exemplo n.º 11
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."
else:
    sys.exit("please declare environment variable 'SUMO_HOME'")

import traci  # noqa
import randomTrips  # noqa

if __name__ == "__main__":

    net = 'pedestrians.net.xml'
    # 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',
            '0',
            '--trip-attributes',
            'departPos="random" arrivalPos="random"',
            '--binomial',
            '4',
            '--period',
            '35'
        ]))
Exemplo n.º 13
0
 def generate(self):
     logging.info(
         f'Generating trips for vehicle class {self.vclass} with density of {self.density} veh/km/h'
     )
     randomTrips.main(
         randomTrips.get_options(dict_to_list(self.options) + self.flags))
Exemplo n.º 14
0
        os.path.join(os.path.dirname(__file__), '..', '..', '..', '..',
                     "tools"))  # tutorial in tests
    sys.path.append(
        os.path.join(
            os.environ.get(
                "SUMO_HOME",
                os.path.join(os.path.dirname(__file__), "..", "..", "..")),
            "tools"))  # tutorial in docs
    from sumolib import checkBinary  # noqa
except ImportError:
    sys.exit("please declare environment variable 'SUMO_HOME'")

netgenBinary = checkBinary('netgenerate')
jtrrouterBinary = checkBinary('jtrrouter')
sumoBinary = checkBinary('sumo')
import randomTrips  # noqa

call([netgenBinary, '-c', 'data/manhattan.netgcfg'])
randomTrips.main(
    randomTrips.get_options([
        '--flows', '100', '-b', '0', '-e', '1', '-n', 'data/net.net.xml', '-o',
        'data/flows.xml', '--jtrrouter', '--trip-attributes',
        'departPos="random" departSpeed="max"'
    ]))
call([jtrrouterBinary, '-c', 'data/manhattan.jtrrcfg'])
call([
    sumoBinary, '-c', 'data/manhattan.sumocfg', '--duration-log.statistics',
    '-e'
    '1000'
])
Exemplo n.º 15
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)
Exemplo n.º 16
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))))
Exemplo n.º 17
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()
Exemplo n.º 18
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)))))
Exemplo n.º 19
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)))))
Exemplo n.º 20
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()