-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrafficEnv.py
179 lines (114 loc) · 5.39 KB
/
TrafficEnv.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import gymnasium as gym
from gymnasium import spaces
import numpy as np
import traci
from utils import emissions
from utils.model import Emission
from collections import Counter
import os
import random
class SpeedLimitEnv(gym.Env):
"""A simple traffic simulation environment for adjusting speed limits to minimize emissions."""
def __init__(self, visuals=False):
super().__init__()
# whether to open sumo gui or not
if visuals:
self.visuals = 'sumo-gui'
else:
self.visuals = 'sumo'
# action space (discrete speed limits between 40 km/h and 100 km/h, in 10 km/h increments)
self.action_space = spaces.Discrete(7) # 7 options: 40, 50, ..., 100
# self.action_space = spaces.Box(low=40, high=100,shape=(1,),dtype="float32")
# observation space (total small vehicles, total large vehicles, average speed, occupancy (length of cars/lenght of roads), total emission)
self.observation_space = spaces.Box(low=np.array([-np.inf, -np.inf, -np.inf, -np.inf, -np.inf]),
high=np.array([np.inf, np.inf, np.inf, np.inf, np.inf]), dtype=np.float32)
# Initialize state and other variables
self.state = np.array([0,0,0,0,0])
self.tot_emissions = 0
self.occupancy = 0
self.mean_speed = 0
self.total_cars = 0
self.total_trucks = 0
# SUMO simulation set up
self.simulation_dir = 'F:/SUMO/OptimalEmission-SUMO-ReinforcementLearning/scenarios'
self.dirs = [x[0] for x in os.walk(self.simulation_dir)]
self.select_network()
def reset(self, seed=None, options=None):
"""Reset the state of the environment to an initial state."""
self.close()
self.select_network()
# lanes = traci.lane.getIDList()
# for lane in lanes:
# traci.lane.setMaxSpeed(lane, 40)
self.counter = 0
traci.simulationStep()
self.state = np.array(self.get_state(), dtype='float32')
return self.state, {}
def close(self):
traci.close(False)
def step(self, action=None):
"""Execute one time step within the environment."""
self.set_speed_limit(action)
traci.simulationStep()
self.state = np.array(self.get_state(), dtype='float32')
self.reward = - self.state[3]
truncated=False
self.counter += 1
if self.counter > 60000:
truncated = True
# self.close()
done = False
info = {}
return self.state, self.reward, done, truncated, info
def get_state(self):
"""Gets the current state space = total small vehicles, total large vehicles, average speed, occupancy, total emission."""
veh_types =[]
veh_speeds= []
veh_edges = []
total_emissions = Emission()
self.mean_speed = 0
occupancy_sum = 0
vehicles = emissions.get_all_vehicles()
for vehicle in vehicles:
veh_types.append(vehicle.type)
veh_speeds.append(vehicle.speed)
total_emissions += vehicle.emissions
veh_edges.append(vehicle.edge)
for edge in veh_edges:
occupancy_sum += traci.edge.getLastStepOccupancy(edge) #%
travel_time_sum += traci.edge.getTraveltime(edge)
self.occupancy = (occupancy_sum/(len(veh_edges)+0.0001))*100
# print(veh_types)
# self.total_cars = Counter(veh_types)['motorcycle_motorcycle'] + Counter(veh_types)['veh_passenger']
# self.total_trucks = Counter(veh_types)['bus_bus'] + Counter(veh_types)['truck_truck']
self.total_cars = sum(1 for row in veh_types if row[0][0] == 'v' or row[0][0] == 'm')
self.total_trucks = sum(1 for row in veh_types if row[0][0] == 't' or row[0][0] == 'b')
print(self.total_cars+self.total_trucks)
self.mean_speed = sum(veh_speeds) / (len(veh_speeds)+0.00001)
print(self.mean_speed)
total = total_emissions.co2 + total_emissions.co + total_emissions.nox + total_emissions.hc + total_emissions.pmx
self.tot_emissions = total/1000000
# print([self.total_cars, self.total_trucks, self.mean_speed, self.tot_emissions])
return [self.total_cars, self.total_trucks, self.mean_speed, self.tot_emissions, self.occupancy]
def set_speed_limit(self, action):
"""Sets the current speed limit on the network"""
speeds = [40, 50, 60, 70, 80, 90, 100]
print(f'current speed limit: {speeds[action]}')
lanes = traci.edge.getIDList()
for lane in lanes:
traci.edge.setMaxSpeed(lane, speeds[action]/3.6)
# VID = traci.vehicle.getIDList()
# for v in VID:
# traci.vehicle.setMaxSpeed(v, speeds[action]/3.6)
def select_network(self):
# SUMO simulation set up
# scenario = random.choice(self.dirs)
scenario = self.dirs[5]
print(f'selected network: {scenario}')
for f in os.listdir(scenario):
if f.endswith('.sumocfg'):
self._SUMOCFG = os.path.join(scenario, f)
self.sumo_binary = os.path.join(os.environ['SUMO_HOME'], 'bin', self.visuals)
self.sumo_cmd = [self.sumo_binary, "-c", self._SUMOCFG]
# Star simulation
traci.start(self.sumo_cmd)