arm_trajectories.py
Go to the documentation of this file.
00001 #
00002 #
00003 # Copyright (c) 2010, Georgia Tech Research Corporation
00004 # All rights reserved.
00005 # 
00006 # Redistribution and use in source and binary forms, with or without
00007 # modification, are permitted provided that the following conditions are met:
00008 #     * Redistributions of source code must retain the above copyright
00009 #       notice, this list of conditions and the following disclaimer.
00010 #     * Redistributions in binary form must reproduce the above copyright
00011 #       notice, this list of conditions and the following disclaimer in the
00012 #       documentation and/or other materials provided with the distribution.
00013 #     * Neither the name of the Georgia Tech Research Corporation nor the
00014 #       names of its contributors may be used to endorse or promote products
00015 #       derived from this software without specific prior written permission.
00016 # 
00017 # THIS SOFTWARE IS PROVIDED BY GEORGIA TECH RESEARCH CORPORATION ''AS IS'' AND
00018 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
00019 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
00020 # DISCLAIMED. IN NO EVENT SHALL GEORGIA TECH BE LIABLE FOR ANY DIRECT, INDIRECT,
00021 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
00022 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
00023 # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
00024 # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
00025 # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
00026 # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00027 #
00028 
00029 # \author Advait Jain (Healthcare Robotics Lab, Georgia Tech.)
00030 
00031 
00032 import scipy.optimize as so
00033 
00034 import math, numpy as np
00035 import pylab as pl
00036 import sys, optparse, time
00037 import copy
00038 
00039 from enthought.mayavi import mlab
00040 
00041 import mekabot.hrl_robot as hr
00042 import mekabot.coord_frames as mcf
00043 import matplotlib_util.util as mpu
00044 
00045 #import util as ut
00046 import roslib; roslib.load_manifest('2010_icra_epc_pull')
00047 import hrl_lib.util as ut, hrl_lib.transforms as tr
00048 import hrl_tilting_hokuyo.display_3d_mayavi as d3m
00049 
00050 import segway_motion_calc as smc
00051 
00052 class JointTrajectory():
00053     ''' class to store joint trajectories.
00054         data only - use for pickling.
00055     '''
00056     def __init__(self):
00057         self.time_list = [] # time in seconds
00058         self.q_list = [] #each element is a list of 7 joint angles.
00059         self.qdot_list = [] #each element is a list of 7 joint angles.
00060         self.qdotdot_list = [] #each element is a list of 7 joint angles.
00061 
00062 ## class to store trajectory of a coord frame executing planar motion (x,y,a)
00063 #data only - use for pickling
00064 class PlanarTajectory():
00065     def __init__(self):
00066         self.time_list = [] # time in seconds
00067         self.x_list = []
00068         self.y_list = []
00069         self.a_list = []
00070 
00071 class CartesianTajectory():
00072     ''' class to store trajectory of cartesian points.
00073         data only - use for pickling
00074     '''
00075     def __init__(self):
00076         self.time_list = [] # time in seconds
00077         self.p_list = [] #each element is a list of 3 coordinates
00078         self.v_list = [] #each element is a list of 3 coordinates (velocity)
00079 
00080 class ForceTrajectory():
00081     ''' class to store time evolution of the force at the end effector.
00082         data only - use for pickling
00083     '''
00084     def __init__(self):
00085         self.time_list = [] # time in seconds
00086         self.f_list = [] #each element is a list of 3 coordinates
00087 
00088 ##
00089 # @param traj - JointTrajectory
00090 # @return CartesianTajectory after performing FK on traj to compute
00091 # cartesian position, velocity
00092 def joint_to_cartesian(traj):
00093     firenze = hr.M3HrlRobot(connect=False)
00094     pts = []
00095     cart_vel = []
00096     for i in range(len(traj.q_list)):
00097         q = traj.q_list[i]
00098         p = firenze.FK('right_arm', q)
00099         pts.append(p.A1.tolist())
00100 
00101         if traj.qdot_list != []:
00102             qdot = traj.qdot_list[i]
00103             jac = firenze.Jac('right_arm', q)
00104             vel = jac * np.matrix(qdot).T
00105             cart_vel.append(vel.A1[0:3].tolist())
00106 
00107     ct = CartesianTajectory()
00108     ct.time_list = copy.copy(traj.time_list)
00109     ct.p_list = copy.copy(pts)
00110     ct.v_list = copy.copy(cart_vel)
00111     #return np.matrix(pts).T
00112     return ct
00113 
00114 def plot_forces_quiver(pos_traj,force_traj,color='k'):
00115     import arm_trajectories as at
00116     #if traj.__class__ == at.JointTrajectory:
00117     if isinstance(pos_traj,at.JointTrajectory):
00118         pos_traj = joint_to_cartesian(pos_traj)
00119 
00120     pts = np.matrix(pos_traj.p_list).T
00121     label_list = ['X coord (m)', 'Y coord (m)', 'Z coord (m)']
00122     x = pts[0,:].A1.tolist()
00123     y = pts[1,:].A1.tolist()
00124 
00125     forces = np.matrix(force_traj.f_list).T
00126     u = (-1*forces[0,:]).A1.tolist()
00127     v = (-1*forces[1,:]).A1.tolist()
00128     pl.quiver(x,y,u,v,width=0.002,color=color,scale=100.0)
00129 #    pl.quiver(x,y,u,v,width=0.002,color=color)
00130     pl.axis('equal')
00131 
00132 ##
00133 # @param xaxis - x axis for the graph (0,1 or 2)
00134 # @param zaxis - for a 3d plot. not implemented.
00135 def plot_cartesian(traj, xaxis=None, yaxis=None, zaxis=None, color='b',label='_nolegend_',
00136                    linewidth=2, scatter_size=10, plot_velocity=False):
00137 
00138     import arm_trajectories as at
00139     #if traj.__class__ == at.JointTrajectory:
00140     if isinstance(traj,at.JointTrajectory):
00141         traj = joint_to_cartesian(traj)
00142 
00143     pts = np.matrix(traj.p_list).T
00144     label_list = ['X coord (m)', 'Y coord (m)', 'Z coord (m)']
00145     x = pts[xaxis,:].A1.tolist()
00146     y = pts[yaxis,:].A1.tolist()
00147 
00148     if plot_velocity:
00149         vels = np.matrix(traj.v_list).T
00150         xvel = vels[xaxis,:].A1.tolist()
00151         yvel = vels[yaxis,:].A1.tolist()
00152 
00153     if zaxis == None:
00154         mpu.plot_yx(y, x, color, linewidth, '-', scatter_size, label,
00155                     axis = 'equal', xlabel = label_list[xaxis],
00156                     ylabel = label_list[yaxis],)
00157         if plot_velocity:
00158             mpu.plot_quiver_yxv(y, x, np.matrix([xvel,yvel]),
00159                                 width = 0.001, scale = 1.)
00160         mpu.legend()
00161     else:
00162         from numpy import array
00163         from enthought.mayavi.api import Engine
00164         engine = Engine()
00165         engine.start()
00166         if len(engine.scenes) == 0:
00167             engine.new_scene()
00168 
00169         z = pts[zaxis,:].A1.tolist()
00170         time_list = [t-traj.time_list[0] for t in traj.time_list]
00171         mlab.plot3d(x,y,z,time_list,tube_radius=None,line_width=4)
00172         mlab.axes()
00173         mlab.xlabel(label_list[xaxis])
00174         mlab.ylabel(label_list[yaxis])
00175         mlab.zlabel(label_list[zaxis])
00176         mlab.colorbar(title='Time')
00177 
00178         # ------------------------------------------- 
00179         axes = engine.scenes[0].children[0].children[0].children[1]
00180         axes.axes.position = array([ 0.,  0.])
00181         axes.axes.label_format = '%-#6.2g'
00182         axes.title_text_property.font_size=4
00183 
00184 ## compute the force that the arm would apply given the stiffness matrix
00185 # @param  q_actual_traj - Joint Trajectory (actual angles.)
00186 # @param  q_eq_traj - Joint Trajectory (equilibrium point angles.)
00187 # @param torque_traj - JointTrajectory (torques measured at the joints.)
00188 # @param rel_stiffness_list - list of 5 elements (stiffness numbers for the joints.)
00189 # @return lots of things, look at the code.
00190 def compute_forces(q_actual_traj,q_eq_traj,torque_traj,rel_stiffness_list):
00191     firenze = hr.M3HrlRobot(connect=False)
00192 
00193     d_gains_list_mN_deg_sec = [-100,-120,-15,-25,-1.25]
00194     d_gains_list = [180./1000.*s/math.pi for s in d_gains_list_mN_deg_sec]
00195 
00196     stiff_list_mNm_deg = [1800,1300,350,600,60]
00197     stiff_list_Nm_rad = [180./1000.*s/math.pi for s in stiff_list_mNm_deg]
00198 #    stiffness_settings = [0.15,0.7,0.8,0.8,0.8]
00199 #    dia = np.array(stiffness_settings) * np.array(stiff_list_Nm_rad)
00200     dia = np.array(rel_stiffness_list) * np.array(stiff_list_Nm_rad)
00201     k_q = np.matrix(np.diag(dia))
00202     dia_inv = 1./dia
00203     k_q_inv = np.matrix(np.diag(dia_inv))
00204 
00205     actual_cart = joint_to_cartesian(q_actual_traj)
00206     eq_cart = joint_to_cartesian(q_eq_traj)
00207     force_traj_jacinv = ForceTrajectory()
00208     force_traj_stiff = ForceTrajectory()
00209     force_traj_torque = ForceTrajectory()
00210 
00211     k_cart_list = []
00212 
00213     for q_actual,q_dot,q_eq,actual_pos,eq_pos,t,tau_m in zip(q_actual_traj.q_list,q_actual_traj.qdot_list,q_eq_traj.q_list,actual_cart.p_list,eq_cart.p_list,q_actual_traj.time_list,torque_traj.q_list):
00214         q_eq = firenze.clamp_to_physical_joint_limits('right_arm',q_eq)
00215         q_delta = np.matrix(q_actual).T - np.matrix(q_eq).T
00216         tau = k_q * q_delta[0:5,0] - np.matrix(np.array(d_gains_list)*np.array(q_dot)[0:5]).T
00217 
00218         x_delta = np.matrix(actual_pos).T - np.matrix(eq_pos).T
00219 
00220         jac_full = firenze.Jac('right_arm',q_actual)
00221         jac = jac_full[0:3,0:5]
00222 
00223         jac_full_eq = firenze.Jac('right_arm',q_eq)
00224         jac_eq = jac_full_eq[0:3,0:5]
00225         k_cart = np.linalg.inv((jac_eq*k_q_inv*jac_eq.T))    # calculating stiff matrix using Jacobian for eq pt.
00226         k_cart_list.append(k_cart)
00227 
00228         pseudo_inv_jac = np.linalg.inv(jac_full*jac_full.T)*jac_full
00229 
00230         tau_full = np.row_stack((tau,np.matrix(tau_m[5:7]).T))
00231         #force = (-1*pseudo_inv_jac*tau_full)[0:3]
00232         force = -1*pseudo_inv_jac[0:3,0:5]*tau
00233         force_traj_jacinv.f_list.append(force.A1.tolist())
00234         force_traj_stiff.f_list.append((k_cart*x_delta).A1.tolist())
00235         force_traj_torque.f_list.append((pseudo_inv_jac*np.matrix(tau_m).T)[0:3].A1.tolist())
00236 
00237     return force_traj_jacinv,force_traj_stiff,force_traj_torque,k_cart_list
00238 
00239 ## return two lists containing the radial and tangential components of the forces.
00240 # @param f_list - list of forces. (each force is a list of 2 or 3 floats)
00241 # @param p_list - list of positions. (each position is a list of 2 or 3 floats)
00242 # @param cx - x coord of the center of the circle.
00243 # @param cy - y coord of the center of the circle.
00244 # @return list of magnitude of radial component, list of magnitude tangential component.
00245 def compute_radial_tangential_forces(f_list,p_list,cx,cy):
00246     f_rad_l,f_tan_l = [],[]
00247     for f,p in zip(f_list,p_list):
00248         rad_vec = np.array([p[0]-cx,p[1]-cy])
00249         rad_vec = rad_vec/np.linalg.norm(rad_vec)
00250         f_vec = np.array([f[0],f[1]])
00251         f_rad_mag = np.dot(f_vec,rad_vec)
00252         f_tan_mag = np.linalg.norm(f_vec-rad_vec*f_rad_mag)
00253         f_rad_mag = abs(f_rad_mag)
00254         f_rad_l.append(f_rad_mag)
00255         f_tan_l.append(f_tan_mag)
00256 
00257     return f_rad_l,f_tan_l
00258         
00259 
00260 ## find the x and y coord of the center of the circle and the radius that
00261 # best matches the data.
00262 # @param rad_guess - guess for the radius of the circle
00263 # @param x_guess - guess for x coord of center
00264 # @param y_guess - guess for y coord of center.
00265 # @param pts - 2xN np matrix of points.
00266 # @param method - optimization method. ('fmin' or 'fmin_bfgs')
00267 # @param verbose - passed onto the scipy optimize functions. whether to print out the convergence info.
00268 # @return r,x,y  (radius, x and y coord of the center of the circle)
00269 def fit_circle(rad_guess,x_guess,y_guess,pts,method,verbose=True):
00270     def error_function(params):
00271         center = np.matrix((params[0],params[1])).T
00272         rad = params[2]
00273         #print 'pts.shape', pts.shape
00274         #print 'center.shape', center.shape
00275         #print 'ut.norm(pts-center).shape',ut.norm(pts-center).shape
00276         err = ut.norm(pts-center).A1 - rad
00277         res = np.dot(err,err)
00278         return res
00279 
00280     params_1 = [x_guess,y_guess,rad_guess]
00281     if method == 'fmin':
00282         r = so.fmin(error_function,params_1,xtol=0.0002,ftol=0.000001,full_output=1,disp=verbose)
00283         opt_params_1,fopt_1 = r[0],r[1]
00284     elif method == 'fmin_bfgs':
00285         r = so.fmin_bfgs(error_function, params_1, full_output=1,
00286                          disp = verbose, gtol=1e-5)
00287         opt_params_1,fopt_1 = r[0],r[1]
00288     else:
00289         raise RuntimeError('unknown method: '+method)
00290 
00291     params_2 = [x_guess,y_guess+2*rad_guess,rad_guess]
00292     if method == 'fmin':
00293         r = so.fmin(error_function,params_2,xtol=0.0002,ftol=0.000001,full_output=1,disp=verbose)
00294         opt_params_2,fopt_2 = r[0],r[1]
00295     elif method == 'fmin_bfgs':
00296         r = so.fmin_bfgs(error_function, params_2, full_output=1,
00297                          disp = verbose, gtol=1e-5)
00298         opt_params_2,fopt_2 = r[0],r[1]
00299     else:
00300         raise RuntimeError('unknown method: '+method)
00301 
00302     if fopt_2<fopt_1:
00303         return opt_params_2[2],opt_params_2[0],opt_params_2[1]
00304     else:
00305         return opt_params_1[2],opt_params_1[0],opt_params_1[1]
00306 
00307 
00308 ## changes the cartesian trajectory to put everything in the same frame.
00309 # NOTE - velocity transformation does not work if the segway is also
00310 # moving. This is because I am not logging the velocity of the segway.
00311 # @param pts - CartesianTajectory
00312 # @param st - object of type PlanarTajectory (segway trajectory)
00313 # @return CartesianTajectory
00314 def account_segway_motion(cart_traj,st):
00315     ct = CartesianTajectory()
00316     for i in range(len(cart_traj.p_list)):
00317         x,y,a = st.x_list[i], st.y_list[i], st.a_list[i]
00318         p_tl = np.matrix(cart_traj.p_list[i]).T
00319         p_ts = smc.tsTtl(p_tl, x, y, a)
00320         p = p_ts
00321         ct.p_list.append(p.A1.tolist())
00322 
00323         # this is incorrect. I also need to use the velocity of the
00324         # segway. Unclear whether this is useful right now, so not
00325         # implementing it. (Advait. Jan 6, 2010.)
00326         if cart_traj.v_list != []:
00327             v_tl = np.matrix(cart_traj.v_list[i]).T
00328             v_ts = smc.tsRtl(v_tl, a)
00329             ct.v_list.append(v_ts.A1.tolist())
00330 
00331     ct.time_list = copy.copy(cart_traj.time_list)
00332     return ct
00333 
00334 # @param cart_traj - CartesianTajectory
00335 # @param z_l - list of zenither heights
00336 # @return CartesianTajectory
00337 def account_zenithering(cart_traj, z_l):
00338     ct = CartesianTajectory()
00339     h_start = z_l[0]
00340     for i in range(len(cart_traj.p_list)):
00341         h = z_l[i]
00342         p = cart_traj.p_list[i]
00343         p[2] += h - h_start
00344         ct.p_list.append(p)
00345 
00346         # this is incorrect. I also need to use the velocity of the
00347         # zenither. Unclear whether this is useful right now, so not
00348         # implementing it. (Advait. Jan 6, 2010.)
00349         if cart_traj.v_list != []:
00350             ct.v_list.append(cart_traj.v_list[i])
00351 
00352     ct.time_list = copy.copy(cart_traj.time_list)
00353     return ct
00354 
00355 ##
00356 # remove the parts of the trjectory in which the hook is not moving.
00357 # @param ct - cartesian trajectory of the end effector in the world frame.
00358 # @return 2xN np matrix, reject_idx
00359 def filter_cartesian_trajectory(ct):
00360     pts_list = ct.p_list
00361     ee_start_pos = pts_list[0]
00362     l = [pts_list[0]]
00363 
00364     for i, p in enumerate(pts_list[1:]):
00365         l.append(p)
00366         pts_2d = (np.matrix(l).T)[0:2,:]
00367         st_pt = pts_2d[:,0]
00368         end_pt = pts_2d[:,-1]
00369         dist_moved = np.linalg.norm(st_pt-end_pt)
00370         #if dist_moved < 0.1:
00371         if dist_moved < 0.03:
00372             reject_idx = i
00373 
00374     pts_2d = pts_2d[:,reject_idx:]
00375     return pts_2d, reject_idx
00376 
00377 ##
00378 # remove the parts of the trjectory in which the hook slipped off
00379 # @param ct - cartesian trajectory of the end effector in the world frame.
00380 # @param ft - force trajectory
00381 # @return cartesian trajectory with the zero force end part removed, force trajectory
00382 def filter_trajectory_force(ct, ft):
00383     vel_list = copy.copy(ct.v_list)
00384     pts_list = copy.copy(ct.p_list)
00385     time_list = copy.copy(ct.time_list)
00386     ft_list = copy.copy(ft.f_list)
00387     f_mag_list = ut.norm(np.matrix(ft.f_list).T).A1.tolist()
00388 
00389     if len(pts_list) != len(f_mag_list):
00390         print 'arm_trajectories.filter_trajectory_force: force and end effector lists are not of the same length.'
00391         print 'Exiting ...'
00392         sys.exit()
00393 
00394     n_pts = len(pts_list)
00395     i = n_pts - 1
00396     hook_slip_off_threshold = 1.5 # from compliant_trajectories.py
00397     while i > 0:
00398         if f_mag_list[i] < hook_slip_off_threshold:
00399             pts_list.pop()
00400             time_list.pop()
00401             ft_list.pop()
00402             if vel_list != []:
00403                 vel_list.pop()
00404         else:
00405             break
00406         i -= 1
00407 
00408     ct2 = CartesianTajectory()
00409     ct2.time_list = time_list
00410     ct2.p_list = pts_list
00411     ct2.v_list = vel_list
00412 
00413     ft2 = ForceTrajectory()
00414     ft2.time_list = copy.copy(time_list)
00415     ft2.f_list = ft_list
00416     return ct2, ft2
00417 
00418 
00419 if __name__ == '__main__':
00420     p = optparse.OptionParser()
00421     p.add_option('-f', action='store', type='string', dest='fname',
00422                  help='pkl file to use.', default='')
00423     p.add_option('--xy', action='store_true', dest='xy',
00424                  help='plot the x and y coordinates of the end effector.')
00425     p.add_option('--yz', action='store_true', dest='yz',
00426                  help='plot the y and z coordinates of the end effector.')
00427     p.add_option('--xz', action='store_true', dest='xz',
00428                  help='plot the x and z coordinates of the end effector.')
00429     p.add_option('--plot_ellipses', action='store_true', dest='plot_ellipses',
00430                  help='plot the stiffness ellipse in the x-y plane')
00431     p.add_option('--pfc', action='store_true', dest='pfc',
00432                  help='plot the radial and tangential components of the force.')
00433     p.add_option('--pmf', action='store_true', dest='pmf',
00434                  help='plot things with the mechanism alinged with the axes.')
00435     p.add_option('--pff', action='store_true', dest='pff',
00436                  help='plot the force field corresponding to a stiffness ellipse.')
00437     p.add_option('--pev', action='store_true', dest='pev',
00438                  help='plot the stiffness ellipses for different combinations of the rel stiffnesses.')
00439     p.add_option('--plot_forces', action='store_true', dest='plot_forces',
00440                  help='plot the force in the x-y plane')
00441     p.add_option('--plot_forces_error', action='store_true', dest='plot_forces_error',
00442                  help='plot the error between the computed and measured (ATI) forces in the x-y plane')
00443     p.add_option('--xyz', action='store_true', dest='xyz',
00444                  help='plot in 3d the coordinates of the end effector.')
00445     p.add_option('-r', action='store', type='float', dest='rad',
00446                  help='radius of the joint.', default=None)
00447     p.add_option('--noshow', action='store_true', dest='noshow',
00448                  help='do not display the figure (use while saving figures to disk)')
00449     p.add_option('--exptplot', action='store_true', dest='exptplot',
00450                  help='put all the graphs of an experiment as subplots.')
00451     p.add_option('--sturm', action='store_true', dest='sturm',
00452                  help='make log files to send to sturm')
00453     p.add_option('--icra_presentation_plot', action='store_true',
00454                  dest='icra_presentation_plot',
00455                  help='plot explaining CEP update.')
00456 
00457     opt, args = p.parse_args()
00458     fname = opt.fname
00459     xy_flag = opt.xy
00460     yz_flag = opt.yz
00461     xz_flag = opt.xz
00462     plot_forces_flag = opt.plot_forces
00463     plot_ellipses_flag = opt.plot_ellipses
00464     plot_forces_error_flag = opt.plot_forces_error
00465     plot_force_components_flag = opt.pfc
00466     plot_force_field_flag = opt.pff
00467     plot_mechanism_frame = opt.pmf
00468     xyz_flag = opt.xyz
00469     rad = opt.rad
00470     show_fig = not(opt.noshow)
00471     plot_ellipses_vary_flag = opt.pev
00472     expt_plot = opt.exptplot
00473     sturm_output = opt.sturm
00474 
00475 
00476     if plot_ellipses_vary_flag:
00477         show_fig=False
00478         i = 0
00479         ratio_list1 = [0.1,0.3,0.5,0.7,0.9] # coarse search
00480         ratio_list2 = [0.1,0.3,0.5,0.7,0.9] # coarse search
00481         ratio_list3 = [0.1,0.3,0.5,0.7,0.9] # coarse search
00482 #        ratio_list1 = [0.7,0.8,0.9,1.0]
00483 #        ratio_list2 = [0.7,0.8,0.9,1.0]
00484 #        ratio_list3 = [0.3,0.4,0.5,0.6,0.7]
00485 #        ratio_list1 = [1.0,2.,3.0]
00486 #        ratio_list2 = [1.,2.,3.]
00487 #        ratio_list3 = [0.3,0.4,0.5,0.6,0.7]
00488 
00489         inv_mean_list,std_list = [],[]
00490         x_l,y_l,z_l = [],[],[]
00491         s0 = 0.2
00492         #s0 = 0.4
00493         for s1 in ratio_list1:
00494             for s2 in ratio_list2:
00495                 for s3 in ratio_list3:
00496                     i += 1
00497                     s_list = [s0,s1,s2,s3,0.8]
00498                     #s_list = [s1,s2,s3,s0,0.8]
00499                     print '################## s_list:', s_list
00500                     m,s = plot_stiff_ellipse_map(s_list,i)
00501                     inv_mean_list.append(1./m)
00502                     std_list.append(s)
00503                     x_l.append(s1)
00504                     y_l.append(s2)
00505                     z_l.append(s3)
00506 
00507         ut.save_pickle({'x_l':x_l,'y_l':y_l,'z_l':z_l,'inv_mean_list':inv_mean_list,'std_list':std_list},
00508                        'stiff_dict_'+ut.formatted_time()+'.pkl')
00509         d3m.plot_points(np.matrix([x_l,y_l,z_l]),scalar_list=inv_mean_list,mode='sphere')
00510         mlab.axes()
00511         d3m.show()
00512 
00513         sys.exit()
00514 
00515     if fname=='':
00516         print 'please specify a pkl file (-f option)'
00517         print 'Exiting...'
00518         sys.exit()
00519 
00520     d = ut.load_pickle(fname)
00521     actual_cartesian_tl = joint_to_cartesian(d['actual'])
00522     actual_cartesian = account_segway_motion(actual_cartesian_tl,d['segway'])
00523     if d.has_key('zenither_list'):
00524         actual_cartesian = account_zenithering(actual_cartesian,
00525                                                d['zenither_list'])
00526 
00527     eq_cartesian_tl = joint_to_cartesian(d['eq_pt'])
00528     eq_cartesian = account_segway_motion(eq_cartesian_tl, d['segway'])
00529     if d.has_key('zenither_list'):
00530         eq_cartesian = account_zenithering(eq_cartesian, d['zenither_list'])
00531 
00532     cartesian_force_clean, _ = filter_trajectory_force(actual_cartesian,
00533                                                        d['force'])
00534     pts_2d, reject_idx = filter_cartesian_trajectory(cartesian_force_clean)
00535 
00536     if rad != None:
00537         #rad = 0.39 # lab cabinet recessed.
00538         #rad = 0.42 # kitchen cabinet
00539         #rad = 0.80 # lab glass door
00540         pts_list = actual_cartesian.p_list
00541         eq_pts_list = eq_cartesian.p_list
00542         ee_start_pos = pts_list[0]
00543         x_guess = ee_start_pos[0]
00544         y_guess = ee_start_pos[1] - rad
00545         print 'before call to fit_rotary_joint'
00546         force_list = d['force'].f_list
00547 
00548         if sturm_output:
00549             str_parts = fname.split('.')
00550             sturm_file_name = str_parts[0]+'_sturm.log'
00551             print 'Sturm file name:', sturm_file_name
00552             sturm_file = open(sturm_file_name,'w')
00553             sturm_pts = cartesian_force_clean.p_list
00554             print 'len(sturm_pts):', len(sturm_pts)
00555             print 'len(pts_list):', len(pts_list)
00556 
00557             for i,p in enumerate(sturm_pts[1:]):
00558                 sturm_file.write(" ".join(map(str,p)))
00559                 sturm_file.write('\n')
00560 
00561             sturm_file.write('\n')
00562             sturm_file.close()
00563 
00564         rad_guess = rad
00565         rad, cx, cy = fit_circle(rad_guess,x_guess,y_guess,pts_2d,
00566                                  method='fmin_bfgs',verbose=False)
00567         c_ts = np.matrix([cx, cy, 0.]).T
00568         start_angle = tr.angle_within_mod180(math.atan2(pts_2d[0,1]-cy,
00569                                pts_2d[0,0]-cx) - math.pi/2)
00570         end_angle = tr.angle_within_mod180(math.atan2(pts_2d[-1,1]-cy,
00571                                pts_2d[-1,0]-cx) - math.pi/2)
00572         mpu.plot_circle(cx, cy, rad, start_angle, end_angle,
00573                         label='Actual\_opt', color='r')
00574 
00575 
00576     if opt.icra_presentation_plot:
00577         mpu.set_figure_size(30,20)
00578         rad = 1.0
00579         x_guess = pts_2d[0,0]
00580         y_guess = pts_2d[1,0] - rad
00581 
00582         rad_guess = rad
00583         rad, cx, cy = fit_circle(rad_guess,x_guess,y_guess,pts_2d,
00584                                  method='fmin_bfgs',verbose=False)
00585         print 'Estimated rad, cx, cy:', rad, cx, cy
00586 
00587         start_angle = tr.angle_within_mod180(math.atan2(pts_2d[1,0]-cy,
00588                                pts_2d[0,0]-cx) - math.pi/2)
00589         end_angle = tr.angle_within_mod180(math.atan2(pts_2d[1,-1]-cy,
00590                                pts_2d[0,-1]-cx) - math.pi/2)
00591 
00592         subsample_ratio = 1
00593         pts_2d_s = pts_2d[:,::subsample_ratio]
00594 
00595         cep_force_clean, force_new = filter_trajectory_force(eq_cartesian,
00596                                                              d['force'])
00597         cep_2d = np.matrix(cep_force_clean.p_list).T[0:2,reject_idx:]
00598 
00599         # first draw the entire CEP and end effector trajectories
00600         mpu.figure()
00601         mpu.plot_yx(pts_2d_s[1,:].A1, pts_2d_s[0,:].A1, color='b',
00602                     label = 'FK', axis = 'equal', alpha = 1.0,
00603                     scatter_size=7, linewidth=0, marker='x',
00604                     marker_edge_width = 1.5)
00605 
00606         cep_2d_s = cep_2d[:,::subsample_ratio]
00607         mpu.plot_yx(cep_2d_s[1,:].A1, cep_2d_s[0,:].A1, color='g',
00608                     label = 'CEP', axis = 'equal', alpha = 1.0,
00609                     scatter_size=10, linewidth=0, marker='+',
00610                     marker_edge_width = 1.5)
00611 
00612         mpu.plot_circle(cx, cy, rad, start_angle, end_angle,
00613                         label='Estimated Kinematics', color='r',
00614                         alpha=0.7)
00615         mpu.plot_radii(cx, cy, rad, start_angle, end_angle,
00616                        interval=end_angle-start_angle, color='r',
00617                        alpha=0.7)
00618         mpu.legend()
00619         mpu.savefig('one.png')
00620 
00621         # now zoom in to a small region to show the force
00622         # decomposition.
00623         zoom_location = 10
00624         pts_2d_zoom = pts_2d[:,:zoom_location]
00625         cep_2d_zoom = cep_2d[:,:zoom_location]
00626 
00627         mpu.figure()
00628         mpu.plot_yx(pts_2d_zoom[1,:].A1, pts_2d_zoom[0,:].A1, color='b',
00629                     label = 'FK', axis = 'equal', alpha = 1.0,
00630                     scatter_size=7, linewidth=0, marker='x',
00631                     marker_edge_width = 1.5)
00632         mpu.plot_yx(cep_2d_zoom[1,:].A1, cep_2d_zoom[0,:].A1, color='g',
00633                     label = 'CEP', axis = 'equal', alpha = 1.0,
00634                     scatter_size=10, linewidth=0, marker='+',
00635                     marker_edge_width = 1.5)
00636         mpu.pl.xlim(0.28, 0.47)
00637         mpu.legend()
00638         mpu.savefig('two.png')
00639 
00640         rad, cx, cy = fit_circle(1.0,x_guess,y_guess,pts_2d_zoom,
00641                                  method='fmin_bfgs',verbose=False)
00642         print 'Estimated rad, cx, cy:', rad, cx, cy
00643         start_angle = tr.angle_within_mod180(math.atan2(pts_2d[1,0]-cy,
00644                                pts_2d[0,0]-cx) - math.pi/2)
00645         end_angle = tr.angle_within_mod180(math.atan2(pts_2d_zoom[1,-1]-cy,
00646                                pts_2d_zoom[0,-1]-cx) - math.pi/2)
00647         mpu.plot_circle(cx, cy, rad, start_angle, end_angle,
00648                         label='Estimated Kinematics', color='r',
00649                         alpha=0.7)
00650         mpu.pl.xlim(0.28, 0.47)
00651         mpu.legend()
00652         mpu.savefig('three.png')
00653 
00654         current_pos = pts_2d_zoom[:,-1]
00655         radial_vec = current_pos - np.matrix([cx,cy]).T
00656         radial_vec = radial_vec / np.linalg.norm(radial_vec)
00657         tangential_vec = np.matrix([[0,-1],[1,0]]) * radial_vec
00658         mpu.plot_quiver_yxv([pts_2d_zoom[1,-1]],
00659                             [pts_2d_zoom[0,-1]],
00660                             radial_vec, scale=10., width = 0.002)
00661         rad_text_loc = pts_2d_zoom[:,-1] + np.matrix([0.001,0.01]).T
00662         mpu.pl.text(rad_text_loc[0,0], rad_text_loc[1,0], '\huge{$\hat v_{rad}$}')
00663         mpu.plot_quiver_yxv([pts_2d_zoom[1,-1]],
00664                             [pts_2d_zoom[0,-1]],
00665                             tangential_vec, scale=10., width = 0.002)
00666 
00667         tan_text_loc = pts_2d_zoom[:,-1] + np.matrix([-0.012, -0.011]).T
00668         mpu.pl.text(tan_text_loc[0,0], tan_text_loc[1,0], s = '\huge{$\hat v_{tan}$}')
00669         mpu.pl.xlim(0.28, 0.47)
00670         mpu.legend()
00671         mpu.savefig('four.png')
00672 
00673         wrist_force = -np.matrix(force_new.f_list[zoom_location]).T
00674         frad = (wrist_force[0:2,:].T * radial_vec)[0,0] * radial_vec
00675         mpu.plot_quiver_yxv([pts_2d_zoom[1,-1]],
00676                             [pts_2d_zoom[0,-1]],
00677                             wrist_force, scale=50., width = 0.002,
00678                             color='y')
00679         wf_text = rad_text_loc + np.matrix([-0.05,0.015]).T
00680         mpu.pl.text(wf_text[0,0], wf_text[1,0], color='y',
00681                     fontsize = 15, s = 'Wrist Force')
00682 
00683         mpu.plot_quiver_yxv([pts_2d_zoom[1,-1]],
00684                             [pts_2d_zoom[0,-1]],
00685                             frad, scale=50., width = 0.002,
00686                             color='y')
00687         frad_text = rad_text_loc + np.matrix([0.,0.015]).T
00688         mpu.pl.text(frad_text[0,0], frad_text[1,0], color='y', s = '\huge{$\hat F_{rad}$}')
00689 
00690         mpu.pl.xlim(0.28, 0.47)
00691         mpu.legend()
00692         mpu.savefig('five.png')
00693 
00694         frad = (wrist_force[0:2,:].T * radial_vec)[0,0]
00695         hook_force_motion = -(frad - 5) * radial_vec * 0.001
00696         tangential_motion = 0.01 * tangential_vec
00697         total_cep_motion = hook_force_motion + tangential_motion
00698 
00699         mpu.plot_quiver_yxv([cep_2d_zoom[1,-1]],
00700                             [cep_2d_zoom[0,-1]],
00701                             hook_force_motion, scale=0.1, width = 0.002)
00702         hw_text = cep_2d_zoom[:,-1] + np.matrix([-0.002,-0.012]).T
00703         mpu.pl.text(hw_text[0,0], hw_text[1,0], color='k', fontsize=14,
00704                     s = '$h[t]$ = $0.1cm/N \cdot (|\hat{F}_{rad}|-5N) \cdot \hat{v}_{rad}$')
00705         mpu.pl.xlim(0.28, 0.47)
00706         mpu.legend()
00707         mpu.savefig('six.png')
00708 
00709         mpu.plot_quiver_yxv([cep_2d_zoom[1,-1]],
00710                             [cep_2d_zoom[0,-1]],
00711                             tangential_motion, scale=0.1, width = 0.002)
00712         mw_text = cep_2d_zoom[:,-1] + np.matrix([-0.038,0.001]).T
00713         mpu.pl.text(mw_text[0,0], mw_text[1,0], color='k', fontsize=14,
00714                     s = '$m[t]$ = $1cm \cdot \hat{v}_{tan}$')
00715         mpu.pl.xlim(0.28, 0.47)
00716         mpu.legend()
00717         mpu.savefig('seven.png')
00718 
00719         mpu.plot_quiver_yxv([cep_2d_zoom[1,-1]],
00720                             [cep_2d_zoom[0,-1]],
00721                             total_cep_motion, scale=0.1, width = 0.002)
00722         cep_text = cep_2d_zoom[:,-1] + np.matrix([-0.058,-0.013]).T
00723         mpu.pl.text(cep_text[0,0], cep_text[1,0], color='k', fontsize=14,
00724                     s = '$x_{eq}[t]$ = &x_{eq}[t-1] + m[t] + h[t]$')
00725         mpu.pl.xlim(0.28, 0.47)
00726         mpu.legend()
00727         mpu.savefig('eight.png')
00728 
00729         new_cep = cep_2d_zoom[:,-1] + total_cep_motion
00730         mpu.plot_yx(new_cep[1,:].A1, new_cep[0,:].A1, color='g',
00731                     axis = 'equal', alpha = 1.0,
00732                     scatter_size=10, linewidth=0, marker='+',
00733                     marker_edge_width = 1.5)
00734         mpu.pl.xlim(0.28, 0.47)
00735         mpu.legend()
00736         mpu.savefig('nine.png')
00737 
00738         #mpu.plot_radii(cx, cy, rad, start_angle, end_angle,
00739         #               interval=end_angle-start_angle, color='r',
00740         #               alpha=0.7)
00741 
00742 
00743 
00744 
00745     if plot_mechanism_frame:
00746         if expt_plot:
00747             pl.subplot(231)
00748 
00749         # transform points so that the mechanism is in a fixed position.
00750         start_pt = actual_cartesian.p_list[0]
00751         x_diff = start_pt[0] - cx
00752         y_diff = start_pt[1] - cy
00753         angle = math.atan2(y_diff,x_diff) - math.radians(90)
00754         rot_mat = tr.Rz(angle)[0:2,0:2]
00755         translation_mat = np.matrix([cx,cy]).T
00756 
00757         robot_width,robot_length = 0.1,0.2
00758         robot_x_list = [-robot_width/2,-robot_width/2,robot_width/2,robot_width/2,-robot_width/2]
00759         robot_y_list = [-robot_length/2,robot_length/2,robot_length/2,-robot_length/2,-robot_length/2]
00760         robot_mat = rot_mat*(np.matrix([robot_x_list,robot_y_list]) - translation_mat)
00761         mpu.plot_yx(robot_mat[1,:].A1,robot_mat[0,:].A1,linewidth=2,scatter_size=0,
00762                     color='k',label='torso', axis='equal')
00763 
00764         pts2d_actual = (np.matrix(actual_cartesian.p_list).T)[0:2]
00765         pts2d_actual_t = rot_mat *(pts2d_actual -  translation_mat)
00766         mpu.plot_yx(pts2d_actual_t[1,:].A1,pts2d_actual_t[0,:].A1,scatter_size=20,label='FK',
00767                     axis = 'equal')
00768 
00769         end_pt = pts2d_actual_t[:,-1]
00770         end_angle = tr.angle_within_mod180(math.atan2(end_pt[1,0],end_pt[0,0])-math.radians(90))
00771 
00772         mpu.plot_circle(0,0,rad,0.,end_angle,label='Actual_opt',color='r')
00773         mpu.plot_radii(0,0,rad,0.,end_angle,interval=math.radians(15),color='r')
00774         pl.legend(loc='best')
00775         pl.axis('equal')
00776 
00777         if not(expt_plot):
00778             str_parts = fname.split('.')
00779             fig_name = str_parts[0]+'_robot_pose.png'
00780             pl.savefig(fig_name)
00781             pl.figure()
00782         else:
00783             pl.subplot(232)
00784 
00785         pl.text(0.1,0.15,d['info'])
00786         pl.text(0.1,0.10,'control: '+d['strategy'])
00787         pl.text(0.1,0.05,'robot angle: %.2f'%math.degrees(angle))
00788         pl.text(0.1,0,'optimized radius: %.2f'%rad_opt)
00789         pl.text(0.1,-0.05,'radius used: %.2f'%rad)
00790         pl.text(0.1,-0.10,'opening angle: %.2f'%math.degrees(end_angle))
00791         s_list = d['stiffness'].stiffness_list
00792         s_scale = d['stiffness'].stiffness_scale
00793         sl = [min(s*s_scale,1.0) for s in s_list]
00794         pl.text(0.1,-0.15,'stiffness list: %.2f, %.2f, %.2f, %.2f'%(sl[0],sl[1],sl[2],sl[3]))
00795         pl.text(0.1,-0.20,'stop condition: '+d['result'])
00796         time_dict = d['time_dict']
00797         pl.text(0.1,-0.25,'time to hook: %.2f'%(time_dict['before_hook']-time_dict['before_pull']))
00798         pl.text(0.1,-0.30,'time to pull: %.2f'%(time_dict['before_pull']-time_dict['after_pull']))
00799 
00800         pl.ylim(-0.45,0.25)
00801         if not(expt_plot):
00802             pl.figure()
00803 
00804     if xy_flag:
00805         st_pt = pts_2d[:,0]
00806         end_pt = pts_2d[:,-1]
00807 
00808 #        if rad != None:
00809 #            start_angle = tr.angle_within_mod180(math.atan2(st_pt[1,0]-cy,st_pt[0,0]-cx) - math.radians(90))
00810 #            end_angle = tr.angle_within_mod180(math.atan2(end_pt[1,0]-cy,end_pt[0,0]-cx) - math.radians(90))
00811 #            
00812 #            print 'start_angle, end_angle:', math.degrees(start_angle), math.degrees(end_angle)
00813 #            print 'angle through which mechanism turned:', math.degrees(end_angle-start_angle)
00814 
00815         if expt_plot:
00816             pl.subplot(233)
00817 
00818         plot_cartesian(actual_cartesian, xaxis=0, yaxis=1, color='b',
00819                        label='FK', plot_velocity=False)
00820         plot_cartesian(eq_cartesian, xaxis=0,yaxis=1,color='g',label='Eq Point')
00821         #leg = pl.legend(loc='best',handletextsep=0.020,handlelen=0.003,labelspacing=0.003)
00822         #leg.draw_frame(False)
00823 
00824     elif yz_flag:
00825         plot_cartesian(actual_cartesian,xaxis=1,yaxis=2,color='b',label='FK')
00826         plot_cartesian(eq_cartesian, xaxis=1,yaxis=2,color='g',label='Eq Point')
00827     elif xz_flag:
00828         plot_cartesian(actual_cartesian,xaxis=0,yaxis=2,color='b',label='FK')
00829         plot_cartesian(eq_cartesian, xaxis=0,yaxis=2,color='g',label='Eq Point')
00830 
00831 
00832     if plot_forces_flag or plot_forces_error_flag or plot_ellipses_flag or plot_force_components_flag or plot_force_field_flag:
00833         arm_stiffness_list = d['stiffness'].stiffness_list
00834         scale = d['stiffness'].stiffness_scale
00835         asl = [min(scale*s,1.0) for s in arm_stiffness_list]
00836         ftraj_jinv,ftraj_stiff,ftraj_torque,k_cart_list=compute_forces(d['actual'],d['eq_pt'],
00837                                                                        d['torque'],asl)
00838         if plot_forces_flag:
00839             plot_forces_quiver(actual_cartesian,d['force'],color='k')
00840             #plot_forces_quiver(actual_cartesian,ftraj_jinv,color='y')
00841             #plot_forces_quiver(actual_cartesian,ftraj_stiff,color='y')
00842 
00843         if plot_ellipses_flag:
00844             #plot_stiff_ellipses(k_cart_list,actual_cartesian)
00845             if expt_plot:
00846                 subplotnum=234
00847             else:
00848                 pl.figure()
00849                 subplotnum=111
00850             plot_stiff_ellipses(k_cart_list,eq_cartesian,subplotnum=subplotnum)
00851 
00852         if plot_forces_error_flag:
00853             plot_error_forces(d['force'].f_list,ftraj_jinv.f_list)
00854             #plot_error_forces(d['force'].f_list,ftraj_stiff.f_list)
00855 
00856         if plot_force_components_flag:
00857             p_list = actual_cartesian.p_list
00858             cx = 45.
00859             cy = -0.3
00860             frad_list,ftan_list = compute_radial_tangential_forces(d['force'].f_list,p_list,cx,cy)
00861             if expt_plot:
00862                 pl.subplot(235)
00863             else:
00864                 pl.figure()
00865 
00866             time_list = d['force'].time_list
00867             time_list = [t-time_list[0] for t in time_list]
00868             x_coord_list = np.matrix(p_list)[:,0].A1.tolist()
00869             mpu.plot_yx(frad_list,x_coord_list,scatter_size=50,color=time_list,cb_label='time',axis=None)
00870             pl.xlabel('x coord of end effector (m)')
00871             pl.ylabel('magnitude of radial force (N)')
00872             pl.title(d['info'])
00873             if expt_plot:
00874                 pl.subplot(236)
00875             else:
00876                 pl.figure()
00877             mpu.plot_yx(ftan_list,x_coord_list,scatter_size=50,color=time_list,cb_label='time',axis=None)
00878             pl.xlabel('x coord of end effector (m)')
00879             pl.ylabel('magnitude of tangential force (N)')
00880             pl.title(d['info'])
00881 
00882         if plot_force_field_flag:
00883             plot_stiffness_field(k_cart_list[0],plottitle='start')
00884             plot_stiffness_field(k_cart_list[-1],plottitle='end')
00885 
00886 
00887     str_parts = fname.split('.')
00888     if d.has_key('strategy'):
00889         addon = ''
00890         if opt.xy:
00891             addon = '_xy'
00892         if opt.xz:
00893             addon = '_xz'
00894         fig_name = str_parts[0]+'_'+d['strategy']+addon+'.png'
00895     else:
00896         fig_name = str_parts[0]+'_res.png'
00897 
00898     if expt_plot:
00899         f = pl.gcf()
00900         curr_size = f.get_size_inches()
00901         f.set_size_inches(curr_size[0]*2,curr_size[1]*2)
00902         f.savefig(fig_name)
00903 
00904     if show_fig:
00905         pl.show()
00906     else:
00907         print '################################'
00908         print 'show_fig is FALSE'
00909         if not(expt_plot):
00910             pl.savefig(fig_name)
00911 
00912     if xyz_flag:
00913         plot_cartesian(traj, xaxis=0,yaxis=1,zaxis=2)
00914         mlab.show()
00915 
00916 
00917 
00918 
00919 
00920 
00921 


2010_icra_epc_pull
Author(s): Advait Jain, Charles C. Kemp (Healthcare Robotics Lab, Georgia Tech)
autogenerated on Wed Nov 27 2013 12:14:43