arm_trajectories.py
Go to the documentation of this file.
00001 
00002 import scipy.optimize as so
00003 
00004 import math, numpy as np
00005 import pylab as pl
00006 import sys, optparse, time
00007 import copy
00008 
00009 from enthought.mayavi import mlab
00010 
00011 
00012 #import util as ut
00013 import roslib; roslib.load_manifest('doors_forces_kinematics')
00014 roslib.load_manifest('epc_core')
00015 import cody_arms.arms as ca
00016 #import mekabot.coord_frames as mcf
00017 import cody_arms.coord_frames as mcf
00018 
00019 import hrl_lib.util as ut, hrl_lib.transforms as tr
00020 
00021 roslib.load_manifest('hrl_tilting_hokuyo')
00022 import hrl_tilting_hokuyo.display_3d_mayavi as d3m
00023 
00024 roslib.load_manifest('epc_door_opening')
00025 import epc_door_opening.segway_motion_calc as smc
00026 
00027 class JointTrajectory():
00028     ''' class to store joint trajectories.
00029         data only - use for pickling.
00030     '''
00031     def __init__(self):
00032         self.time_list = [] # time in seconds
00033         self.q_list = [] #each element is a list of 7 joint angles.
00034         self.qdot_list = [] #each element is a list of 7 joint angles.
00035         self.qdotdot_list = [] #each element is a list of 7 joint angles.
00036 
00037 ## class to store trajectory of a coord frame executing planar motion (x,y,a)
00038 #data only - use for pickling
00039 class PlanarTrajectory():
00040     def __init__(self):
00041         self.time_list = [] # time in seconds
00042         self.x_list = []
00043         self.y_list = []
00044         self.a_list = []
00045 
00046 class CartesianTajectory():
00047     ''' class to store trajectory of cartesian points.
00048         data only - use for pickling
00049     '''
00050     def __init__(self):
00051         self.time_list = [] # time in seconds
00052         self.p_list = [] #each element is a list of 3 coordinates
00053         self.v_list = [] #each element is a list of 3 coordinates (velocity)
00054 
00055 class ForceTrajectory():
00056     ''' class to store time evolution of the force at the end effector.
00057         data only - use for pickling
00058     '''
00059     def __init__(self):
00060         self.time_list = [] # time in seconds
00061         self.f_list = [] #each element is a list of 3 coordinates
00062 
00063 ##
00064 # @param traj - JointTrajectory
00065 # @return CartesianTajectory after performing FK on traj to compute
00066 # cartesian position, velocity
00067 def joint_to_cartesian(traj, arm):
00068     firenze = ca.M3HrlRobot(end_effector_length = 0.17318)
00069     #firenze = ca.M3HrlRobot()
00070     pts = []
00071     cart_vel = []
00072     for i in range(len(traj.q_list)):
00073         q = traj.q_list[i]
00074         p = firenze.FK(arm, q)
00075         pts.append(p.A1.tolist())
00076 
00077         if traj.qdot_list != [] and traj.qdot_list[0] != None:
00078             qdot = traj.qdot_list[i]
00079             jac = firenze.Jac(arm, q)
00080             vel = jac * np.matrix(qdot).T
00081             cart_vel.append(vel.A1[0:3].tolist())
00082 
00083     ct = CartesianTajectory()
00084     ct.time_list = copy.copy(traj.time_list)
00085     ct.p_list = copy.copy(pts)
00086     ct.v_list = copy.copy(cart_vel)
00087     #return np.matrix(pts).T
00088     return ct
00089 
00090 def plot_forces_quiver(pos_traj,force_traj,color='k'):
00091     import arm_trajectories as at
00092     #if traj.__class__ == at.JointTrajectory:
00093     if isinstance(pos_traj,at.JointTrajectory):
00094         pos_traj = joint_to_cartesian(pos_traj)
00095 
00096     pts = np.matrix(pos_traj.p_list).T
00097     label_list = ['X coord (m)', 'Y coord (m)', 'Z coord (m)']
00098     x = pts[0,:].A1.tolist()
00099     y = pts[1,:].A1.tolist()
00100 
00101     forces = np.matrix(force_traj.f_list).T
00102     u = (-1*forces[0,:]).A1.tolist()
00103     v = (-1*forces[1,:]).A1.tolist()
00104     pl.quiver(x,y,u,v,width=0.002,color=color,scale=100.0)
00105 #    pl.quiver(x,y,u,v,width=0.002,color=color)
00106     pl.axis('equal')
00107 
00108 ##
00109 # @param xaxis - x axis for the graph (0,1 or 2)
00110 # @param zaxis - for a 3d plot. not implemented.
00111 def plot_cartesian(traj, xaxis=None, yaxis=None, zaxis=None, color='b',label='_nolegend_',
00112                    linewidth=2, scatter_size=10, plot_velocity=False):
00113     import matplotlib_util.util as mpu
00114     import arm_trajectories as at
00115     #if traj.__class__ == at.JointTrajectory:
00116     if isinstance(traj,at.JointTrajectory):
00117         traj = joint_to_cartesian(traj)
00118 
00119     pts = np.matrix(traj.p_list).T
00120     label_list = ['X coord (m)', 'Y coord (m)', 'Z coord (m)']
00121     x = pts[xaxis,:].A1.tolist()
00122     y = pts[yaxis,:].A1.tolist()
00123 
00124     if plot_velocity:
00125         vels = np.matrix(traj.v_list).T
00126         xvel = vels[xaxis,:].A1.tolist()
00127         yvel = vels[yaxis,:].A1.tolist()
00128 
00129     if zaxis == None:
00130         mpu.plot_yx(y, x, color, linewidth, '-', scatter_size, label,
00131                     axis = 'equal', xlabel = label_list[xaxis],
00132                     ylabel = label_list[yaxis],)
00133         if plot_velocity:
00134             mpu.plot_quiver_yxv(y, x, np.matrix([xvel,yvel]),
00135                                 width = 0.001, scale = 1.)
00136         mpu.legend()
00137     else:
00138         from numpy import array
00139         from enthought.mayavi.api import Engine
00140         engine = Engine()
00141         engine.start()
00142         if len(engine.scenes) == 0:
00143             engine.new_scene()
00144 
00145         z = pts[zaxis,:].A1.tolist()
00146         time_list = [t-traj.time_list[0] for t in traj.time_list]
00147         mlab.plot3d(x,y,z,time_list,tube_radius=None,line_width=4)
00148         mlab.axes()
00149         mlab.xlabel(label_list[xaxis])
00150         mlab.ylabel(label_list[yaxis])
00151         mlab.zlabel(label_list[zaxis])
00152         mlab.colorbar(title='Time')
00153 
00154         # ------------------------------------------- 
00155         axes = engine.scenes[0].children[0].children[0].children[1]
00156         axes.axes.position = array([ 0.,  0.])
00157         axes.axes.label_format = '%-#6.2g'
00158         axes.title_text_property.font_size=4
00159 
00160 ## return two lists containing the radial and tangential components of the forces.
00161 # @param f_list - list of forces. (each force is a list of 2 or 3 floats)
00162 # @param p_list - list of positions. (each position is a list of 2 or 3 floats)
00163 # @param cx - x coord of the center of the circle.
00164 # @param cy - y coord of the center of the circle.
00165 # @return list of magnitude of radial component, list of magnitude
00166 # tangential component, list of the force along the remaining
00167 # direction
00168 def compute_radial_tangential_forces(f_list,p_list,cx,cy):
00169     f_rad_l,f_tan_l, f_res_l = [], [], []
00170     for f,p in zip(f_list,p_list):
00171         rad_vec = np.array([p[0]-cx,p[1]-cy])
00172         rad_vec = rad_vec/np.linalg.norm(rad_vec)
00173         tan_vec = (np.matrix([[0,-1],[1,0]]) * np.matrix(rad_vec).T).A1
00174         f_vec = np.array([f[0],f[1]])
00175 
00176         f_tan_mag = np.dot(f_vec, tan_vec)
00177         f_rad_mag = np.dot(f_vec, rad_vec)
00178 
00179 #        f_res_mag = np.linalg.norm(f_vec- rad_vec*f_rad_mag - tan_vec*f_tan_mag)
00180         f_rad_mag = abs(f_rad_mag)
00181         f_tan_mag = abs(f_tan_mag)
00182 
00183         f_rad_l.append(f_rad_mag)
00184         f_tan_l.append(f_tan_mag)
00185         f_res_l.append(abs(f[2]))
00186 
00187     return f_rad_l, f_tan_l, f_res_l
00188         
00189 
00190 
00191 def fit_circle_priors(rad_guess, x_guess, y_guess, pts, sigma_r,
00192                       sigma_xy, sigma_pts, verbose=True):
00193     global x_prior, y_prior
00194     x_prior = x_guess
00195     y_prior = y_guess
00196     def error_function(params):
00197         center = np.matrix((params[0],params[1])).T
00198         rad = params[2]
00199         err_pts = ut.norm(pts-center).A1 - rad
00200         lik = np.dot(err_pts, err_pts) / (sigma_pts * sigma_pts)
00201         pri = ((rad - rad_guess)**2) / (sigma_r * sigma_r)
00202         #pri += ((x_prior - center[0,0])**2) / (sigma_xy * sigma_xy)
00203         #pri += ((y_prior - center[1,0])**2) / (sigma_xy * sigma_xy)
00204         return (lik + pri)
00205 
00206     params_1 = [x_prior, y_prior, rad_guess]
00207     r = so.fmin_bfgs(error_function, params_1, full_output=1,
00208                      disp = verbose, gtol=1e-5)
00209     opt_params_1,fopt_1 = r[0],r[1]
00210 
00211     y_prior = y_guess + 2*rad_guess
00212     params_2 = [x_prior, y_prior, rad_guess]
00213     r = so.fmin_bfgs(error_function, params_2, full_output=1,
00214                      disp = verbose, gtol=1e-5)
00215     opt_params_2,fopt_2 = r[0],r[1]
00216 
00217     if fopt_2<fopt_1:
00218         return opt_params_2[2],opt_params_2[0],opt_params_2[1]
00219     else:
00220         return opt_params_1[2],opt_params_1[0],opt_params_1[1]
00221 
00222 
00223 
00224 ## find the x and y coord of the center of the circle and the radius that
00225 # best matches the data.
00226 # @param rad_guess - guess for the radius of the circle
00227 # @param x_guess - guess for x coord of center
00228 # @param y_guess - guess for y coord of center.
00229 # @param pts - 2xN np matrix of points.
00230 # @param method - optimization method. ('fmin' or 'fmin_bfgs')
00231 # @param verbose - passed onto the scipy optimize functions. whether to print out the convergence info.
00232 # @return r,x,y  (radius, x and y coord of the center of the circle)
00233 def fit_circle(rad_guess, x_guess, y_guess, pts, method, verbose=True,
00234                rad_fix = False):
00235     def error_function(params):
00236         center = np.matrix((params[0],params[1])).T
00237         if rad_fix:
00238             rad = rad_guess
00239         else:
00240             rad = params[2]
00241 
00242         err = ut.norm(pts-center).A1 - rad
00243         res = np.dot(err,err)
00244         #if not rad_fix and rad < 0.3:
00245         #    res = res*(0.3-rad)*100
00246         return res
00247 
00248     params_1 = [x_guess,y_guess]
00249     if not rad_fix:
00250         params_1.append(rad_guess)
00251     if method == 'fmin':
00252         r = so.fmin(error_function,params_1,xtol=0.0002,ftol=0.000001,full_output=1,disp=verbose)
00253         opt_params_1,fopt_1 = r[0],r[1]
00254     elif method == 'fmin_bfgs':
00255         r = so.fmin_bfgs(error_function, params_1, full_output=1,
00256                          disp = verbose, gtol=1e-5)
00257         opt_params_1,fopt_1 = r[0],r[1]
00258     else:
00259         raise RuntimeError('unknown method: '+method)
00260 
00261     params_2 = [x_guess,y_guess+2*rad_guess]
00262     if not rad_fix:
00263         params_2.append(rad_guess)
00264     if method == 'fmin':
00265         r = so.fmin(error_function,params_2,xtol=0.0002,ftol=0.000001,full_output=1,disp=verbose)
00266         opt_params_2,fopt_2 = r[0],r[1]
00267     elif method == 'fmin_bfgs':
00268         r = so.fmin_bfgs(error_function, params_2, full_output=1,
00269                          disp = verbose, gtol=1e-5)
00270         opt_params_2,fopt_2 = r[0],r[1]
00271     else:
00272         raise RuntimeError('unknown method: '+method)
00273 
00274     if fopt_2<fopt_1:
00275         if rad_fix:
00276             return rad_guess,opt_params_2[0],opt_params_2[1]
00277         else:
00278             return opt_params_2[2],opt_params_2[0],opt_params_2[1]
00279     else:
00280         if rad_fix:
00281             return rad_guess,opt_params_1[0],opt_params_1[1]
00282         else:
00283             return opt_params_1[2],opt_params_1[0],opt_params_1[1]
00284 
00285 
00286 ## changes the cartesian trajectory to put everything in the same frame.
00287 # NOTE - velocity transformation does not work if the segway is also
00288 # moving. This is because I am not logging the velocity of the segway.
00289 # @param pts - CartesianTajectory
00290 # @param st - object of type PlanarTrajectory (segway trajectory)
00291 # @return CartesianTajectory
00292 def account_segway_motion(cart_traj, force_traj, st):
00293     ct = CartesianTajectory()
00294     ft = ForceTrajectory()
00295     for i in range(len(cart_traj.p_list)):
00296         x,y,a = st.x_list[i], st.y_list[i], st.a_list[i]
00297         p_tl = np.matrix(cart_traj.p_list[i]).T
00298         p_ts = smc.tsTtl(p_tl, x, y, a)
00299         p = p_ts
00300         ct.p_list.append(p.A1.tolist())
00301 
00302         # transform forces to the world frame.
00303         f_tl = np.matrix(force_traj.f_list[i]).T
00304         f_ts = smc.tsRtl(f_tl, a)
00305         f = f_ts
00306         ft.f_list.append(f.A1.tolist())
00307 
00308         # this is incorrect. I also need to use the velocity of the
00309         # segway. Unclear whether this is useful right now, so not
00310         # implementing it. (Advait. Jan 6, 2010.)
00311         if cart_traj.v_list != []:
00312             v_tl = np.matrix(cart_traj.v_list[i]).T
00313             v_ts = smc.tsRtl(v_tl, a)
00314             ct.v_list.append(v_ts.A1.tolist())
00315 
00316     ct.time_list = copy.copy(cart_traj.time_list)
00317     ft.time_list = copy.copy(force_traj.time_list)
00318     return ct, ft
00319 
00320 # @param cart_traj - CartesianTajectory
00321 # @param z_l - list of zenither heights
00322 # @return CartesianTajectory
00323 def account_zenithering(cart_traj, z_l):
00324     ct = CartesianTajectory()
00325     h_start = z_l[0]
00326     for i in range(len(cart_traj.p_list)):
00327         h = z_l[i]
00328         p = cart_traj.p_list[i]
00329         p[2] += h - h_start
00330         ct.p_list.append(p)
00331 
00332         # this is incorrect. I also need to use the velocity of the
00333         # zenither. Unclear whether this is useful right now, so not
00334         # implementing it. (Advait. Jan 6, 2010.)
00335         if cart_traj.v_list != []:
00336             ct.v_list.append(cart_traj.v_list[i])
00337 
00338     ct.time_list = copy.copy(cart_traj.time_list)
00339     return ct
00340 
00341 ##
00342 # remove the initial part of the trjectory in which the hook is not moving.
00343 # @param ct - cartesian trajectory of the end effector in the world frame.
00344 # @return 2xN np matrix, reject_idx
00345 def filter_cartesian_trajectory(ct):
00346     pts_list = ct.p_list
00347     ee_start_pos = pts_list[0]
00348     l = [pts_list[0]]
00349 
00350     for i, p in enumerate(pts_list[1:]):
00351         l.append(p)
00352         pts_2d = (np.matrix(l).T)[0:2,:]
00353         st_pt = pts_2d[:,0]
00354         end_pt = pts_2d[:,-1]
00355         dist_moved = np.linalg.norm(st_pt-end_pt)
00356         #if dist_moved < 0.1:
00357         if dist_moved < 0.03:
00358             reject_idx = i
00359 
00360     pts_2d = pts_2d[:,reject_idx:]
00361     return pts_2d, reject_idx
00362 
00363 ##
00364 # remove the  last part of the trjectory in which the hook might have slipped off
00365 # @param ct - cartesian trajectory of the end effector in the world frame.
00366 # @param ft - force trajectory
00367 # @return cartesian trajectory with the zero force end part removed, force trajectory
00368 def filter_trajectory_force(ct, ft):
00369     vel_list = copy.copy(ct.v_list)
00370     pts_list = copy.copy(ct.p_list)
00371     time_list = copy.copy(ct.time_list)
00372     ft_list = copy.copy(ft.f_list)
00373     f_mag_list = ut.norm(np.matrix(ft.f_list).T).A1.tolist()
00374 
00375     if len(pts_list) != len(f_mag_list):
00376         print 'arm_trajectories.filter_trajectory_force: force and end effector lists are not of the same length.'
00377         print 'Exiting ...'
00378         sys.exit()
00379 
00380     n_pts = len(pts_list)
00381     i = n_pts - 1
00382     hook_slip_off_threshold = 1.5 # from compliant_trajectories.py
00383     while i > 0:
00384         if f_mag_list[i] < hook_slip_off_threshold:
00385             pts_list.pop()
00386             time_list.pop()
00387             ft_list.pop()
00388             if vel_list != []:
00389                 vel_list.pop()
00390         else:
00391             break
00392         i -= 1
00393 
00394     ct2 = CartesianTajectory()
00395     ct2.time_list = time_list
00396     ct2.p_list = pts_list
00397     ct2.v_list = vel_list
00398 
00399     ft2 = ForceTrajectory()
00400     ft2.time_list = copy.copy(time_list)
00401     ft2.f_list = ft_list
00402     return ct2, ft2
00403 
00404 
00405 if __name__ == '__main__':
00406     import matplotlib_util.util as mpu
00407 
00408     p = optparse.OptionParser()
00409     p.add_option('-f', action='store', type='string', dest='fname',
00410                  help='pkl file to use.', default='')
00411     p.add_option('--xy', action='store_true', dest='xy',
00412                  help='plot the x and y coordinates of the end effector.')
00413     p.add_option('--yz', action='store_true', dest='yz',
00414                  help='plot the y and z coordinates of the end effector.')
00415     p.add_option('--xz', action='store_true', dest='xz',
00416                  help='plot the x and z coordinates of the end effector.')
00417     p.add_option('--plot_ellipses', action='store_true', dest='plot_ellipses',
00418                  help='plot the stiffness ellipse in the x-y plane')
00419     p.add_option('--pfc', action='store_true', dest='pfc',
00420                  help='plot the radial and tangential components of the force.')
00421     p.add_option('--pff', action='store_true', dest='pff',
00422                  help='plot the force field corresponding to a stiffness ellipse.')
00423     p.add_option('--pev', action='store_true', dest='pev',
00424                  help='plot the stiffness ellipses for different combinations of the rel stiffnesses.')
00425     p.add_option('--plot_forces', action='store_true', dest='plot_forces',
00426                  help='plot the force in the x-y plane')
00427     p.add_option('--plot_forces_error', action='store_true', dest='plot_forces_error',
00428                  help='plot the error between the computed and measured (ATI) forces in the x-y plane')
00429     p.add_option('--xyz', action='store_true', dest='xyz',
00430                  help='plot in 3d the coordinates of the end effector.')
00431     p.add_option('-r', action='store', type='float', dest='rad',
00432                  help='radius of the joint.', default=None)
00433     p.add_option('--noshow', action='store_true', dest='noshow',
00434                  help='do not display the figure (use while saving figures to disk)')
00435     p.add_option('--exptplot', action='store_true', dest='exptplot',
00436                  help='put all the graphs of an experiment as subplots.')
00437     p.add_option('--sturm', action='store_true', dest='sturm',
00438                  help='make log files to send to sturm')
00439     p.add_option('--icra_presentation_plot', action='store_true',
00440                  dest='icra_presentation_plot',
00441                  help='plot explaining CEP update.')
00442 
00443     opt, args = p.parse_args()
00444     fname = opt.fname
00445     xy_flag = opt.xy
00446     yz_flag = opt.yz
00447     xz_flag = opt.xz
00448     plot_forces_flag = opt.plot_forces
00449     plot_ellipses_flag = opt.plot_ellipses
00450     plot_forces_error_flag = opt.plot_forces_error
00451     plot_force_components_flag = opt.pfc
00452     plot_force_field_flag = opt.pff
00453     xyz_flag = opt.xyz
00454     rad = opt.rad
00455     show_fig = not(opt.noshow)
00456     plot_ellipses_vary_flag = opt.pev
00457     expt_plot = opt.exptplot
00458     sturm_output = opt.sturm
00459 
00460 
00461     if plot_ellipses_vary_flag:
00462         show_fig=False
00463         i = 0
00464         ratio_list1 = [0.1,0.3,0.5,0.7,0.9] # coarse search
00465         ratio_list2 = [0.1,0.3,0.5,0.7,0.9] # coarse search
00466         ratio_list3 = [0.1,0.3,0.5,0.7,0.9] # coarse search
00467 #        ratio_list1 = [0.7,0.8,0.9,1.0]
00468 #        ratio_list2 = [0.7,0.8,0.9,1.0]
00469 #        ratio_list3 = [0.3,0.4,0.5,0.6,0.7]
00470 #        ratio_list1 = [1.0,2.,3.0]
00471 #        ratio_list2 = [1.,2.,3.]
00472 #        ratio_list3 = [0.3,0.4,0.5,0.6,0.7]
00473 
00474         inv_mean_list,std_list = [],[]
00475         x_l,y_l,z_l = [],[],[]
00476         s0 = 0.2
00477         #s0 = 0.4
00478         for s1 in ratio_list1:
00479             for s2 in ratio_list2:
00480                 for s3 in ratio_list3:
00481                     i += 1
00482                     s_list = [s0,s1,s2,s3,0.8]
00483                     #s_list = [s1,s2,s3,s0,0.8]
00484                     print '################## s_list:', s_list
00485                     m,s = plot_stiff_ellipse_map(s_list,i)
00486                     inv_mean_list.append(1./m)
00487                     std_list.append(s)
00488                     x_l.append(s1)
00489                     y_l.append(s2)
00490                     z_l.append(s3)
00491 
00492         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},
00493                        'stiff_dict_'+ut.formatted_time()+'.pkl')
00494         d3m.plot_points(np.matrix([x_l,y_l,z_l]),scalar_list=inv_mean_list,mode='sphere')
00495         mlab.axes()
00496         d3m.show()
00497 
00498         sys.exit()
00499 
00500     if fname=='':
00501         print 'please specify a pkl file (-f option)'
00502         print 'Exiting...'
00503         sys.exit()
00504 
00505     d = ut.load_pickle(fname)
00506     actual_cartesian_tl = joint_to_cartesian(d['actual'], d['arm'])
00507     actual_cartesian, _ = account_segway_motion(actual_cartesian_tl,d['force'], d['segway'])
00508     if d.has_key('zenither_list'):
00509         actual_cartesian = account_zenithering(actual_cartesian,
00510                                                d['zenither_list'])
00511 
00512     eq_cartesian_tl = joint_to_cartesian(d['eq_pt'], d['arm'])
00513     eq_cartesian, _ = account_segway_motion(eq_cartesian_tl, d['force'], d['segway'])
00514     if d.has_key('zenither_list'):
00515         eq_cartesian = account_zenithering(eq_cartesian, d['zenither_list'])
00516 
00517     cartesian_force_clean, _ = filter_trajectory_force(actual_cartesian,
00518                                                        d['force'])
00519     pts_2d, reject_idx = filter_cartesian_trajectory(cartesian_force_clean)
00520 
00521     if rad != None:
00522         #rad = 0.39 # lab cabinet recessed.
00523         #rad = 0.42 # kitchen cabinet
00524         #rad = 0.80 # lab glass door
00525         pts_list = actual_cartesian.p_list
00526         eq_pts_list = eq_cartesian.p_list
00527         ee_start_pos = pts_list[0]
00528         x_guess = ee_start_pos[0]
00529         y_guess = ee_start_pos[1] - rad
00530         print 'before call to fit_rotary_joint'
00531         force_list = d['force'].f_list
00532 
00533         if sturm_output:
00534             str_parts = fname.split('.')
00535             sturm_file_name = str_parts[0]+'_sturm.log'
00536             print 'Sturm file name:', sturm_file_name
00537             sturm_file = open(sturm_file_name,'w')
00538             sturm_pts = cartesian_force_clean.p_list
00539             print 'len(sturm_pts):', len(sturm_pts)
00540             print 'len(pts_list):', len(pts_list)
00541 
00542             for i,p in enumerate(sturm_pts[1:]):
00543                 sturm_file.write(" ".join(map(str,p)))
00544                 sturm_file.write('\n')
00545 
00546             sturm_file.write('\n')
00547             sturm_file.close()
00548 
00549         rad_guess = rad
00550         rad, cx, cy = fit_circle(rad_guess,x_guess,y_guess,pts_2d,
00551                                  method='fmin_bfgs',verbose=False)
00552         print 'rad, cx, cy:', rad, cx, cy
00553         c_ts = np.matrix([cx, cy, 0.]).T
00554         start_angle = tr.angle_within_mod180(math.atan2(pts_2d[1,0]-cy,
00555                                pts_2d[0,0]-cx) - math.pi/2)
00556         end_angle = tr.angle_within_mod180(math.atan2(pts_2d[1,-1]-cy,
00557                                pts_2d[0,-1]-cx) - math.pi/2)
00558         mpu.plot_circle(cx, cy, rad, start_angle, end_angle,
00559                         label='Actual\_opt', color='r')
00560 
00561 
00562     if opt.icra_presentation_plot:
00563         mpu.set_figure_size(30,20)
00564         rad = 1.0
00565         x_guess = pts_2d[0,0]
00566         y_guess = pts_2d[1,0] - rad
00567 
00568         rad_guess = rad
00569         rad, cx, cy = fit_circle(rad_guess,x_guess,y_guess,pts_2d,
00570                                  method='fmin_bfgs',verbose=False)
00571         print 'Estimated rad, cx, cy:', rad, cx, cy
00572 
00573         start_angle = tr.angle_within_mod180(math.atan2(pts_2d[1,0]-cy,
00574                                pts_2d[0,0]-cx) - math.pi/2)
00575         end_angle = tr.angle_within_mod180(math.atan2(pts_2d[1,-1]-cy,
00576                                pts_2d[0,-1]-cx) - math.pi/2)
00577 
00578         subsample_ratio = 1
00579         pts_2d_s = pts_2d[:,::subsample_ratio]
00580 
00581         cep_force_clean, force_new = filter_trajectory_force(eq_cartesian,
00582                                                              d['force'])
00583         cep_2d = np.matrix(cep_force_clean.p_list).T[0:2,reject_idx:]
00584 
00585         # first draw the entire CEP and end effector trajectories
00586         mpu.figure()
00587         mpu.plot_yx(pts_2d_s[1,:].A1, pts_2d_s[0,:].A1, color='b',
00588                     label = '\huge{End Effector Trajectory}', axis = 'equal', alpha = 1.0,
00589                     scatter_size=7, linewidth=0, marker='x',
00590                     marker_edge_width = 1.5)
00591 
00592         cep_2d_s = cep_2d[:,::subsample_ratio]
00593         mpu.plot_yx(cep_2d_s[1,:].A1, cep_2d_s[0,:].A1, color='g',
00594                     label = '\huge{Equilibrium Point Trajectory}', axis = 'equal', alpha = 1.0,
00595                     scatter_size=10, linewidth=0, marker='+',
00596                     marker_edge_width = 1.5)
00597 
00598         mpu.plot_circle(cx, cy, rad, start_angle, end_angle,
00599                         label='\huge{Estimated Kinematics}', color='r',
00600                         alpha=0.7)
00601         mpu.plot_radii(cx, cy, rad, start_angle, end_angle,
00602                        interval=end_angle-start_angle, color='r',
00603                        alpha=0.7)
00604         mpu.legend()
00605         fig_name = 'epc'
00606         fig_number = 1
00607         mpu.savefig(fig_name+'%d'%fig_number)
00608         fig_number += 1
00609 
00610         # now zoom in to a small region to show the force
00611         # decomposition.
00612         zoom_location = 10
00613         pts_2d_zoom = pts_2d[:,:zoom_location]
00614         cep_2d_zoom = cep_2d[:,:zoom_location]
00615 
00616 #        image_name = 'anim'
00617 #        for i in range(zoom_location):
00618 #            mpu.figure()
00619 #            mpu.plot_yx(pts_2d_zoom[1,:].A1, pts_2d_zoom[0,:].A1, color='w',
00620 #                        axis = 'equal', alpha = 1.0)
00621 #            mpu.plot_yx(cep_2d_zoom[1,:].A1, cep_2d_zoom[0,:].A1, color='w',
00622 #                        axis = 'equal', alpha = 1.0)
00623 #            mpu.plot_yx(pts_2d_zoom[1,:i+1].A1, pts_2d_zoom[0,:i+1].A1, color='b',
00624 #                        label = '\huge{End Effector Trajectory}', axis = 'equal', alpha = 1.0,
00625 #                        scatter_size=7, linewidth=0, marker='x',
00626 #                        marker_edge_width = 1.5)
00627 #            mpu.plot_yx(cep_2d_zoom[1,:i+1].A1, cep_2d_zoom[0,:i+1].A1, color='g',
00628 #                        label = '\huge{Equilibrium Point Trajectory}', axis = 'equal', alpha = 1.0,
00629 #                        scatter_size=10, linewidth=0, marker='+',
00630 #                        marker_edge_width = 1.5)
00631 #            mpu.pl.xlim(0.28, 0.47)
00632 #            mpu.legend()
00633 #            mpu.savefig(image_name+'%d.png'%(i+1))
00634 
00635         mpu.figure()
00636         mpu.plot_yx(pts_2d_zoom[1,:].A1, pts_2d_zoom[0,:].A1, color='b',
00637                     label = '\huge{End Effector Trajectory}', axis = 'equal', alpha = 1.0,
00638                     scatter_size=7, linewidth=0, marker='x',
00639                     marker_edge_width = 1.5)
00640         mpu.plot_yx(cep_2d_zoom[1,:].A1, cep_2d_zoom[0,:].A1, color='g',
00641                     label = '\huge{Equilibrium Point Trajectory}', axis = 'equal', alpha = 1.0,
00642                     scatter_size=10, linewidth=0, marker='+',
00643                     marker_edge_width = 1.5)
00644         mpu.pl.xlim(0.28, 0.47)
00645         mpu.legend()
00646         #mpu.savefig('two.png')
00647         mpu.savefig(fig_name+'%d'%fig_number)
00648         fig_number += 1
00649 
00650         rad, cx, cy = fit_circle(1.0,x_guess,y_guess,pts_2d_zoom,
00651                                  method='fmin_bfgs',verbose=False)
00652         print 'Estimated rad, cx, cy:', rad, cx, cy
00653         start_angle = tr.angle_within_mod180(math.atan2(pts_2d[1,0]-cy,
00654                                pts_2d[0,0]-cx) - math.pi/2)
00655         end_angle = tr.angle_within_mod180(math.atan2(pts_2d_zoom[1,-1]-cy,
00656                                pts_2d_zoom[0,-1]-cx) - math.pi/2)
00657         mpu.plot_circle(cx, cy, rad, start_angle, end_angle,
00658                         label='\huge{Estimated Kinematics}', color='r',
00659                         alpha=0.7)
00660         mpu.pl.xlim(0.28, 0.47)
00661         mpu.legend()
00662         #mpu.savefig('three.png')
00663         mpu.savefig(fig_name+'%d'%fig_number)
00664         fig_number += 1
00665 
00666         current_pos = pts_2d_zoom[:,-1]
00667         radial_vec = current_pos - np.matrix([cx,cy]).T
00668         radial_vec = radial_vec / np.linalg.norm(radial_vec)
00669         tangential_vec = np.matrix([[0,-1],[1,0]]) * radial_vec
00670         mpu.plot_quiver_yxv([pts_2d_zoom[1,-1]],
00671                             [pts_2d_zoom[0,-1]],
00672                             radial_vec, scale=10., width = 0.002)
00673         rad_text_loc = pts_2d_zoom[:,-1] + np.matrix([0.001,0.01]).T
00674         mpu.pl.text(rad_text_loc[0,0], rad_text_loc[1,0], '$\hat v_{rad}$', fontsize = 30)
00675         mpu.plot_quiver_yxv([pts_2d_zoom[1,-1]],
00676                             [pts_2d_zoom[0,-1]],
00677                             tangential_vec, scale=10., width = 0.002)
00678 
00679         tan_text_loc = pts_2d_zoom[:,-1] + np.matrix([-0.012, -0.011]).T
00680         mpu.pl.text(tan_text_loc[0,0], tan_text_loc[1,0], s = '$\hat v_{tan}$', fontsize = 30)
00681         mpu.pl.xlim(0.28, 0.47)
00682         mpu.legend()
00683         #mpu.savefig('four.png')
00684         mpu.savefig(fig_name+'%d'%fig_number)
00685         fig_number += 1
00686 
00687         wrist_color = '#A0A000'
00688         wrist_force = -np.matrix(force_new.f_list[zoom_location]).T
00689         frad = (wrist_force[0:2,:].T * radial_vec)[0,0] * radial_vec
00690         mpu.plot_quiver_yxv([pts_2d_zoom[1,-1]],
00691                             [pts_2d_zoom[0,-1]],
00692                             wrist_force, scale=50., width = 0.002,
00693                             color=wrist_color)
00694                             #color='y')
00695         wf_text = rad_text_loc + np.matrix([-0.06,0.015]).T
00696         mpu.pl.text(wf_text[0,0], wf_text[1,0], color=wrist_color,
00697                     fontsize = 25, s = 'Total Force')
00698 
00699         mpu.plot_quiver_yxv([pts_2d_zoom[1,-1]],
00700                             [pts_2d_zoom[0,-1]],
00701                             frad, scale=50., width = 0.002,
00702                             color=wrist_color)
00703         frad_text = rad_text_loc + np.matrix([0.,0.015]).T
00704         mpu.pl.text(frad_text[0,0], frad_text[1,0], color=wrist_color, s = '$\hat F_{rad}$', fontsize = 30)
00705 
00706         mpu.pl.xlim(0.28, 0.47)
00707         mpu.legend()
00708         #mpu.savefig('five.png')
00709         mpu.savefig(fig_name+'%d'%fig_number)
00710         fig_number += 1
00711 
00712         frad = (wrist_force[0:2,:].T * radial_vec)[0,0]
00713         hook_force_motion = -(frad - 5) * radial_vec * 0.001
00714         tangential_motion = 0.01 * tangential_vec
00715         total_cep_motion = hook_force_motion + tangential_motion
00716 
00717         mpu.plot_quiver_yxv([cep_2d_zoom[1,-1]],
00718                             [cep_2d_zoom[0,-1]],
00719                             hook_force_motion, scale=0.1, width = 0.002)
00720         hw_text = cep_2d_zoom[:,-1] + np.matrix([-0.002,-0.012]).T
00721         mpu.pl.text(hw_text[0,0], hw_text[1,0], color='k', fontsize=20,
00722                     s = '$h[t]$')
00723         mpu.pl.xlim(0.28, 0.47)
00724         mpu.legend()
00725         #mpu.savefig('six.png')
00726         mpu.savefig(fig_name+'%d'%fig_number)
00727         fig_number += 1
00728 
00729         mpu.plot_quiver_yxv([cep_2d_zoom[1,-1]],
00730                             [cep_2d_zoom[0,-1]],
00731                             tangential_motion, scale=0.1, width = 0.002)
00732         mw_text = cep_2d_zoom[:,-1] + np.matrix([-0.018,0.001]).T
00733         mpu.pl.text(mw_text[0,0], mw_text[1,0], color='k', fontsize=20,
00734                     s = '$m[t]$')
00735         mpu.pl.xlim(0.28, 0.47)
00736         mpu.legend()
00737         #mpu.savefig('seven.png')
00738         mpu.savefig(fig_name+'%d'%fig_number)
00739         fig_number += 1
00740 
00741         mpu.plot_quiver_yxv([cep_2d_zoom[1,-1]],
00742                             [cep_2d_zoom[0,-1]],
00743                             total_cep_motion, scale=0.1, width = 0.002)
00744         cep_text = cep_2d_zoom[:,-1] + np.matrix([-0.058,-0.023]).T
00745         mpu.pl.text(cep_text[0,0], cep_text[1,0], color='k', fontsize=20,
00746                     s = '$x_{eq}[t]$ = &x_{eq}[t-1] + m[t] + h[t]$')
00747         mpu.pl.xlim(0.28, 0.47)
00748         mpu.legend()
00749         #mpu.savefig('eight.png')
00750         mpu.savefig(fig_name+'%d'%fig_number)
00751         fig_number += 1
00752 
00753         new_cep = cep_2d_zoom[:,-1] + total_cep_motion
00754         mpu.plot_yx(new_cep[1,:].A1, new_cep[0,:].A1, color='g',
00755                     axis = 'equal', alpha = 1.0,
00756                     scatter_size=10, linewidth=0, marker='+',
00757                     marker_edge_width = 1.5)
00758         mpu.pl.xlim(0.28, 0.47)
00759         mpu.legend()
00760         #mpu.savefig('nine.png')
00761         mpu.savefig(fig_name+'%d'%fig_number)
00762         fig_number += 1
00763 
00764         mpu.show()
00765 
00766     if xy_flag:
00767         st_pt = pts_2d[:,0]
00768         end_pt = pts_2d[:,-1]
00769 
00770         if expt_plot:
00771             pl.subplot(233)
00772 
00773         plot_cartesian(actual_cartesian, xaxis=0, yaxis=1, color='b',
00774                        label='FK', plot_velocity=False)
00775         plot_cartesian(eq_cartesian, xaxis=0,yaxis=1,color='g',label='Eq Point')
00776 
00777     elif yz_flag:
00778         plot_cartesian(actual_cartesian,xaxis=1,yaxis=2,color='b',label='FK')
00779         plot_cartesian(eq_cartesian, xaxis=1,yaxis=2,color='g',label='Eq Point')
00780     elif xz_flag:
00781         plot_cartesian(actual_cartesian,xaxis=0,yaxis=2,color='b',label='FK')
00782         plot_cartesian(eq_cartesian, xaxis=0,yaxis=2,color='g',label='Eq Point')
00783 
00784 
00785     if plot_forces_flag or plot_forces_error_flag or plot_ellipses_flag or plot_force_components_flag or plot_force_field_flag:
00786         #        arm_stiffness_list = d['stiffness'].stiffness_list
00787         #        scale = d['stiffness'].stiffness_scale
00788         #        asl = [min(scale*s,1.0) for s in arm_stiffness_list]
00789         #        ftraj_jinv,ftraj_stiff,ftraj_torque,k_cart_list=compute_forces(d['actual'],d['eq_pt'],
00790         #                                                                       d['torque'],asl)
00791         if plot_forces_flag:
00792             plot_forces_quiver(actual_cartesian,d['force'],color='k')
00793             #plot_forces_quiver(actual_cartesian,ftraj_jinv,color='y')
00794             #plot_forces_quiver(actual_cartesian,ftraj_stiff,color='y')
00795 
00796         if plot_ellipses_flag:
00797             #plot_stiff_ellipses(k_cart_list,actual_cartesian)
00798             if expt_plot:
00799                 subplotnum=234
00800             else:
00801                 pl.figure()
00802                 subplotnum=111
00803             plot_stiff_ellipses(k_cart_list,eq_cartesian,subplotnum=subplotnum)
00804 
00805         if plot_forces_error_flag:
00806             plot_error_forces(d['force'].f_list,ftraj_jinv.f_list)
00807             #plot_error_forces(d['force'].f_list,ftraj_stiff.f_list)
00808 
00809         if plot_force_components_flag:
00810             p_list = actual_cartesian.p_list
00811             #cx = 45.
00812             #cy = -0.3
00813             frad_list,ftan_list,_ = compute_radial_tangential_forces(d['force'].f_list,p_list,cx,cy)
00814             #frad_list,ftan_list,_ = compute_radial_tangential_forces(d['force_raw'].f_list,p_list,cx,cy)
00815             if expt_plot:
00816                 pl.subplot(235)
00817             else:
00818                 pl.figure()
00819 
00820             time_list = d['force'].time_list
00821             time_list = [t-time_list[0] for t in time_list]
00822             x_coord_list = np.matrix(p_list)[:,0].A1.tolist()
00823             mpu.plot_yx(frad_list,x_coord_list,scatter_size=50,color=time_list,cb_label='time',axis=None)
00824             pl.xlabel('x coord of end effector (m)')
00825             pl.ylabel('magnitude of radial force (N)')
00826             pl.title(d['info'])
00827             if expt_plot:
00828                 pl.subplot(236)
00829             else:
00830                 pl.figure()
00831             mpu.plot_yx(ftan_list,x_coord_list,scatter_size=50,color=time_list,cb_label='time',axis=None)
00832             pl.xlabel('x coord of end effector (m)')
00833             pl.ylabel('magnitude of tangential force (N)')
00834             pl.title(d['info'])
00835 
00836         if plot_force_field_flag:
00837             plot_stiffness_field(k_cart_list[0],plottitle='start')
00838             plot_stiffness_field(k_cart_list[-1],plottitle='end')
00839 
00840 
00841     str_parts = fname.split('.')
00842     if d.has_key('strategy'):
00843         addon = ''
00844         if opt.xy:
00845             addon = '_xy'
00846         if opt.xz:
00847             addon = '_xz'
00848         fig_name = str_parts[0]+'_'+d['strategy']+addon+'.png'
00849     else:
00850         fig_name = str_parts[0]+'_res.png'
00851 
00852     if expt_plot:
00853         f = pl.gcf()
00854         curr_size = f.get_size_inches()
00855         f.set_size_inches(curr_size[0]*2,curr_size[1]*2)
00856         f.savefig(fig_name)
00857 
00858     if show_fig:
00859         pl.show()
00860     else:
00861         print '################################'
00862         print 'show_fig is FALSE'
00863         if not(expt_plot):
00864             pl.savefig(fig_name)
00865 
00866     if xyz_flag:
00867         plot_cartesian(traj, xaxis=0,yaxis=1,zaxis=2)
00868         mlab.show()
00869 
00870 
00871 
00872 
00873 
00874 
00875 
00876 #--------------------- OLD, maybe useful functions -------------------
00877 
00878 
00879 ### compute the force that the arm would apply given the stiffness matrix
00880 ## @param  q_actual_traj - Joint Trajectory (actual angles.)
00881 ## @param  q_eq_traj - Joint Trajectory (equilibrium point angles.)
00882 ## @param torque_traj - JointTrajectory (torques measured at the joints.)
00883 ## @param rel_stiffness_list - list of 5 elements (stiffness numbers for the joints.)
00884 ## @return lots of things, look at the code.
00885 #def compute_forces(q_actual_traj,q_eq_traj,torque_traj,rel_stiffness_list):
00886 #    firenze = hr.M3HrlRobot(connect=False)
00887 #
00888 #    d_gains_list_mN_deg_sec = [-100,-120,-15,-25,-1.25]
00889 #    d_gains_list = [180./1000.*s/math.pi for s in d_gains_list_mN_deg_sec]
00890 #
00891 #    stiff_list_mNm_deg = [1800,1300,350,600,60]
00892 #    stiff_list_Nm_rad = [180./1000.*s/math.pi for s in stiff_list_mNm_deg]
00893 ##    stiffness_settings = [0.15,0.7,0.8,0.8,0.8]
00894 ##    dia = np.array(stiffness_settings) * np.array(stiff_list_Nm_rad)
00895 #    dia = np.array(rel_stiffness_list) * np.array(stiff_list_Nm_rad)
00896 #    k_q = np.matrix(np.diag(dia))
00897 #    dia_inv = 1./dia
00898 #    k_q_inv = np.matrix(np.diag(dia_inv))
00899 #
00900 #    actual_cart = joint_to_cartesian(q_actual_traj)
00901 #    eq_cart = joint_to_cartesian(q_eq_traj)
00902 #    force_traj_jacinv = ForceTrajectory()
00903 #    force_traj_stiff = ForceTrajectory()
00904 #    force_traj_torque = ForceTrajectory()
00905 #
00906 #    k_cart_list = []
00907 #
00908 #    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):
00909 #        q_eq = firenze.clamp_to_physical_joint_limits('right_arm',q_eq)
00910 #        q_delta = np.matrix(q_actual).T - np.matrix(q_eq).T
00911 #        tau = k_q * q_delta[0:5,0] - np.matrix(np.array(d_gains_list)*np.array(q_dot)[0:5]).T
00912 #
00913 #        x_delta = np.matrix(actual_pos).T - np.matrix(eq_pos).T
00914 #
00915 #        jac_full = firenze.Jac('right_arm',q_actual)
00916 #        jac = jac_full[0:3,0:5]
00917 #
00918 #        jac_full_eq = firenze.Jac('right_arm',q_eq)
00919 #        jac_eq = jac_full_eq[0:3,0:5]
00920 #        k_cart = np.linalg.inv((jac_eq*k_q_inv*jac_eq.T))    # calculating stiff matrix using Jacobian for eq pt.
00921 #        k_cart_list.append(k_cart)
00922 #
00923 #        pseudo_inv_jac = np.linalg.inv(jac_full*jac_full.T)*jac_full
00924 #
00925 #        tau_full = np.row_stack((tau,np.matrix(tau_m[5:7]).T))
00926 #        #force = (-1*pseudo_inv_jac*tau_full)[0:3]
00927 #        force = -1*pseudo_inv_jac[0:3,0:5]*tau
00928 #        force_traj_jacinv.f_list.append(force.A1.tolist())
00929 #        force_traj_stiff.f_list.append((k_cart*x_delta).A1.tolist())
00930 #        force_traj_torque.f_list.append((pseudo_inv_jac*np.matrix(tau_m).T)[0:3].A1.tolist())
00931 #
00932 #    return force_traj_jacinv,force_traj_stiff,force_traj_torque,k_cart_list
00933 
00934 
00935 
00936 
00937 
00938 ### def plot_error_forces(measured_list,calc_list):
00939 ###     err_x, err_y = [],[]
00940 ###     err_rel_x, err_rel_y = [],[]
00941 ###     mag_x, mag_y = [],[]
00942 ###     for m,c in zip(measured_list,calc_list):
00943 ###         err_x.append(abs(m[0]-c[0]))
00944 ###         err_rel_x.append(abs(m[0]-c[0])/abs(m[0])*100)
00945 ###         #err_rel_x.append(ut.bound(abs(m[0]-c[0])/abs(m[0])*100,100,0))
00946 ###         mag_x.append(abs(m[0]))
00947 ###         err_y.append(abs(m[1]-c[1]))
00948 ###         err_rel_y.append(abs(m[1]-c[1])/abs(m[1])*100)
00949 ###         #err_rel_y.append(ut.bound(abs(m[1]-c[1])/abs(m[1])*100,100,0))
00950 ###         mag_y.append(abs(m[1]))
00951 ### 
00952 ###     x_idx = range(len(err_x))
00953 ###     zero = [0 for i in x_idx]
00954 ### 
00955 ###     fig = pl.figure()
00956 ###     ax1 = fig.add_subplot(111)
00957 ###     ax2 = ax1.twinx()
00958 ### 
00959 ###     ax1.plot(zero,c='k',linewidth=1,label='_nolegend_')
00960 ###     l1 = ax1.plot(err_x,c='b',linewidth=1,label='absolute error')
00961 ###     ax1.scatter(x_idx,err_x,c='b',s=10,label='_nolegend_', linewidths=0)
00962 ###     l2 = ax1.plot(mag_x,c='g',linewidth=1,label='magnitude')
00963 ###     ax1.scatter(x_idx,mag_x,c='g',s=10,label='_nolegend_', linewidths=0)
00964 ###     l3 = ax2.plot(err_rel_x,c='r',linewidth=1,label='relative error %')
00965 ### 
00966 ###     ax1.set_ylim(0,15)
00967 ###     ax2.set_ylim(0,100)
00968 ###     ax1.set_xlabel('measurement number')
00969 ###     ax1.set_ylabel('x component of force (N)')
00970 ###     ax2.set_ylabel('percentage error')
00971 ###     ax1.yaxis.set_label_coords(-0.3,0.5)
00972 ###     ax2.yaxis.set_label_coords(-0.3,0.5)
00973 ###     leg = pl.legend([l1,l2,l3],['absolute error','magnitude','rel error %'],loc='upper left',
00974 ###               handletextsep=0.015,handlelen=0.003,labelspacing=0.003)
00975 ### 
00976 ###     fig = pl.figure()
00977 ###     ax1 = fig.add_subplot(111)
00978 ###     ax2 = ax1.twinx()
00979 ### 
00980 ###     ax1.plot(zero,c='k',linewidth=1)
00981 ###     l1 = ax1.plot(err_y,c='b',linewidth=1)
00982 ###     ax1.scatter(x_idx,err_y,c='b',s=10, linewidths=0)
00983 ###     l2 = ax1.plot(mag_y,c='g',linewidth=1)
00984 ###     ax1.scatter(x_idx,mag_y,c='g',s=10,linewidths=0)
00985 ###     l3 = ax2.plot(err_rel_y,c='r',linewidth=1)
00986 ### 
00987 ###     ax1.set_ylim(0,15)
00988 ###     ax2.set_ylim(0,100)
00989 ###     ax1.yaxis.set_label_coords(-0.3,0.5)
00990 ###     ax2.yaxis.set_label_coords(-0.3,0.5)
00991 ###     ax1.set_xlabel('measurement number')
00992 ###     ax1.set_ylabel('y component of force (N)')
00993 ###     ax2.set_ylabel('percentage error')
00994 ###     #pl.legend(loc='best')
00995 ###     leg = pl.legend([l1,l2,l3],['absolute error','magnitude','rel error %'],loc='upper left',
00996 ###               handletextsep=0.015,handlelen=0.003,labelspacing=0.003)
00997 ### 
00998 ### #    pl.figure()
00999 ### #    pl.plot(zero,c='k',linewidth=0.5,label='_nolegend_')
01000 ### #    pl.plot(err_y,c='b',linewidth=1,label='error')
01001 ### #    pl.plot(err_rel_y,c='r',linewidth=1,label='relative error %')
01002 ### #    pl.scatter(x_idx,err_y,c='b',s=10,label='_nolegend_', linewidths=0)
01003 ### #    pl.plot(mag_y,c='g',linewidth=1,label='magnitude')
01004 ### #    pl.scatter(x_idx,mag_y,c='g',s=10,label='_nolegend_', linewidths=0)
01005 ### #
01006 ### #    pl.xlabel('measurement number')
01007 ### #    pl.ylabel('y component of force (N)')
01008 ### #    pl.legend(loc='best')
01009 ### #    pl.axis('equal')
01010 ### 
01011 ### 
01012 ### def plot_stiff_ellipses(k_cart_list,pos_traj,skip=10,subplotnum=111):
01013 ###     import arm_trajectories as at
01014 ###     if isinstance(pos_traj,at.JointTrajectory):
01015 ###         pos_traj = joint_to_cartesian(pos_traj)
01016 ### 
01017 ###     pts = np.matrix(pos_traj.p_list).T
01018 ###     x_l = pts[0,:].A1.tolist()
01019 ###     y_l = pts[1,:].A1.tolist()
01020 ###     
01021 ###     from pylab import figure, show, rand
01022 ###     from matplotlib.patches import Ellipse
01023 ### 
01024 ###     ells = []
01025 ###     scale = 25000.
01026 ###     ratio_list = []
01027 ###     for k_c,x,y in zip(k_cart_list[::skip],x_l[::skip],y_l[::skip]):
01028 ###         w,v = np.linalg.eig(k_c[0:2,0:2])
01029 ###         w_abs = np.abs(w)
01030 ###         major_axis = np.max(w_abs)
01031 ###         minor_axis = np.min(w_abs)
01032 ###         print 'major, minor:',major_axis,minor_axis
01033 ### #        print 'k_c:', k_c
01034 ###         ratio_list.append(major_axis/minor_axis)
01035 ### 
01036 ###         ells.append(Ellipse(np.array([x,y]),width=w[0]/scale,height=w[1]/scale,angle=math.degrees(math.atan2(v[1,0],v[0,0]))))
01037 ###         ells[-1].set_lw(2)
01038 ###         
01039 ###     #fig = pl.figure()
01040 ###     #ax = fig.add_subplot(111, aspect='equal')
01041 ###     ax = pl.subplot(subplotnum, aspect='equal')
01042 ### 
01043 ###     for e in ells:
01044 ###         ax.add_artist(e)
01045 ###         #e.set_clip_box(ax.bbox)
01046 ###         #e.set_alpha(1.)
01047 ###         e.set_facecolor(np.array([1,1,1]))
01048 ### 
01049 ###     plot_cartesian(pos_traj,xaxis=0,yaxis=1,color='b',
01050 ###                    linewidth=0.0,scatter_size=0)
01051 ### #    plot_cartesian(pos_traj,xaxis=0,yaxis=1,color='b',label='Eq Point',
01052 ### #                   linewidth=1.5,scatter_size=0)
01053 ### #    plot_cartesian(d['actual'],xaxis=0,yaxis=1,color='b',label='FK',
01054 ### #                   linewidth=1.5,scatter_size=0)
01055 ### #    plot_cartesian(d['eq_pt'], xaxis=0,yaxis=1,color='g',label='Eq Point',
01056 ### #                   linewidth=1.5,scatter_size=0)
01057 ### 
01058 ###     mean_ratio = np.mean(np.array(ratio_list))
01059 ###     std_ratio = np.std(np.array(ratio_list))
01060 ### 
01061 ###     return mean_ratio,std_ratio
01062 ### 
01063 ### # plot the force field in the xy plane for the stiffness matrix k_cart.
01064 ### ## @param k_cart: 3x3 cartesian space stiffness matrix.
01065 ### def plot_stiffness_field(k_cart,plottitle=''):
01066 ###     n_points = 20
01067 ###     ang_step = math.radians(360)/n_points
01068 ###     x_list = []
01069 ###     y_list = []
01070 ###     u_list = []
01071 ###     v_list = []
01072 ###     k_cart = k_cart[0:2,0:2]
01073 ### 
01074 ###     for i in range(n_points):
01075 ###         ang = i*ang_step
01076 ###         for r in [0.5,1.,1.5]:
01077 ###             dx = r*math.cos(ang)
01078 ###             dy = r*math.sin(ang)
01079 ###             dtau = -k_cart*np.matrix([dx,dy]).T
01080 ###             x_list.append(dx)
01081 ###             y_list.append(dy)
01082 ###             u_list.append(dtau[0,0])
01083 ###             v_list.append(dtau[1,0])
01084 ###     
01085 ###     pl.figure()
01086 ### #    mpu.plot_circle(0,0,1.0,0.,math.radians(360))
01087 ###     mpu.plot_radii(0,0,1.5,0.,math.radians(360),interval=ang_step,color='r')
01088 ###     pl.quiver(x_list,y_list,u_list,v_list,width=0.002,color='k',scale=None)
01089 ###     pl.axis('equal')
01090 ###     pl.title(plottitle)
01091 ### 
01092 ### def plot_stiff_ellipse_map(stiffness_list,num):
01093 ###     firenze = hr.M3HrlRobot(connect=False)
01094 ###     hook_3dprint_angle = math.radians(20-2.54)
01095 ###     rot_mat = tr.Rz(0.-hook_3dprint_angle)*tr.Ry(math.radians(-90))
01096 ### 
01097 ###     d_gains_list_mN_deg_sec = [-100,-120,-15,-25,-1.25]
01098 ###     d_gains_list = [180./1000.*s/math.pi for s in d_gains_list_mN_deg_sec]
01099 ### 
01100 ###     stiff_list_mNm_deg = [1800,1300,350,600,60]
01101 ###     stiff_list_Nm_rad = [180./1000.*s/math.pi for s in stiff_list_mNm_deg]
01102 ###     dia = np.array(stiffness_list) * np.array(stiff_list_Nm_rad)
01103 ###     k_q = np.matrix(np.diag(dia))
01104 ###     dia_inv = 1./dia
01105 ###     k_q_inv = np.matrix(np.diag(dia_inv))
01106 ### 
01107 ###     s0,s1,s2,s3 = stiffness_list[0],stiffness_list[1],stiffness_list[2],stiffness_list[3]
01108 ### 
01109 ###     i=0
01110 ###     #for z in np.arange(-0.1,-0.36,-0.05):
01111 ###     for z in np.arange(-0.23,-0.27,-0.05):
01112 ###         pl.figure()
01113 ###         k_cart_list = []
01114 ###         pos_traj = CartesianTajectory()
01115 ###         for x in np.arange(0.25,0.56,0.05):
01116 ###             for y in np.arange(-0.15,-0.56,-0.05):
01117 ###                 if math.sqrt(x**2+y**2)>0.55:
01118 ###                     continue
01119 ###                 q = firenze.IK('right_arm',np.matrix([x,y,z]).T,rot_mat)
01120 ###                 if q == None:
01121 ###                     continue
01122 ###                 jac_full = firenze.Jac('right_arm',q)
01123 ###                 jac = jac_full[0:3,0:5]
01124 ###                 k_cart = np.linalg.inv((jac*k_q_inv*jac.T))
01125 ###                 k_cart_list.append(k_cart)
01126 ###                 pos_traj.p_list.append([x,y,z])
01127 ###                 pos_traj.time_list.append(0.1)
01128 ###         if len(pos_traj.p_list)>0:
01129 ###             ret = plot_stiff_ellipses(k_cart_list,pos_traj,skip=1)
01130 ###             pl.axis('equal')
01131 ###             pl.legend(loc='best')
01132 ###             title_string = 'z: %.2f stiff:[%.1f,%.1f,%.1f,%.1f]'%(z,s0,s1,s2,s3)
01133 ###             pl.title(title_string)
01134 ###             i+=1
01135 ###             pl.savefig('ellipses_%03d_%03d.png'%(num,i))
01136 ### 
01137 ###         return ret
01138 ### 
01139 ### def diff_roll_angles():
01140 ###     pl.subplot(211,aspect='equal')
01141 
01142 
01143 
01144 


doors_forces_kinematics
Author(s): Advait Jain. Advisor: Prof. Charlie Kemp (Healthcare Robotics Lab)
autogenerated on Wed Nov 27 2013 11:41:11