Exemple #1
0
def getref(fn):
    ''' return a list of references '''

    refstate = 0
    ls = []
    #txt = open(fn).readlines()
    txt = codecs.open(fn, encoding="utf-8").readlines()
    refstart = refend = len(txt)
    for i in range(len(txt)):
        s = txt[i]
        if refstate == 0:
            if s.startswith("\section{References}"):
                refstate = 1
                refstart = i
            continue
        else:
            ln = latexify( s.strip() )
            if ln == "": continue
            m = re.match("([0-9]+)\. .*\.", ln) # a loose pattern
            if not m: # reference ended
                refend = i
                break

            # strict pattern for volume and pages
            m = re.match("([0-9]+)\. (.*)\. ([0-9]{4})\. (.*). ([0-9a-zA-Z\- ]+): ([0-9a-zA-Z,\- ]+)\.", ln)
            if m:
                ref = Ref(m.group(1), m.group(2), m.group(3), m.group(4), m.group(5), m.group(6))
            else:
                # looser pattern for volume and pages
                m = re.match("([0-9]+)\. (.*)\. ([0-9]{4})\. (.*)\.", ln)
                if not m:
                    print "failed to get the year on %s" % ln
                    continue
                ref = Ref(m.group(1), m.group(2), m.group(3), m.group(4))
            ls += [ref,]
            #print "reference %s" % ref
    return ls, refstart, refend
def perfect_visualizer(p_subplot_list,gridspec_params,**kwargs):
    #p_subplot_list: list of perfect_subplot
    #gridspec_params = [rows,cols] of the subplot grid. Should be compatible with the coordinates of the perfect_subplots
    #kwargs: contains instructions to visualize everything

    
    dimensions=kwarg_default("dimensions",1,**kwargs)
    height=kwarg_default("height",0.15,**kwargs)
    textcols=kwarg_default("textcols",1,**kwargs)
    rows=kwarg_default("rows",gridspec_params[0],**kwargs)
    cols=kwarg_default("cols",gridspec_params[1],**kwargs)

    
    #set the height differently depending on if most plots are colormaps (2D), and thus need colorbars
    if dimensions == 1:
        adjust_bottom=kwarg_default("adjust_bottom",0.15,**kwargs)
        adjust_left=kwarg_default("adjust_left",0.17,**kwargs)
        adjust_top=kwarg_default("adjust_top",0.97,**kwargs)
        adjust_right=kwarg_default("adjust_right",0.95,**kwargs)
        base_rows=3.0
    elif dimensions == 2:
        adjust_bottom=kwarg_default("adjust_bottom",0.15,**kwargs)
        adjust_left=kwarg_default("adjust_left",0.12,**kwargs)
        adjust_top=kwarg_default("adjust_top",0.85,**kwargs)
        adjust_right=kwarg_default("adjust_right",0.99,**kwargs)
        base_rows=2.0
    base_topbot_adjust=adjust_bottom+(1-adjust_top)

    def row_to_height(rows):
            return (rows/base_rows)*3.39*(1-base_topbot_adjust)*(numpy.sqrt(5)-1.0)/2.0 +3.39*base_topbot_adjust*(numpy.sqrt(5)-1.0)/2.0


    height=row_to_height(rows)
    base_height=row_to_height(base_rows)
    adjust_bottom=adjust_bottom*base_height/height
    adjust_top=1-(1-adjust_top)*base_height/height
    
    latexify(fig_height=height,columns=textcols)
    fig=plt.figure()


    fig.subplots_adjust(bottom=adjust_bottom)
    fig.subplots_adjust(left=adjust_left)
    fig.subplots_adjust(top=adjust_top)
    fig.subplots_adjust(right=adjust_right)

    adjust_hspace=kwarg_default("adjust_hspace",0.01,**kwargs)
    adjust_wspace=kwarg_default("adjust_wspace",0.01,**kwargs)
    fig.subplots_adjust(hspace=adjust_hspace)
    fig.subplots_adjust(wspace=adjust_wspace)


    global_xlabel=kwarg_default("global_xlabel",None,**kwargs)
    if global_xlabel is not None:
        if dimensions == 1:
            fig.text(0.5+adjust_left/4, 0.01, global_xlabel, ha='center')
        elif dimensions == 2:
            fig.text(0.5+adjust_left/4, 0.01*base_height/height, global_xlabel, ha='center')
    
    global_ylabel=kwarg_default("global_ylabel",None,**kwargs)
    if global_ylabel is not None:
        if dimensions == 1:
            fig.text(0.01, 0.5+adjust_bottom/4, global_ylabel, va='center', rotation='vertical')
        elif dimensions == 2:
            fig.text(0.01, 0.5+adjust_bottom/4.0, global_ylabel, va='center', rotation='vertical')

    
    gs=gridspec.GridSpec(gridspec_params[0],gridspec_params[1])

    ax_list=[]
    
    for p_subplot in p_subplot_list:
        ax_list.append(plt.subplot(gs[p_subplot.subplot_coordinates]))

    for ax,p_subplot in zip(ax_list,p_subplot_list):
        monkey_patch(ax.xaxis,'x')
        monkey_patch(ax.yaxis,'y')

        #keywords in the p_subplot to control looks:
        ax.spines['bottom'].set_color(p_subplot.border_color)
        ax.spines['top'].set_color(p_subplot.border_color)
        ax.spines['left'].set_color(p_subplot.border_color)
        ax.spines['right'].set_color(p_subplot.border_color)

        ax.spines['bottom'].set_linestyle(p_subplot.border_linestyle)
        ax.spines['top'].set_linestyle(p_subplot.border_linestyle)
        ax.spines['left'].set_linestyle(p_subplot.border_linestyle)
        ax.spines['right'].set_linestyle(p_subplot.border_linestyle)
        if p_subplot.vlines is not None:
            for p in p_subplot.vlines:
                ax.axvline(x=p,color='k',linestyle=':')
        if p_subplot.hlines is not None:
            for p in p_subplot.hlines:
                ax.axhline(y=p,color='silver',linestyle=':')
        
        if p_subplot.show_xaxis_ticklabel == False:
            plt.setp(ax.get_xticklabels(), visible=False)
            ax.xaxis.get_major_formatter().set_powerlimits((float("-inf"), float("inf")))
        else:
            plt.setp(ax.get_xticklabels(), visible=True)
            
        if p_subplot.show_yaxis_ticklabel == False:
            plt.setp(ax.get_yticklabels(), visible=False)
            ax.yaxis.get_major_formatter().set_powerlimits((float("-inf"), float("inf")))

        if p_subplot.show_xaxis == False:
            plt.setp(ax.xaxis, visible=False)
        if p_subplot.show_yaxis == False:
            plt.setp(ax.yaxis, visible=False)

                
        if p_subplot.xscale == 'linear':
            x_locator=ticker.MaxNLocator(p_subplot.xticks)
        if p_subplot.xscale == 'log':
            x_locator=ticker.LogLocator(p_subplot.xticks)
        ax.xaxis.set_major_locator(x_locator)
            
        if p_subplot.yscale == 'linear':
            y_locator=ticker.MaxNLocator(p_subplot.yticks)
        if p_subplot.yscale == 'log':
            y_locator=ticker.LogLocator(p_subplot.yticks)
        ax.yaxis.set_major_locator(y_locator)

       
        ############## 1D #########
        if p_subplot.dimensions == 1:
            x=p_subplot.x
            y=p_subplot.data            
            ax.yaxis.offset_text_position="there"
            

            
            if type(p_subplot.linestyles) is not list:
                p_subplot.linestyles=[p_subplot.linestyles]*len(y)
                p_subplot.linewidths=[p_subplot.linewidths]*len(y)
            for i in range(len(y)):
                try:
                    ax.plot(x[i],y[i],linestyle=p_subplot.linestyles[i],color=p_subplot.colors[i],linewidth=p_subplot.linewidths[i],marker=p_subplot.markers[i],fillstyle=p_subplot.fillstyles[i])
                except IndexError:
                    print "Index error in ax.plot(). Most likely, linestyles, linewidths and colors have the wrong lengths."
                    print "len(colors): " + str(len(p_subplot.colors))
                    print "len(linestyles): " + str(len(p_subplot.linestyles))
                    print "len(linewidths): " + str(len(p_subplot.linewidths))
                    print "len(markers): " + str(len(p_subplot.markers))
                    print "len(fillstyles): " + str(len(p_subplot.fillstyles))
                    print "len(x): " + str(len(x))
                    print "len(y): " + str(len(y))
            ax.yaxis.set_label_coords(-0.15, 0.5)            

        ############# 2D ###########
        if p_subplot.dimensions == 2:
            X,Y=numpy.meshgrid(p_subplot.x,p_subplot.y)
            z=numpy.transpose(p_subplot.data)
  
            ax.pcolor(X, Y, z,rasterized=True,linewidth=0)
            
            if p_subplot.show_zaxis == True:
                divider = make_axes_locatable(ax)
                cax = divider.append_axes("top", "-10%", pad="10%")
                cb=fig.colorbar(ax.collections[0],cax=cax,orientation="horizontal")
                #cb.solids.set_edgecolor("face")
                monkey_patch(cb.ax.xaxis, 'x')
                if p_subplot.yscale == 'linear':
                    tick_locator = ticker.MaxNLocator(nbins=p_subplot.zticks)
                if p_subplot.yscale == 'log':
                    tick_locator = ticker.LogLocator(nbins=p_subplot.zticks)
                cb.locator=tick_locator
                cb.ax.xaxis.set_ticks_position('top')
                cb.ax.xaxis.set_label_position('top')
                cb.ax.set_xscale(p_subplot.zscale)
                cb.ax.tick_params(direction='out', pad=1)
                cb.formatter.set_powerlimits((0, 0))
                cb.update_ticks()
                if p_subplot.show_zaxis_ticklabel == False:
                    plt.setp(cb.ax.get_xticklabels(), visible=False)
                    #makes it impossible to have an offset without a ticklabel
                    cb.formatter.set_powerlimits((float("-inf"), float("inf")))
                    cb.update_ticks()
                cb.ax.xaxis.offset_text_position="there2"

            if p_subplot.zaxis_label is not None:
                cb.ax.set_xlabel(p_subplot.zaxis_label)
            if p_subplot.zlims is not None:
                zmin=p_subplot.zlims[0]
                zmax=p_subplot.zlims[1]
                ax.collections[0].set_clim(zmin,zmax)
                cm=p_subplot.cm
                if p_subplot.symmetrize_cm:
                    cm=symmetrize_colormap(cm,zmin,zmax)
                ax.collections[0].set_cmap(cm)
                for i in p_subplot.hidden_zticklabels:
                    plt.setp(cb.ax.get_xticklabels()[i],visible=False)
            cb.solids.set_edgecolor("face")

                
        
        #we need to sort out ticks after plotting, since they are generated
        #during the plot operation
        if p_subplot.xaxis_label is not None:
            ax.set_xlabel(p_subplot.xaxis_label)
        if p_subplot.yaxis_label is not None:
            #print str(p_subplot.yaxis_label)+": " +"("+str(p_subplot.yaxis_label_x)+","+str(p_subplot.yaxis_label_y)+")"
            ax.set_ylabel(p_subplot.yaxis_label)
            ax.yaxis.set_label_coords(p_subplot.yaxis_label_x,p_subplot.yaxis_label_y) 
        
        if p_subplot.xlims is not None:
            ax.set_xlim(p_subplot.xlims)
        if p_subplot.xlims is not None:
            ax.set_ylim(p_subplot.ylims)

        if p_subplot.xaxis_powerlimits is not None:
            print "Warning: xlabel power limits not fully implemented: offset position unknown, offset not shown."
            ax.ticklabel_format(axis='x', style='sci', scilimits=p_subplot.xaxis_powerlimits)
            #ax.xaxis.get_major_formatter().set_powerlimits(p_subplot.xaxis_powerlimits)
        
        
        if p_subplot.yscale == 'log':
            ax.set_yscale(p_subplot.yscale, nonposy='clip',subsy=[10])
            for ticklabel in ax.get_yticklabels()[0:2:-1]:
                ticklabel.set_visible(False)
            ax.get_yticklabels()[0].set_visible(False)
            ax.get_yticklabels()[-1].set_visible(False)
            ax.get_yticklabels()[1].set_visible(False)
            ax.get_yticklabels()[-2].set_visible(False)
        elif p_subplot.yscale=='linear':
            if p_subplot.yaxis_powerlimits is None:
                ax.ticklabel_format(axis='y', style='sci', scilimits=(-0,1))
            else:
                ax.ticklabel_format(axis='y', style='sci', scilimits=p_subplot.yaxis_powerlimits)
            ax.get_yticklabels()[0].set_visible(False)
            ax.get_yticklabels()[-1].set_visible(False)
        elif p_subplot.yscale=='symlog':
            ax.set_yscale(p_subplot.yscale)
        for i in p_subplot.hidden_xticklabels:
            plt.setp(ax.get_xticklabels()[i],visible=False)
        for i in p_subplot.hidden_yticklabels:  
            plt.setp(ax.get_yticklabels()[i],visible=False)
        

        
        #print str(p_subplot.title)+": " +"("+str(p_subplot.title_x)+","+str(p_subplot.title_y)+")"
        ax.set_title(p_subplot.title,x=p_subplot.title_x,y=p_subplot.title_y,fontsize=8)
def main(argv):
    parser = optparse.OptionParser()

    parser.add_option('',
                      '--avgcolorbar',
                      action="store",
                      type='float',
                      dest='avgcolorbar',
                      help='Color bar',
                      nargs=2,
                      default=(None, None))
    parser.add_option('',
                      '--res',
                      action="store",
                      type='float',
                      dest='res',
                      help='Resolution in deg',
                      nargs=1,
                      default=(5))
    parser.add_option('',
                      '--rep',
                      action="store",
                      type='int',
                      dest='rep',
                      help='How many repetitions',
                      nargs=1,
                      default=(2))
    parser.add_option('',
                      '--limits',
                      action="store",
                      type='float',
                      dest='limits',
                      help='Limits in meter',
                      nargs=4,
                      default=(0.250, 0.450, -0.233,
                               0.197))  # [minx, maxx, miny, maxy]
    parser.add_option('',
                      '--N',
                      action="store",
                      type='float',
                      dest='N',
                      help='Normal force',
                      nargs=1,
                      default=(0.8374 * 9.81))  # Normal force

    (opt, args) = parser.parse_args()

    if len(args) < 1:  # no bagfile name
        parser.error(
            "Usage: plot_friction_vs_vel.py [dir_to_friction_scan_iso]")
        return

    dir_to_friction_scan_iso = args[0]

    figfname_png = dir_to_friction_scan_iso + '/friction_over_direction_overmaterial.png'
    figfname_pdf = dir_to_friction_scan_iso + '/friction_over_direction_overmaterial.pdf'
    ft_wrench = []

    min_x, max_x, min_y, max_y = opt.limits

    center = [(max_x + min_x) / 2, (max_y + min_y) / 2]
    acc = 0

    # a list of materials
    #dirlist = [ name for name in os.listdir(dir_to_friction_scan_iso) if os.path.isdir(os.path.join(dir_to_friction_scan_iso, name)) ]

    dirlist = ['abs', 'delrin', 'plywood', 'pu']

    shape_id = 'rect1'
    vel = 20
    N = opt.N

    linestyles = [':', '-', '-', '-']
    markerstyles = ['', '', '^', 'o']
    markeverys = [1, 1, 3, 3]
    rangex = xrange(0, 360, opt.res)
    raidus = 0.001

    from latexify import latexify
    latexify(scale=2)
    axes = plt.gca()
    axes.grid(True, linewidth=0.25, color='grey')
    axes.set_axisbelow(True)

    for inds, surface in enumerate(dirlist):
        print dir_to_friction_scan_iso, surface, shape_id

        avgs = []
        stds = []
        for deg in rangex:
            vals = []
            for rep in xrange(opt.rep):
                h5filename = 'record_surface=%s_shape=%s_a=%.0f_v=%.0f_deg=%d_rep=%03d.h5' % (
                    surface, shape_id, acc * 1000, vel, deg, rep)
                filepath = '%s/%s/%s/%s' % (dir_to_friction_scan_iso, surface,
                                            shape_id, h5filename)
                f = h5py.File(filepath, "r")
                tip_array = f['tip_array'].value
                ft_wrench = f['ft_wrench'].value

                scale = (len(ft_wrench) * 1.0 / len(tip_array))

                for i, tip_pos in enumerate(tip_array):
                    if np.linalg.norm(
                            np.array(tip_pos[1:3]) -
                            np.array(center)) < raidus:
                        ft_i = int(i * scale)
                        vals.append(ft_wrench[ft_i][1:3])
            avgs.append(np.mean(vals, 0))

            # print surface, ' vel=', v
            # print 'average', '%.3f' % (np.average(vals) / N)
            # print 'std', '%.3f' % (np.std(vals) / N)
            # print 'max', '%.3f' % (np.max(vals) / N)
            # print 'min', '%.3f' % (np.min(vals) / N)

        xs = [ft[0] for ft in avgs]
        ys = [ft[1] for ft in avgs]
        xs.append(xs[0])
        ys.append(ys[0])

        plt.errorbar(xs,
                     ys,
                     color='k',
                     fmt=linestyles[inds] + markerstyles[inds],
                     label=surface,
                     markevery=markeverys[inds],
                     markersize=5,
                     linewidth=0.5)

    axes.set_xlim([-7, 7])
    axes.set_ylim([-7, 7])
    axes.set_aspect('equal')
    axes.set_xlabel('Force x')
    axes.set_ylabel('Force y')

    legend = plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))

    legend.get_frame().set_linewidth(0.25)
    plt.tight_layout(pad=0)
    plt.subplots_adjust(left=0,
                        bottom=None,
                        right=0.87,
                        top=None,
                        wspace=None,
                        hspace=None)
    plt.savefig(figfname_png)
    plt.savefig(figfname_pdf)
    plt.show()
    plt.close()
Exemple #4
0
def main(argv):
    parser = optparse.OptionParser()

    parser.add_option('',
                      '--fmt',
                      action="store",
                      dest='fmt',
                      help='Figure format e.g. png, pdf',
                      default='png')

    (opt, args) = parser.parse_args()

    # files = ['/home/mcube/pnpushdata/friction_scan/plywood/rect1/record_surface=plywood_shape=rect1_a=-1000_v=20_rep=%03d_fcot.h5',
    # '/home/mcube/pnpushdata/friction_scan/delrin/rect1/record_surface=delrin_shape=rect1_a=-1000_v=20_rep=%03d_fcot.h5',
    # '/home/mcube/pnpushdata/friction_scan/pu/rect1/record_surface=pu_shape=rect1_a=0_v=20_rep=%03d_fcot.h5',
    # '/home/mcube/pnpushdata/friction_scan/abs/rect1/record_surface=abs_shape=rect1_a=0_v=20_rep=%03d_fcot.h5']
    files = [
        '/home/mcube/pnpushdata/friction_scan/abs/rect1/record_surface=abs_shape=rect1_a=0_v=20_rep=%03d_fcot.h5',
        '/home/mcube/pnpushdata/friction_scan/delrin/rect1/record_surface=delrin_shape=rect1_a=-1000_v=20_rep=%03d_fcot.h5',
        '/home/mcube/pnpushdata/friction_scan/plywood/rect1/record_surface=plywood_shape=rect1_a=-1000_v=20_rep=%03d_fcot.h5',
        '/home/mcube/pnpushdata/friction_scan/pu/rect1/record_surface=pu_shape=rect1_a=0_v=20_rep=%03d_fcot.h5'
    ]

    legends = ['abs', 'delrin', 'plywood', 'pu']

    linestyles = [':', '-', '-', '-']
    markerstyles = ['', '', 'x', 'o']
    #linestyles = ['-', '--', '-', '--']
    linewidths = [1, 1, 1, 1]

    from latexify import latexify
    latexify(8, fontsize=16)
    fig = plt.figure()
    #plt.rc('font', family='serif', size=20)
    for ind, filename in enumerate(files):
        if not os.path.isfile(filename):
            continue
        print ind, filename
        with h5py.File(filename, "r") as f:
            image_avgs_t = f['image_avgs_t'].value
            image_stds_t = f['image_stds_t'].value
        tmp = []
        for t in range(len(image_avgs_t)):
            tmp.append(0)
            for idx in range(len(image_avgs_t[t])):
                for idy in range(len(image_avgs_t[t][idx])):
                    tmp[-1] += image_avgs_t[t][idx][idy] / 9.0
        plt.errorbar(range(1,
                           len(image_avgs_t) + 1),
                     tmp,
                     fmt=linestyles[ind] + markerstyles[ind],
                     linewidth=linewidths[ind],
                     label=legends[ind],
                     color='k',
                     markevery=10)
        print legends[ind], 'start', tmp[0], 'end', tmp[-1], 'chanage', (
            tmp[-1] - tmp[0]) / tmp[0]

    #plt.rc('font', family='serif', size=15)
    plt.legend(ncol=4)
    axes = plt.gca()
    axes.set_ylim([0.1, 0.35])

    plt.ylabel('Coefficient of friction')
    plt.xlabel('Number of scans')
    fig.subplots_adjust(left=None,
                        bottom=0.16,
                        right=None,
                        top=None,
                        wspace=None,
                        hspace=None)
    plt.tight_layout()
    #plt.title('Change of frictional coefficient over time')
    plt.savefig(
        '/home/mcube/pnpushdata/friction_scan/friction_overtime_overmaterial_lineplot.png'
    )
    plt.savefig(
        '/home/mcube/pnpushdata/friction_scan/friction_overtime_overmaterial_lineplot.pdf'
    )

    plt.show()
def main(argv):
    
    parser = optparse.OptionParser()
    
    parser.add_option('', '--avgcolorbar', action="store", type='float', dest='avgcolorbar', 
                      help='Color bar', nargs=2, default=(None,None))
    parser.add_option('', '--res', action="store", type='float', dest='res', 
                      help='Resolution in meter', nargs=2, default=(0.005,0.005))
    parser.add_option('', '--limits', action="store", type='float', dest='limits', 
                      help='Limits [minx, maxx, miny, maxy]', nargs=4, default=(0.250,0.450, -0.233, 0.197)) 
    parser.add_option('', '--N', action="store", type='float', dest='N', 
                      help='Normal force', nargs=1, default=(0.8374 * 9.81)) 
                      
    parser.add_option('', '--title', action="store", type='string', dest='title', 
                      help='Title', default='')
    parser.add_option('', '--dirpath', action="store", type='string', dest='dirpath', 
                      help='Dirpath', default='./')
                      
    (opt, args) = parser.parse_args()
    
    cachefile = '/tmp/plot_friction_map_fine_overmaterial'
    import shelve
    if os.path.exists(cachefile):
        f = shelve.open(cachefile)
        ss = f['ss'];
        ncol = f['ncol'];
        all_valss = f['all_valss']
        image_avgs = f['image_avgs']
        image_range = f['image_range']
        image_ranges = f['image_ranges']
        opt = f['opt']
        rangex = f['rangex']
        rangey = f['rangey']
    else:
        ss = ['abs', 'delrin', 'plywood', 'pu']
        ncol = 2
        all_valss = []
        image_avgs = []
        image_range = [100, -100]
        image_ranges = []
        
        for i,s in enumerate(ss):
            hdf5_filepath = '%s/%s/rect1/record_surface=%s_shape=rect1_a=0_v=20_rep=000.h5' % (opt.dirpath, s, s)
            (all_vals, image_avg, (minn, maxx), (rangex, rangey)) = extract(opt, hdf5_filepath)
            all_valss.append(all_vals)
            image_avgs.append(image_avg)
            
            import scipy.io as sio
            mat_filepath = '%s/%s/rect1/friction_over_location_map_surface=%s.mat' % (opt.dirpath, s,s )
            import numpy as np
            sio.savemat(mat_filepath, {'image_avg':image_avg})
            
            image_ranges.append([minn, maxx])
            if minn < image_range[0]:
                image_range[0] = minn
            if maxx > image_range[1]:
                image_range[1] = maxx
                
        ll = locals()
        f = shelve.open(cachefile, 'n')
        for key, val in ll.iteritems():
            try:
                f[key] = val
            except:
                pass
    
    
    figfname_png = opt.dirpath + '/friction_over_location_map.png'
    figfname_pdf = opt.dirpath + '/friction_over_location_map.pdf'
    figfname_mat = opt.dirpath + '/friction_over_location_map.pdf'
    figfname_hist_png = opt.dirpath + '/friction_over_location_hist.png'
    figfname_hist_pdf = opt.dirpath + '/friction_over_location_hist.pdf'
    
    # plot the distribution
    
    #plt.rc('text', usetex=True)
    #fig = plt.figure(figsize=(8,4))
    #plt.rc('font', family='serif', size=15, serif=['Times'])
    latexify(scale = 2)
    #fig, ax = plt.subplots()
    ax = plt.gca()
    bins = np.linspace(0, 0.6, 500)
    colors = ['r', 'b', 'g', 'k']
    
    linestyles = [':', '-', '-.', '--']
    markerstyles = ['', '', '', '']
    
    legend_handles = []
    for i, s in enumerate(ss):
        print s
        #plt.hist(np.array(all_vals)/opt.N, bins, normed=1, histtype='stepfilled', facecolor='white', alpha=0.75)
        n, bins, patches= ax.hist(np.array(all_valss[i])/opt.N, bins, normed=1, histtype='stepfilled', 
                 facecolor='none', edgecolor=colors[i], label=s, alpha=0)
        
        #import pdb; pdb.set_trace()
        print 'mean:', np.mean(all_valss[i])/opt.N
        print 'std:', np.std(all_valss[i])/opt.N
        print 'std (%):', np.std(all_valss[i])/ np.mean(all_valss[i]) * 100
        
        bincenters = 0.5*(bins[1:]+bins[:-1])
        # add a 'best fit' line for the normal PDF
        #y = mlab.normpdf( bincenters, mu, sigma)
        #import pdb; pdb.set_trace()
        l, = ax.plot(bincenters, n, linestyles[i]+markerstyles[i], linewidth=2, markevery=20, label=s,
                     color=colors[i], markersize=4, markerfacecolor='white')
        # do legend
        #line = mlines.Line2D([], [], color=colors[i], label=s)
        legend_handles.append(l)
        
    #plt.xticks(np.linspace(0, 0.6, 3))
    #plt.yticks(np.linspace(0, 25, 3))
    plt.ylabel('Probability')
    plt.xlabel('Coefficient of friction')
    legend = ax.legend(legend_handles, ss)
    legend.get_frame().set_linewidth(0.25)

    
    ax.yaxis.set_visible(True)
    plt.tight_layout(pad=0.4)
    
    plt.savefig(figfname_hist_png)
    plt.savefig(figfname_hist_pdf)
    #plt.show()
    plt.close()
    
    
    latexify(scale = 1)
    fig, axes = plt.subplots((len(ss)+ncol-1)/ncol , ncol)
    #plt.rc('font', family='serif', size=15)
    
    ims = []
    for i, s in enumerate(ss):
        
        im = axes.flat[i].imshow(image_avgs[i], extent=(rangey[0], rangey[-1]+opt.res[1], rangex[-1]+opt.res[0], rangex[0]),
                             interpolation='nearest', cmap=cm.Greys, vmin=image_ranges[i][0], vmax=image_ranges[i][1])

        divider = make_axes_locatable(axes.flat[i])
        cax = divider.append_axes("bottom", size="5%", pad=0.05)

        cbar = plt.colorbar(im, cax=cax, orientation='horizontal', ticks=image_ranges[i])
        cbar.ax.set_xticklabels([('%.2f' % image_ranges[i][0]), ('%.2f' % image_ranges[i][1])])
        
        
        axes.flat[i].xaxis.set_visible(False)
        axes.flat[i].yaxis.set_visible(False)
        axes.flat[i].set_title(s)
        
    #plt.legend()
    
    # fig.subplots_adjust(left=0, bottom=0, right=1, top=0.95,
                    # wspace=0.18, hspace=0.17)
    plt.tight_layout(pad=0.4, w_pad=0, h_pad=1.0)
    # fig.subplots_adjust(left=0.02, bottom=None, right=0.98, top=None,
                    # wspace=0.08, hspace=None)
                    
    #plt.tight_layout()
    plt.savefig(figfname_png, dpi=300)
    plt.savefig(figfname_pdf, dpi=300)
    
    print figfname_png
    #plt.show()
    
    plt.close()
import numpy as np
import matplotlib.pyplot as plt
from latexify import latexify
from matplotlib import patches

# Configuro latexify a dos columnas
latexify(columns=2, fontawesome=True)

# Grafico
fig = plt.figure(figsize=(6.9, 3))
ax1 = fig.add_subplot(111)
xmax = 8 * np.pi
ymax = xmax / ((6.9 / 3))
ax1.set_xlim(0, xmax)
ax1.set_ylim(0, ymax)

# Radiance
for ang in [20, 40, 60, 80, 100]:
    x0 = 2.3 * xmax / 4
    y0 = 1.3 * ymax / 4
    a = ang * np.pi / 180
    x0 = x0
    y0 = y0
    r = -ymax * ((ang - 10) * (ang - 110)) / 4000
    plt.annotate("", (x0 + r * np.cos(a), y0 + r * np.sin(a)), (x0, y0),
                 arrowprops=dict(color='C2', arrowstyle="-", lw=2))
    r = r / np.sqrt(2)
    plt.annotate("", (x0 + r * np.cos(a), y0 + r * np.sin(a)), (x0, y0),
                 arrowprops=dict(
                     color='C2',
                     arrowstyle="-|>, head_width=0.3,head_length=1",
Exemple #7
0
random_users = [8] * 100
random_users = np.array(random_users)
random_users[0:27] = 2
random_users[27:39] = 4
random_users[39:48] = 6

random_streams = [8] * 100
norm_users = [8] * 100
norm_users = np.array(norm_users)
norm_users[0:15] = 4
norm_users[15:25] = 6

norm_streams = [8] * 100

params = latexify(columns=2)
matplotlib.rcParams.update(params)

plt.figure()

random_users = np.sort(random_users)
F2 = np.array(range(len(random_users))) / float(len(random_users))
plt.plot(random_users,
         F2,
         color='red',
         linestyle=':',
         linewidth=3,
         label='Random user selection \n(Two streams per user)')

random_streams = np.sort(random_streams)
F2 = np.array(range(len(random_streams))) / float(len(random_streams))
Exemple #8
0
#! /usr/bin/env python
import math
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import argparse
import sys
import os.path
import latexify
latexify.latexify(columns=1)

def offsetLogger(offsets, args, outf="results/offset-stat.txt"):
    with open(outf, "a") as of:
        for offset in offsets:
            of.write("%s %f\n" %(args.outFile, offset))
    of.close()

def extract(tracefile):
    yss = []
    xs = []
    ys1 = []
    ys2 = []
    with open(tracefile) as fin:
        for line in fin:
            line = line.strip()
            rds = line.split()
            if rds[1] == "Node0" and rds[2] == "257" and rds[4] == "InData":
                # print line
                ys1.append(float(rds[5]))
                xs.append(int(rds[int(0)]))
            elif rds[1] == "Node0" and rds[2] == "256" and rds[4] == "InData":
def main(argv):
    parser = optparse.OptionParser()
    
    parser.add_option('', '--res', action="store", type='float', dest='res', 
                      help='Resolution in deg', nargs=1, default=(5))
    parser.add_option('', '--rep', action="store", type='int', dest='rep', 
                      help='How many repetitions', nargs=1, default=(1))
    parser.add_option('', '--limits', action="store", type='float', dest='limits', 
                      help='Limits in meter', nargs=4, default=(0.250,0.450, -0.233, 0.197)) # [minx, maxx, miny, maxy]
    parser.add_option('', '--N', action="store", type='float', dest='N', 
                      help='Normal force', nargs=1, default=(0.8374 * 9.81)) # Normal force
    parser.add_option('', '--surface', action="store", type='string', dest='surface_id', 
                      help='surface', nargs=1, default='plywood') # Normal force
                      
    (opt, args) = parser.parse_args()
    
    if len(args) < 1:  # no bagfile name
        parser.error("Usage: plot_friction_limitsurface.py [dir_to_friction_scan_limitsurface]")
        return
    
    dir_to_friction_scan_ls = args[0]
    
    figfname_png = dir_to_friction_scan_ls + '/friction_limitsurface_%s.png' % opt.surface_id
    figfname_pdf = dir_to_friction_scan_ls + '/friction_limitsurface_%s.pdf' % opt.surface_id
    figfname_png_2d = dir_to_friction_scan_ls + '/friction_limitsurface_%s_2d.png' % opt.surface_id
    figfname_pdf_2d = dir_to_friction_scan_ls + '/friction_limitsurface_%s_2d.pdf' % opt.surface_id
    ft_wrench = []
    
    min_x, max_x, min_y, max_y = opt.limits
    
    center = [(max_x + min_x) /2, (max_y + min_y) /2 ]
    acc = 0
    
    # a list of materials
    #dirlist = [ name for name in os.listdir(dir_to_friction_scan_iso) if os.path.isdir(os.path.join(dir_to_friction_scan_iso, name)) ]
    
    #dirlist = ['abs', 'delrin','plywood',  'pu']
    
    shape_id = 'rect1'
    vel = 20
    N = opt.N
    
    linestyles = [':', '-', '-', '-']
    markerstyles = ['', '', '^', 'o']
    markeverys = [1,1,3,3]
    rangex = xrange(0, 360, opt.res)
    thres = 0.001
    degs_default = xrange(0, 360, 5)
    rep = 0
    radii = [0, 0.0125, 0.025, 0.05]
    rotdegs_default = np.linspace(-80, 80, 21)
      
    #hack
    degs_default = [0, 180]
    #radii = [0, 0.05]
    #rotdegs_default = np.linspace(-64, 64, 17)
    
    
    vals = []
    vals_y_extreme = []
    vals_x_extreme = []
    for radius in radii:
        if radius == 0:
            degs = [0]
        else:
            degs = degs_default
        for deg in degs:  # translation velocity direction
            th = np.deg2rad(deg)
            
            if radius == 0:
                rotdegs = [80, -80]
            elif deg in [0, 90, 180, 270]:
                rotdegs = np.linspace(-88, 88, 45)
            else:
                rotdegs = rotdegs_default
                
            for rotdeg in rotdegs:  # rotation velocity direction
                rotth = np.deg2rad(deg)
                start_ori = ik.helper.qwxyz_from_qxyzw(tfm.quaternion_from_matrix((np.dot(tfm.euler_matrix(0,np.pi,0), tfm.euler_matrix(0,0,rotth)))))
                end_ori = ik.helper.qwxyz_from_qxyzw(tfm.quaternion_from_matrix((np.dot(tfm.euler_matrix(0,np.pi,0), tfm.euler_matrix(0,0,-rotth)))))
                start_pos = [np.cos(th)* radius + center[0], np.sin(th)* radius + center[1]]
                end_pos = [np.cos(th+np.pi)* radius + center[0], np.sin(th+np.pi)* radius + center[1]]
                
                vel_direc = [np.array(end_pos) - np.array(start_pos), 2*rotth]
            
                h5filename = 'record_surface=%s_shape=%s_a=%.0f_v=%.0f_deg=%d_rotdeg=%d_radius=%.3f_rep=%03d.h5' % (opt.surface_id, shape_id, acc*1000, vel, deg, rotdeg, radius, rep)
                
                filepath = '%s/%s/%s/%s' % (dir_to_friction_scan_ls,opt.surface_id,shape_id,h5filename)
                print 'processing', filepath
                if not os.path.isfile(filepath):
                    print 'not exists'
                    break
                    
                f = h5py.File(filepath, "r")
                tip_array = f['tip_pose'].value
                ft_wrench = f['ft_wrench'].value
                f.close()
                
                scale = (len(ft_wrench)*1.0/len(tip_array))
                
                for i, tip_pos  in enumerate(tip_array):
                    if radius == 0: # use the center part only
                        if np.linalg.norm(np.array(tip_pos[3]) - np.array(0)) < np.deg2rad(1):
                            ft_i = int(i * scale)
                            vals.append(list(ft_wrench[ft_i][1:3]) + list([ft_wrench[ft_i][3]]))  # force x y and torque in z
                            vals_y_extreme.append(np.abs(ft_wrench[ft_i][3]))
                    else:
                        if np.linalg.norm(np.array(tip_pos[1:3]) - np.array(center)) < thres and np.linalg.norm(np.array(tip_pos[3]) - np.array(0)) < np.deg2rad(1):
                            ft_i = int(i * scale)
                            vals.append(list(ft_wrench[ft_i][1:3]) + list([ft_wrench[ft_i][3]]))  # force x y and torque in z
                            if np.allclose(rotdeg, 0):
                                vals_x_extreme.append(np.linalg.norm(ft_wrench[ft_i][1:3]))
                            #print ft_wrench[ft_i][0] - tip_pos[0]
    
    # from mpl_toolkits.mplot3d import Axes3D
    # 
    # from latexify import latexify; latexify(scale = 2)
    # 
    # fig = plt.figure()
    # axes = fig.add_subplot(111, projection='3d')
    # #axes = plt.gca()
    # axes.grid(True, linewidth = 0.25, color='grey')
    # axes.set_axisbelow(True)
    # 
    # (x,y,z) = zip(*vals)
    # axes.scatter(x, y, z, c=z, marker='.')
    # 
# 
    # #plt.tight_layout()
    # axes.set_xlabel('force x')
    # axes.set_ylabel('force y')
    # axes.set_zlabel('moment')
        # 
    # #legend = plt.legend(loc='lower right', ncol = 4)
    # 
    # #legend.get_frame().set_linewidth(0.25)
    # plt.subplots_adjust(left=0.12, bottom=0.13, right=None, top=None,
                # wspace=None, hspace=None)
    # plt.savefig(figfname_png)
    # plt.savefig(figfname_pdf)
    # plt.show()
    
    
    
    # plot just 2d
    
    
    from latexify import latexify; latexify(scale = 1, fontsize = 14)
    fig = plt.figure()
    axes = plt.gca()
    
    ######
    from matplotlib.patches import Ellipse
    
    w = np.average(vals_x_extreme)*2
    h = np.average(vals_y_extreme)*2
    stdw = np.std(vals_x_extreme)*2
    stdh = np.std(vals_y_extreme)*2
    
    meane = Ellipse(xy=(0,0), width=w, height=h, angle=0, zorder=2)
    ue = Ellipse(xy=(0,0), width=w+stdw*2, height=h+stdh*2, angle=0, zorder=0)
    le = Ellipse(xy=(0,0), width=w-stdw*2, height=h-stdh*2, angle=0, zorder=1)
    
    axes.add_artist(ue)
    ue.set_alpha(0.2)
    ue.set_facecolor((0,0,0.5))
    ue.set_edgecolor('none')
    
    axes.add_artist(le)
    le.set_alpha(1)
    le.set_facecolor((1,1,1))
    le.set_edgecolor('none')
    
    axes.add_artist(meane)
    meane.set_alpha(1)
    meane.set_facecolor('none')
    ##########
    
    
    
    (x,y,z) = zip(*vals)
    plt.scatter(x, z, s=0.01, marker='x', c='k', zorder=3)
    axes.set_xlabel('$f_x$ (N)')
    # if opt.surface_id != 'plywood':
    axes.set_ylabel('$m$ (N $\cdot$ m)')
    # plt.tick_params(
    # axis='x',          # changes apply to the x-axis
    # which='both',      # both major and minor ticks are affected
    # bottom='off',      # ticks along the bottom edge are off
    # top='off'         # ticks along the top edge are off
    # )
    # plt.tick_params(
    # axis='y',          # changes apply to the x-axis
    # which='both',      # both major and minor ticks are affected
    # bottom='off',      # ticks along the bottom edge are off
    # top='off'         # ticks along the top edge are off
    # )
    
    plt.locator_params(axis='both',nbins=4)
    plt.subplots_adjust(left=0.23, bottom=0.24, right=None, top=None,
                wspace=None, hspace=None)
    
    # if opt.surface_id == 'plywood':
        # #axes.get_yaxis().set_visible(False)
        # for xlabel_i in axes.get_yticklabels():
            # xlabel_i.set_fontsize(0.0)
            # xlabel_i.set_visible(False)
            
    if opt.surface_id == 'pu':
        plt.axis([-20, 20, -1.5, 1.5])
    else:
        plt.axis([-5, 5, -0.2, 0.2])
    plt.savefig(figfname_png_2d, dpi = 300)
    plt.savefig(figfname_pdf_2d)
Exemple #10
0
        temp = []
        for snr in snr_random_streams:
            per_stream_SNR_random_streams.append(snr)
            mcs_id = lookup_mcs(snr)
            per_stream_mcs_random_streams.append(mcs_id)
            temp.append(lookup_rate(snr))
        variance = max(temp) - min(temp)
        per_stream_tput_random_streams.append(variance)
        tput_random_streams.append(R)
        no_of_streams_random_streams.append(len(d_values_random_streams))

print('Infeasible random = {}'.format(infeasible_random))
print('Infeasible norm = {}'.format(infeasible_norm))
print('Infeasible correlation based = {}'.format(infeasible_corr_users))

params = latexify(columns=2)
matplotlib.rcParams.update(params)

plt.figure()

tput_random = np.sort(tput_random)
F2 = np.array(range(len(tput_random))) / float(len(tput_random))
plt.plot(tput_random,
         F2,
         color='red',
         linestyle=':',
         linewidth=3,
         label='Random user selection \n(Two streams per user)')

tput_random_streams = np.sort(tput_random_streams)
F2 = np.array(range(len(tput_random_streams))) / float(
    except IOError:
        pass

    if maximize_window:
        fig_manager = plt.get_current_fig_manager()
        fig_manager.window.showMaximized()
    if save_fig:
        plt.savefig(fig_path + 'forces.pdf')

    # --------------------------------
    # Display the figure on the screen
    # --------------------------------
    plt.show()


# LaTeX Format
latexify.latexify()

# Paths for plotting
# paths = ['F:/friction_simulations/non_pbc/simulation_{0}/'.format(i) for i in range(0, 7)]
paths = ['F:/friction_simulations/pbc2/simulation_pbc_{0}/'.format(i) for i in range(1, 24)]
# paths = ['F:/friction_simulations/pbc3/simulation_pbc_{0}/'.format(i) for i in range(1,15)+range(16,20)]

plot_all(list_of_paths=paths,
         show_work=False,
         show_energy=False,
         show_positions=False,
         show_velocities=True,
         fig_path='F:/',
         save_fig=True)
def main(argv):
    parser = optparse.OptionParser()
    
    parser.add_option('', '--avgcolorbar', action="store", type='float', dest='avgcolorbar', 
                      help='Color bar', nargs=2, default=(None,None))
    parser.add_option('', '--res', action="store", type='float', dest='res', 
                      help='Resolution in deg', nargs=1, default=(5))
    parser.add_option('', '--rep', action="store", type='int', dest='rep', 
                      help='How many repetitions', nargs=1, default=(2))
    parser.add_option('', '--limits', action="store", type='float', dest='limits', 
                      help='Limits in meter', nargs=4, default=(0.250,0.450, -0.233, 0.197)) # [minx, maxx, miny, maxy]
    parser.add_option('', '--N', action="store", type='float', dest='N', 
                      help='Normal force', nargs=1, default=(0.8374 * 9.81)) # Normal force
                      
    (opt, args) = parser.parse_args()
    
    if len(args) < 1:  # no bagfile name
        parser.error("Usage: plot_friction_vs_vel.py [dir_to_friction_scan_iso]")
        return
    
    dir_to_friction_scan_iso = args[0]
    
    figfname_png = dir_to_friction_scan_iso + '/friction_maximal_dissipation_overmaterial.png'
    figfname_pdf = dir_to_friction_scan_iso + '/friction_maximal_dissipation_overmaterial.pdf'
    ft_wrench = []
    
    min_x, max_x, min_y, max_y = opt.limits
    
    center = [(max_x + min_x) /2, (max_y + min_y) /2 ]
    acc = 0
    
    # a list of materials
    #dirlist = [ name for name in os.listdir(dir_to_friction_scan_iso) if os.path.isdir(os.path.join(dir_to_friction_scan_iso, name)) ]
    
    dirlist = ['abs', 'delrin','plywood',  'pu']
    
    shape_id = 'rect1'
    vel = 20
    N = opt.N
    
    linestyles = [':', '-', '-', '-']
    markerstyles = ['', '', '^', 'o']
    markeverys = [1,1,3,3]
    rangex = xrange(0, 360, opt.res)
    raidus = 0.001
    
    from latexify import latexify; latexify(scale = 2, fig_height=1.5)
    axes = plt.gca()
    axes.grid(True, linewidth = 0.25, color='grey')
    axes.set_axisbelow(True)
    
    
    for inds, surface in enumerate(dirlist):
        print dir_to_friction_scan_iso, surface, shape_id
        
        avgs = []
        vel_vecs = []
        for deg in rangex:
            vals = []
            for rep in xrange(opt.rep):
                h5filename = 'record_surface=%s_shape=%s_a=%.0f_v=%.0f_deg=%d_rep=%03d.h5' % (surface, shape_id, acc*1000, vel, deg, rep)
                filepath = '%s/%s/%s/%s' % (dir_to_friction_scan_iso,surface,shape_id,h5filename)
                f = h5py.File(filepath, "r")
                tip_array = f['tip_array'].value
                ft_wrench = f['ft_wrench'].value
                
                scale = (len(ft_wrench)*1.0/len(tip_array))
                
                for i, tip_pos  in enumerate(tip_array):
                    if np.linalg.norm(np.array(tip_pos[1:3]) - np.array(center)) < raidus:
                        ft_i = int(i * scale)
                        vals.append(ft_wrench[ft_i][1:3])
            avgs.append(np.mean(vals, 0))
            
        # print  v * f - max(v * f*) >= 0
        diffs = []
        for i,deg in enumerate(rangex):
            th = np.deg2rad(deg)
            start_pos = [np.sin(th), np.cos(th)]
            end_pos = [np.sin(th+np.pi), np.cos(th+np.pi)]
            vel_vec = -(np.array(end_pos) - np.array(start_pos))
            
            force = avgs[i]
            #import pdb; pdb.set_trace()
            max_power = -np.inf
            for j,deg_p in enumerate(rangex):
                tmp_power = np.dot(vel_vec, avgs[j])
                if tmp_power > max_power:
                    max_power = tmp_power
                
            diffs.append(np.dot(vel_vec, force) - max_power)
            
        plt.errorbar(rangex, diffs, color='k',  fmt=linestyles[inds]+markerstyles[inds], 
         label=surface, markevery = markeverys[inds], markersize=5, linewidth=0.5)

    plt.tight_layout()
    axes.set_xlabel('sliding direction in angles (deg)')
    axes.set_ylabel('$\Delta P$ (m*N/s)')
        
    legend = plt.legend(loc='lower right', ncol = 4)
    
    legend.get_frame().set_linewidth(0.25)
    plt.subplots_adjust(left=0.12, bottom=0.19, right=None, top=None,
                wspace=None, hspace=None)
    plt.savefig(figfname_png)
    plt.savefig(figfname_pdf)
    plt.show()
def func_polyfit_derivative(x,y,deg):
    p=numpy.polyfit(x,y,deg)
    deg=len(p)-1
    def temp(x):
        out=0
        for i in range(len(p)-1):
            out=out + (deg-i)*p[i]*x**(deg-i-1)
        return out
    return temp

def toroidal_flux_derivative(a,kappa,dkappadrho,BT,dBTdr):
    return lambda r :numpy.pi*((1.0/a)*dkappadrho(r/a)*BT(r)*r**2+2*r*kappa(r/a)*BT(r)+dBTdr(r)*kappa(r/a)*r**2)


if __name__=='__main__':
    latexify()
    y=numpy.array([1.23,1.37,1.6])
    x=numpy.array([0,0.5,0.9])
    rho=numpy.linspace(0,1)
    deg=2
    kappa=func_polyfit(x,y,deg)
    #dkappadr=func_polyfit_derivative(x,y,deg)
    q=func_q(1.0,3.5,0.6,1.6)
    #q=func_q(4.0,4.0,0.6,4.0)
    fig = plt.figure()
    ax = fig.add_subplot(1,1,1)
    ax.set_ylim([0,4])
    plt.plot(rho,kappa(rho),'--')
    #plt.plot(rho,dkappadr(rho))
    
    ax.set_xlabel(r"$\rho=r/a$",fontsize=12)
def main(argv):
    parser = optparse.OptionParser()
    
    parser.add_option('', '--avgcolorbar', action="store", type='float', dest='avgcolorbar', 
                      help='Color bar', nargs=2, default=(None,None))
    parser.add_option('', '--res', action="store", type='float', dest='res', 
                      help='Resolution in meter', nargs=2, default=(0.005,0.005))
    parser.add_option('', '--limits', action="store", type='float', dest='limits', 
                      help='Limits in meter', nargs=4, default=(0.250,0.450, -0.233, 0.197)) # [minx, maxx, miny, maxy]
    parser.add_option('', '--N', action="store", type='float', dest='N', 
                      help='Normal force', nargs=1, default=(0.8374 * 9.81)) # Normal force
                      
    (opt, args) = parser.parse_args()
    
    if len(args) < 1:  # no bagfile name
        parser.error("Usage: plot_friction_vs_vel.py [dir_to_friction_scan_vels]")
        return
    
    friction_scan_vel_dir = args[0]
    
    figfname_png = friction_scan_vel_dir + '/friction_over_speed_overmaterial.png'
    figfname_pdf = friction_scan_vel_dir + '/friction_over_speed_overmaterial.pdf'
    ft_wrench = []
    
    min_x, max_x, min_y, max_y = opt.limits
    min_y += opt.res[1]*40   
    max_y -= opt.res[1]*40  
    
    # a list of materials
    #dirlist = [ name for name in os.listdir(friction_scan_vel_dir) if os.path.isdir(os.path.join(friction_scan_vel_dir, name)) ]
    
    dirlist = ['abs', 'delrin', 'plywood', 'pu']
    
    object_id = 'rect1'
    N = opt.N
    
    from latexify import latexify; latexify()
    linestyles = [':', '-', '-', '-']
    markerstyles = ['', '', '^', 'o']
    for inds, surface in enumerate(dirlist):
        print friction_scan_vel_dir, surface, object_id
        filelist = glob.glob("%s/%s/%s/*.h5" % (friction_scan_vel_dir, surface, object_id))
        rangex = []
        avgs = []
        stds = []
        for filepath in filelist:  #record_surface=delrin_shape=rect1_a=0_v=10_rep=000.h5
            v = int(os.path.basename(filepath).split('_')[4].split('=')[1])
            rangex.append(v)
            vals = []
            
            f = h5py.File(filepath, "r")
            tip_array = f['tip_array'].value
            ft_wrench = f['ft_wrench'].value
            scale = (len(ft_wrench)*1.0/len(tip_array))
            
            
            for i, tip_pos  in enumerate(tip_array):
                #print tip_pos
                #raw_input()
                if tip_pos[1] >= min_x and tip_pos[1] <= max_x and tip_pos[2] >= min_y and tip_pos[2] <= max_y:
                    ft_i = int(i * scale)
                    vals.append(np.fabs(ft_wrench[ft_i][2]))
            avgs.append(np.average(vals) / N)
            stds.append(np.std(vals) / N)

            print surface, ' vel=', v
            print 'average', '%.3f' % (np.average(vals) / N)
            print 'std', '%.3f' % (np.std(vals) / N)
            print 'max', '%.3f' % (np.max(vals) / N)
            print 'min', '%.3f' % (np.min(vals) / N)
            
        
        sorted_avgs = [y for (x,y) in sorted(zip(rangex,avgs))]
        sorted_stds = [y for (x,y) in sorted(zip(rangex,stds))]
        sorted_rangex = sorted(rangex)
        
        print sorted_avgs
        print sorted_stds
        print sorted_rangex
        
        #plt.errorbar(sorted_rangex, sorted_avgs, yerr=sorted_stds, color='k', fmt=linestyles[inds]+'o', label=surface)
        plt.errorbar(sorted_rangex, sorted_avgs, color='k', fmt=linestyles[inds]+markerstyles[inds], 
                     label=surface, markersize=3, linewidth=0.25)
        
    axes = plt.gca()
    axes.set_xlim([0, sorted_rangex[-1]+50])
    axes.set_ylim([0, 2])
    axes.set_xlabel('Speed (mm/s)')
    axes.set_ylabel('Coefficient of friction')
        
    legend = plt.legend(ncol=2, loc='upper left')
    legend.get_frame().set_linewidth(0.25)
    plt.tight_layout(pad=0.1)
    plt.savefig(figfname_png)
    plt.savefig(figfname_pdf)
    plt.close()
Exemple #15
0
import numpy as np
import matplotlib.pyplot as plt
from latexify import latexify
from matplotlib import patches

# Configuro latexify a dos columnas
latexify(columns=2, fontawesome=True, siunitx=True)

# Grafico
fig = plt.figure(figsize=(6.9,3))
ax1 = fig.add_subplot(111)
xmax = 2
ymax = xmax/((6.9/3))
ax1.set_xlim(0,xmax)
ax1.set_ylim(0,ymax)

ellipse = patches.Arc(xy=(1, 0.4),width=1.8, height=0.3, 
                        edgecolor='k', fc='w', lw=2,  theta1=0, theta2=360, ls=':',alpha=0.5, angle=5)
ax1.add_patch(ellipse)
ax1.text(1,0.4,s=r"\Huge\faIcon{globe-americas}",
         horizontalalignment='center',
         verticalalignment='center')
ax1.text(0.1,0.32,s=r"\huge\faIcon{satellite}",
         rotation=+45+90+5,
         horizontalalignment='center',
         verticalalignment='center')


ax1.annotate('', xy=(xmax/2+0.05, 0.1), 
                              xytext=(xmax/2+0.9, 0.1),
            arrowprops=dict(facecolor='black', arrowstyle="|-|"))
Exemple #16
0
def main(argv):
    parser = optparse.OptionParser()

    parser.add_option('',
                      '--res',
                      action="store",
                      type='float',
                      dest='res',
                      help='Resolution in deg',
                      nargs=1,
                      default=(5))
    parser.add_option('',
                      '--rep',
                      action="store",
                      type='int',
                      dest='rep',
                      help='How many repetitions',
                      nargs=1,
                      default=(1))
    parser.add_option('',
                      '--limits',
                      action="store",
                      type='float',
                      dest='limits',
                      help='Limits in meter',
                      nargs=4,
                      default=(0.250, 0.450, -0.233,
                               0.197))  # [minx, maxx, miny, maxy]
    parser.add_option('',
                      '--N',
                      action="store",
                      type='float',
                      dest='N',
                      help='Normal force',
                      nargs=1,
                      default=(0.8374 * 9.81))  # Normal force
    parser.add_option('',
                      '--surface',
                      action="store",
                      type='string',
                      dest='surface_id',
                      help='surface',
                      nargs=1,
                      default='plywood')  # Normal force

    (opt, args) = parser.parse_args()

    if len(args) < 1:  # no bagfile name
        parser.error(
            "Usage: plot_friction_limitsurface.py [dir_to_friction_scan_limitsurface]"
        )
        return

    dir_to_friction_scan_ls = args[0]

    figfname_png = dir_to_friction_scan_ls + '/friction_limitsurface_%s.png' % opt.surface_id
    figfname_pdf = dir_to_friction_scan_ls + '/friction_limitsurface_%s.pdf' % opt.surface_id
    figfname_png_2d = dir_to_friction_scan_ls + '/friction_limitsurface_%s_2d.png' % opt.surface_id
    figfname_pdf_2d = dir_to_friction_scan_ls + '/friction_limitsurface_%s_2d.pdf' % opt.surface_id
    ft_wrench = []

    min_x, max_x, min_y, max_y = opt.limits

    center = [(max_x + min_x) / 2, (max_y + min_y) / 2]
    acc = 0

    # a list of materials
    #dirlist = [ name for name in os.listdir(dir_to_friction_scan_iso) if os.path.isdir(os.path.join(dir_to_friction_scan_iso, name)) ]

    #dirlist = ['abs', 'delrin','plywood',  'pu']

    shape_id = 'rect1'
    vel = 20
    N = opt.N

    linestyles = [':', '-', '-', '-']
    markerstyles = ['', '', '^', 'o']
    markeverys = [1, 1, 3, 3]
    rangex = xrange(0, 360, opt.res)
    thres = 0.001
    degs_default = xrange(0, 360, 5)
    rep = 0
    radii = [0, 0.0125, 0.025, 0.05]
    rotdegs_default = np.linspace(-80, 80, 21)

    #hack
    degs_default = [0, 180]
    #radii = [0, 0.05]
    #rotdegs_default = np.linspace(-64, 64, 17)

    vals = []
    vals_y_extreme = []
    vals_x_extreme = []
    for radius in radii:
        if radius == 0:
            degs = [0]
        else:
            degs = degs_default
        for deg in degs:  # translation velocity direction
            th = np.deg2rad(deg)

            if radius == 0:
                rotdegs = [80, -80]
            elif deg in [0, 90, 180, 270]:
                rotdegs = np.linspace(-88, 88, 45)
            else:
                rotdegs = rotdegs_default

            for rotdeg in rotdegs:  # rotation velocity direction
                rotth = np.deg2rad(deg)
                start_ori = ik.helper.qwxyz_from_qxyzw(
                    tfm.quaternion_from_matrix(
                        (np.dot(tfm.euler_matrix(0, np.pi, 0),
                                tfm.euler_matrix(0, 0, rotth)))))
                end_ori = ik.helper.qwxyz_from_qxyzw(
                    tfm.quaternion_from_matrix(
                        (np.dot(tfm.euler_matrix(0, np.pi, 0),
                                tfm.euler_matrix(0, 0, -rotth)))))
                start_pos = [
                    np.cos(th) * radius + center[0],
                    np.sin(th) * radius + center[1]
                ]
                end_pos = [
                    np.cos(th + np.pi) * radius + center[0],
                    np.sin(th + np.pi) * radius + center[1]
                ]

                vel_direc = [
                    np.array(end_pos) - np.array(start_pos), 2 * rotth
                ]

                h5filename = 'record_surface=%s_shape=%s_a=%.0f_v=%.0f_deg=%d_rotdeg=%d_radius=%.3f_rep=%03d.h5' % (
                    opt.surface_id, shape_id, acc * 1000, vel, deg, rotdeg,
                    radius, rep)

                filepath = '%s/%s/%s/%s' % (dir_to_friction_scan_ls,
                                            opt.surface_id, shape_id,
                                            h5filename)
                print 'processing', filepath
                if not os.path.isfile(filepath):
                    print 'not exists'
                    break

                f = h5py.File(filepath, "r")
                tip_array = f['tip_pose'].value
                ft_wrench = f['ft_wrench'].value
                f.close()

                scale = (len(ft_wrench) * 1.0 / len(tip_array))

                for i, tip_pos in enumerate(tip_array):
                    if radius == 0:  # use the center part only
                        if np.linalg.norm(np.array(tip_pos[3]) -
                                          np.array(0)) < np.deg2rad(1):
                            ft_i = int(i * scale)
                            vals.append(
                                list(ft_wrench[ft_i][1:3]) +
                                list([ft_wrench[ft_i][3]
                                      ]))  # force x y and torque in z
                            vals_y_extreme.append(np.abs(ft_wrench[ft_i][3]))
                    else:
                        if np.linalg.norm(
                                np.array(tip_pos[1:3]) -
                                np.array(center)) < thres and np.linalg.norm(
                                    np.array(tip_pos[3]) -
                                    np.array(0)) < np.deg2rad(1):
                            ft_i = int(i * scale)
                            vals.append(
                                list(ft_wrench[ft_i][1:3]) +
                                list([ft_wrench[ft_i][3]
                                      ]))  # force x y and torque in z
                            if np.allclose(rotdeg, 0):
                                vals_x_extreme.append(
                                    np.linalg.norm(ft_wrench[ft_i][1:3]))
                            #print ft_wrench[ft_i][0] - tip_pos[0]

    # from mpl_toolkits.mplot3d import Axes3D
    #
    # from latexify import latexify; latexify(scale = 2)
    #
    # fig = plt.figure()
    # axes = fig.add_subplot(111, projection='3d')
    # #axes = plt.gca()
    # axes.grid(True, linewidth = 0.25, color='grey')
    # axes.set_axisbelow(True)
    #
    # (x,y,z) = zip(*vals)
    # axes.scatter(x, y, z, c=z, marker='.')
    #


#
# #plt.tight_layout()
# axes.set_xlabel('force x')
# axes.set_ylabel('force y')
# axes.set_zlabel('moment')
#
# #legend = plt.legend(loc='lower right', ncol = 4)
#
# #legend.get_frame().set_linewidth(0.25)
# plt.subplots_adjust(left=0.12, bottom=0.13, right=None, top=None,
# wspace=None, hspace=None)
# plt.savefig(figfname_png)
# plt.savefig(figfname_pdf)
# plt.show()

# plot just 2d

    from latexify import latexify
    latexify(scale=1, fontsize=14)
    fig = plt.figure()
    axes = plt.gca()

    ######
    from matplotlib.patches import Ellipse

    w = np.average(vals_x_extreme) * 2
    h = np.average(vals_y_extreme) * 2
    stdw = np.std(vals_x_extreme) * 2
    stdh = np.std(vals_y_extreme) * 2

    meane = Ellipse(xy=(0, 0), width=w, height=h, angle=0, zorder=2)
    ue = Ellipse(xy=(0, 0),
                 width=w + stdw * 2,
                 height=h + stdh * 2,
                 angle=0,
                 zorder=0)
    le = Ellipse(xy=(0, 0),
                 width=w - stdw * 2,
                 height=h - stdh * 2,
                 angle=0,
                 zorder=1)

    axes.add_artist(ue)
    ue.set_alpha(0.2)
    ue.set_facecolor((0, 0, 0.5))
    ue.set_edgecolor('none')

    axes.add_artist(le)
    le.set_alpha(1)
    le.set_facecolor((1, 1, 1))
    le.set_edgecolor('none')

    axes.add_artist(meane)
    meane.set_alpha(1)
    meane.set_facecolor('none')
    ##########

    (x, y, z) = zip(*vals)
    plt.scatter(x, z, s=0.01, marker='x', c='k', zorder=3)
    axes.set_xlabel('$f_x$ (N)')
    # if opt.surface_id != 'plywood':
    axes.set_ylabel('$m$ (N $\cdot$ m)')
    # plt.tick_params(
    # axis='x',          # changes apply to the x-axis
    # which='both',      # both major and minor ticks are affected
    # bottom='off',      # ticks along the bottom edge are off
    # top='off'         # ticks along the top edge are off
    # )
    # plt.tick_params(
    # axis='y',          # changes apply to the x-axis
    # which='both',      # both major and minor ticks are affected
    # bottom='off',      # ticks along the bottom edge are off
    # top='off'         # ticks along the top edge are off
    # )

    plt.locator_params(axis='both', nbins=4)
    plt.subplots_adjust(left=0.23,
                        bottom=0.24,
                        right=None,
                        top=None,
                        wspace=None,
                        hspace=None)

    # if opt.surface_id == 'plywood':
    # #axes.get_yaxis().set_visible(False)
    # for xlabel_i in axes.get_yticklabels():
    # xlabel_i.set_fontsize(0.0)
    # xlabel_i.set_visible(False)

    if opt.surface_id == 'pu':
        plt.axis([-20, 20, -1.5, 1.5])
    else:
        plt.axis([-5, 5, -0.2, 0.2])
    plt.savefig(figfname_png_2d, dpi=300)
    plt.savefig(figfname_pdf_2d)
def main(argv):
    parser = optparse.OptionParser()
    
    parser.add_option('-s', action="store", dest='shape_id', 
                      help='The shape id e.g. rect1-rect3', default='rect1')
                      
    parser.add_option('', '--surface', action="store", dest='surface_id', 
                      help='The surface id e.g. plywood, abs', default='plywood')
                      
    parser.add_option('', '--nrep', action="store", dest='nrep', type='int',
                      help='Repeat how many times', 
                      default=2000)  
    parser.add_option('', '--reptype', action="store", dest='reptype', type='string',
                      help='Repeat type', 
                      default='normal')  
    
    (opt, args) = parser.parse_args()
    
    if len(args) < 1:  # no bagfile name
        parser.error("Usage: plot_rep_pushes.py [dir_to_rep_push] e.g. /home/mcube/pnpushdata/straight_push_rep")  
        return
    dir_to_rep_push = args[0]
    
    vel = 20
    acc = 0
    i = 0
    s = 0.7
    t = 0
    
    figfname_png = dir_to_rep_push + '/rep_push_viz_%s.png' % opt.surface_id
    figfname_pdf = dir_to_rep_push + '/rep_push_viz_%s.pdf' % opt.surface_id
    figfname_2_png = dir_to_rep_push + '/rep_push_viz_2_%s.png' % opt.surface_id
    figfname_2_pdf = dir_to_rep_push + '/rep_push_viz_2_%s.pdf' % opt.surface_id
    
    figfname_hist_png = dir_to_rep_push + '/rep_push_viz_hist_%s.png' % opt.surface_id
    figfname_hist_pdf = dir_to_rep_push + '/rep_push_viz_hist_%s.pdf' % opt.surface_id
    
    cachefile = '/tmp/plot_rep_push_%s' % opt.surface_id
    import shelve
    if os.path.exists(cachefile):
        f = shelve.open(cachefile)
        vals = f['vals'];
        #trajs = f['trajs'];
        #fts = f['fts']
        opt = f['opt']
        #trajs_tippose = f['trajs_tippose']
        meantraj = f['meantraj']
        meantraj_tippose = f['meantraj_tippose']
    else:
        vals = [] # delta between start and end
        trajs = []
        trajs_tippose = []
        fts = []
        for rep in xrange(opt.nrep):
            print rep
            h5filename = 'motion_surface=%s_shape=%s_a=%.0f_v=%.0f_i=%.3f_s=%.3f_t=%.3f_rep=%04d.h5' % (opt.surface_id, opt.shape_id, acc*1000, vel, i, s, t, rep)
            
            #filename = 'motion_surface=%s_shape=%s_a=%.0f_v=%.0f_i=%.3f_s=%.3f_t=%.3f_rep=%04d.bag' % (opt.surface_id, opt.shape_id, acc*1000, speeds[cnt_acc], i, s, t, rep)
            filepath = '%s/%s/%s/%s/%s' % (dir_to_rep_push,opt.surface_id,opt.shape_id,opt.reptype,h5filename)
            if not os.path.isfile(filepath):
                print 'not exists', filepath
                continue
            
            f = h5py.File(filepath, "r")
            ft_array = f['ft_wrench'].value
            object_pose = f['object_pose'].value
            tip_pose = f['tip_pose'].value
            f.close()
            
            invT0 = np.linalg.inv(matrix_from_xyzrpy(object_pose[0][1:3].tolist() + [0], [0,0,object_pose[0][3]]))
            
            T = matrix_from_xyzrpy(object_pose[-1][1:3].tolist() + [0], [0,0,object_pose[-1][3]])
            T_T0 = np.dot(invT0, T)
            scale, shear, angles, trans, persp = tfm.decompose_matrix(T_T0)
            vals.append(np.append(trans[0:2] ,np.unwrap([angles[2]])))
            
            # extract traj
            #if rep in xrange(500):
            if True:
                traj = []
                for p in object_pose:
                    T = matrix_from_xyzrpy(p[1:3].tolist() + [0], [0,0,p[3]])
                    T_T0 = np.dot(invT0, T)
                    scale, shear, angles, trans, persp = tfm.decompose_matrix(T_T0)
                    traj.append(np.append([p[0]-object_pose[0][0]], np.append(trans[0:2] , np.unwrap([angles[2]]))) )
                trajs.append(traj)
                
                traj_tippose = []
                for tip_pose_ in tip_pose:
                    traj_tippose.append(np.append([tip_pose_[0]-tip_pose[0][0]], np.dot(invT0, tip_pose_[1:3].tolist()+[0,1])))
                trajs_tippose.append(traj_tippose)
            
    
        def computeMeanTraj(trajs):
            lenn = 1000000
            for traj in trajs:
                lenn = min(lenn, len(traj))
            
            ncol = len(trajs[0][0])
            meantraj = np.zeros((lenn, ncol))
            ntraj = len(trajs)
            for traj in trajs:
                meantraj = meantraj + np.array(traj[0:lenn]) / ntraj
                
            return meantraj
            
        meantraj = computeMeanTraj(trajs)
        meantraj_tippose = computeMeanTraj(trajs_tippose)
        
        
        ll = locals()
        shv = shelve.open(cachefile, 'n')
        for key, val in ll.iteritems():
            try:
                shv[key] = val
            except:
                pass
        shv.close()
    
    (x,y,th)=zip(*(vals))
    
    valscov = np.cov(vals, rowvar=0)
    valsmean = np.mean(vals, axis=0)
    print 'covariance\n', valscov
    print 'mean', valsmean
    print 'mean', valsmean[0:2] * 1000, 'mm', np.rad2deg(valsmean[2]), 'deg'
    eigvs,eigvec = eigsorted(valscov[0:2][:,0:2])
    print 'error_trans:', np.sqrt(eigvs[0] + eigvs[1]) *1000 , 'mm'
    print 'error_percent_trans:', np.sqrt(eigvs[0] + eigvs[1]) / np.sqrt(valsmean[0]**2+ valsmean[1]**2) *100 , '%'
    print 'error_rot:', np.rad2deg(np.sqrt(valscov[2][2])), 'deg'
    print 'error_percent_rot:', np.sqrt(valscov[2][2]) / np.sqrt(valsmean[2]**2) *100 , '%'
    
    #from latexify import latexify; latexify(fig_width=3.39, fig_height=3.39*(sqrt(5)-1.0)/2.0*2,scale = 2)
    from latexify import latexify; latexify(scale = 2)
    

    #### add the object as polygon
    shape_db = ShapeDB()
    shape = shape_db.shape_db[opt.shape_id]['shape'] # shape of the objects presented as polygon.
    shape_type = shape_db.shape_db[opt.shape_id]['shape_type']
    if shape_type == 'poly':
        shape_polygon_3d = np.hstack((np.array(shape), np.zeros((len(shape), 1)), np.ones((len(shape), 1))))
    elif shape_type == 'ellip':
        shape = shape[0]
    elif shape_type == 'polyapprox':
        shape_polygon_3d = np.hstack((np.array(shape[0]), np.zeros((len(shape[0]), 1)), np.ones((len(shape[0]), 1))))
        
    
    part1 = False
    if part1:
        f1, ((ax1, ax2)) = plt.subplots(1, 2, sharex=True, sharey=True)
        #fig = plt.figure()
        plt.sca(ax1)
        ax = ax1
        (tm, x,y,th) = zip(*meantraj)
        line = plt.plot(x, y, '-k')
        plt.setp(line, linewidth=2)
        
        
        ec, fc = 'black','orangered'
        for ii in np.linspace(0, len(meantraj)-1, 30):
            i = int(ii)
            
            if i == 0:
                alpha , fill = (0.3, True)
            elif i == len(meantraj)-1:
                alpha , fill = (0.6, True)
            else:
                alpha , fill = (0.6, False)
                
            T = matrix_from_xyzrpy([x[i], y[i], 0], [0, 0, th[i]])
            shape_polygon_3d_world = np.dot(T, shape_polygon_3d.T)
            obj = mpatches.Polygon(shape_polygon_3d_world.T[:,0:2], closed=True, fc=fc, ec=ec, alpha=alpha, fill=fill, linewidth=1, linestyle='solid')
            
            ax.add_patch(obj)
        #####
        
        ###add the probes as circle
        probe_radius = 0.00475
        for ind, ii in enumerate(np.linspace(0, len(meantraj_tippose)-1, 30)):
            i = int(ii)
            if opt.surface_id == 'abs' and ind < 4:   # hack
                continue
            if i == 0:
                alpha , fill = (0.8, False)
            elif i == len(meantraj_tippose)-1:
                alpha , fill = (0.8, False)
            else:
                alpha , fill = (0.8, False)
            circle = mpatches.Circle(meantraj_tippose[i][1:3], probe_radius, color='black', alpha=alpha, fill=fill, linewidth=1, linestyle='solid')
                
            ax.add_patch(circle)
        
        
        plt.axis('equal') 
        plt.axis('off')
        
        # ##2. plot all traj
        ax = ax2
        plt.sca(ax)
        
        for traj in trajs:
            (tm, x,y,th) = zip(*traj)
            plt.plot(x, y, 'g', alpha=0.5)
            
          # ##plot begin and final mean block
        (tm,x,y,th) = zip(*meantraj)
        for i in [0, -1]:
            alpha , fill = (0.6, False)
            T = matrix_from_xyzrpy([x[i], y[i], 0], [0, 0, th[i]])
            shape_polygon_3d_world = np.dot(T, shape_polygon_3d.T)
            obj = mpatches.Polygon(shape_polygon_3d_world.T[:,0:2], closed=True, fc=fc, ec=ec, alpha=alpha, fill=fill, linewidth=1, linestyle='solid',  zorder=2)
            ax.add_patch(obj)
        
        line = plt.plot(x, y, '-k')
        plt.setp(line, linewidth=2)
        
        plot_cov_ellipse(valscov[0:2][:,0:2], valsmean[0:2], color='orangered', fill=True, alpha=0.9,  zorder=3)
        #import pdb; pdb.set_trace()
        #plot_cov_ellipse(valscov[0:2][:,0:2], meantraj[-1][1:3], color='orangered', fill=True, alpha=0.9,  zorder=3)
        plt.axis('equal') 
        plt.axis('off')
        
        plt.savefig(figfname_png, dpi=200)
        plt.savefig(figfname_pdf)
    
    
    ## 3. plot final poses
    f2, ((ax3, ax4)) = plt.subplots(1, 2, sharex=False, sharey=False)
    
    ax = ax3
    plt.sca(ax)
    (xd,yd,thd)=zip(*(vals))
    ax.scatter(xd,yd, s=0.2, color='k', alpha=1)
    
    ###   plot begin and final mean block
    ec, fc = 'black','orangered'
    (tm,x,y,th) = zip(*meantraj)
    for i in [0,-1]:
        alpha , fill = (0.6, False)
        T = matrix_from_xyzrpy([x[i], y[i], 0], [0, 0, th[i]])
        shape_polygon_3d_world = np.dot(T, shape_polygon_3d.T)
        #obj = mpatches.Polygon(shape_polygon_3d_world.T[:,0:2], closed=True, fc=fc, ec=ec, alpha=alpha, fill=fill, linewidth=1, linestyle='solid')
        #ax.add_patch(obj)
    
    ### plot 2 sigma bound
    
    plot_cov_ellipse(valscov[0:2][:,0:2], valsmean[0:2], color='orangered', fill=True, alpha=0.9,  zorder=0)
    ##plot_cov_ellipse(valscov[0:2][:,0:2], valsmean[0:2], 3, color='orangered', fill=True, alpha=0.5,  zorder=0)
    ##ax.add_patch(obj)
        
    ax.set_ylim([0,1000])
    plt.axis('equal') 
    plt.axis('off')
    ##ax2.set_title('Scatter plot: $\Delta x$ versus $\Delta y$')
        
    plt.tight_layout(pad=0, w_pad=0, h_pad=0)
    plt.subplots_adjust(left=0.08, bottom=0.06, right=0.97, top=1.0,
                wspace=0.01, hspace=0.20)
                
    
    ax = ax4
    plt.sca(ax)
    ##   plot begin and final mean block
    (tm,x,y,th) = zip(*meantraj)
    for i in [0,1]:
        alpha , fill = (0.6, False)
        T = matrix_from_xyzrpy([x[i], y[i], 0], [0, 0, th[i]])
        shape_polygon_3d_world = np.dot(T, shape_polygon_3d.T)
        obj = mpatches.Polygon(shape_polygon_3d_world.T[:,0:2], closed=True, fc=fc, ec=ec, alpha=alpha, fill=fill, linewidth=1, linestyle='solid',  zorder=2)
        ax.add_patch(obj)
    
    line = plt.plot(x, y, '-k')
    plt.setp(line, linewidth=2)
    
    ## plot simulated data
    (x_sim,y_sim,th_sim) = zip(*get_sim_data())
    line_sim = plt.plot(x_sim, y_sim, '--k')
    plt.setp(line_sim, linewidth=2)
    
    T = matrix_from_xyzrpy([x_sim[-1], y_sim[-1], 0], [0, 0, th_sim[-1]])
    shape_polygon_3d_world = np.dot(T, shape_polygon_3d.T)
    obj = mpatches.Polygon(shape_polygon_3d_world.T[:,0:2], closed=True, fc=fc, ec=ec, alpha=alpha, fill=fill, linewidth=1, linestyle='dashed',  zorder=2)
    ax.add_patch(obj)
    ####
    
    #ax.set_ylim([-0.3,0.05])
    plt.axis('equal') 
    plt.axis('off')
    plt.tight_layout(pad=0, w_pad=0, h_pad=0)
    
    # ax.set_xlim([-0.2,0.2])
    # ax.set_ylim([-0.3,0.05])
    plt.savefig(figfname_2_png, dpi=200)
    plt.savefig(figfname_2_pdf)
    plt.show()
    
    #  5-7 plot histogram
    
    f3, ((ax5, ax6, ax7)) = plt.subplots(1, 3, sharex=False, sharey=False)
    plt.sca(ax5)
    plt.locator_params(axis='x',nbins=4)
    n, bins, patches= ax5.hist(np.array(xd)*1000, 200, normed=1, histtype='stepfilled', 
         facecolor='none', label='x', alpha=1)
    ax5.get_yaxis().set_visible(False)
    ax5.set_xlabel('$\Delta x$ (mm)')
    #ax5.set_title('Histogram of $\Delta x$')
    
    plt.sca(ax6)
    plt.locator_params(axis='x',nbins=4)
    n, bins, patches= ax6.hist(np.array(yd)*1000, 200, normed=1, histtype='stepfilled', 
         facecolor='none', label='y', alpha=1)
    ax6.get_yaxis().set_visible(False)
    ax6.set_xlabel('$\Delta y$ (mm)')
    #ax6.set_title('Histogram of $\Delta y$')
    
    plt.sca(ax7)
    plt.locator_params(axis='x',nbins=4)
    n, bins, patches= ax7.hist(np.rad2deg(thd), 200, normed=1, histtype='stepfilled', 
         facecolor='none', label='theta', alpha=1)
    ax7.get_yaxis().set_visible(False)
    ax7.set_xlabel('$\Delta \\theta$ (degree)')
    #ax7.set_title('Histogram of $\Delta \\theta$')
        
    plt.tight_layout(pad=0, w_pad=0, h_pad=0)
    plt.subplots_adjust(left=0.04, bottom=0.23, right=0.96, top=0.87,
                wspace=0.22, hspace=0.20)
    plt.savefig(figfname_hist_png, dpi=200)
    plt.savefig(figfname_hist_pdf)
    plt.show()
def main(argv):
    parser = optparse.OptionParser()

    parser.add_option('',
                      '--avgcolorbar',
                      action="store",
                      type='float',
                      dest='avgcolorbar',
                      help='Color bar',
                      nargs=2,
                      default=(None, None))
    parser.add_option('',
                      '--res',
                      action="store",
                      type='float',
                      dest='res',
                      help='Resolution in meter',
                      nargs=2,
                      default=(0.005, 0.005))
    parser.add_option('',
                      '--limits',
                      action="store",
                      type='float',
                      dest='limits',
                      help='Limits in meter',
                      nargs=4,
                      default=(0.250, 0.450, -0.233,
                               0.197))  # [minx, maxx, miny, maxy]
    parser.add_option('',
                      '--N',
                      action="store",
                      type='float',
                      dest='N',
                      help='Normal force',
                      nargs=1,
                      default=(0.8374 * 9.81))  # Normal force

    (opt, args) = parser.parse_args()

    if len(args) < 1:  # no bagfile name
        parser.error(
            "Usage: plot_friction_vs_vel.py [dir_to_friction_scan_vels]")
        return

    friction_scan_vel_dir = args[0]

    figfname_png = friction_scan_vel_dir + '/friction_over_speed_overmaterial.png'
    figfname_pdf = friction_scan_vel_dir + '/friction_over_speed_overmaterial.pdf'
    ft_wrench = []

    min_x, max_x, min_y, max_y = opt.limits
    min_y += opt.res[1] * 40
    max_y -= opt.res[1] * 40

    # a list of materials
    #dirlist = [ name for name in os.listdir(friction_scan_vel_dir) if os.path.isdir(os.path.join(friction_scan_vel_dir, name)) ]

    dirlist = ['abs', 'delrin', 'plywood', 'pu']

    object_id = 'rect1'
    N = opt.N

    from latexify import latexify
    latexify()
    linestyles = [':', '-', '-', '-']
    markerstyles = ['', '', '^', 'o']
    for inds, surface in enumerate(dirlist):
        print friction_scan_vel_dir, surface, object_id
        filelist = glob.glob("%s/%s/%s/*.h5" %
                             (friction_scan_vel_dir, surface, object_id))
        rangex = []
        avgs = []
        stds = []
        for filepath in filelist:  #record_surface=delrin_shape=rect1_a=0_v=10_rep=000.h5
            v = int(os.path.basename(filepath).split('_')[4].split('=')[1])
            rangex.append(v)
            vals = []

            f = h5py.File(filepath, "r")
            tip_array = f['tip_array'].value
            ft_wrench = f['ft_wrench'].value
            scale = (len(ft_wrench) * 1.0 / len(tip_array))

            for i, tip_pos in enumerate(tip_array):
                #print tip_pos
                #raw_input()
                if tip_pos[1] >= min_x and tip_pos[1] <= max_x and tip_pos[
                        2] >= min_y and tip_pos[2] <= max_y:
                    ft_i = int(i * scale)
                    vals.append(np.fabs(ft_wrench[ft_i][2]))
            avgs.append(np.average(vals) / N)
            stds.append(np.std(vals) / N)

            print surface, ' vel=', v
            print 'average', '%.3f' % (np.average(vals) / N)
            print 'std', '%.3f' % (np.std(vals) / N)
            print 'max', '%.3f' % (np.max(vals) / N)
            print 'min', '%.3f' % (np.min(vals) / N)

        sorted_avgs = [y for (x, y) in sorted(zip(rangex, avgs))]
        sorted_stds = [y for (x, y) in sorted(zip(rangex, stds))]
        sorted_rangex = sorted(rangex)

        print sorted_avgs
        print sorted_stds
        print sorted_rangex

        #plt.errorbar(sorted_rangex, sorted_avgs, yerr=sorted_stds, color='k', fmt=linestyles[inds]+'o', label=surface)
        plt.errorbar(sorted_rangex,
                     sorted_avgs,
                     color='k',
                     fmt=linestyles[inds] + markerstyles[inds],
                     label=surface,
                     markersize=3,
                     linewidth=0.25)

    axes = plt.gca()
    axes.set_xlim([0, sorted_rangex[-1] + 50])
    axes.set_ylim([0, 2])
    axes.set_xlabel('Speed (mm/s)')
    axes.set_ylabel('Coefficient of friction')

    legend = plt.legend(ncol=2, loc='upper left')
    legend.get_frame().set_linewidth(0.25)
    plt.tight_layout(pad=0.1)
    plt.savefig(figfname_png)
    plt.savefig(figfname_pdf)
    plt.close()
def main(argv):
    
    parser = optparse.OptionParser()
    
    parser.add_option('', '--avgcolorbar', action="store", type='float', dest='avgcolorbar', 
                      help='Color bar', nargs=2, default=(None,None))
    parser.add_option('', '--res', action="store", type='float', dest='res', 
                      help='Resolution in meter', nargs=2, default=(0.005,0.005))
    parser.add_option('', '--limits', action="store", type='float', dest='limits', 
                      help='Limits [minx, maxx, miny, maxy]', nargs=4, default=(0.250,0.450, -0.233, 0.197)) 
    parser.add_option('', '--N', action="store", type='float', dest='N', 
                      help='Normal force', nargs=1, default=(0.8374 * 9.81)) 
                      
    parser.add_option('', '--title', action="store", type='string', dest='title', 
                      help='Title', default='')
    parser.add_option('', '--dirpath', action="store", type='string', dest='dirpath', 
                      help='Dirpath', default='./')
                      
    (opt, args) = parser.parse_args()
    
    cachefile = '/tmp/plot_friction_map_fine_overmaterial'
    import shelve
    if os.path.exists(cachefile):
        f = shelve.open(cachefile)
        ss = f['ss'];
        ncol = f['ncol'];
        all_valss = f['all_valss']
        image_avgs = f['image_avgs']
        image_range = f['image_range']
        image_ranges = f['image_ranges']
        opt = f['opt']
        rangex = f['rangex']
        rangey = f['rangey']
    else:
        ss = ['abs', 'delrin', 'plywood', 'pu']
        ncol = 2
        all_valss = []
        image_avgs = []
        image_range = [100, -100]
        image_ranges = []
        
        for i,s in enumerate(ss):
            hdf5_filepath = '%s/%s/rect1/record_surface=%s_shape=rect1_a=0_v=20_rep=000.h5' % (opt.dirpath, s, s)
            (all_vals, image_avg, (minn, maxx), (rangex, rangey)) = extract(opt, hdf5_filepath)
            all_valss.append(all_vals)
            image_avgs.append(image_avg)
            image_ranges.append([minn, maxx])
            if minn < image_range[0]:
                image_range[0] = minn
            if maxx > image_range[1]:
                image_range[1] = maxx
                
        ll = locals()
        f = shelve.open(cachefile, 'n')
        for key, val in ll.iteritems():
            try:
                f[key] = val
            except:
                pass
    
    
    figfname_png = opt.dirpath + '/friction_over_location_map.png'
    figfname_pdf = opt.dirpath + '/friction_over_location_map.pdf'
    figfname_hist_png = opt.dirpath + '/friction_over_location_hist.png'
    figfname_hist_pdf = opt.dirpath + '/friction_over_location_hist.pdf'
    
    # plot the distribution
    
    #plt.rc('text', usetex=True)
    #fig = plt.figure(figsize=(8,4))
    #plt.rc('font', family='serif', size=15, serif=['Times'])
    latexify(scale = 2)
    #fig, ax = plt.subplots()
    ax = plt.gca()
    bins = np.linspace(0, 0.6, 500)
    colors = ['r', 'b', 'g', 'k']
    
    linestyles = [':', '-', '-.', '--']
    markerstyles = ['', '', '', '']
    
    legend_handles = []
    for i, s in enumerate(ss):
        print s
        #plt.hist(np.array(all_vals)/opt.N, bins, normed=1, histtype='stepfilled', facecolor='white', alpha=0.75)
        n, bins, patches= ax.hist(np.array(all_valss[i])/opt.N, bins, normed=1, histtype='stepfilled', 
                 facecolor='none', edgecolor=colors[i], label=s, alpha=0)
        
        #import pdb; pdb.set_trace()
        print 'mean:', np.mean(all_valss[i])/opt.N
        print 'std:', np.std(all_valss[i])/opt.N
        print 'std (%):', np.std(all_valss[i])/ np.mean(all_valss[i]) * 100
        
        bincenters = 0.5*(bins[1:]+bins[:-1])
        # add a 'best fit' line for the normal PDF
        #y = mlab.normpdf( bincenters, mu, sigma)
        #import pdb; pdb.set_trace()
        l, = ax.plot(bincenters, n, linestyles[i]+markerstyles[i], linewidth=2, markevery=20, label=s,
                     color=colors[i], markersize=4, markerfacecolor='white')
        # do legend
        #line = mlines.Line2D([], [], color=colors[i], label=s)
        legend_handles.append(l)
        
    #plt.xticks(np.linspace(0, 0.6, 3))
    #plt.yticks(np.linspace(0, 25, 3))
    plt.ylabel('Probability')
    plt.xlabel('Coefficient of friction')
    legend = ax.legend(legend_handles, ss)
    legend.get_frame().set_linewidth(0.25)

    
    ax.yaxis.set_visible(True)
    plt.tight_layout(pad=0.4)
    
    plt.savefig(figfname_hist_png)
    plt.savefig(figfname_hist_pdf)
    #plt.show()
    plt.close()
    
    
    latexify(scale = 1)
    fig, axes = plt.subplots((len(ss)+ncol-1)/ncol , ncol)
    #plt.rc('font', family='serif', size=15)
    
    ims = []
    for i, s in enumerate(ss):
        
        im = axes.flat[i].imshow(image_avgs[i], extent=(rangey[0], rangey[-1]+opt.res[1], rangex[-1]+opt.res[0], rangex[0]),
                             interpolation='nearest', cmap=cm.Greys, vmin=image_ranges[i][0], vmax=image_ranges[i][1])

        divider = make_axes_locatable(axes.flat[i])
        cax = divider.append_axes("bottom", size="5%", pad=0.05)

        cbar = plt.colorbar(im, cax=cax, orientation='horizontal', ticks=image_ranges[i])
        cbar.ax.set_xticklabels([('%.2f' % image_ranges[i][0]), ('%.2f' % image_ranges[i][1])])
        
        
        axes.flat[i].xaxis.set_visible(False)
        axes.flat[i].yaxis.set_visible(False)
        axes.flat[i].set_title(s)
        
    #plt.legend()
    
    # fig.subplots_adjust(left=0, bottom=0, right=1, top=0.95,
                    # wspace=0.18, hspace=0.17)
    plt.tight_layout(pad=0.4, w_pad=0, h_pad=1.0)
    # fig.subplots_adjust(left=0.02, bottom=None, right=0.98, top=None,
                    # wspace=0.08, hspace=None)
                    
    #plt.tight_layout()
    plt.savefig(figfname_png, dpi=300)
    plt.savefig(figfname_pdf, dpi=300)
    
    print figfname_png
    #plt.show()
    
    plt.close()
Exemple #20
0
###############################################################################

# Creates all the tickets based on the values in the dictionaries 
# in values
i = 0
for line in ticketFile.readlines():
     if len(line) > 1:
          ticket = line.replace("\n", "")
          ticketIDs.append(ticket)
          doTicket(ticket, values[i % len(values)])
          i += 1

# Inserts all the images into the loaded latex template
for line in latexTemplate.readlines():
     if line == "<REPLACE>\n":
          outputFile.write(latexify(ticketIDs))
     else:
          outputFile.write(line)




print ""
print "Finished creating " + str(i) + " ticket images"
print ""
###############################################################################
# Cleanup
###############################################################################
yamlFile.close()
ticketFile.close()
latexTemplate.close()
def main(argv):
    parser = optparse.OptionParser()
    
    parser.add_option('', '--fmt', action="store", dest='fmt', 
                      help='Figure format e.g. png, pdf', default='png')
  
    (opt, args) = parser.parse_args()
    
    # files = ['/home/mcube/pnpushdata/friction_scan/plywood/rect1/record_surface=plywood_shape=rect1_a=-1000_v=20_rep=%03d_fcot.h5',
             # '/home/mcube/pnpushdata/friction_scan/delrin/rect1/record_surface=delrin_shape=rect1_a=-1000_v=20_rep=%03d_fcot.h5',
             # '/home/mcube/pnpushdata/friction_scan/pu/rect1/record_surface=pu_shape=rect1_a=0_v=20_rep=%03d_fcot.h5',
             # '/home/mcube/pnpushdata/friction_scan/abs/rect1/record_surface=abs_shape=rect1_a=0_v=20_rep=%03d_fcot.h5']
    files = ['/home/mcube/pnpushdata/friction_scan/abs/rect1/record_surface=abs_shape=rect1_a=0_v=20_rep=%03d_fcot.h5',
             '/home/mcube/pnpushdata/friction_scan/delrin/rect1/record_surface=delrin_shape=rect1_a=-1000_v=20_rep=%03d_fcot.h5',
             '/home/mcube/pnpushdata/friction_scan/plywood/rect1/record_surface=plywood_shape=rect1_a=-1000_v=20_rep=%03d_fcot.h5',
             '/home/mcube/pnpushdata/friction_scan/pu/rect1/record_surface=pu_shape=rect1_a=0_v=20_rep=%03d_fcot.h5']
             
    
    legends = ['abs', 'delrin', 'plywood', 'pu']
             
    linestyles = [':', '-', '-', '-']
    markerstyles = ['', '', 'x', 'o']
    #linestyles = ['-', '--', '-', '--']
    linewidths = [1,1,1,1]
    
    from latexify import latexify; latexify(8, fontsize=16)
    fig = plt.figure()
    #plt.rc('font', family='serif', size=20)
    for ind, filename in enumerate(files):
        if not os.path.isfile(filename):
            continue
        print ind, filename
        with h5py.File(filename, "r") as f:
            image_avgs_t = f['image_avgs_t'].value
            image_stds_t = f['image_stds_t'].value
        tmp = []
        for t in range(len(image_avgs_t)):
            tmp.append(0)
            for idx in range(len(image_avgs_t[t])):
                for idy in range(len(image_avgs_t[t][idx])):
                    tmp[-1] += image_avgs_t[t][idx][idy] / 9.0
        plt.errorbar(range(1,len(image_avgs_t)+1), tmp, fmt=linestyles[ind]+markerstyles[ind], 
                     linewidth = linewidths[ind], label=legends[ind], color='k',
                     markevery=10)
        print legends[ind], 'start', tmp[0], 'end', tmp[-1], 'chanage', (tmp[-1]-tmp[0]) / tmp[0]
        
    
    #plt.rc('font', family='serif', size=15)
    plt.legend(ncol=4)
    axes = plt.gca()
    axes.set_ylim([0.1, 0.35])
    
    plt.ylabel('Coefficient of friction')
    plt.xlabel('Number of scans')
    fig.subplots_adjust(left=None, bottom=0.16, right=None, top=None,
                    wspace=None, hspace=None)
    plt.tight_layout()
    #plt.title('Change of frictional coefficient over time')
    plt.savefig('/home/mcube/pnpushdata/friction_scan/friction_overtime_overmaterial_lineplot.png')
    plt.savefig('/home/mcube/pnpushdata/friction_scan/friction_overtime_overmaterial_lineplot.pdf')
    
    
    plt.show()
def main(argv):
    parser = optparse.OptionParser()

    parser.add_option('',
                      '--avgcolorbar',
                      action="store",
                      type='float',
                      dest='avgcolorbar',
                      help='Color bar',
                      nargs=2,
                      default=(None, None))
    parser.add_option('',
                      '--res',
                      action="store",
                      type='float',
                      dest='res',
                      help='Resolution in deg',
                      nargs=1,
                      default=(5))
    parser.add_option('',
                      '--rep',
                      action="store",
                      type='int',
                      dest='rep',
                      help='How many repetitions',
                      nargs=1,
                      default=(2))
    parser.add_option('',
                      '--limits',
                      action="store",
                      type='float',
                      dest='limits',
                      help='Limits in meter',
                      nargs=4,
                      default=(0.250, 0.450, -0.233,
                               0.197))  # [minx, maxx, miny, maxy]
    parser.add_option('',
                      '--N',
                      action="store",
                      type='float',
                      dest='N',
                      help='Normal force',
                      nargs=1,
                      default=(0.8374 * 9.81))  # Normal force

    (opt, args) = parser.parse_args()

    if len(args) < 1:  # no bagfile name
        parser.error(
            "Usage: plot_friction_vs_vel.py [dir_to_friction_scan_iso]")
        return

    dir_to_friction_scan_iso = args[0]

    figfname_png = dir_to_friction_scan_iso + '/friction_maximal_dissipation_overmaterial.png'
    figfname_pdf = dir_to_friction_scan_iso + '/friction_maximal_dissipation_overmaterial.pdf'
    ft_wrench = []

    min_x, max_x, min_y, max_y = opt.limits

    center = [(max_x + min_x) / 2, (max_y + min_y) / 2]
    acc = 0

    # a list of materials
    #dirlist = [ name for name in os.listdir(dir_to_friction_scan_iso) if os.path.isdir(os.path.join(dir_to_friction_scan_iso, name)) ]

    dirlist = ['abs', 'delrin', 'plywood', 'pu']

    shape_id = 'rect1'
    vel = 20
    N = opt.N

    linestyles = [':', '-', '-', '-']
    markerstyles = ['', '', '^', 'o']
    markeverys = [1, 1, 3, 3]
    rangex = xrange(0, 360, opt.res)
    raidus = 0.001

    from latexify import latexify
    latexify(scale=2, fig_height=1.5)
    axes = plt.gca()
    axes.grid(True, linewidth=0.25, color='grey')
    axes.set_axisbelow(True)

    for inds, surface in enumerate(dirlist):
        print dir_to_friction_scan_iso, surface, shape_id

        avgs = []
        vel_vecs = []
        for deg in rangex:
            vals = []
            for rep in xrange(opt.rep):
                h5filename = 'record_surface=%s_shape=%s_a=%.0f_v=%.0f_deg=%d_rep=%03d.h5' % (
                    surface, shape_id, acc * 1000, vel, deg, rep)
                filepath = '%s/%s/%s/%s' % (dir_to_friction_scan_iso, surface,
                                            shape_id, h5filename)
                f = h5py.File(filepath, "r")
                tip_array = f['tip_array'].value
                ft_wrench = f['ft_wrench'].value

                scale = (len(ft_wrench) * 1.0 / len(tip_array))

                for i, tip_pos in enumerate(tip_array):
                    if np.linalg.norm(
                            np.array(tip_pos[1:3]) -
                            np.array(center)) < raidus:
                        ft_i = int(i * scale)
                        vals.append(ft_wrench[ft_i][1:3])
            avgs.append(np.mean(vals, 0))

        # print  v * f - max(v * f*) >= 0
        diffs = []
        for i, deg in enumerate(rangex):
            th = np.deg2rad(deg)
            start_pos = [np.sin(th), np.cos(th)]
            end_pos = [np.sin(th + np.pi), np.cos(th + np.pi)]
            vel_vec = -(np.array(end_pos) - np.array(start_pos))

            force = avgs[i]
            #import pdb; pdb.set_trace()
            max_power = -np.inf
            for j, deg_p in enumerate(rangex):
                tmp_power = np.dot(vel_vec, avgs[j])
                if tmp_power > max_power:
                    max_power = tmp_power

            diffs.append(np.dot(vel_vec, force) - max_power)

        plt.errorbar(rangex,
                     diffs,
                     color='k',
                     fmt=linestyles[inds] + markerstyles[inds],
                     label=surface,
                     markevery=markeverys[inds],
                     markersize=5,
                     linewidth=0.5)

    plt.tight_layout()
    axes.set_xlabel('sliding direction in angles (deg)')
    axes.set_ylabel('$\Delta P$ (m*N/s)')

    legend = plt.legend(loc='lower right', ncol=4)

    legend.get_frame().set_linewidth(0.25)
    plt.subplots_adjust(left=0.12,
                        bottom=0.19,
                        right=None,
                        top=None,
                        wspace=None,
                        hspace=None)
    plt.savefig(figfname_png)
    plt.savefig(figfname_pdf)
    plt.show()
Exemple #23
0
    plt.text(28, 0.41, r"$RTT_{NS-3}$", color='r')

    plt.savefig(OUT_FILE2) #the pdf takes long time to load, png is used to debug
    plt.savefig(OUT_FILE)

    print "save figure to %s and %s" %(OUT_FILE, OUT_FILE2)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Paramenters')
    parser.add_argument('-s', '--suffix', dest='suffix', type=str, nargs='?',
                        help='suffix to identity the scenaro')
    parser.add_argument("--size", dest="size", type=str, nargs='?',
                        help="the size of output figure")

    args = parser.parse_args()
    print "parameter: suffx=%s size=%s" %(args.suffix, args.size)
    fig_size = "default"
    if args.size in ["s", "small"]:
        latexify.latexify(columns=1)
        fig_size = "small"
    elif args.size in ["b", "big", "l", "large"]:
        latexify.latexify(columns=2)
        fig_size = "large"
    elif args.size in ["t", "tiny"]:
        latexify.latexify(columns=0.67)
        fig_size = "tiny"
    else:
        pass

    run(suffix=args.suffix, fig_size=fig_size)
Exemple #24
0
import numpy as np
import matplotlib.pyplot as plt
from latexify import latexify
from matplotlib import patches

# Configuro latexify a dos columnas
latexify(fig_width=5, fontawesome=True, siunitx=True)

# Selected Papers from the 14th Estuarine and Coastal Modeling Conference
g = 0.069

nap_range = np.logspace(-3, 2, 6)
S_range = [0.06, 0.08, 0.10, 0.12]
g_range = np.round(np.linspace(-3, -.8, 5), 1)
x0 = 440
nap = 40
# Grafico
x = np.linspace(400, 700)
bbw = 0.00288 * (x / 500)**(-4.32)
for gbb in g_range:
    bb = 0.604 * nap**(0.766)
    bb = bb * (x / 550)**(gbb)
    plt.plot(x, bb + bbw, label=f"{gbb}")

plt.ylabel(r"$b_b$ [\si{\per\meter}]")
plt.xlabel(r"$\lambda$ [\si{\nano\meter}]")
plt.legend()
plt.tight_layout()
plt.savefig("curso-ico/figs/fig:t2-waternap-bb.pdf")
plt.savefig("curso-ico/figs/fig:t2-waternap-bb.png", dpi=300)
plt.close()
def main(argv):
    parser = optparse.OptionParser()
    
    parser.add_option('', '--avgcolorbar', action="store", type='float', dest='avgcolorbar', 
                      help='Color bar', nargs=2, default=(None,None))
    parser.add_option('', '--res', action="store", type='float', dest='res', 
                      help='Resolution in deg', nargs=1, default=(5))
    parser.add_option('', '--rep', action="store", type='int', dest='rep', 
                      help='How many repetitions', nargs=1, default=(2))
    parser.add_option('', '--limits', action="store", type='float', dest='limits', 
                      help='Limits in meter', nargs=4, default=(0.250,0.450, -0.233, 0.197)) # [minx, maxx, miny, maxy]
    parser.add_option('', '--N', action="store", type='float', dest='N', 
                      help='Normal force', nargs=1, default=(0.8374 * 9.81)) # Normal force
                      
    (opt, args) = parser.parse_args()
    
    if len(args) < 1:  # no bagfile name
        parser.error("Usage: plot_friction_vs_vel.py [dir_to_friction_scan_iso]")
        return
    
    dir_to_friction_scan_iso = args[0]
    
    figfname_png = dir_to_friction_scan_iso + '/friction_over_direction_overmaterial.png'
    figfname_pdf = dir_to_friction_scan_iso + '/friction_over_direction_overmaterial.pdf'
    ft_wrench = []
    
    min_x, max_x, min_y, max_y = opt.limits
    
    center = [(max_x + min_x) /2, (max_y + min_y) /2 ]
    acc = 0
    
    # a list of materials
    #dirlist = [ name for name in os.listdir(dir_to_friction_scan_iso) if os.path.isdir(os.path.join(dir_to_friction_scan_iso, name)) ]
    
    dirlist = ['abs', 'delrin','plywood',  'pu']
    
    shape_id = 'rect1'
    vel = 20
    N = opt.N
    
    linestyles = [':', '-', '-', '-']
    markerstyles = ['', '', '^', 'o']
    markeverys = [1,1,3,3]
    rangex = xrange(0, 360, opt.res)
    raidus = 0.001
    
    from latexify import latexify; latexify(scale = 2)
    axes = plt.gca()
    axes.grid(True, linewidth = 0.25, color='grey')
    axes.set_axisbelow(True)
    
    for inds, surface in enumerate(dirlist):
        print dir_to_friction_scan_iso, surface, shape_id
        
        avgs = []
        stds = []
        for deg in rangex:
            vals = []
            for rep in xrange(opt.rep):
                h5filename = 'record_surface=%s_shape=%s_a=%.0f_v=%.0f_deg=%d_rep=%03d.h5' % (surface, shape_id, acc*1000, vel, deg, rep)
                filepath = '%s/%s/%s/%s' % (dir_to_friction_scan_iso,surface,shape_id,h5filename)
                f = h5py.File(filepath, "r")
                tip_array = f['tip_array'].value
                ft_wrench = f['ft_wrench'].value
                
                scale = (len(ft_wrench)*1.0/len(tip_array))
                
                for i, tip_pos  in enumerate(tip_array):
                    if np.linalg.norm(np.array(tip_pos[1:3]) - np.array(center)) < raidus:
                        ft_i = int(i * scale)
                        vals.append(ft_wrench[ft_i][1:3])
            avgs.append(np.mean(vals, 0))


            # print surface, ' vel=', v
            # print 'average', '%.3f' % (np.average(vals) / N)
            # print 'std', '%.3f' % (np.std(vals) / N)
            # print 'max', '%.3f' % (np.max(vals) / N)
            # print 'min', '%.3f' % (np.min(vals) / N)
            
            
        
        xs = [ft[0] for ft in avgs]
        ys = [ft[1] for ft in avgs]
        xs.append(xs[0])
        ys.append(ys[0])
    
        plt.errorbar(xs, ys, color='k',  fmt=linestyles[inds]+markerstyles[inds], 
         label=surface, markevery = markeverys[inds], markersize=5, linewidth=0.5)
        
    axes.set_xlim([-7, 7])
    axes.set_ylim([-7, 7])
    axes.set_aspect('equal')
    axes.set_xlabel('Force x')
    axes.set_ylabel('Force y')
        
        
    legend = plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))
    
    legend.get_frame().set_linewidth(0.25)
    plt.tight_layout(pad=0)
    plt.subplots_adjust(left=0, bottom=None, right=0.87, top=None,
                wspace=None, hspace=None)
    plt.savefig(figfname_png)
    plt.savefig(figfname_pdf)
    plt.show()
    plt.close()