Search code examples
pythonsumo

Sumo, TraCI: Cannot add a vehicle after removing it without calling simulationStep()


I want to write a method for reinitializing my sumo simulation through TraCI. For this I need to remove all vehicles from the simulation and then add some of them to it again.

I do this by calling 
import traci

conn = traci.connect(port)
conn.vehicle.remove("55")
conn.vehicle.add("55", route_id)

# This throws an exception

The exception that is raised is:

traci.exceptions.TraCIException: The vehicle '55' to add already exists.

If I call conn.simulationStep() in between the remove and the add methods, this exception is not raised. This technically works, but I would prefer to not increment the simulation between removing and adding of vehicles.

When I output traci.vehicles.getIDList() after I removed vehicle 55, I can see that it was successfully removed. Then, why does the add method fail and tell me that this vehicle does exist?


Solution

  • Vehicles which leave the simulation in the current simulation step are only removed at the end of the step while traci commands are handled in the beginning. That's why it is currently not possible to do a remove and an add in the same step (not even without traci). Reusing ids is not considered good style in general. The output of `getIDList´ is not reliable here because it lists only the visible vehicles (it also exludes parking vehicles for instance).

    After all you might be better off trying to save the simulation state and reload it using simulation.saveState and simulation.loadState.