예제 #1
0
 def _simulate(self, num_step):
     traci.switch(self.label)
     # reward = np.zeros(len(self.control_node_names))
     for _ in range(num_step):
         self.sim.simulationStep()
         self.cur_sec += 1
         if self.is_record:
             self._measure_traffic_step()
예제 #2
0
 def simulator_switch(self, params):
     if params["type"] == "SUMO":
         try:
             traci.switch(params["id"])
         except Exception as e:
             raise e
         finally:
             pass
예제 #3
0
 def close(self):
     if self.sumo is None:
         return
     if not LIBSUMO:
         traci.switch(self.label)
     traci.close()
     try:
         self.disp.stop()
     except AttributeError:
         pass
     self.sumo = None
예제 #4
0
 def run_sumo(self):
     global set_phase_ltk, set_phase_lgtht
     traci.switch("sumovn")
     """execute the TraCI control loop"""
     print('running')
     step = 0
     while traci.simulation.getMinExpectedNumber() > 0:
         print(traci.simulation.getMinExpectedNumber())
         traci.simulationStep()
         step += 1
     traci.close()
     sys.stdout.flush()
예제 #5
0
 def _measure_state_step(self):
     traci.switch(self.label)
     for node_name in self.node_names:
         node = self.nodes[node_name]
         for state_name in self.state_names:
             if state_name == 'wave':
                 cur_state = []
                 for k, ild in enumerate(node.ilds_in):
                     if self.name == 'atsc_real_net':
                         cur_wave = 0
                         for ild_seg in ild:
                             cur_wave += self.sim.lane.getLastStepVehicleNumber(
                                 ild_seg)
                         cur_wave /= node.lanes_capacity[k]
                         # cur_wave = min(1.5, cur_wave / QUEUE_MAX)
                     else:
                         cur_wave = self.sim.lanearea.getLastStepVehicleNumber(
                             ild)
                     cur_state.append(cur_wave)
                 cur_state = np.array(cur_state)
             elif state_name == 'wait':
                 cur_state = []
                 for ild in node.ilds_in:
                     max_pos = 0
                     car_wait = 0
                     if self.name == 'atsc_real_net':
                         cur_cars = self.sim.lane.getLastStepVehicleIDs(
                             ild[0])
                     else:
                         cur_cars = self.sim.lanearea.getLastStepVehicleIDs(
                             ild)
                     for vid in cur_cars:
                         car_pos = self.sim.vehicle.getLanePosition(vid)
                         if car_pos > max_pos:
                             max_pos = car_pos
                             car_wait = self.sim.vehicle.getWaitingTime(vid)
                     cur_state.append(car_wait)
                 cur_state = np.array(cur_state)
             if self.record_stats:
                 self.state_stat[state_name] += list(cur_state)
             # normalization
             norm_cur_state = self._norm_clip_state(cur_state,
                                                    self.norms[state_name],
                                                    self.clips[state_name])
             if state_name == 'wave':
                 node.wave_state = norm_cur_state
             else:
                 node.wait_state = norm_cur_state
예제 #6
0
 def _measure_traffic_step(self):
     traci.switch(self.label)
     cars = self.sim.vehicle.getIDList()
     num_tot_car = len(cars)
     num_in_car = self.sim.simulation.getDepartedNumber()
     num_out_car = self.sim.simulation.getArrivedNumber()
     if num_tot_car > 0:
         avg_waiting_time = np.mean(
             [self.sim.vehicle.getWaitingTime(car) for car in cars])
         avg_speed = np.mean(
             [self.sim.vehicle.getSpeed(car) for car in cars])
     else:
         avg_speed = 0
         avg_waiting_time = 0
     # all trip-related measurements are not supported by traci,
     # need to read from outputfile afterwards
     queues = []
     for node_name in self.node_names:
         for ild in self.nodes[node_name].ilds_in:
             if self.name == 'atsc_real_net':
                 cur_queue = 0
                 for ild_seg in ild:
                     cur_queue += self.sim.lane.getLastStepHaltingNumber(
                         ild_seg)
             else:
                 cur_queue = self.sim.lane.getLastStepHaltingNumber(ild)
             queues.append(cur_queue)
     queues = np.array(queues)
     avg_queue = np.mean(queues)
     std_queue = np.std(queues)
     cur_traffic = {
         'episode': self.cur_episode,
         'time_sec': self.cur_sec,
         'number_total_car': num_tot_car,
         'number_departed_car': num_in_car,
         'number_arrived_car': num_out_car,
         'avg_wait_sec': avg_waiting_time,
         'avg_speed_mps': avg_speed,
         'std_queue': std_queue,
         'avg_queue': avg_queue
     }
     self.traffic_data.append(cur_traffic)
예제 #7
0
 def reset(self, gui=False, test_ind=0):
     # have to terminate previous sim before calling reset
     self._reset_state()
     if self.train_mode:
         seed = self.seed
     else:
         seed = self.test_seeds[test_ind]
     try:
         self.terminate()
     except:
         pass
     self._init_sim(seed, gui=gui)
     traci.switch(self.label)
     self.cur_sec = 0
     self.cur_episode += 1
     # initialize fingerprint
     self.update_fingerprint(self._init_policy())
     # next environment random condition should be different
     self.seed += 1
     return self._get_state()
예제 #8
0
 def _init_nodes(self):
     traci.switch(self.label)
     nodes = {}
     tl_nodes = self.sim.trafficlight.getIDList()
     for node_name in self.node_names:
         if node_name not in tl_nodes:
             logging.error('node %s can not be found!' % node_name)
             exit(1)
         neighbor = self.neighbor_map[node_name]
         nodes[node_name] = Node(node_name, neighbor=neighbor, control=True)
         # controlled lanes: l:j,i_k
         lanes_in = self.sim.trafficlight.getControlledLanes(node_name)
         ilds_in = []
         lanes_cap = []
         for lane_name in lanes_in:
             if self.name == 'atsc_real_net':
                 cur_ilds_in = [lane_name]
                 if (node_name, lane_name) in self.extended_lanes:
                     cur_ilds_in += self.extended_lanes[(node_name,
                                                         lane_name)]
                 ilds_in.append(cur_ilds_in)
                 cur_cap = 0
                 for ild_name in cur_ilds_in:
                     cur_cap += self.sim.lane.getLength(ild_name)
                 lanes_cap.append(cur_cap / float(VEH_LEN_M))
             else:
                 ilds_in.append(lane_name)
         nodes[node_name].ilds_in = ilds_in
         if self.name == 'atsc_real_net':
             nodes[node_name].lanes_capacity = lanes_cap
     self.nodes = nodes
     s = 'Env: init %d node information:\n' % len(self.node_names)
     for node_name in self.node_names:
         s += node_name + ':\n'
         node = self.nodes[node_name]
         s += '\tneigbor: %r\n' % node.neighbor
         s += '\tilds_in: %r\n' % node.ilds_in
     logging.info(s)
     self._init_action_space()
     self._init_state_space()
예제 #9
0
 def _measure_reward_step(self):
     traci.switch(self.label)
     rewards = []
     for node_name in self.node_names:
         queues = []
         waits = []
         for ild in self.nodes[node_name].ilds_in:
             if self.obj in ['queue', 'hybrid']:
                 if self.name == 'atsc_real_net':
                     cur_queue = self.sim.lane.getLastStepHaltingNumber(
                         ild[0])
                     cur_queue = min(cur_queue, QUEUE_MAX)
                 else:
                     cur_queue = self.sim.lanearea.getLastStepHaltingNumber(
                         ild)
                 queues.append(cur_queue)
             if self.obj in ['wait', 'hybrid']:
                 max_pos = 0
                 car_wait = 0
                 if self.name == 'atsc_real_net':
                     cur_cars = self.sim.lane.getLastStepVehicleIDs(ild[0])
                 else:
                     cur_cars = self.sim.lanearea.getLastStepVehicleIDs(ild)
                 for vid in cur_cars:
                     car_pos = self.sim.vehicle.getLanePosition(vid)
                     if car_pos > max_pos:
                         max_pos = car_pos
                         car_wait = self.sim.vehicle.getWaitingTime(vid)
                 waits.append(car_wait)
         queue = np.sum(np.array(queues)) if len(queues) else 0
         wait = np.sum(np.array(waits)) if len(waits) else 0
         if self.obj == 'queue':
             reward = -queue
         elif self.obj == 'wait':
             reward = -wait
         else:
             reward = -queue - self.coef_wait * wait
         rewards.append(reward)
     return np.array(rewards)
예제 #10
0
 def _init_sim(self, seed, gui=False):
     sumocfg_file = self._init_sim_config(seed)
     if gui:
         app = 'sumo-gui'
     else:
         app = 'sumo'
     command = [checkBinary(app), '-c', sumocfg_file]
     command += ['--seed', str(seed)]
     command += ['--no-step-log', 'True']
     command += ['--time-to-teleport', '600']  # long teleport for safety
     command += ['--no-warnings', 'True']
     command += ['--duration-log.disable', 'True']
     # collect trip info if necessary
     if self.is_record:
         command += [
             '--tripinfo-output',
             self.output_path + ('%s_%s_trip.xml' % (self.name, self.agent))
         ]
     print(f"Initializing sumo with label {self.label}")
     traci.start(command, label=self.label)
     traci.switch(self.label)
     # wait 1s to establish the traci server
     time.sleep(1)
     self.sim = traci
예제 #11
0
    def run_sumo(self):       
        global set_phase_ltk, set_phase_lgtht, connected, isfirst, issetparams, HOST, PORT
        global list_vehicle_ltkbd, list_vehicle_ltkntd, list_vehicle_lg, list_vehicle_tht       
        traci.switch("sumovn")       
        """execute the TraCI control loop"""
        print('running')
        httphost_get = 'http://'+self.HOST+':'+self.PORT+'/home/gettldata' 
        httphost_put = 'http://'+self.HOST+':'+self.PORT+'/home/puttldata' 
        httphost_putdetails = 'http://'+self.HOST+':'+self.PORT+'/home/puttldatadetails' 
        step = 0
        putdatadetail = False
        while traci.simulation.getMinExpectedNumber() > 0:                  
            traci.simulationStep()          

            #list vehicle in lane
            # print(traci.lane.getLastStepVehicleIDs("ltk32_e10_1"))   
            

            if (int(traci.simulation.getTime())%181) == 0:
                putdatadetail = False

            if (int(traci.simulation.getTime())%180) == 0 and int(traci.simulation.getTime()) > 0 and putdatadetail == False:   
                print("Vehicle come 3 minute ago")             
                print("lg come: ", len(self.list_vehicle_lg))
                print("tht come: ", len(self.list_vehicle_tht))
                print("ltkbd come: ", len(self.list_vehicle_ltkbd))
                print("ltkntd come: ", len(self.list_vehicle_ltkntd))
                
                print("ltkbd pass: "******"ltkntd pass: "******"lg pass: "******"tht pass: "******"ltk32_e10_0") + traci.lane.getLastStepMeanSpeed("ltk32_e10_1"))/2
                    vtb_ltkbd = (traci.lane.getLastStepMeanSpeed("ltkbh_e2_0") + traci.lane.getLastStepMeanSpeed("ltkbh_e2_1"))/2
                    vtb_lg = (traci.lane.getLastStepMeanSpeed("lg_e28_0") + traci.lane.getLastStepMeanSpeed("lg_e29_0"))/2
                    vtb_tht = traci.lane.getLastStepMeanSpeed("tht_e13_0")
                    
                    result_ltkntd = self.queueVehicleLength_ltkntd()    
                    result_ltkbd = self.queueVehicleLength_ltkbd() 
                    result_lg = self.queueVehicleLength_lg() 
                    result_tht = self.queueVehicleLength_tht()
                    info = {'id':'ltk_lg','apprid1':'ltklg_bd', 'apprid2':'ltklg_ntd', 'apprid3':'ltklg_lg', 'apprid4':'ltklg_tht', 'vhccome1': len(self.list_vehicle_ltkbd), 'vhccome2': len(self.list_vehicle_ltkntd), 'vhccome3': len(self.list_vehicle_lg), 'vhccome4': len(self.list_vehicle_tht), 'vhcout1': len(self.list_vehiclepass_ltkbd), 'vhcout2': len(self.list_vehiclepass_ltkntd), 'vhcout3': len(self.list_vehiclepass_lg), 'vhcout4': len(self.list_vehiclepass_tht),'vtb1':vtb_ltkbd, 'vtb2': vtb_ltkntd, 'vtb3': vtb_lg, 'vtb4': vtb_tht, 'queue_elength1': result_ltkbd[0], 'queue_elength2': result_ltkntd[0], 'queue_elength3': result_lg[0], 'queue_elength4': result_tht[0], 'waittime1': result_ltkbd[1], 'waittime2': result_ltkntd[1], 'waittime3': result_lg[1], 'waittime4': result_tht[1]}      
                    res = requests.get(httphost_putdetails, params = info)                    
                    self.list_vehicle_lg = []
                    self.list_vehicle_tht = []
                    self.list_vehicle_ltkbd = []
                    self.list_vehicle_ltkntd = []
                    self.list_vehiclepass_ltkbd = []
                    self.list_vehiclepass_ltkntd = []
                    self.list_vehiclepass_lg = []
                    self.list_vehiclepass_tht = []
                    putdatadetail = True

            self.countVehicleCome(traci.inductionloop.getIDList())                             

            phase = traci.trafficlights.getPhase("ltk_intersection")          

            if (self.connected == True and self.issetparams == False):
                try:
                    info = {'id':'ltk_lg'}      
                    res = requests.get(httphost_get, params = info) 
                    self.connected = True
                except:
                    self.connected = False 
                    print("connect fail")                    

                if (res.json()['isparams'] == True):    
                    print("set params")
                    self.ltk_green = res.json()['phase1']
                    self.set_phase_ltk = True 
                   
                    self.lgtht_green = res.json()['phase2']  
                    self.set_phase_lgtht = True 
                
                if (self.isfirst == True):
                    global fltk_green, flgtht_green
                    if (phase == 0):
                        self.fltk_green = int(traci.trafficlights.getPhaseDuration("ltk_intersection"))
                    if (phase == 2):  
                        self.flgtht_green = int(traci.trafficlights.getPhaseDuration("ltk_intersection"))

                    if (self.fltk_green != 0 and self.flgtht_green != 0):    
                        info = {'id':'ltk_lg', 'p1': self.fltk_green, 'p2': self.flgtht_green, 'firstparams': False}   
                        res = requests.get(httphost_put, params = info)
                        self.isfirst = False
                        print("put param to server")  
                        print(self.fltk_green) 
                        print(self.flgtht_green)

                if (self.set_phase_ltk == True and phase == 0 and int(self.ltk_green) > 10): 
                    old_ltk_green = traci.trafficlights.getPhaseDuration("ltk_intersection")
                    print(old_ltk_green)
                    if(int(self.ltk_green) != int(old_ltk_green)):
                        traci.trafficlights.setPhaseDuration("ltk_intersection", int(self.ltk_green))
                        self.set_phase_ltk = False
                        print("success ltk: ",int(self.ltk_green))
                        info = {'id':'ltk_lg','bparams': False}   
                        res = requests.get(httphost_put, params = info)
                   
                if (self.set_phase_lgtht == True and phase == 2 and int(self.lgtht_green) > 10): 
                    old_lgtht_green = traci.trafficlights.getPhaseDuration("ltk_intersection")
                    if(int(self.lgtht_green) != int(old_lgtht_green)):
                        traci.trafficlights.setPhaseDuration("ltk_intersection", int(self.lgtht_green)) 
                        self.set_phase_lgtht = False
                        print("success lgtht: ",self.lgtht_green) 
                        info = {'id':'ltk_lg','bparams': False}   
                        res = requests.get(httphost_put, params = info)
            else: 
                # print("normal")                    
                if (self.set_phase_ltk == True and phase == 0 and int(self.ltk_green) > 10): 
                    old_ltk_green = traci.trafficlights.getPhaseDuration("ltk_intersection")
                    print(old_ltk_green)
                    print(int(self.ltk_green))
                    if(int(self.ltk_green) != int(old_ltk_green)):
                        traci.trafficlights.setPhaseDuration("ltk_intersection", int(self.ltk_green))
                        self.set_phase_ltk = False
                        print("success ltk: ",self.ltk_green)
                        # self.isfirst = True
                        # self.issetparams = False
                    else:   
                        self.set_phase_ltk = False  
                   
                if (self.set_phase_lgtht == True and phase == 2 and int(self.lgtht_green) > 10): 
                    old_lgtht_green = traci.trafficlights.getPhaseDuration("ltk_intersection")
                    if(int(self.lgtht_green) != int(old_lgtht_green)):
                        traci.trafficlights.setPhaseDuration("ltk_intersection", int(self.lgtht_green)) 
                        self.set_phase_lgtht = False
                        print("success lgtht: ",self.lgtht_green)       
                        # self.isfirst = True     
                        # self.issetparams = False   
                    else:
                        self.set_phase_lgtht = False    
                
                if (self.set_phase_ltk == False and self.set_phase_lgtht == False):
                    # print("TaiNgo")
                    self.issetparams = False 

            # print("step ",step)        
            step += 1            
        traci.close()
        sys.stdout.flush() 
def calculate_features(sim, SUMO):
    try:
        simulation = traci.getConnection(sim)
        traci.switch(sim)
        sub_ego = simulation.vehicle.getSubscriptionResults(
            trafic.vehicle_ego.ID)
        if SUMO.Collision:  # collision happened!
            features.distance = 0  # set the distance of the cars after a collision to 0
            features.v_prec = SUMO.v_prec[
                SUMO.
                step]  # set the velocity of the preceding car after a collision to the value of the previous timestep
            features.v_ego = SUMO.v_ego[
                SUMO.
                step]  # set the velocity of the ego car after a collision to the value of the previous timestep
        elif SUMO.RouteEnd:
            features.distance = SUMO.distance[
                SUMO.
                step]  # set the distance of the cars after preceding vehicle ends route to previous timestep
            features.v_prec = SUMO.v_prec[
                SUMO.
                step]  # set the velocity of the preceding car after preceding vehicle ends route to the value of the previous timestep
            features.v_ego = SUMO.v_ego[
                SUMO.
                step]  # set the velocity of the ego car after preceding vehicle ends route to the value of the previous timestep
        else:
            ## TLS Distance
            if traci.constants.VAR_NEXT_TLS in sub_ego and len(
                    sub_ego[traci.constants.VAR_NEXT_TLS]) > 0:
                features.distance_TLS = sub_ego[
                    traci.constants.VAR_NEXT_TLS][0][2]
                features.TLS_state = sub_ego[
                    traci.constants.VAR_NEXT_TLS][0][3]
            else:
                features.distance_TLS = 1000  # TODO: Handling when no TLS ahead
                features.TLS_state = None

            ## v_ego
            features.v_ego = sub_ego[traci.constants.VAR_SPEED]

            #        print(dynamics_ego.fuel_cons_per_100km)
            ## fuel_consumption
            trafic.vehicle_ego.fuel_cons[SUMO.step + 1] = sub_ego[
                traci.constants.VAR_FUELCONSUMPTION]  # in ml/s
            #        trafic.vehicle_ego.fuel_cons_ECMS[SUMO.step + 1] = dynamics_ego.fuel_cons_per_100km
            #        trafic.vehicle_ego.fuel_cons_ECMS_per_s[SUMO.step + 1] = dynamics_ego.fuel_cons_per_s

            ## distance, v_prec
            try:
                if traci.constants.VAR_LEADER in sub_ego:
                    trafic.vehicle_ego.ID_prec, features.distance = sub_ego[
                        traci.constants.VAR_LEADER]
                    SUMO.distance[SUMO.step + 1] = features.distance
                    features.distance = np.clip(features.distance, None, 250.)
                    features.v_prec = simulation.vehicle.getSpeed(
                        trafic.vehicle_ego.ID_prec)
                    SUMO.v_prec[SUMO.step + 1] = features.v_prec
                else:
                    raise TypeError
            except TypeError:
                features.distance = 250
                SUMO.distance[SUMO.step + 1] = features.distance
                SUMO.v_prec[SUMO.step + 1] = features.v_ego
                trafic.vehicle_ego.ID_prec = 'none'
            if features.distance == 250:
                features.v_prec = copy(
                    features.v_ego
                )  # when no preceding car detected OR distance > 250 (clipped), set a 'virtual velocity' = v_ego

            ## correct distance, v_prec with virtual TLS vehicle
            if trafic.TLS_virt_vehicle:
                if features.TLS_state == 'y' or features.TLS_state == 'r':
                    if features.distance_TLS < features.distance:
                        features.distance = copy(features.distance_TLS)
                        features.v_prec = 0

            ## headway
            if features.v_ego < 0.1:
                features.headway = 10000.
            else:
                features.headway = features.distance / features.v_ego

            ## v_allowed
            if traci.constants.VAR_LANE_ID in sub_ego:
                features.v_allowed = simulation.lane.getMaxSpeed(
                    sub_ego[traci.constants.VAR_LANE_ID])
            else:
                features.v_allowed = 33.33  # tempo limit set to 120 km/h when no signal received, unlikely to happen

        ## plotting variables
        SUMO.headway[SUMO.step + 1] = features.headway
        SUMO.v_ego[SUMO.step + 1] = features.v_ego
    except Exception as ex:
        template = "An exception of type {0} occurred. Arguments:\n{1!r}"
        message = template.format(type(ex).__name__, ex.args)
        #        fitness=timestep
        raise Exception('My error! Calc features', message)
def calculate_features_firststep(sim, SUMO):
    try:
        simulation = traci.getConnection(sim)
        traci.switch(sim)
        #    state = np.zeros([1, feature_number])
        sub_ego = simulation.vehicle.getSubscriptionResults(
            trafic.vehicle_ego.ID)
        #    print(sub_ego[traci.constants.VAR_NEXT_TLS])
        ## TLS Distance
        if traci.constants.VAR_NEXT_TLS in sub_ego and len(
                sub_ego[traci.constants.VAR_NEXT_TLS]) > 0:
            features.distance_TLS = sub_ego[traci.constants.VAR_NEXT_TLS][0][2]
            features.TLS_state = sub_ego[traci.constants.VAR_NEXT_TLS][0][3]
        else:
            features.distance_TLS = 1000  # TODO: Handling when no TLS ahead
            features.TLS_state = None
        errorat = 1
        ## v_ego
        if traci.constants.VAR_SPEED in sub_ego:
            SUMO.v_ego[SUMO.step] = sub_ego[traci.constants.VAR_SPEED]
        else:
            SUMO.v_ego[SUMO.step] = 0.
        features.v_ego = SUMO.v_ego[SUMO.step]

        ## Fuel Consumption
        if traci.constants.VAR_FUELCONSUMPTION in sub_ego:
            trafic.vehicle_ego.fuel_cons[SUMO.step] = sub_ego[
                traci.constants.VAR_FUELCONSUMPTION]
        else:
            trafic.vehicle_ego.fuel_cons[SUMO.step] = 0.
        errorat = 2
        ## distance, v_prec
        try:
            if traci.constants.VAR_LEADER in sub_ego:
                trafic.vehicle_ego.ID_prec, features.distance = sub_ego[
                    traci.constants.VAR_LEADER]
                SUMO.distance[SUMO.step] = features.distance
                features.distance = np.clip(features.distance, None, 250.)
                features.v_prec = simulation.vehicle.getSpeed(
                    trafic.vehicle_ego.ID_prec)
                SUMO.v_prec[SUMO.step] = features.v_prec
                if features.distance == 250:
                    features.v_prec = features.v_ego
            else:
                raise TypeError
        except TypeError:
            trafic.vehicle_ego.ID_prec = 'none'
            features.distance = 250
            SUMO.distance[SUMO.step] = features.distance
            SUMO.v_prec[SUMO.step] = features.v_ego
        if features.distance == 250:
            features.v_prec = copy(features.v_ego)
        errorat = 3
        ## v_allowed
        if traci.constants.VAR_LANE_ID in sub_ego:
            features.v_allowed = simulation.lane.getMaxSpeed(
                sub_ego[traci.constants.VAR_LANE_ID])
        else:
            features.v_allowed = 33.33  # tempo limit set to 120 km/h when no signal received, unlikely to happen

        ## correct distance, v_prec with virtual TLS vehicle
        if trafic.TLS_virt_vehicle:
            if features.TLS_state == 'y' or features.TLS_state == 'r':
                if features.distance_TLS < features.distance:
                    features.distance = copy(features.distance_TLS)
                    features.v_prec = 0

        ## headway
        if features.v_ego < 0.1:
            features.headway = 10000.
        else:
            features.headway = features.distance / features.v_ego
        SUMO.headway[SUMO.step] = features.headway
    except Exception as ex:
        template = "An exception of type {0} occurred. Arguments:\n{1!r}"
        message = template.format(type(ex).__name__, ex.args)
        #        fitness=timestep
        raise Exception('My error! firststep', errorat, message)
예제 #14
0
            station.bikes.append(new_bike)
            allBikes.append(new_bike)
            bikeID += 1
            station.predictedOcc = [len(station.bikes)] * (endSim + 60 * 1000)

    totalDemand = sorted(totalDemand, key=itemgetter(0))
    demand = totalDemand[:]

    # control case
    station_occ, unsat_demand = run_control()
    station_occ = [station_occ]
    unsat_demand = [unsat_demand]

    ############# different control methods to be tested with the same set of demand: #####################
    traci.start(['sumo', "-c", "melbourneFeedback.sumocfg"], label="sim1")
    traci.switch("sim1")
    demand = totalDemand[:]
    resetSim(ini_full)
    station_occ_temp, unsat_demand_temp = run(1)
    station_occ.append(station_occ_temp)
    unsat_demand.append(unsat_demand_temp)

    traci.start(['sumo', "-c", "melbourneFeedback2.sumocfg"], label="sim2")
    traci.switch("sim2")
    resetSim(ini_full)
    demand = totalDemand[:]
    station_occ_temp, unsat_demand_temp = run(2)
    station_occ.append(station_occ_temp)
    unsat_demand.append(unsat_demand_temp)

    traci.start(['sumo', "-c", "melbourneFeedback3.sumocfg"], label="sim3")
예제 #15
0
                           p_east_west=0.2,
                           p_north_south=0.2,
                           p_south_north=0.1)

        print('Starting Episode ' + str(e) + '...')

        # this is the normal way of using traci. sumo is started as a
        # subprocess and then the python script connects and runs
        traci.start([
            sumoBinary, "-c", "data/cross.sumocfg", "--time-to-teleport", "-1",
            "--tripinfo-output", "tripinfo.xml", '--start', '-Q'
        ],
                    label='contestant')
        # Connection to simulation environment
        conn = traci.getConnection("contestant")
        # Run a complete simulation episode with the agent taking actions for as long as the episode lasts.
        # An episode lasts as long as there are cars in the simulation AND the time passed < 1000 seconds
        total_waiting_time, waiting_times, total_emissions = run_episode(
            conn, agent, COMPETITION_ROUND)
        # Cleaning up TraCi environments
        traci.switch("contestant")
        traci.close()
        # Calculate the avg waiting time per vehicle
        avg_waiting_time = total_waiting_time / vehicles
        avg_emissions = total_emissions / (1000 * vehicles)
        waiting_time_per_episode.append(avg_waiting_time)

        print('episode[' + str(e) + '] Average waiting time = ' +
              str(avg_waiting_time) + ' (s) -- Average Emissions (CO2) = ' +
              str(avg_emissions) + "(g)")
예제 #16
0
    def run_sumo(self):       
        global set_phase_ltkhvt, set_phase_tccmt8, connected, HOST, PORT     
        traci.switch("sumovn")       
        """execute the TraCI control loop"""
        print('running')   
        httphost_putdetails = 'http://'+self.HOST+':'+self.PORT+'/home/puttldatadetails' 
        httphost_get = 'http://'+self.HOST+':'+self.PORT+'/home/gettldata'  
        httphost_put = 'http://'+self.HOST+':'+self.PORT+'/home/puttldata'   
        httphost_puttl = 'http://'+self.HOST+':'+self.PORT+'/home/puttrafficlightdata' 
        step = 0
        putdatadetail = False
        while traci.simulation.getMinExpectedNumber() > 0:                  
            traci.simulationStep()                                         

            self.countVehicleCome(traci.inductionloop.getIDList())
            if (int(traci.simulation.getTime())%181) == 0:
                putdatadetail = False
            if (int(traci.simulation.getTime())%180) == 0 and int(traci.simulation.getTime()):   
                print("Vehicle come 3 minute ago")                  
                result_ltk = self.queueVehicleLength_ltk()          
                result_cmt8 = self.queueVehicleLength_cmt8()   
                result_tc = self.queueVehicleLength_tc() 

                vtb_ltk = (traci.lane.getLastStepMeanSpeed("ltk_e2_0") + traci.lane.getLastStepMeanSpeed("ltk_e2_1"))/2
                vtb_cmt8 = (traci.lane.getLastStepMeanSpeed("cmt8_e2_0") + traci.lane.getLastStepMeanSpeed("cmt8_e2_1"))/2
                vtb_tc = (traci.lane.getLastStepMeanSpeed("tc_e2_0") + traci.lane.getLastStepMeanSpeed("tc_e2_1"))/2  
                vtb_hvt = (traci.lane.getLastStepMeanSpeed("hvt_e2_0") + traci.lane.getLastStepMeanSpeed("hvt_e2_1") + traci.lane.getLastStepMeanSpeed("hvt_e5_0") + traci.lane.getLastStepMeanSpeed("hvt_e5_1"))/4 
                print("ltk come: ", len(self.list_vehicle_ltk))
                print("tc come: ", len(self.list_vehicle_tc))
                print("cmt8 come: ", len(self.list_vehicle_cmt8))              
                
                print("ltk pass: "******"hvt pass: "******"cmt8 pass: "******"connect fail")   

                self.list_vehicle_ltk = []
                self.list_vehicle_cmt8 = []
                self.list_vehicle_tc = []                    
                self.list_vehiclepass_ltk = []
                self.list_vehiclepass_cmt8 = []
                self.list_vehiclepass_hvt = []     


            if (self.connected == True and self.issetparams == False):
                try:
                    info = {'id':'bayhien'}      
                    res = requests.get(httphost_get, params = info)                     
                    self.connected = True                    
                except:
                    self.connected = False                    
                    self.isfirst = True       
                    self.disconnectButton.configure(state=DISABLED)     
                    self.connectButton.configure(state=NORMAL)
                    print("connect fail") 

                if (self.connected == True):
                    if (res.json()['isparams'] == 'True'):                            
                        print("set params")
                        self.set_phase_tccmt8 = True
                        self.set_phase_ltkhvt = True   
                        # print(len(res.json()['trafficlight']))
                        for i in range(len(res.json()['trafficlight'])):                      
                            if (res.json()['trafficlight'][i]['apprid'] == 'tc_cmt8'):
                                self.tccmt8_green = res.json()['trafficlight'][i]['tlgreen']
                            if (res.json()['trafficlight'][i]['apprid'] == 'ltk_hvt'):
                                self.ltkhvt_green = res.json()['trafficlight'][i]['tlgreen']

                        info = {'id':'bayhien','bparams': False}   
                        res = requests.get(httphost_put, params = info)
                
            phase = traci.trafficlights.getPhase("bayhien_intersection")   

            global ftccmt8_green, fltkhvt_green, ftccmt8_yellow, fltkhvt_yellow
            if (self.isfirst == True and self.connected == True):               
                if (phase == 0):
                    self.ftccmt8_green = int(traci.trafficlights.getPhaseDuration("bayhien_intersection"))
                if (phase == 1):
                    self.ftccmt8_yellow = int(traci.trafficlights.getPhaseDuration("bayhien_intersection"))
                if (phase == 2):  
                    self.fltkhvt_green = int(traci.trafficlights.getPhaseDuration("bayhien_intersection"))
                if (phase == 3):  
                    self.fltkhvt_yellow = int(traci.trafficlights.getPhaseDuration("bayhien_intersection"))
                # print("first",  self.ftccmt8_green, self.fltkhvt_green)    
                if (self.ftccmt8_green != 0 and self.fltkhvt_green != 0 and self.ftccmt8_yellow != 0 and self.fltkhvt_yellow != 0):    
                    info = {'id':'bayhien', 'apprid': 'tc_cmt8', 'tlgreen': self.ftccmt8_green, 'tlyellow': self.ftccmt8_yellow, 'tlred': self.fltkhvt_green}   
                    res = requests.get(httphost_puttl, params = info)
                    info = {'id':'bayhien', 'apprid': 'ltk_hvt', 'tlgreen': self.fltkhvt_green, 'tlyellow': self.fltkhvt_yellow, 'tlred': self.ftccmt8_green}
                    res = requests.get(httphost_puttl, params = info)
                    self.isfirst = False
                    print("put param to server")  
                    print(self.ftccmt8_green) 
                    print(self.fltkhvt_green)
                    self.ftccmt8_green = 0
                    self.fltkhvt_green = 0                    

            # print("normal")                    
            if (self.set_phase_tccmt8 == True and phase == 0 and int(self.tccmt8_green) > 10): 
                old_tccmt8_green = traci.trafficlights.getPhaseDuration("bayhien_intersection")                
                if(int(self.tccmt8_green) != int(old_tccmt8_green)):
                    traci.trafficlights.setPhaseDuration("bayhien_intersection", int(self.tccmt8_green))
                    self.set_phase_tccmt8 = False
                    print("success tccmt8: ",self.tccmt8_green)                   
                else:   
                    self.set_phase_tccmt8 = False  
                   
            if (self.set_phase_ltkhvt == True and phase == 2 and int(self.ltkhvt_green) > 10): 
                old_ltkhvt_green = traci.trafficlights.getPhaseDuration("bayhien_intersection")
                if(int(self.ltkhvt_green) != int(old_ltkhvt_green)):
                    traci.trafficlights.setPhaseDuration("bayhien_intersection", int(self.ltkhvt_green)) 
                    self.set_phase_ltkhvt = False
                    print("success ltkhvt: ",self.ltkhvt_green)       
                else:
                    self.set_phase_ltkhvt = False                    
            # print("step ",step)        
            step += 1            
        traci.close()
        sys.stdout.flush()    
예제 #17
0
 def _set_phase(self, action, phase_type, phase_duration):
     traci.switch(self.label)
     for node_name, a in zip(self.node_names, list(action)):
         phase = self._get_node_phase(a, node_name, phase_type)
         self.sim.trafficlight.setRedYellowGreenState(node_name, phase)
         self.sim.trafficlight.setPhaseDuration(node_name, phase_duration)
예제 #18
0
 def terminate(self):
     traci.switch(self.label)
     self.sim.close()
예제 #19
0
            station.predictedOcc = [len(station.bikes)] * (endSim + 60 * 300)

    for station in stations:
        for neighbour in station.neighbourhood:
            print(station.name, neighbour.name)
    totalDemand = sorted(totalDemand, key=itemgetter(0))
    times1 = totalDemand[:]
    times2 = totalDemand[:]
    times3 = totalDemand[:]

    station_occ = [[] for x in range(len(stations))]
    unsat_demand = [[] for x in range(len(stations))]
    # run()

    traci.start(['sumo', "-c", "melbourneFeedback.sumocfg"], label="sim2")
    traci.switch("sim2")

    resetSim()
    station_occ2, unsat_demand2 = run2()

    traci.start(['sumo', "-c", "melbourneFeedback2.sumocfg"], label="sim3")
    traci.switch("sim3")

    resetSim()
    station_occ3, unsat_demand3 = run3()

    time = np.arange(0, 10800)
    # f = plt.figure(1)
    xlim = np.arange(0, 60 * 60 * 3.5, 60 * 60)
    # for i in range(len(stations)):
    #     plt.plot(time, station_occ[i])
예제 #20
0
 def step(self, action=None):
     traci.switch(self.thread_label)
     log, reward_list = self.traci_env.sim_step(action)
     terminate = self.traci_env.is_terminated()
     info = None
     return log, reward_list, terminate, info