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()
예제 #2
0
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()
예제 #3
0
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):
예제 #4
0
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()
예제 #5
0
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()
예제 #7
0
def ensure_ceph_storage(service, pool, rbd_img, sizemb, mount_point,
                        blk_device, fstype, system_services=[]):
    """
    To be called from the current cluster leader.
    Ensures given pool and RBD image exists, is mapped to a block device,
    and the device is formatted and mounted at the given mount_point.

    If formatting a device for the first time, data existing at mount_point
    will be migrated to the RBD device before being remounted.

    All services listed in system_services will be stopped prior to data
    migration and restarted when complete.
    """
    # Ensure pool, RBD image, RBD mappings are in place.
    if not pool_exists(service, pool):
        utils.juju_log('INFO', 'ceph: Creating new pool %s.' % pool)
        create_pool(service, pool)

    if not rbd_exists(service, pool, rbd_img):
        utils.juju_log('INFO', 'ceph: Creating RBD image (%s).' % rbd_img)
        create_rbd_image(service, pool, rbd_img, sizemb)

    if not image_mapped(rbd_img):
        utils.juju_log('INFO', 'ceph: Mapping RBD Image as a Block Device.')
        map_block_storage(service, pool, rbd_img)

    # make file system
    # TODO: What happens if for whatever reason this is run again and
    # the data is already in the rbd device and/or is mounted??
    # When it is mounted already, it will fail to make the fs
    # XXX: This is really sketchy!  Need to at least add an fstab entry
    #      otherwise this hook will blow away existing data if its executed
    #      after a reboot.
    if not filesystem_mounted(mount_point):
        make_filesystem(blk_device, fstype)

        for svc in system_services:
            if utils.running(svc):
                utils.juju_log('INFO',
                               'Stopping services %s prior to migrating '\
                               'data' % svc)
                utils.stop(svc)

        place_data_on_ceph(service, blk_device, mount_point, fstype)

        for svc in system_services:
            utils.start(svc)
예제 #8
0
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()
예제 #9
0
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()
예제 #10
0
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()
예제 #11
0
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()
예제 #13
0
     # 运行 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
​
     # 主循环
     while running(demo_mode, step, 1500):
​
         # when reaching 15 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()
​
         # 仿真初始化阶段,构造含有 8 辆车的 platoon
         # 设置 GUI 中画面在整个仿真过程中始终聚焦在 v.0.0, 即头车
         # 镜头缩放参数 20000, 这个可以根据具体场景设置,使得镜头既不会拉的太近,也不会拉的太远。
         if step == 0:
             # create vehicles and track the braking vehicle
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()
예제 #15
0
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()
예제 #16
0
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()
예제 #17
0
​
​
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
​
     while running(demo_mode, step, 3000):
​         
         # We can add reset simulation here just like the brakedemo.py

         traci.simulationStep()
​
         if step == 0:
             # create vehicles and track the braking vehicle
             topology = add_vehicles(plexe, PLATOON_SIZE, PLATOON_NUM, real_engine) # PLATOON_SIZE = 8, PLATOON_NUM = 1
             tracked_veh = "v.0.%d" %(PLATOON_SIZE-1)
             traci.gui.trackVehicle("View #0", tracked_veh)
             traci.gui.setZoom("View #0", 2000)
​             # at this part we can set another View #1 to tracked the first platoon group pass the traffic light
             traci.gui.trackVehicle("View #1", ORI_LEADER_ID)
             traci.gui.setZoom("View #1", 2000)