Example #1
0
def lazy_police(update_steps, t, directions):
    if (simulation.getCurrentTime() % 100) % update_steps == 0:
        max_halt = max([t.edges[d].edge_status['halt'] for d in directions])
        passway = (direction for direction, edge in t.edges.items()
                   if edge.edge_status['halt'] == max_halt).__next__()  # Search keys according to value
        print('Haltest: %s' % passway)
        t.set_passway(passway)
def run():
    global ct
    ct = 0
    edgesList = []
    vehicle_list = []
    #junction '386' is of interest to our adaptive traffic control lets subscribe to it
    junction_ID = '386'
    traci.junction.subscribeContext(junction_ID, tc.CMD_GET_VEHICLE_VARIABLE,
                                    42)
    #la route que g cree pour les vehicules sybils
    traci.route.add(routeID="r1",
                    edges=["-479572754#1", "-479572754#0", "-456316923"])
    print 'CA CEST LE PROGRAM'
    #print traci.trafficlights.getProgram('386')
    #A chaque 100 secondes, je genere 6 vehicules sybiles dont les identifiants commencent par 10000000 et a partir de 28000s
    d = 28000
    z = 0
    for i in range(40):
        v1 = "10000000" + str(z)
        v2 = "10000000" + str(z + 1)
        v3 = "10000000" + str(z + 2)
        v4 = "10000000" + str(z + 3)
        v5 = "10000000" + str(z + 4)
        v6 = "10000000" + str(z + 5)
        traci.vehicle.add(str(v1), "r1", depart=d, pos=0)
        traci.vehicle.add(str(v2), "r1", depart=d, pos=0)
        traci.vehicle.add(str(v3), "r1", depart=d, pos=0)
        traci.vehicle.add(str(v4), "r1", depart=d, pos=0)
        traci.vehicle.add(str(v5), "r1", depart=d, pos=0)
        traci.vehicle.add(str(v6), "r1", depart=d, pos=0)
        traci.vehicle.setColor(str(v1), (250, 0, 0, 0))
        traci.vehicle.setColor(str(v2), (250, 0, 0, 0))
        traci.vehicle.setColor(str(v3), (250, 0, 0, 0))
        traci.vehicle.setColor(str(v4), (250, 0, 0, 0))
        traci.vehicle.setColor(str(v5), (250, 0, 0, 0))
        traci.vehicle.setColor(str(v6), (250, 0, 0, 0))
        d = d + 100
        z = z + 6
    while ct < 32400000:
        traci.simulationStep()
        ct = simulation.getCurrentTime()
        #Insertion de vehicules sybiles
        p = traci.junction.getContextSubscriptionResults(junction_ID)
        if p is not None:
            temp = list(p)
            for x in temp:
                #g des vehicules sybiles que je ne veux pas coller a ma liste
                if ((vehicle_list.count(x) == 0) & (int(x) < 10000000)):
                    vehicle_list.append(x)
    outputVehicle = "Sybil_1_A_1/vehicles_around_junction" + junction_ID + str(
        opt.run) + ".txt"
    with open(outputVehicle, 'w') as out:
        for y in vehicle_list:
            out.write(y + '\n')
    out.close()
    traci.close()
    sys.stdout.flush()
def getTimeInQueue():
    t = sim.getCurrentTime() / 1000
    cumTime = 0
    for det_id in la.getIDList():
        for vid in la.getLastStepVehicleIDs(det_id):
            print('vid in getTimeinQueue:', vid)
            start = vehicles_in_queue.setdefault(vid, t)
            cumTime += t - vehicles_in_queue[vid]
    print(vehicles_in_queue)
    print(cumTime)
    return cumTime
Example #4
0
def run():
    global ct
    ct = 0
    edgesList = []
    vehicle_list = []
    #junctions '386', '428' and '376' is of interest to our adaptive traffic control lets subscribe to it
    junction_ID_1 = '386'
    junction_ID_2 = '428'
    junction_ID_3 = '376'
    traci.junction.subscribeContext(junction_ID_1, tc.CMD_GET_VEHICLE_VARIABLE,
                                    42)
    traci.junction.subscribeContext(junction_ID_2, tc.CMD_GET_VEHICLE_VARIABLE,
                                    42)
    traci.junction.subscribeContext(junction_ID_3, tc.CMD_GET_VEHICLE_VARIABLE,
                                    42)
    while ct < 32400000:
        traci.simulationStep()
        ct = simulation.getCurrentTime()

        #junction 1
        p = traci.junction.getContextSubscriptionResults(junction_ID_1)
        if p is not None:
            temp = list(p)
            for x in temp:
                if vehicle_list.count(x) == 0:
                    vehicle_list.append(x)
        #junction 2
        q = traci.junction.getContextSubscriptionResults(junction_ID_2)
        if q is not None:
            temp = list(q)
            for x in temp:
                if vehicle_list.count(x) == 0:
                    vehicle_list.append(x)
        #junction 3
        r = traci.junction.getContextSubscriptionResults(junction_ID_3)
        if r is not None:
            temp = list(r)
            for x in temp:
                if vehicle_list.count(x) == 0:
                    vehicle_list.append(x)

    outputVehicle = "Normal_3/vehicles_around_junction" + junction_ID_1 + junction_ID_2 + junction_ID_3 + str(
        opt.run) + ".txt"
    with open(outputVehicle, 'w') as out:
        for y in vehicle_list:
            out.write(y + '\n')
        out.close()
    traci.close()
    sys.stdout.flush()
Example #5
0
 def sim_step(self, action):
     if action is not None:
         for i in range(len(self.tls)):
             self.tls[i].set_passway(action[i])
     traci.simulationStep()
     current_step = int(simulation.getCurrentTime() / 1000)
     print("Current Step: %d" % current_step)
     log_list = []
     reward_list = []
     for t in self.tls:
         t_log, t_reward = t.update(current_step)
         log_list.append(t_log)
         reward_list.append(t_reward)
         if self.verbose:
             t.show()
     log = [item for sublist in log_list for item in sublist]  # Flatten the log
     return log, reward_list
Example #6
0
    tl_list=[]    
    for connection in connection_list:
        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()
Example #7
0
    for connection in connection_list:
        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()
def run():
	global ct
	ct = 0
	edgesList = []
	vehicle_list = []
	#junctions '386', '428' and '376' are of interest to our adaptive traffic control lets subscribe to them
	junction_ID_1 = '386'
	junction_ID_2 = '428'
	junction_ID_3 = '376'
	traci.junction.subscribeContext(junction_ID_1, tc.CMD_GET_VEHICLE_VARIABLE, 42)
	traci.junction.subscribeContext(junction_ID_2, tc.CMD_GET_VEHICLE_VARIABLE, 42)
	traci.junction.subscribeContext(junction_ID_3, tc.CMD_GET_VEHICLE_VARIABLE, 42)
	#les 3 routes que g cree pour les vehicules sybils
	traci.route.add(routeID="r1",edges=["-479572754#1","-479572754#0", "-456316923"])
	traci.route.add(routeID="r2",edges=["-300627772#1","-479572754#1", "-479572754#0"])
	traci.route.add(routeID="r3",edges=["-361607072","361607071", "479572754#0"])
	
	#A chaque 100 secondes, je genere 6 vehicules sybiles dont les identifiants commencent par 10000000 et a partir de 28000s
	d=28000
	z=0
	for i in range(40):
		v1="10000000" + str(z)
		v2="10000000" + str(z+1)
		v3="10000000" + str(z+2)
		v4="10000000" + str(z+3)
		v5="10000000" + str(z+4)
		v6="10000000" + str(z+5)
		v7="10000000" + str(z+6)
		v8="10000000" + str(z+7)
		v9="10000000" + str(z+8)
		v10="10000000" + str(z+9)
		v11="10000000" + str(z+10)
		v12="10000000" + str(z+11)
		v13="10000000" + str(z+12)
		v14="10000000" + str(z+13)
		v15="10000000" + str(z+14)
		v16="10000000" + str(z+15)
		v17="10000000" + str(z+16)
		v18="10000000" + str(z+17)
		traci.vehicle.add(str(v1),"r1",depart=d, pos=0)
		traci.vehicle.add(str(v2),"r1",depart=d, pos=0)
		traci.vehicle.add(str(v3),"r1",depart=d, pos=0)
		traci.vehicle.add(str(v4),"r1",depart=d, pos=0)
		traci.vehicle.add(str(v5),"r1",depart=d, pos=0)
		traci.vehicle.add(str(v6),"r1",depart=d, pos=0)
		traci.vehicle.add(str(v7),"r2",depart=d, pos=0)
		traci.vehicle.add(str(v8),"r2",depart=d, pos=0)
		traci.vehicle.add(str(v9),"r2",depart=d, pos=0)
		traci.vehicle.add(str(v10),"r2",depart=d, pos=0)
		traci.vehicle.add(str(v11),"r2",depart=d, pos=0)
		traci.vehicle.add(str(v12),"r2",depart=d, pos=0)
		traci.vehicle.add(str(v13),"r3",depart=d, pos=0)
		traci.vehicle.add(str(v14),"r3",depart=d, pos=0)
		traci.vehicle.add(str(v15),"r3",depart=d, pos=0)
		traci.vehicle.add(str(v16),"r3",depart=d, pos=0)
		traci.vehicle.add(str(v17),"r3",depart=d, pos=0)
		traci.vehicle.add(str(v18),"r3",depart=d, pos=0)
		traci.vehicle.setColor(str(v1),(250,0,0,0))
		traci.vehicle.setColor(str(v2),(250,0,0,0))
		traci.vehicle.setColor(str(v3),(250,0,0,0))
		traci.vehicle.setColor(str(v4),(250,0,0,0))
		traci.vehicle.setColor(str(v5),(250,0,0,0))
		traci.vehicle.setColor(str(v6),(250,0,0,0))
		traci.vehicle.setColor(str(v7),(0,250,0,0))
		traci.vehicle.setColor(str(v8),(0,250,0,0))
		traci.vehicle.setColor(str(v9),(0,250,0,0))
		traci.vehicle.setColor(str(v10),(0,250,0,0))
		traci.vehicle.setColor(str(v11),(0,250,0,0))
		traci.vehicle.setColor(str(v12),(0,250,0,0))
		traci.vehicle.setColor(str(v13),(0,0,250,0))
		traci.vehicle.setColor(str(v14),(0,0,250,0))
		traci.vehicle.setColor(str(v15),(0,0,250,0))
		traci.vehicle.setColor(str(v16),(0,0,250,0))
		traci.vehicle.setColor(str(v17),(0,0,250,0))
		traci.vehicle.setColor(str(v18),(0,0,250,0))
		d=d+100
		z=z+18
		
	while ct < 32400000:
		traci.simulationStep()
		ct = simulation.getCurrentTime()
		#Insertion de vehicules sybiles
		p=traci.junction.getContextSubscriptionResults(junction_ID_1)
		if p is not None:
			temp=list(p)
			for x in temp:
				#g des vehicules sybiles que je ne veux pas coller a ma liste
				if ((vehicle_list.count(x)==0) & (int(x)<10000000)):
					vehicle_list.append(x)
		q=traci.junction.getContextSubscriptionResults(junction_ID_2)
		if q is not None:
			temp=list(q)
			for x in temp:
				#g des vehicules sybiles que je ne veux pas coller a ma liste
				if ((vehicle_list.count(x)==0) & (int(x)<1000000)):
					vehicle_list.append(x)
		r=traci.junction.getContextSubscriptionResults(junction_ID_3)
		if r is not None:
			temp=list(r)
			for x in temp:
				#g des vehicules sybiles que je ne veux pas coller a ma liste
				if ((vehicle_list.count(x)==0) & (int(x)<1000000)):
					vehicle_list.append(x)
	outputVehicle = "Sybil_3_A_2/vehicles_around_junction" + junction_ID_1 + junction_ID_2 + junction_ID_3+ str(opt.run) +".txt"
	with open(outputVehicle,'w') as out:
		for y in vehicle_list:
			out.write(y + '\n')
	out.close()	
	traci.close()
	sys.stdout.flush()
def run(models, state_fn, action_time=12, learn=True, writer=None):
    print("File beginning", flush=True)
    tls_ids = tl.getIDList()
    step()  #traci.simulationStep()
    s = [None for i in range(len(tls_ids))]
    a = [None for i in range(len(tls_ids))]
    r = [None for i in range(len(tls_ids))]
    s_ = [None for i in range(len(tls_ids))]

    next_action_times = np.zeros(len(tls_ids), dtype=int)

    for t, tls_id in enumerate(tls_ids):
        tl.setPhase(tls_id, 2)
        # Find current states
        s[t] = state_fn(tls_id)

    checkpoint = False
    while sim.getMinExpectedNumber() > 0:
        if not checkpoint and "2000" in veh.getIDList():
            writer.add_text("Rate switch", "Vehicle 2000 encountered",
                            sim.getCurrentTime())
            checkpoint = True

        for t, tls_id in enumerate(tls_ids):
            db("Phase duration for " + tls_id, tl.getPhaseDuration(tls_id))
            if next_action_times[t] > 0:
                continue

            tl.setPhaseDuration(tls_id, 10000)
            # Take actions
            a[t] = models[t].select_action(s[t])

            current_phase = tl.getPhase(tls_id)
            if a[t] * 2 != current_phase:  # Change action
                db('Change to other green light')
                tl.setPhase(tls_id, (current_phase + 1) % 4)
                #print("phase:", tl.getPhase("0"))
                yellow_time = (tl.getNextSwitch(tls_id) -
                               sim.getCurrentTime()) // 1000
            else:
                yellow_time = 0

            next_action_times[t] = action_time + yellow_time

        db('actions:', a)
        db("-" * 10)

        # Move simulation forward one step and obtain reward
        #db(action_time + yellow_time)
        step_size = min(next_action_times)
        for j in range(step_size):
            step()  #traci.simulationStep()
            if sim.getMinExpectedNumber() <= 0:
                return

        next_action_times -= step_size

        # Get some kind of reward signal from the E2 loops
        # Let's say its negative of the number of cars on the loop

        for t, tls_id in enumerate(tls_ids):
            if next_action_times[t] > 0:
                continue

            r[t] = getReward(tls_id)
            if writer:
                writer.add_scalar('reward', r[t], sim.getCurrentTime())
            rewards_t.append(r)

            db("reward:", r)
            s_[t] = state_fn(tls_id)

            if learn:
                models[t].update(s[t], a[t], r[t], s_[t], alpha)
            s[t] = s_[t]