-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_env.py
More file actions
235 lines (191 loc) · 7.86 KB
/
test_env.py
File metadata and controls
235 lines (191 loc) · 7.86 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
import glob
import math
import os
import sys
import random
import time
import numpy as np
import cv2
import torch
import torch.nn as nn
from lib.resnet_model_levi_1 import Network
from lib.dataset import unnormalize, resnet_transforms
from lib.model import ResNet, ViTNet
# from carla.models import cnn_version1
try:
sys.path.append(glob.glob('./carla/dist/carla-*%d.%d-%s.egg' % (
sys.version_info.major,
sys.version_info.minor,
'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])
except IndexError:
pass
import carla
SHOW_PREVIEW = False
class CarEnv:
STEER_AMT = 1.0
SHOW_CAM = SHOW_PREVIEW
SECONDS_PER_EPISODE = 60
IMG_WIDTH = 200
IMG_HEIGHT = 88
front_camera = None
def __init__(self):
self.client = carla.Client("127.0.0.1", 2000)
self.client.set_timeout(2.0)
self.world = self.client.get_world()
# self.world = self.client.load_world('Town10')
self.traffic_manager = self.client.get_trafficmanager()
self.traffic_manager.set_random_device_seed(0)
self.blueprint_library = self.world.get_blueprint_library()
self.car = self.blueprint_library.filter("model3")[0]
self.models = ['dodge', 'audi', 'model3', 'mini', 'mustang', 'lincoln', 'prius', 'nissan', 'crown', 'impala']
self.reset()
def reset(self):
self.collision_hist = []
self.actor_list = []
# spawn vehicle agent
self.transform = self.world.get_map().get_spawn_points()[0]
self.vehicle = self.world.spawn_actor(self.car, self.transform)
self.actor_list.append(self.vehicle)
self.world.debug.draw_string(self.transform.location, "Start Point", life_time=5)
# spawn camera
self.rgb_cam = self.blueprint_library.find("sensor.camera.rgb")
self.rgb_cam.set_attribute("image_size_x", f"{self.IMG_WIDTH}")
self.rgb_cam.set_attribute("image_size_y", f"{self.IMG_HEIGHT}")
self.rgb_cam.set_attribute("fov", f"110")
cam_transform = carla.Transform(carla.Location(x=2.5, z=1))
self.rgb_sensor = self.world.spawn_actor(self.rgb_cam, cam_transform, attach_to=self.vehicle)
self.actor_list.append(self.rgb_sensor)
self.rgb_sensor.listen(lambda data: self.process_img(data))
# self.vehicle.apply_control(carla.VehicleControl(throttle=0.0, brake=0.0))
# time.sleep(4)
# spawn collision sensor
collision_sensor = self.blueprint_library.find("sensor.other.collision")
self.collision_sensor = self.world.spawn_actor(collision_sensor, cam_transform, attach_to=self.vehicle)
self.actor_list.append(self.collision_sensor)
self.collision_sensor.listen(lambda event: self.collision_data(event))
time.sleep(2)
# spawn traffic
spawn_points = self.world.get_map().get_spawn_points()[1:]
for i, spawn_point in enumerate(spawn_points):
self.world.debug.draw_string(spawn_point.location, str(i), life_time=2)
blueprints = []
for vehicle in self.world.get_blueprint_library().filter('*vehicle*'):
if any(model in vehicle.id for model in self.models):
blueprints.append(vehicle)
# Set a max number of vehicles and prepare a list for those we spawn
max_vehicles = 50
max_vehicles = min([max_vehicles, len(spawn_points)])
# Take a random sample of the spawn points and spawn some vehicles
'''vehicles = []
for i, spawn_point in enumerate(random.sample(spawn_points, max_vehicles)):
temp = self.world.try_spawn_actor(random.choice(blueprints), spawn_point)
if temp is not None:
temp.set_autopilot(True)
self.actor_list.append(temp)
vehicles.append(temp)
'''
self.vehicle.apply_control(carla.VehicleControl(throttle=0.0, brake=0.0))
time.sleep(4)
while self.front_camera is None:
time.sleep(0.01)
self.episode_start = time.time()
self.vehicle.apply_control(carla.VehicleControl(throttle=0.0, brake=0.0))
return self.front_camera
def cleanup(self):
self.client.apply_batch([carla.command.DestroyActor(x) for x in self.actor_list])
def collision_data(self, event):
self.collision_hist.append(event)
def process_img(self, image):
i = np.array(image.raw_data)
i2 = i.reshape((self.IMG_HEIGHT, self.IMG_WIDTH, 4))
i3 = i2[:, :, :3]
if self.SHOW_CAM:
cv2.imshow("", i3)
cv2.waitKey(1)
self.front_camera = i3
def step(self, action):
done = False
# model
if action == 0:
self.vehicle.apply_control(carla.VehicleControl(throttle=1.0, steer=-1 * self.STEER_AMT))
elif action == 1:
self.vehicle.apply_control(carla.VehicleControl(throttle=1.0, steer=0))
elif action == 2:
self.vehicle.apply_control(carla.VehicleControl(throttle=1.0, steer=1 * self.STEER_AMT))
v = self.vehicle.get_velocity()
khm = int(3.6 * math.sqrt(v.x ** 2 + v.y ** 2 + v.z ** 2))
if len(self.collision_hist) != 0:
self.episode_end = time.time()
done = True
elif khm < 50:
done = False
if self.episode_start + self.SECONDS_PER_EPISODE < time.time():
self.episode_end = time.time()
done = True
return self.front_camera, done, None
def step_2(self, throttle, steer_amt, brake):
done = False
# model
self.vehicle.apply_control(
carla.VehicleControl(throttle=throttle, steer=steer_amt * self.STEER_AMT, brake=brake))
v = self.vehicle.get_velocity()
khm = int(3.6 * math.sqrt(v.x ** 2 + v.y ** 2 + v.z ** 2))
if len(self.collision_hist) != 0:
self.episode_end = time.time()
done = True
#elif khm < 50:
# done = False
if self.episode_start + self.SECONDS_PER_EPISODE < time.time():
self.episode_end = time.time()
done = True
return self.front_camera, done, None
def step_3(self, target_speed, steer_amt):
done = False
v = self.vehicle.get_velocity()
khm = int(3.6 * math.sqrt(v.x ** 2 + v.y ** 2 + v.z ** 2))
throttle = 0.0
brake = 0.0
if target_speed > khm:
throttle = 1
brake = 0.0
elif target_speed < khm:
throttle = 0.0
brake = 0.5
# print(khm, throttle, brake)
self.vehicle.apply_control(carla.VehicleControl(throttle=throttle, steer=steer_amt * self.STEER_AMT))
if len(self.collision_hist) != 0:
self.episode_end = time.time()
done = True
#elif khm < 50:
# done = False
if self.episode_start + self.SECONDS_PER_EPISODE < time.time():
self.episode_end = time.time()
done = True
return self.front_camera, done, None
if __name__ == "__main__":
FPS = 60
random.seed(10)
np.random.seed(10)
env = CarEnv()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = ViTNet()
model.load('./best_vit.pth', device)
model.to(device)
model.eval()
throttle = 0.0 # Set a constant throttle value
brake = 0.0 # Set the brake value
next_image, done, _ = env.step(1)
while True:
time.sleep(1 / FPS)
with torch.no_grad():
img = resnet_transforms()(next_image).to(device).unsqueeze(0)
pred = model.model_input(img)
pred = unnormalize(pred.cpu()[0])
speed = round(float(pred[0]), 2)
steer_amt = float(pred[1])
print(f'speed: {speed} | steer: {steer_amt}')
next_image, done, _ = env.step_3(speed, steer_amt)
if done:
break
env.cleanup()
print(f'Car drove for {env.episode_end - env.episode_start} sec')