当前位置: 首页>>代码示例>>Python>>正文


Python traci.simulationStep函数代码示例

本文整理汇总了Python中traci.simulationStep函数的典型用法代码示例。如果您正苦于以下问题:Python simulationStep函数的具体用法?Python simulationStep怎么用?Python simulationStep使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了simulationStep函数的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()
开发者ID:dimvass,项目名称:Traffic-Simulator,代码行数:60,代码来源:runner.py

示例2: 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()
开发者ID:planetsumo,项目名称:sumo,代码行数:28,代码来源:runner.py

示例3: 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
开发者ID:Szagrat,项目名称:Project,代码行数:29,代码来源:main.py

示例4: 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()
开发者ID:RamonHPSilveira,项目名称:urbansim,代码行数:26,代码来源:runner.py

示例5: 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()
开发者ID:ea89,项目名称:traffic_simulations,代码行数:33,代码来源:RouteGenerator.py

示例6: 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()
开发者ID:cbrafter,项目名称:sumo,代码行数:35,代码来源:runner.py

示例7: 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()
开发者ID:gg-uah,项目名称:GARouter,代码行数:26,代码来源:runner.py

示例8: run

def run():
	traci.init(int(PORT))
	step = 0
	while traci.simulation.getMinExpectedNumber() > 0:
		traci.simulationStep()
		step += 1
	traci.close()
开发者ID:Ameddah,项目名称:sumoStats,代码行数:7,代码来源:runSUMO.py

示例9: 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 
开发者ID:cuijiaxing,项目名称:ea,代码行数:28,代码来源:simulate.py

示例10: run_ere

def run_ere(scenario_name, closed_roads, s_time, duration):
    """
    This is to enable the enroute event scenario using TraCI
    :param scenario_name: the name of the scenario
    :param closed_roads: the list of closed road id
    :param s_time: the starting time stamp for the road closure in seconds
    :param duration: the road closure duration in seconds
    """
    sumo_net = net.readNet(load_map(scenario_name))
    pre_sp_lim = []
    for i in closed_roads:
        pre_sp_lim.append(sumo_net.getEdge(i).getSpeed())

    s_time += traci.simulation.getCurrentTime()/1000
    e_time = s_time + duration

    while traci.simulation.getMinExpectedNumber() > 0:
        cur_step = traci.simulation.getCurrentTime()/1000

        if cur_step == s_time:
            for i in closed_roads:
                traci.edge.setMaxSpeed(i, 0.1)

        if cur_step == e_time:
            for seq, rid in enumerate(closed_roads):
                traci.edge.setMaxSpeed(rid, pre_sp_lim[seq])

        traci.simulationStep()
    traci.close()
    sys.stdout.flush()
开发者ID:ShenWangDCU,项目名称:adanrr,代码行数:30,代码来源:runner.py

示例11: runSimulationStep

def runSimulationStep(mtraci):
    """
    Runs one SUMO simulation step
    """
    mtraci.acquire()
    traci.simulationStep()
    mtraci.release()
开发者ID:gitali,项目名称:ASTra,代码行数:7,代码来源:simulation.py

示例12: 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()
开发者ID:Alex9321,项目名称:sumo,代码行数:26,代码来源:runner.py

示例13: main

def main():
    sumoCmd = [sumoBinary, "-c", sumoConfig]
    traci.start(sumoCmd)                               # 开始仿真
    simulationSteps = 0
    Phaseflag = 0
    while simulationSteps < 1000:                      # 仿真1000个步长
        traci.simulationStep()                         # 执行一步仿真

        # 获取仿真环境中当前仿真步的实时信息
        print('红绿灯路口西侧排队车辆数目:', traci.lanearea.getJamLengthVehicle('W'))
        print('红绿灯路口西侧排队长度:', traci.lanearea.getJamLengthMeters('W'))
        print('红绿灯路口东侧排队车辆数目:', traci.lanearea.getJamLengthVehicle('E'))
        print('红绿灯路口东侧排队长度:', traci.lanearea.getJamLengthMeters('E'))
        print('红绿灯路口北侧排队车辆数目:', traci.lanearea.getJamLengthVehicle('N'))
        print('红绿灯路口北侧排队长度:', traci.lanearea.getJamLengthMeters('N'))
        print('红绿灯路口南侧排队车辆数目:', traci.lanearea.getJamLengthVehicle('S'))
        print('红绿灯路口南侧排队长度:', traci.lanearea.getJamLengthMeters('S'))

        # 红绿灯控制程序
        # 所控红绿灯的相位顺序为:东西直行南北禁行(30秒),南北直行东西禁行(30秒)
        if simulationSteps % 30 == 0:
            if Phaseflag % 2 == 0:
                traci.trafficlight.setPhase('3', 0)   # 改变红绿灯的相位为东西直行南北禁行
            else:
                traci.trafficlight.setPhase('3', 1)   # 改变红绿灯的相位为南北直行东西禁行
            Phaseflag += 1
        simulationSteps += 1
    traci.close()                                     # 结束仿真
开发者ID:howeliu,项目名称:SUMO-Environment,代码行数:28,代码来源:main.py

示例14: 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)]
开发者ID:arminaskari,项目名称:sumo-project,代码行数:59,代码来源:runner.py

示例15: _createVehicle

 def _createVehicle(self,vehID, laneID, pos=0):
     routeID = _edge(laneID)
     laneIndex = int( laneID[laneID.rfind('_')+1:] )
     traci.vehicle.add(vehID,routeID,pos=pos,lane=laneIndex)
     traci._sendIntCmd(traci.constants.CMD_SET_VEHICLE_VARIABLE,
                       traci.constants.VAR_SPEEDSETMODE, vehID, 0)
     traci.vehicle.setLaneChangeMode(vehID, 0)
     traci.simulationStep()
开发者ID:utexas-ghosh-group,项目名称:carstop,代码行数:8,代码来源:sumoMethods.py


注:本文中的traci.simulationStep函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。