コード例 #1
0
ファイル: cpt_tools.py プロジェクト: EJFielding/PySAR
def _get_matplotlib_cmaps(mpldict):
   lutsize = mpl.rcParams['image.lut']
   tempdic = {}
   for k,v in mpldict.iteritems():
      if k not in mpl_noinclude:
         tempdic[k] = _generate_cmap(k,lutsize)
      else:
         n = 100
         indices = np.linspace(0,1.,n)
         t_cmap = _generate_cmap(k,lutsize)
         t_cmapents = t_cmap(indices)
         t_cdict = {}
         for ki,key in enumerate(('red','green','blue')):
            t_cdict[key] = [ (indices[i], t_cmapents[i,ki], t_cmapents[i,ki]) for i in xrange(n) ]
         tempdic[k] = colors.LinearSegmentedColormap(k,t_cdict,lutsize)
   return tempdic
コード例 #2
0
def _get_matplotlib_cmaps(mpldict):
    lutsize = mpl.rcParams['image.lut']
    tempdic = {}
    for k, v in mpldict.iteritems():
        if k not in mpl_noinclude:
            tempdic[k] = _generate_cmap(k, lutsize)
        else:
            n = 100
            indices = np.linspace(0, 1., n)
            t_cmap = _generate_cmap(k, lutsize)
            t_cmapents = t_cmap(indices)
            t_cdict = {}
            for ki, key in enumerate(('red', 'green', 'blue')):
                t_cdict[key] = [(indices[i], t_cmapents[i, ki], t_cmapents[i,
                                                                           ki])
                                for i in xrange(n)]
            tempdic[k] = colors.LinearSegmentedColormap(k, t_cdict, lutsize)
    return tempdic
コード例 #3
0
x_t = np.zeros(shape=(N_tag,df.shape[0],3)) # empty animation array (3D)

for tag in range(12):
    # store data in numpy 3D array: (tag,time-stamp,xyz-coordinates)
    x_t[tag,:,:] = df[tag]

x_t = x_t[:, :, [0, 2, 1]]

# Set up figure & 3D axis for animation
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1], projection='3d')
ax.axis('on')

# choose a different color for each trajectory
from matplotlib.cm import _generate_cmap
cm= _generate_cmap('Spectral', 256)
colors = cm(np.linspace(0, 1, N_trajectories))
#colors = plt.cm.jet(np.linspace(0, 1, N_trajectories))
# set up trajectory lines
lines = sum([ax.plot([], [], [], '-', c=c) for c in colors], [])
# set up points
pts = sum([ax.plot([], [], [], 'o', c=c) for c in colors], [])
# set up lines which create the stick figures

stick_defines = [
    (0, 1),
    (1, 2),
    (3, 4),
    (4, 5),
    (6, 7),
    (7, 8),
コード例 #4
0
ファイル: plot.py プロジェクト: mojin-robotics/atf
    def plot_benchmark(self, style, sharey, hide_groundtruth, hide_min_max,
                       filter_tests, filter_testblocks, filter_metrics):

        sorted_atf_results = ATFConfigurationParser().get_sorted_plot_dicts(
            self.atf_result, filter_tests, filter_testblocks, filter_metrics)

        if style not in list(sorted_atf_results.keys()):
            print("ERROR: style '%s' not implemented" % style)
            return
        plot_dict = sorted_atf_results[style]

        rows = []
        cols = []
        plots = []
        nr_unique_plots = 0
        for row in list(plot_dict.keys()):
            if row not in rows:
                rows.append(row)
            for col in list(plot_dict[row].keys()):
                if col not in cols:
                    cols.append(col)
                for plot in list(plot_dict[row][col].keys()):
                    if plot not in plots:
                        plots.append(plot)

        # sort alphabetically
        rows.sort()
        cols.sort()
        plots.sort()

        print("\nplotting in style '%s' (rows: %d, cols: %d, plots: %d)" %
              (style, len(rows), len(cols), len(plots)))

        fig, axs = plt.subplots(
            len(rows),
            len(cols),
            squeeze=False,
            sharex=True,
            sharey=sharey,
            figsize=(10, 12))  # FIXME calculate width with nr_testblocks

        # always make this a numpy 2D matrix to access rows and cols correclty if len(rows)=1 or len(cols)=1
        #axs = np.atleast_2d(axs)
        #axs = axs.reshape(len(rows), len(cols))
        # --> not needed anymore due to squeeze=False

        # define colormap (one color per plot)
        clut = cm._generate_cmap('Dark2', len(plots))
        colors = [clut(plots.index(plot)) for plot in plots]
        #colors = [(0.10588235294117647, 0.61960784313725492, 0.46666666666666667, 1.0), (0.85098039215686272, 0.37254901960784315, 0.0078431372549019607, 1.0)]*len(plots)

        for row in rows:
            #print "\nrow=", row

            for col in cols:
                #print "  col=", col

                # select subplot
                ax = axs[rows.index(row)][cols.index(col)]

                # format x axis
                x = np.arange(len(plots))
                ax.set_xticks(x)
                ax.set_xticklabels(plots)
                ax.set_xlim(-1, len(plots))

                # format y axis
                ax.autoscale(enable=True, axis='y', tight=False)
                ax.margins(
                    y=0.2)  # make it a little bigger than the min/max values

                # only set title for upper row and ylabel for left col
                if rows.index(row) == 0:
                    ax.set_title(col)
                if cols.index(col) == 0:
                    ax.set_ylabel(row, rotation=45, ha="right")

                for plot in plots:
                    #print "    plot=", plot
                    try:
                        metric_result = plot_dict[row][col][plot]
                    except KeyError:
                        #print "skip", row, col, plot
                        continue

                    ax.grid(True)
                    nr_unique_plots += 1

                    # set data to plot
                    data = metric_result.data.data
                    lower = metric_result.groundtruth.data - metric_result.groundtruth.epsilon
                    upper = metric_result.groundtruth.data + metric_result.groundtruth.epsilon

                    # set groundtruth marker
                    if metric_result.groundtruth.available and not hide_groundtruth:
                        yerr = [[data - lower], [upper - data]]
                    else:
                        yerr = [[0], [0]]

                    # set marker transparency (filled or transparent)
                    if metric_result.status == TestblockStatus.SUCCEEDED\
                        and (metric_result.groundtruth.result == Groundtruth.SUCCEEDED or not metric_result.groundtruth.available):
                        markerfacecolor = None  # plot filled marker
                    else:
                        markerfacecolor = 'None'  # plot transparent marker

                    # set color
                    color = colors[plots.index(plot)]

                    # plot data and groundtruth
                    ax.errorbar(plots.index(plot),
                                data,
                                yerr=yerr,
                                fmt='D',
                                markersize=12,
                                markerfacecolor=markerfacecolor,
                                color=color)

                    # plot min and max
                    if not hide_min_max and not metric_result.mode == MetricResult.SNAP:  # only plot min max for SPAN modes
                        ax.plot(plots.index(plot),
                                metric_result.min.data,
                                '^',
                                markersize=8,
                                color=color)
                        ax.plot(plots.index(plot),
                                metric_result.max.data,
                                'v',
                                markersize=8,
                                color=color)

                    # plot a non-visible zero for y-axis scaling
                    ax.plot(plots.index(plot), 0, '')

        fig.autofmt_xdate(rotation=45)
        plt.tight_layout()

        title = "ATF result for %s" % (self.atf_result.name)
        st = fig.suptitle(title, fontsize="large")
        # shift subplots down:
        fig.subplots_adjust(top=0.90)  # move top for title

        fig.set_facecolor("white")

        fig.savefig("/tmp/test.png")
        plt.show()
        return
コード例 #5
0
def renderSkeleton(data, **kwargs):
    time = kwargs.pop('time', None)
    if time is None:
        time = range(len(data))
    showTrajectory = kwargs.pop('showTrajectory', False)
    showSticks = kwargs.pop('showSticks', False)
    rotate = kwargs.pop('rotate', False)
    hirarchy = kwargs.pop('rotate', [])
    jointsNum = len(data[0])
    
    
    # Set up figure & 3D axis for animation
    fig = plt.figure()
    ax = fig.add_axes([0, 0, 1, 1], projection='3d')
    ax.axis('on')
    
    # choose a different color for each trajectory
    from matplotlib.cm import _generate_cmap
    cm= _generate_cmap('Spectral', 256)
    colors = cm(np.linspace(0, 1, jointsNum))
    # set up trajectory lines
    lines = sum([ax.plot([], [], [], '-', c=c) for c in colors], [])
    # set up points
    pts = sum([ax.plot([], [], [], 'o', c=c) for c in colors], [])
    
    stick_lines = [ax.plot([], [], [], 'k-')[0] for _ in hirarchy]
    dic={}
    dataByJoints = np.zeros(shape=(jointsNum,len(data),3))
    for j in range(jointsNum):
        for l in range(len(data)):
            dataByJoints[j, l, :] = data[l][j]
            #np.array([data[l][3*j], data[l][3*j+1],data[l][3*j+2]])
    
    # prepare the axes limits
    maxes =np.zeros((3,1))
    mins=np.zeros((3,1))
    for d in range(3):
        maxes[d] = np.max(dataByJoints[:,:,d])
        maxes[d] = maxes[d]*1.3 if maxes[d]>0 else maxes[d]*0.7
        mins[d] = np.min(dataByJoints[:,:,d])
        mins[d] = mins[d]*1.3 if mins[d]<0 else mins[d]*0.7
    #maxes=maxes[[0, 2, 1]]  
    #mins=mins[[0, 2, 1]]  
    print maxes
    print mins
    ax.set_xlim((mins[0], maxes[0]))
    ax.set_ylim((mins[2], maxes[2])) # note usage of z coordinate
    ax.set_zlim((mins[1], maxes[1])) # note usage of y coordinate
    
    # set point-of-view: specified by (altitude degrees, azimuth degrees)
    ax.view_init(30, 0)
    
    # initialization function: plot the background of each frame
    def init():
        for line, pt in zip(lines, pts):
            # trajectory lines
            line.set_data([], [])
            line.set_3d_properties([])
            # points
            pt.set_data([], [])
            pt.set_3d_properties([])
        return lines + pts + stick_lines
    
    showTrajectory = True
    showSticks = False
    rotate= False
    # animation function.  This will be called sequentially with the frame number
    #x_t= np.array(data)
    x_t = dataByJoints
    x_t = x_t[:, :, [0, 2, 1]]
    print x_t[0][0] 
    def animate(i):
        # we'll step two time-steps per frame.  This leads to nice results.
        i = (5 * i) % x_t.shape[1]
    
        for line, pt, xi in zip(lines, pts, x_t):
            x, y, z = xi[:i].T # note ordering of points to line up with true exogenous registration (x,z,y)
            pt.set_data(x[-1:], y[-1:])
            pt.set_3d_properties(z[-1:])
            
            # trajectory lines
            if showTrajectory:
                line.set_data(x,y)
                line.set_3d_properties(z)
                
        if showSticks:
            for stick_line, (sp, ep) in zip(stick_lines, hirarchy):
                stick_line._verts3d = x_t[[sp,ep], i, :].T.tolist()
    
        if rotate:
            ax.view_init(30, 0.3 * i)
        fig.canvas.draw()
        return lines + pts + stick_lines
    
    # instantiate the animator.
    anim = animation.FuncAnimation(fig, animate, init_func=init, frames=500, interval=30, blit=True)
    plt.show()
    return fig
コード例 #6
0
 def animate(self, fileName):
     f= open(fileName, 'r')
     headers=f.readline().split()
     # A fix for a bug that misarranged the columns names in the file 
     headers = jointsMap.getFileHeader(headers)
     print headers
     self.hirarchy = jointsMap.getHirarchy(headers)
     joints = jointsMap.getJoints(headers)
     print joints
     jointsNum = len(joints)
     fileLength=0
     for line in f:
         fileLength+=1
     self.mainWindow.ui.slider.setRange(0, fileLength)
     self.mainWindow.ui.skeletonFileLength = fileLength
     x_t = np.zeros(shape=(jointsNum,fileLength,3)) # empty animation array (3D)
     f= open(fileName, 'r')
     f.readline()
     for i,line in enumerate(f):
         lineF=[float(v) for v in line.split()]
         for j, joint in enumerate(joints):
             x_t[j,i,:] = [lineF[headers.index(joint+'_X')],lineF[headers.index(joint+'_Y')],\
                           lineF[headers.index(joint+'_Z')],]
     
     fig = self.figure
     self.ax = fig.add_axes([0, 0, 1, 1], projection='3d')
     self.ax.axis('on')
     #Adjust data to matplotlib axes
     x_t = x_t[:, :, [2, 0, 1]]
     self.ax.set_xlabel("Z axe")
     self.ax.set_ylabel("X axe")
     self.ax.set_zlabel("Y axe")
     
     # choose a different color for each trajectory
     a = np.linspace(0, 1, jointsNum)
     #self.colors = plt.cm.jet(a)
     from matplotlib.cm import _generate_cmap
     cm= _generate_cmap('Spectral', 256)
     self.colors = cm(a)
     self.colors[8] = [0, 0, 0, 1]
     #cm = matplotlib.colors.LinearSegmentedColormap('jet')
     
     # set up trajectory lines
     self.lines = sum([self.ax.plot([], [], [], '-', c=c) for c in self.colors], [])
     # set up points
     self.pts = sum([self.ax.plot([], [], [], 'o', c=c) for c in self.colors], [])
     # set up lines which create the stick figures
     
     self.stick_lines = [self.ax.plot([], [], [], 'k-')[0] for _ in self.hirarchy]
     
     # prepare the axes limits
     self.ax.set_xlim((np.min(x_t[:,:,0]),np.max(x_t[:,:,0])))
     self.ax.set_ylim((np.min(x_t[:,:,1]),np.max(x_t[:,:,1]))) # note usage of z coordinate
     self.ax.set_zlim((np.min(x_t[:,:,2]),np.max(x_t[:,:,2]))) # note usage of y coordinate
     # set point-of-view: specified by (altitude degrees, azimuth degrees)
     #self.ax.view_init(30, 0)
     #self.ax.set_aspect('auto')
     def myAnimate(i):
         if self.mainWindow.pause or self.mainWindow.stop:
             self.draw()
             return self.lines + self.pts + self.stick_lines
         currTime = self.mainWindow.currTime+1
         self.mainWindow.ui.updateCurrTime(currTime)
         for line, pt, xi in zip(self.lines, self.pts, x_t):
             x, y, z = xi[self.mainWindow.start:currTime].T 
             pt.set_data(x[-1:], y[-1:])
             pt.set_3d_properties(z[-1:])
             
             # trajectory lines
             if self.showTrajectory:
                 line.set_data(x,y)
                 line.set_3d_properties(z)
                 
         if self.showSticks:
             if self.hirarchy is None:
                 QtGui.QMessageBox.information(self,"Can't complete command",\
                                                 'Hirarchy is missing')
                 self.showSticks = False
             else:    
                 for stick_line, (sp, ep) in zip(self.stick_lines, self.hirarchy):
                     stick_line._verts3d = x_t[[sp,ep], currTime, :].T.tolist()
         else:
             for stick_line in self.stick_lines:
                 stick_line._verts3d = [[],[],[]]
                 
         if self.rotate:
             self.ax.view_init(30, currTime)
         return self.lines + self.pts + self.stick_lines
     print self.mainWindow.playingSpeed
     return animation.FuncAnimation(
                 fig, myAnimate,init_func=self.init, interval=1000/self.mainWindow.playingSpeed, blit=True)