mechanism_analyse.py
Go to the documentation of this file.
00001 #
00002 # Assumes that all the logs are in one folder with the file names
00003 # giving the different mechanisms, trial number, open or close etc.
00004 #
00005 
00006 import commands
00007 import os
00008 import os.path as pt
00009 import glob
00010 import math, numpy as np
00011 import scipy.signal as ss
00012 import scipy.cluster as clus
00013 
00014 import roslib; roslib.load_manifest('modeling_forces')
00015 import modeling_forces.mf_common as mfc
00016 
00017 import matplotlib_util.util as mpu
00018 import hrl_lib.util as ut
00019 import scipy.stats as st
00020 import pylab as pb
00021 
00022 #import mdp
00023 
00024 
00025 class pca_plot_gui():
00026     def __init__(self, legend_list, mech_vec_list, proj_mat, dir_list, mn):
00027         self.legend_list = legend_list
00028         self.mech_vec_list = mech_vec_list
00029         self.proj_mat = proj_mat
00030         self.dir_list = dir_list
00031         self.mn = mn
00032 
00033     def pick_cb(self, event):
00034         if 'shift' != event.key:
00035             return
00036         selected = np.matrix([event.xdata, event.ydata]).T
00037 #        print 'selected', selected.A1
00038         min_list = []
00039         for i, v in enumerate(self.mech_vec_list):
00040             p = self.proj_mat[:, 0:2].T * (v-self.mn)
00041             min_list.append(np.min(ut.norm(p-selected)))
00042 
00043         mech_idx = np.argmin(min_list)
00044         print 'Selected mechanism was:', self.legend_list[mech_idx]
00045 
00046         plot_tangential_force(self.dir_list[mech_idx], all_trials = True, open = True)
00047 #        mpu.figure()
00048 #        n_dim = 7
00049 #        reconstruction = self.proj_mat[:, 0:n_dim] * (self.proj_mat[:, 0:n_dim].T * (self.mech_vec_list[mech_idx] - self.mn)) + self.mn
00050 #        di = extract_pkls(self.dir_list[mech_idx])
00051 #        nm = get_mech_name(self.dir_list[mech_idx])
00052 #        for i in range(reconstruction.shape[1]):
00053 #            mpu.plot_yx(reconstruction[:,i].A1, color=mpu.random_color(),
00054 #                        plot_title=nm+': %d components'%n_dim)
00055 #        mpu.legend()
00056 #        mpu.figure()
00057 #        plot_velocity(self.dir_list[mech_idx])
00058         mpu.show()
00059 
00060 
00061 
00062 
00063 ##
00064 # list all the mechanisms in dir_list and allow user to type the
00065 # numbers of the desired mechanisms.
00066 # @return list of paths to the selected mechanisms.
00067 def input_mechanism_list(dir_list):
00068     mech_list = []
00069     for i, m in enumerate(dir_list):
00070         t = m.split('/')
00071         mech = t[-1]
00072         if mech == '':
00073             mech = t[-2]
00074         mech_list.append(mech)
00075         print '%d. %s'%(i, mech)
00076 
00077     print ''
00078     print 'Enter mechanism numbers that you want to plot'
00079     s = raw_input()
00080     num_list = map(int, s.split(' '))
00081     chosen_list = []
00082     for n in num_list:
00083         chosen_list.append(dir_list[n])
00084     return chosen_list
00085 
00086 ##
00087 # remove pkls in which the forces are unreasonable large or small
00088 def clean_data_forces(dir):
00089     l = commands.getoutput('find %s/ -name "*mechanism_trajectories*.pkl"'%dir).splitlines()
00090     for pkl in l:
00091         cmd1 = 'rm -f %s'%pkl
00092         cmd2 = 'svn rm %s'%pkl
00093         d = ut.load_pickle(pkl)
00094         radial_mech = d['force_rad_list']
00095         tangential_mech = d['force_tan_list']
00096 
00097         if len(radial_mech) == 0 or len(tangential_mech) == 0:
00098             os.system(cmd1)
00099             os.system(cmd2)
00100             continue
00101 
00102         max_force = max(np.max(np.abs(radial_mech)),
00103                         np.max(np.abs(tangential_mech)))
00104         if max_force > 120.:
00105             os.system(cmd1)
00106             os.system(cmd2)
00107 
00108         n_points = len(radial_mech)
00109         if n_points < 50:
00110             os.system(cmd1)
00111             os.system(cmd2)
00112 
00113         if d.has_key('radius'):
00114             r = d['radius']
00115             if r != -1:
00116                 ang = np.degrees(d['mechanism_x'])
00117                 if np.max(ang) < 20.:
00118                     os.system(cmd1)
00119                     os.system(cmd2)
00120 
00121 
00122         if d.has_key('time_list'):
00123             t_l = d['time_list']
00124             time_diff_l = np.array(t_l[1:]) - np.array(t_l[0:-1])
00125             if len(time_diff_l) == 0:
00126                 os.system(cmd1)
00127                 os.system(cmd2)
00128                 continue
00129 
00130             max_time_diff = np.max(time_diff_l)
00131             if max_time_diff > 0.3:
00132                 print 'max time difference between consec readings:', max_time_diff
00133                 os.system(cmd1)
00134                 os.system(cmd2)
00135 
00136 
00137 ##
00138 # @param dir_name - directory containing the pkls.
00139 # @param all_trials - plot force for all the trials.
00140 # @param open - Boolean (open or close trial)
00141 # @param filter_speed - mech vel above this will be ignored. for
00142 #                       ROTARY joints only, radians/sec
00143 def plot_tangential_force(dir_name, all_trials, open = True,
00144                           filter_speed=math.radians(100)):
00145     mpu.set_figure_size(4.,4.)
00146     fig1 = mpu.figure()
00147 #    fig2 = mpu.figure()
00148 #    fig3 = mpu.figure()
00149     if open:
00150         trial = 'open'
00151     else:
00152         trial = 'close'
00153 
00154     d = extract_pkls(dir_name, open)
00155     mech_name = get_mech_name(dir_name)
00156 
00157 
00158     traj_vel_list = []
00159     for i,ftan_l in enumerate(d['ftan_l_l']):
00160         mech_x = d['mechx_l_l'][i]
00161         if d['typ'] == 'rotary':
00162             max_angle = math.radians(30)
00163             type = 'rotary'
00164         else:
00165             max_angle = 0.3
00166             type = 'prismatic'
00167 
00168         traj_vel = compute_average_velocity(mech_x, d['time_l_l'][i], max_angle, type)
00169         print 'traj_vel:', traj_vel
00170         if traj_vel == -1:
00171             continue
00172         traj_vel_list.append(traj_vel)
00173 
00174     #vel_color_list = ['r', 'g', 'b', 'y', 'k']
00175     #vel_color_list = ['#000000', '#A0A0A0', '#D0D0D0', '#E0E0E0', '#F0F0F0']
00176     #vel_color_list = ['#000000', '#00A0A0', '#00D0D0', '#00E0E0', '#00F0F0']
00177     #vel_color_list = [ '#%02X%02X%02X'%(r,g,b) for (r,g,b) in [(95, 132, 53), (81, 193, 79), (28, 240, 100), (196, 251, 100)]]
00178     vel_color_list = [ '#%02X%02X%02X'%(r,g,b) for (r,g,b) in [(95, 132, 53), (28, 240, 100), (196, 251, 100)]]
00179     traj_vel_sorted = np.sort(traj_vel_list).tolist()
00180     sorted_color_list = []
00181     sorted_scatter_list = []
00182     i = 0
00183     v_prev = traj_vel_sorted[0]
00184     legend_list = []
00185     if d['typ'] == 'rotary':
00186         l = '%.1f'%math.degrees(v_prev)
00187         thresh = math.radians(5)
00188     else:
00189         l = '%.02f'%(v_prev)
00190         thresh = 0.05
00191 
00192     t_v = v_prev
00193     v_threshold = 1000.
00194     for j,v in enumerate(traj_vel_sorted):
00195         if (v - v_prev) > thresh:
00196             if d['typ'] == 'rotary':
00197                 l = l + ' to %.1f deg/sec'%math.degrees(t_v)
00198             else:
00199                 l = l + ' to %.1f m/s'%t_v
00200             legend_list.append(l)
00201             if d['typ'] == 'rotary':
00202                 l = '%.1f'%math.degrees(v)
00203             else:
00204                 l = '%.02f'%(v)
00205             i += 1
00206             if i >= 2:
00207                 v_threshold = min(v_threshold, v)
00208                 if d['typ'] == 'rotary':
00209                     print 'v_threshold:', math.degrees(v_threshold)
00210                 else:
00211                     print 'v_threshold:', v_threshold
00212 
00213             if i == len(vel_color_list):
00214                 i -= 1
00215             v_prev = v
00216         else:
00217             legend_list.append('__nolegend__')
00218         t_v = v
00219         sorted_color_list.append(vel_color_list[i])
00220 
00221     if d['typ'] == 'rotary':
00222         l = l + ' to %.1f deg/sec'%math.degrees(t_v)
00223     else:
00224         l = l + ' to %.1f m/s'%t_v
00225 
00226     legend_list.append(l)
00227     legend_list = legend_list[1:]
00228     giant_list = []
00229 
00230     mpu.set_figure_size(3.,3.)
00231 
00232     for i,ftan_l in enumerate(d['ftan_l_l']):
00233         mech_x = d['mechx_l_l'][i]
00234         trial_num = str(d['trial_num_l'][i])
00235         color = None
00236         scatter_size = None
00237 
00238         traj_vel = compute_average_velocity(mech_x, d['time_l_l'][i],
00239                                             max_angle, d['typ'])
00240         if traj_vel == -1:
00241             continue
00242         if traj_vel >= v_threshold:
00243             continue
00244 
00245         color = sorted_color_list[traj_vel_sorted.index(traj_vel)]
00246         legend = legend_list[traj_vel_sorted.index(traj_vel)]
00247         if d['typ'] == 'rotary':
00248             #traj_vel = compute_trajectory_velocity(mech_x,d['time_l_l'][i],1)
00249             #if traj_vel >= filter_speed:
00250             #    continue
00251             mech_x_degrees = np.degrees(mech_x)
00252             xlabel = 'angle (degrees)'
00253             ylabel = '$f_{tan}$ (N)'
00254         else:
00255             mech_x_degrees = mech_x
00256             xlabel = 'distance (meters)'
00257             ylabel = 'Opening force (N)'
00258 #            n_skip = 65
00259 #            print '>>>>>>>>>>>>> WARNING BEGIN <<<<<<<<<<<<<<<<<'
00260 #            print 'not plotting the last ', n_skip, 'data points for drawers'
00261 #            print '>>>>>>>>>>>>> WARNING END <<<<<<<<<<<<<<<<<'
00262             n_skip = 1
00263             mech_x_degrees = mech_x_degrees[:-n_skip]
00264             ftan_l = ftan_l[:-n_skip]
00265 
00266         mpu.figure(fig1.number)
00267         #color, scatter_size = None, None
00268         scatter_size = None
00269         if color == None:
00270             color = mpu.random_color()
00271         if scatter_size == None:
00272             scatter_size = 1
00273 
00274         giant_list.append((traj_vel, ftan_l, mech_x_degrees, color, legend, xlabel, ylabel, trial_num))
00275 
00276     giant_list_sorted = reversed(sorted(giant_list))
00277     for traj_vel, ftan_l, mech_x_degrees, color, legend, xlabel, ylabel, trial_num in giant_list_sorted:
00278         mpu.plot_yx(ftan_l, mech_x_degrees, axis=None,
00279                     plot_title= '\huge{%s: %s}'%(mech_name, trial), xlabel=xlabel,
00280                     ylabel = ylabel, color = color,
00281                     #scatter_size = 5, linewidth = 1, label=trial_num)
00282                     scatter_size = scatter_size, linewidth = 1, label=legend)
00283     print '>>>>>>>>>> number of trials <<<<<<<<<<<', len(giant_list)
00284 
00285     mpu.figure(fig1.number)
00286 #    mpu.legend(display_mode='less_space')
00287 
00288 
00289 def radial_tangential_ratio(dir_name):
00290     d = extract_pkls(dir_name, open=True)
00291     nm = get_mech_name(dir_name)
00292     frad_ll = d['frad_l_l']
00293     mechx_ll = d['mechx_l_l']
00294     mpu.figure()
00295     for i,ftan_l in enumerate(d['ftan_l_l']):
00296         frad_l = frad_ll[i]
00297         rad_arr = np.array(np.abs(frad_l))
00298         tan_arr = np.array(np.abs(ftan_l))
00299         idxs = np.where(np.logical_and(rad_arr > 0.1, tan_arr > 0.1))
00300         ratio = np.divide(rad_arr[idxs], tan_arr[idxs])
00301         mpu.plot_yx(ratio, np.degrees(np.array(mechx_ll[i])[idxs]),
00302                     color = mpu.random_color(), plot_title=nm,
00303                     ylabel='radial/tangential', xlabel='Angle (degrees)')
00304 
00305 
00306 ##
00307 # get mechanism name from the directory name.
00308 def get_mech_name(d):
00309     t = d.split('/')
00310     mech_name = t[-1]
00311     if mech_name == '':
00312         mech_name = t[-2]
00313     return mech_name
00314 
00315 ##
00316 # get all the information from all the pkls in one directory.
00317 # ASSUMES - all pkls are of the same mechanism (same radius, type ...)
00318 # @param open - extract info for opening trials
00319 def extract_pkls(d, open=True, quiet = False, ignore_moment_list=False):
00320     if open:
00321         trial = 'open'
00322     else:
00323         trial = 'close'
00324     l = glob.glob(d+'/*'+trial+'*mechanism_trajectories*.pkl')
00325     l.sort()
00326     ftan_l_l, frad_l_l, mechx_l_l = [], [], []
00327     time_l_l, trial_num_l = [], []
00328     moment_l_l = []
00329     typ, rad = None, None
00330     for p in l:
00331         d = ut.load_pickle(p)
00332 
00333         if d.has_key('radius'):
00334             rad = d['radius']
00335         else:
00336             rad = -1
00337 #            if quiet == False:
00338 #                print p, 'does not have radius'
00339 #            return None
00340 
00341         if rad != -1:
00342             #moment_l_l.append((np.array(ftan_l_l[-1]) * rad).tolist())
00343             if d.has_key('moment_list'):
00344                 moment_l_l.append(d['moment_list'])
00345             else:
00346 #                if quiet == False:
00347 #                    print p, 'does not have moment_list'
00348 #                continue
00349                 moment_l_l.append([0 for i in range(len(d['force_rad_list']))])
00350 
00351         trial_num = p.split('_')[-5]
00352         trial_num_l.append(int(trial_num))
00353         frad_l_l.append(d['force_rad_list'])
00354         ftan_l_l.append(d['force_tan_list'])
00355 
00356         if d.has_key('mech_type'):
00357             typ = d['mech_type']
00358         else:
00359             if quiet == False:
00360                 print p, 'does not have mech_typ'
00361             return None
00362 
00363         mechx_l_l.append(d['mechanism_x'])
00364 
00365         if d.has_key('time_list'):
00366             t_l = d['time_list']
00367         else:
00368             t_l = [0.03*i for i in range(len(ftan_l_l))]
00369             #if quiet == False:
00370             #    print p, 'does not have time_list'
00371             #return None
00372         time_l_l.append((np.array(t_l)-t_l[0]).tolist())
00373 
00374     r = {}
00375     r['ftan_l_l'] = ftan_l_l
00376     r['frad_l_l'] = frad_l_l
00377     r['mechx_l_l'] = mechx_l_l
00378     r['typ'] = typ
00379     r['rad'] = rad
00380     r['time_l_l'] = time_l_l
00381     r['trial_num_l'] = trial_num_l
00382     r['moment_l_l'] = moment_l_l
00383 
00384     return r
00385 
00386 ##
00387 # take max force magnitude within a bin size
00388 # @param bin_size - depends on the units of poses_list
00389 # @param fn - function to apply to the binned force values (e.g. max, min)
00390 # @param ignore_empty - if True then empty bins are ignored. Else the
00391 #                       value of an empty bin is set to None.
00392 # @param max_pose - maximum value of pose to use if None then derived
00393 #                   from poses_list
00394 # @param empty_value - what to fill in an empty bin (None, np.nan etc.)
00395 def bin(poses_list, ftan_list, bin_size, fn, ignore_empty,
00396         max_pose=None, empty_value = None):
00397     if max_pose == None:
00398         max_dist = max(poses_list)
00399     else:
00400         max_dist = max_pose
00401 
00402     poses_array = np.array(poses_list)
00403     binned_poses_array = np.arange(0., max_dist, bin_size)
00404 
00405     binned_force_list = []
00406     binned_poses_list = []
00407     ftan_array = np.array(ftan_list)
00408 
00409     for i in range(binned_poses_array.shape[0]-1):
00410         idxs = np.where(np.logical_and(poses_array>=binned_poses_array[i],
00411                                        poses_array<binned_poses_array[i+1]))
00412         if idxs[0].shape[0] != 0:
00413             binned_poses_list.append(binned_poses_array[i])
00414             binned_force_list.append(fn(ftan_array[idxs]))
00415         elif ignore_empty == False:
00416             binned_poses_list.append(binned_poses_array[i])
00417             binned_force_list.append(empty_value)
00418 
00419     return binned_poses_list, binned_force_list
00420 
00421 ##
00422 # makes a scatter plot with the radius along the x axis and the max
00423 # force along the y-axis. different color for each mechanism
00424 # @param dir_name - directory containing the pkls.
00425 def max_force_radius_scatter(dir_name_list, open=True):
00426     mpu.figure()
00427     if open:
00428         trial = 'Opening'
00429     else:
00430         trial = 'Closing'
00431 
00432     for d in dir_name_list:
00433         nm = get_mech_name(d)
00434         print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>'
00435         print 'MECHANISM:', nm
00436         print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>'
00437         ftan_l_l, frad_l_l, mechx_l_l, typ, rad = extract_pkls(d, open)
00438         fl, rl = [], []
00439         for n in range(len(ftan_l_l)):
00440             fmax = np.max(np.abs(ftan_l_l[n]))
00441             print 'fmax:', fmax
00442             fl.append(fmax)
00443             rl.append(rad)
00444         print 'Aloha'
00445         print 'len(fl)', len(fl)
00446         print 'len(rl)', len(rl)
00447         #mpu.plot_yx(fl, rl)
00448         plot_title = 'Scatter plot for %s trials'%trial
00449         mpu.plot_yx(fl, rl, color=mpu.random_color(), label=nm,
00450                     axis=None, linewidth=0, xlabel='Radius (m)',
00451                     ylabel='Maximum Force (N)', plot_title=plot_title)
00452     mpu.legend()
00453 
00454 # use all the values of all the bins for all the trials.
00455 # @param plot_type - 'tangential', 'magnitude', 'radial'
00456 def errorbar_one_mechanism(dir_name, open=True, new_figure=True,
00457                            filter_speed = math.radians(100),
00458                            plot_type='tangential', color=None,
00459                            label = None):
00460     if new_figure:
00461         mpu.figure()
00462     nm = get_mech_name(dir_name)
00463 
00464     d = extract_pkls(dir_name, open)
00465     ftan_l_l = d['ftan_l_l']
00466     frad_l_l = d['frad_l_l']
00467     mechx_l_l = d['mechx_l_l']
00468     time_l_l = d['time_l_l']
00469     typ = d['typ']
00470     rad = d['rad']
00471     
00472     fn = list
00473 
00474     binned_mechx_l = []
00475     binned_ftan_ll = []
00476     use_trials_list = []
00477 
00478     if plot_type == 'radial':
00479         force_l_l = frad_l_l
00480     if plot_type == 'tangential':
00481         force_l_l = ftan_l_l
00482     if plot_type == 'magnitude':
00483         force_l_l = []
00484         for ta, ra in zip(ftan_l_l, frad_l_l):
00485             force_l_l.append(ut.norm(np.matrix([ta, ra])).A1.tolist())
00486 
00487     n_trials = len(force_l_l)
00488     for i in range(n_trials):
00489         if typ == 'rotary':
00490             traj_vel = compute_trajectory_velocity(mechx_l_l[i],
00491                                                    time_l_l[i], 1)
00492             if traj_vel >= filter_speed:
00493                 continue
00494             t, f = bin(mechx_l_l[i], force_l_l[i], math.radians(1.),
00495                        fn, ignore_empty=False, max_pose=math.radians(60))
00496         if typ == 'prismatic':
00497             t, f = bin(mechx_l_l[i], force_l_l[i], 0.01,
00498                        fn, ignore_empty=False, max_pose=0.5)
00499         if len(t) > len(binned_mechx_l):
00500             binned_mechx_l = t
00501         binned_ftan_ll.append(f)
00502         use_trials_list.append(i)
00503 
00504     n_trials = len(binned_ftan_ll)
00505     n_bins = len(binned_mechx_l)
00506     force_list_combined = [[] for i in binned_mechx_l]
00507     for i in range(n_trials):
00508         force_l = binned_ftan_ll[i]
00509         for j,p in enumerate(binned_mechx_l):
00510             if force_l[j] != None:
00511                 if open:
00512                     if j < 5:
00513                         force_list_combined[j].append(max(force_l[j]))
00514                         continue
00515                 else:
00516                     if (n_trials-j) < 5:
00517                         force_list_combined[j].append(min(force_l[j]))
00518                         continue
00519                 force_list_combined[j] += force_l[j]
00520 
00521     plot_mechx_l = []
00522     mean_l, std_l = [], []
00523     for i,p in enumerate(binned_mechx_l):
00524         f_l = force_list_combined[i]
00525         if len(f_l) == 0:
00526             continue
00527         plot_mechx_l.append(p)
00528         mean_l.append(np.mean(f_l))
00529         std_l.append(np.std(f_l))
00530 
00531     if open:
00532         trial = 'Open'
00533     else:
00534         trial = 'Close'
00535 
00536     n_sigma = 1
00537     if typ == 'rotary':
00538         x_l = np.degrees(plot_mechx_l)
00539         xlabel='\huge{Angle (degrees)}'
00540     else:
00541         x_l = plot_mechx_l
00542         xlabel='Distance (m)'
00543 
00544     std_arr = np.array(std_l) * n_sigma
00545     if color == None:
00546         color = mpu.random_color()
00547     if label == None:
00548         label= nm+' '+plot_type
00549 
00550     mpu.plot_errorbar_yx(mean_l, std_arr, x_l, linewidth=1, color=color,
00551                          plot_title='\huge{Mean \& %d$\sigma$}'%(n_sigma),
00552                          xlabel=xlabel, label=label,
00553                          ylabel='\huge{Force (N)}')
00554     mpu.legend()
00555 
00556 # take the max of each bin.
00557 def errorbar_one_mechanism_max(dir_name, open=True,
00558                                filter_speed=math.radians(100.)):
00559 #    mpu.figure()
00560     nm = get_mech_name(dir_name)
00561     d = extract_pkls(dir_name, open)
00562     ftan_l_l = d['ftan_l_l']
00563     frad_l_l = d['frad_l_l']
00564     mechx_l_l = d['mechx_l_l']
00565     time_l_l = d['time_l_l']
00566     typ = d['typ']
00567     rad = d['rad']
00568 
00569     fn = max
00570     if open == False:
00571         fn = min
00572 
00573     binned_mechx_l = []
00574     binned_ftan_ll = []
00575     use_trials_list = []
00576 
00577     n_trials = len(ftan_l_l)
00578     for i in range(n_trials):
00579         if typ == 'rotary':
00580             traj_vel = compute_trajectory_velocity(mechx_l_l[i],
00581                                                    time_l_l[i], 1)
00582             if traj_vel >= filter_speed:
00583                 continue
00584             t, f = bin(mechx_l_l[i], ftan_l_l[i], math.radians(1.),
00585                        fn, ignore_empty=False, max_pose=math.radians(60))
00586         if typ == 'prismatic':
00587             t, f = bin(mechx_l_l[i], ftan_l_l[i], 0.01,
00588                        fn, ignore_empty=False, max_pose=0.5)
00589 
00590         if len(t) > len(binned_mechx_l):
00591             binned_mechx_l = t
00592         binned_ftan_ll.append(f)
00593         use_trials_list.append(i)
00594 
00595     binned_ftan_arr = np.array(binned_ftan_ll)
00596     plot_mechx_l = []
00597     mean_l, std_l = [], []
00598     for i,p in enumerate(binned_mechx_l):
00599         f_l = []
00600         for j in range(len(use_trials_list)):
00601             if binned_ftan_arr[j,i] != None:
00602                 f_l.append(binned_ftan_arr[j,i])
00603         if len(f_l) == 0:
00604             continue
00605         plot_mechx_l.append(p)
00606         mean_l.append(np.mean(f_l))
00607         std_l.append(np.std(f_l))
00608 
00609     xlabel = 'Angle (degrees)'
00610 
00611     if open:
00612         trial = 'Open'
00613     else:
00614         trial = 'Close'
00615 
00616     n_sigma = 1
00617     std_arr = np.array(std_l) * n_sigma
00618     mpu.plot_errorbar_yx(mean_l, std_arr, np.degrees(plot_mechx_l),
00619                          linewidth=1, plot_title=nm+': '+trial,
00620                          xlabel='Angle (degrees)',
00621                          label='Mean \& %d$\sigma$'%(n_sigma),
00622                          ylabel='Tangential Force (N)',
00623                          color='y')
00624     mpu.legend()
00625 
00626 def plot_opening_distances_drawers(dir_name_list):
00627     mpu.figure()
00628     for d in dir_name_list:
00629         nm = get_mech_name(d)
00630         ftan_l_l, frad_l_l, mechx_l_l, typ, rad = extract_pkls(d)
00631         if rad != -1:
00632             # ignoring the cabinet doors.
00633             continue
00634 #        print 'Aloha'
00635 #        import pdb; pdb.set_trace()
00636         dist_opened_list = []
00637         for x_l in mechx_l_l:
00638             dist_opened_list.append(x_l[-1] - x_l[0])
00639 
00640         plot_title = 'Opening distance for drawers'
00641         mpu.plot_yx(dist_opened_list, color=mpu.random_color(), label=nm,
00642                     axis=None, linewidth=0, xlabel='Nothing',
00643                     ylabel='Distance opened', plot_title=plot_title)
00644     mpu.legend()
00645 
00646 def handle_height_histogram(dir_name_list, plot_title=''):
00647     mean_height_list = []
00648     for d in dir_name_list:
00649         nm = get_mech_name(d)
00650         pkl = glob.glob(d+'/mechanism_calc_dict.pkl')
00651         if pkl == []:
00652             print 'Mechanism "%s" does not have a mechanism_calc_dict'%nm
00653             continue
00654         pkl = pkl[0]
00655         mech_calc_dict = ut.load_pickle(pkl)
00656         hb = mech_calc_dict['handle_bottom']
00657         ht = mech_calc_dict['handle_top']
00658         mean_height_list.append((hb+ht)/2.)
00659 
00660     #max_height = np.max(mean_height_list)
00661     max_height = 2.0
00662     bin_width = 0.1
00663     bins = np.arange(0.-bin_width/2., max_height+2*bin_width, bin_width)
00664     hist, bin_edges = np.histogram(np.array(mean_height_list), bins)
00665     mpu.plot_histogram(bin_edges[:-1]+bin_width/2., hist,
00666                        width=bin_width*0.8, plot_title=plot_title,
00667                        xlabel='Height (meters)', ylabel='\# of mechanisms')
00668 
00669 def plot_handle_height(dir_name_list, plot_title):
00670     mpu.figure()
00671     for d in dir_name_list:
00672         nm = get_mech_name(d)
00673         pkl = glob.glob(d+'/mechanism_calc_dict.pkl')
00674         if pkl == []:
00675             print 'Mechanism "%s" does not have a mechanism_calc_dict'%nm
00676             continue
00677         pkl = pkl[0]
00678         mech_calc_dict = ut.load_pickle(pkl)
00679         hb = mech_calc_dict['handle_bottom']
00680         ht = mech_calc_dict['handle_top']
00681 
00682         di = extract_pkls(d, open=True)
00683         ftan_l_l = di['ftan_l_l']
00684         frad_l_l = di['frad_l_l']
00685         mechx_l_l = di['mechx_l_l']
00686         time_l_l = di['time_l_l']
00687         typ = di['typ']
00688         rad = di['rad']
00689 #        ftan_l_l, frad_l_l, mechx_l_l, typ, rad = extract_pkls(d,
00690 #                                                        open=True)
00691         fl, hl = [], []
00692         for n in range(len(ftan_l_l)):
00693             fmax = np.max(np.abs(ftan_l_l[n][0:-50]))
00694             fl.append(fmax)
00695             fl.append(fmax)
00696             hl.append(ht)
00697             hl.append(hb)
00698 
00699         mpu.plot_yx(hl, fl, color=mpu.random_color(), label=nm,
00700                     axis=None, linewidth=0, xlabel='Max opening force',
00701                     ylabel='Handle Height (m)', plot_title=plot_title)
00702     mpu.legend()
00703 
00704 def distance_of_handle_from_edges():
00705     pass
00706 
00707 def plot_handle_height_no_office():
00708     opt = commands.getoutput('cd aggregated_pkls_Feb11; ls --ignore=*HSI* --ignore=*HRL* --ignore=a.py')
00709     d_list = opt.splitlines()
00710     dir_list = []
00711     for d in d_list:
00712         dir_list.append('aggregated_pkls_Feb11/'+d)
00713 
00714     plot_title = 'Only homes. Excluding Offices'
00715     plot_handle_height(dir_list[0:], plot_title)
00716 
00717 def plot_handle_height_no_fridge_no_freezer():
00718     opt = commands.getoutput('cd aggregated_pkls_Feb11; ls --ignore=*refrigerator* --ignore=*freezer* --ignore=a.py')
00719     d_list = opt.splitlines()
00720     dir_list = []
00721     for d in d_list:
00722         dir_list.append('aggregated_pkls_Feb11/'+d)
00723 
00724     plot_title = 'Excluding Refrigerators and Freezers'
00725     plot_handle_height(dir_list[0:], plot_title)
00726 
00727 ##
00728 # returns the median of the velocity.
00729 def compute_velocity(mech_x, time_list, smooth_window):
00730     x = np.array(mech_x)
00731     t = np.array(time_list)
00732     kin_info = {'disp_mech_coord_arr': np.array(mech_x),
00733                 'mech_time_arr': np.array(time_list)}
00734     vel_arr = mfc.velocity(kin_info, smooth_window)
00735     return vel_arr
00736 
00737 ##
00738 # mech_x must be in RADIANS.
00739 def compute_trajectory_velocity(mech_x, time_list, smooth_window):
00740     vel_arr = compute_velocity(mech_x, time_list, smooth_window)
00741     filt_vel_arr = vel_arr[np.where(vel_arr>math.radians(2.))]
00742     median_vel = np.median(filt_vel_arr)
00743     return median_vel
00744 
00745 ##
00746 # compute the average velocity = total angle / total time.
00747 def compute_average_velocity(mech_x, time_list, max_angle, type):
00748     reject_num = 20
00749     if len(mech_x) < reject_num:
00750         return -1
00751 
00752     mech_x = mech_x[reject_num:]
00753     time_list = time_list[reject_num:]
00754     if mech_x[-1] < max_angle:
00755         return -1
00756 
00757     if type == 'rotary':
00758         start_angle = math.radians(1)
00759     elif type == 'prismatic':
00760         start_angle = 0.01
00761 
00762     mech_x = np.array(mech_x)
00763     start_idx = np.where(mech_x > start_angle)[0][0]
00764     end_idx = np.where(mech_x > max_angle)[0][0]
00765 
00766     start_x = mech_x[start_idx]
00767     end_x = mech_x[end_idx]
00768 
00769     start_time = time_list[start_idx]
00770     end_time = time_list[end_idx]
00771 
00772     avg_vel = (end_x - start_x) / (end_time - start_time)
00773     return avg_vel
00774 
00775 
00776 def plot_velocity(dir_name):
00777     d = extract_pkls(dir_name, True)
00778     vel_fig = mpu.figure()
00779     acc_fig = mpu.figure()
00780     for i,time_list in enumerate(d['time_l_l']):
00781         mechx_l = d['mechx_l_l'][i]
00782         mechx_l, vel, acc, time_list = mfc.kinematic_params(mechx_l, time_list, 10)
00783         vel_arr = np.array(vel)
00784         acc_arr = np.array(acc)
00785 
00786         trial_num = d['trial_num_l'][i]
00787 
00788         xarr = np.array(mechx_l)
00789         idxs = np.where(np.logical_and(xarr < math.radians(20.),
00790                                        xarr > math.radians(1.)))
00791 
00792         color=mpu.random_color()
00793         mpu.figure(vel_fig.number)
00794         mpu.plot_yx(np.degrees(vel_arr[idxs]),
00795                     np.degrees(xarr[idxs]), color=color,
00796                     label='%d velocity'%trial_num, scatter_size=0)
00797         mpu.legend()
00798 
00799         mpu.figure(acc_fig.number)
00800         mpu.plot_yx(np.degrees(acc_arr[idxs]), np.degrees(xarr[idxs]), color=color,
00801                     label='%d acc'%trial_num, scatter_size=0)
00802         mpu.legend()
00803 
00804 ##
00805 # l list of trials with which to correlate c1
00806 # trial is a list of forces (each element is the max force or some
00807 # other representative value for a given angle)
00808 # lab_list - list of labels
00809 def correlate_trials(c1, l, lab_list):
00810     mpu.figure()
00811     x = 0
00812     corr_list = []
00813     x_l = []
00814     for i,c2 in enumerate(l):
00815         res = ss.correlate(np.array(c1), np.array(c2), 'valid')[0]
00816         r1 = ss.correlate(np.array(c1), np.array(c1), 'valid')[0]
00817         r2 = ss.correlate(np.array(c2), np.array(c2), 'valid')[0]
00818         res = res/math.sqrt(r1*r2) # cross correlation coefficient  http://www.staff.ncl.ac.uk/oliver.hinton/eee305/Chapter6.pdf
00819         if i == 0 or lab_list[i] == lab_list[i-1]:
00820             corr_list.append(res)
00821             x_l.append(x)
00822         else:
00823             mpu.plot_yx(corr_list, x_l, color=mpu.random_color(),
00824                         label=lab_list[i-1], xlabel='Nothing',
00825                         ylabel='Cross-Correlation Coefficient')
00826             corr_list = []
00827             x_l = []
00828         x += 1
00829     mpu.plot_yx(corr_list, x_l, color=mpu.random_color(),
00830                 label=lab_list[i-1])
00831     mpu.legend()
00832 
00833 ##
00834 # plot errorbars showing 1 sigma for tangential component of the force
00835 # and the total magnitude of the force. (Trying to verify that what we
00836 # are capturing using our setup is consistent across people)
00837 def compare_tangential_total_magnitude(dir):
00838     mpu.figure()
00839     errorbar_one_mechanism(dir, open = True,
00840                            filter_speed = math.radians(30),
00841                            plot_type = 'magnitude',
00842                            new_figure = False, color='y',
00843                            label = '\huge{$\hat F_{normal}$}')
00844 
00845     errorbar_one_mechanism(dir, open = True,
00846                            filter_speed = math.radians(30),
00847                            plot_type = 'tangential', color='b',
00848                            new_figure = False,
00849                            label = '\huge{$||\hat F_{normal} + \hat F_{plane}||$}')
00850 
00851 def max_force_vs_velocity(dir):
00852     di = extract_pkls(dir, open)
00853     ftan_l_l = di['ftan_l_l']
00854     frad_l_l = di['frad_l_l']
00855     mechx_l_l = di['mechx_l_l']
00856     time_l_l = di['time_l_l']
00857     typ = di['typ']
00858     rad = di['rad']
00859 
00860     nm = get_mech_name(dir)
00861 #    mpu.figure()
00862     color = mpu.random_color()
00863     mfl = []
00864     tvl = []
00865     for i in range(len(ftan_l_l)):
00866 
00867         xarr = np.array(mechx_l_l[i])
00868         idxs = np.where(np.logical_and(xarr < math.radians(20.),
00869                                        xarr > math.radians(1.)))
00870 
00871         max_force = np.max(np.array(ftan_l_l[i])[idxs])
00872         mechx_short = np.array(mechx_l_l[i])[idxs]
00873         time_short = np.array(time_l_l[i])[idxs]
00874 
00875         vel_arr = compute_velocity(mechx_l_l[i], time_l_l[i], 5)
00876         #vel_arr = compute_velocity(mechx_short[i], time_l_l[i], 5)
00877         vel_short = vel_arr[idxs]
00878         traj_vel = np.max(vel_short)
00879         #acc_arr = compute_velocity(vel_arr, time_l_l[i], 1)
00880         #traj_vel = np.max(acc_arr)
00881         #traj_vel = compute_trajectory_velocity(mechx_short, time_short, 1)
00882 
00883         mfl.append(max_force)
00884         tvl.append(traj_vel)
00885 
00886     mpu.plot_yx(mfl, tvl, color = color,
00887                 xlabel = 'Trajectory vel', label = nm,
00888                 ylabel = 'Max tangential force', linewidth=0)
00889     mpu.legend()
00890 
00891 def mechanism_radius_histogram(dir_list, color='b'):
00892     rad_list = []
00893     for d in dir_list:
00894         nm = get_mech_name(d)
00895         pkl = glob.glob(d+'/mechanism_info.pkl')
00896         if pkl == []:
00897             print 'Mechanism "%s" does not have a mechanism_info_dict'%nm
00898             continue
00899         pkl = pkl[0]
00900         md = ut.load_pickle(pkl)
00901         if md['radius'] != -1:
00902             rad_list.append(md['radius'])
00903     max_radius = np.max(rad_list)
00904     print 'Rad list:', rad_list
00905     bin_width = 0.05
00906     bins = np.arange(0.-bin_width/2., max_radius+2*bin_width, bin_width)
00907     hist, bin_edges = np.histogram(np.array(rad_list), bins)
00908     print 'Bin Edges:', bin_edges
00909     print 'Hist:', hist
00910     h = mpu.plot_histogram(bin_edges[:-1]+bin_width/2., hist,
00911                        width=0.8*bin_width, xlabel='Radius(meters)',
00912                        ylabel='\# of mechanisms',
00913                        plot_title='Histogram of radii of rotary mechanisms',
00914                        color=color)
00915     return h
00916 
00917 
00918 
00919 def make_vector(mechx, ftan_l, lim, bin_size):
00920     t, f = bin(mechx, ftan_l, bin_size, max,
00921                ignore_empty=False, max_pose=lim,
00922                empty_value = np.nan)
00923     f = np.array(f)
00924     t = np.array(t)
00925 
00926 
00927     clean_idx = np.where(np.logical_not(np.isnan(f)))
00928     miss_idx = np.where(np.isnan(f))
00929     if len(miss_idx[0]) > 0:
00930         fclean = f[clean_idx]
00931         mechx_clean = t[clean_idx]
00932         mechx_miss = t[miss_idx]
00933         f_inter = mfc.interpolate_1d(mechx_clean, fclean, mechx_miss)
00934         f[np.where(np.isnan(f))] = f_inter
00935         #import pdb
00936         #pdb.set_trace()
00937     return np.matrix(f).T
00938 
00939 # this makes the vector unit norm before returning it. Currently, this
00940 # function is only used for PCA.
00941 def make_vector_mechanism(dir, use_moment = False):
00942     print '>>>>>>>>>>>>>>>>>>>>>>'
00943     print 'dir:', dir
00944     di = extract_pkls(dir)
00945     ftan_l_l = di['ftan_l_l']
00946     frad_l_l = di['frad_l_l']
00947     mechx_l_l = di['mechx_l_l']
00948     time_l_l = di['time_l_l']
00949     moment_l_l = di['moment_l_l']
00950     typ = di['typ']
00951     rad = di['rad']
00952 
00953     n_trials = len(ftan_l_l)
00954     vec_list = []
00955     tup_list = []
00956     for i in range(n_trials):
00957         if typ == 'rotary':
00958             if use_moment:
00959                 torque_l = moment_l_l[i]
00960             else:
00961                 torque_l = ftan_l_l[i]
00962 
00963             if len(mechx_l_l[i]) < 30:
00964                 continue
00965 
00966             v = make_vector(mechx_l_l[i], torque_l, lim = math.radians(50.),
00967                             bin_size = math.radians(1))
00968             max_angle = math.radians(30)
00969 
00970         if typ == 'prismatic':
00971             v = make_vector(mechx_l_l[i], ftan_l_l[i], lim = 0.25,
00972                             bin_size = 0.01)
00973 
00974 
00975         traj_vel = compute_average_velocity(mechx_l_l[i], time_l_l[i], max_angle, typ)
00976         if traj_vel == -1:
00977             continue
00978         #v = v / np.linalg.norm(v)
00979         vec_list.append(v)
00980         tup_list.append((traj_vel,v))
00981 
00982     if len(vec_list) <= 1:
00983         return None
00984 
00985     tup_list.sort()
00986     [vel_list, vec_list] = zip(*tup_list)
00987 
00988     v_prev = vel_list[0]
00989     t_v = v_prev
00990     thresh = math.radians(5)
00991     i = 0
00992     ret_list = []
00993     for j,v in enumerate(vel_list):
00994         if (v - v_prev) > thresh:
00995             i += 1
00996             if i >= 2:
00997                 break
00998             v_prev = v
00999         ret_list.append(vec_list[j])
01000 
01001     print 'Number of trials:', len(ret_list)
01002 
01003     # selecting only the slowest three trials.
01004 #    tup_list.sort()
01005 #    if len(tup_list) > 3:
01006 #        [acc_list, v_list] = zip(*tup_list)
01007 #        return np.column_stack(v_list[0:3])
01008 
01009     return np.column_stack(ret_list)
01010 
01011 
01012 ##
01013 # one of the figures for the paper.
01014 # showing that different classes have different clusters.
01015 def different_classes_rotary(dir_list):
01016     mech_vec_list = []
01017     legend_list = []
01018     for d in dir_list:
01019         di = extract_pkls(d)
01020         if di == None:
01021             continue
01022         if di.has_key('typ'):
01023             typ = di['typ']
01024             if typ != 'rotary':
01025             #if typ != 'prismatic':
01026                 continue
01027         else:
01028             continue
01029 
01030         v = make_vector_mechanism(d)
01031         if v == None:
01032             continue
01033         mech_vec_list.append(v)
01034         legend_list.append(get_mech_name(d))
01035 
01036     all_vecs = np.column_stack(mech_vec_list)
01037     print '>>>>>>>>> all_vecs.shape <<<<<<<<<<<<<', all_vecs.shape
01038     U, s, _ = np.linalg.svd(np.cov(all_vecs))
01039     mn = np.mean(all_vecs, 1).A1
01040 
01041     mpu.set_figure_size(3.,3.)
01042     mpu.figure()
01043     proj_mat = U[:, 0:2]
01044     legend_made_list = [False, False, False]
01045     for i, v in enumerate(mech_vec_list):
01046         p = proj_mat.T * (v - np.matrix(mn).T)
01047         if np.any(p[0,:].A1<0):
01048             print 'First principal component < 0 for some trial of:', legend_list[i]
01049         color = mpu.random_color()
01050         if 'ree' in legend_list[i]:
01051             #color = 'g'
01052             color = '#66FF33'
01053             if legend_made_list[0] == False:
01054                 label = 'Freezers'
01055                 legend_made_list[0] = True
01056             else:
01057                 label = '__nolegend__'
01058             print 'SHAPE:', p.shape
01059             print 'p:', p
01060 
01061         elif 'ge' in legend_list[i]:
01062             color = '#FF6633'
01063             #color = 'y'
01064             if legend_made_list[1] == False:
01065                 label = 'Refrigerators'
01066                 legend_made_list[1] = True
01067             else:
01068                 label = '__nolegend__'
01069         else:
01070             #color = 'b'
01071             color = '#3366FF'
01072             if legend_made_list[2] == False:
01073                 #label = '\\flushleft Cabinets, Spring \\\\*[-2pt] Loaded Doors'
01074                 label = 'Cabinets'
01075                 legend_made_list[2] = True
01076             else:
01077                 label = '__nolegend__'
01078         mpu.pl.scatter(p[0,:].A1, p[1,:].A1, color = color, s = 15,
01079                        label = label)
01080     mpu.pl.xlabel('First Principle Component')
01081     mpu.pl.ylabel('Second Principle Component')
01082     mpu.pl.axis('equal')
01083     mpu.pl.axhline(y=0., color = 'k', ls='--')
01084     mpu.pl.axvline(x=0., color = 'k', ls='--')
01085     #mpu.legend(loc='upper center', display_mode = 'less_space', draw_frame = True)
01086     mpu.legend(loc='center left', display_mode = 'less_space', draw_frame = True)
01087 
01088     mpu.figure()
01089     mn = np.mean(all_vecs, 1).A1
01090     mn = mn/np.linalg.norm(mn)
01091     mpu.plot_yx(mn, color = '#FF3300',
01092                 label = 'mean (normalized)', scatter_size=7)
01093 
01094     c_list = ['#00CCFF', '#643DFF']
01095     for i in range(2):
01096         mpu.plot_yx(U[:,i].flatten(), color = c_list[i],
01097                     label = 'Eigenvector %d'%(i+1), scatter_size=7)
01098 
01099     mpu.pl.axhline(y=0., color = 'k', ls='--')
01100     mpu.legend(display_mode = 'less_space', draw_frame=False)
01101 
01102     mpu.show()
01103 
01104 
01105 ##
01106 # makes a scatter plot with the radius along the x axis and the max
01107 # force along the y-axis. different color for each mechanism
01108 # @param dir_name - directory containing the pkls.
01109 def max_force_hist(dir_name_list, open=True, type=''):
01110     if open:
01111         trial = 'Opening'
01112     else:
01113         trial = 'Closing'
01114 
01115     fls, freezer_list, fridge_list, springloaded_list = [],[],[],[]
01116     broiler_list = []
01117     num_mech = 0
01118     lens = []
01119 
01120     max_angle = math.radians(15.)
01121     max_dist = 0.1
01122 
01123     for d in dir_name_list:
01124         nm = get_mech_name(d)
01125         ep = extract_pkls(d, open, ignore_moment_list=True)
01126         if ep == None:
01127             continue
01128         ftan_l_l = ep['ftan_l_l']
01129         frad_l_l = ep['frad_l_l']
01130         mechx_l_l = ep['mechx_l_l']
01131         typ = ep['typ']
01132         rad = ep['rad']
01133 
01134         fl, rl = [], []
01135         for n in range(len(ftan_l_l)):
01136             ftan_l = ftan_l_l[n]
01137 
01138             mechx_a = np.array(mechx_l_l[n]) 
01139             if type == 'prismatic':
01140                 indices = np.where(mechx_a < max_dist)[0]
01141             else:
01142                 indices = np.where(mechx_a < max_angle)[0]
01143 
01144             if len(indices) > 0:
01145                 ftan_l = np.array(ftan_l)[indices].tolist()
01146 
01147             fmax = np.max(np.abs(ftan_l))
01148             fl.append(fmax)
01149             rl.append(rad)
01150 
01151         #fmax_max = np.max(fl)
01152         fmax_max = np.min(fl)
01153         if type == 'rotary':
01154             if 'ree' in nm:
01155                 freezer_list.append(fmax_max)
01156             elif 'naveen_microwave' in nm:
01157                 # putting microwave in freezers
01158                 freezer_list.append(fmax_max)
01159                 if fmax_max < 5.:
01160                     print 'nm:', nm
01161             elif 'ge' in nm:
01162                 fridge_list.append(fmax_max)
01163             elif fmax > 60.:
01164                 springloaded_list.append(fmax_max)
01165         else:
01166             if 'ven' in nm:
01167                 broiler_list.append(fmax_max)
01168             if fmax_max > 10.:
01169                 print 'nm:', nm, 'fmax:', fmax_max
01170 
01171         fls.append(fmax_max)
01172         num_mech += 1
01173         lens.append(len(fl))
01174     
01175     if len(fls) > 0:
01176         max_force = np.max(fls)
01177         bin_width = 2.5
01178         bins = np.arange(0.-bin_width/2., max_force+2*bin_width, bin_width)
01179         if type == 'rotary':
01180             mpu.set_figure_size(3.,4.)
01181             mpu.figure()
01182             hist, bin_edges = np.histogram(fls, bins)
01183             h = mpu.plot_histogram(bin_edges[:-1]+bin_width/2., hist,
01184                                width=0.8*bin_width, xlabel='Force (Newtons)',
01185                                ylabel='\# of mechanisms',
01186                                color='b', label='Cabinets')
01187             max_freq = np.max(hist)
01188 
01189             hist, bin_edges = np.histogram(freezer_list + fridge_list, bins)
01190             h = mpu.plot_histogram(bin_edges[:-1]+bin_width/2., hist,
01191                                width=0.8*bin_width, xlabel='Force (Newtons)',
01192                                ylabel='\# of mechanisms',
01193                                color='y', label='Appliances')
01194 
01195             hist, bin_edges = np.histogram(springloaded_list, bins)
01196             h = mpu.plot_histogram(bin_edges[:-1]+bin_width/2., hist,
01197                                width=0.8*bin_width, xlabel='Force (Newtons)',
01198                                ylabel='\# of mechanisms',
01199                                color='g', label='Spring Loaded Doors')
01200             mpu.pl.xticks(np.arange(0.,max_force+2*bin_width, 10.))
01201             mpu.legend(display_mode='less_space', handlelength=1.)
01202 
01203             pb.xlim(-bin_width, max_force+bin_width)
01204             pb.ylim(0, max_freq+0.5)
01205         else:
01206             mpu.set_figure_size(3.,4.)
01207             mpu.figure()
01208             hist, bin_edges = np.histogram(fls, bins)
01209             h = mpu.plot_histogram(bin_edges[:-1]+bin_width/2., hist,
01210                                width=0.8*bin_width, xlabel='Force (Newtons)',
01211                                ylabel='\# of mechanisms',
01212                                color='b', label='Drawers')
01213             max_freq = np.max(hist)
01214 
01215             hist, bin_edges = np.histogram(broiler_list, bins)
01216             h = mpu.plot_histogram(bin_edges[:-1]+bin_width/2., hist,
01217                                width=0.8*bin_width, xlabel='Force (Newtons)',
01218                                ylabel='\# of mechanisms',
01219                                color='y', label='Broilers')
01220 
01221 
01222         mpu.figure()
01223         bin_width = 2.5
01224         bins = np.arange(0.-bin_width/2., max_force+2*bin_width, bin_width)
01225         hist, bin_edges = np.histogram(fls, bins)
01226         h = mpu.plot_histogram(bin_edges[:-1]+bin_width/2., hist,
01227                            width=0.8*bin_width, xlabel='Force (Newtons)',
01228                            ylabel='\# of mechanisms',
01229                            color='b', label='All')
01230         mpu.legend()
01231         pb.xlim(-bin_width, max_force+bin_width)
01232         pb.ylim(0, np.max(hist)+1)
01233         mpu.pl.xticks(np.arange(0.,max_force+2*bin_width, 5.))
01234         mpu.pl.yticks(np.arange(0.,np.max(hist)+0.5, 1.))
01235     else:
01236         print "OH NO! FLS <= 0"
01237 
01238 
01239 def dimen_reduction_mechanisms(dir_list, dimen = 2):
01240     mech_vec_list = []
01241     legend_list = []
01242     dir_list = filter_dir_list(dir_list)
01243     dir_list_new = []
01244     for d in dir_list:
01245         v = make_vector_mechanism(d)
01246         if v == None:
01247             continue
01248         print 'v.shape:', v.shape
01249         mech_vec_list.append(v)
01250         legend_list.append(get_mech_name(d))
01251         dir_list_new.append(d)
01252 
01253     all_vecs = np.column_stack(mech_vec_list)
01254     #U, s, _ = np.linalg.svd(np.cov(all_vecs))
01255     normalized_all_vecs = all_vecs
01256     print '>>>>>>>>>>>> all_vecs.shape <<<<<<<<<<<<<<<', all_vecs.shape
01257     #normalized_all_vecs = (all_vecs - all_vecs.mean(1))
01258 
01259     #Rule this out as it places equal value on the entire trajectory but we want
01260     #to focus modeling efforts on the beginning of the trajectory
01261     #normalized_all_vecs = normalized_all_vecs / np.std(normalized_all_vecs, 1)
01262 
01263     #Removes the effect of force scaling... not sure if we want this
01264     #normalized_all_vecs = normalized_all_vecs / ut.norm(normalized_all_vecs)
01265     U, s, _ = np.linalg.svd(np.cov((normalized_all_vecs)))
01266 
01267     perc_account = np.cumsum(s) / np.sum(s)
01268     mpu.plot_yx([0]+list(perc_account))
01269 
01270     mpu.set_figure_size(5.,5.)
01271     mpu.figure()
01272     mn = np.mean(all_vecs, 1).A1
01273     mpu.plot_yx(mn/np.linalg.norm(mn), color = '#FF3300',
01274                 label = 'mean (normalized)', scatter_size=5)
01275 
01276     c_list = ['#%02x%02x%02x'%(r,g,b) for (r,g,b) in [(152, 32, 176), (23,94,16)]]
01277     c_list = ['#00CCFF', '#643DFF']
01278     for i in range(2):
01279         mpu.plot_yx(U[:,i].flatten(), color = c_list[i],
01280                     label = 'Eigenvector %d'%(i+1), scatter_size=5)
01281 
01282     mpu.pl.axhline(y=0., color = 'k')
01283     mpu.legend(display_mode='less_space')
01284 
01285     if dimen == 2:
01286         fig = mpu.figure()
01287         proj_mat = U[:, 0:2]
01288         for i, v in enumerate(mech_vec_list[:]):
01289             p = proj_mat.T * (v - np.matrix(mn).T)
01290             color = mpu.random_color()
01291             label = legend_list[i]
01292 
01293             mpu.plot_yx(p[1,:].A1, p[0,:].A1, color = color,
01294                         linewidth = 0, label = label,
01295                         xlabel='\huge{First Principle Component}',
01296                         ylabel='\huge{Second Principle Component}',
01297                         axis = 'equal', picker=0.5)
01298 
01299         mpu.pl.axhline(y=0., color = 'k', ls='--')
01300         mpu.pl.axvline(x=0., color = 'k', ls='--')
01301         mpu.legend()
01302 
01303         ppg = pca_plot_gui(legend_list, mech_vec_list, U,
01304                            dir_list_new, np.matrix(mn).T)
01305         fig.canvas.mpl_connect('button_press_event', ppg.pick_cb)
01306         mpu.show()
01307 
01308 def filter_dir_list(dir_list, typ = 'rotary', name = None):
01309     filt_list = []
01310     for d in dir_list:
01311         nm = get_mech_name(d)
01312         if name != None:
01313             if name not in nm:
01314                 continue
01315 
01316 #        trial = 'open'
01317 #        l = glob.glob(d+'/*'+trial+'*mechanism_trajectories*.pkl')
01318 #        di = ut.load_pickle(l[0])
01319 #        m_typ = di['typ']
01320 #        if m_typ != typ:
01321 #            continue
01322 #        filt_list.append(d)
01323 
01324         di = extract_pkls(d, quiet=True)
01325         if di == None:
01326             continue
01327         if di.has_key('typ'):
01328             m_typ = di['typ']
01329             if m_typ != typ:
01330                 continue
01331             filt_list.append(d)
01332         else:
01333             continue
01334     return filt_list
01335 
01336 
01337 
01338 if __name__ == '__main__':
01339     import optparse
01340     p = optparse.OptionParser()
01341     p.add_option('-d', '--dir', action='store', default='',
01342                  type='string', dest='dir', help='directory with logged data')
01343     p.add_option('--check_data', action='store_true', dest='check_data',
01344                  help='count the number of trajectories for each mechanism')
01345     p.add_option('--rearrange', action='store_true', dest='rearrange',
01346                  help='rearrange aggregated pkls into separate folders for each mechanism')
01347     p.add_option('--clean', action='store_true', dest='clean',
01348                  help='remove pkls with corrupted data')
01349 
01350     p.add_option('--max_force_hist', action='store_true',
01351                  dest='max_force_hist', help='histogram of max forces')
01352     p.add_option('--max_force_radius_scatter', action='store_true',
01353                  dest='max_force_radius_scatter', help='scatter plot of max force vs radius')
01354     p.add_option('--opening_distances_drawers', action='store_true',
01355                  dest='opening_distances_drawers', help='opening distances for drawers')
01356     p.add_option('--plot_handle_height', action='store_true',
01357                  dest='plot_handle_height', help='handle height above the ground')
01358     p.add_option('--plot_radius', action='store_true',
01359                  dest='plot_radius', help='histogram of radii of the mechanisms')
01360     p.add_option('--correlate', action='store_true',
01361                  dest='correlate', help='correlation across different trials')
01362     p.add_option('--consistent_across_people', action='store_true',
01363                  dest='consistent_across_people',
01364                  help='plot mean and std for tangential and total magnitude of the force')
01365     p.add_option('--dimen_reduc', action='store_true',
01366                  dest='dimen_reduc',  help='try dimen reduction')
01367     p.add_option('--independence', action='store_true', 
01368                  dest='independence', help='test for conditional independence')
01369     p.add_option('--mech_models', action='store_true',
01370                  dest='mech_models',  help='fit mechanical models to data')
01371     p.add_option('--different_classes_rotary', action='store_true',
01372                  dest='different_classes_rotary',
01373                  help='scatter plot showing the differnt mechanism classes')
01374 
01375     opt, args = p.parse_args()
01376 
01377     dir_list = commands.getoutput('ls -d %s/*/'%(opt.dir)).splitlines()
01378 
01379 #    drawers = 0
01380 #    cabinets = 0
01381 #    for d in dir_list:
01382 #        nm = get_mech_name(d)
01383 #        di = extract_pkls(d)
01384 #        if di == None:
01385 #            print 'di was None for:', nm
01386 #            continue
01387 #        if di['rad'] == -1:
01388 #            drawers += 1
01389 #        else:
01390 #            cabinets += 1
01391 #
01392 #    print 'drawers:', drawers
01393 #    print 'cabinets:', cabinets
01394 #    import sys; sys.exit()
01395 
01396     if opt.clean:
01397         clean_data_forces(opt.dir)
01398     elif opt.rearrange:
01399         # listing all the different mechanisms
01400         pkl_list = commands.getoutput('ls %s/*.pkl'%(opt.dir)).splitlines()
01401         mech_name_list = []
01402         for p in pkl_list:
01403             nm = '_'.join(p.split('/')[-1].split('_')[:-5])
01404             print 'p:', p
01405             print 'nm:', nm
01406             mech_name_list.append(nm)
01407         mech_name_list = list(set(mech_name_list))
01408         print 'List of unique mechanisms:', mech_name_list
01409 
01410         for mech_name in mech_name_list:
01411             nm = '%s/%s'%(opt.dir, mech_name)
01412             os.system('mkdir %s'%nm)
01413             os.system('mv %s/*%s*.pkl %s'%(opt.dir, mech_name, nm))
01414     elif opt.check_data:
01415         mech_list = []
01416         for i, m in enumerate(dir_list):
01417             t = m.split('/')
01418             mech = t[-1]
01419             if mech == '':
01420                 mech = t[-2]
01421             mech_list.append(mech)
01422             print '%d. %s'%(i, mech)
01423 
01424         for i,d in enumerate(dir_list):
01425             mech_nm = mech_list[i]
01426             print '------------------------------------'
01427             print 'Mechanism name:', mech_nm
01428             for trial in ['open', 'close']:
01429                 l = glob.glob(d+'/*'+trial+'*mechanism_trajectories*.pkl')
01430                 l.sort()
01431                 print 'Number of %s trials: %d'%(trial, len(l))
01432     elif opt.max_force_radius_scatter:
01433         max_force_radius_scatter(dir_list[0:], open=True)
01434         max_force_radius_scatter(dir_list[0:], open=False)
01435         mpu.show()
01436     elif opt.max_force_hist:
01437         print 'Found %d mechanisms' % len(dir_list[0:])
01438         max_force_hist(filter_dir_list(dir_list[0:], typ='rotary'), open=True, type='rotary')
01439         max_force_hist(filter_dir_list(dir_list[0:], typ='prismatic'), open=True, type='prismatic')
01440         mpu.show()
01441     elif opt.opening_distances_drawers:
01442         plot_opening_distances_drawers(dir_list[0:])
01443         mpu.show()
01444     elif opt.plot_radius:
01445         l1 = filter_dir_list(dir_list, name='ree')
01446         l2 = filter_dir_list(dir_list, name='ge')
01447         print 'LEN:', len(filter_dir_list(dir_list, name=None))
01448         bar1 = mechanism_radius_histogram(filter_dir_list(dir_list, name=None))
01449         bar2 = mechanism_radius_histogram(l1+l2, color='y')
01450         labels = ['Other', 'Freezers and Refrigerators']
01451         mpu.pl.legend([bar1[0],bar2[0]], labels, loc='best')
01452         mpu.show()
01453     elif opt.plot_handle_height:
01454         #plot_title = 'Opening force at different heights'
01455         #plot_handle_height(dir_list[:], plot_title)
01456 
01457         #plot_handle_height_no_fridge_no_freezer()
01458 #        plot_handle_height_no_office()
01459         #handle_height_histogram(dir_list, plot_title='Homes excluding \n refrigerators and freezers')
01460         #handle_height_histogram(filter_dir_list(dir_list, name='ge'),
01461         #                        plot_title = 'Refrigerators')
01462         handle_height_histogram(filter_dir_list(dir_list, name='ree'),
01463                                 plot_title = 'Freezers')
01464         mpu.show()
01465     elif opt.correlate:
01466         cl = []
01467         lab_list = []
01468         ch_list =  input_mechanism_list(dir_list)
01469         for i, d in enumerate(ch_list):
01470             nm = get_mech_name(d)
01471             di = extract_pkls(d, open)
01472             ftan_l_l = di['ftan_l_l']
01473             frad_l_l = di['frad_l_l']
01474             mechx_l_l = di['mechx_l_l']
01475             time_l_l = di['time_l_l']
01476             typ = di['typ']
01477             rad = di['rad']
01478             #ftan_l_l, frad_l_l, mechx_l_l, typ, rad = extract_pkls(d, open)
01479             for j in range(len(ftan_l_l)):
01480                 if typ == 'rotary':
01481                     traj_vel = compute_trajectory_velocity(mechx_l_l[j],time_l_l[j],1)
01482                     if traj_vel > math.radians(30):
01483                         continue
01484                     t, f = bin(mechx_l_l[j], ftan_l_l[j], math.radians(1.),
01485                                max, ignore_empty=True, max_pose=math.radians(60))
01486                 if typ == 'prismatic':
01487                     t, f = bin(mechx_l_l[j], ftan_l_l[j], 0.01,
01488                                max, ignore_empty=True, max_pose=0.3)
01489                 cl.append(f)
01490                 lab_list.append(nm)
01491         correlate_trials(cl[0], cl[:], lab_list)
01492         mpu.show()
01493     elif opt.consistent_across_people:
01494         ch_list =  input_mechanism_list(dir_list)
01495         for dir in ch_list:
01496             compare_tangential_total_magnitude(dir)
01497         mpu.show()
01498     elif opt.different_classes_rotary:
01499         different_classes_rotary(dir_list)
01500     elif opt.independence:
01501         test_independence_mechanism(dir_list)
01502 
01503     elif opt.dimen_reduc:
01504         #ch_list =  input_mechanism_list(dir_list)
01505         #dimen_reduction_mechanisms(ch_list)
01506         #dimen_reduction_mechanisms(filter_dir_list(dir_list, name='HSI_Suite_210_brown_cabinet_right'))
01507         dimen_reduction_mechanisms(dir_list)
01508     elif opt.mech_models:
01509         dir = filter_dir_list(dir_list,
01510                 name='patient_room_door')[0]
01511         d = extract_pkls(dir, True)
01512         trial_num_list = d['trial_num_l']
01513         states_l = []
01514         xarr_l = [] 
01515         varr_l = []
01516         aarr_l = []
01517         forces_l = []
01518 
01519         for i, n in enumerate(trial_num_list):
01520             print 'i:', i
01521 #            if i != 5:
01522 #                continue
01523             #trial_idx = trial_num_list.index()
01524             mechx_l = d['mechx_l_l'][i]
01525             time_list = d['time_l_l'][i]
01526             forces = np.matrix(d['ftan_l_l'][i])
01527             radius = d['rad']
01528             window_len = 15
01529             mechx_l, vel, acc, time_list = mfc.kinematic_params(mechx_l, time_list, window_len)
01530             xarr = np.array(mechx_l)
01531             idxs = np.where(np.logical_and(xarr > math.radians(1), xarr < math.radians(15)))
01532 
01533             # smooth x
01534             forces = forces[0, window_len-1:-window_len+1]
01535             #compute vel
01536             forces = forces[0, 1:-1]
01537             # smooth vel
01538             forces = forces[0, window_len-1:-window_len+1]
01539             # compute acc
01540             forces = forces[0, 1:-1]
01541             # smooth acc
01542             forces = forces[0, window_len-1:-window_len+1]
01543             forces = forces[0, idxs[0]]
01544             xarr = np.matrix(xarr[idxs])
01545             varr = np.matrix(np.array(vel)[idxs])
01546             aarr = np.matrix(np.array(acc)[idxs])
01547             xarr_l.append(xarr)
01548             varr_l.append(varr)
01549             aarr_l.append(aarr)
01550             forces_l.append(forces)
01551 
01552             #import pdb
01553             #pdb.set_trace()
01554             #door_smd = mfd.DoorSpringMassDamper(radius, k=0., mass=0, damp=0., const=0, noise_cov=0.)
01555             door_smd = mfd.DoorMassDamper(radius)
01556             ones = np.ones(xarr.shape[1])
01557             states_l.append(np.matrix(np.row_stack((xarr, varr, aarr, ones))))
01558 
01559         states = np.column_stack(states_l)
01560         forces = np.column_stack(forces_l)
01561         acc_arr = states[2,:].A1
01562         farr = forces.A1
01563 #        import pdb; pdb.set_trace()
01564         print 'farr:', farr
01565         print 'acc_arr:', acc_arr
01566         mass = np.mean(np.divide(farr, acc_arr))
01567         print 'mass:', mass
01568         #door_smd = door_smd.fit(states, forces.T)
01569         door_smd = door_smd.fit(states[[1,2],:], forces.T)
01570 
01571         print 'fitted model', door_smd
01572         for i in range(len(xarr_l)):
01573             forces = forces_l[i]
01574             xarr = xarr_l[i]
01575             varr = varr_l[i]
01576             aarr = aarr_l[i]
01577             predicted_forces = door_smd.predict(states_l[i][[1,2],:])
01578             predicted_forces_mass = mass * states_l[i][2,:].A1
01579             mpu.figure()
01580             mpu.plot_yx(forces.A1, np.degrees(xarr.A1), label='actual', color='g')
01581             mpu.plot_yx(predicted_forces.A1, np.degrees(xarr.A1), label='predicted SMD', color='b')
01582             mpu.plot_yx(predicted_forces_mass, np.degrees(xarr.A1), label='predicted (mass only)', color='r')
01583             mpu.plot_yx(np.degrees(varr.A1), np.degrees(xarr.A1), label='vel', color=mpu.random_color())
01584             mpu.plot_yx(np.degrees(aarr.A1), np.degrees(xarr.A1), label='acel', color=mpu.random_color())
01585             mpu.legend()
01586         #mpu.show()
01587         
01588         #plot_velocity(dir)
01589         mpu.show()
01590     else:
01591 #        filt_list = filter_dir_list(dir_list)
01592 #        for dir in filt_list:
01593 #            max_force_vs_velocity(dir)
01594 #        mpu.show()
01595 
01596         d_list = input_mechanism_list(dir_list)
01597 #        d_list = filter_dir_list(dir_list, typ='prismatic')
01598 #        mpu.figure()
01599         traj_vel_l = []
01600         for dir in d_list:
01601             #make_vector_mechanism(dir)
01602 
01603 
01604 #            vel_l = []
01605 #            nm = get_mech_name(dir)
01606 #            print '>>>>>>>>>> nm:', nm
01607 #            d = extract_pkls(dir, ignore_moment_list=True)
01608 #            for i, mech_x in enumerate(d['mechx_l_l']):
01609 #                time_list = d['time_l_l'][i]
01610 #                #v = compute_average_velocity(mech_x, time_list, max_angle=math.radians(30), type='rotary')
01611 #                v = compute_average_velocity(mech_x, time_list, max_angle=0.2, type='prismatic')
01612 #                print 'v:', v
01613 #                if v == -1:
01614 #                    continue
01615 #                vel_l.append(v)
01616 #            sorted_vel_l = sorted(vel_l)
01617 #            if len(sorted_vel_l) > 6:
01618 #                vel_l = sorted_vel_l[0:6]
01619 #            else:
01620 #                vel_l = sorted_vel_l
01621 #            traj_vel_l += vel_l
01622 #
01623 #        #print 'mean angular velocity:', math.degrees(np.mean(traj_vel_l))
01624 #        #print 'std angular velocity:', math.degrees(np.std(traj_vel_l))
01625 #
01626 #        print 'mean angular velocity:', np.mean(traj_vel_l)
01627 #        print 'std angular velocity:', np.std(traj_vel_l)
01628 
01629             #plot_tangential_force(dir, all_trials = True, open = True,
01630             #                      filter_speed = math.radians(30))
01631             plot_tangential_force(dir, all_trials = True, open = True)
01632 
01633 #            nm = get_mech_name(dir)
01634 #            mpu.savefig(nm+'_grayscale.png')
01635 #            print 'Aloha ', nm
01636             #radial_tangential_ratio(dir)
01637         mpu.show()
01638 
01639 
01640 
01641 


2010_biorob_everyday_mechanics
Author(s): Advait Jain, Hai Nguyen, Charles C. Kemp (Healthcare Robotics Lab, Georgia Tech)
autogenerated on Wed Nov 27 2013 11:58:43