本文整理汇总了Python中traci.init函数的典型用法代码示例。如果您正苦于以下问题:Python init函数的具体用法?Python init怎么用?Python init使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了init函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
def run():
global current_hour
"""execute the TraCI control loop"""
traci.init(PORT)
src = [
Source("D2",100,1),
Source("D2",100,2),
Source("D2",100,3),
Source("L16",100,51),
Source("L14",50,25),
Source("V4",0,30)
]
dest = [
Destination("V4",150),
Destination("V4",100),
Destination("D8",5),
Destination("V4",150),
Destination("D1",10),
Destination("D1",20)
]
stops = [
ChargingStation(0,"D6",50,2,10,[0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5])
,
ChargingStation(1,"V2",50,2,8,[0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5])
]
types = ["CarA", "CarA", "CarD", "CarB", "CarC", "CarC"]
#number of elechtric vehicle insterted
veh_count = 0
vehicles = []
temp_vehs = []
for i in range(6):
vehicles.append(Electric_Vehicle(veh_count,src[i],dest[i],types[i],1000,temp_vehs))
veh_count+=1
center = Center(stops,vehicles)
for s in stops:
center.seller_report(s)
temp_toDel = False
while vehicles != []:
traci.simulationStep()
if traci.simulation.getCurrentTime()/1000 % 1000 == 0 and traci.simulation.getCurrentTime()>0:
current_hour += 1
print '[HOUR]', current_hour
deleteTempVehicles(temp_vehs)
for v in vehicles:
if (v.updateState(dest) == 1 and not v.reported):
center.buyer_report(v,stops,current_hour,temp_vehs)
center.assign(v,stops)
v.assinged = v.stopToCharge()
v.reported = True
if (v.toDel):
vehicles.remove(v)
if v.reported and not v.assinged:
v.assinged = v.stopToCharge()
traci.close()
sys.stdout.flush()
示例2: run
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()
示例3: run
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()
示例4: initTraciConnection
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))
示例5: run
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()
示例6: beginEvaluate
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
示例7: init
def init(manager, forTest=False):
optParser = OptionParser()
optParser.add_option("-v", "--verbose", action="store_true", dest="verbose",
default=False, help="tell me what you are doing")
optParser.add_option("-g", "--gui", action="store_true", dest="gui",
default=False, help="run with GUI")
optParser.add_option("-c", "--cyber", action="store_true", dest="cyber",
default=False, help="use small cybercars instead of big busses")
optParser.add_option("-d", "--demand", type="int", dest="demand",
default=15, help="period with which the persons are emitted")
optParser.add_option("-b", "--break", type="int", dest="breakstep", metavar="TIMESTEP",
help="let a vehicle break for %s seconds at TIMESTEP" % BREAK_DELAY)
(options, args) = optParser.parse_args()
sumoExe = SUMO
if options.gui:
sumoExe = SUMOGUI
sumoConfig = "%s%02i.sumocfg" % (PREFIX, options.demand)
if options.cyber:
sumoConfig = "%s%02i_cyber.sumocfg" % (PREFIX, options.demand)
sumoProcess = subprocess.Popen([sumoExe, sumoConfig], stdout=sys.stdout, stderr=sys.stderr)
traci.init(PORT)
traci.simulation.subscribe()
setting.manager = manager
setting.verbose = options.verbose
setting.cyber = options.cyber
setting.breakstep = options.breakstep
try:
while setting.step < 100 or statistics.personsRunning > 0:
doStep()
statistics.evaluate(forTest)
finally:
traci.close()
sumoProcess.wait()
示例8: main
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()
示例9: run
def run(edges, connections, speedChanges, optimalization, nogui):
'''execute the TraCI control loop'''
traci.init(PORT)
if not nogui:
traci.gui.trackVehicle('View #0', '0')
#print 'route: {0}'.format(traci.vehicle.getRoute('0'))
destination = traci.vehicle.getRoute('0')[-1]
edgesPoll = list(edges)
time = traci.simulation.getCurrentTime()
while traci.simulation.getMinExpectedNumber() > 0:
if optimalization:
change_edge_speed(edgesPoll, edges, speedChanges)
edge = traci.vehicle.getRoadID('0')
if edge in edges and traci.vehicle.getLanePosition('0') >= 0.9 * traci.lane.getLength(traci.vehicle.getLaneID('0')):
shortestPath = graph.dijkstra(edge, destination, edges, get_costs(edges), connections)
#print 'dijkstra: {0}'.format(shortestPath)
traci.vehicle.setRoute('0', shortestPath)
else:
if len(speedChanges) > 0:
edge, speed = speedChanges.pop()
traci.edge.setMaxSpeed(edge, speed)
else:
change_edge_speed(edgesPoll, edges, [])
traci.simulationStep()
time = traci.simulation.getCurrentTime() - time
traci.close()
sys.stdout.flush()
return time
示例10: run
def run():
traci.init(int(PORT))
step = 0
while traci.simulation.getMinExpectedNumber() > 0:
traci.simulationStep()
step += 1
traci.close()
示例11: __init__
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)
示例12: runSingle
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)
示例13: traciSimulation
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()
示例14: run
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()
示例15: run
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)]