def main(demo_mode, real_engine, setter=None): # used to randomly color the vehicles random.seed(1) start_sumo("cfg/freeway.sumo.cfg", False) plexe = Plexe() traci.addStepListener(plexe) step = 0 while running(demo_mode, step, 6000): # when reaching 60 seconds, reset the simulation when in demo_mode if demo_mode and step == 6000: start_sumo("cfg/freeway.sumo.cfg", True) step = 0 random.seed(1) traci.simulationStep() if step == 1: add_vehicles(plexe, N_VEHICLES, 150, real_engine) add_vehicle(plexe, "v0", 140, 1, 25, "passenger") add_vehicle(plexe, "v1", 250, 0, 20, "passenger2") traci.gui.trackVehicle("View #0", LEADER) traci.gui.setZoom("View #0", 50000) if real_engine and setter is not None: # if we are running with the dashboard, update its values tracked_id = traci.gui.getTrackedVehicle("View #0") if tracked_id != "": ed = plexe.get_engine_data(tracked_id) vd = plexe.get_vehicle_data(tracked_id) setter(ed[RPM], ed[GEAR], vd.speed, vd.acceleration) step += 1 traci.close()
def main(demo_mode, real_engine, setter=None): # used to randomly color the vehicles random.seed(1) start_sumo("cfg/freeway.sumo.cfg", False) plexe = Plexe() traci.addStepListener(plexe) step = 0 state = GOING_TO_POSITION while running(demo_mode, step, 6000): # when reaching 60 seconds, reset the simulation when in demo_mode if demo_mode and step == 6000: start_sumo("cfg/freeway.sumo.cfg", True) step = 0 state = GOING_TO_POSITION random.seed(1) traci.simulationStep() if step == 0: # create vehicles and track the joiner topology = add_vehicles(plexe, N_VEHICLES, real_engine) traci.gui.trackVehicle("View #0", JOINER) traci.gui.setZoom("View #0", 20000) if step % 10 == 1: # simulate vehicle communication every 100 ms communicate(plexe, topology) if step == 100: # at 1 second, let the joiner get closer to the platoon topology = get_in_position(plexe, JOINER, FRONT_JOIN, topology) if state == GOING_TO_POSITION and step > 0: # when the distance of the joiner is small enough, let the others # open a gap to let the joiner enter the platoon if get_distance(plexe, JOINER, FRONT_JOIN) < JOIN_DISTANCE + 1: state = OPENING_GAP topology = open_gap(plexe, BEHIND_JOIN, JOINER, topology, N_VEHICLES) if state == OPENING_GAP: # when the gap is large enough, complete the maneuver if get_distance(plexe, BEHIND_JOIN, FRONT_JOIN) > \ 2 * JOIN_DISTANCE + 2: state = COMPLETED plexe.set_fixed_lane(JOINER, 0, safe=False) plexe.set_active_controller(JOINER, CACC) plexe.set_path_cacc_parameters(JOINER, distance=DISTANCE) plexe.set_active_controller(BEHIND_JOIN, CACC) plexe.set_path_cacc_parameters(BEHIND_JOIN, distance=DISTANCE) topology = reset_leader(BEHIND_JOIN, topology, N_VEHICLES) if real_engine and setter is not None: # if we are running with the dashboard, update its values tracked_id = traci.gui.getTrackedVehicle("View #0") if tracked_id != "": ed = plexe.get_engine_data(tracked_id) vd = plexe.get_vehicle_data(tracked_id) setter(ed[RPM], ed[GEAR], vd.speed, vd.acceleration) step += 1 traci.close()
def main(demo_mode, real_engine, setter=None): # used to randomly color the vehicles random.seed(1) start_sumo("cfg/freeway.sumo.cfg", False) plexe = Plexe() traci.addStepListener(plexe) step = 0 state = GOING_TO_POSITION while running(demo_mode, step, 6000):
def main(demo_mode, real_engine, setter=None): # used to randomly color the vehicles random.seed(1) start_sumo("cfg/freeway.sumo.cfg", False) step = 0 state = GOING_TO_POSITION while running(demo_mode, step, 6000): # when reaching 60 seconds, reset the simulation when in demo_mode if demo_mode and step == 6000: start_sumo("cfg/freeway.sumo.cfg", True) step = 0 state = GOING_TO_POSITION random.seed(1) traci.simulationStep() if step == 0: # create vehicles and track the joiner topology = add_vehicles(N_VEHICLES, real_engine) traci.gui.trackVehicle("View #0", JOINER) traci.gui.setZoom("View #0", 20000) if step % 10 == 1: # simulate vehicle communication every 100 ms communicate(topology) if step == 100: # at 1 second, let the joiner get closer to the platoon topology = get_in_position(JOINER, FRONT_JOIN, topology) if state == GOING_TO_POSITION: # when the distance of the joiner is small enough, let the others # open a gap to let the joiner enter the platoon if get_distance(JOINER, FRONT_JOIN) < JOIN_DISTANCE + 1: state = OPENING_GAP topology = open_gap(BEHIND_JOIN, JOINER, topology, N_VEHICLES) if state == OPENING_GAP: # when the gap is large enough, complete the maneuver if get_distance(BEHIND_JOIN, FRONT_JOIN) > 2 * JOIN_DISTANCE + 2: state = COMPLETED change_lane(JOINER, 0) set_par(JOINER, cc.PAR_ACTIVE_CONTROLLER, cc.CACC) set_par(JOINER, cc.PAR_CACC_SPACING, DISTANCE) set_par(BEHIND_JOIN, cc.PAR_ACTIVE_CONTROLLER, cc.CACC) set_par(BEHIND_JOIN, cc.PAR_CACC_SPACING, DISTANCE) topology = reset_leader(BEHIND_JOIN, topology, N_VEHICLES) if real_engine and setter is not None: # if we are running with the dashboard, update its values tracked_id = traci.gui.getTrackedVehicle("View #0") if tracked_id != "": (g, rpm) = cc.unpack(get_par(tracked_id, cc.PAR_ENGINE_DATA)) data = get_par(tracked_id, cc.PAR_SPEED_AND_ACCELERATION) (v, a, u, x, y, t) = cc.unpack(data) setter(rpm, g, v, a) step += 1 traci.close()
def run_simulation(api: Dragometer, fileName: str, names: list, gaps: list, has_slipstream_device: list, track: int, use_gui: False): """ :param names: The names of the vehicles, ordered from the first to the last. :param gaps: The initial inter-vehicle gaps. The first is the gap between the first and the second vehicle. :param has_slipstream_device: Whether to equip each vehicles with the slipstream device. """ assert len(names) >= 2 assert len(gaps) == len(names) - 1 assert len(names) == len(has_slipstream_device) if True in has_slipstream_device: assert has_slipstream_device[names.index(track)] start_sumo("cfg/freeway.sumo.cfg", False, use_gui) plexe = Plexe() traci.addStepListener(plexe) outfile = open(fileName, "w") writer = csv.DictWriter(outfile, fieldnames=fieldnames) writer.writeheader() step = 0 while running(False, step, 4000): traci.simulationStep() if step == 0: add_vehicles(plexe, names, gaps, has_slipstream_device) if use_gui: traci.gui.trackVehicle("View #0", 'v0') traci.gui.setZoom("View #0", 100000) else: # The example uses only a vehicle type, called "car" # (see cfg/freeway.rou.xml), which has a drag coefficient of 0.24 cd = 0.24 if True in has_slipstream_device: cd = traci.vehicle.getParameter( track, 'device.slipstream.actualDragCoefficient') charge = traci.vehicle.getParameter( track, 'device.battery.actualBatteryCapacity') if api is not None: if True not in has_slipstream_device: api.plot('1', step, float(cd), subplotIndex=0) api.plot('2', step, float(charge), subplotIndex=0) else: api.plot('1', step, float(cd), subplotIndex=1) api.plot('2', step, float(charge), subplotIndex=1) energy = traci.vehicle.getParameter( track, 'device.battery.energyConsumed') data = plexe.get_vehicle_data(track) radar = plexe.get_radar_data(track) log_data(writer, 1, step, data[ACCELERATION], data[SPEED], radar[RADAR_DISTANCE], cd, charge, energy) step += 1 traci.close()
def main(demo_mode, real_engine, setter=None): start_sumo("cfg/freeway.sumo.cfg", False) plexe = Plexe() traci.addStepListener(plexe) step = 0 state_left = None state_right = None random.seed(1) while running(demo_mode, step, 6000): if demo_mode and step == 6000: start_sumo("cfg/freeway.sumo.cfg", True) step = 0 random.seed(1) traci.simulationStep() if step == 1: add_platooning_vehicle(plexe, "p0", 150, 0, 25, 5, real_engine) add_vehicle(plexe, "v0", 140, 1, 25, "passenger") add_vehicle(plexe, "v1", 250, 0, 20, "passenger2") traci.gui.trackVehicle("View #0", "p0") traci.gui.setZoom("View #0", 50000) plexe.set_active_controller("p0", ACC) plexe.set_cc_desired_speed("p0", 25) traci.vehicle.setSpeedMode("p0", 0) if step > 1: state = traci.vehicle.getLaneChangeState("p0", 1)[0] if state_left != state: state_left = state str_status = get_status(state) print("Step %d, vehicle p0. Lane change status (LEFT ): %s" % (step, str_status)) state = traci.vehicle.getLaneChangeState("p0", -1)[0] if state_right != state: state_right = state str_status = get_status(state) print("Step %d, vehicle p0. Lane change status (RIGHT): %s" % (step, str_status)) if real_engine and setter is not None: # if we are running with the dashboard, update its values tracked_id = traci.gui.getTrackedVehicle("View #0") if tracked_id != "": ed = plexe.get_engine_data(tracked_id) vd = plexe.get_vehicle_data(tracked_id) setter(ed[RPM], ed[GEAR], vd.speed, vd.acceleration) step += 1 traci.close()
def main(demo_mode, real_engine, setter=None): # used to randomly color the vehicles random.seed(1) start_sumo("cfg/intersection/intersection.sumo.cfg", False) plexe = Plexe() traci.addStepListener(plexe) step = 0 topology = dict() min_dist = 1e6 # newly added split feature compared with brakedemo.py split = False
def main(demo_mode, real_engine, setter=None): # used to randomly color the vehicles random.seed(1) start_sumo("cfg/freeway.sumo.cfg", False) plexe = Plexe() traci.addStepListener(plexe) step = 0 topology = dict() min_dist = 1e6 while running(demo_mode, step, 1500): # when reaching 60 seconds, reset the simulation when in demo_mode if demo_mode and step == 1500: print("Min dist: %f" % min_dist) start_sumo("cfg/freeway.sumo.cfg", True) step = 0 random.seed(1) traci.simulationStep() if step == 0: # create vehicles and track the braking vehicle topology = add_vehicles(plexe, 8, 1, real_engine) traci.gui.trackVehicle("View #0", BRAKING_VEHICLE) traci.gui.setZoom("View #0", 20000) if step % 10 == 1: # simulate vehicle communication every 100 ms communicate(plexe, topology) if real_engine and setter is not None: # if we are running with the dashboard, update its values tracked_id = traci.gui.getTrackedVehicle("View #0") if tracked_id != "": ed = plexe.get_engine_data(tracked_id) vd = plexe.get_vehicle_data(tracked_id) setter(ed[RPM], ed[GEAR], vd.speed, vd.acceleration) if step == 500: plexe.set_fixed_acceleration(BRAKING_VEHICLE, True, -6) if step > 1: radar = plexe.get_radar_data("v.0.1") if radar[RADAR_DISTANCE] < min_dist: min_dist = radar[RADAR_DISTANCE] step += 1 traci.close()
def main(demo_mode, real_engine, setter=None): # used to randomly color the vehicles # 具体着色是在 utils module 的 add_platooning_vehicle 函数中实现的 random.seed(1) # 运行 SUMO 的配置文件,后边的参数 False / True 表示 SUMO server 是否已经在运行了。 # 若为 False,则打开 SUMO 并加载配置文件 # 若为 True,则重新加载配置文件 # freeway.sumo.cfg 中仿真步长为 0.01s start_sumo("cfg/freeway.sumo.cfg", False) # 以下设置可以使得每次 traci.simulationStep() 之后都调用一次 plexe plexe = Plexe() traci.addStepListener(plexe) step = 0 topology = dict() min_dist = 1e6
def main(demo_mode, real_engine, setter=None): # used to randomly color the vehicles random.seed(1) gui = True start_sumo("cfg/freeway.sumo.cfg", False, gui=gui) plexe = Plexe() traci.addStepListener(plexe) step = 0 while running(demo_mode, step, 6000): # when reaching 60 seconds, reset the simulation when in demo_mode if demo_mode and step == 6000: start_sumo("cfg/freeway.sumo.cfg", True, gui=gui) step = 0 random.seed(1) traci.simulationStep() if step == 0: # create vehicles and track the joiner add_vehicles(plexe, N_VEHICLES, real_engine) if gui: traci.gui.trackVehicle("View #0", LEADER) traci.gui.setZoom("View #0", 20000) if step >= 1: if step % 10 == 0: time = step / 100.0 speed = SPEED + AMP * math.sin(2 * math.pi * FREQ * time) plexe.set_cc_desired_speed(LEADER, speed) if real_engine and setter is not None: # if we are running with the dashboard, update its values tracked_id = traci.gui.getTrackedVehicle("View #0") if tracked_id != "": ed = plexe.get_engine_data(tracked_id) vd = plexe.get_vehicle_data(tracked_id) setter(ed[RPM], ed[GEAR], vd.speed, vd.acceleration) step += 1 traci.close()
def main(demo_mode, real_engine=True, setter=None): random.seed(1) start_sumo("cfg/freeway.sumo.cfg", False) step = 0 plexe = Plexe() traci.addStepListener(plexe) while running(demo_mode, step, 4000): # when reaching 60 seconds, reset the simulation when in demo_mode if demo_mode and step == 4000: start_sumo("cfg/freeway.sumo.cfg", True) step = 0 random.seed(1) traci.simulationStep() if step == 0: # create vehicles and track one of them add_vehicles(plexe) traci.gui.trackVehicle("View #0", VEHICLES[TRACK]) traci.gui.setZoom("View #0", 20000) if step == 100: # at 1 second let them accelerate as much as they can for vid in VEHICLES: plexe.set_fixed_acceleration(vid, True, 20) # in the dashboard, show the engine information about the vehicle # being tracked tracked_id = traci.gui.getTrackedVehicle("View #0") if setter is not None and tracked_id != "": ed = plexe.get_engine_data(tracked_id) vd = plexe.get_vehicle_data(tracked_id) setter(ed[RPM], ed[GEAR], vd.speed, vd.acceleration) step += 1 traci.close()
def main(demo_mode, real_engine=True, setter=None): random.seed(1) start_sumo("cfg/freeway.sumo.cfg", False) step = 0 while running(demo_mode, step, 4000): # when reaching 60 seconds, reset the simulation when in demo_mode if demo_mode and step == 4000: start_sumo("cfg/freeway.sumo.cfg", True) step = 0 random.seed(1) traci.simulationStep() if step == 0: # create vehicles and track one of them add_vehicles() traci.gui.trackVehicle("View #0", VEHICLES[TRACK]) traci.gui.setZoom("View #0", 20000) if step == 100: # at 1 second let them accelerate as much as they can for vid in VEHICLES: set_par(vid, cc.PAR_FIXED_ACCELERATION, cc.pack(1, 20)) # in the dashboard, show the engine information about the vehicle # being tracked tracked_id = traci.gui.getTrackedVehicle("View #0") if setter is not None and tracked_id != "": (g, rpm) = cc.unpack(get_par(tracked_id, cc.PAR_ENGINE_DATA)) data = get_par(tracked_id, cc.PAR_SPEED_AND_ACCELERATION) (v, a, u, x, y, t) = cc.unpack(data) setter(rpm, g, v, a) step += 1 traci.close()
def main(real_engine, setter=None, demo_mode= False): start_sumo("cfg/freeway.sumo.cfg", False) step = 0 batch_num = 0 veh_of_interest = "v.40" source_edges = ['source0', 'source1', 'source2', 'source3'] edge_filter, vtype_filter = validate_params( edge_filter=PLAT_EDGES, vtype_filter=["vtypeauto"]) pstate = NON while running(demo_mode, step, 4132): if demo_mode and step == 4132: start_sumo("cfg/freeway.sumo.cfg", False) step = 0 flags_at_pois = {} if pstate == NON: lanes = lane_gen() add_vehicles(N_VEHICLES_GEN, batch_num, fromEdge = source_edges[0], platoon_len = 24, real_engine = False) batch_num = batch_num + 3 ### Start from here add_vehicles(N_VEHICLES_GEN, batch_num, fromEdge = source_edges[1], platoon_len = 24, real_engine = False) batch_num = batch_num + 3 add_vehicles(N_VEHICLES_GEN, batch_num, fromEdge = source_edges[2], platoon_len = 24, real_engine = False) batch_num = batch_num + 3 add_vehicles(N_VEHICLES_GEN, batch_num, fromEdge = source_edges[3], platoon_len = 24, real_engine = False) batch_num = batch_num + 3 traci.gui.setZoom("View #0", 4500) # f = open("/Users/mac/src/Simulations/mixedtraffic/gen_times","w") # f.write("simulation step is {}".format(traci.simulation.getCurrentTime())) # f.close() #traci.gui.setZoom("View #1", 4500) topology = {} flags_at_pois = {} teleported_vehicles =[] vstate = IDLE pstate = PLATOONING genStep = step print("Gen Step is : {}".format(genStep)) print("pstate at gen is : {}".format(pstate)) if pstate == PLATOONING and step == genStep + 1: veh_of_interest = traci.lane.getLastStepVehicleIDs('source0_3')[::-1][0] print("veh of interest is: {}".format(veh_of_interest)) if pstate == PLATOONING: traci.simulationStep() if step > genStep + 10 and pstate == PLATOONING: print("veh of int is:{}".format(veh_of_interest)) if veh_of_interest in traci.edge.getLastStepVehicleIDs("p12"): print("veh of interest at set location {}!!!!!!!!!!!".format(traci.vehicle.getLaneID(veh_of_interest))) pstate = NON if step <= genStep + 14: set_lc_mode() print("LC Mode Set to FIX_LC") list_of_leaders =[] for lane in lanes: if traci.lane.getLastStepVehicleIDs(lane)==[]: continue lane_vehicles = traci.lane.getLastStepVehicleIDs(lane)[::-1] teleported_vehicles = traci.simulation.getEndingTeleportIDList() print("end teleported {}".format(teleported_vehicles)) teleported_vehicles = [vehicle for vehicle in teleported_vehicles if vehicle not in removed_vehicles] print("Teleported {}".format(teleported_vehicles)) removed_vehicles = [] for vehicle in teleported_vehicles: try: traci.vehicle.remove(vehicle, REMOVE_PARKING) except: print("vehicle already removed") else: removed_vehicles.append(vehicle) print("vehicle {} has been removed".format(vehicle)) #teleported_vehicles = [vehicle for vehicle in end_teleport_vehicles if vehicle in teleported_vehicles and vehicle not in removed_vehicles] if lane_vehicles != []: planes = sorted_planes(lane_vehicles, lane, removed_vehicles) if planes != []: for plane in planes: topology = plane.topo_contsructor() topology = plane.pla_speed_spacing(topology, states) #print("Topology at platSpeedSpacing is : {}".format(topology)) communicate(topology) set_arrived_free(ARR_EDGES) for plane in planes: #print("states are {}".format(states)) if traci.vehicle.getRouteID(plane.plane_leader()).split("_") == '0': continue if plane.near_flag(): leader = plane.plane_leader() print("Veh {} looking for flag".format(leader)) flag_data = look_for_flags(leader,pois,flags_at_pois, step) if flag_data != None: if flag_data[0] == True and plane.safe_to_cl(): print("Veh {} has found a flag, changing lanes now".format(leader)) plane.move_to_next_best_lane(step) flags_at_pois[leader]['state'].append('completed') flags_at_pois[leader]['poitype'].append(flag_data[1]) elif flag_data[0] == True and plane.safe_to_cl() == False: print(plane.safe_to_cl()) #pdb.set_trace() obstruction = plane.plane_obstructed(states, obstructors) if obstruction == True: plane.obst_overtaken(obstructors, states) planers.remove_obstructors() #pdb.set_trace() traci.simulationStep() print("step is : {}".format(step)) print("Current time is :{}".format(traci.simulation.getCurrentTime())) print("pstate is : {}".format(pstate)) step += 1 traci.close()
def main(real_engine, setter=None, demo_mode=False): global genStep # start_sumo("cfg/freeway.sumo.cfg", False) step = 0 batch_num = 0 source_edges = ['source0', 'source1', 'source2', 'source3'] removed_vehs = [] all_arrives = [] all_arrived = [] edge_filter, vtype_filter = validate_params(edge_filter=PLAT_EDGES, vtype_filter=["vtypeauto"]) pstate = INSERT while running(demo_mode, step, 2200): if demo_mode and step == 2200: start_sumo("cfg/freeway.sumo.cfg", False) step = 0 print("step is : {}".format(step)) print("Current time is :{}".format(traci.simulation.getCurrentTime())) print("pstate is : {}".format(pstate)) if pstate == INSERT: add_vehicles(N_VEHICLES_GEN, batch_num, list_of_leaders, fromEdge=source_edges[0], platoon_len=24, real_engine=False) batch_num = batch_num + 3 add_vehicles(N_VEHICLES_GEN, batch_num, list_of_leaders, fromEdge=source_edges[1], platoon_len=24, real_engine=False) batch_num = batch_num + 3 add_vehicles(N_VEHICLES_GEN, batch_num, list_of_leaders, fromEdge=source_edges[2], platoon_len=24, real_engine=False) batch_num = batch_num + 3 add_vehicles(N_VEHICLES_GEN, batch_num, list_of_leaders, fromEdge=source_edges[3], platoon_len=24, real_engine=False) batch_num = batch_num + 3 traci.gui.setZoom("View #0", 4500) all_arrived = arrived_vehz(all_arrives) all_arrives = all_arrived traci.simulationStep() pstate = PLATOONING genStep = step if pstate == INSERT2: inserted = add_vehiclez(N_VEHICLES_GEN, batch_num, list_of_leaders, priorityswitches, fromEdge=source_edges[0], platoon_len=24, real_engine=False) batch_num = batch_num + inserted inserted = add_vehiclez(N_VEHICLES_GEN, batch_num, list_of_leaders, priorityswitches, fromEdge=source_edges[1], platoon_len=24, real_engine=False) batch_num = batch_num + inserted inserted = add_vehiclez(N_VEHICLES_GEN, batch_num, list_of_leaders, priorityswitches, fromEdge=source_edges[2], platoon_len=24, real_engine=False) batch_num = batch_num + inserted inserted = add_vehiclez(N_VEHICLES_GEN, batch_num, list_of_leaders, priorityswitches, fromEdge=source_edges[3], platoon_len=24, real_engine=False) batch_num = batch_num + inserted traci.gui.setZoom("View #0", 4500) all_arrived = arrived_vehz(all_arrives) all_arrives = all_arrived traci.simulationStep() topology = {} pstate = PLATOONING genStep = step if pstate == PLATOONING and step >= genStep + 110: switches = [] for lane in range(1, 4): upstreamcheck = upstream_check(batch_num, lane, all_arrived) downstreamcheck = downstream_check(batch_num, lane, all_arrived) switches.append(upstreamcheck) switches.append(downstreamcheck) priorityswitches = switching_logic(switches) if 'GREEN' in priorityswitches: pstate = INSERT2 if step > genStep + 1 and pstate == PLATOONING: flag_planes = [] lanes = lane_gen() for lane in lanes: if not traci.lane.getLastStepVehicleIDs(lane): continue lane_vehicles = [ veh for veh in traci.lane.getLastStepVehicleIDs(lane)[::-1] if veh not in removed_vehs ] planes = sorted_planes(lane_vehicles, lane) for plane in planes: if plane.near_flag(): flag_planes.append(plane) teleported_vehicles = traci.simulation.getEndingTeleportIDList( ) for vehicle in teleported_vehicles: try: traci.vehicle.remove(vehicle, REMOVE_PARKING) except: print(f"Veh {vehicle} has been removed already") else: print(f"Veh {vehicle} has been removed") removed_vehs.append(vehicle) topology = plane.topo_contsructor(removed_vehs) topology = plane.pla_speed_spacing(topology) communicate(topology) all_arrived = arrived_vehz(all_arrives) all_arrives = all_arrived for plane in flag_planes: flag_n_poi_index = plane.look_for_flags(pois, step) if flag_n_poi_index[0] == True: plane.move_to_next_best_lane( step, flag_n_poi_index) plane.set_arrived_free() traci.simulationStep() remove_parked(removed_vehs) teleported_vehicles = traci.simulation.getEndingTeleportIDList() for vehicle in teleported_vehicles: try: traci.vehicle.remove(vehicle, REMOVE_PARKING) except: print(f"Veh {vehicle} has been removed already") else: print(f"Veh {vehicle} has been removed") removed_vehs.append(vehicle) step += 1 traci.close()
def main(demo_mode, real_engine, setter=None): # used to randomly color the vehicles random.seed(1) start_sumo("cfg/jiangxinzhou.sumo.cfg", False) plexe = Plexe() traci.addStepListener(plexe) step = 0 redlight_stop = 0 topology_0 = dict() platoons_num = 1 car_num = [26] leader = [0] state_2_flag = [0] redlight_stop = [0] judge_flag = [0] special_stop_flag = [0] color = [(255, 255, 255, 255), (255, 255, 0, 255), (0, 255, 255, 255), (255, 0, 255, 255), (255, 255, 255, 255), (255, 255, 0, 255), (0, 255, 255, 255), (255, 0, 255, 255), (255, 255, 255, 255), (255, 255, 0, 255), (0, 255, 255, 255), (255, 0, 255, 255)] special_judge_flag = [0] while running(demo_mode, step, 500000): # when reaching 60 seconds, reset the simulation when in demo_mode if demo_mode and step == 500000: start_sumo("cfg/jiangxinzhou.sumo.cfg", True) step = 0 random.seed(1) traci.simulationStep() if step == 0: # create vehicles and track the braking vehicle distance_0 = 5 speed_0 = 25 car_num_0 = car_num[0] platoons_num_0 = 1 position_0 = 1000 topology_0 = add_vehicles(plexe, car_num_0, platoons_num_0, "vtypeauto", "platoon_route_0", position_0, speed_0, distance_0, real_engine) traci.gui.trackVehicle("View #0", "v.0.0") # traci.vehicle.highlight("v.0.0", color=(255,255,0,255), size=-1, alphaMax=-1, duration=-1, type=0) # traci.gui.trackVehicle("View #1", "v.0.1") traci.gui.setZoom("View #0", 700) # traci.gui.setOffset("View #0",5078.44,6332.91) # acf = traci.gui.getZoom(viewID='View #0') # print (acf) if step % 10 == 1: # simulate vehicle communication every 100 ms communicate(plexe, topology_0) # print (topology_0) if step > 10: # print(platoons_num) for i in range(platoons_num): # print(i) num_temp = int(leader[i]) leader_id = "v.0.%d" % num_temp # for size_cycle in range (0,100): traci.vehicle.highlight(leader_id, color[i], size=50, alphaMax=-1, duration=-1, type=0) # print (leader_id) nextTLS, current_phase, left_distance, absolute_time = getnext_trafficlightandphace( leader_id) if ((left_distance >= RANGE - 1) and (left_distance < RANGE)): judge_flag[i] = 1 else: judge_flag[i] = 0 if left_distance <= 0.5: state_2_flag[i] = 0 special_stop_flag[i] = 0 # print (left_distance,state_2_flag[i],special_stop_flag[i]) leader_data = plexe.get_vehicle_data(leader_id) if (nextTLS != "none" and judge_flag[i] == 1): time_left = absolute_time - traci.simulation.getTime() pass_num = int( math.floor((leader_data.speed * time_left - RANGE) / (LENGTH + DISTANCE))) state = judge_state(plexe, car_num[i], pass_num) # if i==0: # print (pass_num,state) if ((state == 0 and current_phase == 'g') or (current_phase == 'r')) and special_stop_flag[i] == 0: # plexe.set_cc_desired_speed(leader_id, 0) # plexe.set_active_controller(leader_id, 3) decel = leader_data.speed**2 / (2 * (left_distance - 10)) plexe.set_fixed_acceleration("v.0.%d" % int(leader[i]), True, -decel) redlight_stop[i] = 1 # ALL_PASS = 1 # elif state == 1 and current_phase == 'g': # continue # PART_PASS = 2 elif state == 2 and current_phase == 'g' and state_2_flag[ i] == 0: new_platoon_leader = "v.0.%d" % (int(leader[i]) + pass_num) for j in range((int(leader[i]) + pass_num) + 1, (int(leader[i]) + car_num[i])): # temporarily change the leader topology_0["v.0.%d" % j]["leader"] = new_platoon_leader traci.vehicle.setColor("v.0.%d" % j, color[platoons_num]) # the front vehicle if the vehicle opening the gap is the joiner plexe.set_active_controller(new_platoon_leader, ACC) traci.vehicle.setColor(new_platoon_leader, color[platoons_num]) plexe.set_path_cacc_parameters(new_platoon_leader, distance=100) topology_0[new_platoon_leader] = {} leader.append(int(leader[i]) + pass_num) car_num.append(car_num[i] - pass_num) platoons_num = platoons_num + 1 car_num[i] = pass_num redlight_stop.append(1) state_2_flag[i] = 1 state_2_flag.append(0) judge_flag.append(0) special_judge_flag[i] = 1 special_judge_flag.append(0) # must stop after separated special_stop_flag.append(1) leader_data_temp = plexe.get_vehicle_data( "v.0.%d" % int(leader[platoons_num - 1])) nextTLS, current_phase, left_distance, absolute_time = getnext_trafficlightandphace( "v.0.%d" % int(leader[platoons_num - 1])) decel = leader_data_temp.speed**2 / ( 2 * (left_distance - 10)) plexe.set_fixed_acceleration( "v.0.%d" % int(leader[platoons_num - 1]), True, -decel) # plexe.set_cc_desired_speed("v.0.%d" % int(leader[i+1]), 0) # plexe.set_active_controller("v.0.%d" % int(leader[platoons_num-1]), FAKED_CACC) # traci.gui.trackVehicle("View #0", "v.0.%d" % int(leader[i+1])) # if i>=1: # print(i, leader_id, leader, car_num,special_stop_flag,state_2_flag) # print (redlight_stop,current_phase) if redlight_stop[i] == 1 and current_phase != 'r' and int( leader_data.speed) <= 1: plexe.set_fixed_acceleration(leader_id, False, 0) plexe.set_cc_desired_speed(leader_id, 25) plexe.set_active_controller(leader_id, ACC) plexe.set_path_cacc_parameters(leader_id, distance=DISTANCE) redlight_stop[i] = 0 if real_engine and setter is not None: # if we are running with the dashboard, update its values tracked_id = traci.gui.getTrackedVehicle("View #0") if tracked_id != "": ed = plexe.get_engine_data(tracked_id) vd = plexe.get_vehicle_data(tracked_id) setter(ed[RPM], ed[GEAR], vd.speed, vd.acceleration) step += 1 traci.close()
def main(): sumo_binary = "sumo-gui" if args.gui else "sumo" utils.start_sumo(sumo_binary, args.configuration_file, False) edge_filter, vtype_filter = utils.validate_params(args.edge_filter, args.vtype_filter) step = 0 platoons = [] while utils.running(args.demo, step, args.max_step): traci.simulationStep() vehicles = utils.retrieve_vehicles(edge_filter) cacc_vehicles = utils.filter_cacc_vehicles(vehicles, vtype_filter) simulation_vehicles = traci.vehicle.getIDList() for vehicle in cacc_vehicles: if not platooning.in_platoon(platoons, vehicle): platoons.append( platooning.Platoon([vehicle], desired_gap=args.desired_gap, safe_gap=args.safe_gap)) teleported_vehicles = traci.simulation.getEndingTeleportIDList() for vehicle in teleported_vehicles: for platoon in platoons: if vehicle in platoon: platoon.remove_vehicle(platoon.index_of(vehicle)) break for platoon in platoons: # Remove platoons with vehicles that have left the simulation if not platoon.all_members_are_in(simulation_vehicles): platoons.pop(platoons.index(platoon)) continue platoon.look_for_splits() if platoon.leader_wants_to_leave(edge_filter): platoon.leader_leave() merges, lane_changes = platooning.look_for_merges( platoons, max_distance=args.max_distance, max_platoon_length=args.platoon_length, edge_filter=edge_filter, max_relative_speed=args.relative_speed) new_platoons = [] platoons_to_remove = set() for i in range(len(merges)): if merges[i] != -1: new_platoons.append( platooning.merge_platoons(platoons[i], platoons[merges[i]], lane_changes[i])) platoons_to_remove.add(platoons[i]) platoons_to_remove.add(platoons[merges[i]]) platoons.extend(new_platoons) platoons = [ platoon for platoon in platoons if platoon not in platoons_to_remove ] for platoon in platoons: platoon.update_desired_speed_and_lane() platoon.communicate() platoon.maneuver() step += 1 traci.close()
def main(): seeds = [4, 5, 6, 7, 8, 9, 10, 11] modes = [E_GREEDY, UCB1, BAYES_UCB, THOMPSON_SAMPLING, HEINOVSKI] glossary = [] for seed in seeds: for mode in modes: try: Globals.mode = mode Globals.seed = seed random.seed(seed) sleep(0.5) utils.start_sumo("cfg/freeway.sumo.cfg", False, gui=True) # used to randomly color the vehicles plexe = Plexe() traci.addStepListener(plexe) step = 0 counter = [0, 0, 0, 0, 0, 0] happiness_change_monitor_vehicle = [] happiness_change_monitor_platoon = [] spawn_timer = 40 spawn_threshold = random.randint(200, 300) vehicleInfos = {} platoonUtils.registry(vehicleInfos, plexe) Monitoring.registry(vehicleInfos) createUtils.registry(vehicleInfos) PlatooningAlgorithms.registry(vehicleInfos, plexe) neighbor_table = [[] for i in range(500)] spawning_list = [] spawnable_list = [] # Reset simulation afer 6 Minutes. while step <= 60002: try: traci.simulationStep() except: print(sys.exc_info()[0]) """ ############################################################################ Setup Vehicles ############################################################################ """ all_vehicles = list(traci.vehicle.getIDList()) vehicles = list(all_vehicles) spawn_timer += 1 # Generating cars every second (100 timesteps) if spawn_timer >= spawn_threshold and len( vehicles) < AMOUNT_RANDOM_CARS: spawn_timer = 0 if len(spawnable_list) == 0: car_id = "v.%d" % counter[CAR] counter[CAR] += 1 else: car_id = spawnable_list.pop(0) if len(spawning_list) != 0: spawnable_list.append(spawning_list.pop(0)) # 0 - 3 Start # 4 - 6 1. Entry # 7 - 8 2. Entry # 9 3. Entry spawn_threshold = random.randint(200, 300) if step < 17000: vroute = random.randint(0, 3) elif step < 34000: vroute = random.randint(0, 6) spawn_threshold /= 1.5 elif step < 51000: vroute = random.randint(0, 8) spawn_threshold /= 2 if MODE == START_TO_END_SCENARIO: createUtils.add_vehicle(plexe, car_id, 0, vroute=3) else: createUtils.add_vehicle(plexe, car_id, 0, vroute=vroute) """ ############################################################################ Simulate ############################################################################ """ # for every existing car, do the following actions every 100 ms if hundred_ms_times(2, step): """ ############################################################################ Removing Routine at the End of a Car's Route ############################################################################ """ for car in all_vehicles: if car in vehicleInfos: if plexe.get_distance_to_end( car) < 10 or plexe.get_crashed( car) or 0 < vehicleInfos[ car].get_speed() < 0.5: if vehicleInfos[car].is_in_platoon(): platoonUtils.remove_platoon_member(car) pos_relative = int( vehicleInfos[car]. get_neighbor_table_pos()) if car in neighbor_table[pos_relative]: neighbor_table[pos_relative].remove( car) if plexe.get_crashed( car ) or 0 < vehicleInfos[car].get_speed() < 1: counter[CRASH] += 1 traci.vehicle.remove(car) spawning_list.append(car) vehicleInfos.pop(car) if car not in vehicleInfos: vehicles.remove(car) """ ############################################################################ Update Neighbor Table ############################################################################ """ for car in vehicles: pos_relative = int( math.floor( plexe.get_vehicle_data(car)[POS_X] / RADAR_DISTANCE)) pos_relative_old = int( vehicleInfos[car].get_neighbor_table_pos()) if pos_relative_old is not pos_relative: if car in neighbor_table[pos_relative_old]: neighbor_table[pos_relative_old].remove( car) neighbor_table[pos_relative].append(car) vehicleInfos[car].set_neighbor_table_pos( pos_relative) """ ############################################################################ Update Neighbors ############################################################################ """ for car in vehicles: state = vehicleInfos[car].get_state() position = vehicleInfos[ car].get_neighbor_table_pos() # add all vehicles in the specific neighbor_table area to the neighbors list if position == 0: neighbors = neighbor_table[ position] + neighbor_table[position + 1] else: neighbors = neighbor_table[ position - 1] + neighbor_table[ position] + neighbor_table[position + 1] # The current car is not a neighbor of itself if car in neighbors: neighbors.remove(car) vehicleInfos[car].set_neighbors(neighbors) """ ############################################################################ Happiness Update and Algorithms ############################################################################ """ if (state == SINGLE_CAR or (state == PLATOON and not Globals.mode == HEINOVSKI)) \ and hundred_ms_times(10, step): neighbor = PlatooningAlgorithms.processing_neighbor_search( car, neighbors) else: neighbor = None """ ############################################################################ Perform State Actions ############################################################################ """ """ ############################################################################ State = NEW_SPAWNED ############################################################################ """ if state == NEW_SPAWNED: vehicleInfos[car].set_current_speed_factor( vehicleInfos[car].get_desired_speed_factor( )) if vehicleInfos[car].get_road_id() in EDGES: vehicleInfos[car].set_state(SINGLE_CAR) if DEBUG_CREATE: print(car + " start speed: " + str( vehicleInfos[car].get_speed()) + " start speed factor: " + str(vehicleInfos[car]. get_desired_speed_factor())) print(car + " switches to Single Car State") elif state == SINGLE_CAR: """ ############################################################################ State = SINGLE_CAR ############################################################################ """ platoonUtils.fix_speed_factor(car) if platoonUtils.take_next_exit(car): if DEBUG_REMOVE_MEMBER: print(car + ": " + str( plexe.get_distance_to_end(car)) + " m distance to end") vehicleInfos[car].set_state(NO_PLATOONING) elif neighbor is not None and hundred_ms_times( 10, step): if not platoonUtils.cars_in_between(car, neighbor, neighbors) \ and len(vehicleInfos[neighbor].get_platoon_members()) < MAX_PLATOON_SIZE: last_member = vehicleInfos[ neighbor].get_platoon_members()[-1] lane_difference = abs( vehicleInfos[car].get_lane_id() - vehicleInfos[neighbor].get_lane_id( )) # It is only possible to join a platoon, if car is behind the last member of the # existing platoon. if platoonUtils.get_distance(car, last_member) \ > (lane_difference + 1) * JOINING_MINIMAL_DISTANCE: vehicleInfos[car].set_state( PREPARE_JOINING) vehicleInfos[ car].set_desired_platoon_leader( neighbor) vehicleInfos[neighbor].set_joiner() elif state == PREPARE_JOINING: """ ############################################################################ State = PREPARE_JOINING ############################################################################ """ # For monitoring purpose only desired_leader = vehicleInfos[ car].get_desired_platoon_leader() members = vehicleInfos[ desired_leader].get_platoon_members() member_happiness_list = {} for member in members: member_happiness_list[ member] = PlatooningAlgorithms.calc_new_happiness( member, desired_leader) platoonUtils.prepare_joining(car, neighbors) # For monitoring purpose only if not vehicleInfos[car].get_state( ) == PREPARE_JOINING and vehicleInfos[ car].is_from_another_platoon(): if vehicleInfos[car].get_state( ) == NO_PLATOONING: counter[CHANGE_ABORT] += 1 # Monitoring happiness change of single car leader = vehicleInfos[ car].get_platoon_leader() new_happiness = PlatooningAlgorithms.calc_new_happiness( car, leader) happiness_difference = vehicleInfos[ car].get_old_happiness( ) - new_happiness happiness_change_monitor_vehicle.append( (car, happiness_difference, step)) # Monitoring happiness change of joined platoon if change was successful. if leader == desired_leader: members = vehicleInfos[ leader].get_platoon_members() happiness_difference = 0 for member in members: if member in member_happiness_list: new_happiness = PlatooningAlgorithms.calc_new_happiness( member, leader) happiness_difference += ( member_happiness_list[ member] - new_happiness) happiness_change_monitor_platoon.append( (leader, happiness_difference, step)) vehicleInfos[ car].reset_from_another_platoon() elif state == JOINING_PROCESS: """ ############################################################################ State = JOINING_PROCESS ############################################################################ """ platoonUtils.joining_process(car) # This routine checks, whether the car wants to leave the highway soon. # If that is the case, the car will leave its platoon. leader = vehicleInfos[car].get_platoon_leader() if platoonUtils.take_next_exit( car) or platoonUtils.cars_in_between( car, leader, neighbors): if DEBUG_REMOVE_MEMBER: print(car + ": " + str( plexe.get_distance_to_end(car)) + " m distance to end") vehicleInfos[car].set_state( LEAVING_PROCESS) elif state == PLATOON: """ ############################################################################ State = PLATOON ############################################################################ """ # DEBUG: Platoon desired / real speed if DEBUG_PRINT_PLATOON_DESIRED_REAL_SPEED and vehicleInfos[ car].is_leader(): print( str(car) + ": DesiredSpeed: " + str(vehicleInfos[car]. get_desired_speed()) + " isSpeed: " + str(vehicleInfos[car].get_speed())) members = vehicleInfos[ car].get_platoon_members() for member in members[1::]: print("member: " + str(member) + ": DesiredSpeed: " + str(vehicleInfos[member]. get_desired_speed()) + " isSpeed: " + str(vehicleInfos[member]. get_speed())) print( "----------------------------------------------------------------------" ) if DEBUG_PLATOON_MERGING_ALLOWED and hundred_ms_times(10, step) \ and Globals.mode != HEINOVSKI: if platoonUtils.check_merging( car, neighbor, neighbors): counter[MERGE] += 1 if vehicleInfos[car].is_leader(): platoonUtils.handle_auto_lane_change_in_platoon( car) else: # if not vehicleInfos[car].is_leader() leader = vehicleInfos[ car].get_platoon_leader() if vehicleInfos[leader].get_state() == PLATOON \ and not vehicleInfos[car].on_same_lane_with_leader() \ and vehicleInfos[car].get_road_id() == vehicleInfos[leader].get_road_id(): # Checks, if a platooned car is on the wrong lane and handles the situation. platoonUtils.check_emergency_platoon_quit( car, leader) if vehicleInfos[car].get_state( ) == PLATOON and hundred_ms_times(10, step): # This routine checks, whether the car wants to leave the highway soon. if platoonUtils.take_next_exit(car): if DEBUG_REMOVE_MEMBER: print(car + ": " + str( plexe.get_distance_to_end(car)) + " m distance to end") vehicleInfos[car].set_state( LEAVING_PROCESS) # This routine checks, whether better platoons are available. if not vehicleInfos[car].has_joiner(): if platoonUtils.handle_platoon_changing( car, neighbor, neighbors): leader = vehicleInfos[ car].get_platoon_leader() old_happiness = PlatooningAlgorithms.calc_new_happiness( car, leader) counter[CHANGE] += 1 vehicleInfos[ car].set_from_another_platoon( ) vehicleInfos[ car].set_old_happiness( old_happiness) elif state == MERGING: """ ############################################################################ State = MERGING ############################################################################ """ if vehicleInfos[car].is_leader(): leader_front = vehicleInfos[ car].get_desired_platoon_leader() members = vehicleInfos[ car].get_platoon_members() # Platoon is out of range, abort. if platoonUtils.get_distance( car, leader_front) > RADAR_DISTANCE: counter[MERGE_ABORT] += 1 for member in members: vehicleInfos[member].set_state( PLATOON) elif not platoonUtils.cars_in_between( members[-1], leader_front, neighbors): platoonUtils.merge_platoons(car) elif state == LEAVING_PROCESS: """ ############################################################################ State = LEAVING_PROCESS ############################################################################ """ platoonUtils.prepare_for_remove(car) elif state == LEFT: """ ############################################################################ State = LEFT ############################################################################ """ platoonUtils.remove_platoon_member(car) elif state == NO_PLATOONING: """ ############################################################################ State = NO_PLATOONING ############################################################################ """ # Adjust speed factor to desired after leaving a platoon. if platoonUtils.take_next_exit( car ) and vehicleInfos[car].get_lane_id() != 0: vehicleInfos[car].set_current_speed_factor( 0.5) else: platoonUtils.fix_speed_factor(car) if not platoonUtils.take_next_exit(car): if vehicleInfos[car].get_counter() >= 20: vehicleInfos[car].set_state(SINGLE_CAR) if DEBUG_PLATOON_SWITCH: print( car + " is reset into SINGLE CAR STATE" ) vehicleInfos[car].reset_counter() else: vehicleInfos[car].inc_counter() """ ############################################################################ Monitoring ############################################################################ """ if half_second(step): Monitoring.observe(step) step += 1 except: print(sys.exc_info()) print("Simulation " + str(seed) + " stops at step " + str(step)) Monitoring.write_info(counter, step) Monitoring.write_happiness_change(happiness_change_monitor_vehicle, "vehicle") Monitoring.write_happiness_change(happiness_change_monitor_platoon, "platoon") traci.close() glossary.append((seed, mode, step)) Monitoring.writeGlossary(glossary)
topology["v.%d" % i]["leader"] = LEADER return topology def main(demo_mode, real_engine, setter=None): # used to randomly color the vehicles random.seed(1) start_sumo("cfg/freeway.sumo.cfg", False) plexe = Plexe() traci.addStepListener(plexe) step = 0 state = GOING_TO_POSITION while running(demo_mode, step, 6000): # when reaching 60 seconds, reset the simulation when in demo_mode if demo_mode and step == 6000: start_sumo("cfg/freeway.sumo.cfg", True) step = 0 state = GOING_TO_POSITION random.seed(1) traci.simulationStep() if step == 0: # create vehicles and track the joiner topology = add_vehicles(plexe, N_VEHICLES, real_engine) traci.gui.trackVehicle("View #0", JOINER) traci.gui.setZoom("View #0", 20000) if step % 10 == 1: # simulate vehicle communication every 100 ms communicate(plexe, topology)