-
Notifications
You must be signed in to change notification settings - Fork 38
/
rrt-star_ReedsSheep_New.py
437 lines (355 loc) · 12.8 KB
/
rrt-star_ReedsSheep_New.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
import math, sys, pygame, random
from math import *
from pygame import *
import sys
import random
import math
import copy
import numpy as np
import reeds_shepp_path_planning
import matplotlib.pyplot as plt
XDIM = 720
YDIM = 500
windowSize = [XDIM, YDIM]
delta = 10.0
GAME_LEVEL = 1
GOAL_RADIUS = 10
MIN_DISTANCE_TO_ADD = 1.0
NUMNODES = 5000
FPS = 1000
pygame.init()
fpsClock = pygame.time.Clock()
screen = pygame.display.set_mode(windowSize)
white = 255, 255, 255
black = 25, 25, 25
red = 255, 0, 0
blue = 0, 128, 0
green = 0, 0, 255
cyan = 0,180,105
show_animation = True
STEP_SIZE = 2
curvature = 0.05
count = 0
obs = []
def dist(p1,p2): #distance between two points
return sqrt((p1[0]-p2[0])*(p1[0]-p2[0])+(p1[1]-p2[1])*(p1[1]-p2[1]))
def point_circle_collision(p1, p2, radius):
distance = dist(p1,p2)
if (distance <= radius):
return True
return False
def step_from_to(p1,p2):
if dist(p1,p2) < delta:
return p2
else:
theta = atan2(p2[1]-p1[1],p2[0]-p1[0])
return p1[0] + delta*cos(theta), p1[1] + delta*sin(theta)
def collides(p): #check if point collides with the obstacle
return False
def init_obstacles(configNum): #initialized the obstacle
global obs
obs = []
obs.append((150,100,18))
obs.append((150,130,18))
obs.append((150,160,18))
obs.append((150,190,18))
obs.append((150,220,18))
obs.append((150,250,18))
obs.append((180,250,18))
obs.append((210,250,18))
obs.append((240,250,18))
obs.append((270,250,18))
obs.append((300,250,18))
obs.append((330,250,18))
obs.append((330,220,18))
obs.append((330,190,18))
obs.append((330,160,18))
obs.append((330,130,18))
obs.append((330,100,18))
obs.append((300,100,18))
obs.append((270,100,18))
obs.append((240,100,18))
obs.append((240,130,18))
obs.append((240,160,18))
obs.append((240,190,18))
for (ox, oy, size) in obs:
#plt.plot(ox, oy, "ok", ms=30 * size)
pygame.draw.circle(screen, black, (ox, oy), size)
def reset():
global count
screen.fill(white)
init_obstacles(GAME_LEVEL)
count = 0
class RRT():
"""
Class for RRT Planning
"""
def __init__(self, start, goal, obstacleList, randArea,
goalSampleRate=10, maxIter=120):
"""
Setting Parameter
start:Start Position [x,y]
goal:Goal Position [x,y]
obstacleList:obstacle Positions [[x,y,size],...]
randArea:Ramdom Samping Area [min,max]
"""
self.start = Node(start[0], start[1], start[2])
self.end = Node(goal[0], goal[1], goal[2])
self.minrand = randArea[0]
self.maxrand = randArea[1]
self.goalSampleRate = goalSampleRate
self.maxIter = maxIter
self.obstacleList = obstacleList
def Planning(self, animation=True):
"""
Pathplanning
animation: flag for animation on or off
"""
self.nodeList = [self.start]
for i in range(self.maxIter):
if(i%10==0):
print("Planning path",i)
for e in pygame.event.get():
if e.type == QUIT or (e.type == KEYUP and e.key == K_ESCAPE):
sys.exit("Exiting")
rnd = self.get_random_point()
nind = self.GetNearestListIndex(self.nodeList, rnd)
newNode = self.steer(rnd, nind)
if newNode is None:
continue
if self.CollisionCheck(newNode, self.obstacleList):
nearinds = self.find_near_nodes(newNode)
newNode = self.choose_parent(newNode, nearinds)
if newNode is None:
continue
self.nodeList.append(newNode)
self.rewire(newNode, nearinds)
if animation and i % 5 == 0:
self.DrawGraph(rnd=rnd)
#if(newNode.)
# generate coruse
lastIndex = self.get_best_last_index()
if lastIndex is None:
return None
path = self.gen_final_course(lastIndex)
print("Path planning done")
return path
def choose_parent(self, newNode, nearinds):
if len(nearinds) == 0:
return newNode
dlist = []
for i in nearinds:
tNode = self.steer(newNode, i)
if tNode is None:
continue
if self.CollisionCheck(tNode, self.obstacleList):
dlist.append(tNode.cost)
else:
dlist.append(float("inf"))
mincost = min(dlist)
minind = nearinds[dlist.index(mincost)]
if mincost == float("inf"):
print("mincost is inf")
return newNode
newNode = self.steer(newNode, minind)
return newNode
def pi_2_pi(self, angle):
return (angle + math.pi) % (2 * math.pi) - math.pi
def steer(self, rnd, nind):
nearestNode = self.nodeList[nind]
px, py, pyaw, mode, clen = reeds_shepp_path_planning.reeds_shepp_path_planning(
nearestNode.x, nearestNode.y, nearestNode.yaw, rnd.x, rnd.y, rnd.yaw, curvature, STEP_SIZE)
if px is None:
return None
newNode = copy.deepcopy(nearestNode)
newNode.x = px[-1]
newNode.y = py[-1]
newNode.yaw = pyaw[-1]
newNode.path_x = px
newNode.path_y = py
newNode.path_yaw = pyaw
newNode.cost += sum([abs(c) for c in clen])
newNode.parent = nind
return newNode
def get_random_point(self):
if random.randint(0, 100) > self.goalSampleRate:
rnd = [random.uniform(self.minrand, self.maxrand),
random.uniform(self.minrand, self.maxrand),
random.uniform(-math.pi, math.pi)
]
else: # goal point sampling
rnd = [self.end.x, self.end.y, self.end.yaw]
node = Node(rnd[0], rnd[1], rnd[2])
return node
def get_best_last_index(self):
# print("get_best_last_index")
YAWTH = np.deg2rad(3.0)
XYTH = 0.5
goalinds = []
for (i, node) in enumerate(self.nodeList):
if self.calc_dist_to_goal(node.x, node.y) <= XYTH:
goalinds.append(i)
# print("OK XY TH num is")
# print(len(goalinds))
# angle check
fgoalinds = []
for i in goalinds:
if abs(self.nodeList[i].yaw - self.end.yaw) <= YAWTH:
fgoalinds.append(i)
# print("OK YAW TH num is")
# print(len(fgoalinds))
if len(fgoalinds) == 0:
return None
mincost = min([self.nodeList[i].cost for i in fgoalinds])
for i in fgoalinds:
if self.nodeList[i].cost == mincost:
return i
return None
def gen_final_course(self, goalind):
path = [[self.end.x, self.end.y]]
while self.nodeList[goalind].parent is not None:
node = self.nodeList[goalind]
for (ix, iy) in zip(reversed(node.path_x), reversed(node.path_y)):
path.append([ix, iy])
# path.append([node.x, node.y])
goalind = node.parent
path.append([self.start.x, self.start.y])
return path
def calc_dist_to_goal(self, x, y):
return np.linalg.norm([x - self.end.x, y - self.end.y])
def find_near_nodes(self, newNode):
nnode = len(self.nodeList)
r = 50.0 * math.sqrt((math.log(nnode) / nnode))
# r = self.expandDis * 5.0
dlist = [(node.x - newNode.x) ** 2 +
(node.y - newNode.y) ** 2 +
(node.yaw - newNode.yaw) ** 2
for node in self.nodeList]
nearinds = [dlist.index(i) for i in dlist if i <= r ** 2]
return nearinds
def rewire(self, newNode, nearinds):
nnode = len(self.nodeList)
for i in nearinds:
nearNode = self.nodeList[i]
tNode = self.steer(nearNode, nnode - 1)
if tNode is None:
continue
obstacleOK = self.CollisionCheck(tNode, self.obstacleList)
imporveCost = nearNode.cost > tNode.cost
if obstacleOK and imporveCost:
# print("rewire")
self.nodeList[i] = tNode
def DrawGraph(self, rnd=None):
"""
Draw Graph
"""
reset()
if rnd is not None:
plt.plot(rnd.x, rnd.y, "^k")
for node in self.nodeList:
if node.parent is not None:
plt.plot(node.path_x, node.path_y, "-g")
for i in range(1, len(node.path_x)):
pygame.draw.line(screen,blue,(node.path_x[i-1], node.path_y[i-1]), (node.path_x[i], node.path_y[i]))
# plt.plot([node.x, self.nodeList[node.parent].x], [
# node.y, self.nodeList[node.parent].y], "-g")
for (ox, oy, size) in self.obstacleList:
#plt.plot(ox, oy, "ok", ms=30 * size)
pygame.draw.circle(screen, black, (ox, oy), size)
'''reeds_shepp_path_planning.plot_arrow(self.start.x, self.start.y, self.start.yaw)
reeds_shepp_path_planning.plot_arrow(self.end.x, self.end.y, self.end.yaw)'''
pygame.draw.circle(screen, red, (self.start.x, self.start.y), GOAL_RADIUS)
pygame.draw.circle(screen, green, (self.end.x, self.end.y), GOAL_RADIUS)
'''plt.axis([-2, 15, -2, 15])
plt.grid(True)
plt.pause(0.01)'''
pygame.display.update()
# plt.show()
# input()
def GetNearestListIndex(self, nodeList, rnd):
dlist = [(node.x - rnd.x) ** 2 +
(node.y - rnd.y) ** 2 +
(node.yaw - rnd.yaw) ** 2 for node in nodeList]
minind = dlist.index(min(dlist))
return minind
def CollisionCheck(self, node, obstacleList):
for (ox, oy, size) in obstacleList:
for (ix, iy) in zip(node.path_x, node.path_y):
dx = ox - ix
dy = oy - iy
d = dx * dx + dy * dy
if d <= size ** 2:
return False # collision
return True # safe
class Node():
"""
RRT Node
"""
def __init__(self, x, y, yaw):
self.x = x
self.y = y
self.yaw = yaw
self.path_x = []
self.path_y = []
self.path_yaw = []
self.cost = 0.0
self.parent = None
def main():
global count
initPoseSet = False
initialPoint = Node(None, None, 0)
goalPoseSet = False
goalPoint = Node(None, None, 0)
currentState = 'init'
rrt = None
path = None
nodes = []
reset()
while True:
if currentState == 'init':
pygame.display.set_caption('Select Starting Point and then Goal Point')
fpsClock.tick(10)
elif currentState == 'goalFound':
pygame.display.set_caption('Goal Reached')
rrt.DrawGraph()
for i in range(1, len(path)):
pygame.draw.line(screen, red, path[i-1], path[i])
optimizePhase = True
elif currentState == 'optimize':
fpsClock.tick(0.5)
pass
elif currentState == 'buildTree':
rrt = RRT((initialPoint.x, initialPoint.y, initialPoint.yaw), (goalPoint.x, goalPoint.y, goalPoint.yaw), randArea=[0, 500], obstacleList=obs)
path = rrt.Planning(True)
if(path != None):
currentState = 'goalFound'
for e in pygame.event.get():
if e.type == QUIT or (e.type == KEYUP and e.key == K_ESCAPE):
sys.exit("Exiting")
if e.type == MOUSEBUTTONDOWN:
print('mouse down')
if currentState == 'init':
if initPoseSet == False:
nodes = []
if collides(e.pos) == False:
print('initiale point set: '+str(e.pos))
initialPoint = Node(e.pos[0], e.pos[1], np.deg2rad(0.0))
initPoseSet = True
pygame.draw.circle(screen, red, (initialPoint.x, initialPoint.y), GOAL_RADIUS)
elif goalPoseSet == False:
print('goal point set: '+str(e.pos))
if collides(e.pos) == False:
goalPoint = Node(e.pos[0], e.pos[1], np.deg2rad(0.0))
goalPoseSet = True
pygame.draw.circle(screen, green, (goalPoint.x, goalPoint.y), GOAL_RADIUS)
#pygame.display.update()
currentState = 'buildTree'
else:
currentState = 'init'
initPoseSet = False
goalPoseSet = False
reset()
pygame.display.update()
fpsClock.tick(FPS)
if __name__ == '__main__':
main()