Пример #1
0
 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
Пример #2
0
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])
Пример #3
0
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))
Пример #4
0
    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()
Пример #5
0
 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)
Пример #6
0
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)
Пример #7
0
    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)
Пример #8
0
 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)
Пример #9
0
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()
Пример #10
0
    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))
Пример #11
0
    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)
Пример #12
0
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()
Пример #13
0
 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
Пример #14
0
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()
Пример #15
0
    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')
Пример #16
0
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)
Пример #17
0
 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)
Пример #18
0
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)
Пример #19
0
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
Пример #20
0
def generate(netFile, mappedSiteFile, intersectionFile, tripFile):
    # EdgesInDistricts
    # evakuierungsbereich
    options = OptionParser()
    options.maxspeed = 1000.
    options.minspeed = 0.
    options.complete = False
    options.internal = False
    options.vclass = None
    options.assign_from = True
    options.verbose = False
    options.weighted = False
    options.shapeinfo = False
    options.output = "edgesInIntersections.taz.xml"
    net = sumolib.net.readNet(netFile)
    reader = EID.DistrictEdgeComputer(net)
    polyReader = sumolib.shapes.polygon.PolygonReader(True)
    parse(intersectionFile, polyReader)
    reader.computeWithin(polyReader.getPolygons(), options)
    reader.writeResults(options)

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

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

    # OD2TRIPS
    od2t = sumolib.checkBinary('od2trips')
    od2tOptions = [od2t, '--no-step-log', '-d', odm.name, '-n',
                   'edgesInIntersections.taz.xml,evacuationsiteEdges.taz.xml', '-o', tripFile]
    subprocess.call(od2tOptions)
Пример #21
0
    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()))
Пример #22
0
def main():
    options = parse_args()
    copy_tags = options.copy.split(",") if options.copy else []
    if options.direct:
        type = ".xml"
        xmldiff(options.source, options.dest, options.outprefix + type, type, copy_tags)
    else:
        if not options.use_prefix:
            netconvert = sumolib.checkBinary("netconvert", options.path)
            options.source = create_plain(options.source, netconvert)
            options.dest = create_plain(options.dest, netconvert)
        for type in PLAIN_TYPES:
            xmldiff(options.source + type, options.dest + type, options.outprefix + type, type, copy_tags)
Пример #23
0
def runSimulation(options):
    print("running SUMO to determine actual departure times...")
    subprocess.call([sumolib.checkBinary("sumo"),
                     "-n", options.netfile,
                     "-r", options.trips,
                     "--begin", str(options.begin),
                     "--no-step-log",
                     "--ignore-route-errors",
                     "--error-log", options.trips + ".errorlog",
                     "-a", options.ptstops,
                     "--device.rerouting.adaptation-interval", "0",  # ignore tls and traffic effects
                     "--vehroute-output", options.routes,
                     "--stop-output", options.stopinfos, ])
    print("done.")
Пример #24
0
def gof(p):
    para = [('vMax', p[0]), ('aMax', p[1]), ('bMax', p[2]),
            ('lCar', p[3]), ('sigA', p[4]), ('tTau', p[5])]
    print('# simulation with:', *["%s:%.3f" % i for i in para])
    fType = open('data/input_types.add.xml', 'w')
    fType.write(('<routes>\n    <vType accel="%(aMax)s" decel="%(bMax)s" id="pass"' +
                 ' length="%(lCar)s" minGap="2.5" maxSpeed="%(vMax)s"' +
                 ' sigma="%(sigA)s" tau="%(tTau)s" />\n</routes>') % dict(para))
    fType.close()
    result = validate.validate(checkBinary('sumo'))
    print('#### yields rmse: %.4f' % result)
    print("%s %s" % (" ".join(["%.3f" % pe for pe in p]), result), file=fpLog)
    fpLog.flush()
    return result
Пример #25
0
    def initialize(self) :
        if platform.system() == 'Windows' or platform.system().startswith("CYGWIN"):
            sumoBinary = checkBinary('sumo.exe')
        else:
            sumoBinary = checkBinary('sumo')
        sumoCommandLine = [sumoBinary, "-c", self.ConfigFile, "-l", "sumo.log"]
        self.SumoProcess = subprocess.Popen(sumoCommandLine, stdout=sys.stdout, stderr=sys.stderr)
        traci.init(self.Port)

        self.SimulationBoundary = traci.simulation.getNetBoundary()
        self.XBase = self.SimulationBoundary[0][0]
        self.XSize = self.SimulationBoundary[1][0] - self.XBase
        self.YBase = self.SimulationBoundary[0][1]
        self.YSize = self.SimulationBoundary[1][1] - self.YBase
        self.__Logger.warn("starting sumo connector")

        # initialize the edge list, drop all the internal edges
        self.EdgeList = []
        for edge in traci.edge.getIDList() :
            # this is just to ensure that everything is initialized first time
            traci.edge.adaptTraveltime(edge, traci.edge.getTraveltime(edge))

            # only keep the "real" edges for computation for now
            if not edge.startswith(':') :
                self.EdgeList.append(edge)
        self.CurrentEdgeList = list(self.EdgeList)

        # initialize the traffic light state
        tllist = traci.trafficlights.getIDList()
        for tl in tllist :
            self.TrafficLights[tl] = traci.trafficlights.getRedYellowGreenState(tl)
            traci.trafficlights.subscribe(tl,[tc.TL_RED_YELLOW_GREEN_STATE])

        # initialize the induction loops
        illist = traci.inductionloop.getIDList()
        for il in illist :
            traci.inductionloop.subscribe(il, [tc.LAST_STEP_VEHICLE_NUMBER])
Пример #26
0
    def __init__(self, configFile, gui = False, outFile=None):
        """ starts the simulation
            inputs:
            configFile = string, name of the configuration you're using
            gui = boolean (optional), if True, the SUMO gui will pop up
            outFile = string (optional), file for SUMO to save data
        """

        PORT = 8800     
        
        # from sumo demo code (vehicleControl.py)
        try:
            from sumolib import checkBinary
        except ImportError:
            def checkBinary(name):
                return name 
        
        # write terminal command
        completeCommand = [checkBinary("sumo")]
        if gui:
            completeCommand = [checkBinary("sumo-gui")]
        #sumoConfig = "%s.sumocfg" % (configFile)
        sumoConfig = configFile + "/" + configFile + ".sumocfg"
        completeCommand += ["-c", sumoConfig]
        completeCommand += ["--remote-port",str(PORT)]
        if outFile is not None:
            completeCommand += ["--fcd-output","./Results/%s.xml" % outFile ]
        
        self._C = completeCommand        
        
        ## start SUMO
        self.sumoProcess = subprocess.Popen(completeCommand,
                                            stdout=subprocess.PIPE,#sys.stdout,#
                                            stderr=subprocess.STDOUT)
        traci.init(PORT, 10)
        
        self.outFile = outFile
Пример #27
0
def runSim():
    fp = open(configFile, 'w')
    print >> fp, """<configuration>
    <input>
        <net-file value="%s"/>
        <route-files value="%s"/>
    </input>
    <report>
        <no-duration-log value="true"/>
        <no-step-log value="true"/>
        <max-depart-delay value="0"/>
        <tripinfo-output value="%s"/>
    </report>
</configuration>""" % (netFile, routeFile, dumpFile)
    fp.close()
    os.system('%s -c %s' % (sumolib.checkBinary("sumo"), configFile))
Пример #28
0
def init_traci():

    sumoBinary = sumolib.checkBinary('sumo')
#    sumoBinary = sumolib.checkBinary('sumo-gui')

    sumo_call = [sumoBinary, "-c", "data/hello.sumocfg",
                 "--remote-port", str(PORT_TRACI),
                 "--netstate-dump", "rawdump.xml",
                 "--no-step-log",
                 "-v",
                 ]

    sumoProcess = subprocess.Popen(
        sumo_call, stdout=sys.stdout, stderr=sys.stderr)

    traci.init(PORT_TRACI)
def gof(p):
    para = {'vMax': p[0], 'aMax': p[1], 'bMax': p[2], 'lCar': p[3], 'sigA': p[4], 'tTau': p[5]}
    print '# simulation with:',
    for k, v in para.items():
        print "%s:%.3f" % (k,v),
    print
    fType = open('data/input_types.add.xml', 'w')
    fType.write(('<routes>\n    <vType accel="%(aMax)s" decel="%(bMax)s" id="pass"' +
                ' length="%(lCar)s" minGap="2.5" maxSpeed="%(vMax)s"' + 
                ' sigma="%(sigA)s" tau="%(tTau)s" />\n</routes>') % para)
    fType.close()
    result = validate.validate(checkBinary('sumo'))
    print '#### yields rmse: %.4f' % result
    print >> fpLog, "%s %s" % (" ".join(["%.3f" % pe for pe in p]), result)
    fpLog.flush()
    return result
Пример #30
0
def generateNetwork(nodFile, edgFile, typFile, conFile, netFile):
    '''
    Run the netconvert application to generate the network file.
    :param nodFile: The node definition file
    :param edgFile: The edge definition file
    :param typFile: The edge type definition file
    :param conFile: The connections definition file
    :param netFile: The network file
    :return:
    '''
    logger.info("................ Generate the network (netconvert) ...")
    logger.info("\tNode file: %s" % nodFile)
    logger.info("\tEdge file: %s" % edgFile)
    logger.info("\tType file: %s" % typFile)
    logger.info("\tConn file: %s" % conFile)
    logger.info("\tNet file : %s" % netFile)

    # Call to netconvert
    netconvertBin = checkBinary('netconvert')
    options = ["--node-files", nodFile,
               "--edge-files", edgFile,
               "--output-file", netFile,
               "--no-turnarounds",
               "--verbose"]

    # Optional network type file
    if typFile:
        options += ["--type-files", typFile]

    #Optional connection file
    if conFile:
        options += ["--connection-files", conFile]

    status = subprocess.call([netconvertBin] + options,
                             stdout = sys.stdout,
                             stderr = sys.stderr)
    if status != 0:
        logger.critical("Fail: netconvert terminated with error status [%d]" % status, exc_info=True)
        sys.exit(status)
    else:
        logger.info("Success: netconvert finished with status [%d]" % status)

    sys.stdout.flush()
Пример #31
0
    def openSUMO(self):
        self.report("Calling SUMO")

        sumogui = sumolib.checkBinary("sumo-gui")

        subprocess.Popen([sumogui, "-c", self.files["config"]], cwd=self.tmp)
Пример #32
0
SLOTS_PER_ROW = 10
SLOT_WIDTH = 5
SLOT_LENGTH = 9
SLOT_FOOT_LENGTH = 5
CAR_CAPACITY = 3
CYBER_CAPACITY = 20
BUS_CAPACITY = 30
TOTAL_CAPACITY = 60
CYBER_SPEED = 5
CYBER_LENGTH = 9
WAIT_PER_PERSON = 5
OCCUPATION_PROBABILITY = 0.5
BREAK_DELAY = 1200

PORT = 8813
SUMO_HOME = os.path.realpath(
    os.environ.get("SUMO_HOME",
                   os.path.join(os.path.dirname(__file__), "..", "..", "..")))
sys.path.append(os.path.join(SUMO_HOME, "tools"))
try:
    from sumolib import checkBinary
except ImportError:

    def checkBinary(name):
        return name


NETCONVERT = checkBinary("netconvert")
SUMO = checkBinary("sumo")
SUMOGUI = checkBinary("sumo-gui")
Пример #33
0
def main(args=None):
    argParser = initOptions()

    options = argParser.parse_args(args=args)

    if not options.net:
        argParser.error("Option --net-file is mandatory")
    if (not options.trips and not options.routes
            and not options.flows) or (options.trips and options.routes):
        argParser.error(
            "Either --trips, --flows, or --routes have to be given!")
    duaBinary = sumolib.checkBinary("duarouter", options.path)
    sumoBinary = sumolib.checkBinary("sumo", options.path)
    if options.addweights and options.weightmemory:
        argParser.error(
            "Options --addweights and --weight-memory are mutually exclusive.")

    # make sure BOTH binaries are callable before we start
    try:
        subprocess.call(duaBinary, stdout=subprocess.PIPE)
    except OSError:
        sys.exit((
            "Error: Could not locate duarouter (%s).\nMake sure its on the search path or set environment "
            + "variable DUAROUTER_BINARY\n") % duaBinary)
    try:
        subprocess.call(sumoBinary, stdout=subprocess.PIPE)
    except OSError:
        sys.exit((
            "Error: Could not locate sumo (%s).\nMake sure its on the search path or set environment "
            + "variable SUMO_BINARY\n") % sumoBinary)

    sumo_args = assign_remaining_args(sumoBinary, 'sumo',
                                      options.remaining_args)
    dua_args = assign_remaining_args(duaBinary, 'duarouter',
                                     options.remaining_args)

    sys.stdout = sumolib.TeeFile(sys.stdout, open("stdout.log", "w+"))
    log = open("dua.log", "w+")
    if options.zip:
        if options.clean_alt:
            sys.exit(
                "Error: Please use either --zip or --clean-alt but not both.")
        try:
            subprocess.call("7z", stdout=open(os.devnull, 'wb'))
        except Exception:
            sys.exit(
                "Error: Could not locate 7z, please make sure its on the search path."
            )
        zipProcesses = {}
        zipLog = open("7zip.log", "w+")
    starttime = datetime.now()
    if options.trips:
        input_demands = options.trips.split(",")
        initial_type = "trip"
    elif options.flows:
        input_demands = options.flows.split(",")
        initial_type = "flow"
    else:
        input_demands = options.routes.split(",")
        initial_type = "route"
    if options.externalgawron:
        # avoid dependency on numpy for normal duaIterate
        from routeChoices import getRouteChoices, calFirstRouteProbs
        print('use externalgawron')
        edgesMap = {}
    if options.weightmemory:
        costmemory = CostMemory('traveltime',
                                pessimism=options.pessimism,
                                network_file=options.net)
    routesSuffix = ".xml"
    if options.binary:
        routesSuffix = ".sbx"

    if options.weightmemory and options.firstStep != 0:
        # load previous dump files when continuing a run
        print(">> Reassembling cost-memory from previous iteration steps")
        for step in range(0, options.firstStep):
            dumpfile = get_dumpfilename(options, step, "dump")
            print(">>> Loading %s" % dumpfile)
            costmemory.load_costs(dumpfile, step, get_scale(options, step))

    avgTT = sumolib.miscutils.Statistics()
    for step in range(options.firstStep, options.lastStep):
        btimeA = datetime.now()
        print("> Executing step %s" % step)

        router_demands = input_demands
        simulation_demands = input_demands
        # demand files have regular names based on the basename and the step
        if not (options.skipFirstRouting and step == 0):
            simulation_demands = [
                get_basename(f) + "_%03i.rou%s" % (step, routesSuffix)
                for f in input_demands
            ]
        if not ((options.skipFirstRouting and step == 1) or step == 0):
            router_demands = [
                get_basename(f) + "_%03i.rou.alt%s" % (step - 1, routesSuffix)
                for f in input_demands
            ]

        if not (options.skipFirstRouting and step == options.firstStep):
            # call duarouter
            for router_input, output in zip(router_demands,
                                            simulation_demands):
                print(">> Running router on %s" % router_input)
                btime = datetime.now()
                print(">>> Begin time: %s" % btime)
                cfgname = writeRouteConf(duaBinary, step, options, dua_args,
                                         router_input, output,
                                         options.routefile, initial_type)
                log.flush()
                sys.stdout.flush()
                call([duaBinary, "-c", cfgname], log)
                if options.clean_alt and router_input not in input_demands:
                    os.remove(router_input)
                etime = datetime.now()
                print(">>> End time: %s" % etime)
                print(">>> Duration: %s" % (etime - btime))
                print("<<")
                # use the external gawron
                if options.externalgawron:
                    basename = get_basename(router_input)
                    if ((step > 0 and not options.skipFirstRouting)
                            or step > 1):
                        basename = basename[:-4]
                    print('basename', basename)
                    ecomeasure = None
                    if options.ecomeasure:
                        ecomeasure = options.ecomeasure
                    if step == options.firstStep + 1 and options.skipFirstRouting:
                        if options.caloldprob:
                            calFirstRouteProbs(
                                "dump_000_%s.xml" % (options.aggregation),
                                basename + "_001.rou.alt.xml",
                                options.addweights, ecomeasure)
                        else:
                            shutil.copy(basename + "_001.rou.alt.xml",
                                        basename + "_001.rou.galt.xml")
                            shutil.copy(basename + "_001.rou.xml",
                                        basename + "_001.grou.xml")
                    if step == options.firstStep and not options.skipFirstRouting:
                        shutil.copy(basename + "_000.rou.alt.xml",
                                    basename + "_000.rou.galt.xml")
                        shutil.copy(basename + "_000.rou.xml",
                                    basename + "_000.grou.xml")
                    else:
                        print('step:', step)
                        print('get externalgawron')
                        dumpfile = "dump_%03i_%s.xml" % (step - 1,
                                                         options.aggregation)
                        if (not options.skipFirstRouting) or (
                                options.skipFirstRouting and step > 1):
                            output, edgesMap = getRouteChoices(
                                edgesMap, dumpfile,
                                basename + "_%03i.rou.alt.xml" % step,
                                options.net, options.addweights, options.gA,
                                options.gBeta, step, ecomeasure)

        # simulation
        print(">> Running simulation")
        btime = datetime.now()
        print(">>> Begin time: %s" % btime)
        writeSUMOConf(sumoBinary, step, options, sumo_args,
                      ",".join(simulation_demands))  # todo: change 'grou.xml'
        log.flush()
        sys.stdout.flush()
        call([sumoBinary, "-c", "iteration_%03i.sumocfg" % step], log)
        if options.tripinfoFilter:
            filterTripinfo(step, set(options.tripinfoFilter.split(",")))
        etime = datetime.now()
        print(">>> End time: %s" % etime)
        print(">>> Duration: %s" % (etime - btime))
        print("<<")

        if options.weightmemory:
            print(">> Smoothing edge weights")
            costmemory.load_costs(get_dumpfilename(options, step, "dump"),
                                  step, get_scale(options, step))
            costmemory.write_costs(get_weightfilename(options, step, "dump"))
            print(">>> Updated %s edges" % costmemory.loaded())
            print(">>> Decayed %s unseen edges" % costmemory.decayed())
            print(">>> Error avg:%.12g mean:%.12g" %
                  (costmemory.avg_error(), costmemory.mean_error()))
            print(">>> Absolute Error avg:%.12g mean:%.12g" %
                  (costmemory.avg_abs_error(), costmemory.mean_abs_error()))

        if options.zip and step - options.firstStep > 1:
            # this is a little hackish since we zip and remove all files by glob, which may have undesired side effects
            # also note that the 7z file does not have an "_" before the
            # iteration number in order to be not picked up by the remove
            for s in list(zipProcesses.keys()):
                if zipProcesses[s].poll() is not None:
                    for f in glob.glob("*_%03i*" % s):
                        try:
                            os.remove(f)
                        except Exception:
                            print("Could not remove %s" % f, file=zipLog)
                    del zipProcesses[s]
            zipStep = step - 2
            zipProcesses[zipStep] = subprocess.Popen(
                ["7z", "a", "iteration%03i.7z" % zipStep] +
                glob.glob("*_%03i*" % zipStep),
                stdout=zipLog,
                stderr=zipLog)

        converged = False
        if options.convDev:
            sum = 0.
            count = 0
            for t in sumolib.output.parse_fast("tripinfo_%03i.xml" % step,
                                               'tripinfo', ['duration']):
                sum += float(t.duration)
                count += 1
            avgTT.add(sum / count)
            relStdDev = avgTT.relStdDev(options.convIt)
            print(
                "< relative travel time deviation in the last %s steps: %.05f"
                % (min(avgTT.count(), options.convIt), relStdDev))
            if avgTT.count() >= options.convIt and relStdDev < options.convDev:
                converged = True

        print("< Step %s ended (duration: %s)" %
              (step, datetime.now() - btimeA))
        print("------------------\n")

        log.flush()
        sys.stdout.flush()
        if converged:
            break
    if options.zip:
        for s in zipProcesses.keys():
            zipProcesses[s].wait()
            for f in glob.glob("*_%03i*" % s):
                try:
                    os.remove(f)
                except Exception:
                    print("Could not remove %s" % f, file=zipLog)
        zipLog.close()
    print("dua-iterate ended (duration: %s)" % (datetime.now() - starttime))

    log.close()
Пример #34
0
SUMO is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
"""

import sys
import os
import subprocess

sys.path.append(
    os.path.join(os.path.dirname(sys.argv[0]), '..', '..', '..', "tools"))
from sumolib import checkBinary

EDC = checkBinary(
    "emissionsDrivingCycle",
    os.path.join(os.path.dirname(sys.argv[0]), '..', '..', '..', "bin"))
if len(sys.argv) > 2:
    PHEMLIGHTp = os.path.join(os.environ["SUMO_HOME"], "data", "emissions",
                              sys.argv[2])
else:
    PHEMLIGHTp = os.path.join(os.environ["SUMO_HOME"], "data", "emissions",
                              "PHEMlight")
if not os.path.exists(PHEMLIGHTp):
    PHEMLIGHTp = os.path.join(os.path.dirname(sys.argv[0]), '..', '..', '..',
                              "data", "emissions", "PHEMlight")

fd = open("classes.txt")
emissionClasses = fd.readlines()
fd.close()
Пример #35
0
        self.root.destroy()


stereoModes = (
    'ANAGLYPHIC', 'QUAD_BUFFER', 'VERTICAL_SPLIT', 'HORIZONTAL_SPLIT')
optParser = OptionParser()
optParser.add_option("-s", "--stereo", metavar="OSG_STEREO_MODE",
                     help="Defines the stereo mode to use for 3D output; unique prefix of %s" % (
                           ", ".join(stereoModes)))
options, args = optParser.parse_args()

base = os.path.dirname(sys.argv[0])
high = loadHighscore()


guisimPath = sumolib.checkBinary("sumo-gui")
haveOSG = "OSG" in subprocess.check_output(sumolib.checkBinary("sumo"), universal_newlines=True)

if options.stereo:
    for m in stereoModes:
        if m.lower().startswith(options.stereo.lower()):
            os.environ["OSG_STEREO_MODE"] = m
            os.environ["OSG_STEREO"] = "ON"
            break

lang = _LANGUAGE_EN
if "OSG_FILE_PATH" in os.environ:
    os.environ["OSG_FILE_PATH"] += os.pathsep + \
        os.path.join(os.environ.get("SUMO_HOME", ""), "data", "3D")
else:
    os.environ["OSG_FILE_PATH"] = os.path.join(
Пример #36
0
if len(sys.argv) > 1:
    buildEvaSite(sys.argv[1], siteFile)
else:
    buildEvaSite("inputLocations.poi.xml", siteFile)
print("osm Get")
osmGet.get(["-x", siteFile])
print("osm Build")
osmOptions = [
    '-f', 'osm_bbox.osm.xml', '-p', prefix, '--vehicle-classes', 'road', '-m',
    os.path.join(SUMO_HOME, 'data', 'typemap', 'osmPolyconvert.typ.xml')
]
osmBuild.build(osmOptions)
print("polyconvert")
sys.stdout.flush()
subprocess.call([
    sumolib.checkBinary('polyconvert'), '-n',
    '%s.net.xml' % prefix, '--xml-files', siteFile, '-o', mappedSiteFile
])
print("merging")
mergePopulationData("population.csv", 'regions.poly.xml', mergedPopulationFile)
print("extracting population data")
extract(mergedPopulationFile, mappedSiteFile, intersectionFile)
print("generating traffic")
generateTraffic.generate('%s.net.xml' % prefix, mappedSiteFile,
                         intersectionFile, '%s.rou.xml' % prefix)
print("calling sumo")
sys.stdout.flush()
sumo = sumolib.checkBinary('sumo')
sumoOptions = [
    sumo, '-n',
    "%s.net.xml" % prefix, '-a',
Пример #37
0
This file is part of SUMO.
SUMO is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
"""

import os
import subprocess
import sys
sys.path.append(
    os.path.join(os.path.dirname(sys.argv[0]), '..', '..', '..', '..',
                 "tools"))
import sumolib

netconvertBinary = sumolib.checkBinary('netconvert')
duarouterBinary = sumolib.checkBinary('duarouter')
sumoBinary = sumolib.checkBinary('sumo')

print ">>> Building the xml network"
sys.stdout.flush()
subprocess.call([netconvertBinary, "-c", "netconvert.netccfg"],
                stdout=sys.stdout,
                stderr=sys.stderr)
print ">>> Building the binary network"
sys.stdout.flush()
subprocess.call(
    [netconvertBinary, "-c", "netconvert.netccfg", "-o", "circular.net.sbx"],
    stdout=sys.stdout,
    stderr=sys.stderr)
sys.stdout.flush()
Пример #38
0
def run():

    sumoBinary = checkBinary('sumo')
    # else:
    #     sumoBinary = checkBinary('sumo-gui')

    all_v_id = generate_routefile()

    # this is the normal way of using traci. sumo is started as a
    # subprocess and then the python script connects and runs
    traci.start(
        [sumoBinary, "-c", "data/cross.sumocfg", '--fcd-output', 'fcd.data'])

    # traci.vehicle.subscribe(vehID, (tc.VAR_ROAD_ID, tc.VAR_LANEPOSITION))

    step = 0
    # we start with phase 2 where EW has green
    traci.trafficlight.setPhase("0", 2)

    v_still_alive = {}
    for vId in all_v_id:
        v_still_alive[vId] = {'exist': True, 'finished': False}

    v_pos = {}
    max_dist_from_inter = 20
    inter_loc = (510.00, 510.00)

    out = open('ros.out', 'w')

    while traci.simulation.getMinExpectedNumber() > 0:
        traci.simulationStep()
        if traci.trafficlight.getPhase("0") == 2:
            # we are not already switching
            if traci.inductionloop.getLastStepVehicleNumber("0") > 0:
                # there is a vehicle from the north, switch
                traci.trafficlight.setPhase("0", 3)
            else:
                # otherwise try to keep green for EW
                traci.trafficlight.setPhase("0", 2)
        step += 1

        # if not rospy.is_shutdown():
        for vId in traci.vehicle.getIDList():
            if v_still_alive[vId]['exist']:
                try:
                    v = traci.vehicle.getPosition(vId)
                    dist = np.sqrt((v[0] - inter_loc[0])**2 +
                                   (v[1] - inter_loc[1])**2)
                    if dist < max_dist_from_inter:
                        v_pos[vId] = v
                    elif vId in v_pos:
                        del v_pos[vId]
                    v_still_alive[vId]['finished'] = True
                except Exception as e:
                    if ('Vehicle' not in str(e) and 'exit' not in str(e)):
                        print(e)
                    if (v_still_alive[vId]['finished']):
                        v_still_alive[vId]['exist'] = False
                    pass

        if run_with_start_ros:
            rospy.loginfo(v_pos)
            pub.publish(json.dumps(v_pos))
        else:
            print(v_pos, file=out)

    out.close()
    traci.close()
    sys.stdout.flush()
Пример #39
0
def main():
    argParser = initOptions()

    options = argParser.parse_args()
    if not options.net or not options.routes or not options.detvals:
        argParser.error(
            "--net-file, --routes and --detector-values have to be given!")

    if options.mesosim:
        sumoBinary = sumolib.checkBinary("meso", options.path)
    else:
        sumoBinary = sumolib.checkBinary("sumo", options.path)
    calibrator = [
        "java", "-cp", options.classpath, "-Xmx1G",
        "cadyts.interfaces.sumo.SumoController"
    ]
    log = open("cadySumo-log.txt", "w+")

    # calibration init
    starttime = datetime.now()
    evalprefix = None
    if options.evalprefix:
        evalprefix = options.evalprefix

    # begin the calibration
    if options.fmaprefix:
        call(
            calibrator + [
                "INIT", "-varscale", options.varscale, "-freezeit",
                options.freezeit, "-measfile", options.detvals, "-binsize",
                options.aggregation, "-PREPITS", options.PREPITS,
                "-bruteforce", options.bruteforce, "-demandscale",
                options.demandscale, "-mincountstddev", options.mincountstddev,
                "-overridett", options.overridett, "-clonepostfix",
                options.clonepostfix, "-fmaprefix", options.fmaprefix,
                "-cntfirstlink", options.cntfirstlink, "-cntlastlink",
                options.cntlastlink
            ], log)
    else:
        call(
            calibrator + [
                "INIT", "-varscale", options.varscale, "-freezeit",
                options.freezeit, "-measfile", options.detvals, "-binsize",
                options.aggregation, "-PREPITS", options.PREPITS,
                "-bruteforce", options.bruteforce, "-demandscale",
                options.demandscale, "-mincountstddev", options.mincountstddev,
                "-overridett", options.overridett, "-clonepostfix",
                options.clonepostfix, "-cntfirstlink", options.cntfirstlink,
                "-cntlastlink", options.cntlastlink
            ], log)

    for step in range(options.calibStep):
        print('calibration step:', step)
        files = []

        # calibration choice
        firstRoute = options.routes.split(",")[0]
        routname = os.path.basename(firstRoute)
        if '_' in routname:
            output = "%s_%03i.cal.xml" % (routname[:routname.rfind('_')], step)
        else:
            output = "%s_%03i.cal.xml" % (routname[:routname.find('.')], step)

        call(
            calibrator + [
                "CHOICE", "-choicesetfile", options.routes, "-choicefile",
                "%s" % output
            ], log)
        files.append(output)

        # simulation
        print(">> Running simulation")
        btime = datetime.now()
        print(">>> Begin time: %s" % btime)
        writeSUMOConf(sumoBinary, step, options, [], ",".join(files))
        retCode = call([sumoBinary, "-c",
                        "iteration_%03i.sumocfg" % step], log)
        etime = datetime.now()
        print(">>> End time: %s" % etime)
        print(">>> Duration: %s" % (etime - btime))
        print("<<")

        # calibration update
        if evalprefix:
            call(
                calibrator + [
                    "UPDATE", "-netfile",
                    "dump_%03i_%s.xml" %
                    (step, options.aggregation), "-flowfile",
                    "%s_%03i.txt" % (evalprefix, step)
                ], log)
        else:
            call(
                calibrator + [
                    "UPDATE", "-netfile",
                    "dump_%03i_%s.xml" % (step, options.aggregation)
                ], log)
        print("< Step %s ended (duration: %s)" %
              (step, datetime.now() - btime))
        print("------------------\n")
        log.flush()

    print("calibration ended (duration: %s)" % (datetime.now() - starttime))
    log.close()
        det_vehs2 = traci.inductionloop.getLastStepVehicleIDs("det_2")
        for veh in det_vehs:
            print(veh)
            #traci.vehicle.changeLane(veh, 2, 25)

        # if step == 100:
        #     traci.vehicle.changeTarget("1", "e9")
        #     traci.vehicle.changeTarget("3", "e9")

        step += 1

    traci.close()
    sys.stdout.flush()


# main entry point
if __name__ == "__main__":
    options = get_options()

    # check binary
    if options.nogui:
        sumoBinary = checkBinary('sumo')
    else:
        sumoBinary = checkBinary('sumo-gui')

    # traci starts sumo as a subprocess and then this script connects and runs
    traci.start([
        sumoBinary, "-c", "sumo.sumocfg", "--tripinfo-output", "tripinfo.xml"
    ])
    run()
Пример #41
0
def main():
    options = get_options()
    if options.verbose:
        print("parsing network from", options.network)
    net = readNet(options.network, withInternal=True)
    read = 0
    routeInfos = {}  # id-> RouteInfo
    skipped = set()
    for routeFile in options.routeFiles:
        if options.verbose:
            print("parsing routes from", routeFile)
        idx = 0
        if options.standalone:
            for idx, route in enumerate(parse(routeFile, 'route')):
                if options.verbose and idx > 0 and idx % 100000 == 0:
                    print(idx, "routes read")
                addOrSkip(routeInfos, skipped, route.id, route,
                          options.min_edges)
        else:
            if options.heterogeneous:
                for idx, vehicle in enumerate(parse(routeFile, 'vehicle')):
                    if options.verbose and idx > 0 and idx % 100000 == 0:
                        print(idx, "vehicles read")
                    addOrSkip(routeInfos, skipped, vehicle.id,
                              vehicle.route[0], options.min_edges)
            else:
                prev = (None, None)
                for vehicle, route in parse_fast_nested(
                        routeFile, 'vehicle', 'id', 'route', 'edges'):
                    if prev[0] != vehicle.id:
                        if options.verbose and idx > 0 and idx % 500000 == 0:
                            print(idx, "vehicles read")
                        if prev[0] is not None:
                            addOrSkip(routeInfos, skipped, prev[0], prev[1],
                                      options.min_edges)
                        prev = (vehicle.id, route)
                        idx += 1
                if prev[0] is not None:
                    addOrSkip(routeInfos, skipped, prev[0], prev[1],
                              options.min_edges)
        read += idx
    if options.verbose:
        print(read, "routes read", len(skipped), "short routes skipped")

    if options.verbose:
        print("calculating air distance and checking loops")
    for idx, ri in enumerate(routeInfos.values()):
        if options.verbose and idx > 0 and idx % 100000 == 0:
            print(idx, "routes checked")
        calcDistAndLoops(ri, net, options)

    prefix = os.path.commonprefix(options.routeFiles)
    duarouterOutput = prefix + '.rerouted.rou.xml'
    duarouterAltOutput = prefix + '.rerouted.rou.alt.xml'
    if os.path.exists(duarouterAltOutput) and options.reuse_routing:
        if options.verbose:
            print("reusing old duarouter file", duarouterAltOutput)
    else:
        if options.standalone:
            duarouterInput = prefix
            # generate suitable input file for duarouter
            duarouterInput += ".vehRoutes.xml"
            with open(duarouterInput, 'w') as outf:
                outf.write('<routes>\n')
                for rID, rInfo in routeInfos.items():
                    outf.write('    <vehicle id="%s" depart="0">\n' % rID)
                    outf.write('        <route edges="%s"/>\n' %
                               ' '.join(rInfo.edges))
                    outf.write('    </vehicle>\n')
                outf.write('</routes>\n')
        else:
            duarouterInput = ",".join(options.routeFiles)

        command = [
            sumolib.checkBinary('duarouter'), '-n', options.network, '-r',
            duarouterInput, '-o', duarouterOutput, '--no-step-log',
            '--routing-threads',
            str(options.threads), '--routing-algorithm', 'astar',
            '--aggregate-warnings', '1'
        ]
        if options.verbose:
            command += ["-v"]
        if options.verbose:
            print("calling duarouter:", " ".join(command))
        subprocess.call(command)

    for vehicle in parse(duarouterAltOutput, 'vehicle'):
        if vehicle.id in skipped:
            continue
        routeAlts = vehicle.routeDistribution[0].route
        if len(routeAlts) == 1:
            routeInfos[vehicle.id].detour = 0
            routeInfos[vehicle.id].detourRatio = 1
            routeInfos[vehicle.id].shortest_path_distance = routeInfos[
                vehicle.id].length
        else:
            oldCosts = float(routeAlts[0].cost)
            newCosts = float(routeAlts[1].cost)
            assert (routeAlts[0].edges.split() == routeInfos[vehicle.id].edges)
            routeInfos[
                vehicle.id].shortest_path_distance = sumolib.route.getLength(
                    net, routeAlts[1].edges.split())
            if oldCosts <= newCosts:
                routeInfos[vehicle.id].detour = 0
                routeInfos[vehicle.id].detourRatio = 1
                if oldCosts < newCosts:
                    sys.stderr.write((
                        "Warning: fastest route for '%s' is slower than original route "
                        + "(old=%s, new=%s). Check vehicle types\n") %
                                     (vehicle.id, oldCosts, newCosts))
            else:
                routeInfos[vehicle.id].detour = oldCosts - newCosts
                routeInfos[vehicle.id].detourRatio = oldCosts / newCosts

    implausible = []
    allRoutesStats = Statistics("overall implausibility")
    implausibleRoutesStats = Statistics("implausibility above threshold")
    for rID in sorted(routeInfos.keys()):
        ri = routeInfos[rID]
        ri.implausibility = (
            options.airdist_ratio_factor * ri.airDistRatio +
            options.detour_factor * ri.detour +
            options.detour_ratio_factor * ri.detourRatio +
            max(0, options.min_dist / ri.shortest_path_distance - 1) +
            max(0, options.min_air_dist / ri.airDist - 1))
        allRoutesStats.add(ri.implausibility, rID)
        if ri.implausibility > options.threshold or ri.edgeLoop or ri.nodeLoop:
            implausible.append((ri.implausibility, rID, ri))
            implausibleRoutesStats.add(ri.implausibility, rID)

    # generate restrictions
    if options.restrictions_output is not None:
        with open(options.restrictions_output, 'w') as outf:
            for score, rID, ri in sorted(implausible):
                edges = ri.edges
                if options.odrestrictions and len(edges) > 2:
                    edges = [edges[0], edges[-1]]
                outf.write("0 %s\n" % " ".join(edges))

    # write xml output
    if options.xmlOutput is not None:
        with open(options.xmlOutput, 'w') as outf:
            sumolib.writeXMLHeader(outf, "$Id$", options=options)  # noqa
            outf.write('<implausibleRoutes>\n')
            for score, rID, ri in sorted(implausible):
                edges = " ".join(ri.edges)
                outf.write('    <route id="%s" edges="%s" score="%s"/>\n' %
                           (rID, edges, score))
            outf.write('</implausibleRoutes>\n')

    if options.ignore_routes is not None:
        numImplausible = len(implausible)
        ignored = set([r.strip() for r in open(options.ignore_routes)])
        implausible = [r for r in implausible if r not in ignored]
        print(
            "Loaded %s routes to ignore. Reducing implausible from %s to %s" %
            (len(ignored), numImplausible, len(implausible)))

    # generate polygons
    polyOutput = prefix + '.implausible.add.xml'
    colorgen = Colorgen(("random", 1, 1))
    with open(polyOutput, 'w') as outf:
        outf.write('<additional>\n')
        for score, rID, ri in sorted(implausible):
            generate_poly(options, net, rID, colorgen(), ri.edges, outf, score)
        outf.write('</additional>\n')

    sys.stdout.write(
        'score\troute\t(airDistRatio, detourRatio, detour, shortestDist, airDist, edgeLoop, nodeLoop)\n'
    )
    for score, rID, ri in sorted(implausible):
        # , ' '.join(ri.edges)))
        sys.stdout.write('%.7f\t%s\t%s\n' %
                         (score, rID, (ri.airDistRatio, ri.detourRatio,
                                       ri.detour, ri.shortest_path_distance,
                                       ri.airDist, ri.edgeLoop, ri.nodeLoop)))

    print(allRoutesStats)
    print(implausibleRoutesStats)
Пример #42
0
from __future__ import absolute_import
from __future__ import print_function

import os
import subprocess
import sys
import time
sys.path.append(
    os.path.join(os.path.dirname(sys.argv[0]), '..', '..', '..', '..',
                 "tools"))
import traci
import sumolib  # noqa

DELTA_T = 1000

netconvertBinary = sumolib.checkBinary('netconvert')
sumoBinary = sumolib.checkBinary('sumo')


def runSingle(addOption):
    step = 0
    timeline = []
    traci.start([sumoBinary, "-c", "sumo.sumocfg"] + addOption)
    while not step > 10000:
        try:
            traci.simulationStep()
            vehs = traci.vehicle.getIDList()
            timeline.append({})
            for v in vehs:
                timeline[-1][v] = traci.vehicle.getSpeed(v)
            step += 1
Пример #43
0
class FickDich(object):
    """Ubuntu Config"""
    # sys.path.append('/usr/share/sumo/tools')

    sumoBinary = checkBinary('sumo-gui')
    sumoCmd = [sumoBinary, "-c", "../data/hello.sumocfg"]
    """interesting functions:
        gui: screenshot()
            trackVehicle()
    """
    """The abstract environment class that is used by all agents. This class has the exact
    same API that OpenAI Gym uses so that integrating with it is trivial. In contrast to the
    OpenAI Gym implementation, this class only defines the abstract methods without any actual
    implementation.
    """
    reward_range = (-np.inf, np.inf)
    action_space = None
    observation_space = spaces.Box(low=0, high=1000, shape=(1, 19))

    #spaces.Discrete(7) 0-6
    possible_actions = ['r', 'g', 'G', 'y', 'o', 'O', 'u']
    edges = []
    TLSID = "0"

    def __init__(self, lanes):
        self.lanes = lanes
        space_init = []

        for i in range(0, lanes):
            space_init.append([0, 6])
        action_space = spaces.MultiDiscrete(space_init)

    def step(self, action):
        """Run one timestep of the environment's dynamics.
        Accepts an action and returns a tuple (observation, reward, done, info).
        Args:
            action (object): an action provided by the environment
        Returns:
            observation (object): agent's observation of the current environment
            reward (float) : amount of reward returned after previous action
            done (boolean): whether the episode has ended, in which case further step() calls will return undefined results
            info (dict): contains auxiliary diagnostic information (helpful for debugging, and sometimes learning)
        """

        traci.simulationStep()
        # read global info
        """
        arrived_vehicles_in_last_step = traci.simulation.getArrivedNumber()
        departed_vehicles_in_last_step = traci.simulation.getDepartedNumber()
        current_simulation_time_ms = traci.simulation.getCurrentTime()
        vehicles_started_to_teleport = traci.simulation.getStartingTeleportNumber()
        vehicles_ended_teleport = traci.simulation.getEndingTeleportNumber()
        vehicles_still_expected = traci.simulation.getMinExpectedNumber()
        traci.trafficlights.setRedYellowGreenState(self.TLSID, action)
        observation = [arrived_vehicles_in_last_step, departed_vehicles_in_last_step,
                       current_simulation_time_ms, vehicles_started_to_teleport,
                       vehicles_ended_teleport, vehicles_still_expected]

        reward = 0
        avg_edge_values = np.zeros(13)
        for e_id in self.edges:
            edge_values = [
                traci.edge.getWaitingTime(e_id),
                traci.edge.getCO2Emission(e_id),
                traci.edge.getCOEmission(e_id),
                traci.edge.getHCEmission(e_id),
                traci.edge.getPMxEmission(e_id),
                traci.edge.getNOxEmission(e_id),
                traci.edge.getFuelConsumption(e_id),
                traci.edge.getLastStepMeanSpeed(e_id),
                traci.edge.getLastStepOccupancy(e_id),
                traci.edge.getLastStepLength(e_id),
                traci.edge.getTraveltime(e_id),
                traci.edge.getLastStepVehicleNumber(e_id),
                traci.edge.getLastStepHaltingNumber(e_id)
            ]
            #scale using the amount of vehicles
            if edge_values[11]>0:
                edge_values[7] /= edge_values[11]
                edge_values[1] /= edge_values[11]
                edge_values[0] /= edge_values[11]
            avg_edge_values = np.add(avg_edge_values, edge_values)


        avg_edge_values /= len(self.edges)

        observation.extend(avg_edge_values)

        waitingFactor = -avg_edge_values[0] / 100
        if waitingFactor == 0:
            waitingFactor += 1
        co2_factor = -avg_edge_values[1] / 3000
        fuel_factor = -avg_edge_values[7]
        green_factor=7*(action.count("g")+action.count("G"))/self.lanes
        yellow_factor=-0.5*action.count("y")/self.lanes
        red_factor=-2*action.count("r")/self.lanes
        
        reward += waitingFactor+co2_factor+fuel_factor+green_factor+yellow_factor+red_factor

        done = False
        info = {"waitingFactor": waitingFactor, "co2_factor":co2_factor,"fuel_factor":fuel_factor,
                "green_factor":green_factor,"yellow_factor":yellow_factor,"red_factor":red_factor,"total_reward":reward}
"""

        return 1, 2, 3, 4

    def reset(self):
        """
        Resets the state of the environment and returns an initial observation.
        Returns:
            observation (object): the initial observation of the space. (Initial reward is assumed to be 0.)
        """

        traci.start(self.sumoCmd)
        #lanes = traci.trafficlights.getControlledLanes(self.TLSID)
        #for lane in lanes:
        #    self.edges.append(traci.lane.getEdgeID(lane))

        #lust = import_datasets()
        step = 0
        tl = traci.trafficlights

    def render(self, mode='human', close=False):
        """Renders the environment.
        The set of supported modes varies per environment. (And some
        environments do not support rendering at all.) By convention,
        if mode is:
        - human: render to the current display or terminal and
          return nothing. Usually for human consumption.
        - rgb_array: Return an numpy.ndarray with shape (x, y, 3),
          representing RGB values for an x-by-y pixel image, suitable
          for turning into a video.
        - ansi: Return a string (str) or StringIO.StringIO containing a
          terminal-style text representation. The text can include newlines
          and ANSI escape sequences (e.g. for colors).
        Note:
            Make sure that your class's metadata 'render.modes' key includes
              the list of supported modes. It's recommended to call super()
              in implementations to use the functionality of this method.
        Args:
            mode (str): the mode to render with
            close (bool): close all open renderings
        """
        return

    def close(self):
        """Override in your subclass to perform any necessary cleanup.
        Environments will automatically close() themselves when
        garbage collected or when the program exits.
        """
        traci.close()

    def seed(self, seed=None):
        """Sets the seed for this env's random number generator(s).
        Note:
            Some environments use multiple pseudorandom number generators.
            We want to capture all such seeds used in order to ensure that
            there aren't accidental correlations between multiple generators.
        Returns:
            list<bigint>: Returns the list of seeds used in this env's random
              number generators. The first value in the list should be the
              "main" seed, or the value which a reproducer should pass to
              'seed'. Often, the main seed equals the provided 'seed', but
              this won't be true if seed=None, for example.
        """
        raise NotImplementedError()

    def configure(self, *args, **kwargs):
        """Provides runtime configuration to the environment.
        This configuration should consist of data that tells your
        environment how to run (such as an address of a remote server,
        or path to your ImageNet data). It should not affect the
        semantics of the environment.
        """
        raise NotImplementedError()

    def __del__(self):
        self.close()

    def __str__(self):
        return '<{} instance>'.format(type(self).__name__)

    def import_datasets():
        csv_dir = "..\\code\\"
        lust_file_name = "dataset-lust-tl-clusters.csv"
        df = pd.read_csv(csv_dir + lust_file_name)
        df['connections'] = df['connections'].map(
            lambda x: ast.literal_eval(x))
        return df

    def extract_tl_ids(connection_list):
        tl_list = []
        for connection in connection_list:
            tl_list.append(connection[2])
        return tl_list
Пример #44
0
    sys.path.append(
        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' as the root directory of your sumo installation (it should contain folders 'bin', 'tools' and 'docs')"
    )

netconvertBinary = checkBinary('netconvert')
sumoBinary = checkBinary('sumo-gui')
sumoCmd = [sumoBinary, "-c", "../data/hello.sumocfg"]

import traci

# Note: the API of the `Env` and `Space` classes are taken from the OpenAI Gym implementation.
# https://github.com/openai/gym/blob/master/gym/core.py

# read: https://gym.openai.com/docs

#os.environ["SUMO_HOME"] = "/usr/share/sumo"


class FickDich(object):
    """Ubuntu Config"""
Пример #45
0
                    help="Port for the Websocket. Please edit script.js when using an other port than 8010.")

if __name__ == "__main__":
    args = parser.parse_args()
    OSMImporterWebSocket.local = args.testOutputDir is not None or not args.remote
    if args.testOutputDir is not None:
        data = {u'duration': 900,
                u'vehicles': {u'passenger': {u'count': 6, u'fringeFactor': 5},
                              u'bicycle': {u'count': 2, u'fringeFactor': 2},
                              u'pedestrian': {u'count': 4, u'fringeFactor': 1},
                              u'ship': {u'count': 1, u'fringeFactor': 40}},
                u'osm': os.path.abspath(args.osmFile),
                u'poly': True,
                u'publicTransport': True,
                u'leftHand': False,
                u'testOutputDir': args.testOutputDir,
                }
        builder = Builder(data, True)
        builder.build()
        builder.makeConfigFile()
        builder.createBatch()
        subprocess.call([sumolib.checkBinary("sumo"), "-c", builder.files["config"]])
    else:
        if not args.remote:
            webbrowser.open("file://" +
                            os.path.join(os.path.dirname(os.path.abspath(__file__)), "webWizard", "index.html"))

        server = SimpleWebSocketServer(
            args.address, args.port, OSMImporterWebSocket)
        server.serveforever()
Пример #46
0
    sys.path.append(
        os.path.join(
            os.environ.get(
                "SUMO_HOME",
                os.path.join(os.path.dirname(__file__), "..", "..", "..")),
            "tools"))

    from sumolib import checkBinary
except ImportError:
    sys.exit(
        "please declare environment variable 'SUMO_HOME' as the root directory "
        "of your sumo installation (it should contain folders 'bin', 'tools' "
        "and 'docs')")
import traci

SUMO_BINARY = checkBinary('sumo')
VEHICLE_COUNT = 501
VEHICLE_INDEX_START = 1
WINKER_PERIOD = 0.5
TLS = {
    '6': 'gneJ7',
    '7': 'gneJ4',
    '8': 'gneJ8',
    '11': 'gneJ0',
    '12': 'gneJ1',
    '13': 'gneJ2',
    '16': 'gneJ6',
    '17': 'gneJ3',
    '18': 'gneJ9',
    '0': 'gneJ9',
    '1': 'gneJ9',
Пример #47
0
class FickDich(object):
    """Ubuntu Config"""
    # sys.path.append('/usr/share/sumo/tools')

    sumoBinary = checkBinary('sumo-gui')
    sumoCmd = [sumoBinary, "-c", "../data/cross.sumocfg"]

    reward_range = (-np.inf, np.inf)
    action_space = None
    observation_space = spaces.Box(low=0,high=1000, shape=(1,19))

    edges = []


    def __init__(self):
        self.lanes = 12

        self.action_space = spaces.Discrete(2)
        self.reward_range = (-np.inf, np.inf)
        self.observation_space = spaces.Box(low=0, high=1000, shape=(1, 19))
        self.TLSID = "0"


    def step(self, action):
        traci.simulationStep()
        # read global info

        arrived_vehicles_in_last_step = traci.simulation.getArrivedNumber()
        departed_vehicles_in_last_step = traci.simulation.getDepartedNumber()
        current_simulation_time_ms = traci.simulation.getCurrentTime()
        vehicles_started_to_teleport = traci.simulation.getStartingTeleportNumber()
        vehicles_ended_teleport = traci.simulation.getEndingTeleportNumber()
        vehicles_still_expected = traci.simulation.getMinExpectedNumber()
        action = self.convert_sample_to_phase(action)
#        print("   ----- State: {}".format(action))

        #traci.trafficlights.setRedYellowGreenState('0', action)


        observation = [arrived_vehicles_in_last_step, departed_vehicles_in_last_step,
                       current_simulation_time_ms, vehicles_started_to_teleport,
                       vehicles_ended_teleport, vehicles_still_expected]

        reward = 0
        avg_edge_values = np.zeros(13)
        for e_id in self.edges:
            print(traci.edge.getCO2Emission(e_id))
            edge_values = [
                traci.edge.getWaitingTime(e_id),
                traci.edge.getCO2Emission(e_id),
                traci.edge.getCOEmission(e_id),
                traci.edge.getHCEmission(e_id),
                traci.edge.getPMxEmission(e_id),
                traci.edge.getNOxEmission(e_id),
                traci.edge.getFuelConsumption(e_id),
                traci.edge.getLastStepMeanSpeed(e_id),
                traci.edge.getLastStepOccupancy(e_id),
                traci.edge.getLastStepLength(e_id),
                traci.edge.getTraveltime(e_id),
                traci.edge.getLastStepVehicleNumber(e_id),
                traci.edge.getLastStepHaltingNumber(e_id)
            ]
            #scale using the amount of vehicles
            if edge_values[11]>0:
                edge_values[7] /= edge_values[11]
                edge_values[1] /= edge_values[11]
                edge_values[0] /= edge_values[11]
            avg_edge_values = np.add(avg_edge_values, edge_values)


        avg_edge_values /= len(self.edges)

        observation.extend(avg_edge_values)

        waitingFactor = -avg_edge_values[0] / 100
        if waitingFactor == 0:
            waitingFactor += 1
        co2_factor = -avg_edge_values[1] / 3000
        fuel_factor = -avg_edge_values[7]
        green_factor=7*(action.count("g")+action.count("G"))/self.lanes
        yellow_factor=-0.5*action.count("y")/self.lanes
        red_factor=-2*action.count("r")/self.lanes

        reward += waitingFactor+co2_factor+fuel_factor+green_factor+yellow_factor+red_factor

        done = False
        info = {"waitingFactor": waitingFactor, "co2_factor":co2_factor,"fuel_factor":fuel_factor,
                "green_factor":green_factor,"yellow_factor":yellow_factor,"red_factor":red_factor,"total_reward":reward}

        return observation, reward, done, info



    def reset(self):
        traci.start(self.sumoCmd)
        lanes = traci.trafficlights.getControlledLanes(self.TLSID)
        for lane in lanes:
            self.edges.append(traci.lane.getEdgeID(lane))

        return np.zeros(19)

    def render(self, mode='human', close=False):
        return

    def close(self):
        traci.close()

    def _seed(self, seed=None):
        self.np_random, seed = seeding.np_random(seed)
        return [seed]

    def configure(self, *args, **kwargs):
        raise NotImplementedError()

    def __del__(self):
        self.close()

    def __str__(self):
        return '<{} instance>'.format(type(self).__name__)

    def convert_sample_to_phase(self, sample):
        if sample == 1:
            return 'rgrg'
        else:
            return 'grgr'
 def render(self, use_gui):
     if use_gui:
         self.sumo_binary = sumolib.checkBinary('sumo-gui')
     else:
         self.sumo_binary = sumolib.checkBinary('sumo')
Пример #49
0
from __future__ import print_function
from __future__ import absolute_import
import os
import subprocess
import sys
import random
import struct
import random
import time
sys.path.append(
    os.path.join(os.path.dirname(sys.argv[0]), "..", "..", "..", "..", "..",
                 "tools"))
import traci
import sumolib  # noqa

sumoBinary = sumolib.checkBinary('sumo-gui')

PORT = sumolib.miscutils.getFreeSocketPort()
sumoProcess = subprocess.Popen("%s -S -Q -c sumo.sumocfg --remote-port %s" %
                               (sumoBinary, PORT),
                               shell=True,
                               stdout=sys.stdout)
traci.init(PORT)
for step in range(3):
    print("step", step)
    traci.simulationStep()
time.sleep(1)  # give the gui a chance to draw itself
print("views", traci.gui.getIDList())
viewID = traci.gui.DEFAULT_VIEW
print("examining", viewID)
print("zoom", traci.gui.getZoom(viewID))
Пример #50
0
    simulation = StrSumo(scheduler, init_connection_info, vehicles)

    traci.start([sumo_binary, "-c", "./configurations/myconfig.sumocfg", \
                 "--tripinfo-output", "./configurations/trips.trips.xml", \
                 "--fcd-output", "./configurations/testTrace.xml"])

    total_time, end_number, deadlines_missed = simulation.run()
    traci.close()
    print("Average timespan: {}, total vehicle number: {}".format(str(total_time/end_number),\
        str(end_number)))
    print(str(deadlines_missed) + ' deadlines missed.')


if __name__ == "__main__":
    sumo_binary = checkBinary('sumo-gui')
    # sumo_binary = checkBinary('sumo')#use this line if you do not want the UI of SUMO

    # parse config file for map file name
    dom = parse("./configurations/myconfig.sumocfg")

    net_file_node = dom.getElementsByTagName('net-file')
    net_file_attr = net_file_node[0].attributes

    net_file = net_file_attr['value'].nodeValue
    init_connection_info = ConnectionInfo("./configurations/" + net_file)

    route_file_node = dom.getElementsByTagName('route-files')
    route_file_attr = route_file_node[0].attributes
    route_file = "./configurations/" + route_file_attr['value'].nodeValue
    vehicles = get_controlled_vehicles(route_file, init_connection_info, 100,
Пример #51
0
    def build(self, netName="net.net.xml"):
        connections = []
        nodesFile = tempfile.NamedTemporaryFile(mode="w", delete=False)
        print("<nodes>", file=nodesFile)
        for nid in self._nodes:
            n = self._nodes[nid]
            print('    <node id="%s" x="%s" y="%s" type="%s"/>' %
                  (n.nid, n.x, n.y, n.nodeType),
                  file=nodesFile)
        print("</nodes>", file=nodesFile)
        nodesFile.close()

        edgesFile = tempfile.NamedTemporaryFile(mode="w", delete=False)
        print("<edges>", file=edgesFile)
        for eid in self._edges:
            e = self._edges[eid]
            print(
                '    <edge id="%s" from="%s" to="%s" numLanes="%s" speed="%s">'
                %
                (e.eid, e.fromNode.nid, e.toNode.nid, e.numLanes, e.maxSpeed),
                file=edgesFile)
            for s in e.splits:
                print('        <split pos="%s" lanes="%s"/>' %
                      (-s.distance, " ".join(map(str, s.lanes))),
                      file=edgesFile)
            """
        for i,l in enumerate(e.lanes):
            if l.allowed==None and l.disallowed==None:
                continue
            ls =  '        <lane index="%s" ' % (i)
            if l.allowed!=None:
                ls = ls + 'allow="%s"' % l.allowed
            if l.disallowed!=None:
                ls = ls + 'disallow="%s"' % l.disallowed
            print >> edgesFile, ls+'/>'
        """

            connections.extend(e.getConnections(self))
            print('    </edge>', file=edgesFile)

            hadConstraints = False
            for i, l in enumerate(e.lanes):
                if l.allowed is None and l.disallowed is None:
                    continue
                hadConstraints = True
            if hadConstraints:
                for s in e.splits:
                    eid = e.eid
                    if s.distance != 0:
                        eid = eid + ".%s" % -s.distance
                    print('    <edge id="%s">' % (eid), file=edgesFile)
                    for i, l in enumerate(e.lanes):
                        # if i not in s.lanes:
                        #    continue
                        if l.allowed is None and l.disallowed is None:
                            continue
                        ls = '        <lane index="%s" ' % (i)
                        if l.allowed is not None:
                            ls = ls + 'allow="%s"' % l.allowed
                        if l.disallowed is not None:
                            ls = ls + 'disallow="%s"' % l.disallowed
                        print(ls + '/>', file=edgesFile)
                    print('    </edge>', file=edgesFile)

        print("</edges>", file=edgesFile)
        edgesFile.close()

        connectionsFile = tempfile.NamedTemporaryFile(mode="w", delete=False)
        print("<connections>", file=connectionsFile)
        for c in connections:
            eid = c.fromEdge.eid
            if len(c.fromEdge.splits) > 1:
                eid = eid + ".-" + str(c.fromEdge.splits[-1].distance)
            print(
                '    <connection from="%s" to="%s" fromLane="%s" toLane="%s"/>'
                % (eid, c.toEdge.eid, c.fromLane, c.toLane),
                file=connectionsFile)
        for n in self._nodes:
            if len(self._nodes[n].crossings) == 0:
                continue
            for c in self._nodes[n].crossings:
                print('    <crossing node="%s" edges="%s"/>' %
                      (n, " ".join(c)),
                      file=connectionsFile)
        print("</connections>", file=connectionsFile)
        connectionsFile.close()

        netconvert = sumolib.checkBinary("netconvert")

        subprocess.call([
            netconvert, "-v", "-n", nodesFile.name, "-e", edgesFile.name, "-x",
            connectionsFile.name, "-o", netName
        ])
        os.remove(nodesFile.name)
        os.remove(edgesFile.name)
        os.remove(connectionsFile.name)
        self.netName = netName
        return netName
Пример #52
0
    gui = chr(gui)

#Lets check whether Sumo is present or not, and then go to the tools folder of Sumo
print("Checking Sumo...")
try:
    sys.path.append(os.path.join(SUMO_HOME, "tools")) 					#go to tools folder
    from sumolib import checkBinary										#A sumo back-end library to check if sumo is present or not
except ImportError:
    sys.exit("Please declare environment variable 'SUMO_HOME' as the root directory of your sumo installation (it should contain folders 'bin', 'tools' and 'docs')")

# Specify a Port for TCP connection. Python will interact with Sumo on this port. Make sure no other application is using this port
print("Starting Sumo Simulation")
PORT = 8813

if gui=='1':
	sumoBinary = checkBinary('sumo-gui')		#Open SUMO in GUI
else:
	sumoBinary = checkBinary('sumo')			#Open SUMO in CLI

sumoProcess = subprocess.Popen([sumoBinary, "-c", config_file,'--start','--remote-port', str(PORT)], stdout=sys.stdout, stderr=sys.stderr)


# Import Sumo Libraries
import traci, string
import traci.constants as tc

traci.init(PORT)

print(" Running Sumo Simulation...")

while True:
Пример #53
0
import os
import sys
import random
import bisect
import subprocess
from collections import defaultdict
import math
import optparse

if 'SUMO_HOME' in os.environ:
    sys.path.append(os.path.join(os.environ['SUMO_HOME'], 'tools'))
import sumolib  # noqa
from sumolib.miscutils import euclidean  # noqa
from sumolib.geomhelper import naviDegree, minAngleDegreeDiff  # noqa

DUAROUTER = sumolib.checkBinary('duarouter')

SOURCE_SUFFIX = ".src.xml"
SINK_SUFFIX = ".dst.xml"
VIA_SUFFIX = ".via.xml"


def get_options(args=None):
    optParser = optparse.OptionParser()
    optParser.add_option("-n", "--net-file", dest="netfile",
                         help="define the net file (mandatory)")
    optParser.add_option("-a", "--additional-files", dest="additional",
                         help="define additional files to be loaded by the router")
    optParser.add_option("-o", "--output-trip-file", dest="tripfile",
                         default="trips.trips.xml", help="define the output trip filename")
    optParser.add_option("-r", "--route-file", dest="routefile",
Пример #54
0
def main(options):
    targets = []
    if options.file:
        dirname = os.path.dirname(options.file)
        for line in open(options.file):
            line = line.strip()
            if line and line[0] != '#':
                ls = line.split(SOURCE_DEST_SEP) + [""]
                ls[0] = join(dirname, ls[0])
                ls[1] = join(dirname, ls[1])
                targets.append(ls[:3])
    for val in options.args:
        source_and_maybe_target = val.split(SOURCE_DEST_SEP) + ["", ""]
        targets.append(source_and_maybe_target[:3])

    if options.python_script:
        if not os.path.exists(os.path.dirname(options.python_script)):
            os.makedirs(os.path.dirname(options.python_script))
        pyBatch = open(options.python_script, 'w')
        pyBatch.write('''import subprocess, sys, os
from os.path import abspath, dirname, join
THIS_DIR = abspath(dirname(__file__))
SUMO_HOME = os.environ.get("SUMO_HOME", dirname(dirname(THIS_DIR)))
os.environ["SUMO_HOME"] = SUMO_HOME
for d, p in [
''')
    for source, target, app in targets:
        optionsFiles = defaultdict(list)
        configFiles = defaultdict(list)
        potentials = defaultdict(list)
        source = os.path.realpath(source)
        curDir = source
        if curDir[-1] == os.path.sep:
            curDir = os.path.dirname(curDir)
        while True:
            for f in sorted(os.listdir(curDir)):
                path = join(curDir, f)
                if f not in potentials or os.path.isdir(path):
                    potentials[f].append(path)
                if f.startswith("options."):
                    optionsFiles[f[8:]].append(path)
                if f.startswith("config."):
                    configFiles[f[7:]].append(path)
            if curDir == os.path.realpath(join(SUMO_HOME, "tests")) or curDir == os.path.dirname(curDir):
                break
            curDir = os.path.dirname(curDir)
        if not configFiles:
            print("Config not found for %s." % source, file=sys.stderr)
            continue
        if len(glob.glob(os.path.join(source, "testsuite.*"))) > 0:
            print("Directory %s seems to contain a test suite." % source, file=sys.stderr)
            continue
        if app == "":
            for v in configFiles.keys():
                if "." not in v:
                    app = v
                    break
        haveVariant = False
        for variant in set(optionsFiles.keys()) | set(configFiles.keys()):
            if options.application not in (None, "ALL", variant, variant.split(".")[-1]):
                continue
            if options.application is None and len(glob.glob(os.path.join(source, "*" + variant))) == 0:
                if options.verbose:
                    print("ignoring variant %s for '%s'" % (variant, source))
                continue
            haveVariant = True
            cfg = configFiles[variant] + configFiles[app]
            if target == "" and not options.noSubdir:
                target = generateTargetName(os.path.dirname(cfg[-1]), source)
            testPath = os.path.abspath(join(options.output, target))
            if not os.path.exists(testPath):
                os.makedirs(testPath)
            net = None
            skip = False
            appOptions = []
            optFiles = optionsFiles[app] + ([] if variant == app else optionsFiles[variant])
            for f in sorted(optFiles, key=lambda o: o.count(os.sep)):
                for o in shlex.split(open(f).read()):
                    if skip:
                        skip = False
                        continue
                    if o == "--xml-validation" and options.skip_validation:
                        skip = True
                        continue
                    if o == "{CLEAR}":
                        appOptions = []
                        continue
                    if o[0] == "-" and o in appOptions:
                        idx = appOptions.index(o)
                        if idx < len(appOptions) - 1 and appOptions[idx + 1][0] != "-":
                            del appOptions[idx:idx+2]
                    appOptions.append(o)
                    if "=" in o:
                        o = o.split("=")[-1]
                    if o[-8:] == ".net.xml":
                        net = o
            nameBase = "test"
            if options.names:
                nameBase = os.path.basename(target)
            if "." in variant:
                nameBase += variant.split(".")[-1]
            exclude = []
            # gather copy_test_path exclusions
            for config in cfg:
                for line in open(config):
                    entry = line.strip().split(':')
                    if entry and entry[0] == "test_data_ignore":
                        exclude.append(entry[1])
            # copy test data from the tree
            for config in cfg:
                for line in open(config):
                    entry = line.strip().split(':')
                    if entry and "copy_test_path" in entry[0] and entry[1] in potentials:
                        if "net" in app or not net or entry[1][-8:] != ".net.xml" or entry[1] == net:
                            toCopy = potentials[entry[1]][0]
                            if os.path.isdir(toCopy):
                                # copy from least specific to most specific
                                merge = entry[0] == "copy_test_path_merge"
                                for toCopy in reversed(potentials[entry[1]]):
                                    copy_merge(toCopy, join(testPath, os.path.basename(toCopy)), merge, exclude)
                            else:
                                shutil.copy2(toCopy, testPath)
            if options.python_script:
                if app == "netgen":
                    call = ['join(SUMO_HOME, "bin", "netgenerate")'] + ['"%s"' % a for a in appOptions]
                elif app == "tools":
                    call = ['"python"'] + ['"%s"' % a for a in appOptions]
                    call[1] = 'join(SUMO_HOME, "%s")' % appOptions[0]
                elif app == "complex":
                    call = ['"python"']
                    for a in appOptions:
                        if a.endswith(".py"):
                            if os.path.exists(join(testPath, os.path.basename(a))):
                                call.insert(1, '"./%s"' % os.path.basename(a))
                            else:
                                call.insert(1, 'join(SUMO_HOME, "%s")' % a)
                        else:
                            call.append('"%s"' % a)
                else:
                    call = ['join(SUMO_HOME, "bin", "%s")' % app] + ['"%s"' % a for a in appOptions]
                prefix = os.path.commonprefix((testPath, os.path.abspath(pyBatch.name)))
                up = os.path.abspath(pyBatch.name)[len(prefix):].count(os.sep) * "../"
                pyBatch.write('    (r"%s", subprocess.Popen([%s], cwd=join(THIS_DIR, r"%s%s"))),\n' %
                              (testPath[len(prefix):], ', '.join(call), up, testPath[len(prefix):]))
            if options.skip_configuration:
                continue
            oldWorkDir = os.getcwd()
            os.chdir(testPath)
            haveConfig = False
            if app in ["dfrouter", "duarouter", "jtrrouter", "marouter", "netconvert",
                       "netgen", "netgenerate", "od2trips", "polyconvert", "sumo", "activitygen"]:
                if app == "netgen":
                    # binary is now called differently but app still has the old name
                    app = "netgenerate"
                if options.verbose:
                    print("calling %s for testPath '%s' with options '%s'" %
                          (checkBinary(app), testPath, " ".join(appOptions)))
                try:
                    haveConfig = subprocess.call([checkBinary(app)] + appOptions +
                                                 ['--save-configuration', '%s.%scfg' %
                                                  (nameBase, app[:4])]) == 0
                except OSError:
                    print("Executable %s not found, generating shell scripts instead of config." % app, file=sys.stderr)
                if not haveConfig:
                    appOptions.insert(0, '"$SUMO_HOME/bin/%s"' % app)
            elif app == "tools":
                for i, a in enumerate(appOptions):
                    if a.endswith(".py"):
                        del appOptions[i:i+1]
                        appOptions[0:0] = [os.environ.get("PYTHON", "python"), '"$SUMO_HOME/%s"' % a]
                        break
                    if a.endswith(".jar"):
                        del appOptions[i:i+1]
                        appOptions[0:0] = ["java", "-jar", '"$SUMO_HOME/%s"' % a]
                        break
            elif app == "complex":
                for i, a in enumerate(appOptions):
                    if a.endswith(".py"):
                        if os.path.exists(join(testPath, os.path.basename(a))):
                            a = os.path.basename(a)
                        else:
                            a = '"$SUMO_HOME/%s"' % a
                        del appOptions[i:i+1]
                        appOptions[0:0] = [os.environ.get("PYTHON", "python"), a]
                        break
            if not haveConfig:
                if options.verbose:
                    print("generating shell scripts for testPath '%s' with call '%s'" %
                          (testPath, " ".join(appOptions)))
                cmd = [o if " " not in o else "'%s'" % o for o in appOptions]
                open(nameBase + ".sh", "w").write(" ".join(cmd))
                cmd = [o.replace("$SUMO_HOME", "%SUMO_HOME%") if " " not in o else '"%s"' % o for o in appOptions]
                open(nameBase + ".bat", "w").write(" ".join(cmd))
            os.chdir(oldWorkDir)
        if not haveVariant:
            print("No suitable variant found for %s." % source, file=sys.stderr)
    if options.python_script:
        pyBatch.write("""]:
    if p.wait() != 0:
        print("Error: '%s' failed for '%s'!" % (" ".join(p.args), d))
        sys.exit(1)\n""")
Пример #55
0
                     default=False,
                     help="sorts the output by departure time")
optParser.add_option("-p", "--path", dest="path", help="Path to binaries")
optParser.add_option(
    "--cost-modifier",
    dest="costmodifier",
    type="choice",
    choices=('grohnde', 'isar', 'None'),
    default='None',
    help="Whether to modify link travel costs of the given routes")
(options, args) = optParser.parse_args()

sumo = "sumo"
if options.mesosim:
    sumo = "meso"
sumoBinary = sumolib.checkBinary(sumo, options.path)
if options.costmodifier != 'None':
    pyPath = os.path.abspath(os.path.dirname(sys.argv[0]))
    sys.path.append(
        os.path.join(pyPath, "..", "..", "..", "..", "..", "tools", "kkwSim"))
    from kkwCostModifier import costModifier
    print('use the cost modifier')

log = open("one_shot-log.txt", "w")
starttime = datetime.now()
for step in options.frequencies.split(","):
    step = int(step)
    print("> Running simulation with update frequency %s" % step)
    btime = datetime.now()
    print(">> Begin time %s" % btime)
    if options.costmodifier != 'None':
Пример #56
0
                },
                u'ship': {
                    u'count': 1,
                    u'fringeFactor': 40
                }
            },
            u'osm': os.path.abspath(args.osmFile),
            u'poly': True,
            u'publicTransport': True,
            u'leftHand': False,
            u'decal': False,
            u'carOnlyNetwork': False,
            u'testOutputDir': args.testOutputDir,
        }
        builder = Builder(data, True)
        builder.build()
        builder.makeConfigFile()
        builder.createBatch()
        subprocess.call(
            [sumolib.checkBinary("sumo"), "-c", builder.files["config"]])
    else:
        if not args.remote:
            webbrowser.open(
                "file://" +
                os.path.join(os.path.dirname(os.path.abspath(__file__)),
                             "webWizard", "index.html"))

        server = SimpleWebSocketServer(args.address, args.port,
                                       OSMImporterWebSocket)
        server.serveforever()
Пример #57
0
def main(options):
    targets = []
    if options.file:
        dirname = os.path.dirname(options.file)
        for line in open(options.file):
            line = line.strip()
            if line and line[0] != '#':
                l = line.split(SOURCE_DEST_SEP) + [""]
                l[0] = join(dirname, l[0])
                l[1] = join(dirname, l[1])
                targets.append(l[:3])
    for val in options.args:
        source_and_maybe_target = val.split(SOURCE_DEST_SEP) + ["", ""]
        targets.append(source_and_maybe_target[:3])

    for source, target, app in targets:
        outputFiles = glob.glob(join(source, "output.[0-9a-z]*"))
        # print source, target, outputFiles
        # XXX we should collect the options.app.variant files in all parent
        # directories instead. This would allow us to save config files for all
        # variants
        appName = set([f.split('.')[-1] for f in outputFiles])
        if len(appName) != 1:
            if options.application in appName:
                appName = set([options.application])
            elif app in appName:
                appName = set([app])
            else:
                print("Skipping %s because the application was not unique (found %s)." % (
                    source, appName), file=sys.stderr)
                continue
        app = next(iter(appName))
        optionsFiles = []
        configFiles = []
        potentials = defaultdict(list)
        source = os.path.realpath(source)
        curDir = source
        if curDir[-1] == os.path.sep:
            curDir = os.path.dirname(curDir)
        while True:
            for f in os.listdir(curDir):
                path = join(curDir, f)
                if f not in potentials or os.path.isdir(path):
                    potentials[f].append(path)
                if f == "options." + app:
                    optionsFiles.append(path)
            config = join(curDir, "config." + app)
            if curDir == join(SUMO_HOME, "tests") or curDir == os.path.dirname(curDir):
                break
            if os.path.exists(config):
                configFiles.append(config)
            curDir = os.path.dirname(curDir)
        if not configFiles:
            print("Config not found for %s." % source, file=sys.stderr)
            continue
        if target == "":
            target = generateTargetName(
                os.path.dirname(configFiles[-1]), source)
        testPath = os.path.abspath(join(options.output, target))
        if not os.path.exists(testPath):
            os.makedirs(testPath)
        net = None
        skip = False
        appOptions = []
        for f in reversed(optionsFiles):
            for o in open(f).read().split():
                if skip:
                    skip = False
                    continue
                if o == "--xml-validation" and options.skip_validation:
                    skip = True
                    continue
                if o == "{CLEAR}":
                    appOptions = []
                    continue
                appOptions.append(o)
                if "=" in o:
                    o = o.split("=")[-1]
                if o[-8:] == ".net.xml":
                    net = o
        nameBase = "test"
        if options.names:
            nameBase = os.path.basename(target)
        exclude = []
        # gather copy_test_path exclusions
        for config in configFiles:
            for line in open(config):
                entry = line.strip().split(':')
                if entry and entry[0] == "test_data_ignore":
                    exclude.append(entry[1])
        # copy test data from the tree
        for config in configFiles:
            for line in open(config):
                entry = line.strip().split(':')
                if entry and "copy_test_path" in entry[0] and entry[1] in potentials:
                    if "net" in app or not net or entry[1][-8:] != ".net.xml" or entry[1] == net:
                        toCopy = potentials[entry[1]][0]
                        if os.path.isdir(toCopy):
                            # copy from least specific to most specific
                            merge = entry[0] == "copy_test_path_merge"
                            for toCopy in reversed(potentials[entry[1]]):
                                copy_merge(
                                    toCopy, join(testPath, os.path.basename(toCopy)), merge, exclude)
                        else:
                            shutil.copy2(toCopy, testPath)
        if options.skip_configuration:
            continue
        oldWorkDir = os.getcwd()
        os.chdir(testPath)
        if app in ["dfrouter", "duarouter", "jtrrouter", "marouter", "netconvert",
                   "netgen", "netgenerate", "od2trips", "polyconvert", "sumo", "activitygen"]:
            appOptions += ['--save-configuration', '%s.%scfg' %
                           (nameBase, app[:4])]
            if app == "netgen":
                # binary is now called differently but app still has the old
                # name
                app = "netgenerate"
            if options.verbose:
                print("calling %s for testPath '%s' with  options '%s'" %
                      (checkBinary(app), testPath, " ".join(appOptions)))
            subprocess.call([checkBinary(app)] + appOptions)
        elif app == "tools":
            if os.name == "posix" or options.file:
                tool = join("$SUMO_HOME", appOptions[-1])
                open(nameBase + ".sh", "w").write(tool +
                                                  " " + " ".join(appOptions[:-1]))
            if os.name != "posix" or options.file:
                tool = join("%SUMO_HOME%", appOptions[-1])
                open(nameBase + ".bat", "w").write(tool +
                                                   " " + " ".join(appOptions[:-1]))
        os.chdir(oldWorkDir)
Пример #58
0
    def workerThread(self):
        try:
            traci.start([checkBinary("sumo-gui"), "-c", self.sumocfg,
                         "--lateral-resolution", "0.32",
                         "--collision.action", "warn",
                         "--step-length", str(TS)])
            # steal focus for keyboard input after sumo-gui has loaded
            # self.master.focus_force() # not working on all platforms
            # make sure ego vehicle is loaded
            traci.simulationStep()
            speed = traci.vehicle.getSpeed(self.egoID)
            angle = traci.vehicle.getAngle(self.egoID)
            traci.vehicle.setSpeedMode(self.egoID, 0)
            steerAngle = 0
            x, y = traci.vehicle.getPosition(self.egoID)
            traci.gui.trackVehicle(traci.gui.DEFAULT_VIEW, self.egoID)
            while traci.simulation.getMinExpectedNumber() > 0:
                try:
                    if eventQueue.qsize() == 0:
                        if steerAngle > 0:
                            steerAngle = max(0, steerAngle - MAX_STEER_ANGLE * TS)
                        else:
                            steerAngle = min(0, steerAngle + MAX_STEER_ANGLE * TS)
                        # print("revert steerAngle=%.2f" % steerAngle)
                    while eventQueue.qsize():
                        try:
                            msg = eventQueue.get(0)
                            if len(msg) == 1:
                                direction = msg
                                val = None
                            else:
                                direction, val = msg

                            if direction == 'up':
                                if val is None:
                                    val = 1
                                speed += val * TS * traci.vehicle.getAccel(self.egoID)
                            if direction == 'down':
                                if val is None:
                                    val = 1
                                speed -= val * TS * traci.vehicle.getDecel(self.egoID)
                            if direction == 'left':
                                if val is None:
                                    steerAngle -= TS * 5
                                else:
                                    steerAngle = val
                            if direction == 'right':
                                if val is None:
                                    steerAngle += TS * 5
                                else:
                                    steerAngle = val
                        except Queue.Empty:
                            pass
                    if autopy:
                        speed, steerAngle = mouseControl(self.master, speed, steerAngle)
                    # move vehicle
                    # posLat = traci.vehicle.getLateralLanePosition(self.egoID)
                    if traci.vehicle.getLaneID(self.egoID) == "":
                        if abs(speed) > MAX_OFFROAD_SPEED:
                            sign = 1 if speed > 0 else -1
                            speed -= TS * sign * (abs(speed) - MAX_OFFROAD_SPEED) / OFFROAD_DECEL_TIME

                    speed = max(MIN_SPEED, min(speed, traci.vehicle.getMaxSpeed(self.egoID)))
                    steerAngle = min(MAX_STEER_ANGLE, max(-MAX_STEER_ANGLE, steerAngle))
                    angle += steerAngle
                    angle = angle % 360
                    rad = -angle / 180 * math.pi + 0.5 * math.pi
                    x2 = x + math.cos(rad) * TS * speed
                    y2 = y + math.sin(rad) * TS * speed
                    traci.vehicle.moveToXY(self.egoID, "dummy", -1, x2, y2, angle, keepRoute=2)
                    traci.vehicle.setSpeed(self.egoID, speed)
                    traci.vehicle.setLine(self.egoID, str(speed))
                    x3, y3 = traci.vehicle.getPosition(self.egoID)
                    x, y = x2, y2
                    traci.simulationStep()
                    if VERBOSE:
                        print(("old=%.2f,%.2f new=%.2f,%.2f found=%.2f,%.2f speed=%.2f steer=%.2f " +
                               "angle=%s rad/pi=%.2f cos=%.2f sin=%.2f") % (
                            x, y, x2, y2, x3, y3, speed, steerAngle, angle, rad / math.pi,
                            math.cos(rad), math.sin(rad)))
                except traci.TraCIException:
                    pass
            traci.close()
        except traci.FatalTraCIError:
            pass
        self.running = False
Пример #59
0
    return tl_series_data


def get_df(edge_data):
    """ Returns dataframe given dictionary of edge values """
    edge_data = np.array(edge_data)
    df = pd.DataFrame(data=edge_data[1:, 1:],
                      index=edge_data[1:, 0],
                      columns=edge_data[0, 1:])  # 1st row as the column names
    return df


if __name__ == "__main__":

    # Sumo init and global simulatio parameters
    sumoBinary = checkBinary('sumo')
    sumo_cmd = [sumoBinary, "-c", "osm.sumocfg"]
    traci.start(sumo_cmd)
    step = 0
    total_steps = int(
        sys.argv[1]) if sys.argv[1] else 1000  # steps taken by the simulation
    num_entries = int(sys.argv[2]) if sys.argv[
        1] else 10000  # number of edges or traffic lights you want to create files for
    # total_steps = 30 # steps taken by the simulation
    # num_entries = 100  # number of edges or traffic lights you want to create files for
    date = datetime.now().strftime("%I-%M-%S-%B-%d-%Y")  # path parameter
    edge_dir_name = r'\edge_data-{}-{}-{}'.format(total_steps, num_entries,
                                                  date)
    edge_datafile_path = os.path.dirname(
        os.path.abspath(__file__)) + edge_dir_name
    tl_dir_name = r'\tl_data-{}-{}-{}'.format(total_steps, num_entries, date)
Пример #60
0
SUMO is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
"""

import os
import subprocess
import sys
sys.path.append(
    os.path.join(os.path.dirname(sys.argv[0]), "..", "..", "..", "..", "..",
                 "tools"))
import traci
import sumolib

sumoBinary = sumolib.checkBinary('sumo')

PORT = sumolib.miscutils.getFreeSocketPort()
sumoProcess = subprocess.Popen("%s -c sumo.sumocfg --remote-port %s" %
                               (sumoBinary, PORT),
                               shell=True,
                               stdout=sys.stdout)
traci.init(PORT)
for step in range(3):
    print "step", step
    traci.simulationStep()
print "edges", traci.edge.getIDList()
print "edge count", traci.edge.getIDCount()
edgeID = "2fi"
print "examining", edgeID
print "adaptedTraveltime", traci.edge.getAdaptedTraveltime(edgeID, 0)