-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMCTBRRT.py
553 lines (387 loc) · 16.5 KB
/
MCTBRRT.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
import numpy as np
import control
import pdb
import matplotlib.pyplot as plt
import importlib
import scipy.linalg as sp_linalg
class Node:
def __init__(self, state_time = np.zeros(7, dtype=float)):
self.state_time = state_time
#lqr params
self.u = np.zeros(3)
self.parent = None
self.children = []
class TBRRT():
def __init__(self, arm, start, goal):
"""
:param start: robot arm starting position
:param goal: goal position
"""
self.arm = arm
self.Tree = []
self.edge_costs = {} # (parent, child) -> cost
self.start = start
self.goal = goal
# Store variables
self.dt = arm.dt
self.goal = goal
self.eps = np.array([np.deg2rad(2.8), 0.2, 0.03])
# Add start node to the tree
start_node = Node(start)
self.Tree.append(start_node)
self.min_state = np.array([0,0,0,-1,-1,-1])
self.max_state = np.array([2*np.pi,2*np.pi,2*np.pi,1,1,1])
self.maxUs = np.ones(3) * 500
self.minUs = -self.maxUs
def set_sample_region(self):
"""
create a directed joint space between the starting and ending nodes
"""
theta_delta = self.wrap(self.start[0:3], self.goal[0:3])
delta_signs = np.sign(self.goal[0:3] - self.start[0:3])
self.smart_region_min = self.start
self.smart_region_max = self.start + delta_signs * theta_delta
velocity_min = np.zeros(3,1)
for i in range(3):
def sample(self):
"""
Sample the joint space
"""
#compute the relevant range between the starting position and ending position that should be sampled
rand_state = np.random.uniform(self.min_state, self.max_state)
return rand_state
def compute_dist(self, s1, s2):
"""
Return the norm between 2 state-time vectors. Note to wrap the angle difference
"""
return sp_linalg.norm(self.wrap(s1, s2))
def nearest_neighbor(self, xRand):
"""
Find the node in the graph which requires the smallest magnitude of u to get to from the random state.
"""
# TODO: Make this more efficient?
#within a neighborhood of XRand, determine the lowest cost to go
minCost = np.inf
minNode = None
for node in self.Tree:
cost = self.compute_dist(node.state_time[0:6], xRand)
if cost < minCost:
minNode = node
minCost = cost
return minNode
def steer(self, xi, xRand, k = 10):
"""
Select ui to move from xi toward xrand
"""
#test k different controls
minDist = np.inf
bestControl = np.zeros(3)
xi_1 = None
for _ in range(k):
#smarter sampling in the right direction?
u_rand = np.random.uniform(self.minUs, self.maxUs)
nextState = self.simulate_system(xi.state_time[0:6], u_rand)
next_state_dist = self.compute_dist(nextState, xRand)
if next_state_dist < minDist:
minDist = next_state_dist
xi_1 = nextState
bestControl = u_rand
return xi_1, minDist, bestControl
def is_reachable(self, xi):
"""
Checks if xi is reachable, i.e. not self collisions or joint limits
"""
#TODO: Check if any of the links intersect...
return True
def add_edge(self, parent, child, ui):
parent.children.append(child)
child.parent = parent
self.edge_costs[(parent, child)] = ui
def near_goal(self, xi_1):
dist_norm = np.linalg.norm(xi_1[0:3] - self.goal[0:3])
vel_norm = np.linalg.norm(xi_1[3:7] - self.goal[3:7])
time_norm = np.linalg.norm(xi_1[-1] - self.goal[-1])
if (dist_norm < self.eps[0]) and (vel_norm < self.eps[1]) and (time_norm < self.eps[2]):
return True
else:
return False
def get_path(self, end_node):
path = []
node = end_node
while node.parent != None:
path.append(node.parent.state_time)
node = node.parent
path.append(node)
return path.reverse()
def wrap(self, target, source):
"""
Returns wrapped angle
"""
#if you are only checking angular difference
if len(target) == 3:
return np.arctan2(np.sin(target[0:3]-source[0:3]), np.cos(target[0:3]-source[0:3]))
else:
return np.append(np.arctan2(np.sin(target[0:3]-source[0:3]), np.cos(target[0:3]-source[0:3])), target[3:] - source[3:])
def simulate_system(self, state, input, time_step = 0.01):
"""
Simulate system. Only works on state, NOT state time
"""
#set arm position to x
self.arm.reset(q=state[0:3],dq=state[3:6])
#apply the control signal
self.arm.apply_torque(input,time_step)
#get the next step from the arm
xnext = np.append(np.copy(self.arm.q),np.copy(self.arm.dq))
return xnext
def search(self, max_samples = 10000):
"""
Perform TB-RRT Algorithm
:param max_samples: Number of samples until termination
"""
while (len(self.Tree) < max_samples):
xRand = self.sample()
xi = self.nearest_neighbor(xRand)
# xi = self.Tree[np.random.randint(len(self.Tree))]
xi_1, minDist, bestControl = self.steer(xi, xRand)
if self.is_reachable(xi_1):
xi_1_stateTime = np.append(xi_1, xi.state_time[-1] + self.dt)
if xi_1_stateTime[-1] > self.goal[-1]:
continue
xi_1_node = Node(xi_1_stateTime)
xi_1_node.u = bestControl
self.Tree.append(xi_1_node)
if len(self.Tree) % 10 == 0:
print(len(self.Tree))
self.add_edge(xi, xi_1_node, np.linalg.norm(bestControl))
if self.near_goal(xi_1_stateTime):
path = self.get_path(xi_1_node)
return path
if len(self.Tree) % 1000 == 0:
#TODO: This doesnt consider time...
nearest_to_goal = self.nearest_neighbor(self.goal[0:6])
longest_path = -np.inf
for node in self.Tree:
t = node.state_time[-1]
if t > longest_path:
longest_path = t
print(longest_path)
pdb.set_trace()
print("No path found")
"""
- "Nearest neighbor" is the state in the tree that requires the least amount of control effort to get to x_rand.
Questions: How do determine the control cost between two states? For example if x_i is moving in the opposite direction of x_rand, then what
is the cost to make it happen? If we assume instantaneous acceleration.
How do we reduce the the computational complexity? Pruning? Distance or velocity direction heuristics?
We probably don't need Rtree...
- When random samples are found, they are done in the position, velocity space. When they are stored in the tree,
they are tagged with the appropriate time step by setting it to the parent's time + delta_T
- Edge costs are the norm of controls applied when transitioning between two states. This edge should map to some
dictionary which contains the 6d vector of actual joint torques during this transitions
- only using their metric function for assessing proximity to goal
"""
if __name__=='__main__':
subfolder = 'three_link'
arm_name = 'arms.%s.%s' % (subfolder, 'arm')
arm_module = importlib.import_module(name=arm_name)
arm = arm_module.Arm(dt=0.02)
#state = theta (degrees), theta_dot, time
#Start position
start = np.array([0., 0., 0., 0., 0., 0., 0.])
#end position
end = np.array([0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.1]) # This is random...
#intialize Tree with Xo (starting point)
rrt = TBRRT(arm, start,end)
path = rrt.search(100000)import numpy as np
import control
import pdb
import matplotlib.pyplot as plt
import importlib
import scipy.linalg as sp_linalg
class Node:
def __init__(self, state_time = np.zeros(7, dtype=float)):
self.state_time = state_time
#lqr params
self.u = np.zeros(3)
self.parent = None
self.children = []
class TBRRT():
def __init__(self, arm, start, goal):
"""
:param start: robot arm starting position
:param goal: goal position
"""
self.arm = arm
self.Tree = []
self.edge_costs = {} # (parent, child) -> cost
self.start = start
self.goal = goal
# Store variables
self.dt = arm.dt
self.goal = goal
self.eps = np.array([np.deg2rad(2.8), 0.2, 0.03])
# Add start node to the tree
start_node = Node(start)
self.Tree.append(start_node)
self.min_state = np.array([0,0,0,-1,-1,-1])
self.max_state = np.array([2*np.pi,2*np.pi,2*np.pi,1,1,1])
self.maxUs = np.ones(3) * 500
self.minUs = -self.maxUs
def set_sample_region(self):
"""
create a directed joint space between the starting and ending nodes
"""
theta_delta = self.wrap(self.start[0:3], self.goal[0:3])
delta_signs = np.sign(self.goal[0:3] - self.start[0:3])
self.smart_region_min = self.start
self.smart_region_max = self.start + delta_signs * theta_delta
velocity_min = np.zeros(3,1)
for i in range(3):
def sample(self):
"""
Sample the joint space
"""
#compute the relevant range between the starting position and ending position that should be sampled
rand_state = np.random.uniform(self.min_state, self.max_state)
return rand_state
def compute_dist(self, s1, s2):
"""
Return the norm between 2 state-time vectors. Note to wrap the angle difference
"""
return sp_linalg.norm(self.wrap(s1, s2))
def nearest_neighbor(self, xRand):
"""
Find the node in the graph which requires the smallest magnitude of u to get to from the random state.
"""
# TODO: Make this more efficient?
#within a neighborhood of XRand, determine the lowest cost to go
minCost = np.inf
minNode = None
for node in self.Tree:
cost = self.compute_dist(node.state_time[0:6], xRand)
if cost < minCost:
minNode = node
minCost = cost
return minNode
def steer(self, xi, xRand, k = 10):
"""
Select ui to move from xi toward xrand
"""
#test k different controls
minDist = np.inf
bestControl = np.zeros(3)
xi_1 = None
for _ in range(k):
#smarter sampling in the right direction?
u_rand = np.random.uniform(self.minUs, self.maxUs)
nextState = self.simulate_system(xi.state_time[0:6], u_rand)
next_state_dist = self.compute_dist(nextState, xRand)
if next_state_dist < minDist:
minDist = next_state_dist
xi_1 = nextState
bestControl = u_rand
return xi_1, minDist, bestControl
def is_reachable(self, xi):
"""
Checks if xi is reachable, i.e. not self collisions or joint limits
"""
#TODO: Check if any of the links intersect...
return True
def add_edge(self, parent, child, ui):
parent.children.append(child)
child.parent = parent
self.edge_costs[(parent, child)] = ui
def near_goal(self, xi_1):
dist_norm = np.linalg.norm(xi_1[0:3] - self.goal[0:3])
vel_norm = np.linalg.norm(xi_1[3:7] - self.goal[3:7])
time_norm = np.linalg.norm(xi_1[-1] - self.goal[-1])
if (dist_norm < self.eps[0]) and (vel_norm < self.eps[1]) and (time_norm < self.eps[2]):
return True
else:
return False
def get_path(self, end_node):
path = []
node = end_node
while node.parent != None:
path.append(node.parent.state_time)
node = node.parent
path.append(node)
return path.reverse()
def wrap(self, target, source):
"""
Returns wrapped angle
"""
#if you are only checking angular difference
if len(target) == 3:
return np.arctan2(np.sin(target[0:3]-source[0:3]), np.cos(target[0:3]-source[0:3]))
else:
return np.append(np.arctan2(np.sin(target[0:3]-source[0:3]), np.cos(target[0:3]-source[0:3])), target[3:] - source[3:])
def simulate_system(self, state, input, time_step = 0.01):
"""
Simulate system. Only works on state, NOT state time
"""
#set arm position to x
self.arm.reset(q=state[0:3],dq=state[3:6])
#apply the control signal
self.arm.apply_torque(input,time_step)
#get the next step from the arm
xnext = np.append(np.copy(self.arm.q),np.copy(self.arm.dq))
return xnext
def search(self, max_samples = 10000):
"""
Perform TB-RRT Algorithm
:param max_samples: Number of samples until termination
"""
while (len(self.Tree) < max_samples):
xRand = self.sample()
xi = self.nearest_neighbor(xRand)
# xi = self.Tree[np.random.randint(len(self.Tree))]
xi_1, minDist, bestControl = self.steer(xi, xRand)
if self.is_reachable(xi_1):
xi_1_stateTime = np.append(xi_1, xi.state_time[-1] + self.dt)
if xi_1_stateTime[-1] > self.goal[-1]:
continue
xi_1_node = Node(xi_1_stateTime)
xi_1_node.u = bestControl
self.Tree.append(xi_1_node)
if len(self.Tree) % 10 == 0:
print(len(self.Tree))
self.add_edge(xi, xi_1_node, np.linalg.norm(bestControl))
if self.near_goal(xi_1_stateTime):
path = self.get_path(xi_1_node)
return path
if len(self.Tree) % 1000 == 0:
#TODO: This doesnt consider time...
nearest_to_goal = self.nearest_neighbor(self.goal[0:6])
longest_path = -np.inf
for node in self.Tree:
t = node.state_time[-1]
if t > longest_path:
longest_path = t
print(longest_path)
pdb.set_trace()
print("No path found")
"""
- "Nearest neighbor" is the state in the tree that requires the least amount of control effort to get to x_rand.
Questions: How do determine the control cost between two states? For example if x_i is moving in the opposite direction of x_rand, then what
is the cost to make it happen? If we assume instantaneous acceleration.
How do we reduce the the computational complexity? Pruning? Distance or velocity direction heuristics?
We probably don't need Rtree...
- When random samples are found, they are done in the position, velocity space. When they are stored in the tree,
they are tagged with the appropriate time step by setting it to the parent's time + delta_T
- Edge costs are the norm of controls applied when transitioning between two states. This edge should map to some
dictionary which contains the 6d vector of actual joint torques during this transitions
- only using their metric function for assessing proximity to goal
"""
if __name__=='__main__':
subfolder = 'three_link'
arm_name = 'arms.%s.%s' % (subfolder, 'arm')
arm_module = importlib.import_module(name=arm_name)
arm = arm_module.Arm(dt=0.02)
#state = theta (degrees), theta_dot, time
#Start position
start = np.array([0., 0., 0., 0., 0., 0., 0.])
#end position
end = np.array([0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.1]) # This is random...
#intialize Tree with Xo (starting point)
rrt = TBRRT(arm, start,end)
path = rrt.search(100000)