コード例 #1
0
ファイル: main.py プロジェクト: flpolyproject/spatialcov
def start_simulation(Env, sim_number, gui=False, _seed=None, setting_obj=None, dir_name=None, main_env=None, new_players=False):

	#testpath = "./../map/london-seg4/data/london-seg4.sumocfg")

	if gui:
		traci.start(["sumo-gui", "-c", Settings.sumo_config])
	else:
		traci.start(["sumo", "-c", Settings.sumo_config])


	
	env = Env(sim_number=sim_number, _seed=_seed, setting_obj=setting_obj, main_env=main_env, new_players=new_players)
	my_vis = Visualize(env)

	while True:

		traci.simulationStep()
		traci.addStepListener(env)
		if gui:
			my_vis.show()  #this is for visualization of the path
		if env.break_condition:
			break


	#env.reward_to_json(os.path.join(dir_name, f"{sim_number}"))

	print("veh succesffuly arrived ", env.sim_env.success_veh)
	traci.close()



	#env.post_process.to_csv()
	return env.post_process, env
コード例 #2
0
ファイル: test.py プロジェクト: warm2018/bottleneck
def run():
    STEP = 0
    plexe = Plexe()
    traci.addStepListener(plexe)
    StepLength = 0.1
    topology = {}
    while STEP < 3600:
        traci.simulationStep()
        STEP += StepLength
        print(STEP)
        if (int(STEP * 10) % 50 == 0) and STEP >= 300:
            Vehicles_0 = traci.lane.getLastStepVehicleIDs("4_0")
            Vehicles_1 = traci.lane.getLastStepVehicleIDs("4_1")
            #Vehicles_2 = traci.lane.getLastStepVehicleIDs("a1i_1_2")
            #Vehicles_3 = traci.lane.getLastStepVehicleIDs("a1i_1_3")
            for lane in [Vehicles_0, Vehicles_1]:  #Vehicles_2,Vehicles_3]:
                position_result, lane_result = sort_lane(lane)
                platooning_members = find_sequence(lane_result)
                print("&&&&&&&", platooning_members)
                platoon_forming(plexe, platooning_members, topology)
                print("topology", topology)
                print("&&&&&&&", platooning_members)

        if int(STEP * 10) % 50 == 0:
            try:
                platoon_die(plexe, topology)
            except:
                pass

            #print("######")
    traci.close()
    sys.stdout.flush()
コード例 #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
    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()
コード例 #4
0
ファイル: main.py プロジェクト: flpolyproject/ATNE
def start_simulation(Env, sim_number, gui=False, _seed=None):

    if gui:
        traci.start(["sumo-gui", "-c", Settings.sumo_config])
    else:
        traci.start(["sumo", "-c", Settings.sumo_config])

    env = Env(sim_number=sim_number, _seed=_seed)
    my_vis = Visualize(env)

    while True:

        traci.simulationStep()
        traci.addStepListener(env)
        if gui:
            my_vis.show()  #this is for visualization of the path
        if env.break_condition:
            break

    print("veh succesffuly arrived ", env.sim_env.success_veh)
    traci.close()

    env.post_process.to_csv()

    return env.sim_env
コード例 #5
0
ファイル: test.py プロジェクト: warm2018/bottleneck
def run():
    STEP = 0
    plexe = Plexe()
    traci.addStepListener(plexe)
    StepLength = 0.01
    topology = {}
    while STEP < 400:
        traci.simulationStep()
        STEP += StepLength
        if int(STEP * 100) % 500 == 0:
            Vehicles_0 = traci.lane.getLastStepVehicleIDs("a1i_1_0")
            #Vehicles_1 = traci.lane.getLastStepVehicleIDs("a1i_1_1")
            #Vehicles_2 = traci.lane.getLastStepVehicleIDs("a1i_1_2")
            #Vehicles_3 = traci.lane.getLastStepVehicleIDs("a1i_1_3")
            #for lane in [Vehicles_0,Vehicles_1,Vehicles_2,Vehicles_3]:
            for lane in [Vehicles_0]:
                position_result, lane_result = sort_lane(lane)
                platooning_members = find_sequence(lane_result)
                print("&&&&&&&", platooning_members)
                platoon_forming(plexe, platooning_members, topology)
                print("topology", topology)
                print("&&&&&&&", platooning_members)

        if int(STEP * 100) % 500 == 0:
            platoon_die(plexe, topology)
            #print("######")
        if STEP >= 20 and WRITE_EXCEL and int(STEP * 100) % 10 == 0:
            currentIDList = traci.vehicle.getIDList()
            print('999')
            write_excel(STEP, worksheet, begin_step, RouteList, vehicle_store,
                        currentIDList)
    workbook.close()
    traci.close()
    sys.stdout.flush()
コード例 #6
0
ファイル: joindemo.py プロジェクト: zhimintu/plexe-pyapi
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()
コード例 #7
0
ファイル: joindemo.py プロジェクト: ckckck96/plexe-pyapi
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):
コード例 #8
0
def load(config_filename):
    '''
    Load the config from file and create a Platoon Manager
    '''
    global _mgr
    _config.load(config_filename)
    _mgr = _platoonmanager.PlatoonManager()
    if _useStepListener:
        # For SUMO version >= 0.30
        traci.addStepListener(_mgr)
コード例 #9
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()
コード例 #10
0
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()
コード例 #11
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
コード例 #12
0
def start_simulation():

    n_step = 0
    env = EnvironmentListener()

    while True:

        traci.simulationStep()
        traci.addStepListener(env)
        n_step += 1

    traci.close()
コード例 #13
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()
コード例 #14
0
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
コード例 #15
0
ファイル: __init__.py プロジェクト: fieryzig/sumo
def load(config_filename):
    '''
    Load the config from file and create a Platoon Manager
    '''
    global _mgr, _mgr_listenerID
    simpla._config.load(config_filename)
    _mgr = simpla._platoonmanager.PlatoonManager()
    if _useStepListener:
        # For SUMO version >= 0.30
        _mgr_listenerID = traci.addStepListener(_mgr)
コード例 #16
0
ファイル: autofeeddemo.py プロジェクト: zhimintu/plexe-pyapi
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()
コード例 #17
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()
コード例 #18
0
def openGap(vehID, desiredGap, desiredSpeedDiff, maximumDecel, duration):
    '''
    openGap(string, float>0, float>0, float>0, float>0)

    vehID - ID of the vehicle to be controlled
    desiredGap - gap that shall be established
    desiredSpeedDiff - rate at which the gap is open if possible
    maximumDecel - maximal deceleration at which the desiredSpeedDiff is tried to be approximated
    duration - The period for which the gap control should be active

    This methods adds a controller for the opening of a gap in front of the given vehicle.
    The controller stays active for a period of the given duration.
    If a leader is closer than the desiredGap, the controller tries to establish the desiredGap by inducing the
    given speedDifference, while not braking harder than maximumDecel.
    An object of the class GapCreator is created to manage the vehicle state and is added to traci as a stepListener.
    '''
    global _activeGapControllers

    if DEBUG_GAP_CONTROL:
        print("openGap()")

    # Check type error
    errorMsg = None
    if desiredGap <= 0:
        errorMsg = "simpla.openGap(): Parameter desiredGap has to be a positive float (given value = %s)." % desiredGap
    elif desiredSpeedDiff <= 0:
        errorMsg = "simpla.openGap(): Parameter desiredSpeedDiff has to be a positive float (given value = %s)." % (
            desiredSpeedDiff)
    elif maximumDecel <= 0:
        errorMsg = "simpla.openGap(): Parameter maximumDecel has to be a positive float (given value = %s)." % (
            maximumDecel)
    elif duration <= 0:
        errorMsg = "simpla.openGap(): Parameter duration has to be a positive float (given value = %s)." % duration
    if errorMsg is not None:
        raise SimplaException(errorMsg)

    # remove any previous controller attached to the vehicle
    removeGapController(vehID)
    gc = GapController(vehID, desiredGap, desiredSpeedDiff, maximumDecel,
                       duration)
    listenerID = traci.addStepListener(gc)
    _activeGapControllers[vehID] = listenerID
    if DEBUG_GAP_CONTROL:
        print("Active controllers: %s." % (_activeGapControllers))
コード例 #19
0
ファイル: _utils.py プロジェクト: fieryzig/sumo
def openGap(vehID, desiredGap, desiredSpeedDiff, maximumDecel, duration):
    '''
    openGap(string, float>0, float>0, float>0, float>0)

    vehID - ID of the vehicle to be controlled
    desiredGap - gap that shall be established
    desiredSpeedDiff - rate at which the gap is open if possible
    maximumDecel - maximal deceleration at which the desiredSpeedDiff is tried to be approximated
    duration - The period for which the gap control should be active

    This methods adds a controller for the opening of a gap in front of the given vehicle.
    The controller stays active for a period of the given duration.
    If a leader is closer than the desiredGap, the controller tries to establish the desiredGap by inducing the
    given speedDifference, while not braking harder than maximumDecel.
    An object of the class GapCreator is created to manage the vehicle state and is added to traci as a stepListener.
    '''
    global _activeGapControllers

    if DEBUG_GAP_CONTROL:
        print("openGap()")

    # Check type error
    errorMsg = None
    if desiredGap <= 0:
        errorMsg = "simpla.openGap(): Parameter desiredGap has to be a positive float (given value = %s)." % desiredGap
    elif desiredSpeedDiff <= 0:
        errorMsg = "simpla.openGap(): Parameter desiredSpeedDiff has to be a positive float (given value = %s)." % (
            desiredSpeedDiff)
    elif maximumDecel <= 0:
        errorMsg = "simpla.openGap(): Parameter maximumDecel has to be a positive float (given value = %s)." % (
            maximumDecel)
    elif duration <= 0:
        errorMsg = "simpla.openGap(): Parameter duration has to be a positive float (given value = %s)." % duration
    if errorMsg is not None:
        raise SimplaException(errorMsg)

    # remove any previous controller attached to the vehicle
    removeGapController(vehID)
    gc = GapController(vehID, desiredGap, desiredSpeedDiff, maximumDecel, duration)
    listenerID = traci.addStepListener(gc)
    _activeGapControllers[vehID] = listenerID
    if DEBUG_GAP_CONTROL:
        print("Active controllers: %s." % (_activeGapControllers))
def run_algorithm():
    listener = traffic_analyzer.WaitingTimeListener()
    traci.addStepListener(listener)

    #Density for all incoming roads
    density = {}
    density["west"] = 0
    density["north"] = 0
    density["east"] = 0
    density["south"] = 0

    #Time needed for cars on incoming roads to pass through
    time = {}
    time["west"] = 0
    time["north"] = 0
    time["east"] = 0
    time["south"] = 0

    yellow = False
    yellow_timer = 0

    green_timer = GREEN_TIME
    green_time = GREEN_TIME

    max_density = 0
    max_density_edge = "west"

    step = 0

    waiting_time = 0
    waiting_time2 = 0
    vehicle_amount = 0
    while traci.simulation.getMinExpectedNumber() > 0:
        traci.simulationStep()
        step += 1

        if step == 600:
            waiting_time = traffic_analyzer.getWaitingTimes()
            waiting_time2 = traffic_analyzer.getSquaredWaitingTimes()
            vehicle_amount = traffic_analyzer.getVehicleAmount()

        #Switching between roads
        if yellow:
            if yellow_timer < YELLOW_TIME:
                yellow_timer += 1
            else:
                yellow_timer = 0
                yellow = False
                if max_density_edge == "west" or max_density_edge == "east":
                    traci.trafficlight.setRedYellowGreenState(
                        "intersection", WE_GREEN_STATE)
                else:
                    traci.trafficlight.setRedYellowGreenState(
                        "intersection", NS_GREEN_STATE)
        #Light is green
        elif green_timer < green_time:
            green_timer += 1
        #Determine which road that should get green light
        else:
            green_timer = 0

            #Set current green road's values to 0
            if max_density_edge == "west" or max_density_edge == "east":
                density["west"] = 0
                density["east"] = 0
                time["west"] = 0
                time["east"] = 0
            else:
                density["north"] = 0
                density["south"] = 0
                time["north"] = 0
                time["south"] = 0

            previous_edge = max_density_edge
            max_density = 0

            #Get highest density
            for edge in density:
                if density[edge] > max_density:
                    max_density = density[edge]
                    max_density_edge = edge

            #All roads have been taken, recalculate values
            if max_density == 0:
                density["west"], time[
                    "west"] = traffic_analyzer.getDensityAndTimeOnEdge(
                        "west_right")
                density["north"], time[
                    "north"] = traffic_analyzer.getDensityAndTimeOnEdge(
                        "north_down")
                density["east"], time[
                    "east"] = traffic_analyzer.getDensityAndTimeOnEdge(
                        "east_left")
                density["south"], time[
                    "south"] = traffic_analyzer.getDensityAndTimeOnEdge(
                        "south_up")

                #Get highest density, again
                for edge in density:
                    if density[edge] > max_density:
                        max_density = density[edge]
                        max_density_edge = edge

            if max_density_edge == "west" or max_density_edge == "east":
                green_time = min(max(time["west"], time["east"]), GREEN_TIME)
                if previous_edge != "west" and previous_edge != "east":
                    yellow = True
                    traci.trafficlight.setRedYellowGreenState(
                        "intersection", NS_YELLOW_STATE)
            else:
                green_time = min(max(time["north"], time["south"]), GREEN_TIME)
                if previous_edge != "north" and previous_edge != "south":
                    yellow = True
                    traci.trafficlight.setRedYellowGreenState(
                        "intersection", WE_YELLOW_STATE)

    waiting_time = traffic_analyzer.getWaitingTimes() - waiting_time
    waiting_time2 = traffic_analyzer.getSquaredWaitingTimes() - waiting_time2
    vehicle_amount = traffic_analyzer.getVehicleAmount() - vehicle_amount
    print("Average waiting time: " + str(float(waiting_time) / vehicle_amount))
    print("Average squared waiting time: " +
          str(float(waiting_time2) / vehicle_amount))
    traci.close()
    sys.stdout.flush()
    traffic_analyzer.reset()
    return float(waiting_time) / vehicle_amount, float(
        waiting_time2) / vehicle_amount
コード例 #21
0
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)
コード例 #22
0
                    print("\nEmergency breaking required...")
                    self.emergencyBreak = True

# MAIN PROGRAM

print("Starting the TraCI server...")
traci.start(sumoCmd) 

print("Subscribing to vehicle data...")
traci.vehicle.subscribe("veh0", (tc.VAR_COLOR, tc.VAR_SPEED, tc.VAR_ACCELERATION, tc.VAR_POSITION, tc.VAR_LANE_ID, tc.VAR_LANEPOSITION))
traci.vehicle.subscribe("veh1", (tc.VAR_COLOR, tc.VAR_SPEED, tc.VAR_ACCELERATION, tc.VAR_POSITION, tc.VAR_LANE_ID, tc.VAR_LANEPOSITION))
traci.vehicle.subscribe("veh2", (tc.VAR_COLOR, tc.VAR_SPEED, tc.VAR_ACCELERATION, tc.VAR_POSITION, tc.VAR_LANE_ID, tc.VAR_LANEPOSITION))

print("Constructing a StateListener...")
stateListener = StateListener(["veh0", "veh1", "veh2"])
traci.addStepListener(stateListener)

# disable speed control by SUMO
traci.vehicle.setSpeedMode("veh0",0)
# set the desired speed and the time to reach that speed
traci.vehicle.slowDown("veh0",1,3)

step = 0
while step < 20:
    # advance the simulation
    print("\nsimulation step: %i" % step)
    traci.simulationStep()
    step += 1
    # if emergency breaking or a collision occurs stop the simulation
    if stateListener.emergencyBreak or stateListener.collision:
        break
コード例 #23
0
def run_algorithm(not_trained):
    wait_listener = traffic_analyzer.WaitingTimeListener()
    traci.addStepListener(wait_listener)
    delayListener = traffic_analyzer.DelayListener()
    traci.addStepListener(delayListener)
    queueListener = traffic_analyzer.QueueListener()
    traci.addStepListener(queueListener)

    #Reinforcement Learning
    Q = np.zeros([6, 6, 6, 6, 7, 2])
    try:
        Q = np.load('q.npy')
        print("Q matrix loaded")
    except:
        pass
    # Set learning parameters
    lr = .8
    y = .95
    #

    switched = False

    yellow = False
    yellow_time = 0

    green_time = 0
    green_time_at_switch = 0

    west_east = True
    traci.trafficlight.setRedYellowGreenState("intersection", WE_GREEN_STATE)

    state = [0, 0, 0, 0, 0]
    previous_state = state
    action = 0
    previous_waiting_times = 0

    step = 0

    waiting_time = 0
    waiting_time2 = 0
    vehicle_amount = 0
    while traci.simulation.getMinExpectedNumber() > 0:
        traci.simulationStep()
        step += 1

        if step == 600:
            waiting_time = traffic_analyzer.getWaitingTimes()
            waiting_time2 = traffic_analyzer.getSquaredWaitingTimes()
            vehicle_amount = traffic_analyzer.getVehicleAmount()

        if yellow:
            if yellow_time < YELLOW_TIME:
                yellow_time += 1
            else:
                yellow_time = 0
                yellow = False
                if west_east:
                    west_east = False
                    traci.trafficlight.setRedYellowGreenState(
                        "intersection", NS_GREEN_STATE)
                else:
                    west_east = True
                    traci.trafficlight.setRedYellowGreenState(
                        "intersection", WE_GREEN_STATE)
        else:
            if green_time < 10:
                green_time += 1
            elif not switched:
                #Reinforcement learning

                #Get state
                q_w, q_n, q_e, q_s, p_t = sensorValues(
                    traffic_analyzer.queue_lengths["west"],
                    traffic_analyzer.queue_lengths["north"],
                    traffic_analyzer.queue_lengths["east"],
                    traffic_analyzer.queue_lengths["south"], green_time)
                state = [q_w, q_n, q_e, q_s, p_t]

                #Get reward
                waiting_times = traffic_analyzer.getDelay()
                r = waiting_times - previous_waiting_times
                previous_waiting_times = waiting_times

                #Update Q-Table with new knowledge
                Q[previous_state[0], previous_state[1], previous_state[2],
                  previous_state[3], previous_state[4], action] = Q[
                      previous_state[0], previous_state[1], previous_state[2],
                      previous_state[3], previous_state[4], action] + lr * (
                          r + y * np.min(Q[state[0], state[1], state[2],
                                           state[3], state[4], :]) -
                          Q[previous_state[0], previous_state[1],
                            previous_state[2], previous_state[3],
                            previous_state[4], action])

                #Get action and execute it
                explore = 0.1
                if not_trained:
                    explore += (7800 - step) / 7800
                if explore > 1:
                    explore = 1
                action = None
                if random.uniform(0, 1) > explore:
                    action = np.argmin(Q[state[0], state[1], state[2],
                                         state[3], state[4], :])
                else:
                    action = random.randint(0, 1)
                if action == 1 and not west_east:
                    switched = True
                    GREEN_TIME = green_time + 10
                elif action == 0 and west_east:
                    switched = True
                    GREEN_TIME = green_time + 10
                previous_state = state

                green_time += 1
            elif switched:
                if green_time < GREEN_TIME:
                    green_time += 1
                else:
                    green_time = 0
                    switched = False
                    yellow = True
                    if west_east:
                        traci.trafficlight.setRedYellowGreenState(
                            "intersection", WE_YELLOW_STATE)
                    else:
                        traci.trafficlight.setRedYellowGreenState(
                            "intersection", NS_YELLOW_STATE)

    waiting_time = traffic_analyzer.getWaitingTimes() - waiting_time
    waiting_time2 = traffic_analyzer.getSquaredWaitingTimes() - waiting_time2
    vehicle_amount = traffic_analyzer.getVehicleAmount() - vehicle_amount
    np.save('q.npy', Q)
    print("Q matrix stored")
    print("Average waiting time: " + str(float(waiting_time) / vehicle_amount))
    print("Average squared waiting time: " +
          str(float(waiting_time2) / vehicle_amount))
    traci.close()
    sys.stdout.flush()
    traffic_analyzer.reset()
    return float(waiting_time) / vehicle_amount, float(
        waiting_time2) / vehicle_amount
コード例 #24
0
def run_algorithm(gt):
    GREEN_TIME = gt
    green = 0
    yellow = 0
    west_east = True
    yellow_phase = False
    listener = traffic_analyzer.WaitingTimeListener()
    traci.addStepListener(listener)
    step = 0

    waiting_time = 0
    waiting_time2 = 0
    vehicle_amount = 0

    while traci.simulation.getMinExpectedNumber() > 0:
        traci.simulationStep()
        step += 1

        if step == 600:
            waiting_time = traffic_analyzer.getWaitingTimes()
            waiting_time2 = traffic_analyzer.getSquaredWaitingTimes()
            vehicle_amount = traffic_analyzer.getVehicleAmount()

        #Increment time for the different phases
        if yellow_phase:
            yellow += 1
            #Time maximized, switch state
            if yellow > YELLOW_TIME:
                yellow = 0
                yellow_phase = False
                if west_east:
                    traci.trafficlight.setRedYellowGreenState(
                        "intersection", NS_GREEN_STATE)
                    west_east = False
                else:
                    traci.trafficlight.setRedYellowGreenState(
                        "intersection", WE_GREEN_STATE)
                    west_east = True
        else:
            green += 1
            #Time maximized, switch state
            if green > GREEN_TIME:
                green = 0
                yellow_phase = True
                if west_east:
                    traci.trafficlight.setRedYellowGreenState(
                        "intersection", WE_YELLOW_STATE)
                else:
                    traci.trafficlight.setRedYellowGreenState(
                        "intersection", NS_YELLOW_STATE)

    waiting_time = traffic_analyzer.getWaitingTimes() - waiting_time
    waiting_time2 = traffic_analyzer.getSquaredWaitingTimes() - waiting_time2
    vehicle_amount = traffic_analyzer.getVehicleAmount() - vehicle_amount
    print("Average waiting time: " + str(float(waiting_time) / vehicle_amount))
    print("Average squared waiting time: " +
          str(float(waiting_time2) / vehicle_amount))
    traci.close()
    sys.stdout.flush()
    traffic_analyzer.reset()
    return float(waiting_time) / vehicle_amount, float(
        waiting_time2) / vehicle_amount
コード例 #25
0

def runSimulation():
    '''runSimulation(CarsInSimulation) -> none'''
    while traci.simulation.getMinExpectedNumber() > 0:
        traci.simulationStep()
    traci.close()


def setUpSimulation():
    sumoBinary = checkBinary("sumo")
    sumoCmd = [sumoBinary, "-c", "data/first.sumocfg"]
    traci.start(sumoCmd)


if __name__ == "__main__":
    setUpSimulation()
    sl_evaluator = EvaluatorStepListener(Evaluator())
    alpha = ConstantFunction(0)
    epsilon = ConstantFunction(.1)
    discount = .5
    q_learning = RLAgentQLearning(epsilon, alpha, discount)
    state = IntersectionState("C")
    controller = RlTlController(state, q_learning)
    #controller = DoNothingTlController()
    sl_controller = TrafficControllerStepListener(controller)
    traci.addStepListener(sl_evaluator)
    traci.addStepListener(sl_controller)
    runSimulation()
    sl_evaluator.print_results()
コード例 #26
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()
コード例 #27
0
ファイル: smallMap.py プロジェクト: thomasrw/TrafficSim
    else:
        sumoBinary = "/usr/share/sumo/bin/sumo-gui"

    # passing the "--start" option to tell sumo-gui to begin without waiting for the play button to be pressed
    sumoCmd = [sumoBinary, "-c", "/home/thomasrw/j/jconfig", "--start"]
    simplaConfig = "/home/thomasrw/j/mysimpla.cfg.xml"
    #simplaConfig2 = "/home/thomasrw/Model/mysimpla2.cfg.xml"

    traci.start(sumoCmd)
    #simpla.load(simplaConfig)

    #calling config.load() and platoonmanger() explicitly exposes the platoon manager variable allowing listeners
    #  to be specified by platoon manager

    simpla._config.load(simplaConfig)
    ##mgr = simpla._platoonmanager.PlatoonManager()
    mgr = _platoonmanager2.PlatoonManager2()
    mgr_id = traci.addStepListener(mgr)

    #print(str(mgr.getMaxSize()))
    #mgr.setMaxSize(50)
    #print(str(mgr.getMaxSize()))

    #simpla.load(simplaConfig2)

    start = time.time()
    run()
    end = time.time()
    total = end - start
    print("time taken is: " + str(total))