def _init_sim(self, seed, gui=False): sumocfg_file = self._init_sim_config(seed) if gui: app = 'sumo-gui' else: app = 'sumo' command = [checkBinary(app), '-c', sumocfg_file] command += ['--seed', str(seed)] command += ['--remote-port', str(self.port)] command += ['--no-step-log', 'True'] #if self.name != 'real_net': # command += ['--time-to-teleport', '600'] # long teleport for safety #else: command += ['--time-to-teleport', '300'] command += ['--no-warnings', 'True'] command += ['--duration-log.disable', 'True'] command += ['--ignore-route-errors', 'True'] # collect trip info if necessary #if self.is_record: command += [ '--tripinfo-output', self.output_path + ('%s_%s_trip.xml' % (self.name, self.agent)) ] subprocess.Popen(command) # wait 2s to establish the traci server #time.sleep(1) print("connecting on port: ", self.port) self.sim = traci.connect(port=self.port) self._simulate(10)
def startTraciInstance(cfg, begin=None, state_opt=None, port=None): # create args for running sumo on next available port if port == None: port = sim_globals['next_free_port'] sim_globals['next_free_port'] += 1 args = [ sumo_path + '\\sumo-gui.exe', '-c', cfg, '--remote-port', str(port) ] if begin: args += ['--begin', str(begin)] if state_opt: if state_opt['mode'] in ('load', 'both'): args += ['--load-state', state_opt['load-file']] if state_opt['mode'] in ('save', 'both'): args += ['--save-state.period', state_opt['save-period']] args += ['--save-state.prefix', state_opt['save-prefix']] args += ['--save-state.suffix', '.xml'] p = subprocess.Popen(args, stdout=subprocess.PIPE) t = traci.connect(port) return p, t, port
def gen_sim(self): #create sim stuff and intersections #serverless_connect() #self.conn, self.sumo_process = self.server_connect() port = self.args.port+self.idx sumoBinary = checkBinary(self.sumo_cmd) port = self.args.port+self.idx self.sumo_process = subprocess.Popen([sumoBinary, "-c", self.cfg_fp, "--step-length", str(STEP_LEN_SIMU), "--remote-port", str(port), "--no-warnings", "--no-step-log", "--random"], stdout=None, stderr=None) self.conn = traci.connect(port) self.t = 0 self.v_start_times = {} self.v_travel_times = {} self.vehiclegen = None if self.args.sim == 'double' or self.args.sim == 'single': self.vehiclegen = VehicleGen(self.netdata, self.args.sim_len, self.args.demand, self.args.scale, self.args.mode, self.conn)
def __init__(self,args,netdata,log): self.t = 0 self.args = args self.sumo_cmd = set_sumo(args.gui, args.roadnet, args.max_steps, args.port) self.log = log print(self.sumo_cmd) self.save_path = set_save_path(args.roadnet,args.tsc) self.saver = Saver(self.save_path) self.max_steps = args.max_steps self.green_t = args.green_duration self.yellow_t = args.yellow_duration self.red_t = args.red_duration self.mode = args.mode self.scale = args.scale self.port = args.port self.netdata = netdata self.tl_ids = self.netdata['inter'].keys() self.sumo_process = subprocess.Popen(self.sumo_cmd) self.conn = traci.connect(self.port) self.netdata = self.update_netdata() self.vehiclegen = VehicleGen(self.netdata,self.conn,self.mode,self.scale,self.max_steps) self.Controllers = {str(id):None for id in self.tl_ids} self.create_controllers(self.args.tsc) if self.args.tsc == 'dqn' and self.args.tsc == 'test': self.load_model() self.v_start_times = {} self.v_travel_times = {} self.episode_performance = [] self.set_item_path()
def server_connect(self): sumoBinary = checkBinary(self.sumo_cmd) port = self.args.port+self.idx sumo_process = subprocess.Popen([sumoBinary, "-c", self.cfg_fp, "--remote-port", str(port), "--no-warnings", "--no-step-log", "--random"], stdout=None, stderr=None) return traci.connect(port), sumo_process
def start_sumo(binary): ''' Instantiates a SUMO simulation instance and return a connection object. Args: binary: path to the SUMO binary file (path to "sumo" or "sumo-gui") ''' port = sumolib.miscutils.getFreeSocketPort() # start the simulation and pipe its outputs into /dev/null sumoProc = subprocess.Popen([binary] + sumo_cmd + ['--remote-port', str(port)], stdout=open(os.devnull, 'w'), stderr=open(os.devnull, 'w')) return traci.connect(port)
def open(self): command = [] command.append(checkBinary(self.sumo_binary)) command.append("--net-file") command.append(self.sumo_net_file) command.append("--additional-files") command.append(self.sumo_additional_files) command.append("--remote-port") command.append(str(self.port)) command.append("--tripinfo-output") command.append(self.network_path + "/out_tripinfo.xml") command.append("--queue-output") command.append(self.network_path + "/out_queue.xml") command.append("--quit-on-end") command.append("--start") command.append("--step-method.ballistic") # command.append("--game") command.append("--summary-output") command.append(self.network_path + "/out_summary.xml") # command.append("--emission-output") # command.append(self.network_path + "/out_emission.xml") # command.append("--duration-log.statistics") # command.append("--full-output") # command.append(self.network_path + "/out_full.xml") # command.append("--osg-view") if self.sumo_binary == ConnectionManager.SUMO_BINARY_GUI : command.append("--gui-settings-file") command.append(self.sumo_gui_settings_file) command.append("--window-size") command.append("1000,700") command.append("--window-pos") if self.index < 2 : command.append(str(0 + self.index * 800) + ",0") else : command.append(str(0 + self.index * 200) + ",500") self.sp_popen = subprocess.Popen(command) time.sleep(.15) self.traci_connection = traci.connect(self.port) print("".join(elt+" " for elt in command)) print(self.network_path + " connection established.")
def start_sumo(binary=sumo_binary): ''' Instantiates a SUMO simulation instance and return a connection object. Args: binary: path to the SUMO binary file (path to df = pd.DataFrame(columns=["Waiting Time", "Emissions"]) df["Waiting Time"] = waiting_a df["Emissions"] = emission_a"sumo" or "sumo-gui") ''' port = sumolib.miscutils.getFreeSocketPort() # start the simulation and pipe its outputs into /dev/null sumoProc = subprocess.Popen([binary] + sumo_cmd + ['--remote-port', str(port)], stdout=open(os.devnull, 'w'), stderr=open(os.devnull, 'w')) return traci.connect(port)
def gen_sim(self, nogui, sim_len): if nogui is False: sumoBinary = checkBinary('sumo-gui') else: sumoBinary = checkBinary('sumo') ###start thread with sumo sim self.sumo_process = subprocess.Popen([ sumoBinary, "-c", self.cfg_fp, "--remote-port", str(self.port), "--no-warnings", "--no-step-log", "--random" ], stdout=None, stderr=None) ###connect to sumo sim through specific port self.conn = traci.connect(self.port) self.sim_len = sim_len self.t = 0
def start_sumo(self): """ Starts a sumo instance using the configuration files created by the generator class. Also initializes a traci connection to interface with sumo from Python. """ logging.info(" Starting SUMO on port " + str(self.port)) logging.debug(" Cfg file " + str(self.scenario.cfg)) logging.debug(" Emission file: " + str(self.emission_out)) logging.debug(" Time step: " + str(self.time_step)) # Opening the I/O thread to SUMO cfg_file = self.scenario.cfg # if "mode" in self.env_params and self.env_params["mode"] == "ec2": # cfg_file = "/root/code/rllab/" + cfg_file sumo_call = [ self.sumo_binary, "-c", cfg_file, "--remote-port", str(self.port), "--step-length", str(self.time_step) ] logging.info("Traci on port: ", self.port) if self.emission_out: sumo_call.append("--emission-output") sumo_call.append(self.emission_out) subprocess.Popen(sumo_call, stdout=sys.stdout, stderr=sys.stderr) logging.debug(" Initializing TraCI on port " + str(self.port) + "!") # wait a small period of time for the subprocess to activate before # trying to connect with traci time.sleep(0.02) self.traci_connection = traci.connect(self.port, numRetries=100) self.traci_connection.simulationStep()
import sys import shutil import struct import random sys.path.append(os.path.join( os.path.dirname(sys.argv[0]), "..", "..", "..", "..", "..", "tools")) import traci import sumolib sumoBinary = sumolib.checkBinary('sumo') PORTS = [ sumolib.miscutils.getFreeSocketPort(), sumolib.miscutils.getFreeSocketPort()] sumoProcess = [subprocess.Popen( "%s -c sumo.sumocfg --remote-port %s" % (sumoBinary, p), shell=True, stdout=sys.stdout) for p in PORTS] conns = [traci.connect(p) for p in PORTS] for c in conns: for step in range(3): print("step", step) c.simulationStep() for c in conns: print("routes", c.route.getIDList()) print("route count", c.route.getIDCount()) routeID = "horizontal" print("examining", routeID) print("edges", c.route.getEdges(routeID)) c.route.subscribe(routeID) for c in conns: print(c.route.getSubscriptionResults(routeID)) for step in range(3, 6): print("step", step)
def start_simulation(self, ): # pylint: disable=maybe-no-member # find SUMO sumo_binary = checkBinary( 'sumo-gui') if self.sim_params.gui else checkBinary('sumo') # create the command line call sumo_call = [sumo_binary] + sumo_cmd_line(self.sim_params, self) # start the process self.sumo_proc = subprocess.Popen( sumo_call, stdout=subprocess.DEVNULL, ) # stderr=subprocess.STDOUT) # sleep before trying to connect with TRACI time.sleep(1) # connect to traci traci_c = traci.connect(port=self.sim_params.port, numRetries=100) traci_c.setOrder(0) traci_c.simulationStep() # set the traffic lights to the default behaviour and run for warm up period for tl_id in self.sim_params.tl_ids: traci_c.trafficlight.setProgram(tl_id, f'{tl_id}-1') # run for an hour to warm up the simulation for _ in range( int(self.sim_params.warmup_time * 1 / self.sim_step_size)): traci_c.simulationStep() # subscribe to all the vehicles in the network at this state for veh_id in traci_c.vehicle.getIDList(): traci_c.vehicle.subscribe(veh_id, VEHICLE_SUBSCRIPTIONS) # get the light states # for tl_id in self.sim_params.tl_ids: # self._initial_tl_colors[tl_id] = traci_c.trafficlight.getRedYellowGreenState(tl_id) # set the traffic lights to the all green program if not self.sim_params.no_actor: for tl_id in self.sim_params.tl_ids: traci_c.trafficlight.setProgram(tl_id, f'{tl_id}-2') # overwrite the default traffic light states to what they where for tl_id in self.sim_params.tl_ids: traci_c.trafficlight.setPhase(tl_id, 0) # saving the beginning state of the simulation traci_c.simulation.saveState(self.state_file) traci_c.simulation.subscribe([tc.VAR_COLLIDING_VEHICLES_NUMBER]) self.add_traci_call([ [ traci_c.lane.getAllSubscriptionResults, (), tc.VAR_COLLIDING_VEHICLES_NUMBER ], ]) self.sim_time = 0 return traci_c
def start_simulation(self, scenario, sim_params): """Start a sumo simulation instance. This method uses the configuration files created by the scenario class to initialize a sumo instance. Also initializes a traci connection to interface with sumo from Python. """ error = None for _ in range(RETRIES_ON_ERROR): try: # port number the sumo instance will be run on port = sim_params.port sumo_binary = "sumo-gui" if sim_params.render is True \ else "sumo" # command used to start sumo sumo_call = [ sumo_binary, "-c", scenario.cfg, "--remote-port", str(sim_params.port), "--num-clients", str(sim_params.num_clients), ] logging.info(" Starting SUMO on port " + str(port)) logging.debug(" Cfg file: " + str(scenario.cfg)) if sim_params.num_clients > 1: logging.info(" Num clients are" + str(sim_params.num_clients)) logging.debug(" Step length: " + str(sim_params.sim_step)) if sim_params.render: # Opening the I/O thread to SUMO self.sumo_proc = subprocess.Popen(sumo_call, preexec_fn=os.setsid) # wait a small period of time for the subprocess to # activate before trying to connect with traci if os.environ.get("TEST_FLAG", 0): time.sleep(0.1) else: time.sleep(config.SUMO_SLEEP) traci_connection = traci.connect(port, numRetries=100) traci_connection.setOrder(0) traci_connection.simulationStep() else: # Use libsumo to create a simulation instance. libsumo.start(sumo_call[1:3]) libsumo.simulationStep() # libsumo will act as the kernel API traci_connection = libsumo return traci_connection except Exception as e: print("Error during start: {}".format(traceback.format_exc())) error = e self.teardown_sumo() raise error
def start_sumo(self): """Start a sumo instance. Uses the configuration files created by the generator class to initialize a sumo instance. Also initializes a traci connection to interface with sumo from Python. """ error = None for _ in range(RETRIES_ON_ERROR): try: # port number the sumo instance will be run on if self.sumo_params.port is not None: port = self.sumo_params.port else: # Don't do backoff when testing if os.environ.get("TEST_FLAG", 0): # backoff to decrease likelihood of race condition time_stamp = ''.join(str(time.time()).split('.')) # 1.0 for consistency w/ above time.sleep(1.0 * int(time_stamp[-6:]) / 1e6) port = sumolib.miscutils.getFreeSocketPort() sumo_binary = "sumo-gui" if self.sumo_params.render else "sumo" # command used to start sumo sumo_call = [ sumo_binary, "-c", self.scenario.cfg, "--remote-port", str(port), "--step-length", str(self.sim_step) ] #add a check for collisions in junctions sumo_call.append("--collision.check-junctions") sumo_call.append("true") #take the cars out of the simulation when a collision happens sumo_call.append("--collision.action") sumo_call.append("remove") #start the simulation automatically sumo_call.append("--start") #close SUMO on the end of the simulation sumo_call.append("--quit-on-end") # add step logs (if requested) if self.sumo_params.no_step_log: sumo_call.append("--no-step-log") # add the lateral resolution of the sublanes (if requested) if self.sumo_params.lateral_resolution is not None: sumo_call.append("--lateral-resolution") sumo_call.append(str(self.sumo_params.lateral_resolution)) # add the emission path to the sumo command (if requested) if self.sumo_params.emission_path is not None: ensure_dir(self.sumo_params.emission_path) emission_out = \ self.sumo_params.emission_path + \ "{0}-emission.xml".format(self.scenario.name) sumo_call.append("--emission-output") sumo_call.append(emission_out) else: emission_out = None if self.sumo_params.overtake_right: sumo_call.append("--lanechange.overtake-right") sumo_call.append("true") if self.sumo_params.ballistic: sumo_call.append("--step-method.ballistic") sumo_call.append("true") # specify a simulation seed (if requested) if self.sumo_params.seed is not None: sumo_call.append("--seed") sumo_call.append(str(self.sumo_params.seed)) if not self.sumo_params.print_warnings: sumo_call.append("--no-warnings") sumo_call.append("true") # set the time it takes for a gridlock teleport to occur sumo_call.append("--time-to-teleport") sumo_call.append(str(int(self.sumo_params.teleport_time))) logging.info(" Starting SUMO on port " + str(port)) logging.debug(" Cfg file: " + str(self.scenario.cfg)) logging.debug(" Emission file: " + str(emission_out)) logging.debug(" Step length: " + str(self.sim_step)) # Opening the I/O thread to SUMO self.sumo_proc = subprocess.Popen(sumo_call, preexec_fn=os.setsid) # wait a small period of time for the subprocess to activate # before trying to connect with traci if os.environ.get("TEST_FLAG", 0): time.sleep(0.1) else: time.sleep(config.SUMO_SLEEP) self.traci_connection = traci.connect(port, numRetries=100) self.traci_connection.simulationStep() return except Exception as e: print("Error during start: {}".format(traceback.format_exc())) error = e self.teardown_sumo() raise error
def execute_scenario(launch,scenario,routes,step_size,port,autostart,end,delay,debug,seed,objectives=[],wait=True): dprint("[ launching simulation on port "+ str(port) + "... ]") sumoAutoStart = "" if autostart == True: sumoAutoStart = " --start" sumoRandom = "" if seed=="-1": sumoRandom = " --random" else: sumoRandom = " --seed " +str(seed) tripsID = str(random.randint(1111111,9999999)) additional_launch_params = list(set([ aps if "%" not in aps else aps%tripsID for o in objectives if o in additional_parameters.keys() for aps in additional_parameters[o] ])) print("\"%s\""%str(" ".join(additional_launch_params))) sumoLaunch = str(launch +" -n " + scenario +".net.xml" +" -r " + (".rou.xml,".join(routes) if type(routes)==list else routes)+".rou.xml" + sumoAutoStart + sumoRandom + " -Q" + " --step-length " + ("%.2f" % step_size) + " --remote-port " + str(port) + (" " if len(additional_launch_params)>0 else "") + " ".join(additional_launch_params) #TODO PSEUDO-RANDOM SEED (seed parameter) ).split(" ") print("Launching \"%s\""%" ".join(sumoLaunch)) if (debug): sumoProcess = subprocess32.Popen(sumoLaunch) else: sumoProcess = subprocess32.Popen(sumoLaunch, stdout=FNULL, stderr=FNULL) while (hang==1): pass time.sleep(2) t = traci.connect(port=port) if wait==True: #Original single simulation code accidents = 0 arrived = 0 teleported = 0 avg_speeds = [] sum_fuel_consumption = [] stepsLeft = end while(stepsLeft>=0): stepsLeft-=1 t.simulationStep() if delay > 0: time.sleep(delay) if len(objectives)>0: if "accidents" in objectives: accidents += t.simulation.getCollidingVehiclesNumber() if "arrived" in objectives: arrived += t.simulation.getArrivedNumber() if "teleported" in objectives: teleported += t.simulation.getStartingTeleportNumber() if "fuel" in objectives or "avg_speed" in objectives: vehicleIDs = t.vehicle.getIDList() if len(vehicleIDs)>0: if "avg_speed" in objectives: avg_speeds.append(np.mean([t.vehicle.getSpeed(veh) for veh in vehicleIDs])) if "fuel" in objectives: sum_fuel_consumption.append(np.sum([t.vehicle.getFuelConsumption(veh) for veh in vehicleIDs])) if len(objectives)>0: dprint("[ sim results: accidents %d, arrived %d, teleported %d, avg speed %f ]"%(accidents,arrived,teleported,np.mean(avg_speeds))) else: dprint("[ simulation completed with no data collection ]") t.close() sumoProcess.wait() dprint("[ simulation return code: " + str(sumoProcess.returncode)+ " ]") return({ "accidents":accidents, "arrived":arrived, "teleported":teleported, "avg_speed":np.mean(avg_speeds), "sum_fuel_consumption":np.sum(sum_fuel_consumption) }) else: dprint("[ simulation launched and running ]") return {"process":sumoProcess,"traci":t,"tripsID":tripsID}
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', '..', '..', '..')) sys.path.append(os.path.join(SUMO_HOME, 'tools')) import traci import sumolib # noqa sumoBinary = sumolib.checkBinary('sumo') conns = [] sumoProcess = [] for i in range(2): p = sumolib.miscutils.getFreeSocketPort() sumoProcess = subprocess.Popen( [sumoBinary, "-c", "sumo.sumocfg", "--remote-port", str(p)], stdout=sys.stdout) conns.append(traci.connect(p, proc=sumoProcess)) for c in conns: for step in range(3): print("step", step) c.simulationStep() for c in conns: print("routes", c.route.getIDList()) print("route count", c.route.getIDCount()) routeID = "horizontal" print("examining", routeID) print("edges", c.route.getEdges(routeID)) c.route.subscribe(routeID) for c in conns: print(c.route.getSubscriptionResults(routeID)) for step in range(3, 6): print("step", step)
def __init__(self, port, registry): super(Master, self).__init__() self.connection = traci.connect(port=port) self.registry = registry self.detector = adasco.detector.ExactDetector(self.connection)
def start_simulation(self, network, sim_params): """Start a sumo simulation instance. This method uses the configuration files created by the network class to initialize a sumo instance. Also initializes a traci connection to interface with sumo from Python. """ error = None for _ in range(RETRIES_ON_ERROR): try: # port number the sumo instance will be run on port = sim_params.port sumo_binary = "sumo-gui" if sim_params.render is True \ else "sumo" # command used to start sumo sumo_call = [ sumo_binary, "-c", network.cfg, "--remote-port", str(sim_params.port), "--num-clients", str(sim_params.num_clients), "--step-length", str(sim_params.sim_step) ] # add step logs (if requested) if sim_params.no_step_log: sumo_call.append("--no-step-log") # add the lateral resolution of the sublanes (if requested) if sim_params.lateral_resolution is not None: sumo_call.append("--lateral-resolution") sumo_call.append(str(sim_params.lateral_resolution)) # add the emission path to the sumo command (if requested) if sim_params.emission_path is not None: ensure_dir(sim_params.emission_path) emission_out = os.path.join( sim_params.emission_path, "{0}-emission.xml".format(network.name)) sumo_call.append("--emission-output") sumo_call.append(emission_out) else: emission_out = None if sim_params.overtake_right: sumo_call.append("--lanechange.overtake-right") sumo_call.append("true") # specify a simulation seed (if requested) if sim_params.seed is not None: sumo_call.append("--seed") sumo_call.append(str(sim_params.seed)) if not sim_params.print_warnings: sumo_call.append("--no-warnings") sumo_call.append("true") # set the time it takes for a gridlock teleport to occur sumo_call.append("--time-to-teleport") sumo_call.append(str(int(sim_params.teleport_time))) # check collisions at intersections sumo_call.append("--collision.check-junctions") sumo_call.append("true") logging.info(" Starting SUMO on port " + str(port)) logging.debug(" Cfg file: " + str(network.cfg)) if sim_params.num_clients > 1: logging.info(" Num clients are" + str(sim_params.num_clients)) logging.debug(" Emission file: " + str(emission_out)) logging.debug(" Step length: " + str(sim_params.sim_step)) # Opening the I/O thread to SUMO self.sumo_proc = subprocess.Popen(sumo_call, preexec_fn=os.setsid) # wait a small period of time for the subprocess to activate # before trying to connect with traci if os.environ.get("TEST_FLAG", 0): time.sleep(0.1) else: time.sleep(config.SUMO_SLEEP) traci_connection = traci.connect(port, numRetries=100) traci_connection.setOrder(0) traci_connection.simulationStep() return traci_connection except Exception as e: print("Error during start: {}".format(traceback.format_exc())) error = e self.teardown_sumo() raise error
import subprocess import sys SUMO_HOME = os.environ.get('SUMO_HOME', os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', '..', '..', '..')) sys.path.append(os.path.join(SUMO_HOME, 'tools')) import traci import sumolib sumoBinary = sumolib.checkBinary('sumo') conns = [] sumoProcess = [] for i in range(2): p = sumolib.miscutils.getFreeSocketPort() sumoProcess = subprocess.Popen([sumoBinary, "-c", "sumo.sumocfg", "--remote-port", str(p)], stdout=sys.stdout) conns.append(traci.connect(p, proc=sumoProcess)) for c in conns: for step in range(3): print("step", step) c.simulationStep() for c in conns: print("routes", c.route.getIDList()) print("route count", c.route.getIDCount()) routeID = "horizontal" print("examining", routeID) print("edges", c.route.getEdges(routeID)) c.route.subscribe(routeID) for c in conns: print(c.route.getSubscriptionResults(routeID)) for step in range(3, 6): print("step", step)