Beispiel #1
0
def plot_figures(figures, nrows=1, ncols=1):
    """Plot a dictionary of figures.

    Parameters
    ----------
    figures : <title, figure> dictionary
    ncols : number of columns of subplots wanted in the display
    nrows : number of rows of subplots wanted in the figure
    """

    fig, axeslist = plt.subplots(ncols=ncols, nrows=nrows)
    ravel = axeslist.ravel()
    for ind, img in enumerate(figures):
        ravel[ind].imshow(img, cmap=plt.jet())
        ravel[ind].set_title(" %2d " % (ind))
        ravel[ind].set_axis_off()
    plt.tight_layout()  # optional
    def plot_map(self, dataset, attribute_data, min_value=None, max_value=None, file=None,
                 my_title="", filter=None, background=None):
        """    Plots a 2D image of attribute given by 'name'. matplotlib required.
               The dataset must have a method 'get_2d_attribute' defined that returns
               a 2D array that is to be plotted. If min_value/max_value are given, all values
               that are smaller/larger than these values are set to min_value/max_value.
               Argument background is a value to be used for background. If it is not given,
               it is considered as a 1/100 under the minimum value of the array.
               Filter is a 2D array. Points where filter is > 0 are masked out (put into background).
        """
        import matplotlib
        matplotlib.use('Qt4Agg') 
        
        from matplotlib.pylab import jet,imshow,colorbar,show,axis,savefig,close,figure,title,normalize
        from matplotlib.pylab import rot90
        
        attribute_data = attribute_data[filter]
        coord_2d_data = dataset.get_2d_attribute(attribute_data = attribute_data)
        data_mask = coord_2d_data.mask
#        if filter is not None:
#            if isinstance(filter, ndarray):
#                if not ma.allclose(filter.shape, coord_2d_data.shape):
#                    raise StandardError, "Argument filter must have the same shape as the 2d attribute."
#                filter_data = filter
#            else:
#                raise TypeError, "The filter type is invalid. A character string or a 2D numpy array allowed."
#            filter_data = where(ma.filled(filter_data,1) > 0, 1,0)
#            data_mask = ma.mask_or(data_mask, filter_data)
        nonmaskedmin = ma.minimum(coord_2d_data) - .2 * (ma.maximum(coord_2d_data) - ma.minimum(coord_2d_data))
        if max_value == None:
            max_value = ma.maximum(coord_2d_data)
        if min_value == None:
            min_value = nonmaskedmin

        coord_2d_data = ma.filled(coord_2d_data,min_value)
        if background is None:
            value_range = max_value-min_value
            background = min_value-value_range/100
        coord_2d_data = ma.filled(ma.masked_array(coord_2d_data, mask=data_mask), background)

        # Our data uses NW as 0,0, while matplotlib uses SW for 0,0.
        # Rotate the data so the map is oriented correctly.
        coord_2d_data = rot90(coord_2d_data, 1)

        jet()
        figure()
        norm = normalize(min_value, max_value)
        im = imshow(coord_2d_data,
            origin='lower',
            aspect='equal',
            interpolation=None,
            norm=norm,
            )
        
        tickfmt = '%4d'
        if isinstance(min_value, float) or isinstance(max_value, float):
            tickfmt='%1.4f'
        colorbar(format=tickfmt)

        title(my_title)
        axis('off')
        if file:
            savefig(file)
            close()
        else:
            show()
Beispiel #3
0
    def plot_map(self,
                 dataset,
                 attribute_data,
                 min_value=None,
                 max_value=None,
                 file=None,
                 my_title="",
                 filter=None,
                 background=None):
        """    Plots a 2D image of attribute given by 'name'. matplotlib required.
               The dataset must have a method 'get_2d_attribute' defined that returns
               a 2D array that is to be plotted. If min_value/max_value are given, all values
               that are smaller/larger than these values are set to min_value/max_value.
               Argument background is a value to be used for background. If it is not given,
               it is considered as a 1/100 under the minimum value of the array.
               Filter is a 2D array. Points where filter is > 0 are masked out (put into background).
        """
        import matplotlib
        matplotlib.use('Qt4Agg')

        from matplotlib.pylab import jet, imshow, colorbar, show, axis, savefig, close, figure, title, normalize
        from matplotlib.pylab import rot90

        attribute_data = attribute_data[filter]
        coord_2d_data = dataset.get_2d_attribute(attribute_data=attribute_data)
        data_mask = coord_2d_data.mask
        #        if filter is not None:
        #            if isinstance(filter, ndarray):
        #                if not ma.allclose(filter.shape, coord_2d_data.shape):
        #                    raise StandardError, "Argument filter must have the same shape as the 2d attribute."
        #                filter_data = filter
        #            else:
        #                raise TypeError, "The filter type is invalid. A character string or a 2D numpy array allowed."
        #            filter_data = where(ma.filled(filter_data,1) > 0, 1,0)
        #            data_mask = ma.mask_or(data_mask, filter_data)
        nonmaskedmin = ma.minimum(coord_2d_data) - .2 * (
            ma.maximum(coord_2d_data) - ma.minimum(coord_2d_data))
        if max_value == None:
            max_value = ma.maximum(coord_2d_data)
        if min_value == None:
            min_value = nonmaskedmin

        coord_2d_data = ma.filled(coord_2d_data, min_value)
        if background is None:
            value_range = max_value - min_value
            background = min_value - value_range / 100
        coord_2d_data = ma.filled(
            ma.masked_array(coord_2d_data, mask=data_mask), background)

        # Our data uses NW as 0,0, while matplotlib uses SW for 0,0.
        # Rotate the data so the map is oriented correctly.
        coord_2d_data = rot90(coord_2d_data, 1)

        jet()
        figure()
        norm = normalize(min_value, max_value)
        im = imshow(
            coord_2d_data,
            origin='lower',
            aspect='equal',
            interpolation=None,
            norm=norm,
        )

        tickfmt = '%4d'
        if isinstance(min_value, float) or isinstance(max_value, float):
            tickfmt = '%1.4f'
        colorbar(format=tickfmt)

        title(my_title)
        axis('off')
        if file:
            savefig(file)
            close()
        else:
            show()
#% Red Color for segment 3.
barColorMap[3,:] = np.array(np.hstack((.9, .9, .14)))
#% Yellow Color for segment 4.
#% I have not defined any more than 4 colors in this demo.
#% For any number of bars beyond 4, just make up random colors.
if numberOfBars > 4.:
    barColorMap[4:numberOfBars,0:3.] = np.random.rand((numberOfBars-4.), 3.)


elif button == 2.:
    #% Example of using colormap with random colors
    barColorMap = np.random.rand(numberOfBars, 3.)
    
elif button == 3.:
    #% Example of using pre-defined jet colormap
    barColorMap = plt.jet(numberOfBars)
    
elif button == 4.:
    #% Example of using pre-defined Hot colormap
    barColorMap = plt.hot(numberOfBars)
    
else:
    #% Example of using pre-defined lines colormap
    barColorMap = lines(numberOfBars)
    

#% Plot each number one at a time, calling bar() for each y value.
for b in np.arange(1., (numberOfBars)+1):
    #% Plot one single bar as a separate bar series.
    
#% Fancy up the graph.
a1=coeff[0,1]
phi=coeff[1,1]

a0[a0==0]=1
a0[np.isnan(a0)]=1
a1[np.isnan(a1)]=1
a0[np.isinf(a0)]=1
a1[np.isinf(a1)]=1

pp.figure(num=None, figsize=(10, 12.5), dpi=80, facecolor='w', edgecolor='k')
mean_int = a0.mean()
pp.subplot(3,2,1)
pp.imshow(a0, vmin=mean_int*0.65, vmax=mean_int*1.35, interpolation='none')
pp.colorbar()
pp.title('Flat Field Intensity')
pp.jet()
pp.grid()

pp.subplot(3,2,2)
pp.imshow(a1, interpolation='none',vmin=0,vmax=3000)      
pp.colorbar()
pp.title('Flat Field Amplitude')
pp.grid()

pp.subplot(3,2,3)
pp.imshow(phi, vmax=np.pi, vmin=-np.pi, interpolation='none')
cbar=pp.colorbar()
cbar.set_ticks([-np.pi, -0.75*np.pi, -0.5*np.pi, -0.25*np.pi, 0, 0.25*np.pi, 0.5*np.pi, 0.75*np.pi, np.pi])
cbar.set_ticklabels(['-pi', '-pi3/4', '-pi/2', '-pi/4', '0 pi', 'pi/4', 'pi/2', 'pi3/4', 'pi'])
pp.title('Flat Field Phase')
pp.grid()
Beispiel #6
0
def msCompareResults(vol, sigma, shrink_factor=0.5, gui=True, edge_quantil=0.05):
    start = time()
    grad =  msGaussianGradient(vol, sigma)
    elapsed = time() - start
    print "msGaussianGradient took %f seconds to finish" % elapsed

    shp = vol.shape
    weight = np.array(range(shp[2]))
    for ch in range(shp[2]/2):
        grad[...,ch,:] *= weight[ch]

    start = time()
    mean_g = msMeanGradient(grad)   
    elapsed = time() - start
    print "msMeanGradient took %f seconds to finish" % elapsed
    stddev_g = msVector2ImageMagnitude(np.std(grad,2))

    start = time()
    max_g = msMaxGradient(grad)    
    elapsed = time() - start
    print "msMaxGradient took %f seconds to finish" % elapsed

    start = time()
    mv_g , semi_major_g, semi_minor_g = msMVGradient(grad)    
    elapsed = time() - start
    print "msMVGradient took %f seconds to finish" % elapsed
        
    eccentricity_g = np.sqrt(1-semi_minor_g**2/semi_major_g**2)
    
    mean_el = np.array(vg.analysis.cannyEdgelList(vg.Vector2Image(mean_g),np.max(msVector2ImageMagnitude(mean_g))*edge_quantil))
    max_el = np.array(vg.analysis.cannyEdgelList(vg.Vector2Image(max_g),  np.max(msVector2ImageMagnitude(max_g))*edge_quantil))
    mv_el = np.array(vg.analysis.cannyEdgelList(vg.Vector2Image(mv_g),    np.max(msVector2ImageMagnitude(mv_g))*edge_quantil))
    
    if (gui):
        F_mag = pl.figure()
        F_mag.clf()     
        pl.jet()
        grid_mag = ImageGrid(F_mag, 111, \
                      nrows_ncols = (1, 3),\
                      direction="row",\
                      axes_pad = 0.05,\
                      add_all=True,\
                      label_mode = "1",\
                      share_all = True,\
                      cbar_location="right",\
                      cbar_mode="single",\
                      cbar_size="10%",\
                      cbar_pad=0.05)

        max_v = np.max(msVector2ImageMagnitude(mv_g))
        min_v = np.min(msVector2ImageMagnitude(mv_g))
    
        import matplotlib.colors
        norm = matplotlib.colors.normalize(vmax=max_v, vmin=min_v)
        
        grid_mag[0].imshow(msVector2ImageMagnitude(mean_g),norm=norm)
        pl.title("Mean Gradient Mag.")
    
        #pl.figure()
        #pl.subplot(132)
        grid_mag[1].imshow(msVector2ImageMagnitude(max_g), norm=norm)
        pl.title("Max Gradient Mag.")
    
        #pl.figure()
        #pl.subplot(133)
        img_mag = grid_mag[2].imshow(msVector2ImageMagnitude(mv_g), norm=norm)
        pl.title("MV Gradient Mag.")
        grid_mag[2].cax.colorbar(img_mag)
        
	print 'check'        
        F_ang = pl.figure()
        F_ang.clf()     
        pl.hsv()
        grid_ang = ImageGrid(F_ang, 111, \
                      nrows_ncols = (1, 3),\
                      direction="row",\
                      axes_pad = 0.05,\
                      add_all=True,\
                      label_mode = "1",\
                      share_all = True,\
                      cbar_location="right",\
                      cbar_mode="single",\
                      cbar_size="10%",\
                      cbar_pad=0.05)
            
        norm = matplotlib.colors.normalize(vmax=180, vmin=-180)
        grid_ang[0].imshow(msVector2ImageAngle(mean_g), norm=norm)
        pl.title("Mean Gradient Angle")
    
        grid_ang[1].imshow(msVector2ImageAngle(max_g), norm=norm)
        pl.title("Max Gradient Angle")
    
        img_ang = grid_ang[2].imshow(msVector2ImageAngle(mv_g), norm=norm)
        pl.title("MV Gradient Angle")
        grid_ang[2].cax.colorbar(img_ang)
        
        
        
        F_edg = pl.figure()
        F_edg.clf()     
        pl.hsv()
        grid_edg = ImageGrid(F_edg, 111, \
                      nrows_ncols = (1, 3),\
                      direction="row",\
                      axes_pad = 0.05,\
                      add_all=True,\
                      label_mode = "1",\
                      share_all = True,\
                      cbar_location="right",\
                      cbar_mode="single",\
                      cbar_size="10%",\
                      cbar_pad=0.05)
        
        
        grid_edg[0].axis([0, shp[0]-1, shp[1]-1, 0])
        grid_edg[1].axis([0, shp[0]-1, shp[1]-1, 0])
        grid_edg[2].axis([0, shp[0]-1, shp[1]-1, 0])
        plotEdgelList(mean_el, grid_edg[0])
        plotEdgelList(max_el,  grid_edg[1])
        plotEdgelList(mv_el,   grid_edg[2])
        
        #pl.figure()
        #pl.subplot(131,aspect="equal")
        #pl.axis([0, shp[0]-1, shp[1]-1, 0])
        #plotEdgelList(mean_el)
        #pl.title("Mean Gradient Edgel")

        #pl.subplot(132,aspect="equal")
        #pl.axis([0, shp[0]-1, shp[1]-1, 0])
        #plotEdgelList(max_el)
        #pl.title("Max Gradient Edgel")

        #pl.subplot(133,aspect="equal")
        #pl.axis([0, shp[0]-1, shp[1]-1, 0])
        #plotEdgelList(mv_el)
        #pl.title("MV Gradient Edgel")
    
    
        ## MV semi-major and semi-minor axis
        pl.figure()
        pl.subplot(121)
        pl.imshow(semi_major_g)
        pl.copper()
        pl.colorbar(shrink=shrink_factor)
        pl.title("Gradient MV semi-major axis")
    
        pl.subplot(122)
        pl.imshow(semi_minor_g)
        pl.colorbar(shrink=shrink_factor)
        pl.title("Gradient MV semi-minor axis")
        
        
        ## Std. dev of MS Gradients vs. Eccentricity of the MV eigenvals
        pl.figure()
        pl.subplot(121)
        pl.imshow(stddev_g)
        pl.copper()
        pl.colorbar(shrink=shrink_factor)
        pl.title("Gradient std. dev.")
    
        pl.subplot(122)
        pl.imshow(eccentricity_g)
        pl.colorbar(shrink=shrink_factor)
        pl.title("Gradient MV eccentricity")

	pl.show()
    def plotClassifier(self,
                       classifier,
                       dataType="train",
                       catInds=[0, 1, 2],
                       prefix="posterior"):

        # データの選択
        if dataType == "train":
            cat1 = self.cat1_train
            cat2 = self.cat2_train
            cat3 = self.cat3_train
        else:
            cat1 = self.cat1_test
            cat2 = self.cat2_test
            cat3 = self.cat3_test

        for catInd in catInds:
            #fig = plt.figure()

            # 学習データを描画
            # カテゴリ1
            x1, x2 = np.vstack(cat1).transpose()
            plt.plot(x1,
                     x2,
                     'o',
                     color="#FFA500",
                     markeredgecolor='k',
                     markersize=14)

            # カテゴリ2
            x1, x2 = np.vstack(cat2).transpose()
            plt.plot(x1,
                     x2,
                     's',
                     color="#FFFF00",
                     markeredgecolor='k',
                     markersize=14)

            # カテゴリ3
            x1, x2 = np.vstack(cat3).transpose()
            plt.plot(x1,
                     x2,
                     '^',
                     color="#FF00FF",
                     markeredgecolor='k',
                     markersize=14)

            # 識別境界を描画
            N = len(cat1) + len(cat2) + len(cat3)

            #メッシュの作成
            X1, X2 = plt.meshgrid(plt.linspace(-6, 6, 50),
                                  plt.linspace(-6, 6, 50))
            width, height = X1.shape
            X1.resize(X1.size)
            X2.resize(X2.size)
            Z = np.array([
                classifier.predict(np.array([[x1], [x2]]))[catInd]
                for (x1, x2) in zip(X1, X2)
            ])
            X1.resize((width, height))
            X2.resize((width, height))
            Z.resize((width, height))

            # contourプロット
            levels = [x / 10.0 for x in np.arange(0, 11, 1)]
            CS = plt.contourf(X1, X2, Z, levels)

            # contourの数値ラベル
            plt.clabel(CS,
                       colors='black',
                       inline=True,
                       inline_spacing=0,
                       fontsize=14)

            # contourのカラーバー
            CB = plt.colorbar(CS)
            CB.set_ticks(levels)
            CB.ax.tick_params(labelsize=14)
            for line in CB.lines:
                line.set_linewidth(20)

            # 色空間の設定
            plt.jet()

            # plotラベルの設定
            plt.title("p(y={}|x)".format(catInd + 1), fontsize=14)
            plt.xlabel("x1", fontsize=14)
            plt.ylabel("x2", fontsize=14)
            plt.tick_params(labelsize=14)

            # 表示範囲の設定
            plt.xlim(-6, 6)
            plt.ylim(-6, 6)

            # レジェンド
            plt.legend(["category 1", "category 2", "category 3"])

            # 画像として保存
            fullpath = os.path.join(self.visualPath,
                                    "{}_{}.png".format(prefix, catInd + 1))
            plt.savefig(fullpath)

            plt.close()
#% save q and chi data files
chi0name = np.array(np.hstack((dumpname, '\\', imgname, 'chi0.mat')))
q0name = np.array(np.hstack((dumpname, '\\', imgname, 'Q0.mat')))
plt.save(q0name, 'Q0')
plt.save(chi0name, 'chi0')
#%% Normalize and save qchi with all phis
Qchi0_allphi = matdiv(Qchi0_allphi, numphi)
#% normalize the combined-phi image
for n in np.arange(1., (lchi0int)+1):
    #% make a log plot
    
#% Plot qchi
H = imagesc(Q0, chi0, Qchi0log_allphi)
plt.xlabel('Q (A^-1)')
plt.ylabel('chi (deg)')
plt.colorbar
colormap(plt.jet(256.))
#%xlim([2 8]) % these values specific to your data; CHECK!!!
#%ylim([-80 30]) % these values specific to your data; CHECK!!!
caxis(np.array(np.hstack((0.5, 4.))))
#% these values specific to your data; CHECK!!!
savepath = np.array(np.hstack((dumpname, '\\', imgname, 'allphi_cropped.tif')))
saveas(H, savepath)
#% Save qchi data
qx0phiname = np.array(np.hstack((dumpname, '\\', imgname, 'qx0_allphi.mat')))
qx0logphiname = np.array(np.hstack((dumpname, '\\', imgname, 'qx0log_allphi.mat')))
plt.save(qx0phiname, 'Qchi0_allphi')
plt.save(qx0logphiname, 'Qchi0log_allphi')
toc
#% end timer