-
Notifications
You must be signed in to change notification settings - Fork 71
/
multi_env.py
1596 lines (1415 loc) · 61.3 KB
/
multi_env.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
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
multi_env.py: Multi-actor environment interface for CARLA-Gym
Should support two modes of operation. See CARLA-Gym developer guide for
more information
__author__: @Praveen-Palanisamy
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import atexit
import shutil
from datetime import datetime
import logging
import json
import os
import random
import signal
import subprocess
import sys
import time
import traceback
import socket
import math
import numpy as np # linalg.norm is used
import GPUtil
from gym.spaces import Box, Discrete, Tuple, Dict
import pygame
import carla
from macad_gym.core.controllers.traffic import apply_traffic
from macad_gym.multi_actor_env import MultiActorEnv
from macad_gym import LOG_DIR
from macad_gym.core.sensors.utils import preprocess_image
from macad_gym.core.maps.nodeid_coord_map import MAP_TO_COORDS_MAPPING
# from macad_gym.core.sensors.utils import get_transform_from_nearest_way_point
from macad_gym.carla.reward import Reward
from macad_gym.core.sensors.hud import HUD
from macad_gym.viz.render import Render
from macad_gym.carla.scenarios import Scenarios
# The following imports require carla to be imported already.
from macad_gym.core.sensors.camera_manager import CameraManager, CAMERA_TYPES
from macad_gym.core.sensors.derived_sensors import LaneInvasionSensor
from macad_gym.core.sensors.derived_sensors import CollisionSensor
from macad_gym.core.controllers.keyboard_control import KeyboardControl
from macad_gym.carla.PythonAPI.agents.navigation.global_route_planner_dao import ( # noqa: E501
GlobalRoutePlannerDAO,
)
# The following imports depend on these paths being in sys path
# TODO: Fix this. This probably won't work after packaging/distribution
sys.path.append("src/macad_gym/carla/PythonAPI")
from macad_gym.core.maps.nav_utils import PathTracker # noqa: E402
from macad_gym.carla.PythonAPI.agents.navigation.global_route_planner import ( # noqa: E402, E501
GlobalRoutePlanner,
)
from macad_gym.carla.PythonAPI.agents.navigation.local_planner import ( # noqa:E402, E501
RoadOption,
)
logger = logging.getLogger(__name__)
# Set this where you want to save image outputs (or empty string to disable)
CARLA_OUT_PATH = os.environ.get("CARLA_OUT", os.path.expanduser("~/carla_out"))
if CARLA_OUT_PATH and not os.path.exists(CARLA_OUT_PATH):
os.makedirs(CARLA_OUT_PATH)
# Set this to the path of your Carla binary
SERVER_BINARY = os.environ.get(
"CARLA_SERVER", os.path.expanduser("~/software/CARLA_0.9.13/CarlaUE4.sh")
)
# Check if is using on Windows
IS_WINDOWS_PLATFORM = "win" in sys.platform
assert os.path.exists(SERVER_BINARY), (
"Make sure CARLA_SERVER environment"
" variable is set & is pointing to the"
" CARLA server startup script (Carla"
"UE4.sh). Refer to the README file/docs."
)
# TODO: Clean env & actor configs to have appropriate keys based on the nature
# of env
DEFAULT_MULTIENV_CONFIG = {
"scenarios": "DEFAULT_SCENARIO_TOWN1",
"env": {
# Since Carla 0.9.6, you have to use `client.load_world(server_map)`
# instead of passing the map name as an argument
"server_map": "/Game/Carla/Maps/Town01",
"render": True,
"render_x_res": 800,
"render_y_res": 600,
"x_res": 84,
"y_res": 84,
"framestack": 1,
"discrete_actions": True,
"squash_action_logits": False,
"verbose": False,
"use_depth_camera": False,
"send_measurements": False,
"enable_planner": True,
"sync_server": True,
"fixed_delta_seconds": 0.05,
},
"actors": {
"vehicle1": {
"enable_planner": True,
"render": True, # Whether to render to screen or send to VFB
"framestack": 1, # note: only [1, 2] currently supported
"convert_images_to_video": False,
"early_terminate_on_collision": True,
"verbose": False,
"reward_function": "corl2017",
"x_res": 84,
"y_res": 84,
"use_depth_camera": False,
"squash_action_logits": False,
"manual_control": False,
"auto_control": False,
"camera_type": "rgb",
"camera_position": 0,
"collision_sensor": "on", # off
"lane_sensor": "on", # off
"server_process": False,
"send_measurements": False,
"log_images": False,
"log_measurements": False,
}
},
}
# Carla planner commands
COMMANDS_ENUM = {
0.0: "REACH_GOAL",
5.0: "GO_STRAIGHT",
4.0: "TURN_RIGHT",
3.0: "TURN_LEFT",
2.0: "LANE_FOLLOW",
}
# Mapping from string repr to one-hot encoding index to feed to the model
COMMAND_ORDINAL = {
"REACH_GOAL": 0,
"GO_STRAIGHT": 1,
"TURN_RIGHT": 2,
"TURN_LEFT": 3,
"LANE_FOLLOW": 4,
}
ROAD_OPTION_TO_COMMANDS_MAPPING = {
RoadOption.VOID: "REACH_GOAL",
RoadOption.STRAIGHT: "GO_STRAIGHT",
RoadOption.RIGHT: "TURN_RIGHT",
RoadOption.LEFT: "TURN_LEFT",
RoadOption.LANEFOLLOW: "LANE_FOLLOW",
}
# Threshold to determine that the goal has been reached based on distance
DISTANCE_TO_GOAL_THRESHOLD = 0.5
# Threshold to determine that the goal has been reached based on orientation
ORIENTATION_TO_GOAL_THRESHOLD = math.pi / 4.0
# Number of retries if the server doesn't respond
RETRIES_ON_ERROR = 2
# Dummy Z coordinate to use when we only care about (x, y)
GROUND_Z = 22
DISCRETE_ACTIONS = {
# coast
0: [0.0, 0.0],
# turn left
1: [0.0, -0.5],
# turn right
2: [0.0, 0.5],
# forward
3: [1.0, 0.0],
# brake
4: [-0.5, 0.0],
# forward left
5: [0.5, -0.05],
# forward right
6: [0.5, 0.05],
# brake left
7: [-0.5, -0.5],
# brake right
8: [-0.5, 0.5],
}
WEATHERS = {
0: carla.WeatherParameters.ClearNoon,
1: carla.WeatherParameters.CloudyNoon,
2: carla.WeatherParameters.WetNoon,
3: carla.WeatherParameters.WetCloudyNoon,
4: carla.WeatherParameters.MidRainyNoon,
5: carla.WeatherParameters.HardRainNoon,
6: carla.WeatherParameters.SoftRainNoon,
7: carla.WeatherParameters.ClearSunset,
8: carla.WeatherParameters.CloudySunset,
9: carla.WeatherParameters.WetSunset,
10: carla.WeatherParameters.WetCloudySunset,
11: carla.WeatherParameters.MidRainSunset,
12: carla.WeatherParameters.HardRainSunset,
13: carla.WeatherParameters.SoftRainSunset,
}
live_carla_processes = set()
def cleanup():
print("Killing live carla processes", live_carla_processes)
for pgid in live_carla_processes:
if IS_WINDOWS_PLATFORM:
# for Windows
subprocess.call(["taskkill", "/F", "/T", "/PID", str(pgid)])
else:
# for Linux
os.killpg(pgid, signal.SIGKILL)
live_carla_processes.clear()
def termination_cleanup(*_):
cleanup()
sys.exit(0)
signal.signal(signal.SIGTERM, termination_cleanup)
signal.signal(signal.SIGINT, termination_cleanup)
atexit.register(cleanup)
MultiAgentEnvBases = [MultiActorEnv]
try:
from ray.rllib.env import MultiAgentEnv
MultiAgentEnvBases.append(MultiAgentEnv)
except ImportError:
logger.warning("\n Disabling RLlib support.", exc_info=True)
class MultiCarlaEnv(*MultiAgentEnvBases):
def __init__(self, configs=None):
"""MACAD-Gym environment implementation.
Provides a generic MACAD-Gym environment implementation that can be
customized further to create new or variations of existing
multi-agent learning environments. The environment settings, scenarios
and the actors in the environment can all be configured using
the `configs` dict.
Args:
configs (dict): Configuration for environment specified under the
`env` key and configurations for each actor specified as dict
under `actor`.
Example:
>>> configs = {"env":{
"server_map":"/Game/Carla/Maps/Town05",
"discrete_actions":True,...},
"actor":{
"actor_id1":{"enable_planner":True,...},
"actor_id2":{"enable_planner":False,...}
}}
"""
if configs is None:
configs = DEFAULT_MULTIENV_CONFIG
# Functionalities classes
self._reward_policy = Reward()
configs["scenarios"] = Scenarios.resolve_scenarios_parameter(
configs["scenarios"]
)
self._scenario_config = configs["scenarios"]
self._env_config = configs["env"]
self._actor_configs = configs["actors"]
# At most one actor can be manual controlled
manual_control_count = 0
for _, actor_config in self._actor_configs.items():
if actor_config["manual_control"]:
if "vehicle" not in actor_config["type"]:
raise ValueError("Only vehicles can be manual controlled.")
manual_control_count += 1
assert manual_control_count <= 1, (
"At most one actor can be manually controlled. "
f"Found {manual_control_count} actors with manual_control=True"
)
# Camera position is problematic for certain vehicles and even in
# autopilot they are prone to error
self.exclude_hard_vehicles = False
# list of str: Supported values for `type` filed in `actor_configs`
# for actors than can be actively controlled
self._supported_active_actor_types = [
"vehicle_4W",
"vehicle_2W",
"pedestrian",
"traffic_light",
]
# list of str: Supported values for `type` field in `actor_configs`
# for actors that are passive. Example: A camera mounted on a pole
self._supported_passive_actor_types = ["camera"]
# Set attributes as in gym's specs
self.reward_range = (-float("inf"), float("inf"))
self.metadata = {"render.modes": "human"}
# Belongs to env_config.
self._server_map = self._env_config["server_map"]
self._map = self._server_map.split("/")[-1]
self._render = self._env_config["render"]
self._framestack = self._env_config["framestack"]
self._discrete_actions = self._env_config["discrete_actions"]
self._squash_action_logits = self._env_config["squash_action_logits"]
self._verbose = self._env_config["verbose"]
self._render_x_res = self._env_config["render_x_res"]
self._render_y_res = self._env_config["render_y_res"]
self._x_res = self._env_config["x_res"]
self._y_res = self._env_config["y_res"]
self._use_depth_camera = self._env_config["use_depth_camera"]
self._sync_server = self._env_config["sync_server"]
self._fixed_delta_seconds = self._env_config["fixed_delta_seconds"]
# Initialize to be compatible with cam_manager to set HUD.
pygame.font.init() # for HUD
self._hud = HUD(self._render_x_res, self._render_y_res)
# For manual_control
self._control_clock = None
self._manual_controller = None
self._manual_control_camera_manager = None
# Render related
Render.resize_screen(self._render_x_res, self._render_y_res)
self._camera_poses, window_dim = Render.get_surface_poses(
[self._x_res, self._y_res], self._actor_configs
)
if manual_control_count == 0:
Render.resize_screen(window_dim[0], window_dim[1])
else:
self._manual_control_render_pose = (0, window_dim[1])
Render.resize_screen(
max(self._render_x_res, window_dim[0]),
self._render_y_res + window_dim[1],
)
# Actions space
if self._discrete_actions:
self.action_space = Dict(
{
actor_id: Discrete(len(DISCRETE_ACTIONS))
for actor_id in self._actor_configs.keys()
}
)
else:
self.action_space = Dict(
{
actor_id: Box(-1.0, 1.0, shape=(2,))
for actor_id in self._actor_configs.keys()
}
)
# Output space of images after preprocessing
if self._use_depth_camera:
self._image_space = Box(
0.0, 255.0, shape=(self._y_res, self._x_res, 1 * self._framestack)
)
else:
self._image_space = Box(
-1.0, 1.0, shape=(self._y_res, self._x_res, 3 * self._framestack)
)
# Observation space in output
if self._env_config["send_measurements"]:
self.observation_space = Dict(
{
actor_id: Tuple(
[
self._image_space, # image
Discrete(len(COMMANDS_ENUM)), # next_command
Box(
-128.0, 128.0, shape=(2,)
), # forward_speed, dist to goal
]
)
for actor_id in self._actor_configs.keys()
}
)
else:
self.observation_space = Dict(
{actor_id: self._image_space for actor_id in self._actor_configs.keys()}
)
# Set appropriate node-id to coordinate mappings for Town01 or Town02.
self.pos_coor_map = MAP_TO_COORDS_MAPPING[self._map]
self._spec = lambda: None
self._spec.id = "Carla-v0"
self._server_port = None
self._server_process = None
self._client = None
self._num_steps = {}
self._total_reward = {}
self._prev_measurement = {}
self._prev_image = None
self._episode_id_dict = {}
self._measurements_file_dict = {}
self._weather = None
self._start_pos = {} # Start pose for each actor
self._end_pos = {} # End pose for each actor
self._start_coord = {}
self._end_coord = {}
self._last_obs = None
self._image = None
self._surface = None
self._video = False
self._obs_dict = {}
self._done_dict = {}
self._previous_actions = {}
self._previous_rewards = {}
self._last_reward = {}
self._npc_vehicles = [] # List of NPC vehicles
self._npc_pedestrians = [] # List of NPC pedestrians
self._agents = {} # Dictionary of macad_agents with agent_id as key
self._actors = {} # Dictionary of actors with actor_id as key
self._cameras = {} # Dictionary of sensors with actor_id as key
self._path_trackers = {} # Dictionary of sensors with actor_id as key
self._collisions = {} # Dictionary of sensors with actor_id as key
self._lane_invasions = {} # Dictionary of sensors with actor_id as key
self._scenario_map = {} # Dictionary with current scenario map config
@staticmethod
def _get_tcp_port(port=0):
"""
Get a free tcp port number
:param port: (default 0) port number. When `0` it will be assigned a free port dynamically
:return: a port number requested if free otherwise an unhandled exception would be thrown
"""
s = socket.socket()
s.bind(("", port))
server_port = s.getsockname()[1]
s.close()
return server_port
def _init_server(self):
"""Initialize carla server and client
Returns:
N/A
"""
print("Initializing new Carla server...")
# Create a new server process and start the client.
# First find a port that is free and then use it in order to avoid
# crashes due to:"...bind:Address already in use"
self._server_port = self._get_tcp_port()
multigpu_success = False
gpus = GPUtil.getGPUs()
log_file = os.path.join(LOG_DIR, "server_" + str(self._server_port) + ".log")
logger.info(
f"1. Port: {self._server_port}\n"
f"2. Map: {self._server_map}\n"
f"3. Binary: {SERVER_BINARY}"
)
if not self._render and (gpus is not None and len(gpus)) > 0:
try:
min_index = random.randint(0, len(gpus) - 1)
for i, gpu in enumerate(gpus):
if gpu.load < gpus[min_index].load:
min_index = i
# Check if vglrun is setup to launch sim on multipl GPUs
if shutil.which("vglrun") is not None:
self._server_process = subprocess.Popen(
(
"DISPLAY=:8 vglrun -d :7.{} {} -benchmark -fps=20"
" -carla-server -world-port={}"
" -carla-streaming-port=0".format(
min_index,
SERVER_BINARY,
self._server_port,
)
),
shell=True,
# for Linux
preexec_fn=None if IS_WINDOWS_PLATFORM else os.setsid,
# for Windows (not necessary)
creationflags=subprocess.CREATE_NEW_PROCESS_GROUP
if IS_WINDOWS_PLATFORM
else 0,
stdout=open(log_file, "w"),
)
# Else, run in headless mode
else:
# Since carla 0.9.12+ use -RenderOffScreen to start headlessly
# https://carla.readthedocs.io/en/latest/adv_rendering_options/
self._server_process = subprocess.Popen(
( # 'SDL_VIDEODRIVER=offscreen SDL_HINT_CUDA_DEVICE={} DISPLAY='
'"{}" -RenderOffScreen -benchmark -fps=20 -carla-server'
" -world-port={} -carla-streaming-port=0".format(
SERVER_BINARY,
self._server_port,
)
),
shell=True,
# for Linux
preexec_fn=None if IS_WINDOWS_PLATFORM else os.setsid,
# for Windows (not necessary)
creationflags=subprocess.CREATE_NEW_PROCESS_GROUP
if IS_WINDOWS_PLATFORM
else 0,
stdout=open(log_file, "w"),
)
# TODO: Make the try-except style handling work with Popen
# exceptions after launching the server procs are not caught
except Exception as e:
print(e)
# Temporary soln to check if CARLA server proc started and wrote
# something to stdout which is the usual case during startup
if os.path.isfile(log_file):
multigpu_success = True
else:
multigpu_success = False
if multigpu_success:
print("Running sim servers in headless/multi-GPU mode")
# Rendering mode and also a fallback if headless/multi-GPU doesn't work
if multigpu_success is False:
try:
print("Using single gpu to initialize carla server")
self._server_process = subprocess.Popen(
[
SERVER_BINARY,
"-windowed",
"-ResX=",
str(self._env_config["render_x_res"]),
"-ResY=",
str(self._env_config["render_y_res"]),
"-benchmark",
"-fps=20",
"-carla-server",
"-carla-rpc-port={}".format(self._server_port),
"-carla-streaming-port=0",
],
# for Linux
preexec_fn=None if IS_WINDOWS_PLATFORM else os.setsid,
# for Windows (not necessary)
creationflags=subprocess.CREATE_NEW_PROCESS_GROUP
if IS_WINDOWS_PLATFORM
else 0,
stdout=open(log_file, "w"),
)
print("Running simulation in single-GPU mode")
except Exception as e:
logger.debug(e)
print("FATAL ERROR while launching server:", sys.exc_info()[0])
if IS_WINDOWS_PLATFORM:
live_carla_processes.add(self._server_process.pid)
else:
live_carla_processes.add(os.getpgid(self._server_process.pid))
# Start client
self._client = None
while self._client is None:
try:
self._client = carla.Client("localhost", self._server_port)
# The socket establishment could takes some time
time.sleep(2)
self._client.set_timeout(2.0)
print(
"Client successfully connected to server, Carla-Server version: ",
self._client.get_server_version(),
)
except RuntimeError as re:
if "timeout" not in str(re) and "time-out" not in str(re):
print("Could not connect to Carla server because:", re)
self._client = None
self._client.set_timeout(60.0)
# load map using client api since 0.9.6+
self._client.load_world(self._server_map)
self.world = self._client.get_world()
world_settings = self.world.get_settings()
world_settings.synchronous_mode = self._sync_server
if self._sync_server:
# Synchronous mode
# try:
# Available with CARLA version>=0.9.6
# Set fixed_delta_seconds to have reliable physics between sim steps
world_settings.fixed_delta_seconds = self._fixed_delta_seconds
self.world.apply_settings(world_settings)
# Set up traffic manager
self._traffic_manager = self._client.get_trafficmanager()
self._traffic_manager.set_global_distance_to_leading_vehicle(2.5)
self._traffic_manager.set_respawn_dormant_vehicles(True)
self._traffic_manager.set_synchronous_mode(self._sync_server)
# Set the spectator/server view if rendering is enabled
if self._render and self._env_config.get("spectator_loc"):
spectator = self.world.get_spectator()
spectator_loc = carla.Location(*self._env_config["spectator_loc"])
d = 6.4
angle = 160 # degrees
a = math.radians(angle)
location = (
carla.Location(d * math.cos(a), d * math.sin(a), 2.0) + spectator_loc
)
spectator.set_transform(
carla.Transform(location, carla.Rotation(yaw=180 + angle, pitch=-15))
)
if self._env_config.get("enable_planner"):
planner_dao = GlobalRoutePlannerDAO(self.world.get_map())
self.planner = GlobalRoutePlanner(planner_dao)
self.planner.setup()
def _clean_world(self):
"""Destroy all actors cleanly before exiting
Returns:
N/A
"""
for colli in self._collisions.values():
if colli.sensor.is_alive:
colli.sensor.destroy()
for lane in self._lane_invasions.values():
if lane.sensor.is_alive:
lane.sensor.destroy()
for actor in self._actors.values():
if actor.is_alive:
actor.destroy()
for npc in self._npc_vehicles:
npc.destroy()
for npc in zip(*self._npc_pedestrians):
npc[1].stop() # stop controller
npc[0].destroy() # kill entity
# Note: the destroy process for cameras is handled in camera_manager.py
self._cameras = {}
self._actors = {}
self._npc_vehicles = []
self._npc_pedestrians = []
self._path_trackers = {}
self._collisions = {}
self._lane_invasions = {}
print("Cleaned-up the world...")
def _clear_server_state(self):
"""Clear server process"""
print("Clearing Carla server state")
try:
if self._client:
self._client = None
except Exception as e:
print("Error disconnecting client: {}".format(e))
if self._server_process:
if IS_WINDOWS_PLATFORM:
subprocess.call(
["taskkill", "/F", "/T", "/PID", str(self._server_process.pid)]
)
live_carla_processes.remove(self._server_process.pid)
else:
pgid = os.getpgid(self._server_process.pid)
os.killpg(pgid, signal.SIGKILL)
live_carla_processes.remove(pgid)
self._server_port = None
self._server_process = None
def reset(self):
"""Reset the carla world, call _init_server()
Returns:
N/A
"""
# World reset and new scenario selection if multiple are available
self._load_scenario(self._scenario_config)
for retry in range(RETRIES_ON_ERROR):
try:
if not self._server_process:
self._init_server()
self._reset(clean_world=False)
else:
self._reset()
break
except Exception as e:
print("Error during reset: {}".format(traceback.format_exc()))
print("reset(): Retry #: {}/{}".format(retry + 1, RETRIES_ON_ERROR))
self._clear_server_state()
raise e
# Set appropriate initial values for all actors
for actor_id, actor_config in self._actor_configs.items():
if self._done_dict.get(actor_id, True):
self._last_reward[actor_id] = None
self._total_reward[actor_id] = None
self._num_steps[actor_id] = 0
py_measurement = self._read_observation(actor_id)
self._prev_measurement[actor_id] = py_measurement
cam = self._cameras[actor_id]
# Wait for the sensor (camera) actor to start streaming
# Shouldn't take too long
while cam.callback_count == 0:
if self._sync_server:
self.world.tick()
# `wait_for_tick` is no longer needed, see https://github.com/carla-simulator/carla/pull/1803
# self.world.wait_for_tick()
if cam.image is None:
print("callback_count:", actor_id, ":", cam.callback_count)
obs = self._encode_obs(actor_id, cam.image, py_measurement)
self._obs_dict[actor_id] = obs
# Actor correctly reset
self._done_dict[actor_id] = False
return self._obs_dict
# ! Deprecated method
def _on_render(self):
"""Render the pygame window.
Args:
Returns:
N/A
"""
pass
def _spawn_new_actor(self, actor_id):
"""Spawn an agent as per the blueprint at the given pose
Args:
blueprint: Blueprint of the actor. Can be a Vehicle or Pedestrian
pose: carla.Transform object with location and rotation
Returns:
An instance of a subclass of carla.Actor. carla.Vehicle in the case
of a Vehicle agent.
"""
actor_type = self._actor_configs[actor_id].get("type", "vehicle_4W")
if actor_type not in self._supported_active_actor_types:
print("Unsupported actor type:{}. Using vehicle_4W as the type")
actor_type = "vehicle_4W"
if actor_type == "traffic_light":
# Traffic lights already exist in the world & can't be spawned.
# Find closest traffic light actor in world.actor_list and return
from macad_gym.core.controllers import traffic_lights
loc = carla.Location(
self._start_pos[actor_id][0],
self._start_pos[actor_id][1],
self._start_pos[actor_id][2],
)
rot = (
self.world.get_map()
.get_waypoint(loc, project_to_road=True)
.transform.rotation
)
#: If yaw is provided in addition to (X, Y, Z), set yaw
if len(self._start_pos[actor_id]) > 3:
rot.yaw = self._start_pos[actor_id][3]
transform = carla.Transform(loc, rot)
self._actor_configs[actor_id]["start_transform"] = transform
tls = traffic_lights.get_tls(self.world, transform, sort=True)
return tls[0][0] #: Return the key (carla.TrafficLight object) of
#: closest match
if actor_type == "pedestrian":
blueprints = self.world.get_blueprint_library().filter(
"walker.pedestrian.*"
)
elif actor_type == "vehicle_4W":
blueprints = self.world.get_blueprint_library().filter("vehicle")
# Further filter down to 4-wheeled vehicles
blueprints = [
b for b in blueprints if int(b.get_attribute("number_of_wheels")) == 4
]
if self.exclude_hard_vehicles:
blueprints = list(
filter(
lambda x: not (
x.id.endswith("microlino")
or x.id.endswith("carlacola")
or x.id.endswith("cybertruck")
or x.id.endswith("t2")
or x.id.endswith("sprinter")
or x.id.endswith("firetruck")
or x.id.endswith("ambulance")
),
blueprints,
)
)
elif actor_type == "vehicle_2W":
blueprints = self.world.get_blueprint_library().filter("vehicle")
# Further filter down to 2-wheeled vehicles
blueprints = [
b for b in blueprints if int(b.get_attribute("number_of_wheels")) == 2
]
blueprint = random.choice(blueprints)
loc = carla.Location(
x=self._start_pos[actor_id][0],
y=self._start_pos[actor_id][1],
z=self._start_pos[actor_id][2],
)
rot = (
self.world.get_map()
.get_waypoint(loc, project_to_road=True)
.transform.rotation
)
#: If yaw is provided in addition to (X, Y, Z), set yaw
if len(self._start_pos[actor_id]) > 3:
rot.yaw = self._start_pos[actor_id][3]
transform = carla.Transform(loc, rot)
self._actor_configs[actor_id]["start_transform"] = transform
vehicle = None
for retry in range(RETRIES_ON_ERROR):
vehicle = self.world.try_spawn_actor(blueprint, transform)
if self._sync_server:
self.world.tick()
if vehicle is not None and vehicle.get_location().z > 0.0:
# Register it under traffic manager
# Walker vehicle type does not have autopilot. Use walker controller ai
if actor_type == "pedestrian":
# vehicle.set_simulate_physics(False)
pass
else:
vehicle.set_autopilot(False, self._traffic_manager.get_port())
break
# Wait to see if spawn area gets cleared before retrying
# time.sleep(0.5)
# self._clean_world()
print("spawn_actor: Retry#:{}/{}".format(retry + 1, RETRIES_ON_ERROR))
if vehicle is None:
# Request a spawn one last time possibly raising the error
vehicle = self.world.spawn_actor(blueprint, transform)
return vehicle
def _reset(self, clean_world=True):
"""Reset the state of the actors.
A "soft" reset is performed in which the existing actors are destroyed
and the necessary actors are spawned into the environment without
affecting other aspects of the environment.
If the "soft" reset fails, a "hard" reset is performed in which
the environment's entire state is destroyed and a fresh instance of
the server is created from scratch. Note that the "hard" reset is
expected to take more time. In both of the reset modes ,the state/
pose and configuration of all actors (including the sensor actors) are
(re)initialized as per the actor configuration.
Returns:
dict: Dictionaries of observations for actors.
Raises:
RuntimeError: If spawning an actor at its initial state as per its'
configuration fails (eg.: Due to collision with an existing object
on that spot). This Error will be handled by the caller
`self.reset()` which will perform a "hard" reset by creating
a new server instance
"""
self._done_dict["__all__"] = False
if clean_world:
self._clean_world()
weather_num = 0
if "weather_distribution" in self._scenario_map:
weather_num = random.choice(self._scenario_map["weather_distribution"])
if weather_num not in WEATHERS:
weather_num = 0
self.world.set_weather(WEATHERS[weather_num])
self._weather = [
self.world.get_weather().cloudiness,
self.world.get_weather().precipitation,
self.world.get_weather().precipitation_deposits,
self.world.get_weather().wind_intensity,
]
for actor_id, actor_config in self._actor_configs.items():
if self._done_dict.get(actor_id, True):
self._measurements_file_dict[actor_id] = None
self._episode_id_dict[actor_id] = datetime.today().strftime(
"%Y-%m-%d_%H-%M-%S_%f"
)
actor_config = self._actor_configs[actor_id]
# Try to spawn actor (soft reset) or fail and reinitialize the server before get back here
try:
self._actors[actor_id] = self._spawn_new_actor(actor_id)
except RuntimeError as spawn_err:
del self._done_dict[actor_id]
# Chain the exception & re-raise to be handled by the caller `self.reset()`
raise spawn_err from RuntimeError(
"Unable to spawn actor:{}".format(actor_id)
)
if self._env_config["enable_planner"]:
self._path_trackers[actor_id] = PathTracker(
self.world,
self.planner,
(
self._start_pos[actor_id][0],
self._start_pos[actor_id][1],
self._start_pos[actor_id][2],
),
(
self._end_pos[actor_id][0],
self._end_pos[actor_id][1],
self._end_pos[actor_id][2],
),
self._actors[actor_id],
)
# Spawn collision and lane sensors if necessary
if actor_config["collision_sensor"] == "on":
collision_sensor = CollisionSensor(self._actors[actor_id], 0)
self._collisions.update({actor_id: collision_sensor})
if actor_config["lane_sensor"] == "on":
lane_sensor = LaneInvasionSensor(self._actors[actor_id], 0)
self._lane_invasions.update({actor_id: lane_sensor})
# Spawn cameras
pygame.font.init() # for HUD
hud = HUD(self._env_config["x_res"], self._env_config["y_res"])
camera_manager = CameraManager(self._actors[actor_id], hud)
if actor_config["log_images"]:
# TODO: The recording option should be part of config
# 1: Save to disk during runtime
# 2: save to memory first, dump to disk on exit
camera_manager.set_recording_option(1)
# in CameraManger's._sensors
camera_type = self._actor_configs[actor_id]["camera_type"]
camera_pos = getattr(
self._actor_configs[actor_id], "camera_position", 0
)
camera_types = [ct.name for ct in CAMERA_TYPES]
assert (
camera_type in camera_types
), "Camera type `{}` not available. Choose in {}.".format(
camera_type, camera_types
)
camera_manager.set_sensor(
CAMERA_TYPES[camera_type].value - 1, int(camera_pos), notify=False
)
assert camera_manager.sensor.is_listening
self._cameras.update({actor_id: camera_manager})
# Manual Control
if actor_config["manual_control"]:
self._control_clock = pygame.time.Clock()
self._manual_controller = KeyboardControl(
self, actor_config["auto_control"]
)
self._manual_controller.actor_id = actor_id
self.world.on_tick(self._hud.on_world_tick)
self._manual_control_camera_manager = CameraManager(
self._actors[actor_id], self._hud
)
self._manual_control_camera_manager.set_sensor(
CAMERA_TYPES["rgb"].value - 1, pos=2, notify=False
)
self._start_coord.update(
{
actor_id: [
self._start_pos[actor_id][0] // 100,
self._start_pos[actor_id][1] // 100,
]
}
)
self._end_coord.update(
{
actor_id: [
self._end_pos[actor_id][0] // 100,
self._end_pos[actor_id][1] // 100,
]
}