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()
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()
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()
def __init__(self, sysArgs): self.network_set = False self.iterations_set = False self.initiateSimulation(sysArgs) if self.network_set and self.iterations_set: import traci traci.init(CommunicationsAgent.PORT) counter = 0 self.name = Agent.COMM_AGENT_NAME self.agent_name = "CommAgent" self.password = Agent.COMM_AGENT_PASSWORD self.respond_to_ping = False self.Connect_RabbitMQ() # SR 4b the liaison creates a run id and shares it with the MACTS self.simulationId = datetime.datetime.now().strftime( "%Y%m%d|%H%M%S") self.sendCommand(self.publishChannel, Agent.COMMAND_BEGIN) # spin up the main working loop in its own thread thread.start_new_thread(self.working_loop, (traci, )) # SR 12 Network Configuration Discovery / Command Response Handler self.command_response_handler() self.sendStopMessage(self.publishChannel)
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
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)
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()
def initTraciConnection(traciPort, maxRetry): """ Initializes TraCI on the specified port """ sleep = 1 step = 0 traciInit = False Logger.info("{}Initializing TraCI on port {}...".format(constants.PRINT_PREFIX_MANAGER, traciPort)) while not(traciInit) and step < maxRetry: try: traci.init(traciPort) traciInit = True except: Logger.info("{}Traci initialization on port {} failed. Retrying connection in {} seconds...".format(constants.PRINT_PREFIX_MANAGER, traciPort, sleep)) time.sleep(sleep) if sleep >= 4: sleep = 5 else: sleep *= 2 step += 1 if not(traciInit): Logger.error("{}Traci initialization on port {} failed. Shutting down SUMO Manager".format(constants.PRINT_PREFIX_MANAGER, traciPort)) sys.stdout.flush() sys.exit(0) Logger.info("{}Initialized".format(constants.PRINT_PREFIX_MANAGER))
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()
def run(): traci.init(int(PORT)) step = 0 while traci.simulation.getMinExpectedNumber() > 0: traci.simulationStep() step += 1 traci.close()
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()
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()
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
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()
def run_genetic_algorithm(): sumoProcessCmd = run_sumo(SUMO) traci.init(PORT) generate_tollgates() traci.close() sumoProcessCmd.wait() run_simulation()
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)]
def initialize_state(): sumoProcessCmd = run_sumo(SUMO) traci.init(PORT) select_valid_edges() genetic.initialize() state.initialized = True traci.close() sumoProcessCmd.wait()
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)]
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()
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()
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()
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()
def run(max_step=-1): """execute the TraCI control loop""" traci.init(PORT) step = 0 # we start with phase 2 where EW has green #traci.trafficlights.setPhase("0", 0) #pdb.set_trace() while traci.simulation.getMinExpectedNumber() > 0: traci.simulationStep() step += 1 if step > max_step and max_step > 0: break traci.close() sys.stdout.flush()
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) no = traci.inductionloop.getLastStepVehicleNumber("0") if no > 0: programPointer = (0 if programPointer == len(PROGRAM)-1 else 3) traci.trafficlights.setRedYellowGreenState("0", PROGRAM[programPointer]) step += 1 traci.close() sys.stdout.flush()
def init_traci(): sumoBinary = sumolib.checkBinary('sumo') # sumoBinary = sumolib.checkBinary('sumo-gui') sumo_call = [sumoBinary, "-c", "data/hello.sumocfg", "--remote-port", str(PORT_TRACI), "--netstate-dump", "rawdump.xml", "--no-step-log", "-v", ] sumoProcess = subprocess.Popen( sumo_call, stdout=sys.stdout, stderr=sys.stderr) traci.init(PORT_TRACI)
def run(): """execute the TraCI control loop""" traci.init(PORT) step = 0 # Android sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((ANDROID_IP, ANDROID_PORT)) # data = sock.recv(4096) # print (data) # Lanes lanes = traci.lane.getIDList() rlane = lanes[0] for lane in lanes: ms = float(traci.lane.getMaxSpeed(lane)) kmh = ms * 3.6 print 'Lane ' + lane + ' ' + str(kmh) + 'km/h' # Lanes # # Vehicles # add(vehID, routeID, depart=-2, pos=0, speed=0, lane=0, # typeID='DEFAULT_VEHTYPE') traci.vehicle.add("veh1", "route0", 5) # Vehicles # while traci.simulation.getMinExpectedNumber() > 0: ms = float(traci.lane.getLastStepMeanSpeed(rlane)) kmh = ms * 3.6 maxms = float(traci.lane.getMaxSpeed(rlane)) maxkmh = maxms * 3.6 print 'Lane ' + rlane + ' ' + str(int(kmh)) + 'km/h' bstring = '{"speedLimit":'\ + str(int(maxkmh)) + ',"currentSpeed":'\ + str(int(kmh)) + ',"avgLaneSpeed":'\ + str(int(kmh))\ + '}\n' try: sock.send(bstring) # data = sock.recv(4096) except: sock.close() traci.simulationStep() step += 1 traci.close() sys.stdout.flush()
def main(): # initialize all the required arguments args = get_options() if args.gui_enabled: sumo_path = checkBinary('sumo-gui') else: sumo_path = checkBinary('sumo') cfg_path = load_cfg(args.scenario) traci_port = args.traci_port sumo_process = subprocess.Popen("%s -c %s --remote-port %s" % (sumo_path, cfg_path, traci_port), stdout=sys.stdout) traci.init(int(traci_port)) if args.event_enabled: run_ere(args.scenario, args.closed_roads.split(","), 300, 1200) else: run() sumo_process.wait()
def runSingle(traciEndTime, sumoEndTime=None): step = 0 if sumoEndTime is None: opt = addOption else: opt = addOption + ["--end", str(sumoEndTime)] sumoProcess = subprocess.Popen( [sumoBinary, "-c", "sumo.sumocfg", "--remote-port", str(PORT)] + opt) traci.init(PORT) while not step > traciEndTime: traci.simulationStep() step += 1 print("Print ended at step %s" % (traci.simulation.getCurrentTime() / DELTA_T)) traci.close() sumoProcess.wait() sys.stdout.flush()
def run(options, simulation): """execute the TraCI control loop""" traci.init(PORT) possible_programs = simulation.getPossiblePrograms() if options.algo=='static': algo = static.Static("0", possible_programs, options.greentime) title = 'static-' + str(options.greentime) elif options.algo=='smart': algo = smart.SmartTL("0", possible_programs, options.greentime) title = 'smart-' + str(options.greentime) elif options.algo=='smartDelta': algo = SmartDelta("0", possible_programs, options.greentime) title = 'smartDelta-' + str(options.greentime) step = 0 cars_lst={} while traci.simulation.getMinExpectedNumber() > 0: traci.simulationStep() print '========================================================================================================================================================' print 'step',step stepWaitingTime = 0 cnt_waiting_cars = 0 cnt_cars = 0 id_list = traci.vehicle.getIDList() for car in id_list: w = traci.vehicle.getWaitingTime(car) cnt_cars += 1 if not car in cars_lst: cars_lst[car]=0 if w>0.01: #print 'car: ' + car, 'wait time:' + str(w) cnt_waiting_cars+=1 stepWaitingTime+=w cars_lst[car]+=1 print 'XX step:', step, 'stepWaitingTime:',stepWaitingTime,'cnt_waiting_cars:',cnt_waiting_cars,'avgWaitingTime:',stepWaitingTime/(cnt_cars+0.001),'cnt_cars:',cnt_cars traci.trafficlights.setRedYellowGreenState("0", algo.getNextProgram()) step += 1 #print 'YY seed:',options.seed,'title:',title,'Totals steps:', step, 'totalWaitingTime:',sum([cars_lst[x] for x in cars_lst.keys()]),'total_cnt_waiting_cars:',sum([1 for x in cars_lst.keys() if cars_lst[x]>0.01]),'total_cnt_cars:',len(cars_lst) print("YY simulation: %-20s pace_factor: %2d seed: %d algo: %-16s Totals steps: %5d totalWaitingTime: %5d total_cnt_waiting_cars: %5d total_cnt_cars: %5d" % (options.simulation, options.pace_factor , options.seed, title, step, sum([cars_lst[x] for x in cars_lst.keys()]), sum([1 for x in cars_lst.keys() if cars_lst[x]>0.01]), len(cars_lst))) traci.close() sys.stdout.flush()
def __init__(self, options): # this script has been called from the command line. It will start sumo as a # server, then connect and run if options.gui: sumoBinary = checkBinary('sumo-gui') else: sumoBinary = checkBinary('sumo') self.rounds = 1000 self.sumoProcess = subprocess.Popen([sumoBinary, "-n", self.PATH+"/"+self.CASENAME+".net.xml",'-r',self.PATH+"/"+self.CASENAME+".rou.xml",'-a',self.PATH+"/sensors.xml", "--remote-port", str(self.PORT)], stdout=DEVNULL#stdout=sys.stdout, ,stderr=sys.stderr) print "Opening a port at", self.PORT traci.init(self.PORT) print "Connection made with sumo" self.laneAreaList = traci.areal.getIDList() self.stoppedVehicleID = None
def start_simulation(sumo, scenario, network, output, mapa): unused_port_lock = UnusedPortLock() unused_port_lock.__enter__() remote_port = find_unused_port() sumo = subprocess.Popen([sumo, "-c", scenario, "--tripinfo-output", output, "--device.emissions.probability", "1.0", "--remote-port", str(remote_port), "--duration-log.statistics","--log", "logfile.txt"], stdout=sys.stdout, stderr=sys.stderr) unused_port_lock.release() try: traci.init(remote_port) return run(mapa) except Exception as e: print(e) raise finally: print("Terminating SUMO") terminate_sumo(sumo) unused_port_lock.__exit__()
def run(): i = 0 """execute the TraCI control loop""" traci.init(PORT) step = 0 edge_id = traci.inductionloop.getIDList() # we start with phase 2 where EW has green traci.trafficlights.setPhase("0", 2) while traci.simulation.getMinExpectedNumber() > 0: traci.simulationStep() if traci.trafficlights.getPhase("0") == 2: # we are not already switching if traci.inductionloop.getLastStepVehicleNumber( "0") > 0: #gets number of vehicles in the loop #print(traci.inductionloop.getLastStepVehicleNumber("0")) if traci.inductionloop.getLastStepOccupancy( "0" ) == 100.0: #if no of vehicles exceed the detector area then give green signal for NS traci.trafficlights.setPhase( "0", 3) #set green signal for the NS path print(traci.inductionloop.getLastStepOccupancy("0")) else: for i in xrange(1): vehicle_Ids = traci.inductionloop.getLastStepVehicleIDs( edge_id[i]) for vehicle in vehicle_Ids: typeID = traci.vehicle.getTypeID(vehicle) print(typeID) if typeID == "typeNS": #checks the type of the vehicle # there is a emergency vehicle from the north, switch traci.trafficlights.setPhase( "0", 3) #set green signal for the NS path else: # otherwise try to keep green for EW traci.trafficlights.setPhase("0", 2) #green 0 for EW else: # otherwise try to keep green for EW traci.trafficlights.setPhase("0", 2) #green 0 for EW step += 1 traci.close() sys.stdout.flush()
def run_simulation(): state.step = 0 sumoProcessCmd = run_sumo(SUMOGUI if settings.gui else SUMO) traci.init(PORT) traci.simulation.subscribe() try: while state.step < settings.step_limit: simulation_step() if settings.gui and settings.screenshot_directory: fname = 'gen_{}_individual_{}.png'.format(state.generation, state.individual) save_name = os.path.join(settings.screenshot_directory, fname) try: traci.gui.screenshot('View #0', save_name) except Exception as e: error_print('Failed to take screenshot ' + save_name) finally: traci.close() sumoProcessCmd.wait()
def initSimulator(self,withGUI,portnum): # Path to the sumo binary if withGUI: sumoBinary = r"D:\SUMO\bin\sumo-gui" else: sumoBinary = r"D:\SUMO\bin\sumo-gui" sumoConfig = r"D:\gym-sumo-master-updated\gym_sumo\envs\sumo_configs\one_run\cross.sumocfg" # Call the sumo simulator sumoProcess = subprocess.Popen([sumoBinary, "-c", sumoConfig, "--remote-port", str(portnum), \ "--time-to-teleport", str(-1), "--collision.check-junctions", str(True), \ "--no-step-log", str(True), "--no-warnings", str(True)], stdout=sys.stdout, stderr=sys.stderr) # Initialize the simulation traci.init(portnum) return traci
def run(): """Execute the TraCI control loop""" traci.init(PORT) step = 0 print("Sinal 0: ") print(traci.trafficlights.getRedYellowGreenState("0")) traci.trafficlights.setPhase("0", 2) while traci.simulation.getMinExpectedNumber() > 0: traci.simulationStep() if traci.trafficlights.getPhase("0") == 2: if traci.inductionloop.getLastStepVehicleNumber("1to0_0") > 0: # there is a vehicle from the north, switch traci.trafficlights.setPhase("0", 3) else: # otherwise try to keep green for EW traci.trafficlights.setPhase("0", 2) step += 1 traci.close() sys.stdout.flush()
def simulation(self): #traci.start(['sumo-gui', '-c', './scenario/sumodata/shihuxilu_add.sumocfg', '--start']) traci.init(8813) traci.setOrder(2) for junctionID in self.agentids: traci.junction.subscribeContext( #位置、 角度、 类型、 车长、 颜色、 速度 junctionID, tc.CMD_GET_VEHICLE_VARIABLE, 1500, [ tc.VAR_POSITION, tc.VAR_ANGLE, tc.VAR_TYPE, tc.VAR_LENGTH, tc.VAR_COLOR, tc.VAR_SPEED ]) #traci.inductionloop.subscribeContext("d_1", tc.CMD_GET_INDUCTIONLOOP_VARIABLE, 0, [tc.VAR_LANE_ID, tc.LAST_STEP_VEHICLE_NUMBER]) traci.lane.subscribeContext( "lane1_0", tc.CMD_GET_LANE_VARIABLE, -1, [tc.LAST_STEP_MEAN_SPEED, tc.LAST_STEP_VEHICLE_NUMBER]) while traci.simulation.getMinExpectedNumber() > 0: # print("size : ", len(traci.vehicle.getIDList())) # for vec_id in traci.vehicle.getIDList(): # # 订阅车辆信息:坐标,角度,车辆类型,颜色,速度 # traci.vehicle.subscribe(str(vec_id), # (tc.VAR_POSITION, tc.VAR_ANGLE, tc.VAR_TYPE, tc.VAR_COLOR, tc.VAR_SPEED)) traci.simulationStep() ##整合在一起时,只需要一个切帧 self.frame += 1 # n = traci.inductionloop.getLastStepVehicleNumber("d_2") # print("getLastStepVehicleNumber = ", n) dict_sub = traci.lane.getContextSubscriptionResults("lane1_0") #print("lane dict = ", dict_sub) self.process_vehpos_v17() #函数用生成帧数据 #self.process_vehpos() #帧间休眠 sleeping = config.steplength*self.frame - \ (time.perf_counter() - self.start) # print(sleeping) if sleeping > 0: time.sleep(sleeping) sys.stdout.flush() traci.close() #self.record_file.close() self.producer.close() exit(0)
def initialize(self): if platform.system() == 'Windows' or platform.system().startswith( "CYGWIN"): sumoBinary = checkBinary('sumo.exe') else: sumoBinary = checkBinary('sumo') sumoCommandLine = [sumoBinary, "-c", self.ConfigFile, "-l", "sumo.log"] self.SumoProcess = subprocess.Popen(sumoCommandLine, stdout=sys.stdout, stderr=sys.stderr) traci.init(self.Port) self.SimulationBoundary = traci.simulation.getNetBoundary() self.XBase = self.SimulationBoundary[0][0] self.XSize = self.SimulationBoundary[1][0] - self.XBase self.YBase = self.SimulationBoundary[0][1] self.YSize = self.SimulationBoundary[1][1] - self.YBase #self.__Logger.warn("starting sumo connector") # initialize the edge list, drop all the internal edges self.EdgeList = [] for edge in traci.edge.getIDList(): # this is just to ensure that everything is initialized first time traci.edge.adaptTraveltime(edge, traci.edge.getTraveltime(edge)) # only keep the "real" edges for computation for now if not edge.startswith(':'): self.EdgeList.append(edge) self.CurrentEdgeList = list(self.EdgeList) # initialize the traffic light state tllist = traci.trafficlights.getIDList() for tl in tllist: self.TrafficLights[ tl] = traci.trafficlights.getRedYellowGreenState(tl) traci.trafficlights.subscribe(tl, [tc.TL_RED_YELLOW_GREEN_STATE]) # initialize the induction loops illist = traci.inductionloop.getIDList() for il in illist: traci.inductionloop.subscribe(il, [tc.LAST_STEP_VEHICLE_NUMBER])
def start(self): self.init() print 'Start simulation...' ###以一天中的时间为步长仿真,首先是固定配时方案 for day in range(conf.totalDays): sumoProcess = subprocess.Popen([conf.sumoBinaryPath, "-c", "../palm.sumocfg", \ "--remote-port", str(conf.PORT)], stdout=sys.stdout, stderr=sys.stderr) traci.init(conf.PORT) curSeconds = 0 curHour = 0 action = 0 lastAction = 0 curPhaseID = 0 secondsInCurPhase = 0 while curSeconds < conf.secondsInDay: ##如果仍是当前的相位 if curPhaseID == int(traci.trafficlights.getPhase(conf.SL)) and curSeconds != 0: secondsInCurPhase += 1 else : secondsInCurPhase = 0 curPhaseID = int(traci.trafficlights.getPhase(conf.SL)) ##刚转到黄灯时搜集环境信息 if (curPhaseID % 2 == 0) and secondsInCurPhase == 0: if curHour != curSeconds / conf.secondsInHour: curHour = int(curSeconds / conf.secondsInHour) for lane in conf.listLanes: self.__laneQueueTracker[lane] = traci.lane.getLastStepHaltingNumber(str(lane)) self.__laneWaitingTracker[lane] = traci.lane.getWaitingTime(str(lane))/60 self.__laneNumVehiclesTracker[lane] = traci.lane.getLastStepVehicleNumber(str(lane)) curObjValue = self.__algo.computeObjValue(self.__laneQueueTracker, self.__laneQueueTracker) print 'curObjValue=' + str(curObjValue) curSeconds += 1 traci.simulationStep() traci.close() pass
def run(runId): """starts simulation, reads people file, runs sim, outputs results""" global peopleCollection, persons traci.init(PORT) print "Init" traci.simulation.subscribe( [tc.VAR_DEPARTED_VEHICLES_IDS, tc.VAR_ARRIVED_VEHICLES_IDS]) filename = 'SampleInput/Requests/1a/sumo-%s-people.csv' % (runId) peopleCollection.readFile(filename) persons = peopleCollection.getList() persons.sort() while traci.simulation.getMinExpectedNumber() > 0: #traci.simulationStep() doStep() peopleCollection.output('./output/sumo-output1a/', runId) vehicleCollection.output('./output/sumo-output1a/', runId) traci.close()
def runSingle(sumoEndTime, traciEndTime): fdi = open("sumo.sumocfg") fdo = open("used.sumocfg", "w") fdo.write(fdi.read() % {"end": sumoEndTime}) fdi.close() fdo.close() doClose = True 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() vehs = traci.vehicle.getIDList() if vehs.index("horiz") < 0 or len(vehs) > 1: print "Something is false" step += 1 print "Print ended at step %s" % (traci.simulation.getCurrentTime() / DELTA_T) traci.close() sys.stdout.flush()
def main(): """Main body of code, implemented as a function to ease interactive debugging.""" # Parse the options (options, args) = parse_options(sys.argv) step_length = options.step_length agent_period = options.agent_period # Connect to SUMO traci.init(options.port) # Initialize all agents agents = [ Agent(tl_id, options.learning_rate, options.discount_factor, options.curiosity, options.curiosity_decay, options.exploration_period, options.reward_expt, options.default_qvalue) for tl_id in traci.trafficlights.getIDList() ] # Initialize all lanes lane_ids = set(lane for agent in agents for lane in agent.controlled_lanes) lanes = dict((id, Lane(id, options.agent_period)) for id in lane_ids) # Simulate with control curr_step = 0 while curr_step < options.end: # Always update the lanes for l in lanes.values(): l.update() # Let the agents act when they're supposed to if curr_step % agent_period == 0: for a in agents: a.act(lanes) # Request another step traci.simulationStep(0) curr_step += step_length # Disconnect from SUMO traci.close()
def run(): global lanes, vec_sum, lane_data, intersection, lights traci.init(PORT) step = 0 data_count = inter.cycle while step < MAX_STEP: traci.simulationStep() data = dict( zip([key for key in ["east", "west", "north", "south"]], [value for value in [numberv(i) for i in lanes_id()]])) for i in ["east", "west", "north", "south"]: if data[i] > lane_data[i]: inter.lanes[i].Tin += [step] * (data[i] - lane_data[i]) else: inter.lanes[i].Tout += [step] * (lane_data[i] - data[i]) lane_data = data step += 1 data_count -= 1 """ light = get_light_command(lights, data_count) #traci.trafficlights.setRedYellowGreenState("1", light) if data_count ==0: lights = inter.getCommand(step) # update the light cycle print lights data_count = inter.cycle # update the cycle print "cycle updated ",data_count """ traci.close() for lane in inter.lanes: print "lane ", inter.lanes[lane].id, len(inter.lanes[lane].Tin), len( inter.lanes[lane].Tout) print inter.lanes[lane].Tin print inter.lanes[lane].Tout print "========================" waiting = {"east": [], "west": [], "north": [], "south": []} for lane in inter.lanes: for i in range(0, 350, 10): #print "lane ", inter.lanes[lane].id, "step", i, inter.lanes[lane].getQl(i), inter.lanes[lane].getAwt(i) waiting[lane].append(inter.lanes[lane].getAwt(i)) plot(waiting) print "real number is :", cnt
def run(): """execute the TraCI control loop""" traci.init(PORT) step = 0 programManager = MyClasses.ProgramManager( myP + constants.CONST_CURR_MAP.rsplit('\\', 1)[0] + '\\', constants.CONST_CURR_MAP.rsplit('\\', 1)[1], configFile) #This loops through all of the simulaton steps as defined by the configuartion file while traci.simulation.getMinExpectedNumber() > 0: traci.simulationStep() #This performs one simulation step step += 1 #Count the steps programManager.Update(step) if (constants.CONST_FLOW_CUT_OFF and step > constants.CONST_FLOW_SIMULATION_TIME): break programManager.OnExit() traci.close() sys.stdout.flush()
def run(): traci.init(PORT) step = 0 while step < 1500: traci.simulationStep() for vehID in traci.vehicle.getIDList(): if not (vehID in parking.keys()) and ( traci.vehicle.getRoadID(vehID) == 'in'): reserveSlot(vehID) if (vehID in parking.keys()) and (traci.vehicle.getRoadID(vehID) == 'out'): releaseSlot(vehID) if traci.vehicle.isStopped(vehID): traci.vehicle.changeTarget(vehID, 'out') step += 1 traci.close()
def simulationProcess2(sumoMap, ignore=None): port = generator_ports() sumoProcess = subprocess.Popen([ "sumo", "-c", sumoMap, "--tripinfo-output", "tripinfo.xml", "--remote-port", str(port), "--output-prefix", str(port) ], stdout=DEVNULL, stderr=DEVNULL) time.sleep(10) traci.init(port) test.test_init() test.debug() for s in range(50000): traci.simulationStep() if not s % 10 == 0: continue for i in selected_intersections: sensors = intersection_info[i]['sensors'] for s in sensors: if s in ignore: continue data = 0 # for t in range(sensor_num[s]): # data += traci.areal.getLastStepVehicleNumber(s + '#' + str(t)) data = traci.multientryexit.getLastStepVehicleNumber(s) #print "data:" + str(data) + ', sensor:' + str(s) test.handleTrafficSensorInput(s, data, i) res = test.nextClockTick(i) ltState = phaseCodes[i][res] traci.trafficlights.setRedYellowGreenState('tl' + i[10:], ltState) traci.close() sumoProcess.wait() time.sleep(10) return durationAndDistance(port)
def __init__(self, configFile, gui=False, outFile=None): """ starts the simulation inputs: configFile = string, name of the configuration you're using gui = boolean (optional), if True, the SUMO gui will pop up outFile = string (optional), file for SUMO to save data """ PORT = 8800 # from sumo demo code (vehicleControl.py) try: from sumolib import checkBinary except ImportError: def checkBinary(name): return name # write terminal command completeCommand = [checkBinary("sumo")] if gui: completeCommand = [checkBinary("sumo-gui")] #sumoConfig = "%s.sumocfg" % (configFile) sumoConfig = configFile + "/" + configFile + ".sumocfg" completeCommand += ["-c", sumoConfig] completeCommand += ["--remote-port", str(PORT)] if outFile is not None: completeCommand += ["--fcd-output", "./Results/%s.xml" % outFile] self._C = completeCommand ## start SUMO self.sumoProcess = subprocess.Popen( completeCommand, stdout=subprocess.PIPE, #sys.stdout,# stderr=subprocess.STDOUT) traci.init(PORT, 10) self.outFile = outFile
def runSingle(addOption): step = 0 timeline = [] sumoProcess = subprocess.Popen("%s -c %s %s" % (sumoBinary, "sumo.sumocfg", addOption), shell=True, stdout=sys.stdout) traci.init(PORT) while not step > 10000: try: traci.simulationStep() vehs = traci.vehicle.getIDList() timeline.append({}) for v in vehs: timeline[-1][v] = traci.vehicle.getSpeed(v) step += 1 except traciControl.FatalTraCIError: print "Closed by SUMO" break traci.close() sys.stdout.flush() return timeline
def init_traci(): sumoBinary = sumolib.checkBinary('sumo') # sumoBinary = sumolib.checkBinary('sumo-gui') sumo_call = [ sumoBinary, "-c", "data/hello.sumocfg", "--remote-port", str(PORT_TRACI), "--netstate-dump", "rawdump.xml", "--no-step-log", "-v", ] sumoProcess = subprocess.Popen(sumo_call, stdout=sys.stdout, stderr=sys.stderr) traci.init(PORT_TRACI)
def run(): """execute the TraCI control loop""" traci.init(PORT) step = 0 # we start with phase 2 where EW has green traci.trafficlights.setPhase("0", 2) while traci.simulation.getMinExpectedNumber() > 0: traci.simulationStep() if traci.trafficlights.getPhase("0") == 2: # we are not already switching if traci.inductionloop.getLastStepVehicleNumber("0") > 0: # there is a vehicle from the north, switch traci.trafficlights.setPhase("0", 3) else: # otherwise try to keep green for EW traci.trafficlights.setPhase("0", 2) numCars = traci.multientryexit.getLastStepVehicleNumber("e3_0_1i") print numCars step += 1 traci.close() sys.stdout.flush()
def traciLoop(port, traciEndTime, index, steplength=0): orderTime = 0.25 time.sleep(orderTime * index) # assure ordering of outputs if steplength == 0: steplength = DELTA_T / 1000. print("Starting process %s with steplength %s" % (index, steplength)) sys.stdout.flush() traci.init(port) traci.setOrder(index) step = 1 nrEnteredVehicles = 0 sumoStop = False try: traciEndStep = math.ceil(traciEndTime / steplength) while not step > traciEndStep: traci.simulationStep(int(step * steplength * 1000)) #print(index, "asking for vehicles") # sys.stdout.flush() vehs = traci.vehicle.getIDList() nrEnteredVehicles += traci.simulation.getDepartedNumber() #~ print(index, "Newly entered vehicles: ", traci.simulation.getDepartedNumber(), "(vehs: ", vehs, ")") #~ sys.stdout.flush() step += 1 endTime = traci.simulation.getCurrentTime() / DELTA_T traci.close() except traci.FatalTraCIError as e: if str(e) == "connection closed by SUMO": time.sleep(orderTime * index) # assure ordering of outputs sumoStop = True print("client %s: " % index, str(e), " (at TraCIStep %s)" % step) sys.stdout.flush() else: raise if not sumoStop: time.sleep(orderTime * index) # assure ordering of outputs print("Process %s ended at step %s" % (index, endTime)) print("Process %s was informed about %s entered vehicles" % (index, nrEnteredVehicles)) sys.stdout.flush()
def initSimulator(withGUI, portnum, descriptor): # Path to the sumo binary if withGUI: sumoBinary = "/usr/local/bin/sumo-gui" else: sumoBinary = "/usr/local/bin/sumo" # Load the scenario descriptor = descriptor.astype(int) task = str(descriptor[0]) + str(descriptor[1]) + str(descriptor[2]) + str( descriptor[3]) + '.sumocfg' sumoConfig = "/home/disele/Documents/PROJ-DeepRL/gym-sumo/gym_sumo/envs/roadMTL/" + task # Call the sumo simulator sumoProcess = subprocess.Popen([sumoBinary, "-c", sumoConfig, "--remote-port", str(portnum), \ "--time-to-teleport", str(-1), "--collision.check-junctions", str(True), \ "--no-step-log", str(True), "--no-warnings", str(True)], stdout=sys.stdout, stderr=sys.stderr) # Initialize the simulation traci.init(portnum) return traci
def start_simulation(sumo, scenario, output, route, G, dict_edges_net, file_name_json, edges_weight, impedance): unused_port_lock = UnusedPortLock() unused_port_lock.__enter__() remote_port = find_unused_port() sumo = subprocess.Popen( [sumo, "-c", scenario, "--tripinfo-output", output, "--device.emissions.probability", "1.0", "--remote-port", str(remote_port), "--duration-log.statistics", "--log", "logfile.txt"], stdout=sys.stdout, stderr=sys.stderr) unused_port_lock.release() length_total = 0 try: traci.init(remote_port) length_total = run(route, G, dict_edges_net, file_name_json, edges_weight, impedance) except Exception as e: print(e) raise finally: terminate_sumo(sumo) unused_port_lock.__exit__() return length_total
def run(self): vehCount = 0 emitters = EmittersParser.parse(self.cmdLineOptions.emittersInput) self.logger.info('Finished parsing emitters input file.') traci.init(self.port) #adds one-edge routes via TraCI for each emitter self.__addRoutes(emitters) self.logger.info('Finished adding routes to the simulation.') for i in range(1000): traci.simulationStep() for e in emitters: if e.isAllowedToCreateVehicle(i): e.createVehicle(traci,str(vehCount)) vehCount += 1 #TODO alternate lanes, use DEPART_NOW traci.close()
def run(port): """execute the TraCI control loop""" traci.init(port) simulation_steps = 0 positionJunctionE0 = traci.lane.getLength("gneE0_0") positionJunctionE7 = traci.lane.getLength("gneE7_0") positionJunctionE6 = traci.lane.getLength("gneE6_0") positionJunctionE8 = traci.lane.getLength("gneE8_0") print " MAX_POOL %s Arrival margin %s \n", str(MAX_POOL_LEFT), str( ARRIVAL_MARGIN) print "\n" while traci.simulation.getMinExpectedNumber() > 0: traci.simulationStep() veh_ids_E0_0 = traci.lane.getLastStepVehicleIDs("gneE0_0") veh_ids1_E0_1 = traci.lane.getLastStepVehicleIDs("gneE0_1") mergedLIst = veh_ids_E0_0 + veh_ids1_E0_1 save_observations(mergedLIst, positionJunctionE0, veh_ids_E0_0, veh_ids1_E0_1) rules(mergedLIst, veh_ids_E0_0, veh_ids1_E0_1) simulation_steps = simulation_steps + 1 logging.info( "---------------------------------------------------------------------------------------------------------------" ) traci.close() sys.stdout.flush() print "no of simulation_steps ", simulation_steps ids = [ 'flow1.0', 'flow1.1', 'flow1.3', 'flow1.7', 'flow2.0', 'flow2.1', 'flow2.3', 'flow2.7' ] #ids=['flow2.0','flow2.1','flow2.5', 'flow2.7'] draw_graph(ids, mergedLIst)
def run(): """execute the TraCI control loop""" traci.init(PORT) print("Server version: " + str(traci.getVersion())) print("Server timestep: " + str(traci.simulation.getDeltaT())) print(str(traci.simulation.getNetBoundary())) traci.simulation.subscribe([SIMTIME, DEPARTEDVHCLST, ARRIVEDVHCLST]) traci.vehicle.subscribe("x",[0, 1]) for i in range(0, 12100): traci.simulationStep() simsubs = traci.simulation.getSubscriptionResults() vehsubs = traci.vehicle.getSubscriptionResults("x") print("Current SIM time: " + str(simsubs[SIMTIME])) dep = simsubs[DEPARTEDVHCLST] arr = simsubs[ARRIVEDVHCLST] carsinsim = vehsubs[0] print 'dep', dep print 'arr', arr ## for car in carsinsim: ## #traci.vehicle.setSpeed(car, 5.0) ## road = traci.vehicle.getRoadID(car) ## if road == "26:2" and car not in affected: ## #traci.vehicle.slowDown(car, 0.0, 10000) ## #traci.vehicle.setSpeed(car, 4.0) ## traci.vehicle.changeLane(car, 1, 40000) ## affected.append(car) ## elif road != "26:2" and car in affected: ## traci.vehicle.changeLane(car, 1, -1) ## affected.remove(car) time.sleep(0.1) traci.close()
def __init__(self, args): self.args = args host = args.sumo_host port = args.sumo_port if args.sumo_gui is True: sumo_binary = sumolib.checkBinary('sumo-gui') else: sumo_binary = sumolib.checkBinary('sumo') if args.sumo_host is None or args.sumo_port is None: logging.info('Starting new sumo server...') traci.start([ sumo_binary, "-c", args.sumo_cfg_file, '--step-length', str(args.step_length), '--lateral-resolution', '0.25', '--collision.check-junctions' ]) if args.sumo_gui: logging.info( 'Remember to press the play button to start the simulation' ) else: logging.info('Connection to sumo server. Host: %s Port: %s', host, port) traci.init(host=host, port=port) # Structures to keep track of the spawned and destroyed vehicles at each time step. self.spawned_actors = set() self.destroyed_actors = set() # Creating a random route to be able to spawn carla actors. traci.route.add("carla_route", [traci.edge.getIDList()[0]]) # Variable to asign an id to new added actors. self._sequential_id = 0
def launch_sumo_process(sumo_config_file, traci_port, sumo_binary="sumo", gui_on=False): """Takes a SUMO config file and optional path to the SUMO binary and optional argument to launch SUMO with a gui. Launches a SUMO simulation using the subprocess module with a free port open for TraCI. Returns the subprocess and traci port number""" if gui_on: sumo_binary += "-gui" # Append the gui command if requested sumo_command = ("%s -c %s --remote-port %d" % (sumo_binary, sumo_config_file, traci_port)) print("Launching process: %s" % sumo_command) sumo_subprocess = subprocess.Popen(sumo_command, shell=True, stdout=sys.stdout, stderr=sys.stderr) # Open up traci on a free port traci.init(traci_port) print("Port opened on %d" % traci_port) return sumo_subprocess
def run(): """execute the TraCI control loop""" traci.init(PORT) step = 0 my_data = {} vehiclesInSimulation = list while traci.simulation.getMinExpectedNumber() > 0: #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Dynamic vehicles_array list ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ for veh_id in traci.simulation.getDepartedIDList(): vehicles_array.append( veh_id ) # creating an array with the cars that have departed and so are running in the simulation traci.vehicle.subscribe( veh_id, [traci.constants.VAR_POSITION] ) # cant choose the second vehicle cause it hasnt departed yet. So the only solution is to subscribe for all the departed so far or just the first cause it instantly departs traci.vehicle.subscribe(veh_id, [traci.constants.VAR_SPEED]) for veh_id in traci.simulation.getArrivedIDList(): if veh_id in vehicles_array: vehicles_array.remove( veh_id ) # deleting the cars that have arrived to the destination. We need an apdated array otherwize it will crash #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ categorizeVehicles() iteratePassenger() trafficJamDetector() #if step%30==0: #trafficJamDetector() # CLEAR THE FILE FROM PREVIOUS INPUTS #open("close_vehicles.txt", "w").close() #detectCloseVehicles() traci.simulationStep() step += 1 traci.close() sys.stdout.flush()
def run(): """Execute the TraCI control loop""" print("Inicio da Simulacao Controlada:") traci.init(PORT) step = 0 stepOpenedSignal = 0 yellow = False changed = False #No estado inicial, todos os semaforos estao abertos e o comando abaixo fecha metade dos sinais traci.trafficlights.setRedYellowGreenState("0", "GGGGrrrrGGGGrrrr") while traci.simulation.getMinExpectedNumber( ) > 0: #verifica se existem carros na rede traci.simulationStep() vhQtAc = traci.areal.getLastStepVehicleNumber( "1to0_0") + traci.areal.getLastStepVehicleNumber("1to0_1") if (vhQtAc >= 6) and (changed == False): traci.trafficlights.setRedYellowGreenState("0", "yyyyyyyyyyyyyyyy") traci.simulationStep() step += 1 traci.trafficlights.setRedYellowGreenState("0", "rrrrGGGGrrrrGGGG") stepOpenedSignal = step changed = True if ((step - stepOpenedSignal) >= 16) and (changed == True): traci.trafficlights.setRedYellowGreenState("0", "yyyyyyyyyyyyyyyy") traci.simulationStep() step += 1 traci.trafficlights.setRedYellowGreenState("0", "GGGGrrrrGGGGrrrr") changed = False step += 1 traci.close() sys.stdout.flush()
def __enter__(self): if (self.no_gui): sumoBinary = checkBinary('sumo') else: sumoBinary = checkBinary('sumo-gui') print('Starting simulation') # this is the normal way of using traci. sumo is started as a # subprocess and then the python script connects and runs command_string = [ sumoBinary, '-c', self.options.c, "--step-length", str(self.dt), "--remote-port", str(self._port) ] if self.options.a is not None: command_string.extend(["-a", self.options.a]) self.sumo_process = subprocess.Popen(command_string, stdout=sys.stdout, stderr=sys.stderr) print('Initialized traci on port %d' % self._port) traci.init(self._port) return self