Search code examples
pythonsumo

Add/remove vehicles in SUMO via TraCI at runtime


I know that traci.vehicle API has an add and a remove function which is just traci vehicle remove or traci vehicle add. I am using SUMO on Windows. I have the network, the routes and a fixed number of 37000 vehicles in the network. I started my simulation in python and tried to remove a vehicle as follows when simulation is running:

import traci 
traci.start(sumoCmd)
stepz = 0
while traci.simulation.getMinExpectedNumber() > 0 and stepz < 7000:
   traci.simulationStep()
   traci.vehicle.remove("2773")
traci.close()

When I run this I get this error message:

Traceback (most recent call last): File "", line 9, in traci.vehicle.remove("2773")

File "C:\Program Files (x86)\Eclipse\Sumo\tools\traci_vehicle.py", line 1579, in remove tc.CMD_SET_VEHICLE_VARIABLE, tc.REMOVE, vehID, reason)

File "C:\Program Files (x86)\Eclipse\Sumo\tools\traci\connection.py", line 149, in _sendByteCmd self._sendExact() File "C:\Program Files (x86)\Eclipse\Sumo\tools\traci\connection.py", line 112, in _sendExact raise TraCIException(err, prefix[1], _RESULTS[prefix[2]]) TraCIException: Vehicle '2773' is not known.

"2773" is one of the vehicle's ID I got from my mytrip.trips.xml file. I don't know what is wrong with this piece of code and how to fix it. I also would like to know how should I find the RouteID to add a vehicle. Any help will be highly appreciated.


Solution

  • The problem probably is (as Michael pointed out) that you are trying to remove a vehicle that is not in the simulation yet. The vehicle with ID "2773" is only defined in your .rou.xml file. SUMO parses the .rou.xml file in runtime and loads the vehicles while the simulation is running. The vehicle is not yet in the simulation because it is either defined to depart at a different time or it is currently trying to enter the network but there are more vehicles before it (it's queued up).

    The solution is to check whether the vehicle has departed already:

    if "2773" in traci.vehicle.getIDList():
        traci.vehicle.remove("2773")
    

    or, try to remove and catch:

    try:
        traci.vehicle.remove("2773")
    except TraCIException:
        pass  # just do nothing
    

    As for your question in the comment about adding route. The "1" in line traci.route.add("1", ["5367021#0", "-133806981#1"]) is a new ID which you are trying to assign to a route consisting of edges "5367021#0" and "-133806981#1". Make sure you are not adding the same route again. The route id must be unique. In many cases, command is being executed repeatedly in a loop which causes the error.

    You can find everything you need in the documentation here: https://sumo.dlr.de/pydoc/