Repository navigation
Expand file tree
/
Copy pathbase_env.py
More file actions
324 lines (272 loc) · 13.1 KB
/
Copy pathbase_env.py
File metadata and controls
324 lines (272 loc) · 13.1 KB
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
import os
import random
import sys
import uuid
from abc import ABC, abstractmethod
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
import tempfile
import logging
from typing import Optional, Union, List, Tuple
import gym
import sumolib
import traci
from gym.core import ObsType, ActType
from traci import TraCIException
from environment.util.trip_info import TripInfoRecorder, TripInfo
from util.base_config import BaseConfig
if "SUMO_HOME" in os.environ:
_TOOLS_DIR = os.path.join(os.environ["SUMO_HOME"], "tools")
sys.path.append(_TOOLS_DIR)
else:
sys.exit("Variable 'SUMO_HOME' is not declared!")
USE_LIBSUMO = "LIBSUMO_AS_TRACI" in os.environ
_LOGGER = logging.getLogger(__name__)
class BaseGymEnv(gym.Env, ABC):
"""This base environment handles all the low-level SUMO logic (e.g. connection handling, env resetting, etc.)"""
VERBOSE_TRIP_INFO_RECORDER: bool = False
@dataclass
class Config(BaseConfig):
use_gui: bool
net_file_path: Path
route_file_path: Path
max_depart_delay: int = 100000 # Seconds after to-be-inserted vehicles will be discarded from insertion queue
waiting_time_memory: int = 1000
time_to_teleport: int = -1
simulation_begin_time: int = 0 # Time which the simulation begins from, in seconds
seed: Optional[int] = None
suppress_sumo_warnings: bool = False
additional_sumo_args: Optional[List[str]] = None
verbose_traci: bool = False
start_simulator_on_init: bool = True
do_process_trip_info: bool = True # Process TripInfo objects generated by SUMO. See base_env.trip_info_objects
def __post_init__(self):
assert self.simulation_begin_time >= 0
@staticmethod
def _get_file_stem(path: Path) -> str:
stem = path.stem
loc = stem.find(".")
if loc >= 1:
stem = stem[:loc]
return stem
@property
def net_file_stem(self) -> str:
"""Returns the stem of 'net_file_path'. Example: 'test1' for '/home/user/test1.net.xml'."""
return self._get_file_stem(path=self.net_file_path)
@property
def route_file_stem(self) -> str:
"""Returns the stem of 'route_file_path'. Example: 'test1' for '/home/user/test1.rou.xml'."""
return self._get_file_stem(path=self.route_file_path)
_STATE_DIR = Path(tempfile.gettempdir()) / "TempSumoStates"
def __init__(self, config: Config):
assert config.net_file_path.is_file(), f"Net file '{config.net_file_path}' does not exist or is no file!"
assert config.route_file_path.is_file(), f"Route file '{config.route_file_path}' does not exist or is no file!"
self.config = config
self._sumo_connection: Optional[traci.Connection] = None
self.__trip_info_recorder: Optional[TripInfoRecorder] = None
# Determine a unique connection label
while True:
self.__sumo_connection_label = str(random.randint(0, 2**16))
try:
traci.getConnection(self.__sumo_connection_label)
except TraCIException: # This exception is thrown if the given label not yet exists - which is what we want
break
if not self._STATE_DIR.exists():
self._STATE_DIR.mkdir(parents=False, exist_ok=True)
if config.start_simulator_on_init is True:
self.__start_simulator()
def __get_sumo_command(self) -> List[str]:
_sumo_binary_path_str = sumolib.checkBinary("sumo-gui" if self.config.use_gui else "sumo")
command = [_sumo_binary_path_str,
"-n", str(self.config.net_file_path),
"-r", str(self.config.route_file_path),
"--max-depart-delay", str(self.config.max_depart_delay),
"--waiting-time-memory", str(self.config.waiting_time_memory),
"--time-to-teleport", str(self.config.time_to_teleport),
"--begin", str(self.config.simulation_begin_time),]
command.extend(["--random"] if self.config.seed is None else ["--seed", str(self.config.seed)])
if self.config.suppress_sumo_warnings is True:
command += ["--no-warnings"]
if self.config.additional_sumo_args is not None:
command.extend(self.config.additional_sumo_args)
if self.config.use_gui:
command += ["--start", "--quit-on-end"]
if self.config.do_process_trip_info is True:
_port = self.__trip_info_recorder.port
command += ["--tripinfo-output", f"localhost:{_port}", "--tripinfo-output.write-unfinished",
"--device.emissions.probability", "1"]
return command
@property
def is_started(self):
"""Returns if there is currently an open connection to SUMO"""
try:
return self._sumo_connection is not None
except AttributeError:
return False # There is no connection object yet --> Nothing started, so far :-)
@contextmanager
def _open_temporary_sumo_connection_for_config(self) -> traci.Connection:
"""Intended to be used as WITH statement. Opens a temporary SUMO instance to retrieve map config information."""
_cmd = [sumolib.checkBinary('sumo'), '-n', str(self.config.net_file_path)]
if USE_LIBSUMO is True:
traci.start(_cmd, verbose=self.config.verbose_traci)
conn = traci
elif USE_LIBSUMO is False:
_label = f"{self.__sumo_connection_label}//{str(uuid.uuid4())[:8]}"
traci.start(_cmd, label=_label, verbose=self.config.verbose_traci)
conn = traci.getConnection(_label)
yield conn
conn.close()
@abstractmethod
def reset(self, *, seed: Optional[int] = None, return_info: bool = False, options: Optional[dict] = None, **kwargs)\
-> Union[ObsType, tuple[ObsType, dict]]:
gym.Env.reset(self, seed=seed, return_info=return_info, **kwargs)
if seed is not None:
_old_seed = self.config.seed
self.config.seed = seed
if seed != _old_seed:
_LOGGER.debug("Reset(): Seed changed, restarting simulator..")
self.close()
self.__start_simulator()
return "new simulation started"
if self.is_started is False:
self.__start_simulator()
return "new simulation started"
else:
self._sumo_connection.simulation.loadState(str(self.__simulator_state_path))
if self.config.do_process_trip_info is True:
self.__trip_info_recorder.clear()
return "simulation state loaded"
def __start_simulator(self):
assert self.is_started is False
_LOGGER.debug(f"Opening simulator with label '{self.__sumo_connection_label}'")
if self.config.do_process_trip_info is True:
self.__trip_info_recorder = TripInfoRecorder(verbose=self.VERBOSE_TRIP_INFO_RECORDER)
if USE_LIBSUMO is True:
traci.start(self.__get_sumo_command(), verbose=self.config.verbose_traci)
self._sumo_connection = traci
elif USE_LIBSUMO is False:
traci.start(self.__get_sumo_command(),
label=self.__sumo_connection_label, verbose=self.config.verbose_traci)
self._sumo_connection: traci.Connection = traci.getConnection(self.__sumo_connection_label)
if self.config.use_gui is True:
self._sumo_connection.gui.setSchema(traci.gui.DEFAULT_VIEW, "real world")
_filename = f"{self.config.net_file_stem}--" \
f"{datetime.now().strftime('%Y-%m-%d__%H-%M')}--" \
f"{str(uuid.uuid4())[:8]}.xml"
self.__simulator_state_path = self._STATE_DIR / _filename
self._sumo_connection.simulation.saveState(str(self.__simulator_state_path))
def close(self):
if not self.is_started:
return
if USE_LIBSUMO is False:
traci.switch(self.__sumo_connection_label)
traci.close()
self._sumo_connection = None
if self.__trip_info_recorder is not None:
self.__trip_info_recorder.close()
@property
def trip_info_objects(self) -> List[TripInfo]:
"""
Returns all trip info objects that were recorded from SUMO during this episode. Each trip info
stands for one simulated vehicle which finished its trip.
"""
assert self.is_started is True
assert self.config.do_process_trip_info is True
self.__trip_info_recorder.wait_for_pending_messages() # Blocks main thread until all message objects are parsed
return self.__trip_info_recorder.recorded_trip_info_objects
def __del__(self):
self.close()
@abstractmethod
def render(self, mode="human"):
pass
@abstractmethod
def step(self, action: ActType) -> Tuple[ObsType, float, bool, dict]:
pass
class _DummyGymEnv(BaseGymEnv):
def reset(self, *, seed: Optional[int] = None, return_info: bool = False, options: Optional[dict] = None,
**kwargs) -> Union[ObsType, tuple[ObsType, dict]]:
return super(_DummyGymEnv, self).reset(seed=seed, return_info=return_info, options=options)
def render(self, mode="human"):
pass
def step(self, action: ActType) -> Tuple[ObsType, float, bool, dict]:
pass
def test_deferred_start():
print("\n\n")
script_path = Path(__file__).parent
config = BaseGymEnv.Config(use_gui=True, net_file_path=script_path/"unit_test_data/single-intersection.net.xml",
route_file_path=script_path/"unit_test_data/single-intersection.rou.xml",
verbose_traci=False, start_simulator_on_init=False, do_process_trip_info=False)
env = _DummyGymEnv(config=config)
assert env.is_started is False
with env._open_temporary_sumo_connection_for_config() as connection:
assert connection.trafficlight.getIDCount() == 1
env.reset() # Starts the simulator
assert env._sumo_connection.simulation.getTime() == 0
assert env._sumo_connection.simulation.getTime() == 0
for _ in range(1, 100):
env._sumo_connection.simulationStep()
assert env._sumo_connection.simulation.getTime() == _
env.close()
assert env.is_started is False
def test_immediate_start():
print("\n\n")
script_path = Path(__file__).parent
config = BaseGymEnv.Config(use_gui=True, net_file_path=script_path/"unit_test_data/single-intersection.net.xml",
route_file_path=script_path/"unit_test_data/single-intersection.rou.xml",
verbose_traci=False, start_simulator_on_init=True, do_process_trip_info=False)
env = _DummyGymEnv(config=config)
assert env.is_started is True
assert env._sumo_connection.simulation.getTime() == 0
for _ in range(1, 100):
env._sumo_connection.simulationStep()
assert env._sumo_connection.simulation.getTime() == _
env.reset()
assert env._sumo_connection.simulation.getTime() == 0
env.close()
assert env.is_started is False
def test_trip_info():
script_path = Path(__file__).parent
config = BaseGymEnv.Config(use_gui=True, net_file_path=script_path/"unit_test_data/single-intersection.net.xml",
route_file_path=script_path/"unit_test_data/single-intersection.rou.xml",
verbose_traci=False, start_simulator_on_init=True, do_process_trip_info=True)
# BaseGymEnv.VERBOSE_TRIP_INFO_RECORDER = True
env = _DummyGymEnv(config=config)
for _ in range(5):
assert len(env.trip_info_objects) == 0
for _ in range(1, 500):
env._sumo_connection.simulationStep()
assert len(env.trip_info_objects) > 0
env.reset()
env.close()
def test_multi_sim_trip_info():
script_path = Path(__file__).parent
config = BaseGymEnv.Config(use_gui=True, net_file_path=script_path/"unit_test_data/single-intersection.net.xml",
route_file_path=script_path/"unit_test_data/single-intersection.rou.xml",
verbose_traci=False, start_simulator_on_init=True, do_process_trip_info=True)
# BaseGymEnv.VERBOSE_TRIP_INFO_RECORDER = True
env1 = _DummyGymEnv(config=config)
env2 = _DummyGymEnv(config=config)
# Step env1
assert len(env1.trip_info_objects) == 0
for _ in range(1, 100):
env1._sumo_connection.simulationStep()
_n_env1 = len(env1.trip_info_objects)
assert _n_env1 > 0
# Step env2
assert len(env2.trip_info_objects) == 0
for _ in range(1, 100):
env2._sumo_connection.simulationStep()
_n_env2 = len(env2.trip_info_objects)
assert _n_env2 > 0
assert len(env1.trip_info_objects) == _n_env1
# Reset env1 & step
env1.reset()
assert len(env1.trip_info_objects) == 0
for _ in range(1, 100):
env1._sumo_connection.simulationStep()
assert len(env1.trip_info_objects) > 0
assert len(env2.trip_info_objects) == _n_env2
env1.close()
env2.close()