Пример #1
1
def run():
    global current_hour
    """execute the TraCI control loop"""
    traci.init(PORT)

    src = [
        Source("D2",100,1),
        Source("D2",100,2),
        Source("D2",100,3),
        Source("L16",100,51),
        Source("L14",50,25),
        Source("V4",0,30)
        ]
    dest = [
            Destination("V4",150),
            Destination("V4",100),
            Destination("D8",5),
            Destination("V4",150),
            Destination("D1",10),
            Destination("D1",20)
            ]
    stops = [
            ChargingStation(0,"D6",50,2,10,[0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5])
            ,
            ChargingStation(1,"V2",50,2,8,[0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5])
            ]            
    types = ["CarA", "CarA", "CarD", "CarB", "CarC", "CarC"]

    #number of elechtric vehicle insterted
    veh_count = 0
    vehicles = []
    temp_vehs = []
    for i in range(6):
        vehicles.append(Electric_Vehicle(veh_count,src[i],dest[i],types[i],1000,temp_vehs))
        veh_count+=1

    center = Center(stops,vehicles)
    for s in stops:
        center.seller_report(s)

    temp_toDel = False
    while vehicles != []:
        traci.simulationStep()
        if traci.simulation.getCurrentTime()/1000 % 1000 == 0 and traci.simulation.getCurrentTime()>0:
            current_hour += 1
            print '[HOUR]', current_hour
        deleteTempVehicles(temp_vehs)        
        for v in vehicles:
            if (v.updateState(dest) == 1 and not v.reported):
                center.buyer_report(v,stops,current_hour,temp_vehs)
                center.assign(v,stops)
                v.assinged = v.stopToCharge()
                v.reported = True
            if (v.toDel):
                vehicles.remove(v)
            if v.reported and not v.assinged:
                v.assinged = v.stopToCharge()
        
    traci.close()
    sys.stdout.flush()
Пример #2
0
def run():
    create_simulation_scenario()
    if mode == "train":
        for i in range(200):
            if random.uniform(0, 1) > 0.5:
                accident_cars.add("veh" + str(i))

    client_socket = socket.socket()
    client_socket.connect(('127.0.0.1', 9999))
    traci.init(PORT)
    step = 0

    client_socket.send(scenario + "," + mode + "," + time + "\n")
    message = client_socket.recv(1024).splitlines()[0]
    print message

    cars_in_perimeter = set()
    while traci.simulation.getMinExpectedNumber() > 0:
        manage_car_set(cars_in_perimeter)
        send_data_to_rsu(client_socket, cars_in_perimeter)
        traci.simulationStep()
        step += 1
        if mode == "run":
            sleep(0.2)
    traci.close()
    client_socket.close()
Пример #3
0
def run_genetic_algorithm():
    sumoProcessCmd = run_sumo(SUMO)
    traci.init(PORT)
    generate_tollgates()
    traci.close()
    sumoProcessCmd.wait()
    run_simulation()
Пример #4
0
def run():
    """execute the TraCI control loop"""
    traci.init(PORT)

    # track the duration for which the green phase of the vehicles has been
    # active
    greenTimeSoFar = 0

    # whether the pedestrian button has been pressed
    activeRequest = False

    # main loop. do something every simulation step until no more vehicles are
    # loaded or running
    while traci.simulation.getMinExpectedNumber() > 0:
        traci.simulationStep()

        # decide wether there is a waiting pedestrian and switch if the green
        # phase for the vehicles exceeds its minimum duration
        if not activeRequest:
            activeRequest = checkWaitingPersons()
        if traci.trafficlights.getPhase(TLSID) == VEHICLE_GREEN_PHASE:
            greenTimeSoFar += 1
            if greenTimeSoFar > MIN_GREEN_TIME:
                # check whether someone has pushed the button

                if activeRequest:
                    # switch to the next phase
                    traci.trafficlights.setPhase(
                        TLSID, VEHICLE_GREEN_PHASE + 1)
                    # reset state
                    activeRequest = False
                    greenTimeSoFar = 0

    sys.stdout.flush()
    traci.close()
Пример #5
0
def main():
    sumoCmd = [sumoBinary, "-c", sumoConfig]
    traci.start(sumoCmd)                               # 开始仿真
    simulationSteps = 0
    Phaseflag = 0
    while simulationSteps < 1000:                      # 仿真1000个步长
        traci.simulationStep()                         # 执行一步仿真

        # 获取仿真环境中当前仿真步的实时信息
        print('红绿灯路口西侧排队车辆数目:', traci.lanearea.getJamLengthVehicle('W'))
        print('红绿灯路口西侧排队长度:', traci.lanearea.getJamLengthMeters('W'))
        print('红绿灯路口东侧排队车辆数目:', traci.lanearea.getJamLengthVehicle('E'))
        print('红绿灯路口东侧排队长度:', traci.lanearea.getJamLengthMeters('E'))
        print('红绿灯路口北侧排队车辆数目:', traci.lanearea.getJamLengthVehicle('N'))
        print('红绿灯路口北侧排队长度:', traci.lanearea.getJamLengthMeters('N'))
        print('红绿灯路口南侧排队车辆数目:', traci.lanearea.getJamLengthVehicle('S'))
        print('红绿灯路口南侧排队长度:', traci.lanearea.getJamLengthMeters('S'))

        # 红绿灯控制程序
        # 所控红绿灯的相位顺序为:东西直行南北禁行(30秒),南北直行东西禁行(30秒)
        if simulationSteps % 30 == 0:
            if Phaseflag % 2 == 0:
                traci.trafficlight.setPhase('3', 0)   # 改变红绿灯的相位为东西直行南北禁行
            else:
                traci.trafficlight.setPhase('3', 1)   # 改变红绿灯的相位为南北直行东西禁行
            Phaseflag += 1
        simulationSteps += 1
    traci.close()                                     # 结束仿真
Пример #6
0
def main(args):
    sumoBinary = sumolib.checkBinary('sumo')
    sumo_call = [sumoBinary, "-c", "data/hello.sumocfg",
                 "--remote-port", str(PORT_TRACI),
                 "--netstate-dump", "rawdump.xml",
                 "--no-step-log"]
    sumoProcess = subprocess.Popen(
        sumo_call, stdout=sys.stdout, stderr=sys.stderr)
    traci.init(PORT_TRACI)

    for step in range(161):
        traci.simulationStep()
        if step == 120:
            print(traci.vehicle.getDistance('Stapler_00'))
            traci.vehicle.setRoute('Stapler_00', ('ed1', 'ed5'))
            print(traci.vehicle.getRoute('Stapler_00'))
            assert(traci.vehicle.getRoute('Stapler_00')
                   == ['ed0', 'ed1', 'ed5'])
            print(traci.vehicle.getDistance('Stapler_00'))
        if step == 122:
            assert(traci.vehicle.getRoute('Stapler_00')
                   == ['ed0', 'ed1', 'ed5'])
            print(traci.vehicle.getDistance('Stapler_00'))
            traci.vehicle.setRouteID('Stapler_00', "short")
            print(traci.vehicle.getRoute('Stapler_00'))
            print(traci.vehicle.getDistance('Stapler_00'))
    traci.close()
    sumoProcess.wait()
Пример #7
0
def init(manager, forTest=False):
    optParser = OptionParser()
    optParser.add_option("-v", "--verbose", action="store_true", dest="verbose",
                         default=False, help="tell me what you are doing")
    optParser.add_option("-g", "--gui", action="store_true", dest="gui",
                         default=False, help="run with GUI")
    optParser.add_option("-c", "--cyber", action="store_true", dest="cyber",
                         default=False, help="use small cybercars instead of big busses")
    optParser.add_option("-d", "--demand", type="int", dest="demand",
                         default=15, help="period with which the persons are emitted")
    optParser.add_option("-b", "--break", type="int", dest="breakstep", metavar="TIMESTEP",
                         help="let a vehicle break for %s seconds at TIMESTEP" % BREAK_DELAY)
    (options, args) = optParser.parse_args()
    sumoExe = SUMO
    if options.gui:
        sumoExe = SUMOGUI
    sumoConfig = "%s%02i.sumocfg" % (PREFIX, options.demand)
    if options.cyber:
        sumoConfig = "%s%02i_cyber.sumocfg" % (PREFIX, options.demand)
    sumoProcess = subprocess.Popen([sumoExe, sumoConfig], stdout=sys.stdout, stderr=sys.stderr)
    traci.init(PORT)
    traci.simulation.subscribe()
    setting.manager = manager
    setting.verbose = options.verbose
    setting.cyber = options.cyber
    setting.breakstep = options.breakstep
    try:
        while setting.step < 100 or statistics.personsRunning > 0:
            doStep()
        statistics.evaluate(forTest)
    finally:
        traci.close()
        sumoProcess.wait()
Пример #8
0
def run():
    """execute the TraCI control loop"""
    traci.init(PORT)
    step = 0

    num_cars = -1
    parkable_lanes = []
    parked_cars = []

    for lane_id in traci.lane.getIDList():
        if PARKING_EDGE_TWO_LABEL in lane_id:
            parkable_lanes.append(lane_id)

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

        traci.vehicle.add("parking_{}".format(num_cars), "right")
        if len(parkable_lanes) >0:
            parking_target = ""
            parking_target = random.choice(parkable_lanes)
            print parking_target
            traci.vehicle.changeTarget("parking_{}".format(num_cars), "1i_parking_lane_2_2")#parking_target[:-2])
            parkable_lanes.remove(parking_target)
            parked_cars.append("parking_{}".format(num_cars))





        step += 1
    traci.close()
    sys.stdout.flush()
Пример #9
0
def run(edges, connections, speedChanges, optimalization, nogui):
    '''execute the TraCI control loop'''
    traci.init(PORT)
    if not nogui:
        traci.gui.trackVehicle('View #0', '0')
    #print 'route: {0}'.format(traci.vehicle.getRoute('0'))
    destination = traci.vehicle.getRoute('0')[-1]
    edgesPoll = list(edges)

    time = traci.simulation.getCurrentTime()
    while traci.simulation.getMinExpectedNumber() > 0:
        if optimalization:
            change_edge_speed(edgesPoll, edges, speedChanges)
            edge = traci.vehicle.getRoadID('0')
            if edge in edges and traci.vehicle.getLanePosition('0') >= 0.9 * traci.lane.getLength(traci.vehicle.getLaneID('0')):
                shortestPath = graph.dijkstra(edge, destination, edges, get_costs(edges), connections)
                #print 'dijkstra: {0}'.format(shortestPath)
                traci.vehicle.setRoute('0', shortestPath)
        else:
            if len(speedChanges) > 0:
                edge, speed = speedChanges.pop()
                traci.edge.setMaxSpeed(edge, speed)
            else:
                change_edge_speed(edgesPoll, edges, [])
        traci.simulationStep()
    time = traci.simulation.getCurrentTime() - time
    traci.close()
    sys.stdout.flush()
    return time
Пример #10
0
def runSingle(traciEndTime, viewRange, module, objID):
    seen1 = 0
    seen2 = 0
    step = 0
    sumoProcess = subprocess.Popen("%s -c sumo.sumocfg %s" % (sumoBinary, addOption), shell=True, stdout=sys.stdout)
#    time.sleep(20)
    traci.init(PORT)
    traci.poi.add("poi", 400, 500, (1,0,0,0))
    traci.polygon.add("poly", ((400, 400), (450, 400), (450, 400)), (1,0,0,0))
    subscribed = False
    while not step>traciEndTime:
        responses = traci.simulationStep()
        near1 = set()
        if objID in module.getContextSubscriptionResults():
            for v in module.getContextSubscriptionResults()[objID]:
                near1.add(v)
        vehs = traci.vehicle.getIDList()
        pos = {}
        for v in vehs:
            pos[v] = traci.vehicle.getPosition(v)
        shape = None
        egoPos = None
        if hasattr(module, "getPosition"):
            egoPos = module.getPosition(objID)
        elif hasattr(module, "getShape"):
            shape = module.getShape(objID)
        elif module == traci.edge:
            # it's a hack, I know,  but do we really need to introduce edge.getShape?
            shape = traci.lane.getShape(objID+"_0")
        near2 = set()
        for v in pos:
            if egoPos:
                if math.sqrt(dist2(egoPos, pos[v])) < viewRange:
                    near2.add(v)
            if shape:
                lastP = shape[0]
                for p in shape[1:]:
                    if math.sqrt(distToSegmentSquared(pos[v], lastP, p)) < viewRange:
                        near2.add(v)
                    lastP = p
        
        if not subscribed:
            module.subscribeContext(objID, traci.constants.CMD_GET_VEHICLE_VARIABLE, viewRange, [traci.constants.VAR_POSITION] )
            subscribed = True
        else:
            seen1 += len(near1)
            seen2 += len(near2)
            for v in near1:
                if v not in near2:
                    print "timestep %s: %s is missing in subscribed vehicles" % (step, v)
            for v in near2:
                if v not in near1:
                    print "timestep %s: %s is missing in surrounding vehicles" % (step, v)


        step += 1
    print "Print ended at step %s" % (traci.simulation.getCurrentTime() / DELTA_T)
    traci.close()
    sys.stdout.flush()
    print "seen %s vehicles via suscription, %s in surrounding" % (seen1, seen2)
Пример #11
0
def run_ere(scenario_name, closed_roads, s_time, duration):
    """
    This is to enable the enroute event scenario using TraCI
    :param scenario_name: the name of the scenario
    :param closed_roads: the list of closed road id
    :param s_time: the starting time stamp for the road closure in seconds
    :param duration: the road closure duration in seconds
    """
    sumo_net = net.readNet(load_map(scenario_name))
    pre_sp_lim = []
    for i in closed_roads:
        pre_sp_lim.append(sumo_net.getEdge(i).getSpeed())

    s_time += traci.simulation.getCurrentTime()/1000
    e_time = s_time + duration

    while traci.simulation.getMinExpectedNumber() > 0:
        cur_step = traci.simulation.getCurrentTime()/1000

        if cur_step == s_time:
            for i in closed_roads:
                traci.edge.setMaxSpeed(i, 0.1)

        if cur_step == e_time:
            for seq, rid in enumerate(closed_roads):
                traci.edge.setMaxSpeed(rid, pre_sp_lim[seq])

        traci.simulationStep()
    traci.close()
    sys.stdout.flush()
Пример #12
0
def run():
    """execute the TraCI control loop"""
    traci.init(PORT)
    programPointer = len(PROGRAM) - 1
    step = 0
    while traci.simulation.getMinExpectedNumber() > 0:
        traci.simulationStep()
        programPointer = min(programPointer + 1, len(PROGRAM) - 1)
        numPriorityVehicles = traci.inductionloop.getLastStepVehicleNumber("0")
        if numPriorityVehicles > 0:
            if programPointer == len(PROGRAM) - 1:
                # we are in the WEGREEN phase. start the priority phase
                # sequence
                programPointer = 0
            elif PROGRAM[programPointer] != WEYELLOW:
                # horizontal traffic is already stopped. restart priority phase
                # sequence at green
                programPointer = 3
            else:
                # we are in the WEYELLOW phase. continue sequence
                pass
        traci.trafficlights.setRedYellowGreenState(
            "0", PROGRAM[programPointer])
        step += 1
    traci.close()
    sys.stdout.flush()
Пример #13
0
def run():
	traci.init(int(PORT))
	step = 0
	while traci.simulation.getMinExpectedNumber() > 0:
		traci.simulationStep()
		step += 1
	traci.close()
Пример #14
0
def traciSimulation(port):
    '''
    Execute the TraCI control loop on the SUMO simulation.
    :param port:    The port used for communicating with your sumo instance
    :return:        The end second time of the simulation
    '''
    try:
        # Init the TraCI server
        traci.init(port)

        # TraCI runs the simulation step by step
        step = 0
        while traci.simulation.getMinExpectedNumber() > 0:
            traci.simulationStep()
            step += 1
    except traci.TraCIException as ex:
        logger.fatal("Exception in simulation step %d: %s" % (step, ex.message))
        return -1
    except traci.FatalTraCIError as ex:
        logger.fatal("Fatal error in simulation step %d: %s" % (step, ex.message))
        return -1
    else:
        return step + 1
    finally:
        # Close the TraCI server
        traci.close()
Пример #15
0
    def beginEvaluate(self):
        """
        Given the parameters during initialization, we run the simulator to get the fitness
        using port num to identify a connection
        """
        traci.init(self.portNum, 10, "localhost", str(self.portNum))
        #traverse all the traffic lights
        for i in xrange(len(self.trafficLightIdList)):
            #traverse all the traffic lights
            tlsLogicList = traci.trafficlights.getCompleteRedYellowGreenDefinition(self.trafficLightIdList[i])
            #One traffic light has only one phase list now
            tlsLogicList = tlsLogicList[0]
            #each traffic light has several phases
            phaseList = []
            #traverse all the phase
            for j in xrange(len(tlsLogicList._phases)):
#                 print self.individual.genes[i].times[j]
                phaseList.append(traci.trafficlights.Phase(self.individual.genes[i].times[j], self.individual.genes[i].times[j], self.individual.genes[i].times[j], tlsLogicList._phases[j]._phaseDef))
            tlsLogicList._phases = phaseList
            traci.trafficlights.setCompleteRedYellowGreenDefinition(self.trafficLightIdList[i], tlsLogicList)

        totalNumPassed = 0
        for _ in xrange(600):
            traci.simulationStep()
            totalNumPassed = totalNumPassed + traci.simulation.getArrivedNumber()
        traci.close()
        self.fitness = totalNumPassed
        return totalNumPassed 
Пример #16
0
def run(run_time):
    ## execute the TraCI control loop
    traci.init(PORT)
    programPointer = 0 # initiates at start # len(PROGRAM) - 1 # initiates at end
    step = 0
    flow_count = 0
    first_car = True
    prev_veh_id = ' '
    pointer_offset = 0
    car_speeds = []
    

    while traci.simulation.getMinExpectedNumber() > 0 and step <= run_time*(1/step_length): 
        traci.simulationStep() # advance a simulation step

        programPointer = int(math.floor(step/(int(1/step_length))))%len(PROGRAM) - pointer_offset 

        sensor_data = traci.inductionloop.getVehicleData("sensor")

        if len(sensor_data) != 0:
            flow_increment,prev_veh_id = flowCount([sensor_data],["sensor"],prev_veh_id)
            car_speeds.append(traci.vehicle.getSpeed(sensor_data[0][0]))
            flow_count += flow_increment
            if first_car: #if its the first car, record the time that it comes in
                first_time = sensor_data[0][2]
                print first_time
                first_car = False

        if step < 600: #24960, let queue accumulate
            traci.trafficlights.setRedYellowGreenState("0", ALLRED)
        else:
            traci.trafficlights.setRedYellowGreenState("0",PROGRAM[programPointer])


        
        step  += 1
        #print str(step)
   
    print "\n \n"
    print "-------------------------------------------------------- \n"
    print "Total number of cars that have passed: " + str(flow_count)
    tau = np.diff(leaving_times)
    print "Total throughput extrapolated to 1hr: " + str(flow_count*(3600/(run_time-first_time)))
    print "Average car speed: " + str(np.mean(car_speeds))



    print "Max Theoretical throughput: " + str(3600/min(min(tau)))
    print "Min Theoretical throughput: " + str(3600/max(max(tau)))
    

    # print tau
    # print "Mean tau: " + str(np.mean(tau)) + "\n"
    # print "Var tau: " + str(np.var(tau)) + "\n"
    # print "Standard Dev tau: " + str(np.std(tau)) +"\n"

    traci.close()
    sys.stdout.flush()
    return [np.mean(tau),np.var(tau),np.std(tau)]
Пример #17
0
def initialize_state():
    sumoProcessCmd = run_sumo(SUMO)
    traci.init(PORT)
    select_valid_edges()
    genetic.initialize()
    state.initialized = True
    traci.close()
    sumoProcessCmd.wait()
Пример #18
0
def run(run_time):
    ## execute the TraCI control loop
    traci.init(PORT)
    programPointer = 0 # initiates at start # len(PROGRAM) - 1 # initiates at end
    step = 0
    flow_count = 0
    first_car = True
    prev_veh_id = ' '
    leaving_times = []
    car_speeds = []
    

    while traci.simulation.getMinExpectedNumber() > 0 and step <= run_time*(1/step_length): 
        traci.simulationStep() # advance a simulation step

        programPointer = (step*int(1/step_length))%len(PROGRAM)

        sensor_data = traci.inductionloop.getVehicleData("sensor")

        if len(sensor_data) != 0:
            if first_car: #if its the first car, record the time that it comes in
                first_time = sensor_data[0][2]
                print first_time
                first_car = False


            veh_id = sensor_data[0][0]
            if veh_id != prev_veh_id: #if the vehicle coming in has a different id than the previous vehicle, count it towards total flow
                flow_count += 1
                car_speeds.append(traci.inductionloop.getLastStepMeanSpeed("sensor"))


            if sensor_data[0][3] != -1: #if the vehicle is leaving the sensor, record the time it left
                leaving_times.append(sensor_data[0][2])
            prev_veh_id = veh_id

        traci.trafficlights.setRedYellowGreenState("13", PROGRAM[programPointer])
        step  += 1
        #print str(step)
   
    print "\n \n"
    print "-------------------------------------------------------- \n"
    print "Total number of cars that have passed: " + str(flow_count)
    tau = np.diff(leaving_times)
    print "Total throughput extrapolated to 1hr: " + str(flow_count*(3600/(run_time-first_time)))


    print "Max Theoretical throughput: " + str(3600/tau_effective(max(car_speeds)))
    print "Min Theoretical throughput: " + str(3600/tau_effective(min(car_speeds)))
    print tau

    print "Mean tau: " + str(np.mean(tau)) + "\n"
    print "Var tau: " + str(np.var(tau)) + "\n"
    print "Standard Dev tau: " + str(np.std(tau)) +"\n"

    traci.close()
    sys.stdout.flush()
    return [np.mean(tau),np.var(tau),np.std(tau)]
Пример #19
0
def run():
    """execute the TraCI control loop"""
    step = 0
    while traci.simulation.getMinExpectedNumber() > 0:
        step += 1
        traci.simulationStep()

    traci.close()
    sys.stdout.flush()
Пример #20
0
 def finish_sim(self):
     print 'finish_sim'
     for demandobj in self.parent.demand.get_demandobjects():
         print '  finish_sim', demandobj.ident
         # demandobj.finish_sim(self)
     traci.close()
     print '    traci closed.'
     self.get_attrsman().status.set('success')
     return True
Пример #21
0
def runSingle(traciEndTime):
    step = 0
    sumoProcess = subprocess.Popen("%s -c used.sumocfg %s" % (sumoBinary, addOption), shell=True, stdout=sys.stdout)
    traci.init(PORT)
    while not step>traciEndTime:
        traci.simulationStep()
        step += 1
    print "Print ended at step %s" % (traci.simulation.getCurrentTime() / DELTA_T)
    traci.close()
    sys.stdout.flush()
Пример #22
0
def run():
    """execute the TraCI control loop"""
    traci.init(PORT)
    step = 0
    while traci.simulation.getMinExpectedNumber() > 0 and step < 100:
        traci.simulationStep()
        step += 1
        if step == 4:
            traci.trafficlights.setProgram("center", "0")
    traci.close()
    sys.stdout.flush()
Пример #23
0
 def end(self):
     signal.signal(signal.SIGALRM, _timeOutHandler)
     signal.alarm(_wait_in_s)
     try:
         traci.close()
         self.sumoProcess.wait()
     except Exception, exc:
         print exc
         self.sumoProcess.terminate()
         if "" in traci._connections:
             traci._connections[""].close()
             del traci._connections[""]
Пример #24
0
    def _generate_rerouters(self):
        """ Compute the rerouters for each parking lot for SUMO. """

        traci.start([sumolib.checkBinary('sumo'), '--no-step-log', '-n', self._sumo_net])

        distances = collections.defaultdict(dict)
        for parking_a in self._parking_areas.values():
            for parking_b in self._parking_areas.values():
                if parking_a['id'] == parking_b['id']:
                    continue
                if parking_a['edge'] == parking_b['edge']:
                    continue

                route = None
                try:
                    route = traci.simulation.findRoute(
                        parking_a['edge'], parking_b['edge'])
                except traci.exceptions.TraCIException:
                    route = None

                cost = None
                if route and route.edges:
                    cost = route.travelTime
                else:
                    cost = None

                distances[parking_a['id']][parking_b['id']] = cost

        traci.close()

        # select closest parking areas
        for pid, dists in distances.items():
            list_of_dist = [tuple(reversed(x)) for x in dists.items() if x[1] is not None]
            list_of_dist = sorted(list_of_dist)
            rerouters = [(pid, 0.0)]
            for distance, parking in list_of_dist:
                if len(rerouters) > self._num_alternatives:
                    break
                if distance > self._dist_alternatives:
                    break
                rerouters.append((parking, distance))

            if not list_of_dist:
                logging.fatal('Parking %s has 0 neighbours!', pid)

            self._sumo_rerouters[pid] = {
                'rid': pid,
                'edge': self._parking_areas[pid]['edge'],
                'rerouters': rerouters,
            }

        logging.debug('Computed %d rerouters.', len(self._sumo_rerouters.keys()))
Пример #25
0
    def step(self):
        # print "step", self.simtime,self.simtime_end,self.simtime >= self.simtime_end
        traci.simulationStep()
        self.process_step()

        self.get_logger().w(100.0*self.simtime/self.duration, key='progress')
        self.simtime += self.time_step
        if self.simtime >= self.simtime_end:
            print '    end of simulation reached, start closing traci', self.simtime
            traci.close()
            print '    traci closed'
            self.get_attrsman().status.set('success')
            return True
Пример #26
0
    def __inner_run__(self, output_file):
        if self._options.gui:
            sumoBinary = checkBinary('sumo-gui')
            self.__sumoProcess = subprocess.Popen(
                [sumoBinary,"-W",
                "-n", self.conf.network_file,
                "-r", self.conf.route_file,
                "--tripinfo-output", output_file,
                "--remote-port", str(self.conf.port),
                "--gui-settings-file", self.conf.gui_setting_file,
                "--step-length", "1",
                "-v", "true",
                "--time-to-teleport", "-1"],
                stdout = sys.stdout, stderr=sys.stderr)
            time.sleep(20)

        else:
            sumoBinary = checkBinary('sumo')
            self.__sumoProcess = subprocess.Popen(
                [sumoBinary, "-W",
                "-n", self.conf.network_file,
                "-r", self.conf.route_file,
                "--tripinfo-output", output_file,
                "--remote-port", str(self.conf.port),
                "--step-length", "1",
                "-v", "true",
                "--time-to-teleport", "-1"],
                stdout = sys.stdout, stderr=sys.stderr)
            time.sleep(20)

        traci.init(self.conf.port)
        self.initIteration()

        while True:
            traci.simulationStep()

            if traci.simulation.getMinExpectedNumber() <= 0:
                break

            self.stepProcess()

            if traci.simulation.getCurrentTime() % self.conf.short_term_sec == 0:
                self.can_change_lane_list = []
                self.want_chage_vehicle_list = []

        self.endIteration()
        traci.close()

        if self._options.gui:
            os.system('pkill sumo-gui')
        sys.stdout.flush()
Пример #27
0
def main(args):
    init_traci()
    step = -1
    while True:
        step += 1

        traci.simulationStep()

        if step == 140:
            traci.vehicle.resume('Stapler_00')

        if step == 160:
            traci.close()
            break
Пример #28
0
def runSingle(traciEndTime, sumoEndTime=None):
    step = 0
    opt = addOption
    if sumoEndTime is not None:
        opt += (" --end %s" % sumoEndTime)
    sumoProcess = subprocess.Popen(
        "%s -c sumo.sumocfg %s" % (sumoBinary, opt), shell=True, stdout=sys.stdout)
    traci.init(PORT)
    while not step > traciEndTime:
        traci.simulationStep()
        step += 1
    print("Print ended at step %s" % (traci.simulation.getCurrentTime() / DELTA_T))
    traci.close()
    sys.stdout.flush()
Пример #29
0
    def HandleShutdownEvent(self, event) :
        try :
            idlist = traci.vehicle.getIDList()
            for v in idlist : 
                traci.vehicle.remove(v)
        
            traci.close()
            sys.stdout.flush()

            self.SumoProcess.wait()
            self.__Logger.info('shut down')
        except :
            exctype, value =  sys.exc_info()[:2]
            self.__Logger.warn('shutdown failed with exception type %s; %s' %  (exctype, str(value)))
Пример #30
0
def sim():	
	step = 0
	while step < 86400:	
		traci.simulationStep()
		xy=[]
		vehicles = traci.vehicle.getIDList()
		for v in vehicles:
			x=112.96771+(traci.vehicle.getPosition(v)[0]+1509.33)/98838.1145
			y=28.193671+(traci.vehicle.getPosition(v)[1]-105.97)/106287.597
			xy.append([x,y])		
		return xy
		time.sleep(10)
		step += 10
	traci.close()
Пример #31
0
def run(isTesting):
    """execute the TraCI control loop"""
    step = 0
    YELLOW_PHASE = 4
    RED_PHASE = 2

    site4235_detector_delay = []
    site4235_LOOP_COUNT = 11
    for i in range(0, site4235_LOOP_COUNT + 1):  # initiliaze array of 0s
        site4235_detector_delay.append(0)
    lanesForPhases_s4235 = {  # key = phase, values = lanes with green lights
        0: [1, 2, 3, 9, 10, 11],  #A      
        1: [1, 2, 3, 4],  #B
        2: [6, 7]  #C
    }

    detector_delay_s4219 = []
    site4219_LOOP_COUNT = 21
    ignored_phases_s4219 = [
        20, 21, 22
    ]  # could automate this I guess? if not in dict TODO
    for i in range(0, site4219_LOOP_COUNT + 1):  # initiliaze array of 0s
        detector_delay_s4219.append(0)
    lanesForGroupsForPhases_s4219 = {  # key = phase, values = lanes with green lights
        0: [0, 1],  #A    
        1: [1, 6, 7],  #B
        2: [0, 2],  #C
        3: [3, 8],  #D
        4: [3, 4, 7],  #E
        5: [4, 5, 7],  #F
        6: [6, 2, 7]  #G
    }

    lanesForGroups_s4219 = {  # which lanes are grouped together, this is useful for finding when a lane group is no longer active
        0: [
            11, 12
        ],  # such that, a right turn lane can be replaced by oncoming traffic 
        1: [1, 2],
        2: [13, 14],
        3: [15, 16, 17],
        4: [7, 8],
        5: [9, 10],
        6: [3, 4],
        7: [5, 6],
        8: [18, 19]
    }
    conflictingGroups_s4219 = {  # TODO automate this from lanesForGroupsForPhases_s4219 (necessary?)
        0: [3, 4, 5, 6, 7, 8],
        1: [2, 3, 4, 5, 8],
        2: [1, 3, 4, 5, 8],
        3: [0, 1, 2, 3, 5, 6],
        4: [0, 1, 2, 6, 8],
        5: [0, 1, 2, 3, 6, 8],
        6: [0, 3, 4, 5, 8],
        7: [1, 8],
        8: [1, 2, 4, 5, 6, 7]
    }
    earliestDeadline_s4219 = 0
    earliestDeadlineGroup_s4219 = 0
    waitTime_s4219 = 0
    activeTraffic_s4219 = []
    for i in range(0, len(lanesForGroups_s4219)):  # initiliaze array of 99s
        activeTraffic_s4219.append(99)

    detector_delay_s4220 = []
    site4220_LOOP_COUNT = 15
    ignored_phases_s4220 = [
        3, 8, 11
    ]  # could automate this I guess? if not in dict TODO
    for i in range(0, site4220_LOOP_COUNT + 1):  # initiliaze array of -1s
        detector_delay_s4220.append(0)
    lanesForGroupsForPhases_s4220 = {  # key = phase, values = lanes with green lights
        0: [1, 5],  #A    
        1: [5, 6, 0],  #B
        2: [1, 2],  #C
        3: [3, 4],  #D
        4: [2, 6]  #E
    }

    lanesForGroups_s4220 = {  # which lanes are grouped together, this is useful for finding when a lane group is no longer active
        0: [1, 2],
        1: [4, 5, 6],
        2: [7],
        3: [9],
        4: [10],
        5: [12, 13, 14],
        6: [15]
    }
    conflictingGroups_s4220 = {  # TODO automate this from lanesForGroupsForPhases_s4220 (necessary?)
        0: [1, 4],
        1: [0, 6, 4, 3],
        2: [5, 4, 3],
        3: [0, 1, 2, 5, 6],
        4: [0, 1, 2, 5, 6],
        5: [2, 3, 4],
        6: [2, 3, 4, 5]
    }
    earliestDeadline_s4220 = 0
    earliestDeadlineGroup_s4220 = 0
    waitTime_s4220 = 0
    activeTraffic_s4220 = []
    for i in range(0, len(lanesForGroups_s4220)):  # initiliaze array of 99s
        activeTraffic_s4220.append(99)
    next_phase_s4220 = 0

    detector_delay_s4221 = []
    site4221_LOOP_COUNT = 18
    ignored_phases_s4221 = [
        6, 10, 14
    ]  # could automate this I guess? if not in dict TODO
    for i in range(0, site4221_LOOP_COUNT + 1):  # initiliaze array of -1s
        detector_delay_s4221.append(0)
    lanesForGroupsForPhases_s4221 = {  # key = phase, values = lanes with green lights
        0: [3, 7],  #A    
        1: [3, 4],  #B
        2: [7, 8, 0],  #C
        3: [1, 2, 0],  #D
        4: [5, 6],  #E
        5: [4, 8, 0]  #f
    }

    lanesForGroups_s4221 = {  # which lanes are grouped together, this is useful for finding when a lane group is no longer active
        0: [1, 2],
        1: [3],
        2: [4, 5],
        3: [7, 8],
        4: [9],
        5: [11, 12],
        6: [13],
        7: [15, 16],
        8: [17, 18]
    }
    conflictingGroups_s4221 = {  # TODO automate this from lanesForGroupsForPhases_s4221 (necessary?)
        0: [3, 6],
        1: [3, 4, 6, 7, 8],
        2: [3, 4, 5, 7, 8],
        3: [0, 1, 2, 5, 6, 8],
        4: [1, 2, 5, 6, 7],
        5: [2, 3, 4, 7, 8],
        6: [0, 1, 2, 3, 4, 7, 8],
        7: [1, 2, 4, 5, 6],
        8: [1, 2, 3, 5, 6]
    }
    earliestDeadline_s4221 = 0
    earliestDeadlineGroup_s4221 = 0
    waitTime_s4221 = 0
    activeTraffic_s4221 = []
    for i in range(0, len(lanesForGroups_s4221)):  # initiliaze array of 99s
        activeTraffic_s4221.append(99)
    next_phase_s4221 = 0

    MINIMUM_TRAFFIC_ACTIVITY = 3
    traci.trafficlight.setPhase("5861321343", 0)

    #RL stuff
    if isTesting == "1":
        e = 0.0
    else:
        e = 0.5
    rng = str(datetime.datetime.now().time())[6:8]
    random.seed(rng)
    stateActionValuesFile = open("stateActionValues.csv", "r")
    stateActionValues = stateActionValuesFile.readlines()
    stateActionValuesFile.close()
    saveStateActions = open("stateActions.csv", "w")
    takeMove = True
    transitionCounter_s4219 = 0
    currentActivePhase = traci.trafficlight.getPhase(
        "cluster_25977365_314059191_314060044_314061754_314061758_314062509_314062525"
    )
    transition_s2419 = chr(65 + currentActivePhase) + "-" + chr(
        65 + currentActivePhase) + "-1"  # eg. A-A-1
    move = currentActivePhase

    while step <= 600:
        traci.simulationStep()
        # add in other traffic lights
        #static edf algo
        # ----------------------------------------------------------------------SITE 4221--------------------------------------------------------------------------------------------------
        phase_s4221 = traci.trafficlight.getPhase(
            "cluster_25953432_313863435_313863521_314053282"
        )  # phase indexing starts at 0

        if (phase_s4221 in lanesForGroupsForPhases_s4221.keys()
            ):  # if not a transition phase
            waitTime_s4221 += 1  # current phase wait time
            transitionCounter_s4221 = 0

            for i in range(0, len(lanesForGroups_s4221)):
                if i in lanesForGroupsForPhases_s4221[phase_s4221]:
                    groupActivity = []
                    for lane in lanesForGroups_s4221[i]:
                        groupActivity.append(
                            int(
                                traci.inductionloop.getTimeSinceDetection(
                                    "site4221_" + str(lane))))
                        detector_delay_s4221[lane] = 0
                        activeTraffic_s4221[i] = min(groupActivity)
                else:
                    for lane in lanesForGroups_s4221[i]:
                        if int(
                                traci.inductionloop.getTimeSinceDetection(
                                    "site4221_" + str(lane))
                        ) == 0:  # if getLastStepVehicleNumber>0,
                            detector_delay_s4221[lane] = detector_delay_s4221[
                                lane] + 1  # increment loopDetectorDelay

            earliestDeadline_s4221 = detector_delay_s4221.index(
                max(detector_delay_s4221))

            switchPhase_s4221 = True
            for group in lanesForGroups_s4221:  # find which group the EDF lane belongs to
                if earliestDeadline_s4221 in lanesForGroups_s4221[group]:
                    earliestDeadlineGroup_s4221 = group

            for group in lanesForGroupsForPhases_s4221[
                    phase_s4221]:  # do not switch phase if any conflicting lane has traffic, all inactive groups automatically are 99
                if group != 0:
                    if activeTraffic_s4221[group] < MINIMUM_TRAFFIC_ACTIVITY:
                        switchPhase_s4221 = False

            #if earliestDeadlineGroup_s4221 in lanesForGroupsForPhases_s4221[phase_s4221]:
            #    switchPhase_s4221 = False
            if earliestDeadline_s4221 == 0:
                switchPhase_s4221 = False

            if waitTime_s4221 == 180:
                switchPhase_s4221 = True
            if switchPhase_s4221 == True:
                transitionCounter = 0
                # build new phase
                secondDeadline = -1
                secondaryDeadlineGroup_s4221 = earliestDeadlineGroup_s4221
                for i in range(
                        0, len(lanesForGroupsForPhases_s4221)
                ):  # find the secondary group to create new phase
                    if earliestDeadlineGroup_s4221 in lanesForGroupsForPhases_s4221[
                            i]:
                        for group in lanesForGroupsForPhases_s4221[i]:
                            if group != earliestDeadlineGroup_s4221:
                                for lane in lanesForGroups_s4221[group]:
                                    if detector_delay_s4221[
                                            lane] >= secondDeadline:
                                        secondDeadline = detector_delay_s4221[
                                            lane]
                                        secondaryDeadlineGroup_s4221 = group

                for i in range(0, len(lanesForGroupsForPhases_s4221)
                               ):  # find the [hase containing both groups
                    if earliestDeadlineGroup_s4221 in lanesForGroupsForPhases_s4221[
                            i]:
                        if secondaryDeadlineGroup_s4221 in lanesForGroupsForPhases_s4221[
                                i]:
                            next_phase_s4221 = i

                prev_phase_s4221 = phase_s4221
                transition = chr(65 + phase_s4221) + "-" + chr(
                    65 + next_phase_s4221) + "-1"  # eg. A-C-1
                if phase_s4221 != next_phase_s4221:

                    logics = traci.trafficlight.getAllProgramLogics(
                        "cluster_25953432_313863435_313863521_314053282")
                    names = str(logics[0].getPhases()).split("name='")
                    for i in range(1, len(names)):

                        if str(names[i].split("'")[0]) == str(transition):
                            transitionID = i - 1
                    traci.trafficlight.setPhase(
                        "cluster_25953432_313863435_313863521_314053282",
                        transitionID)  #change to transition

                    for group in lanesForGroups_s4221:  # find which group the EDF lane belongs to
                        if next_phase_s4221 in lanesForGroups_s4221[group]:
                            next_group_s4221 = group
                    leftTurn_phase = traci.trafficlight.getPhase("313863797")
                    if (
                            next_phase_s4221 == 0 or next_phase_s4221 == 1
                            or next_phase_s4221 == 4
                    ) and leftTurn_phase == 0:  # should it be green for 4? # if traffic is turning left and should not in next phase, switch to red light
                        traci.trafficlight.setPhase("313863797", 1)
                    elif (
                            next_phase_s4221 == 2 or next_phase_s4221 == 3
                            or next_phase_s4221 == 5
                    ) and leftTurn_phase == 2:  # if traffic can turn left, switch to green light
                        traci.trafficlight.setPhase("313863797", 3)

        else:  #   if active phase is transition phase
            switchPhase_s4221 = False
            waitTime_s4221 = 0
            for group in lanesForGroupsForPhases_s4221[
                    prev_phase_s4221]:  # reset the traffic activity level of each active phase group
                activeTraffic_s4221[group] = 99
            if transitionCounter_s4221 < YELLOW_PHASE:  # while lights are still yellow
                switchPhase_s4221 = False
                #for lane in lanesForGroups_s4221[group]:
                #   detector_delay_s4221[lane] = 0
            elif transitionCounter_s4221 == YELLOW_PHASE + RED_PHASE - 1:
                traci.trafficlight.setPhase(
                    "cluster_25953432_313863435_313863521_314053282",
                    next_phase_s4221)  #change to next phase
            transitionCounter_s4221 = transitionCounter_s4221 + 1

        # ----------------------------------------------------------------------SITE 4220--------------------------------------------------------------------------------------------------
        phase_s4220 = traci.trafficlight.getPhase(
            "gneJ41")  # phase indexing starts at 0

        if (phase_s4220 in lanesForGroupsForPhases_s4220.keys()
            ):  # if not a transition phase
            waitTime_s4220 += 1  # current phase wait time
            transitionCounter_s4220 = 0

            for i in range(0, len(lanesForGroups_s4220)):
                if i in lanesForGroupsForPhases_s4220[phase_s4220]:
                    groupActivity = []
                    for lane in lanesForGroups_s4220[i]:
                        groupActivity.append(
                            int(
                                traci.inductionloop.getTimeSinceDetection(
                                    "site4220_" + str(lane))))
                        detector_delay_s4220[lane] = 0
                        activeTraffic_s4220[i] = min(groupActivity)
                else:
                    for lane in lanesForGroups_s4220[i]:
                        if int(
                                traci.inductionloop.getTimeSinceDetection(
                                    "site4220_" + str(lane))
                        ) == 0:  # if getLastStepVehicleNumber>0,
                            detector_delay_s4220[lane] = detector_delay_s4220[
                                lane] + 1  # increment loopDetectorDelay

            earliestDeadline_s4220 = detector_delay_s4220.index(
                max(detector_delay_s4220))

            switchPhase_s4220 = True
            for group in lanesForGroups_s4220:  # find which group the EDF lane belongs to
                if earliestDeadline_s4220 in lanesForGroups_s4220[group]:
                    earliestDeadlineGroup_s4220 = group

            for group in lanesForGroupsForPhases_s4220[
                    phase_s4220]:  # do not switch phase if any conflicting lane has traffic, all inactive groups automatically are 99
                if activeTraffic_s4220[group] < MINIMUM_TRAFFIC_ACTIVITY:
                    switchPhase_s4220 = False

            #if earliestDeadlineGroup_s4220 in lanesForGroupsForPhases_s4220[phase_s4220]:
            #    switchPhase_s4220 = False
            if earliestDeadline_s4220 == 0:
                switchPhase_s4220 = False

            if waitTime_s4220 == 180:
                switchPhase_s4220 = True

            if switchPhase_s4220 == True:
                transitionCounter = 0
                # build new phase
                secondDeadline = -1
                secondaryDeadlineGroup_s4220 = earliestDeadlineGroup_s4220
                for i in range(
                        0, len(lanesForGroupsForPhases_s4220)
                ):  # find the secondary group to create new phase
                    if earliestDeadlineGroup_s4220 in lanesForGroupsForPhases_s4220[
                            i]:
                        for group in lanesForGroupsForPhases_s4220[i]:
                            if group != earliestDeadlineGroup_s4220:
                                for lane in lanesForGroups_s4220[group]:
                                    if detector_delay_s4220[
                                            lane] >= secondDeadline:
                                        secondDeadline = detector_delay_s4220[
                                            lane]
                                        secondaryDeadlineGroup_s4220 = group

                for i in range(0, len(lanesForGroupsForPhases_s4220)
                               ):  # find the [hase containing both groups
                    if earliestDeadlineGroup_s4220 in lanesForGroupsForPhases_s4220[
                            i]:
                        if secondaryDeadlineGroup_s4220 in lanesForGroupsForPhases_s4220[
                                i]:
                            next_phase_s4220 = i

                prev_phase_s4220 = phase_s4220
                transition_s4220 = chr(65 + phase_s4220) + "-" + chr(
                    65 + next_phase_s4220) + "-1"  # eg. A-C-1
                if phase_s4220 != next_phase_s4220:

                    logics = traci.trafficlight.getAllProgramLogics("gneJ41")
                    names = str(logics[0].getPhases()).split("name='")
                    for i in range(1, len(names)):

                        if str(names[i].split("'")[0]) == str(
                                transition_s4220):
                            transitionID = i - 1
                    traci.trafficlight.setPhase(
                        "gneJ41", transitionID)  #change to transition

                    for group in lanesForGroups_s4220:  # find which group the EDF lane belongs to
                        if next_phase_s4220 in lanesForGroups_s4220[group]:
                            next_group_s4220 = group

        else:  #   if active phase is transition phase
            switchPhase_s4220 = False
            waitTime_s4220 = 0
            for group in lanesForGroupsForPhases_s4220[
                    prev_phase_s4220]:  # reset the traffic activity level of each active phase group
                activeTraffic_s4220[group] = 99
            if transitionCounter_s4220 < YELLOW_PHASE:  # while lights are still yellow
                switchPhase_s4220 = False
                #for lane in lanesForGroups_s4220[group]:
                #   detector_delay_s4220[lane] = 0
            elif transitionCounter_s4220 == YELLOW_PHASE + RED_PHASE - 1:
                traci.trafficlight.setPhase(
                    "gneJ41", next_phase_s4220)  #change to next phase
            transitionCounter_s4220 = transitionCounter_s4220 + 1

        # ----------------------------------------------------------------------SITE 4219--------------------------------------------------------------------------------------------------
        #https://sumo.dlr.de/docs/Simulation/Output/Summary.html for each step reward
        # e1 output can be used if timesteps can be changed to 1 per step

        # Files: rl-runner, stateActionValues.xml, actions.xml, summary.xml, episodeStates.xml, updateTable.xml
        #States:
        # Loop detectors groups high/low (2^8)                              *
        # or time since last activation? 4s = 4^8
        # max expected demand group (9 options)                             *
        # (and 2nd max? (8 options))
        # Current phase (7 options)                                 *
        # -sum of exit lane detector_delays? would indicate the load on adjacent junctions
        # state space size = 4,194,000 or 16,384
        # can hard-code minimum activity time to reduce state size (but kind of goes against RL)

        #Actions:
        # Do nothing, transition to new phase (must stay in new phase for >=1s, transitoining to phase B will affect the reward for state B)
        #Rewards:
        # -vehicles halting
        # or -meanSpeedRelative,
        # not -sum(detector_delay_s4219) as this won't give total time spent waiting?
        #       during that state (divide by total steps between actions?)

        #Algorithm:
        # Expected return of next move = Sum(nextMaxGroup&&nextPhase)[loopDetectorsOff->loopDetectorsOn]
        # e-greedy policy for training: e = .05 = %chance of taking random move. 1-e = .95 = %chance of taking move with max expected reward
        currentPhase_s4219 = traci.trafficlight.getPhase(
            "cluster_25977365_314059191_314060044_314061754_314061758_314062509_314062525"
        )

        groupActivity_s4219 = []
        for i in range(0, len(lanesForGroups_s4219)):
            if i in lanesForGroupsForPhases_s4219[
                    move]:  # if group in current phase

                for lane in lanesForGroups_s4219[
                        i]:  # reset delay for each lane
                    detector_delay_s4219[lane] = 0

            else:
                for lane in lanesForGroups_s4219[i]:
                    if int(
                            traci.inductionloop.getTimeSinceDetection(
                                "site4219_" + str(lane))
                    ) == 0:  # if vehicle waiting on any lane in group
                        detector_delay_s4219[lane] += 1  # increment delay time

        for group in lanesForGroupsForPhases_s4219[move]:
            for lane in lanesForGroups_s4219[
                    group]:  #if getTimeSinceDetection > 0?
                groupActivity_s4219.append(
                    int(
                        traci.inductionloop.getTimeSinceDetection("site4219_" +
                                                                  str(lane))))

        carsFlowing = min(groupActivity_s4219)
        carsFlowing = min(carsFlowing, 9)

        earliestDeadline_s4219 = detector_delay_s4219.index(
            max(detector_delay_s4219))
        for group in lanesForGroups_s4219:
            if earliestDeadline_s4219 in lanesForGroups_s4219[group]:
                earliestDeadlineGroup_s4219 = group

        currentState = str(carsFlowing) + str(currentActivePhase) + str(
            earliestDeadlineGroup_s4219)

        if takeMove:  # when takeMove is true, the move is made on the same timestep
            #print("take move")
            transitionCounter_s4219 = 0
            if random.random() < e:  # take random move

                move = random.randint(0, 6)

            else:  # for the expected max demand group, find the values of all the phases for that group
                if step <= 300:
                    maxGroup = 4
                else:
                    maxGroup = 4
                # group 4 is currently max for both timesteps, ^this method needs to change (automating routeslist would help for this)
                # can this be more efficient? put stateActionValues into panda dataFrame >
                moveValue = -9999
                i = 0

                stateInDec = (int(currentState[0]) * 9 * 7) + (
                    int(currentState[1]) * 9) + int(
                        currentState[2],
                        9)  #convert the state to its row no equivalent
                #print(stateInDec)
                actions = stateActionValues[stateInDec].split(",", 8)[1:8]
                #print(actions)
                i = 0
                for action in actions:
                    actions[i] = float(action)
                    i += 1
                move = actions.index(max(actions))

            transition_s2419 = chr(65 + currentPhase_s4219) + "-" + chr(
                65 + move) + "-1"  # eg. A-C-1

            if move != currentPhase_s4219:
                logics = traci.trafficlight.getAllProgramLogics(
                    "cluster_25977365_314059191_314060044_314061754_314061758_314062509_314062525"
                )
                names = str(logics[0].getPhases()).split("name='")
                for i in range(1, len(names)):
                    if str(names[i].split("'")[0]) == str(transition_s2419):
                        transitionID_s4219 = i - 1

                traci.trafficlight.setPhase(
                    "cluster_25977365_314059191_314060044_314061754_314061758_314062509_314062525",
                    transitionID_s4219)  #change to transition

                takeMove = False  # do not take moves while transitioning phase

                leftTurn_phase = traci.trafficlight.getPhase("5861321343")
                if (
                        move == 0 or move == 2 or move == 3
                ) and leftTurn_phase == 0:  # if traffic is turning left and should not in next phase, switch to red light
                    traci.trafficlight.setPhase("5861321343", 1)
                elif (
                        move == 1 or move == 4 or move == 5 or move == 6
                ) and leftTurn_phase == 2:  # if traffic can turn left, switch to green light
                    traci.trafficlight.setPhase("5861321343", 3)

            #otherwise, do nothing. Reset duration of phase?
            #saveStateActions.write(transition_s2419 +","+ currentLoopsState +","+ str(currentActivePhase) +"\n")#TODO: add max group

        else:
            #need to account for left turn traffic light

            transitionCounter_s4219 += 1
            if transitionCounter_s4219 == YELLOW_PHASE + RED_PHASE:
                currentActivePhase = move
                takeMove = True
                traci.trafficlight.setPhase(
                    "cluster_25977365_314059191_314060044_314061754_314061758_314062509_314062525",
                    move)  #change to next phase

        currentState = str(carsFlowing) + str(currentActivePhase) + str(
            earliestDeadlineGroup_s4219)

        #in order: current phase, index of longest waiting group, loop states[8 bits], activity in current phase[1 bit], action
        #print(currentState +","+ str(move))

        saveStateActions.write(currentState + "," + str(move) +
                               "\n")  #TODO: add max group

        # ----------------------------------------------------------------------SITE 4235--------------------------------------------------------------------------------------------------
        site4235_phase = traci.trafficlight.getPhase(
            "cluster_1707799581_314056954_5931861577"
        )  # phase indexing starts at 0
        for i in range(1, site4235_LOOP_COUNT):  # for each loop detector
            if (i != 5) and (i != 8):  # ignore lanes 5 and 8
                if int(
                        traci.inductionloop.getLastStepVehicleNumber(
                            "site4235_" +
                            str(i))) > 0 or site4235_detector_delay[
                                i] > 0:  # if getLastStepVehicleNumber>0,
                    site4235_detector_delay[i] = site4235_detector_delay[
                        i] + 1  # increment loopDetectorDelay

        if (site4235_phase
                in lanesForPhases_s4235.keys()):  # if not a transition phase
            activeTraffic = 99

            for i in lanesForPhases_s4235[site4235_phase]:
                site4235_detector_delay[
                    i] = 0  # reset loopDetectorDelay for loops in current phase
                if i != 1 and i != 2 and i != 3:  # ignore non conflicting traffic
                    if int(
                            traci.inductionloop.getTimeSinceDetection(
                                "site4235_" + str(i))) < activeTraffic:
                        activeTraffic = int(
                            traci.inductionloop.getTimeSinceDetection(
                                "site4235_" + str(i)))

            if activeTraffic > MINIMUM_TRAFFIC_ACTIVITY:  # if no traffic through active lanes, switch to transition phase for max(loopDetectorDelay)
                activeTraffic = 0
                transitionCounter = 0
                site4235_prev_phase = site4235_phase
                earliestDeadline = site4235_detector_delay.index(
                    max(site4235_detector_delay))
                # build next phase
                if earliestDeadline == 9 or earliestDeadline == 10 or earliestDeadline == 11:  #this can be changed with lanesForGroups_s4235 (TODO)
                    site4235_next_phase = 0  #A
                    if site4235_phase == 1:
                        traci.trafficlight.setPhase(
                            "cluster_1707799581_314056954_5931861577",
                            7)  #change to B-A
                    elif site4235_phase == 2:
                        traci.trafficlight.setPhase(
                            "cluster_1707799581_314056954_5931861577",
                            11)  #change to C-A

                elif earliestDeadline == 4:  # loop detector no. 4
                    site4235_next_phase = 1  #B
                    if site4235_phase == 0:
                        traci.trafficlight.setPhase(
                            "cluster_1707799581_314056954_5931861577",
                            3)  #change to A-B
                    elif site4235_phase == 2:
                        traci.trafficlight.setPhase(
                            "cluster_1707799581_314056954_5931861577",
                            13)  #change to C-B

                elif earliestDeadline == 6 or earliestDeadline == 7:
                    site4235_next_phase = 2  #C
                    if site4235_phase == 0:
                        traci.trafficlight.setPhase(
                            "cluster_1707799581_314056954_5931861577",
                            5)  #change to A-C
                    elif site4235_phase == 1:
                        traci.trafficlight.setPhase(
                            "cluster_1707799581_314056954_5931861577",
                            9)  #change to B-C

                elif earliestDeadline == 1 or earliestDeadline == 2 or earliestDeadline == 3:
                    if site4235_detector_delay[4] > max(
                            site4235_detector_delay[9:11]
                    ):  # compare conflicting lanes
                        site4235_next_phase = 1  #B
                        if site4235_phase == 0:
                            traci.trafficlight.setPhase(
                                "cluster_1707799581_314056954_5931861577",
                                3)  #change to A-B
                        elif site4235_phase == 2:
                            traci.trafficlight.setPhase(
                                "cluster_1707799581_314056954_5931861577",
                                13)  #change to C-B

                    else:
                        site4235_next_phase = 0  #A
                        if site4235_phase == 1:
                            traci.trafficlight.setPhase(
                                "cluster_1707799581_314056954_5931861577",
                                7)  #change to B-A
                        elif site4235_phase == 2:
                            traci.trafficlight.setPhase(
                                "cluster_1707799581_314056954_5931861577",
                                11)  #change to C-A

        else:  #   if active phase is transition phase

            if transitionCounter < YELLOW_PHASE:  # while lights are still yellow
                for i in lanesForPhases_s4235[site4235_prev_phase]:
                    site4235_detector_delay[i] = 0
            elif transitionCounter == YELLOW_PHASE + RED_PHASE - 1:
                traci.trafficlight.setPhase(
                    "cluster_1707799581_314056954_5931861577",
                    site4235_next_phase)  #change to next phase
            transitionCounter = transitionCounter + 1
            #add for case where lights change with no traffic?
        step += 1

    traci.close()
    sys.stdout.flush()
Пример #32
0
 def close(self):
     if self.f is not None:
         self.f.close()
     traci.close()
Пример #33
0
def runQFS():
    stateVect = [[]]
    policyPi = []
    for i in range(0, 80, 1):
        policyPi.insert(i, random.randint(0, 5))
    QSA = np.random.rand(81, 6)
    currTLS = []
    Actions = [20, 25, 30, 20, 25, 30]
    avgTime = []
    numVehs = []
    avgTime.clear()
    numVehs.clear()
    EPSILON = 0.20
    ALPHA = 0.05
    GAMMA = 0.9
    step = 0
    stateNorth = 0
    stateSouth = 0
    stateEast = 0
    stateWest = 0
    currAction = 0
    reward = 0
    totWaittimeSoFar = 0
    curWaittime = 0
    totVehsSoFar = 0
    currVehsHere = 0
    while traci.simulation.getMinExpectedNumber() > 0:
        traci.simulationStep()
        # Determine the state
        stateNorth = traci.lane.getLastStepOccupancy('nc_0')
        stateSouth = traci.lane.getLastStepOccupancy('sc_0')
        stateEast = traci.lane.getLastStepOccupancy('ec_0')
        stateWest = traci.lane.getLastStepOccupancy('wc_0')
        tlsPhase = traci.trafficlight.getPhase("center")
        stateVect.insert(step, [getState(stateNorth), getState(stateEast), getState(stateSouth), getState(stateWest), getPhase(tlsPhase), 0, 0, 0])
        index = getStateIndex(stateVect[step])
        reward = getStateReturn(stateVect[step])
        # Take Action
        if random.uniform(0, 1) < EPSILON:
            currAction = random.randint(0, 5)
        else:
            currAction = np.argmax(QSA[index])
        # Storage
        stateVect[step][5] = index
        stateVect[step][6] = currAction
        stateVect[step][7] = reward
        # Control Simulation
        if currAction > 2:
            phaseToChange = 2
        else:
            phaseToChange = 0
        currTLS = traci.trafficlight.getCompleteRedYellowGreenDefinition("center")
        currTLS[0].phases[phaseToChange].duration = Actions[currAction]
        currTLS[0].phases[phaseToChange].minDur = Actions[currAction]
        currTLS[0].phases[phaseToChange].maxDur = Actions[currAction]
        traci.trafficlight.setCompleteRedYellowGreenDefinition("center", currTLS[0])
        # The Update
        if step > 0 and step % 75 == 0:
            episodeStates = [[]]
            index = 0
            A = 0
            R = 0
            for t in range(0, 74, 1):
                episodeStates.insert(t, stateVect[step-74+t])
            for t in range(0, 73, 1):
                S = episodeStates[t]
                R = S[7]
                A = S[6]
                index = S[5]
                Sprime = episodeStates[t+1]
                indexPrime = Sprime[5]
                QSA[index][A] = QSA[index][A] + ALPHA * (R + (GAMMA * max(QSA[indexPrime])) - QSA[index][A])
                policyPi[index] = np.argmax(QSA[index])

        step += 1
        curWaittime = traci.edge.getWaitingTime('nc') + traci.edge.getWaitingTime('ec') + traci.edge.getWaitingTime('sc') + traci.edge.getWaitingTime('wc')
        totWaittimeSoFar = totWaittimeSoFar + curWaittime
        avgTime.append(totWaittimeSoFar/step)

        currVehsHere = traci.simulation.getArrivedNumber()
        totVehsSoFar = totVehsSoFar + currVehsHere
        numVehs.append(totVehsSoFar)
    traci.close()
    sys.stdout.flush()
    return step, avgTime, numVehs
Пример #34
0
 def stop_sumo(self):
     if self.sumo_running:
         traci.close()
         sys.stdout.flush()
         self.sumo_running = False
Пример #35
0
    def simulation_startup(self):
        rospy.loginfo("Entered simulation_startup. num_vehicles: %d",
                      self.num_vehicles)
        rospy.set_param('done', False)
        sumo_startup = [
            'sumo-gui', '-c',
            self.dirname + '/graph_sumo/{}.sumocfg'.format(self.graph_name)
        ]
        rospy.loginfo(sumo_startup)
        # print 'Click Play button only on ensuring that the patrolling algorithm is running'
        traci.start(sumo_startup)
        rospy.loginfo("Simulation Startup Occured")
        #Click Play Button in the GUI, if GUI
        # pool = Pool(1)                  #CHECKING BATTERY LEVELS
        rospy.sleep(40)
        # p1 = pool.apply_async(self.battery_check_func())
        # print("Thread started")

        while traci.simulation.getTime() <= self.min_time:
            #print traci.simulation.getTime()
            vehicles = traci.vehicle.getIDList()
            rospy.loginfo("VEHICLES : %s", str(vehicles))
            for itr_robot_i in self.robot_ids:
                if self.updated[itr_robot_i]:
                    #print 'here', t.updated
                    #robot_numeral_id = robot_string_2_robot_num[itr_robot_i]
                    if itr_robot_i not in vehicles:
                        rospy.loginfo("Seq of routes of %s : %s", itr_robot_i,
                                      self.seq_of_routes[itr_robot_i])
                        route_id = itr_robot_i + str(random())
                        traci.route.add(routeID=route_id,
                                        edges=self.seq_of_routes[itr_robot_i])
                        traci.vehicle.add(vehID=itr_robot_i,
                                          routeID=route_id,
                                          typeID="type1")
                        #traci.vehicle.setColor(str(i),color_dict[i])
                        self.stopped_already[itr_robot_i] = False
                        rospy.loginfo("Added vehicle %s", str(itr_robot_i))
                    else:
                        e = traci.vehicle.getRoute(itr_robot_i)
                        if traci.vehicle.isStopped(itr_robot_i) and e[
                                -1] == self.seq_of_routes[itr_robot_i][0]:
                            traci.vehicle.resume(itr_robot_i)
                            traci.vehicle.setRoute(
                                vehID=itr_robot_i,
                                edgeList=self.seq_of_routes[itr_robot_i])
                            self.stopped_already[itr_robot_i] = False
                        else:
                            print("\n")
                print("\n******************************** Seq:  " +
                      itr_robot_i + "--" +
                      str(self.seq_of_routes[itr_robot_i]))
                self.updated[itr_robot_i] = False

            srvs = TaskDoneSrv()
            srvs.stamp = traci.simulation.getTime()
            srvs.node_id = []
            srvs.robot_id = []
            for ith_robot in self.robot_ids:
                vehicles = traci.vehicle.getIDList()
                if ith_robot in vehicles:
                    last_edge = traci.vehicle.getRoadID(ith_robot)
                    print("\nLast edge: " + str(last_edge))
                    if last_edge.find(':') == -1:
                        last_node = int(last_edge[:last_edge.find('to')])
                        print("Last node: " + str(last_node))
                        # if traci.vehicle.isStopped(str(i)) and not t.stopped_already[i]:
                        if traci.vehicle.isStopped(ith_robot):
                            stop_node = int(last_edge[last_edge.find('to') +
                                                      2:])
                            print("Stop node: " + str(stop_node))
                            srvs.node_id.append(str(stop_node))
                            srvs.robot_id.append(ith_robot)
                            # self.last_nodes[i] = stop_node
                            self.stopped_already[ith_robot] = True

                        elif not traci.vehicle.isStopped(
                                ith_robot
                        ) and self.last_nodes[ith_robot] != last_node:
                            total_len = traci.lane.getLength(last_edge + '_0')
                            cur_len = traci.vehicle.getLanePosition(ith_robot)
                            if cur_len < total_len / 2:
                                stop_pos = traci.lane.getLength(
                                    self.seq_of_routes[ith_robot][-1] + '_0')
                                traci.vehicle.setStop(
                                    vehID=ith_robot,
                                    edgeID=self.seq_of_routes[ith_robot][-1],
                                    pos=stop_pos,
                                    duration=2000.)
                                #msg.node_id.append(int(last_node))
                                srvs.node_id.append(str(last_node))
                                srvs.robot_id.append(ith_robot)
                                self.last_nodes[ith_robot] = last_node

            if len(srvs.node_id) > 0:
                rospy.loginfo_throttle(
                    1, 'Task done node_ids are ' + str(srvs.node_id))
                print(
                    self.sumo_to_pmm_proxy(srvs.stamp, srvs.node_id,
                                           srvs.robot_id))
                for vehicle_in_sumo in traci.vehicle.getIDList():
                    print(vehicle_in_sumo)
                    if vehicle_in_sumo not in self.robot_ids:
                        traci.vehicle.remove(vehicle_in_sumo, 0x03)
                        del self.seq_of_routes[vehicle_in_sumo]
                        del self.updated[vehicle_in_sumo]
                        del self.last_nodes[vehicle_in_sumo]
                        del self.stopped_already[vehicle_in_sumo]
                        self.num_vehicles = self.num_vehicles - 1

            if sum(self.stopped_already.values()) == 0:
                traci.simulationStep()

        rospy.logwarn('simulation startup exiting')
        rospy.set_param('done', True)
        traci.close()
Пример #36
0
def test(flags, configs, sumoConfig):
    from Env.Env import TL3x3Env
    from Agent.dqn import Trainer
    from Env.MultiEnv import GridEnv
    from utils import save_params, load_params, update_tensorboard

    # init test setting
    sumoBinary = checkBinary('sumo-gui')
    sumoCmd = [sumoBinary, "-c", sumoConfig]

    # setting the rl list
    tl_rl_list = configs['tl_rl_list']
    MAX_STEPS = configs['max_steps']
    reward = 0
    traci.start(sumoCmd)
    agent = Trainer(configs)
    # setting the replay
    if flags.replay_name is not None:
        agent.load_weights(flags.replay_name)
        configs = load_params(configs, flags.replay_name)
    env = TL3x3Env(configs)
    step = 0
    # state initialization
    state = env.get_state()
    # agent setting
    total_reward = 0
    arrived_vehicles = 0
    action_distribution = tuple()
    with torch.no_grad():
        while step < MAX_STEPS:

            action = agent.get_action(state)
            action_distribution += action
            env.step(action)  # action 적용함수
            for _ in range(20):  # 10초마다 행동 갱신
                env.collect_state()
                traci.simulationStep()
                step += 1

            traci.trafficlight.setRedYellowGreenState(tl_rl_list[0], 'y' * 28)
            for _ in range(5):
                traci.simulationStep()
                env.collect_state()
                step += 1

            reward = env.get_reward()
            next_state = env.get_state()
            # agent.save_replay(state, action, reward, next_state)
            state = next_state
            total_reward += reward
            step += 1
            if step == MAX_STEPS:
                done = True
            # agent.update(done) # no update in
            # loss += agent.get_loss()  # 총 loss
            arrived_vehicles += traci.simulation.getArrivedNumber(
            )  # throughput
            traci.simulationStep()
            # if step % 200 == 0:

        agent.target_update()
        traci.close()
        print('======== return: {} arrived number:{}'.format(
            total_reward, arrived_vehicles))
Пример #37
0
def run():
    """execute the TraCI control loop"""
    step = 0
    YELLOW_PHASE = 4
    RED_PHASE = 2

    site4235_detector_delay = []
    site4235_LOOP_COUNT = 11
    for i in range(0, site4235_LOOP_COUNT + 1):  # initiliaze array of 0s
        site4235_detector_delay.append(0)
    lanesForPhases_s4235 = {  # key = phase, values = lanes with green lights
        0: [1, 2, 3, 9, 10, 11],  #A      
        1: [1, 2, 3, 4],  #B
        2: [6, 7]  #C
    }

    detector_delay_s4219 = []
    site4219_LOOP_COUNT = 21
    ignored_phases_s4219 = [
        20, 21, 22
    ]  # could automate this I guess? if not in dict TODO
    for i in range(0, site4219_LOOP_COUNT + 1):  # initiliaze array of 0s
        detector_delay_s4219.append(0)
    lanesForGroupsForPhases_s4219 = {  # key = phase, values = lanes with green lights
        0: [0, 1],  #A    
        1: [1, 6, 7],  #B
        2: [0, 2],  #C
        3: [3, 8],  #D
        4: [3, 4, 7],  #E
        5: [4, 5, 7],  #F
        6: [6, 2, 7]  #G
    }

    lanesForGroups_s4219 = {  # which lanes are grouped together, this is useful for finding when a lane group is no longer active
        0: [
            11, 12
        ],  # such that, a right turn lane can be replaced by oncoming traffic 
        1: [1, 2],
        2: [13, 14],
        3: [15, 16, 17],
        4: [7, 8],
        5: [9, 10],
        6: [3, 4],
        7: [5, 6],
        8: [18, 19]
    }
    conflictingGroups_s4219 = {  # TODO automate this from lanesForGroupsForPhases_s4219 (necessary?)
        0: [3, 4, 5, 6, 7, 8],
        1: [2, 3, 4, 5, 8],
        2: [1, 3, 4, 5, 8],
        3: [0, 1, 2, 3, 5, 6],
        4: [0, 1, 2, 6, 8],
        5: [0, 1, 2, 3, 6, 8],
        6: [0, 3, 4, 5, 8],
        7: [1, 8],
        8: [1, 2, 4, 5, 6, 7]
    }
    earliestDeadline_s4219 = 0
    earliestDeadlineGroup_s4219 = 0
    waitTime_s4219 = 0
    activeTraffic_s4219 = []
    currentActivePhase_s4219 = 0
    for i in range(0, len(lanesForGroups_s4219)):  # initiliaze array of 99s
        activeTraffic_s4219.append(99)

    detector_delay_s4220 = []
    site4220_LOOP_COUNT = 15
    ignored_phases_s4220 = [
        3, 8, 11
    ]  # could automate this I guess? if not in dict TODO
    for i in range(0, site4220_LOOP_COUNT + 1):  # initiliaze array of -1s
        detector_delay_s4220.append(0)
    lanesForGroupsForPhases_s4220 = {  # key = phase, values = lanes with green lights
        0: [1, 5],  #A    
        1: [5, 6, 0],  #B
        2: [1, 2],  #C
        3: [3, 4],  #D
        4: [2, 6]  #E
    }

    lanesForGroups_s4220 = {  # which lanes are grouped together, this is useful for finding when a lane group is no longer active
        0: [1, 2],
        1: [4, 5, 6],
        2: [7],
        3: [9],
        4: [10],
        5: [12, 13, 14],
        6: [15]
    }
    conflictingGroups_s4220 = {  # TODO automate this from lanesForGroupsForPhases_s4220 (necessary?)
        0: [1, 4],
        1: [0, 6, 4, 3],
        2: [5, 4, 3],
        3: [0, 1, 2, 5, 6],
        4: [0, 1, 2, 5, 6],
        5: [2, 3, 4],
        6: [2, 3, 4, 5]
    }
    earliestDeadline_s4220 = 0
    earliestDeadlineGroup_s4220 = 0
    waitTime_s4220 = 0
    activeTraffic_s4220 = []
    for i in range(0, len(lanesForGroups_s4220)):  # initiliaze array of 99s
        activeTraffic_s4220.append(99)
    next_phase_s4220 = 0

    detector_delay_s4221 = []
    site4221_LOOP_COUNT = 18
    ignored_phases_s4221 = [
        6, 10, 14
    ]  # could automate this I guess? if not in dict TODO
    for i in range(0, site4221_LOOP_COUNT + 1):  # initiliaze array of -1s
        detector_delay_s4221.append(0)
    lanesForGroupsForPhases_s4221 = {  # key = phase, values = lanes with green lights
        0: [3, 7],  #A    
        1: [3, 4],  #B
        2: [7, 8, 0],  #C
        3: [1, 2, 0],  #D
        4: [5, 6],  #E
        5: [4, 8, 0]  #f
    }

    lanesForGroups_s4221 = {  # which lanes are grouped together, this is useful for finding when a lane group is no longer active
        0: [1, 2],
        1: [3],
        2: [4, 5],
        3: [7, 8],
        4: [9],
        5: [11, 12],
        6: [13],
        7: [15, 16],
        8: [17, 18]
    }
    conflictingGroups_s4221 = {  # TODO automate this from lanesForGroupsForPhases_s4221 (necessary?)
        0: [3, 6],
        1: [3, 4, 6, 7, 8],
        2: [3, 4, 5, 7, 8],
        3: [0, 1, 2, 5, 6, 8],
        4: [1, 2, 5, 6, 7],
        5: [2, 3, 4, 7, 8],
        6: [0, 1, 2, 3, 4, 7, 8],
        7: [1, 2, 4, 5, 6],
        8: [1, 2, 3, 5, 6]
    }
    earliestDeadline_s4221 = 0
    earliestDeadlineGroup_s4221 = 0
    waitTime_s4221 = 0
    activeTraffic_s4221 = []
    for i in range(0, len(lanesForGroups_s4221)):  # initiliaze array of 99s
        activeTraffic_s4221.append(99)
    next_phase_s4221 = 0

    MINIMUM_TRAFFIC_ACTIVITY = 3
    traci.trafficlight.setPhase("5861321343", 0)
    traci.trafficlight.setPhase("313863797", 0)

    while step <= 600:
        #while traci.simulation.getMinExpectedNumber() > 0:
        traci.simulationStep()
        # add in other traffic lights
        #static edf algo
        # ----------------------------------------------------------------------SITE 4221--------------------------------------------------------------------------------------------------
        phase_s4221 = traci.trafficlight.getPhase(
            "cluster_25953432_313863435_313863521_314053282"
        )  # phase indexing starts at 0

        if (phase_s4221 in lanesForGroupsForPhases_s4221.keys()
            ):  # if not a transition phase
            waitTime_s4221 += 1  # current phase wait time
            transitionCounter_s4221 = 0  # purely for transition phases

            for i in range(0, len(lanesForGroups_s4221)):
                if i in lanesForGroupsForPhases_s4221[phase_s4221]:
                    groupActivity = []
                    for lane in lanesForGroups_s4221[i]:
                        groupActivity.append(
                            int(
                                traci.inductionloop.getTimeSinceDetection(
                                    "site4221_" + str(lane))))
                        detector_delay_s4221[lane] = 0
                        activeTraffic_s4221[i] = min(groupActivity)
                else:
                    for lane in lanesForGroups_s4221[i]:
                        if int(
                                traci.inductionloop.getTimeSinceDetection(
                                    "site4221_" + str(lane))
                        ) == 0:  # if getLastStepVehicleNumber>0,
                            detector_delay_s4221[lane] = detector_delay_s4221[
                                lane] + 1  # increment loopDetectorDelay

            earliestDeadline_s4221 = detector_delay_s4221.index(
                max(detector_delay_s4221))

            switchPhase_s4221 = True
            for group in lanesForGroups_s4221:  # find which group the EDF lane belongs to
                if earliestDeadline_s4221 in lanesForGroups_s4221[group]:
                    earliestDeadlineGroup_s4221 = group

            for group in lanesForGroupsForPhases_s4221[
                    phase_s4221]:  # do not switch phase if any conflicting lane has traffic, all inactive groups automatically are 99
                if group != 0:
                    if activeTraffic_s4221[group] < MINIMUM_TRAFFIC_ACTIVITY:
                        switchPhase_s4221 = False

            #if earliestDeadlineGroup_s4221 in lanesForGroupsForPhases_s4221[phase_s4221]:
            #    switchPhase_s4221 = False
            if earliestDeadline_s4221 == 0:
                switchPhase_s4221 = False

            if waitTime_s4221 == 180:  #TODO: revise waiting time
                switchPhase_s4221 = True

            if switchPhase_s4221 == True:
                transitionCounter = 0
                # build new phase
                secondDeadline = -1
                secondaryDeadlineGroup_s4221 = earliestDeadlineGroup_s4221
                for i in range(
                        0, len(lanesForGroupsForPhases_s4221)
                ):  # find the secondary group to create new phase
                    if earliestDeadlineGroup_s4221 in lanesForGroupsForPhases_s4221[
                            i]:
                        for group in lanesForGroupsForPhases_s4221[i]:
                            if group != earliestDeadlineGroup_s4221:

                                for lane in lanesForGroups_s4221[group]:
                                    if detector_delay_s4221[
                                            lane] >= secondDeadline:
                                        secondDeadline = detector_delay_s4221[
                                            lane]
                                        secondaryDeadlineGroup_s4221 = group

                for i in range(0, len(lanesForGroupsForPhases_s4221)
                               ):  # find the [hase containing both groups
                    if earliestDeadlineGroup_s4221 in lanesForGroupsForPhases_s4221[
                            i]:
                        if secondaryDeadlineGroup_s4221 in lanesForGroupsForPhases_s4221[
                                i]:
                            next_phase_s4221 = i

                prev_phase_s4221 = phase_s4221
                transition = chr(65 + phase_s4221) + "-" + chr(
                    65 + next_phase_s4221) + "-1"  # eg. A-C-1
                if phase_s4221 != next_phase_s4221:

                    logics = traci.trafficlight.getAllProgramLogics(
                        "cluster_25953432_313863435_313863521_314053282")
                    names = str(logics[0].getPhases()).split("name='")
                    for i in range(1, len(names)):

                        if str(names[i].split("'")[0]) == str(transition):
                            transitionID = i - 1
                    traci.trafficlight.setPhase(
                        "cluster_25953432_313863435_313863521_314053282",
                        transitionID)  #change to transition
                    phase_s4221 = traci.trafficlight.getPhase(
                        "cluster_25953432_313863435_313863521_314053282")

                    leftTurn_phase = traci.trafficlight.getPhase("313863797")
                    if (
                            next_phase_s4221 == 0 or next_phase_s4221 == 1
                            or next_phase_s4221 == 4
                    ) and leftTurn_phase == 0:  # if traffic is turning left and should not in next phase, switch to red light
                        traci.trafficlight.setPhase("313863797", 1)
                    elif (
                            next_phase_s4221 == 2 or next_phase_s4221 == 3
                            or next_phase_s4221 == 5
                    ) and leftTurn_phase == 2:  # if traffic can turn left, switch to green light
                        traci.trafficlight.setPhase("313863797", 3)

        else:  #   if active phase is transition phase
            switchPhase_s4221 = False
            waitTime_s4221 = 0
            for i in range(0, len(lanesForGroups_s4221)):
                for lane in lanesForGroups_s4221[i]:
                    if int(
                            traci.inductionloop.getTimeSinceDetection(
                                "site4221_" + str(lane))
                    ) == 0:  # if getLastStepVehicleNumber>0,
                        detector_delay_s4221[lane] = detector_delay_s4221[
                            lane] + 1  # increment loopDetectorDelay

            if transitionCounter_s4221 == YELLOW_PHASE + RED_PHASE - 1:
                traci.trafficlight.setPhase(
                    "cluster_25953432_313863435_313863521_314053282",
                    next_phase_s4221)  #change to next phase
            transitionCounter_s4221 = transitionCounter_s4221 + 1

        # ----------------------------------------------------------------------SITE 4220--------------------------------------------------------------------------------------------------
        phase_s4220 = traci.trafficlight.getPhase(
            "gneJ41")  # phase indexing starts at 0

        if (phase_s4220 in lanesForGroupsForPhases_s4220.keys()
            ):  # if not a transition phase
            waitTime_s4220 += 1  # current phase wait time
            transitionCounter_s4220 = 0

            for i in range(0, len(lanesForGroups_s4220)):
                if i in lanesForGroupsForPhases_s4220[phase_s4220]:
                    groupActivity = []
                    for lane in lanesForGroups_s4220[i]:
                        groupActivity.append(
                            int(
                                traci.inductionloop.getTimeSinceDetection(
                                    "site4220_" + str(lane))))
                        detector_delay_s4220[lane] = 0
                    activeTraffic_s4220[i] = min(groupActivity)
                else:
                    for lane in lanesForGroups_s4220[i]:
                        if int(
                                traci.inductionloop.getTimeSinceDetection(
                                    "site4220_" + str(lane))
                        ) == 0:  # if getLastStepVehicleNumber>0,
                            detector_delay_s4220[lane] = detector_delay_s4220[
                                lane] + 1  # increment loopDetectorDelay

            earliestDeadline_s4220 = detector_delay_s4220.index(
                max(detector_delay_s4220))

            switchPhase_s4220 = True
            for group in lanesForGroups_s4220:  # find which group the EDF lane belongs to
                if earliestDeadline_s4220 in lanesForGroups_s4220[group]:
                    earliestDeadlineGroup_s4220 = group

            for group in lanesForGroupsForPhases_s4220[
                    phase_s4220]:  # do not switch phase if any conflicting lane has traffic, all inactive groups automatically are 99
                if activeTraffic_s4220[group] < MINIMUM_TRAFFIC_ACTIVITY:
                    switchPhase_s4220 = False

            #if earliestDeadlineGroup_s4220 in lanesForGroupsForPhases_s4220[phase_s4220]:
            #    switchPhase_s4220 = False
            if earliestDeadline_s4220 == 0:
                switchPhase_s4220 = False

            if waitTime_s4220 == 180:
                switchPhase_s4220 = True

            if switchPhase_s4220 == True:
                transitionCounter = 0
                # build new phase
                secondDeadline = -1
                secondaryDeadlineGroup_s4220 = earliestDeadlineGroup_s4220
                for i in range(
                        0, len(lanesForGroupsForPhases_s4220)
                ):  # find the secondary group to create new phase
                    if earliestDeadlineGroup_s4220 in lanesForGroupsForPhases_s4220[
                            i]:
                        for group in lanesForGroupsForPhases_s4220[i]:
                            if group != earliestDeadlineGroup_s4220:
                                for lane in lanesForGroups_s4220[group]:
                                    if detector_delay_s4220[
                                            lane] >= secondDeadline:
                                        secondDeadline = detector_delay_s4220[
                                            lane]
                                        secondaryDeadlineGroup_s4220 = group

                for i in range(0, len(lanesForGroupsForPhases_s4220)
                               ):  # find the [hase containing both groups
                    if earliestDeadlineGroup_s4220 in lanesForGroupsForPhases_s4220[
                            i]:
                        if secondaryDeadlineGroup_s4220 in lanesForGroupsForPhases_s4220[
                                i]:
                            next_phase_s4220 = i

                prev_phase_s4220 = phase_s4220
                transition = chr(65 + phase_s4220) + "-" + chr(
                    65 + next_phase_s4220) + "-1"  # eg. A-C-1
                if phase_s4220 != next_phase_s4220:

                    logics = traci.trafficlight.getAllProgramLogics("gneJ41")
                    names = str(logics[0].getPhases()).split("name='")
                    for i in range(1, len(names)):

                        if str(names[i].split("'")[0]) == str(transition):
                            transitionID = i - 1
                    traci.trafficlight.setPhase(
                        "gneJ41", transitionID)  #change to transition

                    for group in lanesForGroups_s4220:  # find which group the EDF lane belongs to
                        if next_phase_s4220 in lanesForGroups_s4220[group]:
                            next_group_s4220 = group

        else:  #   if active phase is transition phase
            switchPhase_s4220 = False
            waitTime_s4220 = 0
            for group in lanesForGroupsForPhases_s4220[
                    prev_phase_s4220]:  # reset the traffic activity level of each active phase group
                activeTraffic_s4220[group] = 99
            if transitionCounter_s4220 < YELLOW_PHASE:  # while lights are still yellow
                switchPhase_s4220 = False
                #for lane in lanesForGroups_s4220[group]:
                #   detector_delay_s4220[lane] = 0
            elif transitionCounter_s4220 == YELLOW_PHASE + RED_PHASE - 1:
                traci.trafficlight.setPhase(
                    "gneJ41", next_phase_s4220)  #change to next phase
            transitionCounter_s4220 = transitionCounter_s4220 + 1

        # ----------------------------------------------------------------------SITE 4219--------------------------------------------------------------------------------------------------
        phase_s4219 = traci.trafficlight.getPhase(
            "cluster_25977365_314059191_314060044_314061754_314061758_314062509_314062525"
        )  # phase indexing starts at 0

        if (phase_s4219 in lanesForGroupsForPhases_s4219.keys()
            ):  # if not a transition phase
            waitTime_s4219 += 1  # current phase wait time
            transitionCounter_s4219 = 0  # purely for transition phases

            for i in range(0, len(lanesForGroups_s4219)):
                if i in lanesForGroupsForPhases_s4219[
                        currentActivePhase_s4219]:
                    groupActivity = []
                    for lane in lanesForGroups_s4219[i]:
                        groupActivity.append(
                            int(
                                traci.inductionloop.getTimeSinceDetection(
                                    "site4219_" + str(lane))))
                        detector_delay_s4219[lane] = 0
                    activeTraffic_s4219[i] = min(groupActivity)
                else:
                    for lane in lanesForGroups_s4219[i]:
                        if int(
                                traci.inductionloop.getTimeSinceDetection(
                                    "site4219_" + str(lane))
                        ) == 0:  # if getLastStepVehicleNumber>0,
                            detector_delay_s4219[lane] = detector_delay_s4219[
                                lane] + 1  # increment loopDetectorDelay

            earliestDeadline_s4219 = detector_delay_s4219.index(
                max(detector_delay_s4219))

            switchPhase_s4219 = True
            for group in lanesForGroups_s4219:  # find which group the EDF lane belongs to
                if earliestDeadline_s4219 in lanesForGroups_s4219[group]:
                    earliestDeadlineGroup_s4219 = group

            for group in lanesForGroupsForPhases_s4219[
                    phase_s4219]:  # do not switch phase if any conflicting lane has traffic, all inactive groups automatically are 99
                if group != 7:
                    if activeTraffic_s4219[group] < MINIMUM_TRAFFIC_ACTIVITY:
                        switchPhase_s4219 = False

            #if earliestDeadlineGroup_s4219 in lanesForGroupsForPhases_s4219[phase_s4219]:
            #    switchPhase_s4219 = False
            if earliestDeadline_s4219 == 0:
                switchPhase_s4219 = False

            if waitTime_s4219 == 180:  #TODO: revise waiting time
                switchPhase_s4219 = True

            if switchPhase_s4219 == True:
                transitionCounter = 0
                # build new phase
                secondDeadline = -1
                secondaryDeadlineGroup_s4219 = earliestDeadlineGroup_s4219
                for i in range(
                        0, len(lanesForGroupsForPhases_s4219)
                ):  # find the secondary group to create new phase
                    if earliestDeadlineGroup_s4219 in lanesForGroupsForPhases_s4219[
                            i]:
                        for group in lanesForGroupsForPhases_s4219[i]:
                            if group != earliestDeadlineGroup_s4219:

                                for lane in lanesForGroups_s4219[group]:
                                    if detector_delay_s4219[
                                            lane] >= secondDeadline:
                                        secondDeadline = detector_delay_s4219[
                                            lane]
                                        secondaryDeadlineGroup_s4219 = group

                for i in range(0, len(lanesForGroupsForPhases_s4219)
                               ):  # find the [hase containing both groups
                    if earliestDeadlineGroup_s4219 in lanesForGroupsForPhases_s4219[
                            i]:
                        if secondaryDeadlineGroup_s4219 in lanesForGroupsForPhases_s4219[
                                i]:
                            next_phase_s4219 = i

                prev_phase_s4219 = phase_s4219
                transition = chr(65 + phase_s4219) + "-" + chr(
                    65 + next_phase_s4219) + "-1"  # eg. A-C-1
                if phase_s4219 != next_phase_s4219:

                    logics = traci.trafficlight.getAllProgramLogics(
                        "cluster_25977365_314059191_314060044_314061754_314061758_314062509_314062525"
                    )
                    names = str(logics[0].getPhases()).split("name='")
                    for i in range(1, len(names)):

                        if str(names[i].split("'")[0]) == str(transition):
                            transitionID = i - 1
                    traci.trafficlight.setPhase(
                        "cluster_25977365_314059191_314060044_314061754_314061758_314062509_314062525",
                        transitionID)  #change to transition
                    phase_s4219 = traci.trafficlight.getPhase(
                        "cluster_25977365_314059191_314060044_314061754_314061758_314062509_314062525"
                    )

                    leftTurn_phase = traci.trafficlight.getPhase("5861321343")
                    if (
                            next_phase_s4219 == 0 or next_phase_s4219 == 2
                            or next_phase_s4219 == 3
                    ) and leftTurn_phase == 0:  # if traffic is turning left and should not in next phase, switch to red light
                        traci.trafficlight.setPhase("5861321343", 1)
                    elif (
                            next_phase_s4219 == 1 or next_phase_s4219 == 4
                            or next_phase_s4219 == 5 or next_phase_s4219 == 6
                    ) and leftTurn_phase == 2:  # if traffic can turn left, switch to green light
                        traci.trafficlight.setPhase("5861321343", 3)

        else:  #   if active phase is transition phase
            switchPhase_s4219 = False
            waitTime_s4219 = 0
            for i in range(0, len(lanesForGroups_s4219)):
                for lane in lanesForGroups_s4219[i]:
                    if int(
                            traci.inductionloop.getTimeSinceDetection(
                                "site4219_" + str(lane))
                    ) == 0:  # if getLastStepVehicleNumber>0,
                        detector_delay_s4219[lane] = detector_delay_s4219[
                            lane] + 1  # increment loopDetectorDelay

            if transitionCounter_s4219 == YELLOW_PHASE + RED_PHASE - 1:
                currentActivePhase_s4219 = next_phase_s4219
                traci.trafficlight.setPhase(
                    "cluster_25977365_314059191_314060044_314061754_314061758_314062509_314062525",
                    next_phase_s4219)  #change to next phase
            transitionCounter_s4219 = transitionCounter_s4219 + 1

        # ----------------------------------------------------------------------SITE 4235--------------------------------------------------------------------------------------------------
        site4235_phase = traci.trafficlight.getPhase(
            "cluster_1707799581_314056954_5931861577"
        )  # phase indexing starts at 0
        for i in range(1, site4235_LOOP_COUNT):  # for each loop detector
            if (i != 5) and (i != 8):  # ignore lanes 5 and 8
                if int(
                        traci.inductionloop.getLastStepVehicleNumber(
                            "site4235_" +
                            str(i))) > 0 or site4235_detector_delay[
                                i] > 0:  # if getLastStepVehicleNumber>0,
                    site4235_detector_delay[i] = site4235_detector_delay[
                        i] + 1  # increment loopDetectorDelay

        if (site4235_phase
                in lanesForPhases_s4235.keys()):  # if not a transition phase
            activeTraffic = 99

            for i in lanesForPhases_s4235[site4235_phase]:
                site4235_detector_delay[
                    i] = 0  # reset loopDetectorDelay for loops in current phase
                if i != 1 and i != 2 and i != 3:  # ignore non conflicting traffic
                    if int(
                            traci.inductionloop.getTimeSinceDetection(
                                "site4235_" + str(i))) < activeTraffic:
                        activeTraffic = int(
                            traci.inductionloop.getTimeSinceDetection(
                                "site4235_" + str(i)))

            if activeTraffic > MINIMUM_TRAFFIC_ACTIVITY:  # if no traffic through active lanes, switch to transition phase for max(loopDetectorDelay)
                activeTraffic = 0
                transitionCounter = 0
                site4235_prev_phase = site4235_phase
                earliestDeadline = site4235_detector_delay.index(
                    max(site4235_detector_delay))
                # build next phase
                if earliestDeadline == 9 or earliestDeadline == 10 or earliestDeadline == 11:  #this can be changed with lanesForGroups_s4235 (TODO)
                    site4235_next_phase = 0  #A
                    if site4235_phase == 1:
                        traci.trafficlight.setPhase(
                            "cluster_1707799581_314056954_5931861577",
                            7)  #change to B-A
                    elif site4235_phase == 2:
                        traci.trafficlight.setPhase(
                            "cluster_1707799581_314056954_5931861577",
                            11)  #change to C-A

                elif earliestDeadline == 4:  # loop detector no. 4
                    site4235_next_phase = 1  #B
                    if site4235_phase == 0:
                        traci.trafficlight.setPhase(
                            "cluster_1707799581_314056954_5931861577",
                            3)  #change to A-B
                    elif site4235_phase == 2:
                        traci.trafficlight.setPhase(
                            "cluster_1707799581_314056954_5931861577",
                            13)  #change to C-B

                elif earliestDeadline == 6 or earliestDeadline == 7:
                    site4235_next_phase = 2  #C
                    if site4235_phase == 0:
                        traci.trafficlight.setPhase(
                            "cluster_1707799581_314056954_5931861577",
                            5)  #change to A-C
                    elif site4235_phase == 1:
                        traci.trafficlight.setPhase(
                            "cluster_1707799581_314056954_5931861577",
                            9)  #change to B-C

                elif earliestDeadline == 1 or earliestDeadline == 2 or earliestDeadline == 3:
                    if site4235_detector_delay[4] > max(
                            site4235_detector_delay[9:11]
                    ):  # compare conflicting lanes
                        site4235_next_phase = 1  #B
                        if site4235_phase == 0:
                            traci.trafficlight.setPhase(
                                "cluster_1707799581_314056954_5931861577",
                                3)  #change to A-B
                        elif site4235_phase == 2:
                            traci.trafficlight.setPhase(
                                "cluster_1707799581_314056954_5931861577",
                                13)  #change to C-B

                    else:
                        site4235_next_phase = 0  #A
                        if site4235_phase == 1:
                            traci.trafficlight.setPhase(
                                "cluster_1707799581_314056954_5931861577",
                                7)  #change to B-A
                        elif site4235_phase == 2:
                            traci.trafficlight.setPhase(
                                "cluster_1707799581_314056954_5931861577",
                                11)  #change to C-A

        else:  #   if active phase is transition phase

            if transitionCounter < YELLOW_PHASE:  # while lights are still yellow
                for i in lanesForPhases_s4235[site4235_prev_phase]:
                    site4235_detector_delay[i] = 0
            elif transitionCounter == YELLOW_PHASE + RED_PHASE - 1:
                traci.trafficlight.setPhase(
                    "cluster_1707799581_314056954_5931861577",
                    site4235_next_phase)  #change to next phase
            transitionCounter = transitionCounter + 1
            #add for case where lights change with no traffic?
        step += 1

    traci.close()
    sys.stdout.flush()
Пример #38
0
 def close(self):
     """Override in your subclass to perform any necessary cleanup.
     Environments will automatically close() themselves when
     garbage collected or when the program exits.
     """
     traci.close()
Пример #39
0
 def closer(self):
     #Meant for forced close ops.
     traci.close(False)
Пример #40
0
def runSingle(traciEndTime, viewRange, module, objID):
    seen1 = 0
    seen2 = 0
    step = 0
    sumoProcess = subprocess.Popen("%s -c sumo.sumocfg %s" %
                                   (sumoBinary, addOption),
                                   shell=True,
                                   stdout=sys.stdout)
    #    time.sleep(20)
    traci.init(PORT)
    traci.poi.add("poi", 400, 500, (1, 0, 0, 0))
    traci.polygon.add("poly", ((400, 400), (450, 400), (450, 400)),
                      (1, 0, 0, 0))
    subscribed = False
    while not step > traciEndTime:
        responses = traci.simulationStep()
        near1 = set()
        if objID in module.getContextSubscriptionResults():
            for v in module.getContextSubscriptionResults()[objID]:
                near1.add(v)
        vehs = traci.vehicle.getIDList()
        pos = {}
        for v in vehs:
            pos[v] = traci.vehicle.getPosition(v)
        shape = None
        egoPos = None
        if hasattr(module, "getPosition"):
            egoPos = module.getPosition(objID)
        elif hasattr(module, "getShape"):
            shape = module.getShape(objID)
        elif module == traci.edge:
            # it's a hack, I know,  but do we really need to introduce
            # edge.getShape?
            shape = traci.lane.getShape(objID + "_0")
        near2 = set()
        for v in pos:
            if egoPos:
                if math.sqrt(dist2(egoPos, pos[v])) < viewRange:
                    near2.add(v)
            if shape:
                lastP = shape[0]
                for p in shape[1:]:
                    if math.sqrt(distToSegmentSquared(pos[v], lastP,
                                                      p)) < viewRange:
                        near2.add(v)
                    lastP = p

        if not subscribed:
            module.subscribeContext(objID,
                                    traci.constants.CMD_GET_VEHICLE_VARIABLE,
                                    viewRange, [traci.constants.VAR_POSITION])
            subscribed = True
        else:
            seen1 += len(near1)
            seen2 += len(near2)
            for v in near1:
                if v not in near2:
                    print("timestep %s: %s is missing in subscribed vehicles" %
                          (step, v))
            for v in near2:
                if v not in near1:
                    print(
                        "timestep %s: %s is missing in surrounding vehicles" %
                        (step, v))

        step += 1
    print("Print ended at step %s" %
          (traci.simulation.getCurrentTime() / DELTA_T))
    traci.close()
    sumoProcess.wait()
    sys.stdout.flush()
    print("uncheck: seen %s vehicles via subscription, %s in surrounding" %
          (seen1, seen2))
    if seen1 == seen2:
        print("Ok: Subscription and computed are same")
    else:
        print("Error: subscribed number and computed number differ")
Пример #41
0
 def stop_sumo(self):
     if self.sumo_running:
         traci.close()
         self.sumo_running = False
Пример #42
0
def run(algorithm):
    """execute the TraCI control loop"""
    step = 0

    # if algorithm == 0: #hardcoded
    #     print("hardcoded")

    #     ##
    #     vehiclesPast = 0 #need to count like that cause otherwise it only checks per 10 secs
    #     #traci.trafficlight.setPhase("A", 2) #trial 1
    #     traci.trafficlight.setPhase("A", 0) #trial 2
    #     ##
    #     while traci.simulation.getMinExpectedNumber() > 0:
    #         #trial 1 (induction loops)
    #         # if traci.trafficlight.getPhase("A") == 2:
    #         #     # if there are more than 2 cars have passed the induction loop (thus waiting), make it green
    #         #     if traci.inductionloop.getLastStepVehicleNumber("nA1") > 0 or traci.inductionloop.getLastStepVehicleNumber("nA0") > 0:
    #         #         vehiclesPast += 1
    #         #     if vehiclesPast > 2:
    #         #         traci.trafficlight.setPhase("A", 0)
    #         #         vehiclesPast = 0
    #         #     else:
    #         #         traci.trafficlight.setPhase("A", 2)
    #         ##

    #         #trial 2 lane area detectors
    #         if traci.trafficlight.getPhase("A") == 0:
    #             if traci.lanearea.getLastStepHaltingNumber("wA0") > 2:
    #                  traci.trafficlight.setPhase("A", 2)
    #             else:
    #                  traci.trafficlight.setPhase("A", 0)

    #         traci.simulationStep()

    #         step += 1

    if algorithm == 1:  # q-learning
        print("q-learning")
        # create "q-table"
        qtable = create_qtable(18, 2)  # 6 states, 2 actions
        total_reward = 0
        state = get_state()
        epsilon = 0.9
        alpha = 0.01  # 1
        gamma = 0.01  # 0
        waiting_cars_array = []
        time_step = 0
        waiting_cars = 0

        while traci.simulation.getMinExpectedNumber() > 0:
            traci.trafficlight.setPhase("A", 2)

            action = choose_action(state, qtable, epsilon)
            if action == 0:
                traci.trafficlight.setPhase("A", 2)
            else:
                traci.trafficlight.setPhase("A", 0)

            for i in range(10):  # changing this makes difference

                traci.simulationStep()

            step += 10
            time_step += 1

            next_state = get_state()
            reward = calc_reward()
            total_reward += reward

            # to plot the total number of cars waiting for every 100 time steps
            if time_step < 10:
                waiting_cars += -1 * reward

            else:
                waiting_cars += -1 * reward
                waiting_cars_array.append(waiting_cars)
                waiting_cars = 0
                time_step = 0

            qtable = update_table(qtable, reward, state, action, alpha, gamma,
                                  next_state)
            # print(qtable)
            # print(reward)
            # qtable[state,action] = reward
            state = next_state
            epsilon -= 0.01  # this might be something else

        print("total reward: %i" % total_reward)
        waiting_cars_array = np.hstack(waiting_cars_array)
        plot(waiting_cars_array)
        # print(rewards)

    else:  # original
        total_reward = 0
        waiting_cars_array = []
        time_step = 0
        waiting_cars = 0

        while traci.simulation.getMinExpectedNumber() > 0:
            # traci.simulationStep()
            # step += 1
            for i in range(10):  # changing this makes difference

                traci.simulationStep()

            step += 10
            time_step += 1
            reward = calc_reward()
            # print("reward: %i" % reward)
            total_reward += reward

            # to plot the total number of cars waiting for every 100 time steps
            if time_step < 10:
                waiting_cars += -1 * reward

            else:
                waiting_cars += -1 * reward
                # print("waiting_cars %i" % waiting_cars)
                waiting_cars_array.append(waiting_cars)
                waiting_cars = 0
                time_step = 0

        print("total reward: %i" % total_reward)
        waiting_cars_array = np.hstack(waiting_cars_array)
        plot(waiting_cars_array)

    traci.close()
    sys.stdout.flush()
Пример #43
0
def run():
    global id2tls, id2car, edge2tls, tls2edges, e2oppoe

    traci.init(PORT)
    step = simulationStartTime

    Tls.traci = traci
    Car.traci = traci
    Tls.tls2ph2time = get_tls2duration()

    tlslist = traci.trafficlights.getIDList()
    if iprintinfo > 0: print '>>> tlslist\n', tlslist

    directory = 'outfile' + str(PORT)
    if not os.path.exists(directory):
        os.makedirs(directory)
    # fd=open(directory+'/tlslist.txt','w')
    for tls in tlslist:
        tmp = Tls(tls)
        tmp.setProgram('p1')
        tmp.setOutputDir(directory + '/')
        id2tls[tls] = tmp
        # fd.write(tls+'.txt\n')
    # fd.close()

    edge2tls = get_edge2tls()
    if iprintinfo > 1: print '>>> edge2tls', edge2tls
    tls2edges = get_tls2edges()
    if iprintinfo > 1: print '>>> tls2edges', tls2edges
    alledges = traci.edge.getIDList()
    for eid in alledges[:]:  # deep copy!
        if eid.startswith(":"):
            alledges.remove(eid)
        else:
            getoppositeedge(eid)
    Car.edge2tls = edge2tls
    Car.tls2edges = tls2edges
    Car.e2oppoe = e2oppoe
    Car.id2car = id2car
    tmpcar = None

    while step <= simulationEndTime:
        traci.simulationStep()
        step += 1
        print "\n>> -- step: ", step

        teleport = traci.simulation.getStartingTeleportIDList()
        for vid in teleport:
            if iprintstep >= 2: print('teleport=', teleport)
            id2car[vid].remove(step)

        try:
            deadlist = traci.simulation.getArrivedIDList()
            if iprintstep >= 2: print('deadlist=', deadlist)
            for vid in deadlist:
                id2car[vid].setDead(step)
            vnum = traci.vehicle.getIDCount()
            if iprintstep > 0: print('vnum=' + str(vnum))
        except:
            if iprintstep > 0: print('traci deadlist WRONG step=', step)

        newcars = traci.simulation.getDepartedIDList()
        if iprintstep >= 2: print('newcars=', newcars)
        for vid in newcars:
            tmp = Car(vid)
            tmp.subscribe(varlistroute)
            tmp.setStartTime(step)
            tmp.setOutputFile(directory + "/" + str(hash(vid) % numlog))
            id2car[vid] = tmp

        for tlsid in tlslist:  # all tls list
            id2tls[tlsid].updataPhase(step)

        for vid in traci.vehicle.getIDList():
            id2car[vid].process(step)
            lid, lpo, spd = id2car[vid].getLanePosSpeed()
            if lid not in lane2len.keys():
                lane2len[lid] = traci.lane.getLength(lid)
            if spd < 2 * Car.minSpeed and lpo > 100 and lane2len[
                    lid] - lpo < 100:  # candidate
                if lid not in lane2vq.keys():
                    lane2vq[lid] = []  # remdist, spd, vid
                lane2vq[lid].append([lane2len[lid] - lpo + Car.VLen, spd, vid])

        vp = "a1"
        for vid in traci.vehicle.getIDList():
            tmpcar = id2car[vid]
            tlsid = tmpcar.getTls()
            tls2 = ""  #tmpcar.get2ndTls()
            if tlsid != "":
                lid, lpo, spd = tmpcar.getLanePosSpeed()
                pred = id2tls[tlsid].getFuturePhaseSeq(step + 150)
                if iprintverb or vp == vid: print(tmpcar.id, tlsid, pred)
                if lid not in lane2vq.keys():
                    vq = []
                else:
                    vq = lane2vq[lid]
                    if iprintverb or vp == vid: print("Queue", lid, sorted(vq))
                if tls2 == "":
                    tmpcar.adjustSpeedGivenPhasePred(pred, vq)
                else:
                    pred = id2tls[tls2].getFuturePhaseSeq(step + 300)
                    tmpcar.adjustSpeedGivenPhasePred(pred, vq)

            if iprintverb or vp == vid:
                print(var_dic_to_str(tmpcar.getSubscriptionResults()))
                id2car[vid].set_iprint(1)

        for lid in lane2vq.keys():  # need to refresh queue len
            lane2vq[lid] = []

    traci.close()
    sys.stdout.flush()
Пример #44
0
def run(env):

    rou_curr= "12to"+str(random.choice([13]))
    env.reset(rou_curr)
    sumo_step=1.0
    bn=[0, 17, 30, 31, 32, 33]
    cr=0.0
    rl_step=1.0
    idle=np.zeros((36,1))
    v_idle=[[] for _ in range(36)]
    edge=[0]
    ga=[]
    gav=[]
    ss=[]
    prev_node=env.state
    while traci.simulation.getMinExpectedNumber()>0:

        traci.simulationStep()
        idle+=1
        for i in bn:
            idle[i]=0
        edge=traci.vehicle.getRoadID('veh0')
        if edge and (edge[0]!=':'):
            curr_node= edge.split('to')
            curr_node=int(curr_node[1])
        elif edge[0]==':':
            curr_node=edge[1:].split('_')
            curr_node=int(curr_node[0])
        env.state=curr_node

        # Action decision on new edge
        if prev_node!=curr_node:
            print(edge)
            print('p_node:',prev_node, 'c_node:',curr_node)
            print('Veh angle: ', traci.vehicle.getAngle('veh0'))
            rou_step=[]
            prev_reward=env.reward_out(idle, prev_node)[0]
            print('reward on prev step: ', prev_reward)
            v_idle[int(prev_node)].append(prev_reward.copy())

            avg_v_idl, max_v_idl, sd_v_idl, glo_v_idl, glo_max_v_idl, glo_sd_v_idl, glo_idl, glo_max_idl = eval_met(idle, v_idle,sumo_step, 36)
            print('global avg node visit idleness: ', glo_v_idl, '\nglobal max node visit idleness: ', glo_max_v_idl)
            print('global avg instant idleness: ', glo_idl, '\nglobal max instant idleness: ', glo_max_idl)
            gav.append(glo_v_idl)
            ga.append(glo_idl)
            ss.append(sumo_step)
            cr+=prev_reward
            acr=cr/sumo_step
            idle[int(prev_node)]=0
            print(idle.reshape(6,6))
            lane = traci.vehicle.getLaneID('veh0')
            links = traci.lane.getLinks(lane, extended=False)
            s_lanes = [i[0] for i in links]
            n_edges=[]
            n_nodes=[]
            for nodes in s_lanes:
                n_edges.append(nodes.split('_')[0])
            for edges in n_edges:
                n_nodes.append(int(edges.split('to')[1]))
            print(n_edges, n_nodes)
            env.set_actionSpace(n_edges)
            action=env.sample()
            # next_state, reward, action = env.step(action, idle)
            #print('action: ', action, 'next_state: ', next_state, 'reward: ', reward)
            rou_step.append(rou_curr)
            rou_step.append(action)
            print('next_route: ', rou_step)
            print(':::::::::::::to next node::::::::::::::::')
            traci.vehicle.setRoute(vehID = 'veh0', edgeList = rou_step)
            rou_curr=action

        prev_node=curr_node
        sumo_step+=1
        if sumo_step ==20000:
            break
    plt.plot(ss,ga, "-r", linewidth=0.6,label="Global Average Idleness")
    plt.plot(ss,gav, "-b", linewidth=4, label="Global Average Node Visit Idleness")
    plt.legend(loc="lower right")
    up=np.ceil(max(ga)/20)*20
    plt.yticks(np.linspace(0,up,(up/20)+1, endpoint=True))
    plt.xlabel('Unit Time')
    plt.ylabel('Idleness')
    plt.title('Performance')
    traci.close()
    plt.show()
    sys.stdout.flush()
Пример #45
0
    def run_one_episode_training(self, episode, total_episodes):

        # gen random route.
        simu_type = genorator.gen_route(episode, is_random = True)
        
        print('Training on random route with type: ', self.get_simu_type_str(simu_type))
        self._epsilon = 1.0 - (episode / constants.total_ep_for_epislon)								# setup epsilon
        traci.start(self._sumoCmd)														                # then, start sumo
        
        # INIT some vars:
        self._steps = 0			
        self._sum_intersection_queue = 0		# increases every step/seconds
        tot_neg_reward = 0						# total negative reward
        pre_wait_time = 0						# 

        # INIT my vars:
        action = 0						        # initial action
        old_action = 0
        state = self._get_state(self.I)
        action_count = [0,0]                    # cal percent of actions
        good_bad_count = [0,0]                  #   count good bad actions

        # run 1 simulation (maxsteps)
        while self._steps < self._max_steps:
            # reset current_wait_time:
            current_wait_time = 0

            # select action (select index of action, then edit action_time)
            action = self._choose_action(state)
            # just count numb of taken actions.
            action_count[action] += 1

            #  ================================ Take action ====================================================================
            if self._steps != 0 and old_action != action:
                # just set traffic_light in sumo
                self._set_yellow_phase(old_action)
                
                # ver 1: fixed yellow.
                # current_wait_time = self._simulate(self._yellow_duration)

                # ver 2: dynamic yellow.
                yellow_duration_new = self.cal_yellow_duration(old_action)
                current_wait_time = self._simulate(yellow_duration_new)     

            self._set_green_phase(action)
            current_wait_time = self._simulate(self._green_duration)
            #  =================================================================================================================

            # get next_state and reward
            next_state = self._get_state(self.I)

            reward = pre_wait_time - current_wait_time
            if reward < 0:
                tot_neg_reward += reward
                good_bad_count[1] += 1
            else:
                good_bad_count[0] += 1
            
            # save tuple:			
            self._memory.add_sample((state, action, reward, next_state))
            
            # training:
            self._replay()

            # reassign:
            pre_wait_time = current_wait_time
            state = next_state
            old_action = action

            # print
            eval_this_action = 'Good action' if (reward>=0) else 'Bad Action'
            print('step: ', self._steps, '|',self._max_steps,' || action: ', self.get_action_name(action), ': ',eval_this_action,' || negative reward: ', tot_neg_reward)


        print('percent of actions: ', np.array(action_count)/sum(action_count))
        print("Total negative reward: {}, Eps: {}".format(tot_neg_reward, self._epsilon))
        
        # append data
        self._save_stats(simu_type,tot_neg_reward)		
        
        # save array to disk:
        self.save_all_arrays()

        # close gui.
        traci.close(wait = False)
                reward2 = traci.edge.getLastStepHaltingNumber(
                    '2si') + traci.edge.getLastStepHaltingNumber('1si')
                for i in range(10):
                    stepz += 1
                    traci.trafficlight.setPhase('cluster_1933306735_2322926274_2322926295_2322926370', 0)
                    reward1 += traci.edge.getLastStepVehicleNumber(
                        '4si') + traci.edge.getLastStepVehicleNumber('3si')
                    reward2 += traci.edge.getLastStepHaltingNumber(
                        '2si') + traci.edge.getLastStepHaltingNumber('1si')
                    waiting_time += (traci.edge.getLastStepHaltingNumber('1si') + traci.edge.getLastStepHaltingNumber(
                        '2si') + traci.edge.getLastStepHaltingNumber('3si') + traci.edge.getLastStepHaltingNumber('4si'))
                    traci.simulationStep()

            new_state = sumoInt.getState()
            reward = reward1 - reward2
            agent.remember(state, action, reward, new_state, False)
            # Randomly Draw 32 samples and train the neural network by RMS Prop algorithm
            if(len(agent.memory) > batch_size):
                agent.replay(batch_size)

        mem = agent.memory[-1]
        del agent.memory[-1]
        agent.memory.append((mem[0], mem[1], reward, mem[3], True))
        log.write('episode - ' + str(e) + ', total waiting time - ' + str(waiting_time) + ', number of cycles - ' + str(num_cycles) + '\n')
        log.close()
        print('episode - ' + str(e) + ' total waiting time - ' + str(waiting_time) + ' number of cycles - ' + str(num_cycles))
        agent.save('reinf_traf_control_' + str(e) + '.h5')
        traci.close(wait=False)

sys.stdout.flush()
Пример #47
0
    async def run(self):
        # try:
        emission_classes = list(self.veh_dist.keys())
        emission_weights = list(self.veh_dist.values())
        box_ids = list(bremicker_boxes.keys())

        detector_steps = [step * 600 for step in range(0, self.df_traffic.shape[0])]
        self.df_traffic = self.df_traffic.fillna(0)
        self.df_traffic = self.df_traffic.reset_index()
        self.df_traffic = self.df_traffic[box_ids]
        self.df_traffic.index = pd.Series(self.df_traffic.index).apply(lambda x: x * 600)
        print('traffic:', self.df_traffic)
        print('detector steps:', detector_steps)
        current_step = 0
        detected_vehicles = {}
        while traci.simulation.getMinExpectedNumber() > 0:
            if current_step > (self.timesteps * 1.2):
                print("[SUMO] Simulation took to long. Aborting after %s simulated seconds" % str(current_step))
                break

            for box_id in box_ids:
                if box_id in detected_vehicles:
                    detected_vehicles[box_id] += traci.inductionloop.getLastStepVehicleNumber("det_%s_0" % box_id) + traci.inductionloop.getLastStepVehicleNumber("det_%s_1" % box_id)
                else:
                    detected_vehicles[box_id] = traci.inductionloop.getLastStepVehicleNumber("det_%s_0" % box_id) + traci.inductionloop.getLastStepVehicleNumber("det_%s_1" % box_id)
            # print(detected_vehicles)
            traci.simulationStep()
            if current_step in detector_steps:
                step = detector_steps.pop(0)
                for box_id in box_ids:
                    max_vehicles = self.df_traffic[box_id].max()
                    vehicle_threshold = self.df_traffic.loc[step][box_id]
                    needed_vehicles = detected_vehicles[box_id] - vehicle_threshold
                    veh_ids = list(traci.inductionloop.getLastStepVehicleIDs("det_%s_0" % box_id))
                    veh_ids += list(traci.inductionloop.getLastStepVehicleIDs("det_%s_1" % box_id))
                    veh_ids = list(dict.fromkeys(veh_ids))
                    loaded_routes = traci.route.getIDList()
                    print('detected vehicles until now', detected_vehicles)
                    print('current step: ', step)
                    print('vehicle number too much/low: needed vehicles: %s' % str(needed_vehicles))

                    # while needed_vehicles > 0:
                    #     #remove vehicles
                    #     veh = veh_ids.pop(0)
                    #     # print("[TRACI] removed vehicle %s" % veh)
                    #     traci.vehicle.remove(veh)
                    #     needed_vehicles -= 1

                    while needed_vehicles < 0:
                        # add vehicles
                        veh = veh_ids.pop(0) if len(veh_ids) != 0 else randrange(1, max_vehicles + 1, 1)
                        route_id = traci.vehicle.getRouteID(veh) if len(veh_ids) != 0 else choice(loaded_routes)

                        # new_id = datetime.datetime.today().timestamp()
                        new_id = time.time()
                        # print("[TRACI] added vehicle id: %s_%s" % (str(veh), str(new_id)))
                        # print("[TRACI] added vehicle route id", str(route_id))
                        traci.vehicle.add(
                            vehID='%s_%s' % (str(veh), str(new_id)),
                            routeID=route_id,
                            typeID=choices(emission_classes, weights=emission_weights)[0]
                        )
                        needed_vehicles += 1
                    detected_vehicles[box_id] = 0
            current_step += 1
        # except Exception as e:
        #     raise Exception('[SUMO] An error occurred while running the simulation: %s' % str(e))
        # finally:
        traci.close()
        sys.stdout.flush()
        return
 def close(self):
     traci.close()
Пример #49
0
    def run(self):
        # first, generate the route file for this simulation and set up sumo
        self._traffic_gen.generate_routefile(1234)
        traci.start(self._sumoCmd)

        # inits
        self._steps = 0
        old_action = 3
        self._waiting_times = {}
        self._sum_intersection_queue = 0
        action = 0
        current_total_wait = 0
        current_total_wait_road = [0, 0, 0, 0]
        cycle_start = 0
        old_total_wait = 0.0001
        n_cars = 0

        while self._steps < self._max_steps:
            n_cars += self._get_total_no_of_cars()
            # waiting time = seconds waited by a car since the spawn in the environment, cumulated for every car in incoming lanes
            current_total_wait_road[0] += self._get_waiting_times(["NtoC"])
            current_total_wait_road[1] += self._get_waiting_times(["EtoC"])
            current_total_wait_road[2] += self._get_waiting_times(["StoC"])
            current_total_wait_road[3] += self._get_waiting_times(["WtoC"])
            current_total_wait += self._get_waiting_times()
            self._cumulative_wait_store[self._steps] = self._get_waiting_times(
            ) / self._get_total_no_of_cars()
            self._no_of_cars[self._steps] = self._get_total_no_of_cars()
            # if the chosen phase is different from the last phase, activate the yellow phase
            if self._steps != 0 and old_action != action:
                self._set_yellow_phase(old_action)
                self._simulate(self._yellow_duration)

            # execute the phase selected before
            self._set_green_phase(self._action_order[action])
            self._simulate(self._green_duration[self._action_order[action]])

            # saving variables for later
            old_action = self._action_order[action]
            action += 1
            if action == 4:
                for i in range(4):
                    current_total_wait_road[i] /= n_cars
                current_total_wait /= n_cars
                action = 0
                self._k += 1
                self._total_wait_time_store[self._k] = self._mu_store[
                    self._k - 1] * (self._k - 1) + current_total_wait
                self._mu_store.append(self._total_wait_time_store[self._k] /
                                      self._k)
                vk = current_total_wait - self._mu_store[self._k]
                self._sigma_store.append(np.sqrt((vk * vk) / self._k))
                x = self._mu_store[
                    self._k - 1] + self._c * self._sigma_store[self._k - 1]
                self._recompute_green_duration(current_total_wait,
                                               current_total_wait_road, x)

                self._current_waiting_time_vs_no_of_cars[
                    self._sum_intersection_queue] = current_total_wait
                self._total_wait_vs_no_of_cars[
                    self.
                    _sum_intersection_queue] = self._total_wait_time_store[
                        self._k]
                self._sum_intersection_queue = 0
                old_total_wait = current_total_wait
                current_total_wait = 0
                current_total_wait_road[0] = 0
                current_total_wait_road[1] = 0
                current_total_wait_road[2] = 0
                current_total_wait_road[3] = 0
                n_cars = 0
                self._cycle_duration.append(self._steps - cycle_start)
                cycle_start = self._steps

        traci.close()
Пример #50
0
def run():
    """execute the TraCI control loop"""
    """ This stuff powers through the fist 2 steps"""
    step = 0
    traci.simulationStep()
    traci.simulationStep()
    step += 2
    traci.vehicle.add("bike", "bike1",
                      typeID='typeBike')  #Adds bike to simulation
    traci.vehicle.setSpeed("bike", 0)
    oldTLSID = ''
    warnCounter = 0
    warnRepeat = 0
    savedLight = ''
    carsWarned = False
    warningTriggered = False
    while True:
        starttime = time.time()
        updatePosition()

        upcominglights = traci.vehicle.getNextTLS("bike")
        if len(upcominglights) > 0:
            tank = str(
                upcominglights[0][0])  # tank holds the current traficlight ID,
            #trafic light identification logic will have to be tied to this variable

            LightLocation(
                tank
            )  # this pulls the trafic light location out and stores it in variables for usage
            greenz(
                tank
            )  #has to be here beacuse flask crashes traci if it is after the simulation step
            #this must be processed in the simulation, can1t be done in the webserver it will break things
            #likely because it is not thread safe
            if upcominglights[0][
                    2] < 30 and BikeSpeed > 0:  #Check if cyclist is going for it to trigger warning beacon
                warnRepeat = 8
                savedLight = tank
                warningTriggered = True

            if warnRepeat > 0:
                warnCars(savedLight)
                warnRepeat -= 1

            if warnRepeat == 0 and warningTriggered == True:  #Reset cars
                clearCars()
                warningTriggered = False

            # if carsWarned == True and tank != oldTLSID and step-warnCounter > 5:
            # clearCars(oldTLSID)
            # carsWarned = False
            # elif upcominglights[0][2] < 12 and BikeSpeed > 0: #Check if cyclist is crossing intersection for warning beacon
            # oldTLSID = tank
            # warnCars(tank)
            # warnCounter = step
            # carsWarned = True

        traci.simulationStep()
        step += 1
        time.sleep(1.0 - ((time.time() - starttime) % 1.0))
    traci.close()
Пример #51
0
def runner(pid, t1, t2, t3, t4):
    #def runner(pid):
    options = get_options()
    # this script has been called from the command line. It will start sumo as a
    # server, then connect and run
    if options.nogui:
        sumoBinary = checkBinary('sumo')
    else:
        sumoBinary = checkBinary('sumo-gui')
    #假设是所需的,完整的数据
    #with open('C:\\Users\\Mr.Du\\Desktop\\BH_f\\0903\\megerate0903.json','r') as load_f:
    with open('C:\\Users\\Mr.Du\\Desktop\\help\\megerate0902.json',
              'r') as load_f:
        megerate = json.load(load_f)
    redtime_A = 12
    redtime_B = 10
    redtime_D = 10
    #信号灯ID
    tlsID_A = '30885212'
    tlsID_B = '5535842383'
    tlsID_D = '1877642863'
    #车道数
    Num_A = 4
    Num_B = 2
    Num_D = 2
    j = 0  #处于第几个20秒
    p_A = []
    p_B = []
    p_D = []  #存储信号灯相位
    # this is the normal way of using traci. sumo is started as a
    # subprocess and then the python script connects and runs
    traci.start([
        'sumo-gui', "-c", r"C:\Users\Mr.Du\Desktop\help\BH.sumocfg",
        "--output-prefix",
        str(pid)
    ])
    #traci.start(['sumo', "-c", r"C:\Users\Mr.Du\Desktop\BH_f\0903\BH.sumocfg", "--output-prefix", str(pid)])
    for step in range(0, 18600):
        '''if step%20 == 0:#0.1步长
            r_A = megerate['Anzac'][j]
            r_B = megerate['Boundary'][j]
            r_D = megerate['Deception'][j]#每20s重新计算一次merge rate;此时步长为1
            j = j+1
            redtime_A = max(min(cal_redtime(r_A, Num_A), redtime_A+10), redtime_A-5)
            redtime_B = max(min(cal_redtime(r_B, Num_B), redtime_B+10), redtime_B-5)
            redtime_D = max(min(cal_redtime(r_D, Num_D), redtime_D+10), redtime_D-5)'''
        traci.simulationStep()
        '''p_A.append(traci.trafficlight.getPhase(tlsID_A))
        p_B.append(traci.trafficlight.getPhase(tlsID_B))
        p_D.append(traci.trafficlight.getPhase(tlsID_D))
        #第一步的时候不能进行以下计算
        if step != 0:
            if p_A[step] == 2 and (p_A[step-1] == 0 or p_A[step-1] == 1): #进入红灯,但是只能是刚进入
                traci.trafficlight.setPhaseDuration(tlsID_A, redtime_A)#每个周期都设置一下红灯时长
            if p_B[step] == 2 and (p_B[step-1] == 0 or p_B[step-1] == 1): #进入红灯,但是只能是刚进入
                traci.trafficlight.setPhaseDuration(tlsID_B, redtime_B)#每个周期都设置一下红灯时长
            if p_D[step] == 2 and (p_D[step-1] == 0 or p_D[step-1] == 1): #进入红灯,但是只能是刚进入
                traci.trafficlight.setPhaseDuration(tlsID_D, redtime_D)'''#每个周期都设置一下红灯时长
        '''vehicles = traci.inductionloop.getLastStepVehicleIDs('815 SB_0')+traci.inductionloop.getLastStepVehicleIDs('815 SB_1')+traci.inductionloop.getLastStepVehicleIDs('815 SB_2')
        for v in vehicles:
            traci.vehicle.updateBestLanes(v)
        vehicles = traci.inductionloop.getLastStepVehicleIDs('814 SB_0')+traci.inductionloop.getLastStepVehicleIDs('814 SB_1')+traci.inductionloop.getLastStepVehicleIDs('814 SB_2')
        for v in vehicles:
            traci.vehicle.updateBestLanes(v)
        vehicles = traci.inductionloop.getLastStepVehicleIDs('813 SB_0')+traci.inductionloop.getLastStepVehicleIDs('813 SB_1')+traci.inductionloop.getLastStepVehicleIDs('813 SB_2')
        for v in vehicles:
            traci.vehicle.updateBestLanes(v)'''

        if step > 5400:
            vehicles1 = traci.edge.getLastStepVehicleIDs('444071858.7')
            '''vehicles12 = traci.edge.getLastStepVehicleIDs('577463657')
            vehicles13 = traci.edge.getLastStepVehicleIDs('444071852')
            vehicles14 = traci.edge.getLastStepVehicleIDs('583369727#1')'''
            vehicles2 = traci.edge.getLastStepVehicleIDs(
                '444071862')  #从该路段开始修改车辆属性
            vehicles3 = traci.edge.getLastStepVehicleIDs('444071865')
            vehicles4 = traci.edge.getLastStepVehicleIDs('M2.4')

            for v in vehicles1:
                sigma = max(min(random.normalvariate(0.2, 0.1), 1),
                            0)  #生成随机sigma,在0,1之间
                tau1 = max(random.normalvariate(t1, 0.3), 0)
                traci.vehicle.setTau(v, tau1)
                traci.vehicle.setImperfection(v, sigma)
            '''for v in vehicles12:
                tau2 = max(random.normalvariate(1.35, 0.2), 0)
                traci.vehicle.setTau(v, tau2) 
            for v in vehicles13:
                tau2 = max(random.normalvariate(1.4, 0.2), 0)
                traci.vehicle.setTau(v, tau2)
            for v in vehicles14:
                tau2 = max(random.normalvariate(1.36, 0.2), 0)
                traci.vehicle.setTau(v, tau2)'''
            for v in vehicles2:
                tau2 = max(random.normalvariate(t2, 0.3), 0)
                traci.vehicle.setTau(v, tau2)
            for v in vehicles3:
                tau3 = max(random.normalvariate(t3, 0.3), 0)
                traci.vehicle.setTau(v, tau3)
            for v in vehicles4:
                tau4 = max(random.normalvariate(t4, 0.3), 0)
                traci.vehicle.setTau(v, tau4)
    traci.close()
    #return p_A, p_B, p_D
    return
Пример #52
0
def main():
    # read inputs
    argParser = initOptions()
    options = argParser.parse_args()

    r_all = {}
    rv_dict = {}
    memory_problems = [0]

    # start traci
    if options.sumocfg:
        run_traci = [
            options.sumo, "-c", options.sumocfg,
            '--tripinfo-output.write-unfinished'
        ]
    else:
        run_traci = [
            options.sumo, '--net-file',
            '%s' % options.network, '-r',
            '%s,%s' % (options.reservations, options.taxis), '-l', 'log.txt',
            '--device.taxi.dispatch-algorithm', 'traci', '--tripinfo-output',
            '%s' % options.output, '--tripinfo-output.write-unfinished'
        ]
        if options.gui_settings:
            run_traci.extend(['-g', '%s' % options.gui_settings])

    traci.start(run_traci)

    # execute the TraCI control loop
    step = traci.simulation.getTime() + 10
    v_type = None
    rerouting = True
    while rerouting:
        traci.simulationStep(step)

        # get vType for route calculation
        if not v_type:
            fleet = traci.vehicle.getTaxiFleet(-1)
            v_type = traci.vehicle.getTypeID(fleet[0])

        # get new reservations
        r_id_new = []
        for x in traci.person.getTaxiReservations(1):

            # search direct travel time
            direct = int(
                traci.simulation.findRoute(x.fromEdge,
                                           x.toEdge,
                                           v_type,
                                           x.depart,
                                           routingMode=0).travelTime)

            # add new reservation attributes
            setattr(x, 'direct', direct)  # direct travel time
            setattr(x, 'vehicle', False)  # id of assigned vehicle
            setattr(x, 'delay',
                    0)  # difference between assigned pick up time and real one
            setattr(
                x, 'tw_pickup',
                [x.depart, x.depart + options.max_wait])  # pickup time window
            # drop off time window
            if x.direct * options.drf < options.drf_min:
                setattr(x, 'tw_dropoff', [
                    x.tw_pickup[0] + direct,
                    x.tw_pickup[1] + direct + options.drf_min
                ])
            else:
                setattr(x, 'tw_dropoff', [
                    x.tw_pickup[0] + direct,
                    x.tw_pickup[1] + direct * options.drf
                ])

            # add id to new reservations
            r_id_new.append(x.id)
            # add reservation to list
            r_all[x.id] = x

        # unassigned reservations
        r_id_unassigned = [x.id for x_id, x in r_all.items() if not x.vehicle]

        # if reservations pending
        if r_id_unassigned:
            if options.debug:
                print('\nRun dispatcher')
                if r_id_new:
                    print('New reservations: ', r_id_new)
                print('Unassigned reservations: ',
                      list(set(r_id_unassigned) - set(r_id_new)))

            # get fleet
            fleet = traci.vehicle.getTaxiFleet(-1)
            if set(fleet) != set(fleet) & set(
                    traci.vehicle.getIDList()):  # TODO manage teleports
                print("\nVehicle %s is being teleported, skip to next step" %
                      (set(fleet) - set(traci.vehicle.getIDList())))
                step += options.sim_step
                continue  # if a vehicle is being teleported skip to next step

            # remove reservations already served
            r_id_current = [x.id for x in traci.person.getTaxiReservations(0)]
            r_id_served = list(set(r_all.keys()) - set(r_id_current))
            [r_all.pop(key) for key in r_id_served]
            [
                rv_dict.pop(key) for key in list(rv_dict)
                if set(r_id_served) & set(rv_dict[key][2])
            ]

            # reservations already picked up
            r_id_picked = [x.id for x in traci.person.getTaxiReservations(8)]

            # search request-vehicles pairs
            if options.debug:
                print('Calculate RV-Graph')
            get_rv(options, r_id_new, r_id_picked, r_id_served, r_all, fleet,
                   v_type, rv_dict, step)

            # search trips (rtv graph)
            # TODO define/import algorithm before to avoid checking each time
            # Maybe a list with the function as element and get the element (0, 1, 2)

            if options.debug:
                print('Calculate RTV-Graph')
            if options.rtv_algorithm == '0':
                rtv_dict, r_id_rtv, memory_problems = rtvAlgorithm.exhaustive_search(
                    options, r_id_unassigned, r_id_picked, r_all, fleet,
                    v_type, rv_dict, step, memory_problems)
            elif options.rtv_algorithm == '1':
                rtv_dict, r_id_rtv = rtvAlgorithm.simple(
                    options, r_id_unassigned, r_id_picked, r_id_served, r_all,
                    fleet, v_type, rv_dict, step)
            elif options.rtv_algorithm == '2':
                rtv_dict, r_id_rtv = rtvAlgorithm.simple_rerouting(
                    options, r_id_unassigned, r_id_picked, r_id_served, r_all,
                    fleet, v_type, rv_dict, step)
            # rtv_dict, r_id_rtv = get_rtv(options, r_id_unassigned, r_id_picked, r_id_served, r_all,
            #                              fleet, v_type, rv_dict, step)

            if len(rtv_dict) == 0:
                step += options.sim_step
                continue  # if no routes found

            elif len(rtv_dict.keys()) == 1:
                # if one vehicle darp, assign route
                best_routes = list(rtv_dict.keys())

            else:
                # if multiple vehicle darp, solve ILP with pulp
                vehicle_constraints = {}
                request_constraints = {}
                costs = {}
                trips = list(rtv_dict.keys()
                             )  # list of all trips for ILP solution parse

                # add bonus_cost to trip cost (makes trips with more served requests cheaper than splitting
                # the requests to more vehicles with smaller trips if both strategies would yield a similar cost)
                for idx, trip_id in enumerate(trips):
                    # rtv_dict[route] = [travel_time, v_bin, r_bin, value]
                    # TODO specific cost for vehicle can be consider here
                    bonus_cost = (sum(rtv_dict[trip_id][2]) +
                                  1) * options.cost_per_trip
                    costs.update({idx: rtv_dict[trip_id][0] + bonus_cost
                                  })  # generate dict with cost
                    # generate dict with vehicle used in the trip
                    vehicle_constraints.update({idx: rtv_dict[trip_id][1]})
                    # generate dict with served requests in the trip
                    request_constraints.update({idx: rtv_dict[trip_id][2]})

                if options.debug:
                    print('Solve ILP')
                ilp_result = ilp_solve(options, len(fleet), len(r_id_rtv),
                                       costs, vehicle_constraints,
                                       request_constraints)

                # parse ILP result
                best_routes = [
                    trips[int(route_index)] for route_index in ilp_result
                ]

            # assign routes to vehicles
            for route_id in best_routes:
                stops = route_id.replace('y', '')
                stops = stops.replace('z', '')
                stops = stops.split("_")
                # first check if route different or better (when no optimal solution) than already assigned
                current_route = []
                try:  # get current route
                    for taxi_stop in traci.vehicle.getStops(stops[0]):
                        sub_stops = taxi_stop.actType.split(
                            ",")  # if more than 1 reservation in stop
                        for sub_stop in sub_stops:
                            current_route.append(sub_stop.split(" ")[2][1:-1])
                except:
                    current_route = ['None']
                if current_route == stops[1:]:
                    # route is the same
                    continue
                elif set(current_route) == set(
                        stops[1:]) and len(current_route) == len(stops[1:]):
                    # if route serve same request, check if new is faster
                    tt_current_route = 0
                    edges = [
                        taxi_stops.lane.split("_")[0]
                        for taxi_stops in traci.vehicle.getStops(stops[0])
                    ]  # TODO check next_act update
                    edges.insert(
                        0,
                        traci.vehicle.getLaneID(
                            stops[0]).split("_")[0])  # add current edge
                    for idx, edge in enumerate(edges[:-1]):
                        # TODO default stop time ticket #6714
                        tt_current_route += int(
                            traci.simulation.findRoute(
                                edge,
                                edges[idx + 1],
                                v_type,
                                step,
                                routingMode=0).travelTime) + 60
                    tt_new_route = rtv_dict[route_id][0]
                    if tt_new_route >= tt_current_route:
                        continue  # current route better than new found
                if options.debug:
                    print('Dispatch: ', route_id)
                traci.vehicle.dispatchTaxi(stops[0], stops[1:])
                # assign vehicle to requests
                # TODO to avoid major changes in the pick-up time when assigning new passengers,
                # tw_pickup should be updated, whit some constant X seconds, e.g. 10 Minutes
                for x_id in set(stops[1:]):
                    x = r_all[x_id]
                    x.vehicle = stops[0]

        # TODO ticket #8385
        if step > options.end_time or (traci.simulation.getMinExpectedNumber()
                                       <= 0 and not traci.person.getIDList()):
            rerouting = False

        step += options.sim_step

    if options.rtv_algorithm == 0:  # if exhaustive search
        if sum(memory_problems) == 0:
            print('Optimal solution found.')
        else:
            print(
                'The maximal specified calculation time has been exceeded. Solution could be not optimal.'
            )
    print('DRT simulation ended')
    traci.close()
Пример #53
0
def runQFA():
    stateVect = [[]]
    # policyPi = []
    # for i in range(0, 80, 1):
    #     policyPi.insert(i, random.randint(0, 5))
    QSA = np.random.rand(6, 1)
    # QdashSA = np.array(np.random.rand(1, 6))
    # Returns = [[0]*6 for x in range(81)]
    phiSA = [[0]*13 for x in range(6)]
    for i in range(6):
        phiSA[i][12] = 1
    theta = np.array(np.random.rand(13, 1))
    # thetaDash = np.array(np.random.rand(13, 1))
    currTLS = []
    Actions = [20, 25, 30, 20, 25, 30]
    # Actions = [30, 60, 120, 30, 60, 120]
    avgTime = []
    numVehs = []
    avgTime.clear()
    numVehs.clear()

    EPSILON = 0.20
    ALPHA = 0.05
    GAMMA = 0.9
    step = 0

    stateNorth = 0
    stateSouth = 0
    stateEast = 0
    stateWest = 0

    currAction = 0
    reward = 0
    totWaittimeSoFar = 0
    curWaittime = 0
    totVehsSoFar = 0
    currVehsHere = 0
    while traci.simulation.getMinExpectedNumber() > 0:
        traci.simulationStep()
        # print(QSA)
        stateNorth = traci.lane.getLastStepOccupancy('nc_0')
        stateSouth = traci.lane.getLastStepOccupancy('sc_0')
        stateEast = traci.lane.getLastStepOccupancy('ec_0')
        stateWest = traci.lane.getLastStepOccupancy('wc_0')
        tlsPhase = traci.trafficlight.getPhase("center")
        currTLS = traci.trafficlight.getCompleteRedYellowGreenDefinition("center")
        # Determine the state
        lenFeature = (getState(stateNorth) + getState(stateEast) + getState(stateSouth) + getState(stateWest))*1.0 / 8
        timeFeature = getSwitchTime(tlsPhase, currTLS, traci.simulation.getTime())
        reward = -1.0 * (lenFeature + timeFeature)
        # Take epsilon-greedy action
        if random.uniform(0, 1) < EPSILON:
            currAction = random.randint(0, 5)
        else:
            currAction = np.argmax(QSA)
        # Storage
        phiSA[currAction][currAction*2] = lenFeature
        phiSA[currAction][currAction*2 + 1] = timeFeature
        # QSA = np.array(np.random.rand(1, 6))
        stateVect.insert(step, [lenFeature, timeFeature, 0, 0])
        stateVect[step][3] = currAction
        stateVect[step][2] = reward

        # Control simulation
        if currAction > 2:
            phaseToChange = 2
        else:
            phaseToChange = 0
        # currTLS = traci.trafficlight.getCompleteRedYellowGreenDefinition("center")
        currTLS[0].phases[phaseToChange].duration = Actions[currAction]
        currTLS[0].phases[phaseToChange].minDur = Actions[currAction]
        currTLS[0].phases[phaseToChange].maxDur = Actions[currAction]
        traci.trafficlight.setCompleteRedYellowGreenDefinition("center", currTLS[0])

        # The Update
        if step > 0 and step % 75 == 0:
            episodeStates = [[]]
            A = 0
            R = 0
            for t in range(0, 74, 1):
                episodeStates.insert(t, stateVect[step-74+t])
            for t in range(0, 73, 1):
                S = episodeStates[t]
                R = S[2]
                A = S[3]
                Sprime = episodeStates[t+1]
                QSA = np.matmul(phiSA, theta)
                QdashSA = getQdash(phiSA, Sprime, theta)

                # print(Sprime)
                gradWqsa = [0]*13
                for i in range(13):
                    for j in range(6):
                        gradWqsa[i] = gradWqsa[i] + phiSA[j][i]
                # for i in range(6):
                #     print(phiSA[i])
                # print(gradWqsa)
                # break
                err = R + GAMMA * max(QdashSA) - QSA[A]
                const = ALPHA * err
                for i in range(13):
                    theta[i] = theta[i] + const * gradWqsa[i]
                # print(theta)

        # print(phiSA, sep='\n')
        # print(np.matrix(phiSA))
        # print('\n'.join(['\t'.join([str(cell) for cell in row]) for row in phiSA]))
        step += 1

        curWaittime = traci.edge.getWaitingTime('nc') + traci.edge.getWaitingTime('ec') + traci.edge.getWaitingTime('sc') + traci.edge.getWaitingTime('wc')
        totWaittimeSoFar = totWaittimeSoFar + curWaittime
        avgTime.append(totWaittimeSoFar/step)

        currVehsHere = traci.simulation.getArrivedNumber()
        totVehsSoFar = totVehsSoFar + currVehsHere
        numVehs.append(totVehsSoFar)
    traci.close()
    # print(phi)
    sys.stdout.flush()
    return step, avgTime, numVehs
Пример #54
0
print("convertRoad2D", traci.simulation.convert2D("o", 0.))
print("convertRoad3D", traci.simulation.convert3D("o", 0.))
print("convertRoadGeo", traci.simulation.convert2D("o", 0., toGeo=True))
print("convertRoadGeoAlt", traci.simulation.convert3D("o", 0., toGeo=True))
print("convert2DGeo", traci.simulation.convertGeo(488.65, 501.65))
print("convertGeo2D", traci.simulation.convertGeo(12, 48, True))
print("convert2DRoad", traci.simulation.convertRoad(488.65, 501.65))
print("convertGeoRoad", traci.simulation.convertRoad(12, 48.1, True))
print("distance2D",
      traci.simulation.getDistance2D(488.65, 501.65, 498.65, 501.65))
print(
    "drivingDistance2D",
    traci.simulation.getDistance2D(488.65,
                                   501.65,
                                   498.65,
                                   501.65,
                                   isDriving=True))
print("distanceRoad", traci.simulation.getDistanceRoad("o", 0., "2o", 0.))
print("drivingDistanceRoad",
      traci.simulation.getDistanceRoad("o", 0., "2o", 0., isDriving=True))
print("clearing pending")
traci.simulation.clearPending()
print("save simstate")
traci.simulation.saveState("state.xml")
for step in range(6):
    print("step", step)
    traci.simulationStep()
    print(traci.simulation.getSubscriptionResults())
traci.close()
sumoProcess.wait()
Пример #55
0
 def close(self):
     traci.close()
     self.time = 0
Пример #56
0
def city_dqn_test(flags, sumoCmd, configs):
    # Environment Setting
    from Agent.super_dqn import Trainer
    from Env.CityEnv import CityEnv
    # init test setting
    if flags.replay_name is not None:
        # 여기앞에 configs 설정해도 의미 없음
        configs = load_params(configs, flags.replay_name)
        configs['replay_epoch'] = str(flags.replay_epoch)
        configs['mode'] = 'test'

    phase_num_matrix = torch.tensor(  # 각 tl이 갖는 최대 phase갯수
        [
            len(configs['traffic_node_info'][index]['phase_duration'])
            for _, index in enumerate(configs['traffic_node_info'])
        ])
    sumoCmd += ['--seed', '1']
    agent = Trainer(configs)
    agent.save_params(configs['time_data'])
    agent.load_weights(flags.replay_name)
    # init training
    NUM_AGENT = configs['num_agent']
    TL_RL_LIST = configs['tl_rl_list']
    MAX_PHASES = configs['max_phase_num']
    MAX_STEPS = configs['max_steps']
    OFFSET = torch.tensor(
        configs['offset'],  # i*10
        device=configs['device'],
        dtype=torch.int)
    TL_PERIOD = torch.tensor(configs['tl_period'],
                             device=configs['device'],
                             dtype=torch.int)
    # state initialization
    # agent setting
    # check performance
    avg_waiting_time = 0
    avg_part_velocity = 0
    avg_velocity = 0
    arrived_vehicles = 0
    part_velocity = list()
    waiting_time = list()
    total_velocity = list()
    # travel time
    travel_time = list()
    with torch.no_grad():
        step = 0
        traci.start(sumoCmd)
        env = CityEnv(configs)
        # Total Initialization
        actions = torch.zeros((NUM_AGENT, configs['action_size']),
                              dtype=torch.int,
                              device=configs['device'])
        # Mask Matrix : TL_Period가 끝나면 True
        mask_matrix = torch.ones((NUM_AGENT),
                                 dtype=torch.bool,
                                 device=configs['device'])

        # MAX Period까지만 증가하는 t
        t_agent = torch.zeros((NUM_AGENT),
                              dtype=torch.int,
                              device=configs['device'])
        t_agent -= OFFSET

        # Action configs['offset']on Matrix : 비교해서 동일할 때 collect_state, 없는 state는 zero padding
        action_matrix = torch.zeros((NUM_AGENT, MAX_PHASES),
                                    dtype=torch.int,
                                    device=configs['device'])  # 노란불 3초 해줘야됨
        action_index_matrix = torch.zeros(
            (NUM_AGENT), dtype=torch.long,
            device=configs['device'])  # 현재 몇번째 phase인지
        action_update_mask = torch.eq(  # action이 지금 update해야되는지 확인
            t_agent,
            action_matrix[0,
                          action_index_matrix]).view(NUM_AGENT)  # 0,인 이유는 인덱싱

        # 최대에 도달하면 0으로 초기화 (offset과 비교)
        clear_matrix = torch.eq(t_agent % TL_PERIOD, 0)
        t_agent[clear_matrix] = 0
        # action 넘어가야된다면 action index증가 (by tensor slicing)
        action_index_matrix[action_update_mask] += 1
        action_index_matrix[clear_matrix] = 0

        # mask update, matrix True로 전환
        mask_matrix[clear_matrix] = True
        mask_matrix[~clear_matrix] = False

        # state initialization
        state = env.collect_state(action_update_mask, action_index_matrix,
                                  mask_matrix)
        total_reward = 0

        # agent setting
        arrived_vehicles = 0
        a = time.time()
        while step < MAX_STEPS:

            # action 을 정하고
            actions = agent.get_action(state, mask_matrix)
            if mask_matrix.sum() > 0:
                print(actions.transpose(1, 2))
            # action형태로 변환 # 다음으로 넘어가야할 시점에 대한 matrix
            action_matrix = env.calc_action(action_matrix, actions,
                                            mask_matrix)
            # 누적값으로 나타남

            # environment에 적용
            # action 적용함수, traci.simulationStep 있음
            env.step(actions, mask_matrix, action_index_matrix,
                     action_update_mask)

            # 전체 1초증가 # traci는 env.step에
            step += 1
            t_agent += 1
            # 최대에 도달하면 0으로 초기화 (offset과 비교)
            clear_matrix = torch.eq(t_agent % TL_PERIOD, 0)

            # 넘어가야된다면 action index증가 (by tensor slicing)

            # action 넘어가야된다면 action index증가 (by tensor slicing)
            for idx, _ in enumerate(TL_RL_LIST):
                action_update_mask[
                    idx] = torch.eq(  # update는 단순히 진짜 현시만 받아서 결정해야됨
                        t_agent[idx],
                        action_matrix[idx, action_index_matrix[idx]].view(
                            -1))  # 0,인 이유는 인덱싱

            action_index_matrix[action_update_mask] += 1
            # agent의 최대 phase를 넘어가면 해당 agent의 action index 0으로 초기화
            action_index_matrix[clear_matrix] = 0

            # mask update, matrix True로 전환
            t_agent[clear_matrix] = 0
            mask_matrix[clear_matrix] = True
            mask_matrix[~clear_matrix] = False

            # check performance
            for _, interests in enumerate(configs['interest_list']):
                # delete 중복
                dup_list = list()
                for interest in interests:
                    inflow = interest['inflow']
                    outflow = interest['outflow']
                    # 신호군 흐름
                    if inflow != None and inflow not in dup_list:
                        # 차량의 대기시간, 차량이 있을 때만
                        if traci.edge.getLastStepVehicleNumber(inflow) != 0:
                            waiting_time.append(
                                traci.edge.getWaitingTime(inflow))  #/float(
                            #traci.edge.getLastStepVehicleNumber(inflow)))
                            # 차량의 평균속도
                            # part_velocity.append(
                            #     traci.edge.getLastStepMeanSpeed(inflow))
                            tmp_travel = traci.edge.getTraveltime(inflow)
                            if tmp_travel <= 500 and tmp_travel != -1:  # 이상한 값 거르기
                                travel_time.append(tmp_travel)
                        dup_list.append(inflow)

                    if outflow != None and outflow not in dup_list:
                        if traci.edge.getLastStepVehicleNumber(outflow) != 0:
                            # part_velocity.append(
                            #     traci.edge.getLastStepMeanSpeed(interest['outflow']))
                            tmp_travel = traci.edge.getTraveltime(outflow)
                            if tmp_travel <= 500 and tmp_travel != -1:  # 이상한 값 거르기
                                travel_time.append(tmp_travel)
                        dup_list.append(interest['outflow'])
            # edge_list=traci.edge.getIDList()
            # for edgeid in edge_list:
            #     if traci.edge.getLastStepVehicleNumber(edgeid) !=None:
            #         total_velocity.append(traci.edge.getLastStepMeanSpeed(edgeid))
            next_state = env.collect_state(action_update_mask,
                                           action_index_matrix, mask_matrix)
            state = next_state
            # info

            arrived_vehicles += traci.simulation.getArrivedNumber()

        b = time.time()
        traci.close()
        print("time:", b - a)
        avg_part_velocity = torch.tensor(part_velocity,
                                         dtype=torch.float).mean()
        avg_velocity = torch.tensor(total_velocity, dtype=torch.float).mean()
        avg_part_velocity = torch.tensor(part_velocity,
                                         dtype=torch.float).mean()
        avg_travel_time = torch.tensor(travel_time, dtype=torch.float).mean()
        avg_waiting_time = torch.tensor(waiting_time, dtype=torch.float).mean()
        print(
            '======== arrived number:{} avg waiting time:{},avg velocity:{} avg_part_velocity: {} avg_travel_time: {}'
            .format(arrived_vehicles, avg_waiting_time, avg_velocity,
                    avg_part_velocity, avg_travel_time))
        print("Reward: {}".format(env.cum_reward.sum()))
Пример #57
0
        tl_list.append(connection[2])
    return tl_list


#lust= import_datasets()

#tls= extract_tl_ids(lust.iloc[0])
#print tls
#connections = dataset[5]==[from,to,tl,dir,state]
if True:
    TLSID = "0"
    while step < 1000:
        simulationStep()
        arrived_vehicles_in_last_step = simulation.getArrivedNumber()
        departed_vehicles_in_last_step = simulation.getDepartedNumber()
        current_simulation_time_ms = simulation.getCurrentTime()
        print arrived_vehicles_in_last_step
        phase = trafficlights.getPhase(TLSID)
        trafficlights.setRedYellowGreenState(TLSID, "grrrrrrrrrrr")

        lanes = trafficlights.getControlledLanes(TLSID)
        print len(lanes)
        #for lane in lanes:
        #    print lane
        print phase
        #if traci.inductionloop.getLastStepVehicleNumber("0") > 0:
        #   traci.trafficlights.setRedYellowGreenState("0", "GrGr")
        step += 1

    close()
Пример #58
0
 def stop_sumo(self):
     traci.close()
Пример #59
0
def main():
    # Use the global parameters for iteration steps. Maybe their value varies.
    global time_steps
    global min_step
    global max_step

    # Parse the input commands.
    params = ConfigurationInput().parse()

    verbose = False
    if params.has_key(VERBOSE):
        verbose = True

    # If unbounded time step is added, turn the time steps to unlimited
    if params.has_key(UNBOUNDED_STEP):
        time_steps = -1
        min_step = -1
        max_step = -1
    else:
        if params.has_key(STEP_LIMIT):
            steps = int(params[STEP_LIMIT].pop()) 
            if ge(steps, 0):
                time_steps = steps
    
        if params.has_key(START_STEP):
            startStep = int(params[START_STEP].pop())
            if ge(startStep, 0):
                min_step = startStep
    
        if params.has_key(END_STEP):
            endStep = int(params[END_STEP].pop())
            if le(endStep, time_steps):
                max_step = endStep
    
        if ge(max_step, time_steps) or le(max_step, min_step):
            max_step = time_steps
        if ge(min_step, max_step) or ge(min_step, time_steps):
            min_step = 0

    if params.has_key(NET):
        # Open the net file to get the static data from net.
        netFile = params[NET].pop()
        net = sumolib.net.readNet(netFile)
    else:
        # we have a input error.
        print "Error: Parameter -net was not set or parameters are invalid."
        print "Try " + sys.argv[0] + " --help\n"
        exit()
    
    # Blank space is the default format string separator
    separator = ' '
    if params.has_key(SEPARATOR):
        sep = params[SEPARATOR].pop()
        if not eq(sep, None):
            if eq(sep.lower(), TAB):
                separator = '\t'
            elif eq(sep.lower(), BLANK):
                separator = ' '
            elif eq(sep.lower(), COMMA):
                separator = ','

    # Breaks the full option in various type of outputs
    if params.has_key(FULL):
        for key in ALL_PARAMS:
            if not params.has_key(key):
                params[key] = []
        del params[FULL]
    elif (EDGE_PARAMS.isdisjoint(params.keys()) and VEHICLE_PARAMS.isdisjoint(params.keys()) 
          and TRAFFIC_LIGHT_PARAMS.isdisjoint(params.keys()) and NODE_PARAMS.isdisjoint(params.keys())):
        # we have a input error.
        print "Error: You need to choose at least one of output parameters(Vehicle, Edge, Traffic Lights)."
        print "Try " + sys.argv[0] + " --help\n"
        exit()

    if params.has_key(PORT):
        port = int(params[PORT].pop())
        # For the use of SUMO with traci-hub.
        if ge(port, 0):
            traci.init(port)
        else:
            traci.init(DEFAULT_PORT)
    else:
        # For the use of SUMO without traci-hub.
        traci.init(DEFAULT_PORT)

    # If some edges parameter is common
    if not EDGE_PARAMS.isdisjoint(params.keys()):

        # Instantiate the monitor of edges.
        edgeMonitor = EdgeMonitor()
        edgeMonitor.minStep = min_step
        edgeMonitor.maxStep = max_step

        # Search for the edge id's list, and filter it, removing all the id's 
        # that refers to lanes (initiates with ':')
        traciEdgeList = traci.edge.getIDList()
        traciEdgeList = filter(lambda x: x.find(':') == -1, traciEdgeList)

        commonKeys = EDGE_PARAMS.intersection(params.keys())
        edgeIdSet = set()

        # At this point, we have to recognize all the input type for the edges,  
        # if the all parameter for edges is inserted, it is necessary to add all
        # the types of edges output and the list of ids.
        if EDGE_ALL in commonKeys:
            listValues = params.get(EDGE_ALL,[])
            # The key is giving but no parameter, so we need to add some edges
            if eq(len(listValues),0):
                listValues = traciEdgeList
            for key in EDGE_PARAMS.difference(set([EDGE_ALL])):
                edgeMonitor.addEdgesIdOutput(listValues, key)
                params[key] = copy(listValues)
                edgeIdSet.update(listValues)
            del params[EDGE_ALL]
        else:
            for key in commonKeys:
                listValues = params.get(key,'')
                # The key is giving but no parameter, so we need to add some edges
                if eq(len(listValues),0):
                    listValues = traciEdgeList
                edgeMonitor.addEdgesIdOutput(listValues, key)
                params[key] = copy(listValues)
                edgeIdSet.update(listValues)

        # Creates a list with all edge id's that exists and are inserted by user
        edgeIdList = list(edgeIdSet.intersection(traciEdgeList))

        # Warranty that we have some edges to evaluate, taking all the edges
        if eq(len(edgeIdList), 0):
            edgeIdList = traciEdgeList

        # Creates and inserts the initialized edges in the monitor.
        for edgeId in edgeIdList:
            # Ignore every edge that not correspond to a full edge, in that case
            # , the junction lanes.
            if not edgeId.startswith(":"):
                edgeSumoLib = net.getEdge(edgeId)
                fromNode = edgeSumoLib._from._id
                toNode = edgeSumoLib._to._id
                lengthEdge = edgeSumoLib.getLength()
                edge = Edge(edgeId, fromNode, toNode, lengthEdge, verbose)
                edge.minStep = min_step
                edge.maxStep = max_step
                edgeMonitor.addEdge(edge)
    
    if not VEHICLE_PARAMS.isdisjoint(params.keys()):
        # Instantiate the monitor of vehicles.
        vehicleMonitor = VehicleMonitor()
        vehicleMonitor.minStep = min_step
        vehicleMonitor.maxStep = max_step

        # Search for the vehicle id's list.
        traciVehicleList = traci.vehicle.getIDList()

        commonKeys = VEHICLE_PARAMS.intersection(params.keys())
        vehicleIdSet = set()

        # At this point, we have to recognize all the input type for the 
        # vehicles, if the all parameter for vehicles is inserted, it is   
        # necessary to add all the types of vehicles output and the list of ids.
        if (VEHICLE_ALL in commonKeys):
            listValues = params.get(VEHICLE_ALL,[])
            # The key is giving but no parameter, so we need to add some 
            # vehicles.
            if eq(len(listValues),0):
                listValues = traciVehicleList
            for key in VEHICLE_PARAMS.difference(set([VEHICLE_ALL])):
                vehicleMonitor.addVehiclesIdOutput(listValues, key)
                params[key] = copy(listValues)
                vehicleIdSet.update(listValues)
            del params[VEHICLE_ALL]
        else:
            for key in commonKeys:
                listValues = params.get(key,[])
                # The key is giving but no parameter, so we need to add some 
                # vehicles.
                if eq(len(listValues),0):
                    listValues = traciVehicleList
                vehicleMonitor.addVehiclesIdOutput(listValues, key)
                params[key] = copy(listValues)
                vehicleIdSet.update(listValues)

        # Creates a list with all vehicle id's that exists and are inserted by 
        # user.
        vehicleIdList = list(vehicleIdSet.intersection(traciVehicleList))

        # Warranty that we have some vehicles to evaluate, taking all the 
        # vehicles.
        if eq(len(vehicleIdList), 0):
            vehicleIdList = traciVehicleList

        # Creates and inserts the initialized vehicles in the monitor.
        for vehicleId in vehicleIdList:
            if not vehicleMonitor.hasVehicleById(vehicleId):
                vehicle = Vehicle(vehicleId)
                vehicle.minStep = min_step
                vehicle.maxStep = max_step
                vehicle.departure = 0
                vehicleMonitor.addVehicle(vehicle)

    if not TRAFFIC_LIGHT_PARAMS.isdisjoint(params.keys()):
        # Instantiate the monitor of traffic lights.
        trafficLightsMonitor = TrafficLightsMonitor()
        trafficLightsMonitor.minStep = min_step
        trafficLightsMonitor.maxStep = max_step

        # Search for the traffic lights id's list.
        traciTrafficLightsList = traci.trafficlights.getIDList()

        commonKeys = TRAFFIC_LIGHT_PARAMS.intersection(params.keys())
        trafficLightsIdSet = set()

        # At this point, we have to recognize all the input type for the traffic
        # lights, if the all parameter for traffic lights is inserted, it is   
        # necessary to add all the types of traffic lights output and the list 
        # of ids.
        if TRAFFIC_LIGHT_ALL in commonKeys:
            listValues = params.get(TRAFFIC_LIGHT_ALL,[])
            # The key is giving but no parameter, so we need to add some traffic
            # lights
            if eq(len(listValues),0):
                listValues = traciTrafficLightsList
            for key in TRAFFIC_LIGHT_PARAMS.difference(set([TRAFFIC_LIGHT_ALL])):
                trafficLightsMonitor.addTrafficLightsIdOutput(listValues, key)
                params[key] = copy(listValues)
                trafficLightsIdSet.update(listValues)
            del params[TRAFFIC_LIGHT_ALL]
        else:
            for key in commonKeys:
                listValues = params.get(key,'')
                # The key is giving but no parameter, so we need to add some 
                # traffic lights
                if eq(len(listValues),0):
                    listValues = traciTrafficLightsList
                trafficLightsMonitor.addTrafficLightsIdOutput(listValues, key)
                params[key] = copy(listValues)
                trafficLightsIdSet.update(listValues)

        # Creates a list with all traffic lights id's that exists and are 
        # inserted by user
        trafficLightsIdList = list(trafficLightsIdSet.intersection(traciTrafficLightsList))

        # Warranty that we have some traffic lights to evaluate, taking all the 
        # traffic lights
        if eq(len(trafficLightsIdList), 0):
            trafficLightsIdList = traciTrafficLightsList

        for trafficLightsId in trafficLightsIdList:
            # Instantiate the traffic lights object and add some data.
            trafficLights = TrafficLights(trafficLightsId)
            # Simulation steps interval
            trafficLights.minStep = min_step
            trafficLights.maxStep = max_step
            # Controlled lanes
            trafficLights.controlledLanes = traci.trafficlights.getControlledLanes(trafficLightsId)
            # Controlled links
            trafficLights.controlledLinks = traci.trafficlights.getControlledLinks(trafficLightsId)

            # Complete logic and phases of the semaphore
            programList = traci.trafficlights.getCompleteRedYellowGreenDefinition(trafficLightsId)

            # Take the first and unique program in the list
            while len(programList) > 0:
                phases = []
                program = programList.pop()
                if program:
                    # Instantiate the logic program helper class for traffic 
                    # lights.
                    trafficLightsProgram = TrafficLightsProgram()
                    trafficLightsProgram.id = program._subID
                    trafficLightsProgram.programType = program._type
                    trafficLightsProgram.subParameter = program._subParameter
                    trafficLightsProgram.currentPhaseIndex = program._currentPhaseIndex

                    # Take the phases of the signal state
                    for phase in program._phases:
                        ph = Phase(phase._duration, phase._duration1, phase._duration2, phase._phaseDef)
                        phases.append(ph)
                    trafficLightsProgram.phases = phases

                    # Adds the semaphore program to the traffic lights
                    trafficLights.addLogicProgram(trafficLightsProgram)

            # Inserts the initialised traffic lights in the monitor.
            trafficLightsMonitor.addTrafficLights(trafficLights)

    if not NODE_PARAMS.isdisjoint(params.keys()):
        pass

## reroute test
#    traci.route.add(
#       "sp_route1", 
#       ["south/center", "center/north", "north/center", "center/south"]
#    )
#    traci.route.add(
#       "sp_route2", 
#       ["center/south", "south/center", "center/north", "north/center"]
#    )
#    traci.route.add(
#       "sp_route3", 
#       ["north/center", "center/south", "south/center", "center/north"]
#    )
#    traci.route.add(
#       "sp_route4", 
#       ["center/north", "north/center", "center/south","south/center"]
#    )
#    traci.vehicle.add("special", "sp_route1", 0)

    # For each iteration of the simulation.
    timeStep = 0
    timeStepFinal = 0

    # Creating the clone summary output
    data = ["#step"]
    data.append("loaded")
    data.append("departed")
    data.append("running")
    data.append("arrived")
    summaryData = [separator.join(data)]

    totalLoaded = 0
    totalDeparted = 0
    totalArrived = 0

    #
    # Simulation beginning
    #
    while True:

        # All vehicles have arrived
        if timeStep > 5 and totalArrived == totalDeparted:
            traci.close()
            break

        # The maximum time step has been reached
        if not eq(time_steps,-1) and gt(timeStep, max_step):
            traci.close()
            break

        try:

            # Executes one step
            traci.simulationStep()

            totalLoaded += traci.simulation.getLoadedNumber()
            totalDeparted += traci.simulation.getDepartedNumber()
            totalArrived += traci.simulation.getArrivedNumber()
            totalRunning = totalDeparted - totalArrived

            data = []   # clear list
            data.append(str(timeStep))
            data.append(str(totalLoaded))
            data.append(str(totalDeparted))
            data.append(str(totalRunning))
            data.append(str(totalArrived))
            summaryData.append(separator.join(data))

#            # All vehicles have arrived
#            if timeStep > 5 and totalArrived == totalDeparted:
#                traci.close()
#                break
#
#            # The maximum time step has been reached
#            if not eq(time_steps,-1) and gt(timeStep, max_step):
#                traci.close()
#                break

#        except traci.FatalTraCIError as message:
#            print message
#            traci.close()
#            #exit()
#            break

            # One step execution of evaluation
            if (ge(timeStep, min_step) and le(timeStep, max_step)) or eq(time_steps,-1):
                if not EDGE_PARAMS.isdisjoint(params.keys()):
                    # Updates the edges in the monitor with the data of simulation 
                    # in this step.
                    for edgeId in edgeIdList:
                        edgeMonitor.updateEdge(
                                               timeStep, edgeId,
                                               traci.edge.getLastStepVehicleNumber(edgeId),
                                               traci.edge.getLastStepMeanSpeed(edgeId),
                                               traci.edge.getLastStepHaltingNumber(edgeId),
                                               traci.edge.getLastStepLength(edgeId),
                                               traci.edge.getLastStepOccupancy(edgeId)
                                               )
                if not VEHICLE_PARAMS.isdisjoint(params.keys()):
                    # Search for the vehicle id's list.
                    traciVehicleList = traci.vehicle.getIDList()
     
                    commonKeys = VEHICLE_PARAMS.intersection(params.keys())
                    vehicleIdSet = set()
    
                    for key in commonKeys:
                        listValues = params.get(key,[])
    
                        # The key is giving but no parameter, so we need to add some 
                        # vehicles
                        if not listValues:
                            # Takes the actual list of vehicles in simulation
                            listValues = traciVehicleList
                            # and adds to the output list.
                            vehicleMonitor.addVehiclesIdOutput(listValues, key)
    
                        vehicleIdSet.update(listValues)
    
                    # Creates a list with all vehicle id's that exists and are 
                    # inserted by user
                    vehicleIdList = list(vehicleIdSet)
    
                    # Warranty that we have some vehicles to evaluate, taking all 
                    # the vehicles
                    if not vehicleIdList:
                        vehicleIdList = traciVehicleList
    
                    # Creates and inserts the initialized vehicles in the monitor.
                    # Updates the vehicles in the monitor with the data of 
                    # simulation in this step.
                    for vehicleId in vehicleIdList:
                        if not vehicleMonitor.hasVehicleById(vehicleId):
                            # Insert the new vehicle
                            vehicle = Vehicle(vehicleId)
                            vehicle.minStep = min_step
                            vehicle.maxStep = max_step
                            vehicle.departure = timeStep
                            vehicleMonitor.addVehicle(vehicle)
    
    #                    #reroute test
    #                    if "special" in vehicleIdList:
    #                        #print traci.vehicle.getRoadID("special")
    #                        if traci.vehicle.getRoadID("special") == "south/center":
    #                            traci.vehicle.setRouteID("special", "sp_route1")
    #                        elif traci.vehicle.getRoadID("special") == "center/north":
    #                            traci.vehicle.setRouteID("special", "sp_route4")
    #                        elif traci.vehicle.getRoadID("special") == "north/center":
    #                            traci.vehicle.setRouteID("special", "sp_route3")
    #                        elif traci.vehicle.getRoadID("special") == "center/south":
    #                            traci.vehicle.setRouteID("special", "sp_route2")
    
                    #TODO: ainda precisa corrigir aqui, para evitar que o '-' fique sendo inserido regularmente
                    for vehicleId in vehicleMonitor.getVehiclesIdList():
                        # The current simulation vehicles
                        if vehicleId in traci.vehicle.getIDList():
                            edgeId = traci.vehicle.getRoadID(vehicleId)
                            if net.hasEdge(edgeId):
                                edgeLength = net.getEdge(edgeId).getLength()
                            else:
                                edgeId = '-'
                                edgeLength = 0
    
                            vehicleMonitor.updateVehicle(
                                                   timeStep, vehicleId,
                                                   traci.vehicle.getSpeed(vehicleId),
                                                   traci.vehicle.getRouteID(vehicleId),
                                                   traci.vehicle.getRoute(vehicleId),
                                                   edgeId, edgeLength
                                                   )
    
                    for vehicleId in traci.simulation.getArrivedIDList():
                        if vehicleMonitor.hasVehicleById(vehicleId):
                            vehicleMonitor.updateArrivedVehicle(timeStep, vehicleId)
                    timeStepFinal +=1
    
                if not TRAFFIC_LIGHT_PARAMS.isdisjoint(params.keys()):
                    # Updates the traffic lights in the monitor with the data of 
                    # simulation in this step.
                    for trafficLightsId in trafficLightsIdList:
                        lanes = trafficLightsMonitor.getTrafficLightsLanesById(trafficLightsId)
                        haltingVehicles = [traci.lane.getLastStepHaltingNumber(laneId) for laneId in lanes]
                        trafficLightsMonitor.updateTrafficLights(
                                                                 timeStep,
                                                                 trafficLightsId,
                                                                 haltingVehicles
                                                                 )
    
                # dynamics
    #            # assumed time to next switch
    #            traci.trafficlights.getNextSwitch(trafficLightsId)
    #            # index of the current phase index request
    #            traci.trafficlights.getPhase(trafficLightsId)
    #            # traffic light states, encoded as rRgGyYoO
    #            print traci.trafficlights.getRedYellowGreenState(trafficLightsId)
    #                    trafficLightsMonitor.updateEdge(
    #                                           timeStep, trafficLightsId
    #                                           )
    
                if not NODE_PARAMS.isdisjoint(params.keys()):
                    pass
    
            timeStep += 1

        # End of simulation by closing the SUMO simulator.
        except traci.FatalTraCIError as message:
            print message
            traci.close()
            #exit()
            break

    # After completed the generation of data for the simulation, save in the file.
    uniqueId = str(abs(hash(random())))

    # summary copy output
    fileSummary = FileManager(createName(uniqueId, '', summary=True))
    fileSummary.addData("\n".join(summaryData))

    # Instantiate the file objects for future manipulate.
    if not EDGE_PARAMS.isdisjoint(params.keys()):
        fileEval = FileManager(createName(uniqueId, EDGE_ALL, True))
        fileEval.addData(edgeMonitor.toStringEvaluate(separator))
        for param in EDGE_PARAMS:
            if params.has_key(param):
                fileBase = FileManager(createName(uniqueId, param))
                fileBase.addData(edgeMonitor.toString(param,separator))

    if not VEHICLE_PARAMS.isdisjoint(params.keys()):
        # TODO: needs a verification
        # Update all the vehicles arrived time for vehicles that not have really
        # arrived at end of simulation.
        vehicleMonitor.update(timeStepFinal)
        fileEval = FileManager(createName(uniqueId, VEHICLE_ALL, True))
        fileEval.addData(vehicleMonitor.toStringEvaluate(separator))
        for param in VEHICLE_PARAMS:
            if params.has_key(param):
                fileBase = FileManager(createName(uniqueId, param))
                fileBase.addData(vehicleMonitor.toString(param,separator))

    if not TRAFFIC_LIGHT_PARAMS.isdisjoint(params.keys()):
        fileEval = FileManager(createName(uniqueId, TRAFFIC_LIGHT_ALL, True))
        fileEval.addData(trafficLightsMonitor.toStringEvaluate(separator))
        for param in TRAFFIC_LIGHT_PARAMS:
            if params.has_key(param):
                fileBase = FileManager(createName(uniqueId, param))
                fileBase.addData(trafficLightsMonitor.toString(param,separator))

    if not NODE_PARAMS.isdisjoint(params.keys()):
        # TODO: need development
        pass

    exit()
Пример #60
0
 def close():
     """
     Closes traci client.
     """
     traci.close()