Пример #1
0
    def plot_quiver(self, n):
        """ Plot the curve and the vector field at a particular timestep """
        self.new_figure()

        x,y = self.split_array(self.Q[n])

        u,v = self.split_array(self.U[n])

        mag = [np.sqrt(u[i]**2+v[i]**2) for i in xrange(np.size(u))]
        norm = plt.normalize(np.min(mag), np.max(mag))

        C = [plt.cm.jet(norm(m)) for m in mag]

        plt.plot(x,y)
        plt.quiver(x,y,-u,-v,color=C)
        #plt.plot(*self.split_array(self.qA),color='grey',ls=':')
        plt.plot(*self.split_array(self.qB),color='grey',ls=':')
Пример #2
0
def create_matplot(matrix, xlabels=None, ylabels=None, main=''):
    """Creates a image from a matrix."""
    from matplotlib.pylab import matshow, xticks, text, title, normalize, setp, gca, colorbar
    norm = normalize(matrix.min(), matrix.max())
    image = matshow(matrix, norm=norm)
    nrows, ncols = matrix.shape
    if xlabels is not None:
        #xticks(arange(ncols)+0.5, xlabels)
        setp(gca(), xticks=[])
        for icol in range(ncols):
            text(icol+0.5, -0.5, xlabels[icol], horizontalalignment='right', rotation='vertical')
    if ylabels is not None:
        setp(gca(), yticks=[])
        for irow in range(nrows):
            text(-0.5, irow+0.5, ylabels[irow], horizontalalignment='right')
    tickfmt='%1.4f'
    colorbar(format=tickfmt)
    title(main)
Пример #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()
Пример #4
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()
Пример #5
0
                      edgecolor='none')
    ax_params.grid(1)
    ax_params.set_xlabel('mu')
    ax_params.set_ylabel('lambda')

    mymap = mpl.colors.LinearSegmentedColormap.from_list('mycolors',['blue','red'])

    for di, d in enumerate(chains):
        subsamp = 4
        s = np.array(d['scores'])[::subsamp]
        t = np.array(d['times'])[::subsamp] - d['times'][0]
        ax_score.plot(t, s, alpha=0.7, c='k')

        allscores.append(d['scores'])
    sm = pylab.cm.ScalarMappable(cmap=mymap, 
                                 norm=pylab.normalize(vmin=1, vmax=5.0))
    sm._A = []
    ax_score.tick_params(axis='both', which='major', labelsize=6)
    ax_score.tick_params(axis='both', which='minor', labelsize=6)
    ax_score.set_xlabel('time (s)')
    ax_score.grid(1)
    all_s = np.hstack(allscores).flatten()
    #r = np.max(all_s) - np.min(all_s)
    #ax_score.set_ylim(np.min(all_s) + r*0.95, np.max(all_s)+r*0.05)
    
    bins = np.arange(1, 11)
    hist, _ = np.histogram(groupcounts, bins)

    ax_groups.bar(bins[:-1], hist)
    ax_groups.set_xlim(bins[0], bins[-1])
Пример #6
0
def saveBitmap(outputFileName, imageData, cutLevels, size, colorMapName, caption, clipSizeDeg, scale=None):
    """Makes a bitmap image from an image array; the image format is specified by the
    filename extension. (e.g. ".jpg" =JPEG, ".png"=PNG).
    
    @type outputFileName: string
    @param outputFileName: filename of output bitmap image
    @type imageData: numpy array
    @param imageData: image data array
    @type cutLevels: list
    @param cutLevels: sets the image scaling - available options:
        - pixel values: cutLevels=[low value, high value].
        - histogram equalisation: cutLevels=["histEq", number of bins ( e.g. 1024)]
        - relative: cutLevels=["relative", cut per cent level (e.g. 99.5)]
        - smart: cutLevels=["smart", cut per cent level (e.g. 99.5)]
    ["smart", 99.5] seems to provide good scaling over a range of different images. 
    @type size: int
    @param size: size of output image in pixels
    @type colorMapName: string
    @param colorMapName: name of a standard matplotlib colormap, e.g. "hot", "cool", "gray"
    etc. (do "help(pylab.colormaps)" in the Python interpreter to see available options)
    
    """		

    clipSizeArcsec = clipSizeDeg*60*60.
    if not scale:
      cut=intensityCutImage(imageData, cutLevels)
    else:
      anorm = pylab.normalize(scale[0],scale[1])
      cut = {'image': imageData, 'norm': anorm}  
    # Make plot
    aspectR=float(cut['image'].shape[0])/float(cut['image'].shape[1])
    fig = pylab.figure(figsize=(10,10*aspectR))
    xPix = size
    yPix = size
    dpi = 100
    xSizeInches = size/dpi
    ySizeInches = xSizeInches
    fig.set_size_inches(xSizeInches,ySizeInches)
    ax = pylab.axes([0,0,1,1])
 #pylab.minorticks_off()
    
    try:
        colorMap=pylab.cm.get_cmap(colorMapName)
    except AssertionError:
        raise Exception, colorMapName+" is not a defined matplotlib colormap."
    
    if cutLevels[0]=="histEq":
        ax.imshow(cut['image'],  interpolation="bilinear", origin='lower', cmap=colorMap)
    else:
        ax.imshow(cut['image'],  interpolation="bilinear",  norm=cut['norm'], origin='lower',
            cmap=colorMap)
    xmin,xmax = ax.get_xlim()
    ymin,ymax = ax.get_ylim()
    ax.text(xmin+1,ymin+1,caption,color="red",fontsize=20,fontweight=500,backgroundcolor='white')
    ax.axhline(y=ymax*0.95, xmin=0.25, xmax=0.75,color='red',linewidth=2.4)
    ax.text(xmin+1,ymax*0.90,'%s"' % (round(clipSizeArcsec/2,1)) ,color="red",fontsize=12,fontweight=500,backgroundcolor='white')
    #pylab.axis("off")
    ax.set_axis_off()
    ax.grid(False, which="minor")
    ax.grid(False, which="majorminor") 
    pylab.savefig(outputFileName,format="png",dpi=dpi)	
    fig.clf()
    del ax,fig
    gc.collect()
Пример #7
0
def intensityCutImage(imageData, cutLevels):
    """Creates a matplotlib.pylab plot of an image array with the specified cuts in intensity
    applied. This routine is used by L{saveBitmap} and L{saveContourOverlayBitmap}, which both
    produce output as .png, .jpg, etc. images.
    
    @type imageData: numpy array
    @param imageData: image data array
    @type cutLevels: list
    @param cutLevels: sets the image scaling - available options:
        - pixel values: cutLevels=[low value, high value].
        - histogram equalisation: cutLevels=["histEq", number of bins ( e.g. 1024)]
        - relative: cutLevels=["relative", cut per cent level (e.g. 99.5)]
        - smart: cutLevels=["smart", cut per cent level (e.g. 99.5)]
    ["smart", 99.5] seems to provide good scaling over a range of different images.
    @rtype: dictionary
    @return: image section (numpy.array), matplotlib image normalisation (matplotlib.colors.Normalize), in the format {'image', 'norm'}.
    
    @note: If cutLevels[0] == "histEq", then only {'image'} is returned.
    
    """
    
    oImWidth=imageData.shape[1]
    oImHeight=imageData.shape[0]
                    
    # Optional histogram equalisation
    if cutLevels[0]=="histEq":
        
        imageData=histEq(imageData, cutLevels[1])
        anorm=pylab.normalize(imageData.min(), imageData.max())
        
    elif cutLevels[0]=="relative":
        
        # this turns image data into 1D array then sorts
        sorted=numpy.sort(numpy.ravel(imageData))	
        maxValue=sorted.max()
        minValue=sorted.min()
        
        # want to discard the top and bottom specified
        topCutIndex=len(sorted-1) \
            -int(math.floor(float((100.0-cutLevels[1])/100.0)*len(sorted-1)))
        bottomCutIndex=int(math.ceil(float((100.0-cutLevels[1])/100.0)*len(sorted-1)))
        topCut=sorted[topCutIndex]
        bottomCut=sorted[bottomCutIndex]
        anorm=pylab.normalize(bottomCut, topCut)
        
    elif cutLevels[0]=="smart":
        
        # this turns image data into 1Darray then sorts
        sorted=numpy.sort(numpy.ravel(imageData))	
        maxValue=sorted.max()
        minValue=sorted.min()
        numBins=10000 		# 0.01 per cent accuracy
        binWidth=(maxValue-minValue)/float(numBins)
        histogram=ndimage.histogram(sorted, minValue, maxValue, numBins)
        
        # Find the bin with the most pixels in it, set that as our minimum
        # Then search through the bins until we get to a bin with more/or the same number of
        # pixels in it than the previous one.
        # We take that to be the maximum.
        # This means that we avoid the traps of big, bright, saturated stars that cause
        # problems for relative scaling
        backgroundValue=histogram.max()
        foundBackgroundBin=False
        foundTopBin=False
        lastBin=-10000					
        for i in range(len(histogram)):
            
            if histogram[i]>=lastBin and foundBackgroundBin==True:
                
                # Added a fudge here to stop us picking for top bin a bin within 
                # 10 percent of the background pixel value
                if (minValue+(binWidth*i))>bottomBinValue*1.1:
                    topBinValue=minValue+(binWidth*i)
                    foundTopBin=True
                    break
            
            if histogram[i]==backgroundValue and foundBackgroundBin==False:
                bottomBinValue=minValue+(binWidth*i)
                foundBackgroundBin=True

            lastBin=histogram[i]
        
        if foundTopBin==False:
            topBinValue=maxValue
         
        #Now we apply relative scaling to this
        smartClipped=numpy.clip(sorted, bottomBinValue, topBinValue)
        topCutIndex=len(smartClipped-1) \
            -int(math.floor(float((100.0-cutLevels[1])/100.0)*len(smartClipped-1)))
        bottomCutIndex=int(math.ceil(float((100.0-cutLevels[1])/100.0)*len(smartClipped-1)))
        topCut=smartClipped[topCutIndex]
        bottomCut=smartClipped[bottomCutIndex]
        anorm=pylab.normalize(bottomCut, topCut)
    else:
        
        # Normalise using given cut levels
        anorm=pylab.normalize(cutLevels[0], cutLevels[1])
    
    if cutLevels[0]=="histEq":
        return {'image': imageData.copy()}
    else:
        return {'image': imageData.copy(), 'norm': anorm}
Пример #8
0
    ax_params.grid(1)
    ax_params.set_xlabel('mu')
    ax_params.set_ylabel('lambda')

    mymap = mpl.colors.LinearSegmentedColormap.from_list(
        'mycolors', ['blue', 'red'])

    for di, d in enumerate(chains):
        subsamp = 4
        s = np.array(d['scores'])[::subsamp]
        t = np.array(d['times'])[::subsamp] - d['times'][0]
        ax_score.plot(t, s, alpha=0.7, c='k')

        allscores.append(d['scores'])
    sm = pylab.cm.ScalarMappable(cmap=mymap,
                                 norm=pylab.normalize(vmin=1, vmax=5.0))
    sm._A = []
    ax_score.tick_params(axis='both', which='major', labelsize=6)
    ax_score.tick_params(axis='both', which='minor', labelsize=6)
    ax_score.set_xlabel('time (s)')
    ax_score.grid(1)
    all_s = np.hstack(allscores).flatten()
    #r = np.max(all_s) - np.min(all_s)
    #ax_score.set_ylim(np.min(all_s) + r*0.95, np.max(all_s)+r*0.05)

    bins = np.arange(1, 11)
    hist, _ = np.histogram(groupcounts, bins)

    ax_groups.bar(bins[:-1], hist)
    ax_groups.set_xlim(bins[0], bins[-1])