Advertisement
Slayerfeed

Sumo_python

Aug 6th, 2022 (edited)
1,001
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.47 KB | None | 0 0
  1. import traci
  2. import time
  3. import traci.constants as tc
  4. import pytz
  5. import datetime
  6. from random import randrange
  7. import pandas as pd
  8.  
  9.  
  10. def getdatetime():
  11.         utc_now = pytz.utc.localize(datetime.datetime.utcnow())
  12.         currentDT = utc_now.astimezone(pytz.timezone("Asia/Singapore"))
  13.         DATIME = currentDT.strftime("%Y-%m-%d %H:%M:%S")
  14.         return DATIME
  15.  
  16. def flatten_list(_2d_list):
  17.     flat_list = []
  18.     for element in _2d_list:
  19.         if type(element) is list:
  20.             for item in element:
  21.                 flat_list.append(item)
  22.         else:
  23.             flat_list.append(element)
  24.     return flat_list
  25.  
  26.  
  27. sumoCmd = ["sumo-gui", "-c", "osm.sumocfg"]
  28. traci.start(sumoCmd)
  29.  
  30. packVehicleData = []
  31. packTLSData = []
  32. packBigData = []
  33.  
  34. while traci.simulation.getMinExpectedNumber() > 0:
  35.        
  36.         traci.simulationStep();
  37.  
  38.         vehicles=traci.vehicle.getIDList();
  39.         trafficlights=traci.trafficlight.getIDList();
  40.  
  41.         for i in range(0,len(vehicles)):
  42.  
  43.                 #Function descriptions
  44.                 #https://sumo.dlr.de/docs/TraCI/Vehicle_Value_Retrieval.html
  45.                 #https://sumo.dlr.de/pydoc/traci._vehicle.html#VehicleDomain-getSpeed
  46.                 vehid = vehicles[i]
  47.                 x, y = traci.vehicle.getPosition(vehicles[i])
  48.                 coord = [x, y]
  49.                 lon, lat = traci.simulation.convertGeo(x, y)
  50.                 gpscoord = [lon, lat]
  51.                 spd = round(traci.vehicle.getSpeed(vehicles[i])*3.6,2)
  52.                 edge = traci.vehicle.getRoadID(vehicles[i])
  53.                 lane = traci.vehicle.getLaneID(vehicles[i])
  54.                 displacement = round(traci.vehicle.getDistance(vehicles[i]),2)
  55.                 turnAngle = round(traci.vehicle.getAngle(vehicles[i]),2)
  56.                 nextTLS = traci.vehicle.getNextTLS(vehicles[i])
  57.  
  58.                 #Packing of all the data for export to CSV/XLSX
  59.                 vehList = [getdatetime(), vehid, coord, gpscoord, spd, edge, lane, displacement, turnAngle, nextTLS]
  60.                
  61.                
  62.                 print("Vehicle: ", vehicles[i], " at datetime: ", getdatetime())
  63.                 print(vehicles[i], " >>> Position: ", coord, " | GPS Position: ", gpscoord, " |", \
  64.                                        " Speed: ", round(traci.vehicle.getSpeed(vehicles[i])*3.6,2), "km/h |", \
  65.                                       #Returns the id of the edge the named vehicle was at within the last step.
  66.                                        " EdgeID of veh: ", traci.vehicle.getRoadID(vehicles[i]), " |", \
  67.                                       #Returns the id of the lane the named vehicle was at within the last step.
  68.                                        " LaneID of veh: ", traci.vehicle.getLaneID(vehicles[i]), " |", \
  69.                                       #Returns the distance to the starting point like an odometer.
  70.                                        " Distance: ", round(traci.vehicle.getDistance(vehicles[i]),2), "m |", \
  71.                                       #Returns the angle in degrees of the named vehicle within the last step.
  72.                                        " Vehicle orientation: ", round(traci.vehicle.getAngle(vehicles[i]),2), "deg |", \
  73.                                       #Return list of upcoming traffic lights [(tlsID, tlsIndex, distance, state), ...]
  74.                                        " Upcoming traffic lights: ", traci.vehicle.getNextTLS(vehicles[i]), \
  75.                        )
  76.  
  77.                 idd = traci.vehicle.getLaneID(vehicles[i])
  78.  
  79.                 tlsList = []
  80.        
  81.                 for k in range(0,len(trafficlights)):
  82.  
  83.                         #Function descriptions
  84.                         #https://sumo.dlr.de/docs/TraCI/Traffic_Lights_Value_Retrieval.html#structure_of_compound_object_controlled_links
  85.                         #https://sumo.dlr.de/pydoc/traci._trafficlight.html#TrafficLightDomain-setRedYellowGreenState
  86.                        
  87.                         if idd in traci.trafficlight.getControlledLanes(trafficlights[k]):
  88.  
  89.                                 tflight = trafficlights[k]
  90.                                 tl_state = traci.trafficlight.getRedYellowGreenState(trafficlights[k])
  91.                                 tl_phase_duration = traci.trafficlight.getPhaseDuration(trafficlights[k])
  92.                                 tl_lanes_controlled = traci.trafficlight.getControlledLanes(trafficlights[k])
  93.                                 tl_program = traci.trafficlight.getCompleteRedYellowGreenDefinition(trafficlights[k])
  94.                                 tl_next_switch = traci.trafficlight.getNextSwitch(trafficlights[k])
  95.  
  96.                                 #Packing of all the data for export to CSV/XLSX
  97.                                 tlsList = [tflight, tl_state, tl_phase_duration, tl_lanes_controlled, tl_program, tl_next_switch]
  98.                                
  99.                                 print(trafficlights[k], " --->", \
  100.                                       #Returns the named tl's state as a tuple of light definitions from rRgGyYoO, for red,
  101.                                       #green, yellow, off, where lower case letters mean that the stream has to decelerate
  102.                                         " TL state: ", traci.trafficlight.getRedYellowGreenState(trafficlights[k]), " |" \
  103.                                       #Returns the default total duration of the currently active phase in seconds; To obtain the
  104.                                       #remaining duration use (getNextSwitch() - simulation.getTime()); to obtain the spent duration
  105.                                       #subtract the remaining from the total duration
  106.                                         " TLS phase duration: ", traci.trafficlight.getPhaseDuration(trafficlights[k]), " |" \
  107.                                       #Returns the list of lanes which are controlled by the named traffic light. Returns at least
  108.                                       #one entry for every element of the phase state (signal index)                                
  109.                                         " Lanes controlled: ", traci.trafficlight.getControlledLanes(trafficlights[k]), " |", \
  110.                                       #Returns the complete traffic light program, structure described under data types                                      
  111.                                         " TLS Program: ", traci.trafficlight.getCompleteRedYellowGreenDefinition(trafficlights[k]), " |"
  112.                                       #Returns the assumed time (in seconds) at which the tls changes the phase. Please note that
  113.                                       #the time to switch is not relative to current simulation step (the result returned by the query
  114.                                       #will be absolute time, counting from simulation start);
  115.                                       #to obtain relative time, one needs to subtract current simulation time from the
  116.                                       #result returned by this query. Please also note that the time may vary in the case of
  117.                                       #actuated/adaptive traffic lights
  118.                                         " Next TLS switch: ", traci.trafficlight.getNextSwitch(trafficlights[k]))
  119.  
  120.                 #Pack Simulated Data
  121.                 packBigDataLine = flatten_list([vehList, tlsList])
  122.                 packBigData.append(packBigDataLine)
  123.  
  124.  
  125.                 ##----------MACHINE LEARNING CODES/FUNCTIONS HERE----------##
  126.  
  127.  
  128.                 ##---------------------------------------------------------------##
  129.  
  130.  
  131.                 ##----------CONTROL Vehicles and Traffic Lights----------##
  132.  
  133.                 #***SET FUNCTION FOR VEHICLES***
  134.                 #REF: https://sumo.dlr.de/docs/TraCI/Change_Vehicle_State.html
  135.                
  136.  
  137.                 #***SET FUNCTION FOR TRAFFIC LIGHTS***
  138.                 #REF: https://sumo.dlr.de/docs/TraCI/Change_Traffic_Lights_State.html
  139.            
  140.  
  141.                 ##------------------------------------------------------##
  142.  
  143.  
  144. traci.close()
  145.  
  146. #Generate Excel file
  147. columnnames = ['dateandtime', 'vehid', 'coord', 'gpscoord', 'spd', 'edge', 'lane', 'displacement', 'turnAngle', 'nextTLS', \
  148.                        'tflight', 'tl_state', 'tl_phase_duration', 'tl_lanes_controlled', 'tl_program', 'tl_next_switch']
  149. dataset = pd.DataFrame(packBigData, index=None, columns=columnnames)
  150. dataset.to_excel("output.xlsx", index=False)
  151. time.sleep(5)
  152.  
  153.  
  154.  
  155. # ref
  156. # https://www.youtube.com/watch?v=zQH1n0Fvxes
  157.  
  158.  
  159.  
  160.  
  161.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement