def run(): if len(sys.argv) < 2: print('Please provide the path to the .sumocfg of a SUMO scenario') exit() print('started') ## GUI / CLI # traci.start(["sumo-gui", "-c", sys.argv[1]]) traci.start(["sumo", "-W", "-c", sys.argv[1]]) print('traci init') step = 0 startTime = datetime.now() print('started at ', startTime.strftime('%Y-%m-%dT%H:%M:%SZ')) while traci.simulation.getMinExpectedNumber() > 0: traci.simulationStep() step += 1 if (step % 1000 == 0): print('\nTime: ', datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ'), '\n') traci.close() endTime = datetime.now() print("Simulation Time:", startTime.strftime('%Y-%m-%dT%H:%M:%SZ'), endTime.strftime('%Y-%m-%dT%H:%M:%SZ'), "differnce:", (endTime - startTime).strftime('%Y-%m-%dT%H:%M:%SZ')) sys.stdout.flush()
def runOneStepSUMOSim(TM, stepNum): requireStop = 0 timeT = libsumo.simulation.getCurrentTime() #当前时间 vehicles = libsumo.vehicle.getIDList() #当前在道路上的车辆 curTime = timeT / 1000 #for len(vehicles)>0: # traci.vehicle.setParameter("00001", "carFollowModel.SimpleCACC1", "Hi") #每隔20秒加入1车队 if timeT % 20000 == 0: tmp3 = str(int(curTime / 20)) platoonId1 = tmp3 for i in range(TM.platoonSize): vehichID = TM.DPM.platoons[platoonId1][i] veh = TM.vehDict[vehichID] veh.speed = 0 libsumo.vehicle.addLegacy(vehichID, "r1", -3, veh.position, veh.speed, str(veh.lane), "car1") libsumo.vehicle.setLaneChangeMode(vehichID, 0) libsumo.simulationStep() if timeT / 1000 > 300: #if time is over 200 second stoping the simulation requireStop = 1 return TM, stepNum, requireStop
def run(): if len(sys.argv) < 2: print('Please provide the path to the .sumocfg of a SUMO scenario') exit() influx_host = INFLUX_HOST influx_port = INFLUX_PORT if len(sys.argv) == 4: influx_host = sys.argv[2] influx_port = int(sys.argv[3]) print('started') client = InfluxDBClient(influx_host, influx_port, 'admin', 'admin') client.drop_database(SUMO_DB) client.create_database(SUMO_DB) client.switch_database(SUMO_DB) print('client available') ## GUI / CLI # traci.start(["sumo-gui", "-c", sys.argv[1]]) traci.start(["sumo", "-c", sys.argv[1]]) print('traci init') step = 0 startTime = datetime.now() print('started at ', startTime.strftime('%Y-%m-%dT%H:%M:%SZ')) while traci.simulation.getMinExpectedNumber() > 0: traci.simulationStep() departed_ids = traci.simulation.getDepartedIDList() # ALL VEHICLES [subscribe(x) for x in departed_ids] # ONLY BUS # [subscribe(x) for x in departed_ids if traci.vehicle.getTypeID(x) == 'bus'] subscription_results = traci.vehicle.getAllSubscriptionResults() vehicles = [subscriberToInfluxJson( id, subscription_results[id]) for id in subscription_results] client.write_points(vehicles) step += 1 if(step % 1000 == 0): print('\n', 'Subscriptions: ', len(subscription_results)) print('Time: ', datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ')) traci.close() endTime = datetime.now() print("Simulation Time:", startTime.strftime('%Y-%m-%dT%H:%M:%SZ'), endTime.strftime('%Y-%m-%dT%H:%M:%SZ'), "differnce:", (endTime - startTime).strftime('%Y-%m-%dT%H:%M:%SZ')) sys.stdout.flush()
def _simulation_step(self): if self.visual == False: libsumo.simulationStep() self.time += 1 return else: self.time += 1 traci.simulationStep() return
def _simulation_step(self): if self.visual == False: libsumo.simulationStep() self.time += 1 #print('time is {}'.format(self.time)) return else: self.time += 1 traci.simulationStep() return
def main(): # CAUTION! step is in MILLISECONDS in version 0.30.0, but in SECONDS in version 1.1.0 #step = BEGIN_TIME*1000 step = BEGIN_TIME #while step < END_TIME*1000: while step <= END_TIME: ## if step%(3600*1000) == 0: ## print("Current Time: {}:00".format(step//(3600*1000))) ## for edge in edge_charoenRat: ## for lane in range(0,NUM_LANES[edge]): ## print("{}: {}".format(lane, traci.lanearea.getLastStepOccupancy("e2_{}_{}_0".format(edge,lane)))) traci.simulationStep(step=step) ## traci.simulationStep() ## step += STEP_SIZE*1000 step += STEP_SIZE print(step) traci.close()
def main(): step = float(BEGIN_TIME) SIMULATION_STEPS = (END_TIME - BEGIN_TIME) // 5 + 1 # 1 for the beginning step print() while step < END_TIME: #break if step % 3600 == 0: print("Current Time: {}:00".format(step // 3600)) for edge in edge_charoenRat: for lane in range(0, NUM_LANES[edge]): print("{}: {}".format( lane, traci.lanearea.getLastStepOccupancy("e2_{}_{}_0".format( edge, lane)))) traci.simulationStep(step=step) step += STEP_SIZE print(step) traci.close()
def step(self, action): if action != self.action and not self.changing: self.changing = 1 if self.changing > 0: ryg = self.red_yellow_green[self.action] ryg = ryg.replace('G', 'y') ryg = ryg.replace('g', 'y') libsumo.trafficlight.setRedYellowGreenState(self.light, ryg) self.changing += 1 else: libsumo.trafficlight.setRedYellowGreenState( self.light, self.red_yellow_green[action]) self.action = action if self.changing > self.yellow_length + 1: self.changing = 0 self.action = not self.action libsumo.trafficlight.setRedYellowGreenState( self.light, self.red_yellow_green[self.action]) libsumo.simulationStep() current_cars = libsumo.vehicle.getIDList() state = [] total_wait = 0 max_wait = 0 # overriding reward exited = 0 for c in current_cars: c_x, c_y, c_road, direction, c_target = self._car_from_id(c) if c_road == c_target or c not in self.cars: self.cars[c] = 1 else: self.cars[c] += 1 total_wait += self.cars[c] # overriding reward if c_road == c_target and (c_x < -36.6 or c_x > 24.649 or c_y < 44.5 or c_y > 87.2): exited += 1 max_wait = max_wait if self.cars[c] < max_wait else self.cars[c] state.append((np.array(c_x), np.array(c_y), c_road, direction, c_target, self.cars[c])) # overriding reward reward = np.array([exited, -max_wait / 100]) exited = 0 k = list(self.cars.keys()) for c in k: if c not in current_cars: del self.cars[c] exited += 1 self.state = state # obs = self.render() # reward = np.array([exited, -max_wait/100]) self.e_step += 1 terminal = self.e_step == self.episode_length if terminal: pass # libsumo.close() state = self.state_to_grid(self.state, self.action, self.changing) norm_timestep = self.e_step / (self.episode_length / 2) - 1 return ((state, norm_timestep), self.state), reward, terminal, {}
SUMO_HOME = os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "..") sys.path += [os.path.join(SUMO_HOME, "tools"), os.path.join(SUMO_HOME, "bin")] if len(sys.argv) > 1: import libsumo as traci # noqa else: import traci # noqa import sumolib # noqa traci.start([ sumolib.checkBinary('sumo'), "-c", "sumo.sumocfg", '--pedestrian.model', 'nonInteracting' ]) for step in range(3): print("step", step) traci.simulationStep() print("edges", traci.edge.getIDList()) print("edge count", traci.edge.getIDCount()) edgeID = "2fi" print("examining", edgeID) print("laneNumber", traci.edge.getLaneNumber(edgeID)) print("adaptedTraveltime", traci.edge.getAdaptedTraveltime(edgeID, 0)) print("effort", traci.edge.getEffort(edgeID, 0)) print("CO2", traci.edge.getCO2Emission(edgeID)) print("CO", traci.edge.getCOEmission(edgeID)) print("HC", traci.edge.getHCEmission(edgeID)) print("PMx", traci.edge.getPMxEmission(edgeID)) print("NOx", traci.edge.getNOxEmission(edgeID)) print("Fuel", traci.edge.getFuelConsumption(edgeID)) print("Noise", traci.edge.getNoiseEmission(edgeID)) print("Elec", traci.edge.getElectricityConsumption(edgeID))
def start_simulation(self, scenario, sim_params): """Start a sumo simulation instance. This method uses the configuration files created by the scenario class to initialize a sumo instance. Also initializes a traci connection to interface with sumo from Python. """ error = None for _ in range(RETRIES_ON_ERROR): try: # port number the sumo instance will be run on port = sim_params.port sumo_binary = "sumo-gui" if sim_params.render is True \ else "sumo" # command used to start sumo sumo_call = [ sumo_binary, "-c", scenario.cfg, "--remote-port", str(sim_params.port), "--num-clients", str(sim_params.num_clients), ] logging.info(" Starting SUMO on port " + str(port)) logging.debug(" Cfg file: " + str(scenario.cfg)) if sim_params.num_clients > 1: logging.info(" Num clients are" + str(sim_params.num_clients)) logging.debug(" Step length: " + str(sim_params.sim_step)) if sim_params.render: # Opening the I/O thread to SUMO self.sumo_proc = subprocess.Popen(sumo_call, preexec_fn=os.setsid) # wait a small period of time for the subprocess to # activate before trying to connect with traci if os.environ.get("TEST_FLAG", 0): time.sleep(0.1) else: time.sleep(config.SUMO_SLEEP) traci_connection = traci.connect(port, numRetries=100) traci_connection.setOrder(0) traci_connection.simulationStep() else: # Use libsumo to create a simulation instance. libsumo.start(sumo_call[1:3]) libsumo.simulationStep() # libsumo will act as the kernel API traci_connection = libsumo return traci_connection except Exception as e: print("Error during start: {}".format(traceback.format_exc())) error = e self.teardown_sumo() raise error
def step(self, action): """Run one timestep of the environment's dynamics. When end of episode is reached, you are responsible for calling `reset()` Input: action (object): an action provided by the environment Returns: observation (object): agent's observation of the current environment reward (float) : amount of reward returned after previous action done (boolean): whether the episode has ended, in which case further step() calls will return undefined results info (dict): contains auxiliary diagnostic information (helpful for debugging, and sometimes learning) """ ## print("I AM IN STEPPP") # Make yellow lights at the beginning of the timestep if change traffic phase if action != self._action and not self.idle: self._setYellowLights(self._action, action) total_throughput = 0 # 5 steps for yellow lights for _ in range(5): self._step += 1 traci.simulationStep(step=self._step) total_throughput += self._getThroughput() # Change traffic phase after 5 seconds and set self._action to be equal to the action if action != self._action and not self.idle: self._setTrafficLights(action) self._action = action if self.idle: self._action = self._getTrafficLights() ## print(self._action) # need to step 1 at a time since induction loop requires addition for _ in range(self.step_size-5): self._step += 1 traci.simulationStep(step=self._step) total_throughput += self._getThroughput() _travel_times = self._getTravelTimes() # Return dictionary of travel times _jam_lengths = self._getJamLengths() # Return dictionary of jam lengths _mean_speeds = self._getMeanSpeeds() # Return dictionary of mean_speeds _waiting_times = self._getWaitingTimes() # Return dictionary of waiting_times observation = self._getObservation() reward, _weighted_occupancy = self._getReward(total_throughput, observation[0][:-3]) #neglect downstream ## done = (self._step >= self.end_time) # done if step is more than end time done = (self._step >= self.begin_time+500) info = {"total_throughput": total_throughput, "weighted_occupancy" : _weighted_occupancy, "name": self.name, } info = {**info, **_travel_times, **_jam_lengths, **_mean_speeds, **_waiting_times} # Merge all dictionaies ## print(info) if WITH_LIBSUMO and not WITH_GUI: print("Step {}/{} Reward: {} Throughput: {} WeightedOccupancy: {}*****".format(self._step, self.end_time, int(reward), total_throughput, int(_weighted_occupancy)), end = '\r' ) return observation, reward, done, info