-
Notifications
You must be signed in to change notification settings - Fork 0
/
car_env.py
234 lines (196 loc) · 7.77 KB
/
car_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
"""
Environment for 2D car driving.
You can customize this script in a way you want.
View more on [莫烦Python] : https://morvanzhou.github.io/tutorials/
Requirement:
pyglet >= 1.2.4
numpy >= 1.12.1
"""
import numpy as np
import pyglet
pyglet.clock.set_fps_limit(10000)
class CarEnv(object):
n_sensor = 5
action_dim = 1
state_dim = n_sensor
viewer = None
viewer_xy = (500, 500)
sensor_max = 150.
start_point = [450, 300]
speed = 50.
dt = 0.1
def __init__(self, discrete_action=False):
self.is_discrete_action = discrete_action
if discrete_action:
self.actions = [-1, 0, 1]
else:
self.action_bound = [-1, 1]
self.terminal = False
# node1 (x, y, r, w, l),
self.car_info = np.array([0, 0, 0, 20, 40], dtype=np.float64) # car coordination
self.obstacle_coords = np.array([
[120, 120],
[380, 120],
[380, 380],
[120, 380],
])
self.sensor_info = self.sensor_max + np.zeros((self.n_sensor, 3)) # n sensors, (distance, end_x, end_y)
def step(self, action):
if self.is_discrete_action:
action = self.actions[action]
else:
action = np.clip(action, *self.action_bound)[0]
self.car_info[2] += action * np.pi/30 # max r = 6 degree
self.car_info[:2] = self.car_info[:2] + \
self.speed * self.dt * np.array([np.cos(self.car_info[2]), np.sin(self.car_info[2])])
self._update_sensor()
s = self._get_state()
r = -1 if self.terminal else 0
return s, r, self.terminal
def reset(self):
self.terminal = False
self.car_info[:3] = np.array([*self.start_point, -np.pi/2])
self._update_sensor()
return self._get_state()
def render(self):
if self.viewer is None:
self.viewer = Viewer(*self.viewer_xy, self.car_info, self.sensor_info, self.obstacle_coords)
self.viewer.render()
def sample_action(self):
if self.is_discrete_action:
a = np.random.choice(list(range(3)))
else:
a = np.random.uniform(*self.action_bound, size=self.action_dim)
return a
def set_fps(self, fps=30):
pyglet.clock.set_fps_limit(fps)
def _get_state(self):
s = self.sensor_info[:, 0].flatten()/self.sensor_max
return s
def _update_sensor(self):
cx, cy, rotation = self.car_info[:3]
n_sensors = len(self.sensor_info)
sensor_theta = np.linspace(-np.pi / 2, np.pi / 2, n_sensors)
xs = cx + (np.zeros((n_sensors, ))+self.sensor_max) * np.cos(sensor_theta)
ys = cy + (np.zeros((n_sensors, ))+self.sensor_max) * np.sin(sensor_theta)
xys = np.array([[x, y] for x, y in zip(xs, ys)]) # shape (5 sensors, 2)
# sensors
tmp_x = xys[:, 0] - cx
tmp_y = xys[:, 1] - cy
# apply rotation
rotated_x = tmp_x * np.cos(rotation) - tmp_y * np.sin(rotation)
rotated_y = tmp_x * np.sin(rotation) + tmp_y * np.cos(rotation)
# rotated x y
self.sensor_info[:, -2:] = np.vstack([rotated_x+cx, rotated_y+cy]).T
q = np.array([cx, cy])
for si in range(len(self.sensor_info)):
s = self.sensor_info[si, -2:] - q
possible_sensor_distance = [self.sensor_max]
possible_intersections = [self.sensor_info[si, -2:]]
# obstacle collision
for oi in range(len(self.obstacle_coords)):
p = self.obstacle_coords[oi]
r = self.obstacle_coords[(oi + 1) % len(self.obstacle_coords)] - self.obstacle_coords[oi]
if np.cross(r, s) != 0: # may collision
t = np.cross((q - p), s) / np.cross(r, s)
u = np.cross((q - p), r) / np.cross(r, s)
if 0 <= t <= 1 and 0 <= u <= 1:
intersection = q + u * s
possible_intersections.append(intersection)
possible_sensor_distance.append(np.linalg.norm(u*s))
# window collision
win_coord = np.array([
[0, 0],
[self.viewer_xy[0], 0],
[*self.viewer_xy],
[0, self.viewer_xy[1]],
[0, 0],
])
for oi in range(4):
p = win_coord[oi]
r = win_coord[(oi + 1) % len(win_coord)] - win_coord[oi]
if np.cross(r, s) != 0: # may collision
t = np.cross((q - p), s) / np.cross(r, s)
u = np.cross((q - p), r) / np.cross(r, s)
if 0 <= t <= 1 and 0 <= u <= 1:
intersection = p + t * r
possible_intersections.append(intersection)
possible_sensor_distance.append(np.linalg.norm(intersection - q))
distance = np.min(possible_sensor_distance)
distance_index = np.argmin(possible_sensor_distance)
self.sensor_info[si, 0] = distance
self.sensor_info[si, -2:] = possible_intersections[distance_index]
if distance < self.car_info[-1]/2:
self.terminal = True
class Viewer(pyglet.window.Window):
color = {
'background': [1]*3 + [1]
}
fps_display = pyglet.clock.ClockDisplay()
bar_thc = 5
def __init__(self, width, height, car_info, sensor_info, obstacle_coords):
super(Viewer, self).__init__(width, height, resizable=False, caption='2D car', vsync=False) # vsync=False to not use the monitor FPS
self.set_location(x=80, y=10)
pyglet.gl.glClearColor(*self.color['background'])
self.car_info = car_info
self.sensor_info = sensor_info
self.batch = pyglet.graphics.Batch()
background = pyglet.graphics.OrderedGroup(0)
foreground = pyglet.graphics.OrderedGroup(1)
self.sensors = []
line_coord = [0, 0] * 2
c = (73, 73, 73) * 2
for i in range(len(self.sensor_info)):
self.sensors.append(self.batch.add(2, pyglet.gl.GL_LINES, foreground, ('v2f', line_coord), ('c3B', c)))
car_box = [0, 0] * 4
c = (249, 86, 86) * 4
self.car = self.batch.add(4, pyglet.gl.GL_QUADS, foreground, ('v2f', car_box), ('c3B', c))
c = (134, 181, 244) * 4
self.obstacle = self.batch.add(4, pyglet.gl.GL_QUADS, background, ('v2f', obstacle_coords.flatten()), ('c3B', c))
def render(self):
pyglet.clock.tick()
self._update()
self.switch_to()
self.dispatch_events()
self.dispatch_event('on_draw')
self.flip()
def on_draw(self):
self.clear()
self.batch.draw()
# self.fps_display.draw()
def _update(self):
cx, cy, r, w, l = self.car_info
# sensors
for i, sensor in enumerate(self.sensors):
sensor.vertices = [cx, cy, *self.sensor_info[i, -2:]]
# car
xys = [
[cx + l / 2, cy + w / 2],
[cx - l / 2, cy + w / 2],
[cx - l / 2, cy - w / 2],
[cx + l / 2, cy - w / 2],
]
r_xys = []
for x, y in xys:
tempX = x - cx
tempY = y - cy
# apply rotation
rotatedX = tempX * np.cos(r) - tempY * np.sin(r)
rotatedY = tempX * np.sin(r) + tempY * np.cos(r)
# rotated x y
x = rotatedX + cx
y = rotatedY + cy
r_xys += [x, y]
self.car.vertices = r_xys
if __name__ == '__main__':
np.random.seed(1)
env = CarEnv()
env.set_fps(30)
for ep in range(20):
s = env.reset()
# for t in range(100):
while True:
env.render()
s, r, done = env.step(env.sample_action())
if done:
break