Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
import sumolib # noqa
traci.start([sumolib.checkBinary("sumo"), '-c', 'sumo.sumocfg'])
step = 0
done = False
bus_id = "bus"
while traci.simulation.getMinExpectedNumber() > 0:
next_stops = traci.vehicle.getNextStops(bus_id)
if len(next_stops) > 0:
stop = next_stops[0]
bus_stop_pos = stop[1]
if stop[2] == "busStop2" and traci.vehicle.getLaneID(bus_id) == stop[0]:
bus_pos = traci.vehicle.getLanePosition(bus_id)
if bus_stop_pos - bus_pos < 10:
traci.vehicle.setBusStop(bus_id, "busStop2", 0, 0, 0)
print("abort stop at busStop2 at t=%s" % traci.simulation.getTime())
traci.simulationStep()
traci.close()
if refVehID == "":
leader = results[tc.VAR_LEADER][0]
leaderDist = results[tc.VAR_LEADER][1]
elif not leaderArrived:
leader = refVehID
arrived = traci.simulation.getArrivedIDList()
# print ("arrived vehicles: %s"%(str(arrived)))
if leader in arrived:
print("Reference vehicle has been removed.")
leaderArrived = True
targetGapEstablished = True
gapControlActive = False
else:
traci.vehicle.subscribe(leaderID, [tc.VAR_SPEED])
leaderEdgeID = traci.vehicle.getRoadID(leader)
leaderPos = traci.vehicle.getLanePosition(leader)
leaderDist = traci.vehicle.getDrivingDistance(followerID, leaderEdgeID, leaderPos)
followerSpeed = results[tc.VAR_SPEED]
leaderSpeed = traci.vehicle.getSubscriptionResults(leaderID)[tc.VAR_SPEED]
currentTimeHeadway = leaderDist/followerSpeed if followerSpeed > 0 else 10000
currentTime = traci.simulation.getTime()
print("Time %s: Gap 'follower'->'%s' = %.3f (headway=%.3f)" %
(currentTime, leader, leaderDist, currentTimeHeadway))
print("'follower' speed = %s" % followerSpeed)
sys.stdout.flush()
if (not gapControlActive and not targetGapEstablished and currentTime > 50.):
print("## Starting to open gap.")
sys.stdout.flush()
print("(followerID, targetTimeHeadway, targetSpaceHeadway, duration, changeRate) = %s" %
str((followerID, targetTimeHeadway, targetSpaceHeadway, duration, changeRate)))
if refVehID == "":
if maxDecel == -1:
def check(x, y, angle, exLane, exPos, exPosLat, comment):
traci.vehicle.moveToXY(vehID, "", 0, x, y, angle)
traci.simulationStep()
x2, y2 = traci.vehicle.getPosition(vehID)
lane2 = traci.vehicle.getLaneID(vehID)
pos2 = traci.vehicle.getLanePosition(vehID)
posLat2 = traci.vehicle.getLateralLanePosition(vehID)
if (abs(x - x2) > 0.1 or
abs(y - y2) > 0.1 or
(exLane != lane2 and exLane is not None) or
(exPos is not None and abs(exPos - pos2) > 0.1) or
(exPosLat is not None and abs(exPosLat - posLat2) > 0.1)):
print(comment, ("failed: x=%s, x2=%s, y=%s, y2=%s, lane=%s, lane2=%s, pos=%s, pos2=%s " +
"posLat=%s posLat2=%s") % (x, x2, y, y2, exLane, lane2, exPos, pos2, exPosLat, posLat2))
else:
# (comment, "success")
pass
print(traci.simulation.getTime(),
" lane=%s" % lane2,
# " route=%s" % str(traci.vehicle.getRoute(vehID)),
" right=%s, %s" % traci.vehicle.getLaneChangeStatePretty(vehID, -1),
" left=%s, %s" % traci.vehicle.getLaneChangeStatePretty(vehID, 1),
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.getTime(),
vehID,
traci.vehicle.getLaneID(vehID),
traci.vehicle.getLanePosition(vehID),
traci.vehicle.getSpeed(vehID)))
except traci.TraCIException:
pass
if steps > 1:
print()
def checkOffRoad(vehID):
print(("veh", vehID,
"speed", traci.vehicle.getSpeed(vehID),
"pos", posToString(traci.vehicle.getPosition(vehID)),
"pos3d", posToString(traci.vehicle.getPosition3D(vehID)),
"angle", traci.vehicle.getAngle(vehID),
"road", traci.vehicle.getRoadID(vehID),
"lane", traci.vehicle.getLaneID(vehID),
"lanePos", traci.vehicle.getLanePosition(vehID),
"CO2", traci.vehicle.getCO2Emission(vehID)
))
def get_lane_position(self, vID):
lanepos = traci.vehicle.getLanePosition(vID)
lane = traci.vehicle.getLaneID(vID).split("_")
return self.lanestarts[lane[0]] + lanepos
def distance_between_vehicles(v1, v2, recursion=False):
"""
Computes the distance between two vehicles (from v1 to v2)
:param v1: ID of the first vehicle
:param v2: ID of the second vehicle
:param recursion: whether this function is called from itself or not
:type v1: str
:type v2: str
:type recursion: bool
:return: tuple with the distance between the two vehicles (from v1 to v2)
and whether this distance is valid or not
:rtype: (float, bool)
"""
edge = traci.vehicle.getRoadID(v2)
pos = traci.vehicle.getLanePosition(v2)
lane = traci.vehicle.getLaneIndex(v2)
if lane < 0:
return -1, False
distance = traci.vehicle.getDrivingDistance(v1, edge, pos, lane)
# Sometimes both vehicles will be unreachable for each other, in this case
# the computed distance in both ways will be negative and invalid
if recursion and distance < 0:
return -1, False
# Since getDrivingDistance can return a negative and invalid distance when
# computing the distance to a vehicle that is placed behind, we compute the
# distance in both directions to use the valid distance (which will be the
# positive and valid one) and multiply the distance to a rear vehicle by -1
sign = -1 if recursion else 1
length = len(priorityVehicles)
# Checking if the next traffic light has to be changed for each priority vehicleId in the simulation
for prioVehIndex in range(0, length):
vehicleId = priorityVehicles[prioVehIndex]
# Getting route and position information for the current priority vehicleId
mtraci.acquire()
route = traci.vehicle.getRoute(vehicleId)
currentLane = traci.vehicle.getLaneID(vehicleId)
mtraci.release()
if currentLane != '' and not isJunction(currentLane):
# Getting speed information for space and time predictions
mtraci.acquire()
lanePosition = traci.vehicle.getLanePosition(vehicleId)
laneLength = traci.lane.getLength(currentLane)
mtraci.release()
currentEdge = getEdgeFromLane(currentLane)
currentEdgeIndex = route.index(currentEdge)
remainingLength = laneLength - lanePosition
edge = currentEdge
lane = currentLane
edgeIndex = currentEdgeIndex
# Browsing the next edges the vehicleId will go to
while remainingLength <= constants.YELLOW_LENGTH_ANTICIPATION and edgeIndex < len(route) - 1:
# If the current edge (the vehicleId is not) ends with a traffic light
if edge in tllDict:
# If the car is close enough for the traffic light to become green
if remainingLength <= constants.GREEN_LENGTH_ANTICIPATION:
def _get_state(self):
state = np.zeros(self._model.num_states)
for veh_id in traci.vehicle.getIDList():
lane_pos = traci.vehicle.getLanePosition(veh_id)
lane_id = traci.vehicle.getLaneID(veh_id)
lane_pos = 750 - lane_pos # inversion of lane so if close to TL, lane_pos = 0
lane_group = -1 # just initialization
valid_car = False # flag for dont detecting cars crossing the intersection or driving away from it
if lane_pos < 7:
lane_cell = 0
elif lane_pos < 14:
lane_cell = 1
elif lane_pos < 21:
lane_cell = 2
elif lane_pos < 28:
lane_cell = 3
elif lane_pos < 40:
lane_cell = 4
elif lane_pos < 60:
warn("Given parameter switchImpatience < 0. Assuming == 0.")
switchImpatience = 0.
# obtain the preferred deceleration and the tau of the target vType
decel = vTypeParameters[self._vTypes[targetMode]][tc.VAR_DECEL]
tau = vTypeParameters[self._vTypes[targetMode]][tc.VAR_TAU]
speed = self.state.speed
# If time until switch decreases below 0, this indicates that a switch from platoon to normal mode is required
maxDecel = vTypeParameters[self._vTypes[targetMode]][tc.VAR_EMERGENCY_DECEL] * switchImpatience \
+ (1. - switchImpatience) * decel
# check whether a halt at the end of the lane would prohibit the switch to a lower deceleration
# TODO: restrict check to situations where a halt is really required
if vTypeParameters[self._vTypes[self._currentPlatoonMode]][tc.VAR_DECEL] > decel:
distToLaneEnd = traci.lane.getLength(self.state.laneID) - traci.vehicle.getLanePosition(self._ID)
if self.brakeGap(speed, maxDecel) > distToLaneEnd:
return False
# check whether the ego vehicle has a leader, which must be considered
if self.state.leaderInfo is None:
return True
leader = self.state.leader
gap = self.state.leaderInfo[1]
minGapDifference = vTypeParameters[self._vTypes[targetMode]][
tc.VAR_MINGAP] - vTypeParameters[self.getCurrentVType()][tc.VAR_MINGAP]
gap -= minGapDifference
if gap < 0.:
# may arise when minGap of target type differs
return False