• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python sumolib.checkBinary函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sumolib.checkBinary函数的典型用法代码示例。如果您正苦于以下问题:Python checkBinary函数的具体用法?Python checkBinary怎么用?Python checkBinary使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了checkBinary函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: get_start_cmd

 def get_start_cmd(self, init_time, gui=False, withdet=False):
     """
     Raise SUMO and run the simulation.
     :param init_time: strategy to controll traffic light
     :param gui: with GUI
     :param withdet: with detector(e1,e2,e3)
     :return:
     """
     self.init_time = init_time
     if gui:
         sumoBinary = checkBinary('sumo-gui')
     else:
         sumoBinary = checkBinary('sumo')
     if withdet:
         sumocfg = self.sumocfg
     else:
         sumocfg = self.sumocfg_nodet
     # self.task_record_dir = os.path.join(self.output_dir, init_time)
     self.task_record_dir = self.output_dir
     if not os.path.isdir(self.task_record_dir):
         os.makedirs(self.task_record_dir)
     self.summary_file = os.path.join(self.task_record_dir, self.netname+'_summary.xml')
     self.gen_detectors()
     self.sumocfg = self.gen_sumocfg()
     self.sumocfg_nodet = self.gen_sumocfg(withdetector=False)
     sumo_env = os.environ.copy()
     sumo_env['SUMO_HOME'] = sumo_root
     # sumoProcess = subprocess.Popen([sumoBinary, '-c', sumocfg, '--remote-port', str(port),
     #                                 '--summary', self.summary_file],
     #                                env=sumo_env, stdout=PIPE, stderr=PIPE)
     sumoCMD = [sumoBinary, '-c', sumocfg, '--summary', self.summary_file,
                '--time-to-teleport', '-1']
     # sumoProcess.wait()
     return sumoCMD, sumo_env
开发者ID:allenwoods,项目名称:parasys,代码行数:34,代码来源:create_cfg.py


示例2: build

def build(args=None, bindir=None):
    (options, args) = optParser.parse_args(args=args)

    if ((options.oldapi_prefix and options.osm_file) or
            not (options.oldapi_prefix or options.osm_file)):
        optParser.error(
            "exactly one of the options --osm-file and --oldapi-prefix must be supplied")
    if options.typemap and not path.isfile(options.typemap):
        # fail early because netconvert may take a long time
        optParser.error('typemap file "%s" not found' % options.typemap)
    if not (options.vehicle_classes in vclassRemove):
        optParser.error('invalid vehicle class "%s" given' %
                        options.vehicle_classes)
    if not path.isdir(options.output_directory):
        optParser.error('output directory "%s" does not exist' %
                        options.output_directory)

    netconvert = sumolib.checkBinary('netconvert', bindir)
    polyconvert = sumolib.checkBinary('polyconvert', bindir)

    netconvertOpts = [netconvert]
    if options.pedestrians:
        netconvertOpts += ['--sidewalks.guess', '--crossings.guess']
    if options.netconvert_typemap:
        netconvertOpts += ["-t", options.netconvert_typemap]
    netconvertOpts += options.netconvert_options.split(',') + ['--osm-files']
    polyconvertOpts = ([polyconvert] + options.polyconvert_options.split(',') +
                       ['--type-file', options.typemap, '--osm-files'])

    prefix = options.oldapi_prefix
    if prefix:  # used old API
        num = options.tiles
        tiles = ",".join(["%s%s_%s.osm.xml" % (prefix, i, num)
                          for i in range(num)])
        netconvertOpts += [tiles]
        polyconvertOpts += [tiles]
    else:  # used new API
        netconvertOpts += [options.osm_file]
        polyconvertOpts += [options.osm_file]
        prefix = path.basename(options.osm_file).replace('.osm.xml', '')

    if options.prefix:
        prefix = options.prefix

    basename = path.join(options.output_directory, prefix)
    netfile = prefix + '.net.xml'
    netconvertOpts += vclassRemove[options.vehicle_classes] + ["-o", netfile]

    # write config
    cfg = basename + ".netccfg"
    subprocess.call(netconvertOpts + ["--save-configuration", cfg])
    subprocess.call([netconvert, "-c", cfg])

    if options.typemap:
        # write config
        cfg = basename + ".polycfg"
        polyconvertOpts += ["-n", netfile, "-o", prefix + '.poly.xml']
        subprocess.call(polyconvertOpts + ["--save-configuration", cfg])
        subprocess.call([polyconvert, "-c", cfg])
开发者ID:fieryzig,项目名称:sumo,代码行数:59,代码来源:osmBuild.py


示例3: build

def build(args=None, bindir=None):
    (options, args) = optParser.parse_args(args=args)
    netconvert = sumolib.checkBinary('netconvert', bindir)
    polyconvert = sumolib.checkBinary('polyconvert', bindir)

    if ((options.oldapi_prefix and options.osm_file) or
            not (options.oldapi_prefix or options.osm_file)):
        optParser.error(
            "exactly one of the options --osm-file and --oldapi-prefix must be supplied")
    if options.typemap and not path.isfile(options.typemap):
        # fail early because netconvert may take a long time
        optParser.error('typemap file "%s" not found' % options.typemap)
    if not (options.vehicle_classes in vclassRemove):
        optParser.error('invalid vehicle class "%s" given' %
                        options.vehicle_classes)
    if not path.isdir(options.output_directory):
        optParser.error('output directory "%s" does not exist' %
                        options.output_directory)

    netconvertOpts = ' ' + \
        ' '.join(options.netconvert_options.split(',')) + ' --osm-files '
    if options.pedestrians:
        netconvertOpts = " --sidewalks.guess --crossings.guess" + \
            netconvertOpts
    if options.netconvert_typemap:
        netconvertOpts = " -t " + options.netconvert_typemap + netconvertOpts
    polyconvertOpts = ' ' + \
        ' '.join(options.polyconvert_options.split(',')) + \
        ' --type-file %s --osm-files ' % options.typemap

    prefix = options.oldapi_prefix
    if prefix:  # used old API
        num = options.tiles
        for i in range(num):
            if i != 0:
                netconvertOpts += ","
                polyconvertOpts += ","
            netconvertOpts += "%s%s_%s.osm.xml" % (prefix, i, num)
            polyconvertOpts += "%s%s_%s.osm.xml" % (prefix, i, num)

    else:  # used new API
        netconvertOpts += options.osm_file
        polyconvertOpts += options.osm_file
        prefix = path.basename(options.osm_file).replace('.osm.xml', '')

    if options.prefix:
        prefix = options.prefix

    remove = vclassRemove[options.vehicle_classes]
    netfile = path.join(options.output_directory, prefix + '.net.xml')
    polyfile = path.join(options.output_directory, prefix + '.poly.xml')

    call(netconvert + netconvertOpts + remove + " -o %s" % netfile)
    if options.typemap:
        call(polyconvert + polyconvertOpts + " -n %s -o %s" %
             (netfile, polyfile))
开发者ID:RamonHPSilveira,项目名称:urbansim,代码行数:56,代码来源:osmBuild.py


示例4: __inner_run__

    def __inner_run__(self, output_file):
        if self._options.gui:
            sumoBinary = checkBinary('sumo-gui')
            self.__sumoProcess = subprocess.Popen(
                [sumoBinary,"-W",
                "-n", self.conf.network_file,
                "-r", self.conf.route_file,
                "--tripinfo-output", output_file,
                "--remote-port", str(self.conf.port),
                "--gui-settings-file", self.conf.gui_setting_file,
                "--step-length", "1",
                "-v", "true",
                "--time-to-teleport", "-1"],
                stdout = sys.stdout, stderr=sys.stderr)
            time.sleep(20)

        else:
            sumoBinary = checkBinary('sumo')
            self.__sumoProcess = subprocess.Popen(
                [sumoBinary, "-W",
                "-n", self.conf.network_file,
                "-r", self.conf.route_file,
                "--tripinfo-output", output_file,
                "--remote-port", str(self.conf.port),
                "--step-length", "1",
                "-v", "true",
                "--time-to-teleport", "-1"],
                stdout = sys.stdout, stderr=sys.stderr)
            time.sleep(20)

        traci.init(self.conf.port)
        self.initIteration()

        while True:
            traci.simulationStep()

            if traci.simulation.getMinExpectedNumber() <= 0:
                break

            self.stepProcess()

            if traci.simulation.getCurrentTime() % self.conf.short_term_sec == 0:
                self.can_change_lane_list = []
                self.want_chage_vehicle_list = []

        self.endIteration()
        traci.close()

        if self._options.gui:
            os.system('pkill sumo-gui')
        sys.stdout.flush()
开发者ID:gg-uah,项目名称:ParkiNego,代码行数:51,代码来源:simulator.py


示例5: main

def main(options):
    if options.sumo is None:
        SUMO = sumolib.checkBinary('sumo')
    else:
        SUMO = options.sumo

    statsRetrievers = [(Statistics("%11s" % key), build_retriever(key)) for key in [
        'Inserted',
        'Running',
        'RouteLength',
        'Duration',
        'WaitingTime',
        'TimeLoss',
        'DepartDelay',
    ]]

    for i in range(options.numRuns):
        sys.stdout.write('.')
        sys.stdout.flush()
        seed = str(random.randint(0, 2**31))
        output = check_output([SUMO, '-c', options.config,
                               '--duration-log.statistics',
                               '--no-duration-log', 'false',
                               '--seed', seed])
        for stats, retriever in statsRetrievers:
            stats.add(retriever(output), seed)
    print()
    for stats, retriever in statsRetrievers:
        print(stats)
开发者ID:behrisch,项目名称:sumo,代码行数:29,代码来源:averageRuns.py


示例6: __init__

    def __init__(self, params, withDefaultDemand=True):
        Scenario.__init__(self, self.THIS_DIR)
        self.params = params
        if "equipment-rate" not in self.params:
            self.params["equipment-rate"] = 1
        # network
        if fileNeedsRebuild(os.path.join(self.THIS_DIR, self.NET_FILE), "netconvert"):
            netconvert = sumolib.checkBinary("netconvert")
            subprocess.call([netconvert, "-c", os.path.join(self.THIS_DIR, "build.netc.cfg")])
        # build the demand model (streams)
        if withDefaultDemand:
            self.demand = demandGenerator.Demand()
            for f in flowsRiLSA1:
                for rel in f[1]:
                    prob = rel[2] / 100.
                    iprob = 1. - prob

                    pkwEprob = iprob * self.params["equipment-rate"]
                    pkwNprob = iprob - pkwEprob
                    lkwEprob = prob * self.params["equipment-rate"]
                    lkwNprob = prob - lkwEprob

                    self.demand.addStream(demandGenerator.Stream(f[0] + "__" + rel[0], 0, 3600, rel[1], f[0], rel[0],
                                                                 {"passenger": pkwEprob,
                                                                  "COLOMBO_undetectable_passenger": pkwNprob,
                                                                  "hdv": lkwEprob,
                                                                  "COLOMBO_undetectable_hdv": lkwNprob}))
            if fileNeedsRebuild(self.fullPath("routes.rou.xml"), "duarouter"):
                self.demand.build(
                    0, 3600, self.fullPath(self.NET_FILE), self.fullPath("routes.rou.xml"))
            self.demandName = self.fullPath("routes.rou.xml")

        self.netName = self.sandboxPath(self.NET_FILE)
        shutil.copy(
            self.fullPath(self.NET_FILE), self.sandboxPath(self.NET_FILE))
开发者ID:fieryzig,项目名称:sumo,代码行数:35,代码来源:rilsa1_out_tls24.py


示例7: makeConfigFile

    def makeConfigFile(self):
        "Save the configuration for SUMO in a file"

        self.report("Generating configuration file")

        self.filename("guisettings", ".view.xml")
        with open(self.files["guisettings"], 'w') as f:
            f.write("""
<viewsettings>
    <scheme name="real world"/>
    <delay value="20"/>
</viewsettings>
""")
        sumo = sumolib.checkBinary("sumo")

        self.filename("config", ".sumocfg")
        opts = [sumo, "-n", self.files["net"], "--gui-settings-file", self.files["guisettings"],
                "--duration-log.statistics",
                "--device.rerouting.adaptation-steps", "180",
                "-v", "--no-step-log", "--save-configuration", self.files["config"], "--ignore-route-errors"]

        if self.routenames:
            opts += ["-r", ",".join(self.routenames)]

        if len(self.additionalFiles) > 0:
            opts += ["-a", ",".join(self.additionalFiles)]

        subprocess.call(opts)
开发者ID:fieryzig,项目名称:sumo,代码行数:28,代码来源:osmWebWizard.py


示例8: setUpClass

    def setUpClass(cls):
        """ setup generates all sumo files - once. """
        
        netcon_bin = sumolib.checkBinary('netconvert')
#        print ('xxxxxxxxxxxxxxxxxxx', netcon_bin)
        
        for node_file, net_file in [
                #(NODEFILE_2D, NETFILE_2D),
                (NODEFILE_3D, NETFILE_3D)
        ]:
            
            command    = [netcon_bin,
                          "-n", node_file,
                          "-e", EDGEFILE,
                          "-o", net_file,
                          "--offset.disable-normalization"]

            netconvertProcess = subprocess.call(
                command,
                stdout=sys.stdout,
                stderr=sys.stderr)
            
#        cls.sumo_net_2d = sumolib.net.readNet(
#            NETFILE_2D,
#            withInternal=True)

        cls.sumo_net = sumolib.net.readNet(
            NETFILE_3D,
            withInternal=True)
开发者ID:planetsumo,项目名称:sumo,代码行数:29,代码来源:unittests_shapes_coords_3d.py


示例9: build

 def build(self, b, e, netName="net.net.xml", routesName="input_routes.rou.xml", sampleFactor=None):
     vehicles = []
     running = 0
     for s in self.streams:
         vehicles.extend(s.toVehicles(b, e, len(vehicles), sampleFactor))
     fdo = tempfile.NamedTemporaryFile(mode="w", delete=False)
     fdo.write("<routes>\n")
     for v in sorted(vehicles, key=lambda veh: veh.depart):
         via = ""
         if v._via != None:
             via = ' via="%s"' % v._via
         if v.vType == "pedestrian":
             fdo.write('    <person id="%s" depart="%s" type="pedestrian"><walk from="%s" to="%s"/></person>\n' %
                       (v.id, v.depart, v.fromEdge, v.toEdge))
         else:
             fdo.write('    <trip id="%s" depart="%s" from="%s" to="%s" type="%s" %s/>\n' %
                       (v.id, v.depart, v.fromEdge, v.toEdge, v.vType, via))
     fdo.write("</routes>")
     fdo.close()
     duarouter = sumolib.checkBinary("duarouter")
     print "netName > %s" % netName
     print "routesName > %s" % routesName
     # aeh, implicitly setting --no-warnings is not nice, is it?; and the
     # need to dump generated vtypes to a temporary file as well
     retCode = subprocess.call([duarouter, "-v", "-n", netName,  "-t", fdo.name, "-o", routesName,
                                "--no-warnings", "--additional-files", "vtypes.add.xml", "--vtype-output", "tmp.add.xml"])
     os.remove(fdo.name)
开发者ID:sequielo,项目名称:sumo,代码行数:27,代码来源:demand.py


示例10: gen_network

 def gen_network(self, xnumber, ynumber, xlength, ylength,
                 nettype='grid', tlstype='static'):
     """
     Generate network model
     :param xnumber: nodes on x axis
     :param ynumber: nodes on y axis
     :param xlength: length of each edge on x axis
     :param ylength: length of each edge on y axis
     :param nettype: type of network, sumo support 'grid', 'spider', 'random'.
     :param tlstype:
     :return:
     """
     if int(xnumber) < 2 or int(ynumber) < 2:
         if xnumber == ynumber == str(1) and xlength == ylength:
             self.gen_intersection(xlength, tlstype)
             return 0
         else:
             raise ValueError('Grid sharp is not supported(yet)')
     netgenerate = checkBinary('netgenerate')
     netgenProcessor = subprocess.Popen([netgenerate, '--%s' % nettype,
                                         '--grid.x-number', xnumber, '--grid.y-number', ynumber,
                                         '--grid.x-length', xlength, '--grid.y-length', ylength,
                                         '--tls.guess', 'true', '--tls.default-type', tlstype,
                                         '--default.lanenumber', '2',
                                         '--check-lane-foes.all', 'true',
                                         '--%s.attach-length' % nettype, xlength,
                                         '--plain-output-prefix',
                                         os.path.join(self.data_dir, self.netname, self.netname),
                                         '-o', self.netfile], stdout=sys.stdout, stderr=sys.stderr)
开发者ID:allenwoods,项目名称:parasys,代码行数:29,代码来源:create_cfg.py


示例11: main

def main(args):
    sumoBinary = sumolib.checkBinary('sumo')
    sumo_call = [sumoBinary, "-c", "data/hello.sumocfg",
                 "--remote-port", str(PORT_TRACI),
                 "--netstate-dump", "rawdump.xml",
                 "--no-step-log"]
    sumoProcess = subprocess.Popen(
        sumo_call, stdout=sys.stdout, stderr=sys.stderr)
    traci.init(PORT_TRACI)

    for step in range(161):
        traci.simulationStep()
        if step == 120:
            print(traci.vehicle.getDistance('Stapler_00'))
            traci.vehicle.setRoute('Stapler_00', ('ed1', 'ed5'))
            print(traci.vehicle.getRoute('Stapler_00'))
            assert(traci.vehicle.getRoute('Stapler_00')
                   == ['ed0', 'ed1', 'ed5'])
            print(traci.vehicle.getDistance('Stapler_00'))
        if step == 122:
            assert(traci.vehicle.getRoute('Stapler_00')
                   == ['ed0', 'ed1', 'ed5'])
            print(traci.vehicle.getDistance('Stapler_00'))
            traci.vehicle.setRouteID('Stapler_00', "short")
            print(traci.vehicle.getRoute('Stapler_00'))
            print(traci.vehicle.getDistance('Stapler_00'))
    traci.close()
    sumoProcess.wait()
开发者ID:planetsumo,项目名称:sumo,代码行数:28,代码来源:runner.py


示例12: computeRoutesFromFlows

def computeRoutesFromFlows(netFile, detFile, flowFile, tazFile, grpFile, dfrouFile, emittFile, poiFile, vssFile,
                           beginSecs, endSecs, departPos, keepLongerRoutes, incUnusedRoutes, xmlValidation, routesForAll):
    shortRate = 0.1
    removeEmpty = True

    logger.info("............... Run the garouter ...")
    logger.info("Net file           : %s" % netFile)
    logger.info("Detection file     : %s" % detFile)
    logger.info("Flow measure file  : %s" % flowFile)
    logger.info("Taz file           : %s" % tazFile)
    logger.info("O/D group file     : %s" % grpFile)
    logger.info("DFRoute file       : %s" % dfrouFile)
    logger.info("Emitter file       : %s" % emittFile)
    logger.info("POI file           : %s" % poiFile)
    #logger.info("VSS file           : %s" % vssFile)
    logger.info("Begin secs         : %d" % beginSecs)
    logger.info("End secs           : %d" % endSecs)
    logger.info("Depart pos         : %s" % departPos)
    #logger.info("Keep longer routes : %s" % keepLongerRoutes)
    #logger.info("Inc. unused routes : %s" % incUnusedRoutes)
    logger.info("XML validation     : %s" % xmlValidation)
    logger.info("Shortest routes rate: %f" % shortRate)
    logger.info("Remove empty dets  : %s" % str(removeEmpty))
    #logger.info("Routes for all     : %s" % routesForAll)


    # Run the garouter
    garouterBin = checkBinary('garouter')
    options = ["--net-file", netFile,
               "--taz-file", tazFile,
               "--od-groups-file", grpFile,
               "--detector-files", detFile,
               "--measure-files", flowFile,
               "--routes-output", dfrouFile,
               "--emitters-output", emittFile,
              #"--routes-for-all", routesForAll,
               "--detectors-poi-output", poiFile,
               #"--variable-speed-sign-output", vssFile,
               "--departpos", departPos,
               "--shortest-routes-rate", str(shortRate),
               "--remove-empty-detectors", str(removeEmpty),
                #"--keep-longer-routes", keepLongerRoutes,
               #"--include-unused-routes", incUnusedRoutes,
               "--begin", str(beginSecs),
               "--end", str(endSecs),
               #"--xml-validation", xmlValidation,
               "--verbose"]
    #options = ["-c", os.path.join(const.BASE_DIR, const.CONFIG_DIR, "garouter.garcfg")]
    status = subprocess.call([garouterBin] + options,
                             stdout = sys.stdout,
                             stderr = sys.stderr)

    if status != 0:
        logger.critical("Fail: garouter terminated with error status [%s]" % status)
        sys.exit(1)
    else:
        logger.info("Success: garouter finished with status [%s]" % status)

    sys.stdout.flush()
开发者ID:gg-uah,项目名称:GARouter,代码行数:59,代码来源:runner.py


示例13: main

def main():
    # initialize all the required arguments
    args = get_options()
    if args.gui_enabled:
        sumo_path = checkBinary('sumo-gui')
    else:
        sumo_path = checkBinary('sumo')
    cfg_path = load_cfg(args.scenario)
    traci_port = args.traci_port

    sumo_process = subprocess.Popen("%s -c %s --remote-port %s" % (sumo_path, cfg_path, traci_port), stdout=sys.stdout)
    traci.init(int(traci_port))
    if args.event_enabled:
        run_ere(args.scenario, args.closed_roads.split(","), 300, 1200)
    else:
        run()
    sumo_process.wait()
开发者ID:ShenWangDCU,项目名称:adanrr,代码行数:17,代码来源:runner.py


示例14: __init__

 def __init__(self, options):
          # this script has been called from the command line. It will start sumo as a
     # server, then connect and run
     if options.gui:
         sumoBinary = checkBinary('sumo-gui')
     else:
         sumoBinary = checkBinary('sumo')
          
     self.rounds = 1000
     self.sumoProcess = subprocess.Popen([sumoBinary, "-n", self.PATH+"/"+self.CASENAME+".net.xml",'-r',self.PATH+"/"+self.CASENAME+".rou.xml",'-a',self.PATH+"/sensors.xml", "--remote-port", str(self.PORT)], stdout=DEVNULL#stdout=sys.stdout,
     ,stderr=sys.stderr)
 
     print "Opening a port at", self.PORT
     traci.init(self.PORT)
     print "Connection made with sumo"
     self.laneAreaList = traci.areal.getIDList()
     self.stoppedVehicleID = None
开发者ID:baumfalk,项目名称:SumoSensors,代码行数:17,代码来源:test.py


示例15: get_options

    def get_options(self):
        '''Get command line options'''

        optParser = OptionParser()
        optParser.add_option('--nogui', action='store_true', default=False, help='run the command line version of sumo')
        optParser.add_option('--nogen', action='store_true', default=False, help='run without road network generation')
        optParser.add_option('-p', '--prefix', dest='prefix', default='random', help='files names prefix')
        optParser.add_option('-s', '--size', dest='size', default='10', help='road network size')
        optParser.add_option('-a', '--alpha', dest='alpha', default='0.05', help='alpha parameter')
        optParser.add_option('-r', '--rate', dest='rate', default='2', help='repetition rate')
        optParser.add_option('-v', '--verbose', action='store_true', default=False, help='run with detailed information')
        optParser.add_option('-d', '--max-distance', dest='distance', default='500', help='maximum length of edge')
        self.options, args = optParser.parse_args()

        if self.options.nogui:
            self.sumoBinary = checkBinary('sumo')
        else:
            self.sumoBinary = checkBinary('sumo-gui')
开发者ID:OR2013,项目名称:OnlinePathOptimalization,代码行数:18,代码来源:simulation.py


示例16: gen_intersection

 def gen_intersection(self, edgelen, tlstype='static'):
     length = int(edgelen)
     cross_nodes_file = os.path.join(self.net_dir, '%s.nod.xml' % self.netname)
     cross_edges_file = os.path.join(self.net_dir, '%s.edg.xml' % self.netname)
     # Generate nodes
     node_xsd_file = "http://sumo.dlr.de/xsd/nodes_file.xsd"
     nodes_root = etree.Element("nodes",
                                nsmap={'xsi': "http://www.w3.org/2001/XMLSchema-instance"},
                                attrib={'noNamespaceSchemaLocation': node_xsd_file})
     cross_node = etree.SubElement(nodes_root, 'node')
     cross_node.set('id', 'cross')
     cross_node.set('x', '0')
     cross_node.set('y', '0')
     cross_node.set('type', 'traffic_light')
     cross_node.set('tlType', tlstype)
     n_node = etree.SubElement(nodes_root, 'node')
     n_node.set('id', 'north')
     n_node.set('x', '0')
     n_node.set('y', str(length))
     n_node.set('type', 'priority')
     s_node = etree.SubElement(nodes_root, 'node')
     s_node.set('id', 'south')
     s_node.set('x', '0')
     s_node.set('y', str(-length))
     s_node.set('type', 'priority')
     e_node = etree.SubElement(nodes_root, 'node')
     e_node.set('id', 'east')
     e_node.set('x', str(length))
     e_node.set('y', '0')
     e_node.set('type', 'priority')
     w_node = etree.SubElement(nodes_root, 'node')
     w_node.set('id', 'west')
     w_node.set('x', str(-length))
     w_node.set('y', '0')
     w_node.set('type', 'priority')
     nodes_tree = etree.ElementTree(nodes_root)
     print(cross_nodes_file)
     nodes_tree.write(cross_nodes_file,
                      pretty_print=True, xml_declaration=True, encoding='utf-8')
     # Create edges
     edges_xsd_file = "http://sumo.dlr.de/xsd/edges_file.xsd"
     edges_root = etree.Element("edges",
                                nsmap={'xsi': "http://www.w3.org/2001/XMLSchema-instance"},
                                attrib={'noNamespaceSchemaLocation': edges_xsd_file})
     create_edges(edges_root, 'north', 'cross')
     create_edges(edges_root, 'south', 'cross')
     create_edges(edges_root, 'east', 'cross')
     create_edges(edges_root, 'west', 'cross')
     edges_tree = etree.ElementTree(edges_root)
     edges_tree.write(cross_edges_file,
                      pretty_print=True, xml_declaration=True, encoding='utf-8')
     netconvert = checkBinary('netconvert')
     netconvertor = subprocess.Popen([netconvert,
                                      '--node-files', cross_nodes_file,
                                      '--edge-files', cross_edges_file,
                                      '--output-file', self.netfile],
                                     stdout=sys.stdout, stderr=sys.stderr)
开发者ID:allenwoods,项目名称:parasys,代码行数:57,代码来源:create_cfg.py


示例17: main

def main():
    options = parseArgs()
    netconvert = sumolib.checkBinary("netconvert")
    nodes = []
    edges = []
    conns = []
    tlls = []
    tmpDir = tempfile.mkdtemp()
    for d in options.desc:
        createPlain(
            netconvert, options.net, os.path.join(tmpDir, d[0]), d[1], d[2])
        out = open(os.path.join(tmpDir, "%s_.nod.xml" % d[0]), 'w')
        for line in open(os.path.join(tmpDir, "%s.nod.xml" % d[0])):
            if 'location' in line:
                continue
            line = line.replace('id="', 'id="%s_' % d[0])
            line = line.replace('tl="', 'tl="%s_' % d[0])
            out.write(line)
        out.close()
        nodes.append(out.name)
        out = open(os.path.join(tmpDir, "%s_.edg.xml" % d[0]), 'w')
        for line in open(os.path.join(tmpDir, "%s.edg.xml" % d[0])):
            line = line.replace('id="', 'id="%s_' % d[0])
            line = line.replace('from="', 'from="%s_' % d[0])
            line = line.replace('to="', 'to="%s_' % d[0])
            if options.drop_types:
                typeStart = line.find('type="')
                if typeStart >= 0:
                    typeEnd = line.find('"', typeStart + 6)
                    line = line[0:typeStart] + line[typeEnd + 1:]
            out.write(line)
        out.close()
        edges.append(out.name)
        out = open(os.path.join(tmpDir, "%s_.con.xml" % d[0]), 'w')
        for line in open(os.path.join(tmpDir, "%s.con.xml" % d[0])):
            line = line.replace('from="', 'from="%s_' % d[0])
            line = line.replace('to="', 'to="%s_' % d[0])
            out.write(line)
        out.close()
        conns.append(out.name)
        out = open(os.path.join(tmpDir, "%s_.tll.xml" % d[0]), 'w')
        for line in open(os.path.join(tmpDir, "%s.tll.xml" % d[0])):
            line = line.replace('id="', 'id="%s_' % d[0])
            line = line.replace('from="', 'from="%s_' % d[0])
            line = line.replace('to="', 'to="%s_' % d[0])
            line = line.replace('tl="', 'tl="%s_' % d[0])
            out.write(line)
        out.close()
        tlls.append(out.name)
    options.node_files = ",".join(nodes)
    options.edge_files = ",".join(edges)
    options.connection_files = ",".join(conns)
    options.tllogic_files = ",".join(tlls)
    if sumolib.call(netconvert, options) != 0:
        print("Something went wrong, check '%s'!" % tmpDir, file=sys.stderr)
    else:
        shutil.rmtree(tmpDir)
开发者ID:behrisch,项目名称:sumo,代码行数:57,代码来源:netduplicate.py


示例18: fileNeedsRebuild

def fileNeedsRebuild(filePath, app):
    print("fileNeedsRebuild> %s" % filePath)
    if REBUILD:
        return True
    if not os.path.exists(filePath):
        return True
    genAppPath = sumolib.checkBinary(app)
    tf = os.path.getmtime(filePath)
    ta = os.path.getmtime(genAppPath)
    return tf < ta
开发者ID:aarongolliver,项目名称:sumo,代码行数:10,代码来源:__init__.py


示例19: main

def main(arguments):
    global args
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('n', help="size of grid (along one side)",type=int, default=5)
    parser.add_argument('seed', help="seed value",type=int, default=42)
    parser.add_argument('max_step', help="max steps per simulation",type=int, default=-1)
    parser.add_argument('use_gui', help="use gui or not", type=bool, default=False)
    args = parser.parse_args(arguments)
    n = args.n
    seed_val = args.seed
    max_step = args.max_step
    if args.use_gui:
        sumoBinary = checkBinary('sumo')
    else:
        sumoBinary = checkBinary('sumo-gui')

    setup_and_run_sumo(n, seed_val)
开发者ID:W4ngatang,项目名称:TrafficSwarmOptimization,代码行数:19,代码来源:runner.py


示例20: _generate_rerouters

    def _generate_rerouters(self):
        """ Compute the rerouters for each parking lot for SUMO. """

        traci.start([sumolib.checkBinary('sumo'), '--no-step-log', '-n', self._sumo_net])

        distances = collections.defaultdict(dict)
        for parking_a in self._parking_areas.values():
            for parking_b in self._parking_areas.values():
                if parking_a['id'] == parking_b['id']:
                    continue
                if parking_a['edge'] == parking_b['edge']:
                    continue

                route = None
                try:
                    route = traci.simulation.findRoute(
                        parking_a['edge'], parking_b['edge'])
                except traci.exceptions.TraCIException:
                    route = None

                cost = None
                if route and route.edges:
                    cost = route.travelTime
                else:
                    cost = None

                distances[parking_a['id']][parking_b['id']] = cost

        traci.close()

        # select closest parking areas
        for pid, dists in distances.items():
            list_of_dist = [tuple(reversed(x)) for x in dists.items() if x[1] is not None]
            list_of_dist = sorted(list_of_dist)
            rerouters = [(pid, 0.0)]
            for distance, parking in list_of_dist:
                if len(rerouters) > self._num_alternatives:
                    break
                if distance > self._dist_alternatives:
                    break
                rerouters.append((parking, distance))

            if not list_of_dist:
                logging.fatal('Parking %s has 0 neighbours!', pid)

            self._sumo_rerouters[pid] = {
                'rid': pid,
                'edge': self._parking_areas[pid]['edge'],
                'rerouters': rerouters,
            }

        logging.debug('Computed %d rerouters.', len(self._sumo_rerouters.keys()))
开发者ID:behrisch,项目名称:sumo,代码行数:52,代码来源:generateParkingAreaRerouters.py



注:本文中的sumolib.checkBinary函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python net.getEdges函数代码示例发布时间:2022-05-27
下一篇:
Python utils.smart_int函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap