How to use traci - 10 common examples

To help you get started, we’ve selected a few traci examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github LucasAlegre / sumo-rl / sumo_rl / environment / traffic_signal.py View on Github external
def __init__(self, env, ts_id, delta_time, yellow_time, min_green, max_green, phases):
        self.id = ts_id
        self.env = env
        self.time_on_phase = 0.0
        self.delta_time = delta_time
        self.yellow_time = yellow_time
        self.min_green = min_green
        self.max_green = max_green
        self.green_phase = 0
        self.num_green_phases = len(phases) // 2
        self.lanes = list(dict.fromkeys(traci.trafficlight.getControlledLanes(self.id)))  # remove duplicates and keep order

        logic = traci.trafficlight.Logic("new-program", 0, 0, phases=phases)
        traci.trafficlight.setCompleteRedYellowGreenDefinition(self.id, logic)
github eclipse / sumo / tests / complex / traci / connection / repeatedConnection / runner.py View on Github external
fdi = open("sumo.sumocfg")
    fdo = open("used.sumocfg", "w")
    fdo.write(fdi.read() % {"end": sumoEndTime})
    fdi.close()
    fdo.close()
    step = 0
    sumoProcess = subprocess.Popen(
        "%s -c used.sumocfg -S -Q --remote-port %s" % (sumoBinary, PORT), 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) > 3:
            print("Something is wrong")
        step += 1
    print("Print ended at step %s" % traci.simulation.getTime())
    traci.close()
    sumoProcess.wait()
    sys.stdout.flush()
github eclipse / sumo / tests / complex / traci / ContextSubscriptionFilters / lanesUpDownDistance / runner.py View on Github external
traci.simulationStep()

        if subscribed:
            # check if objID has arrived at destination
            arrivedList = traci.simulation.getArrivedIDList()
            if objID in arrivedList:
                print("[%03d] Vehicle '%s' has arrived at destination" % (step, objID))
                break

            print("[%03d] Context results for vehicle '%s':" % (step, objID))
            for v in sorted(traci.vehicle.getContextSubscriptionResults(objID) or []):
                print(v)

        if not subscribed:
            print("Subscribing to vehicle context of object '%s'" % (objID))
            traci.vehicle.subscribeContext(objID, traci.constants.CMD_GET_VEHICLE_VARIABLE,
                                           viewRange, [traci.constants.VAR_POSITION])
            sys.stdout.flush()

            laneList = map(int, sys.argv[3].strip('[]').split(','))

            traci.vehicle.addSubscriptionFilterLanes(laneList)
            traci.vehicle.addSubscriptionFilterUpstreamDistance(float(sys.argv[4]))
            traci.vehicle.addSubscriptionFilterDownstreamDistance(float(sys.argv[5]))

            # advice all vehicle not to change lanes
            for vehID in traci.vehicle.getIDList():
                traci.vehicle.changeLane(vehID, traci.vehicle.getLaneIndex(vehID), 111)

            subscribed = True
        step += 1
github eclipse / sumo / tests / complex / traci / vehicle / vehicle / runner.py View on Github external
def check(vehID):
    print("vehicles", traci.vehicle.getIDList())
    print("vehicle count", traci.vehicle.getIDCount())
    print("examining", vehID)
    print("speed", traci.vehicle.getSpeed(vehID))
    print("speedLat", traci.vehicle.getLateralSpeed(vehID))
    print("speed w/o traci", traci.vehicle.getSpeedWithoutTraCI(vehID))
    print("acceleration", traci.vehicle.getAcceleration(vehID))
    print("pos", posToString(traci.vehicle.getPosition(vehID)))
    print("pos3D", posToString(traci.vehicle.getPosition3D(vehID)))
    print("angle", traci.vehicle.getAngle(vehID))
    print("road", traci.vehicle.getRoadID(vehID))
    print("lane", traci.vehicle.getLaneID(vehID))
    print("laneIndex", traci.vehicle.getLaneIndex(vehID))
    print("type", traci.vehicle.getTypeID(vehID))
    print("routeID", traci.vehicle.getRouteID(vehID))
    print("routeIndex", traci.vehicle.getRouteIndex(vehID))
    print("route", traci.vehicle.getRoute(vehID))
github eclipse / sumo / tests / complex / sumo / ToCDevice / LC_during_MRM / runner.py View on Github external
def printToCParams(vehID, only_dynamic=False):
    holder = traci.vehicle.getParameter(vehID, "device.toc.holder")
    manualType = traci.vehicle.getParameter(vehID, "device.toc.manualType")
    automatedType = traci.vehicle.getParameter(vehID, "device.toc.automatedType")
    responseTime = traci.vehicle.getParameter(vehID, "device.toc.responseTime")
    recoveryRate = traci.vehicle.getParameter(vehID, "device.toc.recoveryRate")
    initialAwareness = traci.vehicle.getParameter(vehID, "device.toc.initialAwareness")
    mrmDecel = traci.vehicle.getParameter(vehID, "device.toc.mrmDecel")
    currentAwareness = traci.vehicle.getParameter(vehID, "device.toc.currentAwareness")
    state = traci.vehicle.getParameter(vehID, "device.toc.state")
    speed = traci.vehicle.getSpeed(vehID)

    print("time", traci.simulation.getTime())
    print("ToC device infos for vehicle '%s'" % vehID)
    if not only_dynamic:
        print("Static parameters:")
        print("  holder = %s" % holder)
        print("  manualType = %s" % manualType)
        print("  automatedType = %s" % automatedType)
        print("  responseTime = %s" % responseTime)
        print("  recoveryRate = %s" % recoveryRate)
        print("  initialAwareness = %s" % initialAwareness)
        print("  mrmDecel = %s" % mrmDecel)
        print("Dynamic parameters:")
    print("  currentAwareness = %s" % currentAwareness)
    print("  currentSpeed = %s" % speed)
    print("  state = %s" % state)
github eclipse / sumo / tests / complex / traci / bugs / ticket2804 / runner.py View on Github external
def check(vehID, steps=1):
    for i in range(steps):
        if i > 0:
            traci.simulationStep()
        try:
            print("%s vehicle %s on lane=%s pos=%s speed=%s" % (
                traci.simulation.getCurrentTime() / 1000.0,
                vehID,
                traci.vehicle.getLaneID(vehID),
                traci.vehicle.getLanePosition(vehID),
                traci.vehicle.getSpeed(vehID)))
        except traci.TraCIException:
            pass
    if steps > 1:
        print()
github eclipse / sumo / tests / complex / sumo / ToCDevice / use_cases / runner.py View on Github external
step += 1
        if options.debug:
            print("\n---------------------------------\nsimstep: %s" % step)
        # Keep book of entered AVs
        arrivedVehs = [vehID for vehID in traci.simulation.getArrivedIDList() if vehID.startswith(AV_identifier)]
        downwardToCPending.update([vehID for vehID in traci.simulation.getDepartedIDList()
                                   if vehID.startswith(AV_identifier)])

        # provide the ToCService at the traffic sign for informing the lane closure
        doToC(downwardToCPending, downwardTocRequested, timeUntilMRM, downwardEdgeID, distance)
        downwardToCPending.difference_update(downwardTocRequested)

        # keep book on performed ToCs and trigger best lanes update by resetting the route
        downwardTocPerformed = set()
        for vehID in downwardTocRequested:
            if traci.vehicle.getVehicleClass(vehID) == "passenger":
                if options.debug:
                    print("successful change for vehicle '%s'" % vehID)
                downwardTocPerformed.add(vehID)
                routeEdges = traci.route.getEdges(routeID)
                traci.vehicle.setRoute(vehID, routeEdges[traci.vehicle.getRouteIndex(vehID)])
                traci.vehicle.setRouteID(vehID, routeID)
        downwardTocRequested.difference_update(downwardTocPerformed)
        upwardToCPending.update(downwardTocPerformed)

        # provide ToCService to the upwardTransitions
        upwardTocPerformed = set()
        doToC(upwardToCPending, upwardTocPerformed, 0., upwardEdgeID, upwardDist)
        upwardToCPending.difference_update(upwardTocPerformed)
        if options.debug:
            print("downwardTocRequested=%s" % downwardTocRequested)
            print("Downward ToC performed: %s" % str(sorted(downwardTocPerformed)))
github eclipse / sumo / tests / complex / sumo / ToCDevice / dynamic_ToC_stop / runner.py View on Github external
def run():
    """execute the TraCI control loop"""
    step = 0
    printToCParams(ToC_vehicle, False)
    t = traci.simulation.getTime()
    # prevent LCs
    origLCMode = traci.vehicle.getLaneChangeMode(ToC_vehicle)
    traci.vehicle.setLaneChangeMode(ToC_vehicle, 768)
    restoredLCMode = False
    traci.simulationStep()
    while traci.simulation.getMinExpectedNumber() > 0:
        t = traci.simulation.getTime()
        print("Time %s: Current lane of veh '%s': %s" % (t, ToC_vehicle, traci.vehicle.getLaneID(ToC_vehicle)))
        printToCParams(ToC_vehicle, True)
        if not restoredLCMode and traci.vehicle.getParameter(ToC_vehicle, "device.toc.state") == "RECOVERING":
            traci.vehicle.setLaneChangeMode(ToC_vehicle, origLCMode)
            print("Switched to manual mode: Allowing LCs!")
            # ~ restoredLCMode = True
        sys.stdout.flush()
        step += 1
        traci.simulationStep()
github eclipse / sumo / tests / complex / traci / vehicle / vehicle / runner.py View on Github external
traci.vehicle.subscribe(electricVeh, [tc.VAR_POSITION, tc.VAR_POSITION3D])
for i in range(10):
    step()
    print(('%s speed="%s" consumed="%s" charged="%s" cap="%s" maxCap="%s" station="%s" mass=%s emissionClass=%s ' +
           'electricityConsumption=%s') % (
        electricVeh,
        traci.vehicle.getSpeed(electricVeh),
        traci.vehicle.getParameter(electricVeh, "device.battery.energyConsumed"),
        traci.vehicle.getParameter(electricVeh, "device.battery.energyCharged"),
        traci.vehicle.getParameter(electricVeh, "device.battery.actualBatteryCapacity"),
        traci.vehicle.getParameter(electricVeh, "device.battery.maximumBatteryCapacity"),
        traci.vehicle.getParameter(electricVeh, "device.battery.chargingStationId"),
        traci.vehicle.getParameter(electricVeh, "device.battery.vehicleMass"),
        traci.vehicle.getEmissionClass(electricVeh),
        traci.vehicle.getElectricityConsumption(electricVeh),
    ))
    print(sorted(traci.vehicle.getSubscriptionResults(electricVeh).items()))
# test for adding a trip
traci.route.add("trip2", ["3si", "4si"])
traci.vehicle.addLegacy("triptest2", "trip2", typeID="reroutingType")
print("triptest route:", traci.vehicle.getRoute("triptest2"))
step()
print("triptest route:", traci.vehicle.getRoute("triptest2"))
# test for adding a vehicle without specifying the route
traci.vehicle.addLegacy("noRouteGiven", "")
step()
print("noRouteGiven routeID: %s edges: %s" % (
    traci.vehicle.getRouteID("noRouteGiven"),
    traci.vehicle.getRoute("noRouteGiven")))
# test for adding a vehicle with explicit departLane
traci.vehicle.add("vehDepartLane", "horizontal", departLane="0")
github eclipse / sumo / tests / complex / sumo / ToCDevice / incomplete_MRM / runner.py View on Github external
# this script has been called from the command line. It will start sumo as a
    # server, then connect and run
    if options.nogui:
        sumoBinary = checkBinary('sumo')
    else:
        sumoBinary = checkBinary('sumo-gui')

    # this is the normal way of using traci. sumo is started as a
    # subprocess and then the python script connects and runs
    traci.start([sumoBinary, "-n", "input_net.net.xml", "-r", "input_routes.rou.xml", "-a",
                 "input_additional.add.xml", "--fcd-output", "fcd.xml",
                 "--no-step-log", "true",
                 "--default.speeddev", "0"])

    # Wait until the vehicle enters
    while ToC_vehicle not in traci.vehicle.getIDList():
        traci.simulationStep()

    printToCParams(ToC_vehicle)

    run()

    traci.close()
    sys.stdout.flush()