/
motionPlanner.py
381 lines (323 loc) · 14.9 KB
/
motionPlanner.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
from klampt import *
from klampt import vectorops,so3,se3,gldraw,trajectory,visualization,robotplanning
from klampt.cspace import CSpace,MotionPlan
from klampt.robotsim import Geometry3D
from klampt.robotcollide import WorldCollider
from klampt.robotcspace import ClosedLoopRobotCSpace
from baxter import *
import math
import os
import random
class LimbCSpace (CSpace):
"""Much of your code for HW4 will go here. This class
defines hooks for a motion planner. Primarily you must define a sampling
bound and feasibility test. See klampt/cspace.py for more details
on what else you can tweak.
The configuration space is the 7-DOF configuration space of a
single limb's joint angles.
Attributes:
- planner: the LimbPlanner object. Useful for calling the
get/set/check methods.
- limb: the moving limb
Attributes inherited from CSpace:
- bounds: configuration sampling bounds, a list of pairs indicating
the minimum/maximum range on each dimension.
- eps: edge collision tolerance
"""
def __init__(self,planner,limb):
CSpace.__init__(self)
self.planner = planner
self.limb = limb
#TODO: what Cartesian bounding box should the planner sample from?
self.robot = self.planner.robot
id_to_index = dict([(self.robot.link(i).getID(),i) for i in range(self.robot.numLinks())])
if limb=='left':
# self.limb_indices = left_arm_geometry_indices + left_hand_geometry_indices
self.limb_indices = self.planner.left_arm_indices
else:
# self.limb_indices = right_arm_geometry_indices + right_hand_geometry_indices
self.limb_indices = self.planner.right_arm_indices
qmin,qmax = self.robot.getJointLimits()
self.bound = [(qmin[i]-1e-6,qmax[i]+1e-6) for i in self.limb_indices]
self.eps = 1e-1
def feasible(self,q):
if len(q) != len(self.bound):
# print len(q), len(self.bound)
qnew = q[0:len(self.bound)]
q=qnew
for i in range(len(q)):
# print "q", i, q[i], self.bound[i][0], self.bound[i][1]
if (q[i] < self.bound[i][0]) :
print "Joint #",self.limb_indices[i],"(",q[i],") out of limits (min:",self.bound[i][0],")"
print "Changed joint value to its minimum"
q[i] = self.bound[i][0]
if (q[i] > self.bound[i][1]) :
print "Joint #",self.limb_indices[i],"(",q[i],") out of limits (max:",self.bound[i][1],")"
print "Changed joint value to its maximum"
q[i] = self.bound[i][1]
if not CSpace.feasible(self,q):
# print "LimbCSpace.feasible: Configuration is out of bounds"
return False
# cond = self.planner.check_limb_collision_free(self.limb,q)
# if not cond:
if not self.planner.check_limb_collision_free(self.limb,q):
# print "LimbCSpace.feasible: Configuration is in collision"
return False
return True
class LimbPlanner:
"""Much of your code for HW4 will go here.
Attributes:
- world: the WorldModel
- robot: the RobotModel
- knowledge: the KnowledgeBase objcet
- collider: a WorldCollider object (see the klampt.robotcollide module)
"""
def __init__(self,world,knowledge):
self.world = world
self.robot = world.robot(0)
self.knowledge = knowledge
self.collider = WorldCollider(world)
#these may be helpful
self.left_camera_link = self.robot.link(left_camera_link_name)
self.right_camera_link = self.robot.link(right_camera_link_name)
self.left_gripper_link = self.robot.link(left_gripper_link_name)
self.right_gripper_link = self.robot.link(right_gripper_link_name)
self.left_arm_links = [self.robot.link(i) for i in left_arm_link_names]
self.right_arm_links = [self.robot.link(i) for i in right_arm_link_names]
id_to_index = dict([(self.robot.link(i).getID(),i) for i in range(self.robot.numLinks())])
self.left_arm_indices = left_arm_geometry_indices + left_hand_geometry_indices
self.right_arm_indices = right_arm_geometry_indices + right_hand_geometry_indices
self.dynamic_objects = []
self.roadmap = ([],[])
self.limb_indices = []
self.pathToDraw = []
self.colMargin = 0
self.activeLimb = None
def set_limb_config(self,limb,limbconfig,q):
"""Helper: Sets the 7-DOF configuration of the given limb in
q. Other DOFs are not touched."""
assert len(q) == self.robot.numLinks()
if limb=='left':
for (i,v) in zip(self.left_arm_indices,limbconfig):
q[i] = v
else:
for (i,v) in zip(self.right_arm_indices,limbconfig):
q[i] = v
def get_limb_config(self,q,limb):
"""Helper: Gets the 7-DOF configuration of the given limb given
a full-robot configuration q"""
qlimb = [0.0]*len(self.left_arm_indices)
if limb=='left':
qlimb = [0.0]*len(self.left_arm_indices)
for (i,j) in enumerate(self.left_arm_indices):
qlimb[i] = q[j]
else:
qlimb = [0.0]*len(self.right_arm_indices)
for (i,j) in enumerate(self.right_arm_indices):
qlimb[i] = q[j]
return qlimb
def check_collision_free(self,limb):
"""Checks whether the given limb is collision free at the robot's
current configuration"""
armfilter = None
if limb=='left':
collindices = set(left_arm_geometry_indices+left_hand_geometry_indices)
# collindices = set(self.left_arm_indices)
else:
collindices = set(right_arm_geometry_indices+right_hand_geometry_indices)
armfilter = lambda x:isinstance(x,RobotModelLink) and (x.index in collindices)
ignoreList = ["Amazon_Picking_Shelf", "bin_"]
ignoreList = '\t'.join(ignoreList)
spatulaIgnoreList = [57]
#check with objects in world model
for o1,o2 in self.collider.collisionTests(armfilter,lambda x:True): # NOTE: what is bb_reject??
# print "Collision Test: Collision between",o1[0].getName(),o2[0].getName()
if o1[0].getName()[0:3] in ignoreList and o2[0].index in spatulaIgnoreList:
# print "ignoring collision between shelf and spautla"
continue
if o2[0].getName()[0:3] in ignoreList and o1[0].index in spatulaIgnoreList:
# print "ignoring collision between shelf and spautla"
continue
if o1[0].getName()[0:3] in ignoreList:
for obj in self.dynamic_objects:
assert obj.info.geometry != None
if o1[1].collides(obj.info.geometry):
continue
if o2[0].getName()[0:3] in ignoreList:
for obj in self.dynamic_objects:
assert obj.info.geometry != None
if o1[1].collides(obj.info.geometry):
continue
if o1[1].collides(o2[1]):
# print "Collision between",o1[0].getName(),o2[0].getName()
return False
return True
def rebuild_dynamic_objects(self):
# self.dynamic_objects = []
# #check with objects in knowledge
# for (k,objList) in self.knowledge.bin_contents.iteritems():
# if objList == None:
# #not sensed
# continue
# for item in objList:
# assert item.info.geometry != None
# item.info.geometry.setCurrentTransform(*item.xform)
# self.dynamic_objects.append(item)
return
def check_limb_collision_free(self,limb,limbconfig):
"""Checks whether the given 7-DOF limb configuration is collision
free, keeping the rest of self.robot fixed."""
q = self.robot.getConfig()
self.set_limb_config(limb,limbconfig,q)
self.robot.setConfig(q)
return self.check_collision_free(limb)
def plan_limb(self,limb,limbstart,limbgoal, printer=True, iks = None):
"""Returns a 7-DOF milestone path for the given limb to move from the
start to the goal, or False if planning failed"""
self.rebuild_dynamic_objects()
# NOTE: Not sure, but I think this is what's happening
# Need to reset pathToDraw here because the MyGLViewer.draw() is called
# concurrently, it uses an old path (ex. of left arm) while using the
# new limb (ex. right limb) for drawing the trajectory. This throws an
# Index-Out-of-Range exception for drawing the path
self.pathToDraw = []
# NOTE:
cspace = LimbCSpace(self,limb)
if iks != None:
print "Initializing ClosedLoopCSPace"
cspace = ClosedLoopCSpaceTest(self,limb,iks)
if not cspace.feasible(limbstart):
print " Start configuration is infeasible!"
return 1
if not cspace.feasible(limbgoal):
print " Goal configuration is infeasible!"
return 2
MotionPlan.setOptions(type="rrt", perturbationRadius = 1, connectionThreshold=2, bidirectional = True, shortcut = True, restart=True)
plan = MotionPlan(cspace)
plan.setEndpoints(limbstart,limbgoal)
# maxPlanIters = 20
# maxSmoothIters = 100
maxPlanIters = 10
maxSmoothIters = 100
print " Planning.",
for iters in xrange(maxPlanIters):
# print iters
if limb=='left':
self.limb_indices = self.left_arm_indices
self.activeLimb = 'left'
else:
self.limb_indices = self.right_arm_indices
self.activeLimb = 'right'
self.roadmap = plan.getRoadmap()
V,E =self.roadmap
print ".",
plan.planMore(10) # 100
path = plan.getPath()
if path != None:
if printer:
print "\n Found a path on iteration",iters
if len(path) > 2:
print " Smoothing path"
# plan.planMore(min(maxPlanIters-iters,maxSmoothIters))
plan.planMore(maxSmoothIters)
path = plan.getPath()
cspace.close()
plan.close()
self.pathToDraw = path
return path
cspace.close()
plan.close()
if printer:
print " No path found"
return False
def plan(self,start,goal,limb,printer=True, iks = None, ignoreColShelfSpatula = True):
"""Plans a motion for the robot to move from configuration start
to configuration goal. By default, moves the left arm first,
then the right. To move the right first, set the 'order' argument
to ['right','left']"""
limbstart = {}
limbgoal = {}
# for l in ['left','right']:
l =limb
limbstart[l] = self.get_limb_config(start,l)
limbgoal[l] = self.get_limb_config(goal,l)
path = [start]
curconfig = start[:]
diff = sum((a-b)**2 for a,b in zip(limbstart[l],limbgoal[l]))
if diff > 1e-8:
if printer:
print "< Planning for limb",l,">"
# print " Euclidean distance:",math.sqrt(diff)
self.robot.setConfig(curconfig)
#do the limb planning
if not ignoreColShelfSpatula:
self.left_arm_indices = left_arm_geometry_indices + left_hand_geometry_indices + [55,56,57]
else:
self.left_arm_indices = left_arm_geometry_indices + left_hand_geometry_indices
# print " Left arm links", self.left_arm_indices
if iks == None:
limbpath = self.plan_limb(l,limbstart[l],limbgoal[l],printer=printer, iks=iks)
else:
trajectory = self.plan_closedLoop(start,goal,iks=iks)
return trajectory
if limbpath == 1 or limbpath == 2 or limbpath == False:
if printer:
print " Failed to plan for limb",l,"\n"
return limbpath
if printer:
print " Planned successfully for limb",l, "\n"
#concatenate whole body path
for qlimb in limbpath[1:]:
q = path[-1][:]
self.set_limb_config(l,qlimb,q)
path.append(q)
self.set_limb_config(l,limbgoal[l],curconfig)
return path
def plan_closedLoop(self,qstart,qgoal,iks,printer=False):
if printer:
print "starting config: ", qstart
print "goal config: ", qgoal
self.world.terrain(0).geometry().setCollisionMargin(0.05)
cspace = robotcspace.ClosedLoopRobotCSpace(self.robot, iks, self.collider)
cspace.eps = 1e-3
cspace.setup()
configs=[]
configs.append(qstart)
configs.append(qgoal)
configs[0] = cspace.solveConstraints(configs[0])
configs[1] = cspace.solveConstraints(configs[1])
settings = { 'type':"sbl", 'perturbationRadius':0.5, 'bidirectional':1, 'shortcut':1, 'restart':1, 'restartTermCond':"{foundSolution:1,maxIters:1000}" }
wholepath = [configs[0]]
for i in range(len(configs)-1):
#this code uses the robotplanning module's convenience functions
self.robot.setConfig(configs[i])
plan = robotplanning.planToConfig(self.world,self.robot,configs[i+1],
movingSubset='all',
**settings)
if plan is None:
return False
print " Planning..."
keepPlanning = True
while keepPlanning:
plan.planMore(500)
#this code just gives some debugging information. it may get expensive
# V,E = plan.getRoadmap()
# self.roadmap = plan.getRoadmap()
# print " ", len(V),"feasible milestones sampled,",len(E),"edges connected"
path = plan.getPath()
if path is None or len(path)==0:
print "Failed to plan path"
#debug some sampled configurations
# print V[0:max(10,len(V))]
# return False
else:
keepPlanning = False
self.pathToDraw = path
#the path is currently a set of milestones: discretize it so that it stays near the contact surface
path = cspace.discretizePath(path,epsilon=1e-2)
# path = cspace.discretizePath(path,epsilon=1e-4)
wholepath += path[1:]
#to be nice to the C++ module, do this to free up memory
plan.space.close()
plan.close()
return wholepath