Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
[sumo-dev] sumo crashes when setting a stop

Hi,

running the scenario of Ifezue Obiako I got an segment fault under linux when setting a stop

time  3600s vehicle 1 (running) send to charging station (fuel  354000.00, stopState 0)

Program received signal SIGSEGV, Segmentation fault.
std::_Rb_tree<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::__cxx11::basic_string<char, std::ch
ar_traits<char>, std::allocator<char> > >, std::_Select1st<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char
> > > >, std::less<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::__cxx11::basi
c_string<char, std::char_traits<char>, std::allocator<char> > > > >::_Reuse_or_alloc_node::_Reuse_or_alloc_node (this=0x7fffffffc600, __t=...) at /usr/include/c++/11/bits/stl_tree.h:444                                                
444             : _M_root(__t._M_root()), _M_nodes(__t._M_rightmost()), _M_t(__t)
(gdb) bt
#0  std::_Rb_tree<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::__cxx11::basic_string<char, std
::char_traits<char>, std::allocator<char> > >, std::_Select1st<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<
char> > > >, std::less<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::__cxx11::
basic_string<char, std::char_traits<char>, std::allocator<char> > > > >::_Reuse_or_alloc_node::_Reuse_or_alloc_node (this=0x7fffffffc600, __t=...) at /usr/include/c++/11/bits/stl_tree.h:444                                            
#1  0x0000555555670326 in std::_Rb_tree<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::__cxx11::
basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::_Select1st<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::__cxx11::basic_string<char, std::char_traits<
char>, std::allocator<char> > > >, std::less<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >
const, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >::operator= (this=0x8, __x=...) at /usr/include/c++/11/bits/stl_tree.h:1751                                                                 
#2  0x000055555566874b in std::map<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::less<std::__cxx11::basic_strin
g<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::__cxx11::basic_string<char, std::char_traits<char>, std::
allocator<char> > > > >::operator= (this=0x8) at /usr/include/c++/11/bits/stl_map.h:319                                                                                                                                                  
#3  0x0000555555668781 in Parameterised::operator= (this=0x0) at /dosd/src/opensource/Sumo/sumo-git-co/sumo/src/utils/common/Parameterised.h:41
#4  0x000055555568660d in SUMOVehicleParameter::Stop::operator= (this=0x0) at /dosd/src/opensource/Sumo/sumo-git-co/sumo/src/utils/vehicle/SUMOVehicleParameter.h:334
#5  0x00005555556c4b2b in MSBaseVehicle::replaceStop (this=0x55555b54c020, nextStopIndex=0, stop=..., info="traci:replaceStop", teleport=false, errorMsg="")
   at /dosd/src/opensource/Sumo/sumo-git-co/sumo/src/microsim/MSBaseVehicle.cpp:1447
#6  0x000055555586405c in libsumo::Vehicle::replaceStop (vehID="1", nextStopIndex=0, edgeID="chargingStation_-7855681#1.111_1_1", pos=1, laneIndex=0, duration=900, flags=32, startPos=-1073741824, until=-1073741824, teleport=0)
   at /dosd/src/opensource/Sumo/sumo-git-co/sumo/src/libsumo/Vehicle.cpp:967
#7  0x00005555557cba9c in TraCIServerAPI_Vehicle::processSet (server=..., inputStorage=..., outputStorage=...) at /dosd/src/opensource/Sumo/sumo-git-co/sumo/src/traci-server/TraCIServerAPI_Vehicle.cpp:512
#8  0x000055555578d852 in TraCIServer::dispatchCommand (this=0x55555629bc40) at /dosd/src/opensource/Sumo/sumo-git-co/sumo/src/traci-server/TraCIServer.cpp:823
#9  0x000055555578caed in TraCIServer::processCommandsUntilSimStep (this=0x55555629bc40, step=3600000) at /dosd/src/opensource/Sumo/sumo-git-co/sumo/src/traci-server/TraCIServer.cpp:664
#10 0x00005555555a7316 in MSNet::simulationStep (this=0x5555562a4730) at /dosd/src/opensource/Sumo/sumo-git-co/sumo/src/microsim/MSNet.cpp:594
#11 0x00005555555a3eab in MSNet::simulate (this=0x5555562a4730, start=0, stop=-1000) at /dosd/src/opensource/Sumo/sumo-git-co/sumo/src/microsim/MSNet.cpp:389
#12 0x00005555555a04ab in main (argc=13, argv=0x7fffffffd998) at /dosd/src/opensource/Sumo/sumo-git-co/sumo/src/sumo_main.cpp:98

The software version is
v1_12_0+0394-869defde81a

Attached is the traci script. The stack trace is

Traceback (most recent call last):
 File "/dosd/Sumo/Vincent/TestingFiles_Hybrid/./runner_1b_3_Hybrid_R2_H1.py", line 175, in fueling_behavior
   traci.vehicle.replaceStop(e, nextStop, chargingStations, duration=refuelTime, flags=32) #chargingStation_-7855681#1_0_0
 File "/usr/local/lib/python3.9/dist-packages/traci/_vehicle.py", line 1116, in replaceStop
   self._setCmd(tc.CMD_REPLACE_STOP, vehID, "tsdbdiddib", 9, edgeID, pos,
 File "/usr/local/lib/python3.9/dist-packages/traci/domain.py", line 189, in _setCmd
   self._connection._sendCmd(self._cmdSetID, varID, objectID, format, *values)
 File "/usr/local/lib/python3.9/dist-packages/traci/connection.py", line 181, in _sendCmd
   return self._sendExact()
 File "/usr/local/lib/python3.9/dist-packages/traci/connection.py", line 91, in _sendExact
   raise FatalTraCIError("connection closed by SUMO")
traci.exceptions.FatalTraCIError: connection closed by SUMO

Regards Harald

#!/usr/bin/python3
import os
import sys

if 'SUMO_HOME' in os.environ:
     tools = os.path.join(os.environ['SUMO_HOME'], 'tools')
     sys.path.append(tools)
else:
     sys.exit("please declare environment variable 'SUMO_HOME'")

# import time
from sumolib import checkBinary
from enum import Enum
import traceback
import argparse

parser = argparse.ArgumentParser(
    prog='runner.py',
    #usage='%(prog)s [optional arguments] -- SUMOARGS',
    description='Run SUMO and compute passengers per vehicle',
    epilog="Examples\n"
          '  runner.py -t 5000 \n'
          '    run SUMO until 5000 sec'
, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-f','--first', type=int, default=3600, help='From time')
parser.add_argument('-l','--last', type=int, default=65000, help='last time step for simulation')
parser.add_argument('-s','--seed', type=int, default=42, help='random seed')
parser.add_argument('-g','--gui', action='store_true', help='Use sumo-gui')
parser.add_argument('-L','--libsumo', action='store_true', help='Use libsumo')
parser.add_argument('-F','--fcd', action='store_true', help='export fcd data')
parser.add_argument('-d','--gdb', action='store_true', help='Run with gdb')
args = parser.parse_args()

'''
call tree
  run  -+->  fueling_behavior
        +->  maintain_headway  -> maintainHeadway
        +->  takeDriverBreak   -> insertDriverBreak (not yet)

Functions for common tasks
  extendCurrentStop
  printVehicleMessage
  printVehicleStateMessage
'''

if args.libsumo:
  import libsumo as traci
else:
  import traci

class BusState(Enum):
  running = 0
  goingToCharge = 1
  charging = 2
  waitingForGoingToCharge = 3

class DriverBreakStatus(Enum):
    running = 0
    AMbathroomFood = 5
    PMbathroomFood = 6
    shiftChange = 7
    Lunch = 8
#     notBreaking = 8

class DriveType(Enum):
    hydrogen = 0
    hdb_diesel = 1

# class FuelDepletionState (Enum):
#     hydrogenDepletionLevel = 212400
#     hdb_dieselDepletionLevel = 666667
#
# class Fuel

# naming convention lists have always a plural s
breakStates = {"0":0, "1":0, "2":0, "3":0, "4":0, "5":0, "6":0, "7":0}
vehicles = ("0", "1", "2", "3", "4", "5", "6", "7") # This was previously a list
vehiclesDriveType = {'0' : DriveType.hdb_diesel, '1' : DriveType.hdb_diesel, '2':DriveType.hdb_diesel, '3':DriveType.hdb_diesel, '4':DriveType.hdb_diesel,
                     '5':DriveType.hdb_diesel, '6':DriveType.hdb_diesel, '7':DriveType.hdb_diesel}
refuelingDurations = {'0':900, '1':900, '2':900, '3':900, '4':900, '5':900, '6':900, '7':900}
fuelDepletionLevels = {'0':666667, '1':666667, '2':666667, '3':666667, '4':666667, '5':666667, '6':666667, '7':666667}

# fuelDepletionLevels = {'0':666667, '1':212400, '2':212400, '3':666667, '4':666667, '5':666667, '6':666667, '7':666667}
topOffLevels = {'0':1055555, '1':1055555, '2':1055555, '3':1055555, '4':1055555, '5':1055555, '6':1055555, '7':1055555}
chargingStationType = {'0':'chargingStation_-7855681#1.111_1_1', '1':'chargingStation_-7855681#1.111_1_1', '2':'chargingStation_-7855681#1.111_1_1',
                       '3':'chargingStation_-7855681#1.111_1_1', '4':'chargingStation_-7855681#1.111_1_1', '5':'chargingStation_-7855681#1.111_1_1',
                       '6':'chargingStation_-7855681#1.111_1_1', '7':'chargingStation_-7855681#1.111_1_1'}

finishedBuses = []
activeBuses = []

waitingBuses = {}
chargingStationEdge = '-7855681#1.111'
# chargingStationsEdge = {}
# chargingStationIndex = {}
# refuelingDurations = {}
# fuelDepletionLevels = {}
# topOffLevels = {}

# chargingStationsEdge[DriveType.hydrogen] = 'chargingStation_-7855681#1.111_0_0'
# chargingStationsEdge[DriveType.hdb_diesel] = 'chargingStation_-7855681#1.111_1_1'
# chargingStationIndex[DriveType.hydrogen] = 0
# chargingStationIndex[DriveType.hdb_diesel] = 1
# chargingStationIDs[DriveType.hydrogen] = 'chargingStation_-7855681#1.111_0_0'
# chargingStationIDs[DriveType.hdb_diesel] = 'chargingStation_-7855681#1.111_1_1'
# refuelingDurations[DriveType.hydrogen] = 300 # Refueling duration for H2 buses
# refuelingDurations[DriveType.hdb_diesel] = 900 # Refueling duration for HDB_buses
# fuelDepletionLevels[DriveType.hydrogen] = 212400 # Fuel level for H2 buses to refuel @
# fuelDepletionLevels[DriveType.hdb_diesel] = 666667 # Fuel level for HDB_Diesel buses to refuel @
# topOffLevels[DriveType.hydrogen] = 336300 # Fuel stop level for H2 buses
# topOffLevels[DriveType.hdb_diesel] = 1055555 # Fuel stop level for HDB_Diesel buses
# have a dictionary of vehicles and their states, initially all running
busStates = {}

csvfile = None
energyfile = None
eventfile = None

def fuelingHeadway(vehID, headway):
    traci.vehicle.setMinGap(vehID, headway)

def printVehicleStateMessage(vehicleId, message, states = busStates):
    global eventfile

    stateMessage = '(%s) %s' % (states[vehicleId].name, message)
    printVehicleMessage(vehicleId, stateMessage)

def printVehicleMessage(vehicleId, message):
    global eventfile
    global current_time

    longMessage = 'time %5ds vehicle %s %s' % (current_time, vehicleId, message)
    print(longMessage)
    print(longMessage, file=eventfile, flush=True)

# plugins for the main loop fror different questions
def fueling_behavior(current_time):
  global csvfile, energyfile, eventfile
  global actualFuelLevel, numActualFuelLevel, numBusRiders
  global activeBuses

  if 3600 <= current_time <= 65000:

    simTime = [str(current_time)]
    for e in activeBuses:
        try:
          actualFuelLevel = traci.vehicle.getParameter(e, "device.battery.actualBatteryCapacity")
        except Exception as ex:
          if str(ex).endswith(' is not known.'):
            printVehicleStateMessage(e, 'error %s' % ( str(ex)))
            finishedBuses.append(e)
            activeBuses.remove(e)
            printVehicleStateMessage(e, 'finishedBuses %s' % ( str(finishedBuses)))
            printVehicleStateMessage(e, 'e in finishedBuses %s' % (e in finishedBuses))
          else:
            traceback.print_exc(file=eventfile)
          continue
        numActualFuelLevel = float(actualFuelLevel)
        numBusRiders, stopState = traci.vehicle.getPersonNumber(e), traci.vehicle.getStopState(e)
        # here is the state machine
        if busStates[e] == BusState.running:
#           fuelingHeadway(e, 1) # if the vehicle is ABs; OTHERWISE COMMENT OUT <<<<----
          roadID = traci.vehicle.getRoadID(e)
          if (numActualFuelLevel <= fuelDepletionLevels[e]) and numBusRiders == 0 and (not roadID.startswith(':')):#666667:Diesel/Biodiesel, 665102: Propane/NaturalGas, 86400:Electricity, 212400:Hydrogen (40% fuel depletion)
            try:
                nextStop = 0
                if stopState != 0:
                  nextStop = 1
                vehicleDriveType = vehiclesDriveType[e] # eletric, diesel
#                 chargingStationEdge = chargingStationsEdge[vehicleDriveType]
#                 chargingStationID = chargingStationsEdge
                chargingStations = chargingStationType[e]
                refuelTime=refuelingDurations[e]
                printVehicleStateMessage(e, 'send to charging station %s (fuel %10.2f, stopState %d, duration=%d)' % (chargingStations, numActualFuelLevel, stopState, refuelTime))
                traci.vehicle.replaceStop(e, nextStop, chargingStations, duration=refuelTime, flags=32) #chargingStation_-7855681#1_0_0
                busStates[e], routeIndex, route = BusState.goingToCharge, traci.vehicle.getRouteIndex(e), traci.vehicle.getRoute(e)
                if routeIndex >= 0:
                  try:
                    newStopIndex = route.index(chargingStationEdge, routeIndex) #chargingStationEdge
                  except:
                    newStopIndex = -1
                  printVehicleStateMessage(e, 'New route from index %d to %d' % ( routeIndex, newStopIndex))
                #print('new route for vehicle %s = %s' % (e, ' '.join(traci.vehicle.getRoute(e))))
            except Exception as ex:
                traceback.print_exc(file=eventfile)
                #print(str(e))
                #print ("Unexpected error:", sys.exc_info()[0])
                printVehicleStateMessage(e, 'error cannot set new stop (%s)' % (str(ex)))
                busStates[e], roadID = BusState.waitingForGoingToCharge, traci.vehicle.getRoadID(e)
                printVehicleStateMessage(e, 'is at %s' % (roadID))
                # wait 100 sec and try again
                waitingBuses[e] = 100
        elif busStates[e] == BusState.waitingForGoingToCharge:
          waitingBuses[e] -= 1
          if waitingBuses[e] == 0:
            busStates[e] = BusState.running
            printVehicleStateMessage(e, 'is running again')
        elif busStates[e] == BusState.goingToCharge:
          roadID = traci.vehicle.getRoadID(e)
          if roadID == chargingStationEdge:
            busStates[e] = BusState.charging
            fuelingHeadway(e, 8) # if the vehicle is ABs; OTHERWISE COMMENT OUT <<<<----
            printVehicleStateMessage(e, 'at %-30s fuel %10.2f' % (roadID, numActualFuelLevel))
        elif busStates[e] == BusState.charging:
          roadID = traci.vehicle.getRoadID(e)
          #printVehicleStateMessage(e, 'at %-30s fuel %10.2f' % (roadID, numActualFuelLevel))
          # charging stops, when
          #   the stop at the charging station is finished
          #   or a resume command is issued
          if roadID != chargingStationEdge:
            busStates[e] = BusState.running
          if numActualFuelLevel > topOffLevels[e]: #1055555:Diesel/Biodiesel, 1053078:Propane/NaturalGas, 136800:Electricity, 336300:Hydrogen (95% full)
            try:
              printVehicleStateMessage(e, 'resume (fuel %10.2f)' % (numActualFuelLevel))
              traci.vehicle.resume(e)
              busStates[e] = BusState.running
            except Exception as ex:
                printVehicleStateMessage(e, 'error cannot resume (%s)' % (str(ex)))
            actualFuelLevel = 0
        simTime.append(str(actualFuelLevel))
        simTime.append(str(numBusRiders))
    #print('fuel and pass', ' '.join(simTime))
    print(','.join(simTime), file=energyfile, flush=True)

#       print ('%.0f Vehicle %s Battery %8.2f' % (current_time, '0', float(current_fuel_Level)))
def extendCurrentStop(vehID, newDuration, stopData = None):
    '''Common routine to extend stop duration'''
    try:
        if stopData == None: # --- WHY IS THIS NEEDED? ARE YOU TRYING TO CONTROL ERRORS IN THE CODE? ---
            stopData = traci.vehicle.getStops(vehID, 1)
        traci.vehicle.setBusStop(vehID, stopData[0].stoppingPlaceID, # --- IS "stopData[0].stoppingPlaceID" LOOKING AT THE CURRENT STOPPINGPLACE THE BUS IS AT? ---
                                 # Scf: It is the current or the next one
                                 duration=newDuration)
        newStopData = traci.vehicle.getStops(vehID, 1)
        #printVehicleMessage(vehID, 'new %s' % newStopData)
        if newStopData[0].duration != newDuration:
          printVehicleMessage(vehID, 'setting of duration does not work')
    except Exception as ex:
        printVehicleMessage(vehID, 'error with extendCurrentStop %s' % (str(ex)))
        printVehicleMessage(vehID, 'stopData old %s' % (stopData[0]))

def insertDriverBreak(vehId, stops, duration, reason, newDriverBreakStatus):
  '''Construction area - one routine for all types of break'''
  stopData = traci.vehicle.getStops(vehId, 1)
  #print(stopData)
  if (stopData[0].stopFlags & 8) and stopData[0].stoppingPlaceID in stops: # --- WHY DID YOU USE A STOPFLAG TO CHECK CONDITION? --- # MY UNDERSTANDING: if bus is at a bus stop and bus stop is one of stops in break list
    # Scf: stopFlags are already known, otherwise I need an extra call to traci
    printVehicleMessage(vehId, 'is taking a %d min %s break' %
                        (duration/60, reason))
    extendCurrentStop(vehId, duration, stopData)
    breakStates[vehId] = newDriverBreakStatus

def takeDriverBreak(current_time):
    global DriverStops, currentDriverStop
    stopsForAMbreak = ["busStop_-467228692#3_1_10", "busStop_JagTranRdSB7_1_8",
                       "busStop_GreekRowSB20_1_1", "busStop_357822997#2_0_3",
                       "Y1"
      ]
    stopsForLunchbreak = ["busStop_-467228692#3_1_10", "busStop_JagTranRdSB7_1_8",
                          "busStop_GreekRowSB20_1_1", "busStop_357822997#2_0_3"
      ]
    stopsForPMbreak = ["busStop_-467228692#3_1_10", "busStop_JagTranRdSB7_1_8",
                          "busStop_GreekRowSB20_1_1", "busStop_357822997#2_0_3"
      ]

    for e in activeBuses:
        if vehiclesDriveType[e] != DriveType.hdb_diesel:
            continue
        if vehiclesDriveType[e] == DriveType.hdb_diesel:
            if (10800 < current_time < 14400):
                if (breakStates[e] != DriverBreakStatus.AMbathroomFood):
                    if busStates[e] == BusState.running and numBusRiders == 0 and numActualFuelLevel > float(666667):
                        insertDriverBreak(e, stopsForAMbreak, 600, 'AM Bathroom/Snack', DriverBreakStatus.AMbathroomFood)
        if vehiclesDriveType[e] == DriveType.hdb_diesel:
            if (21600 < current_time < 27000):
                if (breakStates[e] != DriverBreakStatus.Lunch):
                    if busStates[e] == BusState.running and numBusRiders == 0 and numActualFuelLevel > float(666667):
                        insertDriverBreak(e, stopsForLunchbreak, 600, 'Lunch', DriverBreakStatus.Lunch)
        if vehiclesDriveType[e] == DriveType.hdb_diesel:
            if (30600 < current_time < 37800):
                if (breakStates[e] != DriverBreakStatus.PMbathroomFood):
                    if busStates[e] == BusState.running and numBusRiders == 0 and numActualFuelLevel > float(666667):
                        insertDriverBreak(e, stopsForPMbreak, 600, 'PM Bathroom/Snack', DriverBreakStatus.PMbathroomFood)
#         if 30600 < current_time < 37800:
#             if busStates[e] == BusState.running and numBusRiders == 0 and numActualFuelLevel > float(416625):
#                 if currentDriverStop == "busStop_-467228692#3_1_10" or currentDriverStop == "busStop_JagTranRdSB7_1_8" or currentDriverStop == "busStop_GreekRowSB20_1_1" or currentDriverStop == "busStop_GreekRowNB4_1_0" or currentDriverStop == "Y1":
#                     try:
#                         print("Time: %7.2fs, Vehicle %s is taking a 30 min Lunch Break" % (current_time, e))
#                         traci.vehicle.setBusStop(e, currentDriverStop, duration=1800, flags=0)
#                         breakStates[e] = DriverBreakStatus.Lunch
#                     except:
#                         print("Time: %7.2fs, Vehicle %s does not need a Lunch Break" % (current_time, e))

def maintain_headway(current_time):
    #Maintaining headway between Yellow Buses, Blue Buses, & Green Buses; respectively
    #bus_ids = ["0", "1", "2", "3", "4", "5", "6", "7"]
    simulation_time = [str(current_time)]
    if current_time >= 3600:
        maintainHeadway('3', '4', 200) #HDBdelay=200, ABdelay=140
        maintainHeadway('4', '3', 200) #HDBdelay=200, ABdelay=140
        maintainHeadway('1', '2', 300) #HDBdelay=300, ABdelay=240
        maintainHeadway('2', '1', 300) #HDBdelay=300, ABdelay=240
        maintainHeadway('5', '6') #HDBdelay=160, ABdelay=100
        maintainHeadway('6', '5') #HDBdelay=160, ABdelay=100

def maintainHeadway(leaderID, followerID, delay = 160):
    global finishedBuses

    if leaderID in finishedBuses or followerID in finishedBuses:
      return
    try:
        # First check if leader is at a bus stop (for performance)
        leaderIsAtBusStop = traci.vehicle.isAtBusStop(leaderID)
        #printVehicleMessage(leaderID, 'is at bus stop %s' % (leaderIsAtBusStop))
        if leaderIsAtBusStop: # --- I THOUGHT YOU NEEDED TO VERIFY THIS AGAINST A TRUE, SINCE IT RETURNS A BOOLEAN? ---
          # Scf: See style guide for python
          # https://www.python.org/dev/peps/pep-0008/
          # Look for "Don't compare boolean values to True or False using =="
          # this form make scode readable, it is a plain englissh sentence
          # might be we should use underscores
          #   if leader_is_at_bus_stop
          followersStopData = traci.vehicle.getStops(followerID, 2)
          #printVehicleMessage(followerID, 'followers next stop %s' % (followersStopData))
          if len(followersStopData) > 0 or followersStopData[0].duration != delay:
            leaderStopData = traci.vehicle.getStops(leaderID, 1)
            leadersCurrentStop = leaderStopData[0].stoppingPlaceID
            leadersCurrentLane   = leaderStopData[0].lane #stoppingPlaceID for CURRENT
            followersCurrentLane = followersStopData[0].lane #stoppingPlaceID for CURRENT
            followersCurrentStop = followersStopData[0].stoppingPlaceID #stoppingPlaceID for CURRENT

            if len(followersStopData) >= 2 or len(leaderStopData) >= 2:
                followersNextStopLane = followersStopData[1].lane # --- IS THIS HOW YOU LOOK AT THE LANEID AT NEXT STOP AHEAD? ---
        #            followersCurrentStop = followersStopData[0].stoppingPlaceID #stoppingPlaceID for CURRENT
                followersNextStop = followersStopData[1].stoppingPlaceID # --- Looking at next stop for follower vehicle ---

            else:
                followersNextStopLane = None
                followersNextStop = None

            # Scf Yes
            #printVehicleMessage(leaderID,   ' leader   current stop %s' % (leadersCurrentLane))
            #printVehicleMessage(followerID, ' follower current stop %s)' % (followersCurrentLane))

            #Exclude the case the leader of the leader is actually the follower
            if leadersCurrentStop == followersCurrentStop:
                leader_of_leader = traci.vehicle.getLeader(leaderID)
                if leader_of_leader != None:
                    if leader_of_leader[0] == followerID:
                        printVehicleMessage(leaderID, 'is not the leader of %s' % (followerID))
                        return

            if (leadersCurrentStop == followersCurrentStop) or (leadersCurrentStop == followersNextStop):
                if (leadersCurrentLane == followersCurrentLane) or (leadersCurrentLane == followersNextStopLane):
                  printVehicleMessage(followerID, 'waits at %s for %d sec (headway)' % (followersCurrentStop, delay))
                  extendCurrentStop(followerID, delay, followersStopData)
                  #checkStatus = traci.vehicle.getStops(followerID, 1)
                  #printVehicleMessage(followerID, 'new duration %d' % (checkStatus[0].duration))
    except Exception as ex:
      print('Vehicle %s error %s' % (followerID, str(ex)))
      traceback.print_exc(file=eventfile)

def run(seed, gui = False, endTime = 65000):
  global busStates, breakStates
  global csvfile, energyfile, eventfile
  global current_time
  global finishedBuses
  global activeBuses

  # define file names
  csvfile = open('passengers.%d.Hybrid_Medium_out.csv' % seed, 'w')
  energyfile = open("batteryCapacity.%d.Hybrid_Medium_out.csv" % seed, "w")
  eventfile = open("events.%d.Hybrid_Medium_out.txt" % seed, "w")
  chargingOutput = "chargingstations.%d.Hybrid_Medium_out.xml" % seed
  stopOutput = "stop.%d.Hybrid_Medium_out.xml" % seed

  if gui:
    sumoBinary = checkBinary ("sumo-gui")
  else:
    sumoBinary = checkBinary ("sumoD")

  sumoCmd = []
  if args.gdb:
    sumoCmd.extend(['gdb', '-ex', 'run', '--args'])
  sumoCmd.extend([sumoBinary, "--quit-on-end", "--start"])
  sumoCmd.extend(['--seed', str(seed), '-c', 'test.sumocfg'])
  sumoCmd.extend(['--chargingstations-output', chargingOutput])
  sumoCmd.extend(['--stop-output', stopOutput])
  if args.fcd:
    sumoCmd.extend(['--fcd-output', 'fcd.%s.out.xml' % seed, '--person-device.fcd.probability', '0', '--fcd-output.distance'])

  print('Run ' + ' '.join(sumoCmd))

  # reset global mvariables for each run
  activeBuses = []
  for v in vehicles:
    busStates[v] = BusState.running
    breakStates[v] = DriverBreakStatus.running
    activeBuses.append(v)
  finishedBuses = []
  waitingBuses = {}

  traci.start(sumoCmd)
  step = 0

  # main loop, current_time serves as step
  while traci.simulation.getMinExpectedNumber() > 0:
    traci.simulationStep()
    current_time = traci.simulation.getTime()
    if current_time <= 1:
      printVehicleMessage('0', 'start simulation')

    # Execution for Beginning of Simulation
    # do nothing special
    # Execution for collecting Ridership within Bus Vehicles
    # stop if all buses are gone
    if len(activeBuses) == 0:
      break
    # call plugins
    fueling_behavior(current_time)
    maintain_headway(current_time)
    for i in vehiclesDriveType:
        if vehiclesDriveType[i] == DriveType.hdb_diesel:
            takeDriverBreak(current_time)

    if 3600 <= step:
          # This set of code gets the number of riders currently within the bus
        list_of_ridership = [str(current_time)]
        for id in vehicles:
          # take care, if vehicle does not exist
          ridership = 0
          if not id in finishedBuses:
            try:
              ridership = traci.vehicle.getPersonNumber(id)
              vehicleDistance = traci.vehicle.getDistance(id)
              vehicleEnergyCons = traci.vehicle.getElectricityConsumption(id)
            except:
              pass
          list_of_ridership.append(str(ridership))
          list_of_ridership.append(str(vehicleDistance))
          list_of_ridership.append(str(vehicleEnergyCons))
          list_of_ridership.append(str(actualFuelLevel))
        # create a comma-separated list
        print(','.join(list_of_ridership), file=csvfile, flush=True)
    if current_time > endTime:
      break
    step += 1 # not really used any more

  csvfile.close()
  eventfile.close()
  traci.close()

if __name__ == "__main__":
  run(args.seed, args.gui, args.last)

# ===============================PARKING LOT============================================================================================
#       current_fuel_Level_Red = traci.vehicle.getParameter(vehicle[0], "device.battery.actualBatteryCapacity")
#       current_fuel_Level_Blue1 = traci.vehicle.getParameter(vehicle[1], "device.battery.actualBatteryCapacity")
#       current_fuel_Level_Blue2 = traci.vehicle.getParameter(vehicle[2], "device.battery.actualBatteryCapacity")
#       current_fuel_Level_Yellow1 = traci.vehicle.getParameter(vehicle[3], "device.battery.actualBatteryCapacity")
#       current_fuel_Level_Yellow2 = traci.vehicle.getParameter(vehicle[4], "device.battery.actualBatteryCapacity")
#       current_fuel_Level_Green1 = traci.vehicle.getParameter(vehicle[5], "device.battery.actualBatteryCapacity")
#       current_fuel_Level_Green2 = traci.vehicle.getParameter(vehicle[6], "device.battery.actualBatteryCapacity")
#       current_fuel_Level_Orange = traci.vehicle.getParameter(vehicle[7], "device.battery.actualBatteryCapacity")
#       print("At timestep %8.2f: %8.2f, %8.2f, %8.2f, %8.2f, %8.2f, %8.2f, %8.2f, %8.2f" % (current_time, float(current_fuel_Level_Red), float(current_fuel_Level_Blue1),
#                                                                         float(current_fuel_Level_Blue2), float(current_fuel_Level_Yellow1), float(current_fuel_Level_Yellow2),
#                                                                         float(current_fuel_Level_Green1), float(current_fuel_Level_Green2), float(current_fuel_Level_Orange)))

        # Turning Lane ID into Edge ID to use as variable for setting Stop for bus 3
#         detect_EdgeID = str(traci.vehicle.getLaneID("3"))
#         edge_ID = detect_EdgeID[:-2] #detect_EdgeID.replace("_1","")

#For Green Route Buses (ONLY)
  # Detect Vehicle 6 so that Vehicle 5 can slow down
#   =========================================================
#   if current_time >= 3600:
#     secondVehicle = '3'
#     leader = traci.vehicle.getLeader(secondVehicle, 5)
#     atBusStop = traci.vehicle.isAtBusStop(secondVehicle)
#     if (atBusStop != False) and leader != None:
#         print("At timestep %.0f JagTran %s is at Bus Stop" % (current_time, secondVehicle))
#         print('leader', leader)
#         #print('Leader of 5 %s' % leader_id)
#         if leader[0] == "4" and leader[1] <= 10:
#              oldSpeed = traci.vehicle.getSpeed(secondVehicle)
#              traci.vehicle.slowDown(secondVehicle, 0.02, 65)
#              print('%.0f Slowdown vehicle %s with current speed %4.1f' % (current_time, secondVehicle, oldSpeed))
# ==========================================================================

#              traci.vehicle.getNextStops(secondVehicle)
#              traci.vehicle.replaceStop(secondVehicle, 1, "GreekRowSB20", 12.10, 1, 7.15, 460, 0)
#             traci.vehicle.setSpeed(secondVehicle, 0.00)

#         if leader_id >= ("6", 15):
#             traci.vehicle.openGap("5", 360, 1850, 300, -0.5, -0.5, "6")
#             traci.vehicle.getSt

Back to the top