compliant_trajectories.py
Go to the documentation of this file.
00001 #
00002 # Copyright (c) 2009, Georgia Tech Research Corporation
00003 # All rights reserved.
00004 # 
00005 # Redistribution and use in source and binary forms, with or without
00006 # modification, are permitted provided that the following conditions are met:
00007 #     * Redistributions of source code must retain the above copyright
00008 #       notice, this list of conditions and the following disclaimer.
00009 #     * Redistributions in binary form must reproduce the above copyright
00010 #       notice, this list of conditions and the following disclaimer in the
00011 #       documentation and/or other materials provided with the distribution.
00012 #     * Neither the name of the Georgia Tech Research Corporation nor the
00013 #       names of its contributors may be used to endorse or promote products
00014 #       derived from this software without specific prior written permission.
00015 # 
00016 # THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
00017 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
00018 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
00019 # DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
00020 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
00021 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
00022 # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
00023 # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
00024 # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
00025 # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00026 #
00027 
00028 # Author: Advait Jain
00029 
00030 import m3.toolbox as m3t
00031 
00032 import hokuyo.hokuyo_scan as hs
00033 import tilting_hokuyo.tilt_hokuyo_servo as ths
00034 import mekabot.hrl_robot as hr
00035 import hrl_lib.util as ut, hrl_lib.transforms as tr
00036 import util as uto
00037 import camera
00038 
00039 import sys, time, os, optparse
00040 import math, numpy as np
00041 import copy
00042 
00043 import arm_trajectories as at
00044 
00045 from opencv.cv import *
00046 from opencv.highgui import *
00047 
00048 
00049 from threading import RLock
00050 import threading
00051 
00052 hook_3dprint_angle = math.radians(20-2.54)
00053 
00054 class CompliantMotionGenerator(threading.Thread):
00055     ''' a specific form of compliant motion.
00056         class name might be inappropriate.
00057     '''
00058     def __init__(self):
00059         # stiffness in Nm/rad: [20,50,15,25]
00060         self.settings_r = hr.MekaArmSettings(stiffness_list=[0.1939,0.6713,0.748,0.7272,0.8])
00061 #        self.settings_r = hr.MekaArmSettings(stiffness_list=[0.2,1.0,1.0,0.4,0.8])
00062 
00063         self.settings_stiff = hr.MekaArmSettings(stiffness_list=[0.8,1.0,1.0,1.0,0.8])
00064         self.firenze = hr.M3HrlRobot(connect=True,right_arm_settings=self.settings_stiff)
00065 
00066         self.hok = hs.Hokuyo('utm',0,flip=True)
00067         self.thok = ths.tilt_hokuyo('/dev/robot/servo0',5,self.hok,l1=0.,l2=-0.055)
00068 
00069         self.cam = camera.Camera('mekabotUTM')
00070         self.set_camera_settings()
00071 
00072         self.fit_circle_lock = RLock()
00073         threading.Thread.__init__(self)
00074 
00075     def run(self):
00076         self.circle_estimator()
00077 
00078     def stop(self):
00079         self.run_fit_circle_thread = False
00080         self.firenze.stop()
00081 
00082     ## pose the arm by moving the end effector to the hookable location.
00083     # @param hook_angle - RADIANS(0, -90, 90 etc.)
00084     # 0 - horizontal, -pi/2 hook points up, +pi/2 hook points down
00085     def pose_arm(self,hook_angle):
00086         print 'press ENTER to pose the robot.'
00087         k=m3t.get_keystroke()
00088 
00089         if k!='\r':
00090             print 'You did not press ENTER.'
00091             return
00092 
00093 #        settings_r_orig = copy.copy(self.firenze.arm_settings['right_arm'])
00094         settings_torque_gc = hr.MekaArmSettings(stiffness_list=[0.,0.,0.,0.,0.],control_mode='torque_gc')
00095         self.firenze.set_arm_settings(settings_torque_gc,None)
00096         self.firenze.step()
00097         print 'hit ENTER to end posing, something else to exit'
00098         k=m3t.get_keystroke()
00099 
00100         p = self.firenze.end_effector_pos('right_arm')
00101 
00102         q = self.firenze.get_joint_angles('right_arm')
00103 #        self.firenze.set_arm_settings(settings_r_orig,None)
00104         self.firenze.set_arm_settings(self.settings_stiff,None)
00105         self.firenze.set_joint_angles('right_arm',q)
00106         self.firenze.step()
00107         self.firenze.set_joint_angles('right_arm',q)
00108         self.firenze.step()
00109 
00110         rot_mat = tr.Rz(hook_angle-hook_3dprint_angle)*tr.Ry(math.radians(-90))
00111         self.firenze.go_cartesian('right_arm',p,rot_mat,speed=0.1)
00112 
00113         print 'hit ENTER after making finer adjustment, something else to exit'
00114         k=m3t.get_keystroke()
00115         p = self.firenze.end_effector_pos('right_arm')
00116         q = self.firenze.get_joint_angles('right_arm')
00117         self.firenze.set_joint_angles('right_arm',q)
00118         self.firenze.step()
00119 
00120     def set_camera_settings(self):
00121         self.cam.set_frame_rate(30)
00122         self.cam.set_auto()
00123         self.cam.set_gamma(1)
00124         self.cam.set_whitebalance(r_val=512,b_val=544)
00125 
00126     def compliant_motion(self,equi_pt_generator,time_step,rapid_call_func=None):
00127         ''' equi_pt_generator: function that returns stop,q
00128                                  q: list of 7 joint angles
00129                                  stop: string which is '' for compliant motion to continue
00130             rapid_call_func: called in the time between calls to the equi_pt_generator
00131                              can be used for logging, safety etc.
00132                              returns stop
00133                                  stop: string which is '' for compliant motion to continue
00134             time_step: time between successive calls to equi_pt_generator
00135 
00136             returns stop (the string which has the reason why the compliant motion stopped.)
00137         '''
00138         
00139         stop,q = equi_pt_generator()
00140         while stop == '':
00141             self.firenze.set_joint_angles('right_arm',q)
00142             t1 = time.time()
00143             t_end = t1+time_step
00144             while t1<t_end:
00145                 self.firenze.step()
00146                 if rapid_call_func != None:
00147                     stop = rapid_call_func()
00148                     if stop != '':
00149                         break
00150                 t1 = time.time()
00151 
00152             if stop != '':
00153                 break
00154             stop,q = equi_pt_generator()
00155         return stop
00156 
00157     ## log the joint angles, equi pt joint angles and forces.
00158     def log_state(self):
00159         t_now = time.time()
00160         q_now = self.firenze.get_joint_angles('right_arm')
00161         qdot_now = self.firenze.get_joint_velocities('right_arm')
00162 
00163         tau_now = self.firenze.get_joint_torques('right_arm')
00164         self.jt_torque_trajectory.q_list.append(tau_now)
00165         self.jt_torque_trajectory.time_list.append(t_now)
00166 
00167         self.pull_trajectory.q_list.append(q_now)
00168         self.pull_trajectory.qdot_list.append(qdot_now)
00169         self.pull_trajectory.time_list.append(t_now)
00170 
00171         #self.eq_pt_trajectory.p_list.append(self.eq_pt_cartesian.A1.tolist())
00172         self.eq_pt_trajectory.q_list.append(self.q_guess) # see equi_pt_generator - q_guess is the config for the eq point.
00173         self.eq_pt_trajectory.time_list.append(t_now)
00174     
00175         wrist_force = self.firenze.get_wrist_force('right_arm',base_frame=True)
00176         self.force_trajectory.f_list.append(wrist_force.A1.tolist())
00177         self.force_trajectory.time_list.append(t_now)
00178 
00179     def common_stopping_conditions(self):
00180         stop = ''
00181         if self.q_guess == None:
00182             stop = 'IK fail'
00183 
00184         wrist_force = self.firenze.get_wrist_force('right_arm',base_frame=True)
00185         mag = np.linalg.norm(wrist_force)
00186         if mag > self.eq_force_threshold:
00187             stop = 'force exceed'
00188 
00189         if mag < 1.2 and self.hooked_location_moved:
00190             if (self.prev_force_mag - mag) > 10.:
00191                 stop = 'slip: force step decrease and below thresold.'
00192             else:
00193                 self.slip_count += 1
00194         else:
00195             self.slip_count = 0
00196 
00197         if self.slip_count == 4:
00198             stop = 'slip: force below threshold for too long.'
00199 
00200         curr_pos = self.firenze.FK('right_arm',self.pull_trajectory.q_list[-1])
00201         if curr_pos[0,0]<0.27 and curr_pos[1,0]>-0.2:
00202             stop = 'danger of self collision'
00203 
00204         return stop
00205 
00206     def update_eq_point(self,motion_vec,step_size):
00207         next_pt = self.eq_pt_cartesian + step_size * motion_vec
00208         rot_mat = self.eq_IK_rot_mat
00209 #        self.q_guess[1] += math.radians(1)
00210         q_eq = self.firenze.IK('right_arm',next_pt,rot_mat,self.q_guess)
00211         self.eq_pt_cartesian = next_pt
00212         self.q_guess = q_eq
00213         return q_eq
00214 
00215     def circle_estimator(self):
00216         self.run_fit_circle_thread = True
00217         print 'Starting the circle estimating thread.'
00218 
00219         while self.run_fit_circle_thread:
00220             self.fit_circle_lock.acquire()
00221             if len(self.cartesian_pts_list)==0:
00222                 self.fit_circle_lock.release()
00223                 continue
00224             pts_2d = (np.matrix(self.cartesian_pts_list).T)[0:2,:]
00225             self.fit_circle_lock.release()
00226 
00227             rad = self.rad_guess
00228             start_pos = self.firenze.FK('right_arm',self.pull_trajectory.q_list[0])
00229             rad,cx,cy = at.fit_circle(rad,start_pos[0,0],start_pos[1,0]-rad,pts_2d,method='fmin_bfgs',verbose=False)
00230             rad = ut.bound(rad,3.0,0.1)
00231 
00232             self.fit_circle_lock.acquire()
00233             self.cx = cx
00234             self.cy = cy
00235     #        self.rad = rad
00236             self.fit_circle_lock.release()
00237 
00238         print 'Ended the circle estimating thread.'
00239 
00240 
00241     ## constantly update the estimate of the kinematics and move the
00242     # equilibrium point along the tangent of the estimated arc, and
00243     # try to keep the radial force constant.
00244     def equi_pt_generator_control_radial_force(self):
00245         self.log_state()
00246         q_eq = self.update_eq_point(self.eq_motion_vec,0.01)
00247         stop = self.common_stopping_conditions()
00248 
00249         wrist_force = self.firenze.get_wrist_force('right_arm',base_frame=True)
00250         mag = np.linalg.norm(wrist_force)
00251 
00252         start_pos = self.firenze.FK('right_arm',self.pull_trajectory.q_list[0])
00253         curr_pos = self.firenze.FK('right_arm',self.pull_trajectory.q_list[-1])
00254         if (start_pos[0,0]-curr_pos[0,0])>0.09 and self.hooked_location_moved==False:
00255             # change the force threshold once the hook has started pulling.
00256             self.hooked_location_moved = True
00257             self.eq_force_threshold = ut.bound(mag+30.,20.,80.)
00258             self.piecewise_force_threshold = ut.bound(mag+5.,0.,80.)
00259             
00260         self.fit_circle_lock.acquire()
00261         self.cartesian_pts_list.append(curr_pos.A1.tolist())
00262         self.fit_circle_lock.release()
00263 
00264         # find tangential direction.
00265         radial_vec = curr_pos[0:2]-np.matrix([self.cx,self.cy]).T
00266         radial_vec = radial_vec/np.linalg.norm(radial_vec)
00267         tan_x,tan_y = -radial_vec[1,0],radial_vec[0,0]
00268         
00269         if tan_x >0.:
00270             tan_x = -tan_x
00271             tan_y = -tan_y
00272 
00273         self.eq_motion_vec = np.matrix([tan_x,tan_y,0.]).T
00274 
00275         f_vec = -1*np.array([wrist_force[0,0],wrist_force[1,0]])
00276         f_rad_mag = np.dot(f_vec,radial_vec.A1)
00277         #if f_rad_mag>10.:
00278         if f_rad_mag>5.:
00279             self.eq_motion_vec[0:2] -= radial_vec/2. * self.hook_maintain_dist_plane/0.05
00280         else:
00281             self.eq_motion_vec[0:2] += radial_vec/2. * self.hook_maintain_dist_plane/0.05
00282 
00283         self.prev_force_mag = mag
00284         return stop,q_eq
00285 
00286     ## moves eq point along the -x axis.
00287     def equi_pt_generator_line(self):
00288         self.log_state()
00289         #q_eq = self.update_eq_point(self.eq_motion_vec,0.005)
00290         q_eq = self.update_eq_point(self.eq_motion_vec,0.010)
00291         stop = self.common_stopping_conditions()
00292 
00293         wrist_force = self.firenze.get_wrist_force('right_arm',base_frame=True)
00294         mag = np.linalg.norm(wrist_force)
00295 
00296         start_pos = self.firenze.FK('right_arm',self.pull_trajectory.q_list[0])
00297         curr_pos = self.firenze.FK('right_arm',self.pull_trajectory.q_list[-1])
00298         if (start_pos[0,0]-curr_pos[0,0])>0.09 and self.hooked_location_moved==False:
00299             # change the force threshold once the hook has started pulling.
00300             self.hooked_location_moved = True
00301             self.eq_force_threshold = ut.bound(mag+15.,20.,80.)
00302             
00303         self.prev_force_mag = mag
00304         return stop,q_eq
00305 
00306     ## move the end effector to properly hook onto the world
00307     # direction of motion governed by the hook angle.
00308     # @param hook_angle - angle of hook in RADIANS (see pose_arm or pull for details.)
00309     def get_firm_hook(self, hook_angle):
00310         rot_mat = tr.Rz(hook_angle-hook_3dprint_angle)*tr.Ry(math.radians(-90))
00311 
00312         # move in the +x until contact.
00313         vec = np.matrix([0.08,0.,0.]).T
00314         self.firenze.move_till_hit('right_arm',vec=vec,force_threshold=2.0,rot=rot_mat,
00315                                    speed=0.05)
00316 
00317         # now move in direction of hook.
00318         vec = tr.rotX(-hook_angle) * np.matrix([0.,0.05,0.]).T
00319         self.firenze.move_till_hit('right_arm',vec=vec,force_threshold=5.0,rot=rot_mat,
00320                                    speed=0.05,bias_FT=False)
00321         self.firenze.set_arm_settings(self.settings_r,None)
00322         self.firenze.step()
00323 
00324     def pull(self,hook_angle,force_threshold,use_utm=False,use_camera=False,strategy='line_neg_x',
00325              pull_loc=None, info_string=''):
00326         ''' force_threshold - max force at which to stop pulling.
00327             hook_angle - radians(0, -90, 90 etc.)
00328                          0 - horizontal, -pi/2 hook points up, +pi/2 hook points down
00329             use_utm - to take 3D scans or not.
00330             use_camera - to take pictures from the camera or not.
00331             strategy - 'line_neg_x': move eq point along -x axis.
00332                        'piecewise_linear': try and estimate circle and move along it.
00333                        'control_radial_force': try and keep the radial force constant
00334                        'control_radial_dist'
00335             pull_loc - 3x1 np matrix of location for pulling. If None then arm will go into
00336                        gravity comp and user can show the location.
00337             info_string - string saved with key 'info' in the pkl.
00338         '''
00339         if use_utm:
00340             self.firenze.step()
00341             armconfig1 = self.firenze.get_joint_angles('right_arm')
00342             plist1,slist1 = self.scan_3d()
00343 
00344         if use_camera:
00345             cam_plist1, cam_imlist1 = self.image_region()
00346         else:
00347             cam_plist1,cam_imlist1 = None,None
00348 
00349         rot_mat = tr.Rz(hook_angle-hook_3dprint_angle)*tr.Ry(math.radians(-90))
00350 
00351         if pull_loc == None:
00352             self.pose_arm(hook_angle)
00353             pull_loc = self.firenze.end_effector_pos('right_arm')
00354             ut.save_pickle(pull_loc,'pull_loc_'+info_string+'_'+ut.formatted_time()+'.pkl')
00355         else:
00356             pt1 = copy.copy(pull_loc)
00357             pt1[0,0] = pt1[0,0]-0.1
00358             print 'pt1:', pt1.A1
00359             print 'pull_loc:', pull_loc.A1
00360             self.firenze.go_cartesian('right_arm',pt1,rot_mat,speed=0.2)
00361             self.firenze.go_cartesian('right_arm',pull_loc,rot_mat,speed=0.07)
00362 
00363 
00364         print 'press ENTER to pull'
00365         k=m3t.get_keystroke()
00366         if k != '\r':
00367             return
00368 
00369         time_dict = {}
00370         time_dict['before_hook'] = time.time()
00371         print 'first getting a good hook'
00372         self.get_firm_hook(hook_angle)
00373         time.sleep(0.5)
00374         time_dict['before_pull'] = time.time()
00375 
00376         print 'pull begins'
00377         stiffness_scale = self.settings_r.stiffness_scale
00378         vec = tr.rotX(-hook_angle) * np.matrix([0.,0.05/stiffness_scale,0.]).T
00379         self.keep_hook_vec = vec
00380         self.hook_maintain_dist_plane = np.dot(vec.A1,np.array([0.,1.,0.]))
00381         self.eq_pt_cartesian = self.firenze.end_effector_pos('right_arm') + vec
00382         q_eq = self.firenze.IK('right_arm',self.eq_pt_cartesian,rot_mat)
00383         self.firenze.go_jointangles('right_arm',q_eq,speed=math.radians(30))
00384         self.q_guess = q_eq
00385 
00386 #        self.q_guess = self.firenze.get_joint_angles('right_arm')
00387 
00388         self.pull_trajectory = at.JointTrajectory()
00389         self.jt_torque_trajectory = at.JointTrajectory()
00390         self.eq_pt_trajectory = at.JointTrajectory()
00391         self.force_trajectory = at.ForceTrajectory()
00392 
00393         self.firenze.step()
00394         start_config = self.firenze.get_joint_angles('right_arm')
00395 
00396         self.eq_IK_rot_mat = rot_mat # for equi pt generators.
00397         self.eq_force_threshold = force_threshold
00398         self.hooked_location_moved = False # flag to indicate when the hooking location started moving.
00399         self.prev_force_mag = np.linalg.norm(self.firenze.get_wrist_force('right_arm'))
00400         self.eq_motion_vec = np.matrix([-1.,0.,0.]).T
00401         self.slip_count = 0
00402         if strategy == 'line_neg_x':
00403             result = self.compliant_motion(self.equi_pt_generator_line,0.025)
00404         elif strategy == 'control_radial_force':
00405             self.cartesian_pts_list = []
00406             self.piecewise_force_threshold = force_threshold
00407             self.rad_guess = 1.0
00408             self.cx = 0.6
00409             self.cy = -self.rad_guess
00410             self.start() # start the circle estimation thread
00411             result = self.compliant_motion(self.equi_pt_generator_control_radial_force,0.025)
00412         else:
00413             raise RuntimeError('unknown pull strategy: ', strategy)
00414 
00415         if result == 'slip: force step decrease' or result == 'danger of self collision':
00416             self.firenze.motors_off()
00417             print 'powered off the motors.'
00418 
00419         print 'Compliant motion result:', result
00420         print 'Original force threshold:', force_threshold
00421         print 'Adapted force threshold:', self.eq_force_threshold
00422 
00423         time_dict['after_pull'] = time.time()
00424 
00425         d = {'actual': self.pull_trajectory, 'eq_pt': self.eq_pt_trajectory,
00426              'force': self.force_trajectory, 'torque': self.jt_torque_trajectory,
00427              'stiffness': self.firenze.arm_settings['right_arm'],
00428              'info': info_string, 'force_threshold': force_threshold,
00429              'eq_force_threshold': self.eq_force_threshold, 'hook_angle':hook_angle,
00430              'result':result,'strategy':strategy,'time_dict':time_dict}
00431 
00432         self.firenze.step()
00433         armconfig2 = self.firenze.get_joint_angles('right_arm')
00434         if use_utm:
00435             plist2,slist2 = self.scan_3d()
00436             d['start_config']=start_config
00437             d['armconfig1']=armconfig1
00438             d['armconfig2']=armconfig2
00439             d['l1'],d['l2']=0.,-0.055
00440             d['scanlist1'],d['poslist1']=slist1,plist1
00441             d['scanlist2'],d['poslist2']=slist2,plist2
00442 
00443         d['cam_plist1']=cam_plist1
00444         d['cam_imlist1']=cam_imlist1
00445 
00446         ut.save_pickle(d,'pull_trajectories_'+d['info']+'_'+ut.formatted_time()+'.pkl')
00447 
00448     def scan_3d(self):
00449         tilt_angles = (math.radians(20),math.radians(70))
00450         pos_list,scan_list = self.thok.scan(tilt_angles,speed=math.radians(10),save_scan=False)
00451         return pos_list,scan_list
00452 
00453     def save_frame(self):
00454         cvim = self.cam.get_frame()
00455         cvSaveImage('im_'+ut.formatted_time()+'.png',cvim)
00456 
00457     def image_region(self):
00458         ''' takes images from the UTM camera at different angles.
00459             returns list of servo angles, list of images.
00460             images are numpy images. so that they can be pickled.
00461         '''
00462         im_list = []
00463         p_list = []
00464 
00465         for cmd_ang in [0,30,45]:
00466             self.thok.servo.move_angle(math.radians(cmd_ang))
00467             cvim = self.cam.get_frame()
00468             cvim = self.cam.get_frame()
00469             im_list.append(uto.cv2np(cvim,format='BGR'))
00470             p_list.append(self.thok.servo.read_angle())
00471 
00472         self.thok.servo.move_angle(math.radians(0))
00473         return p_list,im_list
00474 
00475 def test_IK(rot_mat):
00476     ''' try out the IK at a number of different cartesian
00477         points in the workspace, with the given rotation
00478         matrix for the end effector.
00479     '''
00480     print 'press ENTER to start.'
00481     k=m3t.get_keystroke()
00482     while k=='\r':
00483         p = firenze.end_effector_pos('right_arm')
00484         firenze.go_cartesian('right_arm',p,rot_mat,speed=0.1)
00485         firenze.step()
00486         print 'press ENTER to save joint angles.'
00487         k=m3t.get_keystroke()
00488         if k == '\r':
00489             firenze.step()
00490             q = firenze.get_joint_angles('right_arm')
00491             ut.save_pickle(q,'arm_config_'+ut.formatted_time()+'.pkl')
00492         print 'press ENTER for next IK test. something else to exit.'
00493         k=m3t.get_keystroke()
00494 
00495 def test_elbow_angle():
00496     firenze = hr.M3HrlRobot(connect=False)
00497     hook_3dprint_angle = math.radians(20-2.54)
00498     rot_mat = tr.Rz(math.radians(-90.)-hook_3dprint_angle)*tr.Ry(math.radians(-90))
00499 
00500     x_list = [0.55,0.45,0.35]
00501     y = -0.2
00502     z = -0.23
00503     for x in x_list:
00504         p0 = np.matrix([x,y,z]).T
00505         q = firenze.IK('right_arm',p0,rot_mat)
00506 #        q[1] = math.radians(15)
00507 #        q = firenze.IK('right_arm',p0,rot_mat,q_guess = q)
00508         elbow_angle = firenze.elbow_plane_angle('right_arm',q)
00509         print '---------------------------------------'
00510         print 'ee position:', p0.A1
00511 #        print 'joint angles:', q
00512         print 'elbow_angle:', math.degrees(elbow_angle)
00513 
00514 
00515 
00516 if __name__=='__main__':
00517 
00518     p = optparse.OptionParser()
00519     p.add_option('--ik_single_pos', action='store_true', dest='ik_single_pos',
00520                  help='test IK at a single position.')
00521     p.add_option('--ik_test', action='store_true', dest='ik_test',
00522                  help='test IK in a loop.')
00523     p.add_option('--pull', action='store_true', dest='pull',
00524                  help='pull with hook up (name will be changed later).')
00525     p.add_option('--pull_pos', action='store', type='string', dest='pull_pos_pkl',
00526                  help='pkl file with 3D coord of point to start pulling at.', default='')
00527     p.add_option('--firm_hook', action='store_true', dest='firm_hook',
00528                  help='test getting a firm hook on things.')
00529     p.add_option('--scan', action='store_true', dest='scan',
00530                  help='take and save 3D scans. specify --pull also.')
00531     p.add_option('--camera', action='store_true', dest='camera',
00532                  help='take and save images from UTM camera. specify --pull also.')
00533     p.add_option('--ha', action='store', dest='ha',type='float',
00534                  default=None,help='hook angle (degrees).')
00535     p.add_option('--ft', action='store', dest='ft',type='float',
00536                  default=None,help='force threshold (Newtons).')
00537     p.add_option('--info', action='store', type='string', dest='info_string',
00538                  help='string to save in the pkl log.', default='')
00539     p.add_option('--ve', action='store_true', dest='ve',
00540                  help='vary experiment. (vary stiffness settings and repeatedly pull)')
00541     p.add_option('--eaf', action='store_true', dest='eaf',
00542                  help='test elbow angle finding with the horizontal plane.')
00543 
00544     opt, args = p.parse_args()
00545     ik_single_pos_flag = opt.ik_single_pos
00546     test_ik_flag = opt.ik_test
00547     pull_flag = opt.pull
00548     pull_pos_pkl = opt.pull_pos_pkl
00549     firm_hook_flag = opt.firm_hook
00550     scan_flag = opt.scan
00551     camera_flag = opt.camera
00552     ha = opt.ha
00553     ft = opt.ft
00554     info_string = opt.info_string
00555     vary_expt_flag = opt.ve
00556     elbow_angle_flag = opt.eaf
00557 
00558     try:
00559         if vary_expt_flag:
00560             stiff_scale_list = [1.0,1.2,0.8]
00561             if pull_pos_pkl != '':
00562                 pull_loc = ut.load_pickle(pull_pos_pkl)
00563             else:
00564                 raise RuntimeError('Need to specify a pull_pos with vary_expt')
00565 
00566             cmg = CompliantMotionGenerator()
00567             print 'hit a key to power up the arms.'
00568             k=m3t.get_keystroke()
00569             cmg.firenze.power_on()
00570                 
00571             #for strategy in ['line_neg_x','control_radial_force']:
00572             for strategy in ['line_neg_x','control_radial_dist','control_radial_force']:
00573             #for strategy in ['line_neg_x']:
00574             #for strategy in ['piecewise_linear']:
00575                 for s_scale in stiff_scale_list:
00576                     cmg.settings_r.stiffness_scale = s_scale
00577                     cmg.pull(math.radians(ha), ft,use_utm=scan_flag,use_camera=camera_flag,
00578                              strategy=strategy,pull_loc=pull_loc,info_string=info_string)
00579                     cmg.firenze.maintain_configuration()
00580                     cmg.firenze.motors_on()
00581                     cmg.firenze.set_arm_settings(cmg.settings_stiff,None)
00582                     time.sleep(0.5)
00583 
00584             print 'hit  a key to end everything'
00585             k=m3t.get_keystroke()
00586             cmg.firenze.stop()
00587 
00588             sys.exit()
00589 
00590         if pull_flag or firm_hook_flag:
00591             if ha == None:
00592                 print 'please specify hook angle (--ha)'
00593                 print 'Exiting...'
00594                 sys.exit()
00595 
00596             if ft == None and pull_flag:
00597                 print 'please specify force threshold (--ft) along with --pull'
00598                 print 'Exiting...'
00599                 sys.exit()
00600 
00601             cmg = CompliantMotionGenerator()
00602 
00603             print 'hit a key to power up the arms.'
00604             k=m3t.get_keystroke()
00605             cmg.firenze.power_on()
00606 
00607             if pull_flag:
00608                 if pull_pos_pkl != '':
00609                     pull_loc = ut.load_pickle(pull_pos_pkl)
00610                 else:
00611                     pull_loc = None
00612 
00613     #            cmg.pull(math.radians(ha), ft,use_utm=scan_flag,use_camera=camera_flag,
00614     #                     strategy = 'control_radial_dist',pull_loc=pull_loc,info_string=info_string)
00615     #            cmg.pull(math.radians(ha), ft,use_utm=scan_flag,use_camera=camera_flag,
00616     #                     strategy = 'piecewise_linear',pull_loc=pull_loc,info_string=info_string)
00617                 cmg.pull(math.radians(ha), ft,use_utm=scan_flag,use_camera=camera_flag,
00618                          strategy = 'control_radial_force',pull_loc=pull_loc,info_string=info_string)
00619     #            cmg.pull(math.radians(ha), ft,use_utm=scan_flag,use_camera=camera_flag,
00620     #                     strategy = 'line_neg_x',pull_loc=pull_loc,info_string=info_string)
00621 
00622             if firm_hook_flag:
00623                 hook_angle = math.radians(ha)
00624                 p = np.matrix([0.3,-0.25,-0.2]).T
00625                 rot_mat = tr.Rz(hook_angle-hook_3dprint_angle)*tr.Ry(math.radians(-90))
00626                 cmg.firenze.go_cartesian('right_arm',p,rot_mat,speed=0.1)
00627                 print 'hit a key to get a firm hook.'
00628                 k=m3t.get_keystroke()
00629                 cmg.get_firm_hook(hook_angle)
00630 
00631             print 'hit  a key to end everything'
00632             k=m3t.get_keystroke()
00633             cmg.stop()
00634 
00635     #        cmg = CompliantMotionGenerator()
00636     #        print 'hit a key to test IK'
00637     #        k=m3t.get_keystroke()
00638     #        cmg.get_firm_hook(ha)
00639 
00640         #----------- non-class functions test --------------------
00641         if elbow_angle_flag:
00642             test_elbow_angle()
00643 
00644         if ik_single_pos_flag or test_ik_flag:
00645             if ha == None:
00646                 raise RuntimeError('You need to specify a hooking angle (--ha)')
00647 
00648             settings_r = hr.MekaArmSettings(stiffness_list=[0.15,0.7,0.8,0.8,0.8])
00649             firenze = hr.M3HrlRobot(connect=True,right_arm_settings=settings_r)
00650             print 'hit a key to power up the arms.'
00651             k=m3t.get_keystroke()
00652             firenze.power_on()
00653 
00654             print 'hit a key to test IK'
00655             k=m3t.get_keystroke()
00656             #p = np.matrix([0.26,-0.25,-0.25]).T
00657             p = np.matrix([0.45,-0.2,-0.23]).T
00658             rot_mat = tr.Rz(math.radians(ha)-hook_3dprint_angle)*tr.Ry(math.radians(-90))
00659             #rot_mat = tr.Rz(math.radians(0))*tr.Ry(math.radians(-90))
00660             firenze.go_cartesian('right_arm',p,rot_mat,speed=0.1)
00661 
00662 
00663             if test_ik_flag:
00664                 rot_mat = tr.Rz(math.radians(-110))*tr.Ry(math.radians(-90))
00665                 #rot_mat = tr.Rz(math.radians(0))*tr.Ry(math.radians(-90))
00666                 test_IK(rot_mat)
00667 
00668             print 'hit  a key to end everything'
00669             k=m3t.get_keystroke()
00670             firenze.stop()
00671 
00672     except (KeyboardInterrupt, SystemExit):
00673         cmg.stop()
00674 
00675 
00676 


2009_humanoids_epc_pull
Author(s): Advait Jain, Charles C. Kemp (Healthcare Robotics Lab, Georgia Tech)
autogenerated on Wed Nov 27 2013 12:05:07