def main(): sumoCmd = [sumoBinary, "-c", sumoConfig] traci.start(sumoCmd) # 开始仿真 simulationSteps = 0 Phaseflag = 0 while simulationSteps < 1000: # 仿真1000个步长 traci.simulationStep() # 执行一步仿真 # 获取仿真环境中当前仿真步的实时信息 print('红绿灯路口西侧排队车辆数目:', traci.lanearea.getJamLengthVehicle('W')) print('红绿灯路口西侧排队长度:', traci.lanearea.getJamLengthMeters('W')) print('红绿灯路口东侧排队车辆数目:', traci.lanearea.getJamLengthVehicle('E')) print('红绿灯路口东侧排队长度:', traci.lanearea.getJamLengthMeters('E')) print('红绿灯路口北侧排队车辆数目:', traci.lanearea.getJamLengthVehicle('N')) print('红绿灯路口北侧排队长度:', traci.lanearea.getJamLengthMeters('N')) print('红绿灯路口南侧排队车辆数目:', traci.lanearea.getJamLengthVehicle('S')) print('红绿灯路口南侧排队长度:', traci.lanearea.getJamLengthMeters('S')) # 红绿灯控制程序 # 所控红绿灯的相位顺序为:东西直行南北禁行(30秒),南北直行东西禁行(30秒) if simulationSteps % 30 == 0: if Phaseflag % 2 == 0: traci.trafficlight.setPhase('3', 0) # 改变红绿灯的相位为东西直行南北禁行 else: traci.trafficlight.setPhase('3', 1) # 改变红绿灯的相位为南北直行东西禁行 Phaseflag += 1 simulationSteps += 1 traci.close() # 结束仿真
def startTraci(self): if self.config.sumo_home is not None: os.environ["SUMO_HOME"] = self.config.sumo_home if "-gui" in self.config.sumoCmd[0]: self.gui=True else: self.gui=False traci.start(self.config.sumoCmd)
def start(self, cmd): traci.start(cmd, port=int(self.port), label=self.label) # time.sleep(5) # print(cmd + ['--remote-port', self.port]) # sumoProcess = Popen(cmd + ['--remote-port', self.port], # env=envs, stdout=PIPE, stderr=PIPE) time.sleep(3) print("SUMO PROCESS RAISED!") # traci.init(port=int(self.port), label=self.label) # step = 1 self.tls = [TrafficLight(t) for t in trafficlights.getIDList()]
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()))
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 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 except traciControl.FatalTraCIError: print("Closed by SUMO") break traci.close() sys.stdout.flush() return timeline
def run_cml(self, cml): cmllist = cml.split(' ') print 'SumoTraci.run_cml', cmllist traci.start(cmllist) self.simtime = self.simtime_start self.duration = 1.0+self.simtime_end-self.simtime_start self.get_attrsman().status.set('running') print ' traci started', self.get_attrsman().status.get() simobjects = [] for simobj in self.parent.simulation.get_simobjects(): # print ' prepare_sim',demandobj.ident simobjects += simobj.prepare_sim(self) #simobjects = self._prtservice.prepare_sim(self) self.simobjects = [] for time_sample, simfunc in simobjects: self.simobjects.append([0, time_sample, simfunc]) # print ' simobjects=',self.simobjects return True
def run_cml(self, cml): cmllist = cml.split(' ') # cmllist.append('--start') print 'run_cml', cmllist traci.start(cmllist) self.simtime = self.simtime_start self.duration = 1.0+self.simtime_end-self.simtime_start self.get_attrsman().status.set('running') # print 'run_cml cml=',cml # print ' pid = ',self.pid # if not self.is_run_background: # self._subprocess.wait() # # if self._subprocess.returncode == 0: # attrsman.status.set('success') # return True # # else: # attrsman.status.set('error') # return False print ' traci started', self.get_attrsman().status.get() return True
def run(self, episode, epsilon, is_gui=False): """ Runs an episode of simulation, then starts a training session """ start_time = timeit.default_timer() # first, generate the route file for this simulation and set up sumo self._TrafficGen.generate_routefile(seed=episode) sumo_args = self._sumo_cmd.copy() if is_gui and 'gui' not in sumo_args[0]: sumo_args[0] += '-gui' traci.start(sumo_args) print("Simulating...") # inits self._step = 0 self._waiting_times = {} self._sum_neg_reward = 0 self._sum_queue_length = 0 self._sum_waiting_time = 0 old_total_wait = 0 old_state = -1 old_action = -1 while self._step < self._max_steps: # get current state of the intersection current_state = self._get_state() # calculate reward of previous action: (change in cumulative waiting time between actions) # waiting time = seconds waited by a car since the spawn in the environment, cumulated for every car in incoming lanes current_total_wait = self._collect_waiting_times() reward = old_total_wait - current_total_wait # saving the data into the memory if self._step != 0: self._Memory.add_sample( (old_state, old_action, reward, current_state)) # choose the light phase to activate, based on the current state of the intersection action = self._choose_action(current_state, epsilon) # if the chosen phase is different from the last phase, activate the yellow phase if self._step != 0 and old_action != action: self._set_yellow_phase(old_action) self._simulate(self._yellow_duration) # execute the phase selected before self._set_green_phase(action) self._simulate(self._green_duration) # saving variables for later & accumulate reward old_state = current_state old_action = action old_total_wait = current_total_wait # saving only the meaningful reward to better see if the agent is behaving correctly if reward < 0: self._sum_neg_reward += reward self._save_episode_stats() print("Total reward:", self._sum_neg_reward, "- Epsilon:", round(epsilon, 2)) traci.close() simulation_time = round(timeit.default_timer() - start_time, 1) print("Training...") start_time = timeit.default_timer() for _ in range(self._training_epochs): self._replay() training_time = round(timeit.default_timer() - start_time, 1) return simulation_time, training_time
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
def serverless_connect(self): traci.start([ self.sumo_cmd, "-c", self.cfg_fp, "--no-step-log", "--no-warnings", "--random" ])
def get_options(): optParser = optparse.OptionParser() optParser.add_option("--nogui", action="store_true", default=False, help="run the commandline version of sumo") options, args = optParser.parse_args() return options # this is the main entry point of this script if __name__ == "__main__": options = get_options() # this script has been called from the command line. It will start sumo as a # server, then connect and run if options.nogui: sumoBinary = checkBinary('sumo') else: sumoBinary = checkBinary('sumo-gui') # 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", "secondTry.sumocfg", "--tripinfo-output", "tripinfo.xml" ]) run()
def get_options(): optParser = optparse.OptionParser() optParser.add_option("--nogui", action="store_true", default=False, help="run the commandline version of sumo") options, args = optParser.parse_args() return options # this is the main entry point of this script if __name__ == "__main__": options = get_options() # this script has been called from the command line. It will start sumo as a # server, then connect and run if options.nogui: sumoBinary = checkBinary('sumo') else: sumoBinary = checkBinary('sumo-gui') # first, generate the route file for this simulation 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", "map1.sumocfg", "--tripinfo-output", "tripinfo.xml" ]) run()
step = 0 waiting_time = 0 reward1 = 0 reward2 = 0 #reward3 related to fuel consumption total_reward = reward1 - reward2 stepz = 0 action = 0 # overall fuel consumption fuel_consumptions = 0 # overall vehicles num_vehicles = 0 traci.start([sumoBinary, "-c", "cross3ltl.sumocfg", '--start']) traci.trafficlight.setPhase("0", 0) traci.trafficlight.setPhaseDuration("0", 200) memory = agent.init_memory() print('length_memory', len(memory)) total_time = 7000 pbar = tqdm(total=total_time) while traci.simulation.getMinExpectedNumber( ) > 0 and stepz < total_time: traci.simulationStep() stepz += 1 # print('current_time', traci.simulation.getCurrentTime() / 1000) state = sumoInt.getState()
def __init__(self, sumoBinary, name="MultiAgent1.0", ambulance_goal_distance=500, rel_amb_y_min=-41, rel_amb_y_max=16): self.end_q_tables_list = [] # New in 1.43 self.aggregation_method = Config.AGGREGATION_METHOD # New in 1.43 # "AVG" or "MAX" ONLY. self.name = name # NOT USED EXCEPT FOR DISPLAY PURPOSES self.amb_goal_dist = ambulance_goal_distance self.reward = 0.0 self.emer_start_lane = None self.emer_car_len = 2.0 self.agent_car_len = 2.0 self.rel_amb_y_min = rel_amb_y_min self.rel_amb_y_max = rel_amb_y_max self.agents = [] # Stays as is in multiagent self.emer = None # Stays as is in multiagent self.hidden_state = None self.observed_state = None self.full_state = None self.Actions = ["change_left", "change_right", "acc", "no_acc", "dec"] self.action_to_string_dict = { "change_left": 0, "change_right": 1, "acc": 2, "no_acc": 3, "dec": 4 } # Must maintain order in Actions self.count_emergency_vehicles = 0 # Temporary assigned variable, reassigned in .reset()->recount_vehicles() to avoid calling a non-initialized vehicle self.count_ego_vehicles = 0 # Temporary assigned variable, reassigned in .reset()->recount_vehicles() to avoid calling a non-initialized vehicle # vehicles_data # dict with: key = lane number, value = number of cars in lane self.max_possible_cars = None # Maximum possible number of cars in lane give starting position self.optimal_time = 0 # Temporary assigned variable, reassigned in .reset() to avoid calling a non-initialized vehicle self.max_steps = 10000 # Temporary assigned variable, reassigned in .reset() to avoid calling a non-initialized vehicle # ---------------------------------------------------------------------------- # # 2 : R A N D O M L Y I N I T I A L I Z E X M L s # and consequently vehicles data # ---------------------------------------------------------------------------- # self.templates_reset() # ---------------------------------------------------------------------------- # # 3 : I N I T I A T E S U M O E N V I R O N M E N T # and vehicles list # ---------------------------------------------------------------------------- # traci.start([ sumoBinary, "-c", Sumocfg_DIR, "--tripinfo-output", "tripinfo.xml", "--seed", str(Sumo_random_seed) ]) # SUMO starts self.vehicle_params = dict() self.vehicle_params['Actions'] = self.Actions self.vehicle_params[ 'action_to_string_dict'] = self.action_to_string_dict self.vehicle_params['rel_amb_y_min'] = self.rel_amb_y_min self.vehicle_params['rel_amb_y_max'] = self.rel_amb_y_max self.vehicles_list = [ Vehicle("LH", vehicle_params=self.vehicle_params, control_algorithm_name="SUMO_KRAUSS") ] # NOTE: No error will be produced if some cars are not in this list. # An error will be produced only when in a not-present ID is requested # Create the real global vehicles list (temporary/fake: initialized one in Config.py with ambulance only): agent_list_index = 0 for lane, num_cars in vehicles_data.items(): for agent_index in range(num_cars): # set control_type according to chosen percentage: if random.uniform(0, 1) < percent_rl: # Then, choose RL ALgorithm control_type = "Q_LEARNING_SINGLE_AGENT" # possible values: ["Q_LEARNING_SINGLE_AGENT", "SUMO_KRAUSS"] else: # Then, choose the SUMO Algorithm control_type = "SUMO_KRAUSS" # possible values: ["Q_LEARNING_SINGLE_AGENT", "SUMO_KRAUSS"] # The plus one is because the ambulance always comes first in the vehicles list self.vehicles_list.append( Vehicle(ID=env.create_vehicle_id(lane, agent_index), vehicle_params=self.vehicle_params, control_algorithm_name=control_type)) agent_list_index += 1 for vehc in self.vehicles_list: # vehicles initialized vehc.initialize() self.list_of_vehicles = copy.copy( self.vehicles_list ) # Note: to copy the list, keeping reference to the original vehicles (as opposed to deepcopy, which would copy vehicles) self.recount_vehicles()
tlsState = data[2] else: print 'Invalid tlsState value received' else: print 'Not response from server' print 'Closing connection with server at %s' % date sock.close() return tlsState if __name__ == "__main__": options = OptionParser() options.add_option("-r", "--run", help="run id", dest="run", default=1) (opt, arg) = options.parse_args() outputFile = "Sybil_3_A_1/tripInfo" + str(opt.run) + ".xml" logFile = "Sybil_3_A_1/log" + str(opt.run) + ".xml" print 'Sybil IS IN THE HOUSE' seed = random.randint(1000, 10000) # Starting Traci traci.start([ 'sumo-gui', "-c", "montreal3_A_1.sumo.cfg", "-a", "montreal.additional.xml", "--step-length", "0.1" ]) # to generate the tripInfo files in Sybil scenario for run number in the option for 3 junctions #traci.start(['sumo', "-c", "montreal3_A_1.sumo.cfg", "--step-length", "0.1", "--seed", str(seed), "--tripinfo-output", outputFile, '--duration-log.statistics', 'True', '--collision.action', 'warn', '--log', logFile]) run()
sys.stdout.flush() def get_options(): optParser = optparse.OptionParser() optParser.add_option("--nogui", action="store_true", default=False, help="run the commandline version of sumo") options, args = optParser.parse_args() return options if __name__ == "__main__": options = get_options() # this script has been called from the command line. It will start sumo as a # server, then connect and run if options.nogui: sumoBinary = checkBinary('sumo') else: sumoBinary = checkBinary('sumo') # 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", "Chula_SSS_BTS_MC/bts_added.sumocfg", "--tripinfo-output", "tripinfo.xml" ]) run()
#for SUMO 0.30.0 traci.start([ sumoBinary, '-c', CONFIG_FILE, '-a', '{},{}'.format(EDITED_FILE, DETECTOR_FILE), ## '-a', '{}'.format(EDITED_FILE), '--no-internal-links', 'true', '--time-to-teleport', '-1', '--ignore-junction-blocker', '-1', '--random', 'false', '--seed', '20', '--start', 'true', #'--quit-on-end','true', '--no-warnings', 'true', '--step-length', '1', '--gui-settings-file', VIEW_FILE, '--time-to-impatience', '300', ]) print("i ran start")
sys.stdout.flush() def get_options(): optParser = optparse.OptionParser() optParser.add_option("--nogui", action="store_true", default=False, help="run the commandline version of sumo") options, args = optParser.parse_args() return options # this is the main entry point of this script if __name__ == "__main__": options = get_options() # this script has been called from the command line. It will start sumo as a # server, then connect and run if options.nogui: sumoBinary = checkBinary('sumo') else: sumoBinary = checkBinary('sumo-gui') # 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", sumocfg]) #################### SET THE RIGHT FILE run()
def SimInitializer(trafic, episode): error=False try: timestep=1 trafic.number_episodes=2000 feature_number=4 trafic.training=True sample_generation=False trafic.TLS_virt_vehicle = True # Red and Yellow traffic lights are considered as preceding vehicles with v=0 trafic.TLS_ID = '0' trafic.evaluation=False trafic.vehicle2_exist = False # currently no meaningful trajectory / route - keep on False trafic.vehicle3_exist = True trafic.vehicle3_vprofile = 'sinus' # 'sinus', 'emergstop' liveplot = False # memory leak problem on windows when turned on trafic.Route_Ego = ['startedge', 'gneE01', 'gneE02', 'stopedge'] trafic.ego_depart_speed = np.ones((trafic.number_episodes,))*0. # specific depart speed for ego vehicle when not training trafic.Route_Traffic1 = ['gneE01', 'junction_out'] # for vehicle2 trafic.Route_Traffic2 = ['gneE01', 'gneE02', 'stopedge'] # for vehicle3 trafic.state_empty=np.zeros([feature_number,1]) timestep=2 np.random.seed(42+episode) SUMO2 = SUMO(trafic.Route_Ego, trafic.Route_Traffic1, trafic.Route_Traffic2, timestep=0.2) ## create velocity profile of preceding vehicle ## """Hier werden bei 'training = True' unterschiedliche Geschwindigkeitsprofile für das vorausfahrende Fahrzeug definiert. Für 'training = False' wird ein festes sinusförmiges Profil mit Mittelwert 30 km/h und Amplitude +- 25 km/h definiert.""" if trafic.vehicle3_exist: if trafic.vehicle3_vprofile == 'sinus': if trafic.training: # create random sinusodial velocity profiles for training SUMO2.prec_train_amplitude = np.random.rand(trafic.number_episodes) * 20/3.6 SUMO2.prec_train_mean = np.random.rand(trafic.number_episodes) * 20/3.6 + 10/3.6 else: SUMO2.prec_train_amplitude = 25/3.6 # a=25/3.6 SUMO2.prec_train_mean = 30/3.6 # c=30/3.6 SUMO2.create_v_profile_prec(a=SUMO.prec_train_amplitude, c=SUMO.prec_train_mean) elif vehicle3_vprofile == 'emergstop': SUMO2.create_v_profile_emerg_stop() else: raise NameError('No valid velocity profile selected') trafic.vehicle_ego = Vehicle(ego=True, ID='ego', RouteID='RouteID_ego', Route=trafic.Route_Ego, powertrain_concept='ICEV') trafic.dynamics_ego = Longitudinal_dynamics(tau=0.5) if trafic.vehicle2_exist: trafic.vehicle_2 = Vehicle(ego=False, ID='traffic.0', RouteID='traci_route_traffic.0', Route=trafic.Route_Traffic1) if trafic.vehicle3_exist: trafic.vehicle_3 = Vehicle(ego=False, ID='traffic.1', RouteID='traci_route_traffic.1', Route=trafic.Route_Traffic2) acc_controller = {} timestep=3 # if trafic.training and liveplot: # fig_running, ax_running_1, ax_running_2, ax_running_3, ax_running_4 = plot_running_init(training) process_param= multiprocessing.Process() # print(process_param.name) traci.start(['sumo', '-c', 'SUMO_config.sumocfg', '--no-warnings'], label=str(process_param.name))#, label=sim) simulation=traci.getConnection(process_param.name) simulation.route.add(trafic.vehicle_ego.RouteID, trafic.vehicle_ego.Route) if trafic.vehicle2_exist: simulation.route.add(trafic.vehicle_2.RouteID, trafic.vehicle_2.Route) if trafic.vehicle3_exist: simulation.route.add(trafic.vehicle_3.RouteID, trafic.vehicle_3.Route) simulation.vehicletype.setSpeedFactor(typeID='traffic_vehicle', factor=5.0) length_episode = np.zeros((trafic.number_episodes, 1)) restart_step = 0 # counter for calculating the reset timing when the simulation time gets close to 24 days evaluation = False if trafic.training: trafic.vehicle_ego.depart_speed = np.random.randint(0, 30, size=trafic.number_episodes) else: trafic.vehicle_ego.depart_speed = ego_depart_speed simulation.trafficlight.setProgram(tlsID='junction1', programID=trafic.TLS_ID) timestep=4+episode if not trafic.training: simulation.trafficlight.setPhase('junction1', 0) if trafic.training and not trafic.evaluation and trafic.vehicle3_exist: trafic.vehicle3 = np.random.choice([True, False], p=[0.95, 0.05]) simulation.lane.setMaxSpeed('gneE01_0', np.random.choice([8.33, 13.89, 19.44, 25.])) simulation.lane.setMaxSpeed('gneE02_0', np.random.choice([8.33, 13.89, 19.44, 25.])) simulation.lane.setMaxSpeed('startedge_0', np.random.choice([8.33, 13.89, 19.44, 25.])) SUMO2.create_v_profile_prec(a=SUMO2.prec_train_amplitude[episode-1], c=SUMO2.prec_train_mean[episode-1]) else: trafic.vehicle3 = vehicle3_exist simulation.lane.setMaxSpeed('startedge_0', 13.89) # 13.89 simulation.lane.setMaxSpeed('gneE01_0', 19.44) # 19.44 simulation.lane.setMaxSpeed('gneE02_0', 13.89) # 13.89 simulation.lane.setMaxSpeed('stopedge_0', 8.33) # 8.33 trafic.episoden_variante=np.random.rand()*240. return process_param.name, SUMO2, error except Exception as ex: template = "An exception of type {0} occurred. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) error=True try: traci.close() except: pass
else: generate_route_file_dmaking(route_file_path, n_scenario) # this is the normal way of using traci. sumo is started as a # # subprocess and then the python script connects and runs if rospy.has_param('~sumo_config_file_name'): sumo_config_file_name = rospy.get_param('~sumo_config_file_name') else: rospy.loginfo("SUMO Interface -- Using default sumo config file") sumo_config_file_name = "network.sumocfg" sumo_config_file_path = ros_pack.get_path( 'hybrid_simulation') + "/sumo_files/" + sumo_config_file_name traci.start([ sumoBinary, "-c", sumo_config_file_path, "--collision.action", "none" ], label="sim_sumo") traci.simulation.subscribe() traci_controller.setting.step = 0 # we start with phase 2 where EW has green # traci.trafficlight.setPhase("911", 2) global ego_vehicle ego_vehicle = None rospy.Timer(rospy.Duration.from_sec(0.05), publish_tf_timer_callback) rospy.Timer(rospy.Duration.from_sec(0.05), run) rospy.loginfo("SUMO Interface -- Starting spinner")
# sim step traci.simulationStep() # sleep enough to make sim step take 1 second (real-time) dt = (time.time() - t0) # time.sleep(max(sim_step- dt, 0)) traci.close() sys.stdout.flush() if __name__ == "__main__": if GUI: sumoBinary = checkBinary('sumo-gui') else: sumoBinary = checkBinary('sumo') traci.start([sumoBinary] + COMMAND_LINE_LIST) run(detector_ids=DETECTOR_IDS, sim_step=SIM_STEP, sim_length=SIM_LENGTH, traffic_light_id=TRAFFIC_LIGHT_ID, lane_num=GATE_LANE_NUM, control_edge=CONTROL_EDGE, automated_gate_edge=AUTOMATED_GATE_EDGE, automated_tl_id=AUTOMATED_TL_ID, acceptable_ids=ACCEPTABLE_IDS, rejected_edge=EXIT_EDGE)
def main(): # read inputs ap = initOptions() options = ap.parse_args() res_all = {} if options.sumo == 'sumo': SUMO = checkBinary('sumo') else: SUMO = checkBinary('sumo-gui') # start traci if options.sumocfg: run_traci = [ SUMO, "-c", options.sumocfg, '--tripinfo-output.write-unfinished', '--routing-algorithm', options.routing_algorithm ] else: run_traci = [ SUMO, '--net-file', '%s' % options.network, '-r', '%s,%s' % (options.reservations, options.taxis), '-l', 'log.txt', '--device.taxi.dispatch-algorithm', 'traci', '--tripinfo-output', '%s' % options.output, '--tripinfo-output.write-unfinished', '--routing-algorithm', options.routing_algorithm, '--stop-output', 'stops_%s' % options.output ] if options.gui_settings: run_traci.extend(['-g', '%s' % options.gui_settings]) if options.dua_times: if options.verbose: print('Calculate travel time between edges with duarouter') if not options.reservations: sys.exit( "please specify the reservation file with the option '--reservations'" ) # noqa if not options.network: sys.exit( "please specify the sumo network file with the option '--network'" ) # noqa pairs_dua_times = find_dua_times(options) else: pairs_dua_times = {} traci.start(run_traci) # execute the TraCI control loop step = traci.simulation.getTime() + 10 veh_type = None rerouting = True while rerouting: traci.simulationStep(step) # TODO ticket #8385 if not traci.vehicle.getTaxiFleet(-1) and step < options.end_time: step += options.sim_step continue # get vType and its parameters for route calculation if not veh_type: fleet = traci.vehicle.getTaxiFleet(-1) veh_type = traci.vehicle.getTypeID(fleet[0]) veh_time_pickup = float( traci.vehicle.getParameter(fleet[0], 'device.taxi.pickUpDuration')) veh_time_dropoff = float( traci.vehicle.getParameter(fleet[0], 'device.taxi.dropOffDuration')) # get new reservations res_id_new = [] for res in traci.person.getTaxiReservations(1): # search direct travel time direct = pairs_dua_times.get("%s_%s" % (res.fromEdge, res.toEdge)) if direct is None: direct = int( findRoute( res.fromEdge, res.toEdge, veh_type, res.depart, routingMode=options.routing_mode).travelTime) # noqa # add new reservation attributes setattr(res, 'direct', direct) # direct travel time setattr(res, 'vehicle', False) # id of assigned vehicle setattr(res, 'delay', 0) # real pick up time - assigned time # read extra attributes person_id = res.persons[0] pickup_earliest = traci.person.getParameter( person_id, "pickup_earliest") if pickup_earliest: pickup_earliest = float(pickup_earliest) dropoff_latest = traci.person.getParameter(person_id, "dropoff_latest") if dropoff_latest: dropoff_latest = float(dropoff_latest) max_waiting = traci.person.getParameter(person_id, "max_waiting") if max_waiting: max_waiting = float(max_waiting) # calculates time windows if not max_waiting: # take global value max_waiting = options.max_wait if pickup_earliest and dropoff_latest: # set latest pickup based on waiting time or latest drop off pickup_latest = min(pickup_earliest + max_waiting, dropoff_latest - direct) # if drop off time given, set time window based on waiting time dropoff_earliest = max(pickup_earliest + direct, dropoff_latest - max_waiting) elif dropoff_latest: # if latest drop off given, calculate pickup window based # on max. travel time with drf if res.direct * options.drf < options.drf_min: pickup_earliest = max(res.depart, dropoff_latest - options.drf_min) else: pickup_earliest = max( res.depart, dropoff_latest - direct * options.drf) pickup_latest = max(pickup_earliest, dropoff_latest - direct) dropoff_earliest = max(pickup_earliest + direct, dropoff_latest - max_waiting) else: if not pickup_earliest: # if no time was given pickup_earliest = res.depart # set earliest drop off based on pickup and max. travel time dropoff_earliest = pickup_earliest + direct # check if min travel time or drf must be applied if res.direct * options.drf < options.drf_min: dropoff_latest = pickup_earliest + direct + options.drf_min else: dropoff_latest = pickup_earliest + direct * options.drf # set latest pickup based on waiting time pickup_latest = min(dropoff_latest - direct, pickup_earliest + max_waiting) # add time window attributes setattr(res, 'tw_pickup', [pickup_earliest, pickup_latest]) setattr(res, 'tw_dropoff', [dropoff_earliest, dropoff_latest]) # time out for request processing if options.max_processing: setattr(res, 'max_processing', step + options.max_processing * options.sim_step) else: setattr(res, 'max_processing', pickup_latest + options.sim_step) # add reservation id to new reservations res_id_new.append(res.id) # add reservation object to list res_all[res.id] = res # find unassigned reservations and # remove reservations which have exceeded the processing time res_id_unassigned = [] res_id_proc_exceeded = [] for res_key, res_values in res_all.items(): if not res_values.vehicle: if step >= res_values.max_processing: res_id_proc_exceeded.append(res_key) print( "\nProcessing time for reservation %s -person %s- was exceeded. Reservation can not be served" % (res_key, res_values.persons)) # noqa for person in res_values.persons: traci.person.removeStages(person) else: res_id_unassigned.append(res_key) # remove reservations [res_all.pop(key) for key in res_id_proc_exceeded] # if reservations pending if res_id_unassigned: if options.verbose: print('\nRun dispatcher') if res_id_new: print('New reservations:', sorted(res_id_new)) print('Pending reservations:', sorted(set(res_id_unassigned) - set(res_id_new))) # get fleet fleet = traci.vehicle.getTaxiFleet(-1) if set(fleet) != set(fleet) & set( traci.vehicle.getIDList()): # TODO manage teleports # noqa print("\nVehicle %s is being teleported, skip to next step" % (set(fleet) - set(traci.vehicle.getIDList()))) step += options.sim_step continue # if a vehicle is being teleported skip to next step # find vehicle in same edge, avoid calculating same routes twice veh_edges = {} for veh_id in fleet: if traci.vehicle.getRoadID(veh_id).startswith(':'): # avoid routing error when in intersection TODO #5829 edge_index = traci.vehicle.getRouteIndex(veh_id) + 1 veh_edge = traci.vehicle.getRoute(veh_id)[edge_index] else: veh_edge = traci.vehicle.getRoadID(veh_id) if veh_edges.get(veh_edge) is not None: veh_edges[veh_edge].append(veh_id) else: veh_edges[veh_edge] = [veh_id] # remove reservations already served res_id_current = [ res.id for res in traci.person.getTaxiReservations(0) ] # noqa res_id_served = list(set(res_all.keys()) - set(res_id_current)) [res_all.pop(key) for key in res_id_served] # reservations already picked up res_id_picked = [ res.id for res in traci.person.getTaxiReservations(8) ] # noqa # call DARP solver to find the best routes if options.verbose: print('Solve DARP with %s' % options.darp_solver) darp_solution = darpSolvers.main(options, step, fleet, veh_type, veh_time_pickup, veh_time_dropoff, res_all, res_id_new, res_id_unassigned, res_id_picked, veh_edges, pairs_dua_times) routes, ilp_res_cons, exact_sol = darp_solution if len(routes) == 0: step += options.sim_step continue # if no routes found elif ilp_res_cons is None: # if DARP solver found optimal routes, this is, no ILP needed best_routes = list(routes.keys()) else: # if DARP solver not optimized routes, run Integer Linear # Programming with pulp veh_constraints = {} res_constraints = {} costs = {} trips = list(routes.keys()) # trips for parsing ILP solution # add bonus_cost to trip cost (makes trips with more served # reservations cheaper than splitting the reservations to more # vehicles with smaller trips if both strategies would yield # a similar cost) for idx, trip_id in enumerate(trips): # routes[route] = [travel_time, veh_bin, res_bin, value] # TODO specific cost for vehicle can be consider here bonus_cost = (sum(routes[trip_id][2]) + 1) * \ options.cost_per_trip # generate dict with costs costs.update({idx: routes[trip_id][0] + bonus_cost}) # generate dict with vehicle used in the trip veh_constraints.update({idx: routes[trip_id][1]}) # generate dict with served reservations in the trip res_constraints.update({idx: routes[trip_id][2]}) if options.verbose: print('Solve ILP') ilp_result = ilp_solve(options, len(fleet), len(ilp_res_cons), costs, veh_constraints, res_constraints) # parse ILP result best_routes = [ trips[int(route_index)] for route_index in ilp_result ] # assign routes to vehicles for route_id in best_routes: stops = route_id.replace('y', '') stops = stops.replace('z', '') stops = stops.split("_") veh_id = stops[0] # first check if new route is better than the current one current_route = [] if traci.vehicle.getStops(veh_id): for taxi_stop in traci.vehicle.getStops(veh_id): next_act = taxi_stop.actType.split(",")[0].split( " ")[0] if not next_act: # vehicle doesn't have a current route continue next_id = taxi_stop.actType.split(",")[0].split( " ")[-1][1:-1] if next_act == 'pickup' and next_id in res_id_picked: # person already picked up, consider next stop continue elif next_act == 'dropOff' and next_id not in res_all.keys( ): # person already dropped off, consider next stop continue # get reservations served at each stop sub_stops = taxi_stop.actType.split(",") # if more than 1 reservation in stop for sub_stop in sub_stops: current_route.append(sub_stop.split(" ")[2][1:-1]) if current_route == stops[1:]: # route is the same continue elif (set(current_route) == set(stops[1:]) and len(current_route) == len(stops[1:])): # if route serve same reservations and have the same stops # get travel time of current route tt_current_route = step edges = [ taxi_stop.lane.split("_")[0] for taxi_stop in traci.vehicle.getStops(veh_id) ] stop_types = [ taxi_stop.actType for taxi_stop in traci.vehicle.getStops(veh_id) ] # add current edge to list if traci.vehicle.getRoadID(veh_id).startswith(':'): # avoid routing error when in intersection TODO #5829 edge_index = traci.vehicle.getRouteIndex(veh_id) + 1 veh_edge = traci.vehicle.getRoute(veh_id)[edge_index] else: veh_edge = traci.vehicle.getRoadID(veh_id) edges.insert(0, veh_edge) # calculate travel time for idx, edge in enumerate(edges[:-1]): tt_pair = pairs_dua_times.get("%s_%s" % (edge, edges[idx + 1])) if tt_pair is None: tt_pair = int( findRoute(edge, edges[idx + 1], veh_type, step, routingMode=options.routing_mode). travelTime) # noqa if 'pickup' in stop_types[idx]: tt_current_route += tt_pair + veh_time_pickup else: tt_current_route += tt_pair + veh_time_dropoff # get travel time of the new route tt_new_route = routes[route_id][0] if tt_new_route >= tt_current_route: continue # current route better than new found if options.verbose: print('Dispatch:', route_id) traci.vehicle.dispatchTaxi(veh_id, stops[1:]) # assign vehicle to reservations # TODO to avoid major changes in the pick-up time when assigning new passengers, # noqa # tw_pickup should be updated, whit some constant X seconds, e.g. 10 Minutes # noqa for res_id in set(stops[1:]): res = res_all[res_id] res.vehicle = veh_id # TODO ticket #8385 if step > options.end_time: rerouting = False step += options.sim_step if all(exact_sol): print('\nExact solution found.') else: print('\nApproximate solution found.') print('DRT simulation ended') traci.close()
def start_traci_simulation(sumocfg_file: str, sumo_log_file: str, traci_log_file: str): sumoBinary = os.path.join(os.environ['SUMO_HOME'], 'bin', 'sumo-gui') sumoCmd = [sumoBinary, "-c", sumocfg_file, "--log", sumo_log_file] traci.start(sumoCmd, traceFile=traci_log_file)
print("Average Travel Duration: ", df['duration'].mean()) if __name__ == "__main__": random.seed(42) # make tests reproducible sumoBinary = checkBinary('sumo-gui') file = open("log.txt", 'w') sys.stdout = file #genrate route file generate_routefile() #Start Simulation traci.start([ sumoBinary, "-c", "sim.sumocfg", "--tripinfo-output", "simtripinfo.xml", "--device.rerouting.probability", "0.00", "--summary", "summary.xml" ]) #run Route Choice Server run() print("simulation completed successfully!!") #Stop simulation traci.close() sys.stdout.flush() print("simulation completed successfully!!") #Process Data print("Processing Data: ") processData()
print("In ", step, "seconds (", minutes, " minutes)") # TraCI traci.close() sys.stdout.flush() def get_options(): opt_parser = optparse.OptionParser() opt_parser.add_option("--nogui", action="store_true", default=False, help="run the commandline version of sumo") options, args = opt_parser.parse_args() return options if __name__ == "__main__": options = get_options() if options.nogui: sumoBinary = checkBinary("SUMO") else: sumoBinary = checkBinary("sumo-gui") #traci.start([sumoBinary, "-c", "base_case.sumocfg", "--step-length", "0.001", "--tripinfo-output", "tripinfo.xml", "--emission-output","emissionOutput.xml"]) traci.start([ sumoBinary, "-c", "case1.sumocfg", "--tripinfo-output", "tripinfo.xml", "--emission-output", "emissionOutput.xml" ]) run()
def __init__(self, step_length, mode, init_n_ego_dict, training_task='left'): # mode 'display' or 'training' self.random_traffic = None self.sim_time = 0 self.n_ego_vehicles = defaultdict(list) self.step_length = step_length self.step_time_str = str(float(step_length) / 1000) self.collision_flag = False self.n_ego_collision_flag = {} self.collision_ego_id = None self.v_light = None self.n_ego_dict = init_n_ego_dict # dict(DL1=dict(x=1.875, y=-30, v=3, a=90, l=4.8, w=2.2), # UR1=dict(x=-1.875, y=30, v=3, a=-90, l=4.8, w=2.2), # DR1=dict(x=5.625, y=-30, v=3, a=90, l=4.8, w=2.2), # RU1=dict(x=5.625, y=-30, v=3, a=90, l=4.8, w=2.2)) self.mode = mode self.training_light_phase = 0 self.training_task = training_task self.ego_route = TASK2ROUTEID[self.training_task] if training_task == 'right': if random.random() > 0.5: self.training_light_phase = 2 try: traci.start( [ SUMO_BINARY, "-c", SUMOCFG_DIR, "--step-length", self.step_time_str, "--lateral-resolution", "3.5", "--random", # "--start", # "--quit-on-end", "--no-warnings", "--no-step-log", # '--seed', str(int(seed)) ], numRetries=5) # '--seed', str(int(seed)) except FatalTraCIError: print('Retry by other port') port = sumolib.miscutils.getFreeSocketPort() traci.start( [ SUMO_BINARY, "-c", SUMOCFG_DIR, "--step-length", self.step_time_str, "--lateral-resolution", "3.5", "--random", # "--start", # "--quit-on-end", "--no-warnings", "--no-step-log", # '--seed', str(int(seed)) ], port=port, numRetries=5) # '--seed', str(int(seed)) traci.vehicle.subscribeContext( 'collector', traci.constants.CMD_GET_VEHICLE_VARIABLE, 999999, [ traci.constants.VAR_POSITION, traci.constants.VAR_LENGTH, traci.constants.VAR_WIDTH, traci.constants.VAR_ANGLE, traci.constants.VAR_SIGNALS, traci.constants.VAR_SPEED, # traci.constants.VAR_TYPE, # traci.constants.VAR_EMERGENCY_DECEL, # traci.constants.VAR_LANE_INDEX, # traci.constants.VAR_LANEPOSITION, traci.constants.VAR_EDGES, # traci.constants.VAR_ROUTE_INDEX ], 0, 2147483647) while traci.simulation.getTime() < 100: if traci.simulation.getTime() < 80: traci.trafficlight.setPhase('0', 2) else: traci.trafficlight.setPhase('0', 0) # if self.mode == "training": # traci.trafficlight.setPhase('0', self.training_light_phase) traci.simulationStep()
if __name__ == "__main__": options = get_options() # server, then connect and run if options.nogui: sumoBinary = checkBinary('sumo') else: sumoBinary = checkBinary('sumo-gui') accum=[];produc=[];outfl=[]; #for j in range(1,10): Accumulation = [] Production = []; Outflow = []; for i in range(1,6): ChangeDemandRandom0() traci.start([sumoBinary, "-c", "MFDGrid.sumocfg"]) a,b,c = run() Accumulation.append(a) Production.append(b) Outflow.append(c) Accumulation = np.array(Accumulation) Accumulation = Accumulation.reshape(i*12,order='c') Production = np.array(Production) Production = Production.reshape(i*12,order='c') Outflow = np.array(Outflow) Outflow = Outflow.reshape(i*12,order='c') accum = Accumulation produc = Production outfl = Outflow Accumulation = []
def runSingle(traciEndTime, viewRange, module, objID): seen1 = 0 seen2 = 0 step = 0 traci.start(sumoCall + ["-c", "sumo.sumocfg"]) traci.poi.add("poi", 400, 500, (1, 0, 0, 0)) traci.polygon.add("poly", ((400, 400), (450, 400), (450, 400)), (1, 0, 0, 0)) subscribed = False while not step > traciEndTime: responses = traci.simulationStep() near1 = set() if objID in module.getContextSubscriptionResults(): for v in module.getContextSubscriptionResults()[objID]: near1.add(v) vehs = traci.vehicle.getIDList() pos = {} for v in vehs: pos[v] = traci.vehicle.getPosition(v) shape = None egoPos = None if hasattr(module, "getPosition"): egoPos = module.getPosition(objID) elif hasattr(module, "getShape"): shape = module.getShape(objID) elif module == traci.edge: # it's a hack, I know, but do we really need to introduce # edge.getShape? shape = traci.lane.getShape(objID + "_0") near2 = set() for v in pos: if egoPos: if math.sqrt(dist2(egoPos, pos[v])) < viewRange: near2.add(v) if shape: lastP = shape[0] for p in shape[1:]: if math.sqrt(distToSegmentSquared(pos[v], lastP, p)) < viewRange: near2.add(v) lastP = p if not subscribed: module.subscribeContext(objID, traci.constants.CMD_GET_VEHICLE_VARIABLE, viewRange, [traci.constants.VAR_POSITION]) subscribed = True else: seen1 += len(near1) seen2 += len(near2) for v in near1: if v not in near2: print("timestep %s: %s is missing in subscribed vehicles" % (step, v)) for v in near2: if v not in near1: print( "timestep %s: %s is missing in surrounding vehicles" % (step, v)) step += 1 module.unsubscribeContext(objID, traci.constants.CMD_GET_VEHICLE_VARIABLE, viewRange) responses = traci.simulationStep() if responses: print("Error: Unsubscribe did not work") else: print("Ok: Unsubscribe successful") print("Print ended at step %s" % (traci.simulation.getCurrentTime() / DELTA_T)) traci.close() sys.stdout.flush() print("uncheck: seen %s vehicles via subscription, %s in surrounding" % (seen1, seen2)) if seen1 == seen2: print("Ok: Subscription and computed are same") else: print("Error: subscribed number and computed number differ")
options, args = optParser.parse_args() return options # this is the main entry point of this script if __name__ == "__main__": options = get_options() # this script has been called from the command line. It will start sumo as a # server, then connect and run if options.nogui: sumoBinary = checkBinary('sumo') else: sumoBinary = checkBinary('sumo-gui') # 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, "-n", "input_net.net.xml", "-r", "input_routes.rou.xml", "-a", "input_additional.add.xml", "--fcd-output", "fcd.xml", "--no-step-log", "true"]) # Wait until the vehicle enters while not ToC_vehicle in traci.vehicle.getIDList(): traci.simulationStep() printToCParams(ToC_vehicle) run() traci.close() sys.stdout.flush()
step += 1 traci.close() sys.stdout.flush() def get_options(): optParser = optparse.OptionParser() optParser.add_option("--nogui", action="store_true", default=False, help="run the commandline version of sumo") options, args = optParser.parse_args() return options # this is the main entry point of this script if __name__ == "__main__": options = get_options() # this script has been called from the command line. It will start sumo as a # server, then connect and run if options.nogui: sumoBinary = checkBinary("sumo") else: sumoBinary = checkBinary("sumo-gui") # first, generate the route file for this simulation 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", "--tripinfo-output", "tripinfo.xml"]) run()
sys.stdout.flush() def get_options(): optParser = optparse.OptionParser() optParser.add_option("--nogui", action="store_true", default=False, help="run the commandline version of sumo") options, args = optParser.parse_args() return options # this is the main entry point of this script if __name__ == "__main__": options = get_options() # this script has been called from the command line. It will start sumo as a # server, then connect and run if options.nogui: sumoBinary = checkBinary('sumo') else: sumoBinary = checkBinary('sumo-gui') # first, generate the route file for this simulation 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", "--tripinfo-output", "tripinfo.xml"]) run()
def get_options(): opt_parse = optparse.OptionParser() opt_parse.add_option("--nogui", action="store_true", default=False, help="run the commandline version of sumo") options, args = opt_parse.parse_args() return options def run(): l = traci.getIDList() print(l) if __name__ == "__main__": options = get_options() #check binary if options.nogui: sumoBinary = checkBinary("sumo") else: sumoBinary = checkBinary("sumo-gui") traci.start([ sumoBinary, "-c", "hello.sumo.cfg", "--tripinfo-output", "tripinfo.xml" ]) run()
def get_options(): optParser = optparse.OptionParser() optParser.add_option("--nogui", action="store_true", default=False, help="run the commandline version of sumo") options, args = optParser.parse_args() return options # this is the main entry point of this script if __name__ == "__main__": options = get_options() # this script has been called from the command line. It will start sumo as a # server, then connect and run if options.nogui: sumoBinary = checkBinary('sumo') else: sumoBinary = checkBinary('sumo-gui') #sumoBinary = checkBinary('sumo') # 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", "network/testmap.sumocfg", "--tripinfo-output", "tripinfo.xml", "--xml-validation", "never", "--verbose", "True"])#specify your own files here run()
def __init__(self, net_file, route_file, out_csv_path=None, out_csv_name=None, use_gui=False, num_seconds=20000, max_depart_delay=100000, time_to_load_vehicles=0, delta_time=4, single_agent=False): self._net = net_file self._route = route_file self.use_gui = use_gui if self.use_gui: self._sumo_binary = sumolib.checkBinary('sumo-gui') else: self._sumo_binary = sumolib.checkBinary('sumo') traci.start([sumolib.checkBinary('sumo'), '-n', self._net]) # start only to retrieve information self.single_agent = single_agent self.ts_ids = traci.trafficlight.getIDList() self.lanes_per_ts = len( set(traci.trafficlight.getControlledLanes(self.ts_ids[0]))) self.traffic_signals = dict() self.vehicles = dict() self.last_measure = dict( ) # used to reward function remember last measure self.last_reward = {i: 0 for i in self.ts_ids} self.sim_max_time = num_seconds self.time_to_load_vehicles = time_to_load_vehicles # number of simulation seconds ran in reset() before learning starts self.delta_time = delta_time # seconds on sumo at each step self.max_depart_delay = max_depart_delay # Max wait time to insert a vehicle self.yellow_time = 2 # addition self.passed_num_of_veh_in_ts = dict() self.pass_veh_between_intersection_start = dict() self.pass_veh_between_intersection_end = [] self.wait_veh = dict() self.last_step_waiting_time = 0 input = [{ 'gneE1_0': 'gneE11_0' }, { '-gneE9_0': 'gneE3_0' }, { 'gneE1_0': 'gneE10_0' }, { '-gneE9_0': 'gneE2_0' }] # manually self.in_lane = [] self.out_lane = [] for index in input: for key, value in index.items(): if key not in self.in_lane: self.in_lane.append(key) if value not in self.out_lane: self.out_lane.append(value) """ Default observation space is a vector R^(#greenPhases + 1 + 2 * #lanes) s = [current phase one-hot encoded, elapsedTime / maxGreenTime, density for each lane, queue for each lane] You can change this by modifing self.observation_space and the method _compute_observations() Action space is which green phase is going to be open for the next delta_time seconds """ # self.observation_space = spaces.Box(low=np.zeros(self.num_green_phases + 1 + 2*self.lanes_per_ts), high=np.ones(self.num_green_phases + 1 + 2*self.lanes_per_ts)) # self.action_space = spaces.Discrete(2) self.reward_range = (-float('inf'), float('inf')) self.metadata = {} self.spec = '' self.run = 0 self.metrics = [] self.out_csv_name = out_csv_name self.out_csv_path = out_csv_path traci.close()
u'fringeFactor': 2 }, u'taxi': { u'count': 2, u'fringeFactor': 2 } } } edges = net.readNet(config.road_map_file_path).getEdges() for vehicle, options in data["vehicles"].items(): route_file_name = '{}/{}.rou.xml'.format(config.base_dir, vehicle) trips_file_name = '{}/{}.trips.xml'.format(config.base_dir, vehicle) try: options = parse_trip_opts(config.road_map_file_path, float(config.end)) except ZeroDivisionError: continue randomTrips.main(randomTrips.get_options(options)) # start sumo as a sub process traci.start([ checkBinary('sumo') if main_options.nogui else checkBinary('sumo-gui'), "-c", "{}/map.sumo.cfg".format(config.base_dir), "-a", "{}/newTLS.add.xml".format(config.base_dir) ]) run()
'-n', 'input_net.net.xml', '-r', 'input_routes.rou.xml', '--lanechange-output', 'lanechanges.xml', '--lanechange-output.started', '--lanechange-output.ended', '--fcd-output', 'fcd.xml', '--no-step-log', '--begin', '0', #~ '--lateral-resolution', '3.2', '--step-length', '0.1', '--default.action-step-length', '1.0', #'-S', '-Q', ] traci.start(cmd) traci.simulationStep() vehID = "v0" traci.vehicle.setLaneChangeMode(vehID, 0b0100000000) traci.vehicle.changeLane(vehID, 1, 0) for i in range(10): step = traci.simulation.getCurrentTime() traci.simulationStep(step + 1000) traci.vehicle.setSpeed(vehID, 0) for i in range(10): step = traci.simulation.getCurrentTime() traci.simulationStep(step + 1000) traci.vehicle.setSpeed(vehID, -1) for i in range(10): step = traci.simulation.getCurrentTime() traci.simulationStep(step + 1000)
# server, then connect and run if options.nogui: sumoBinary = checkBinary('sumo') else: sumoBinary = checkBinary('sumo-gui') net = 'pedcrossing.net.xml' # build the multi-modal network from plain xml inputs subprocess.call([checkBinary('netconvert'), '-c', os.path.join('data', 'pedcrossing.netccfg'), '--output-file', net], stdout=sys.stdout, stderr=sys.stderr) # generate the pedestrians for this simulation randomTrips.main(randomTrips.get_options([ '--net-file', net, '--output-trip-file', 'pedestrians.trip.xml', '--seed', '42', # make runs reproducible '--pedestrians', '--prefix', 'ped', # prevent trips that start and end on the same edge '--min-distance', '1', '--trip-attributes', 'departPos="random" arrivalPos="random"', '--binomial', '4', '--period', '35'])) # this is the normal way of using traci. sumo is started as a # subprocess and then the python script connects and runs traci.start([sumoBinary, '-c', os.path.join('data', 'run.sumocfg')]) run()
find_neighbor_nodes = get_find_neighbor_nodes(edges, connections) generateRoute = get_generateRoute(sumo_graph) if __name__ == '__main__': nodes, ways = parser( '/home/sheng/git/Ambulance-Routing/net_files/ncku.osm') osm_graph = convert2graph(nodes, ways) # source = "307351699" # target = "165031123" source = random.choice(list(osm_graph)) target = random.choice(list(osm_graph)) sumo_graph, edges, connections, tls = get_sumo_info( '/home/sheng/git/Ambulance-Routing/net_files/ncku.net.xml', osm_graph) find_neighbor_nodes = get_find_neighbor_nodes(edges, connections) generateRoute = get_generateRoute(sumo_graph) route = generateRoute(source, target) # print("The route is :", route) routes = [route] traci.start([ '/home/sheng/git/sumo/bin/sumo', '-c', '/home/sheng/git/Ambulance-Routing/net_files/run.sumo.cfg' ]) rl_env = env(osm_graph, routes, tls) s = rl_env.reset() n_s, r, d = rl_env.step(1) print("s :", s) print("n_s :", n_s) print("r :", r) print("d :", d) traci.close()
def ramp_control(flag, q_table): #信号灯ID tlsID = {'A': '30885212', 'B': '5535842383', 'D': '1877642863'} #信号灯ID Num = {'A': 4, 'B': 2, 'D': 2} #车道数 mNum = {'A': 4, 'B': 3, 'D': 3} #主线车道数 interval = 20 #每20秒更新计算1次 Ramp = ['A'] #作为共同的索引 space = {'A': 110, 'B': 140, 'D': 65} #匝道下游主路检测器,用于获取占有率,流量 detector_down = { 'A': ["812 SB_0", "812 SB_1", "812 SB_2", "812 SB_3", "812 SB_4"], 'B': ["820AN SB_0", "820AN SB_1", "820AN SB_2"], 'D': ['208-SB_0', "208-SB_1", "208-SB_2"] } #匝道上游主路检测器,用于获取占有率,流量 detector_up = {'A': ["813 SB_0", "813 SB_1", "813 SB_2"]} edgeRamp = { 'A': ['On3', '-160415#0'], 'B': ['-160330', '577463705'], 'D': ['On1', '577723261'] } vehicles = {} #主线各检测器20s经过的车辆ID vehicles0 = {} nrdetector = {} #匝道各检测器20s经过的车辆ID nrdetector0 = {} occupied_duration = {} for key in Ramp: for d in detector_down[key]: occupied_duration[d] = 0 #为所有要用到的检测器创造储存数组 vehicles[d] = [] vehicles0[d] = [] for d in detector_up[key]: occupied_duration[d] = 0 # vehicles[d] = [] vehicles0[d] = [] for j in range(Num[key]): nrdetector[key + '_' + str(j + 1)] = [] nrdetector0[key + '_' + str(j + 1)] = [] Carnum_list = [] CarnumRamp_list = [] q = {'A': [0], 'B': [0], 'D': [0]} # qt = {'A': 0, 'B': 0, 'D': 0} # redtime = {'A': [12], 'B': [12], 'D': [12]} #记录当前计算所得红灯时长 p = {'A': [], 'B': [], 'D': []} #存储信号灯相位 # 开始仿真 traci.start( ['sumo', "-c", "BH4eval.sumocfg", "--output-prefix", str(flag)]) # 道路所有路段id,其实可以通过traci获取 edgeIDs = [ '-160415#0', '-160415#1', '443921506', '444071852', '444071857.6', '444071865', '578076505', '578076510', '583369725', '583369727#1', ':1837357028_0', ':1837537313_0', ':30885211_0', ':30885212_0', ':5540085417_0', ':5540085534_0', ':5576783866_0', ':cluster_1837537309_gneJ1_0', ':cluster_5780610093_gneJ0_gneJ1_0', ':cluster_5780610093_gneJ0_gneJ1_2', ':cluster_gneJ11_gneJ12_0', 'M2.4', 'On3' ] # 开始单步循环仿真 for step in range(0, 18600): #仿真时长 # 每一秒记录所有在路网的车辆数 carnum = np.sum( [traci.edge.getLastStepVehicleNumber(x) for x in edgeIDs]) Carnum_list.append(carnum) # 每一秒记录在匝道的车辆数 CarnumRamp_list.append( traci.edge.getLastStepVehicleNumber(edgeRamp['A'][0]) + traci.edge.getLastStepVehicleNumber(edgeRamp['A'][1])) if step != 0 and step % interval == 0: #第一步是不调节的 for ramp in Ramp: flowr = reduce(lambda x, y: x + y, [ len( set([ vid for vid in nrdetector[d] if vid not in nrdetector0[d] ])) for d in nrdetector.keys() if ramp in d ]) flow_up = reduce(lambda x, y: x + y, [ len( set([ vid for vid in vehicles[d] if vid not in vehicles0[d] ])) for d in vehicles.keys() if d in detector_up[ramp] ]) flow_down = reduce(lambda x, y: x + y, [ len( set([ vid for vid in vehicles[d] if vid not in vehicles0[d] ])) for d in vehicles.keys() if d in detector_down[ramp] ]) o_up = np.mean( reduce(lambda x, y: x + y, [occupied_duration[d] for d in detector_up[ramp] ])) / mNum[ramp] / interval * 100 o_down = np.mean( reduce(lambda x, y: x + y, [occupied_duration[d] for d in detector_down[ramp] ])) / mNum[ramp] / interval * 100 q[ramp].append(qt[ramp]) print(o_down) state = [o_down, flowr, qt[ramp] / space[ramp]] qt[ramp] = 0 redtime1 = qlchoose_action(q_table, state) redtime[ramp].append(redtime1) #print(redtime1) for d in nrdetector.keys(): nrdetector0[d] = nrdetector[d] nrdetector[d] = [] #每20s清空一次通过车辆ID for d in vehicles.keys(): vehicles0[d] = vehicles[d] vehicles[d] = [] #每20s清空一次通过车辆ID for d in occupied_duration.keys(): occupied_duration[d] = 0 traci.simulationStep() for d in occupied_duration.keys(): v_info = traci.inductionloop.getVehicleData(d) for car in v_info: if car[3] != -1.0: occupied_duration[d] += car[3] - car[2] vehicles[d] += traci.inductionloop.getLastStepVehicleIDs(d) for ramp in Ramp: # 每一秒数一下匝道上的车,并取最大值 qt[ramp] = max( qt[ramp], (traci.edge.getLastStepVehicleNumber(edgeRamp[ramp][0]) + traci.edge.getLastStepVehicleNumber(edgeRamp[ramp][1]))) p[ramp].append(traci.trafficlight.getPhase(tlsID[ramp])) #记录信号灯相位 for d in nrdetector.keys(): nrdetector[d] += traci.inductionloop.getLastStepVehicleIDs(d) #第一步的时候不能进行以下计算 if step > 15: #第一个周期无调节 for ramp in Ramp: if p[ramp][step] == 1 and p[ramp][step - 1] == 0: traci.trafficlight.setPhaseDuration( tlsID[ramp], redtime[ramp][-1] - 1) if step > 5400: vehicles3 = traci.edge.getLastStepVehicleIDs('444071865') for v in vehicles3: tau3 = max(random.normalvariate(1.3, 0.2), 0) traci.vehicle.setTau(v, tau3) traci.close() return q['A'], redtime['A'], Carnum_list, CarnumRamp_list
def init_params(self): self.route_manager.init_routes() traci.start(self.sumoCmd) self.deltaT = traci.simulation.getDeltaT()
"""--------------------------------------------------------------------------------------------------""" """--------------------------Simulation of collision ----------------------------------------------- """ """--------------------------------------------------------------------------------------------------""" import traci import traci.constants as tc sumoBinary = "C:/Program Files (x86)/DLR/Sumo/bin/sumo-gui" sumoCmd = [sumoBinary, "-c", "autobahn.sumocfg"] traci.start(sumoCmd, label = "sim3") conn1 = traci.getConnection("sim3") """ -----------------------------------------Simulation Rear Collision-----------------------------------------------------------""" #Information des Ego vehicle veh = "veh0" # Variable to begin step. i = 0 """------------------------------------Add Route dynamicaly-----------------------------------------------------------------------""" traci.route.add("route0", ['Lane1','Lane2','Lane4','Lane5']) """------------------------------------Add Vehicle dynamicaly---------------------------------------------------------------------"""
optParser.add_option("--nogui", action="store_true", default=False, help="run the commandline version of sumo") options, args = optParser.parse_args() return options # this is the main entry point of this script if __name__ == "__main__": # load whether to run with or without GUI options = get_options() # If this script has been called from the command line. It will start sumo as a # server, then connect and run if options.nogui: sumoBinary = checkBinary('sumo') else: sumoBinary = checkBinary('sumo-gui') sumoCmd = [sumoBinary, "-c", "testing/thisisthefile.sumo.cfg"] traci.start(sumoCmd) run()