def run_bootstrap_correlations(Xs, Ys, num_perms, plot=False, verbose=False, permute=False):
# Returns the difference of correlation between X[1]*Y[1] - X[0]*Y[0] using bootstrap
    corrs = []
    pvals = []
    boot_corrs = []

    # need to define ahead of time the bootstrap indexes so we run the same ones for X[1] and X[0] (e.g. baseline and last)
    num_subjects = Xs[0].shape[0]
    boot_idx = np.random.random_integers(0, num_subjects-1, [num_perms, num_subjects])
    for X, Y in zip(Xs, Ys):
        corr = np.empty([X.shape[1], Y.shape[1]])
        pval = np.empty([X.shape[1], Y.shape[1]])
        for x in range(X.shape[1]):
            for y in range(Y.shape[1]):
                corr[x, y], pval[x, y] = stats.pearsonr(X[:, x], Y[:, y])

        corrs.append(corr)
        pvals.append(pval)

        if plot:
            plot_correlations(corr)
            pl.title('n=%d'%X.shape[0])
            pl.clim(-.2, .8)
            pl.draw()

        # checking p-values of the differences
        boot_res = do_bootstrapping(X, Y, num_perms, verbose, reuse_ids=boot_idx)
        boot_corrs.append(boot_res)

    dcorr = boot_corrs[1] - boot_corrs[0]

    return (corrs, pvals, dcorr)
示例#2
0
    def plot_onereg(self, regid):
        """Plot mintime of connectivity for one individual region"""
        tomat = self.llat * np.nan
        for i,v in enumerate(self.mintmat[1:,regid]):
            tomat[self.regmat==(i+1)] = v
        frmat = self.llat * np.nan
        for i,v in enumerate(self.mintmat[regid,1:]):
            frmat[self.regmat==(i+1)] = v
        djtk,lim = djdticks(max(np.nanmax(tomat), np.nanmax(frmat)))
        figpref.current()
        pl.close(1)
        fig = pl.figure(1,(8,8))
        pl.clf()
        pl.suptitle("Connectivity for region %i" % regid)

        mask = self.regmat == regid
        x,y = self.gcm.mp(self.llon[mask], self.llat[mask])
        pl.subplots_adjust(hspace=0, top=0.95,bottom = 0.15)

        pl.subplot(2,1,1, axisbg="0.8")
        self.gcm.pcolor(frmat, cmap=WRY(), rasterized=True)
        pl.clim(0,lim)
        self.gcm.mp.text(70,60,'Time from region')
        self.gcm.mp.scatter(x,y,5,'b')

        pl.subplot(2,1,2, axisbg="0.8")
        self.gcm.pcolor(tomat, cmap=WRY(), rasterized=True)
        pl.clim(0,lim)
        self.gcm.mp.text(70,60,'Time to region')
        self.gcm.mp.scatter(x,y,5,'b')

        if 'mycolor' in sys.modules:
            mycolor.freecbar([0.2,0.12,0.6,0.025], djtk, cmap=WRY())
        pl.savefig('figs/onereg_%02i_%02i_%06i.png' %
                   (self.regdi, self.regdj, regid))
示例#3
0
    def drawplot(self, dates, hrs, observability):
        """Generate the observability figure.

        """
        if self.dt == 0:
            ylabel = 'UTC Time'
        else:
            ylabel = 'UTC +{}'.format(self.dt)

        observer = ephem.Observer()
        ddates = []
        for d in dates:
            observer.date = str(d)
            ddates.append(observer.date.datetime())

        fig = py.figure()
        axpos = [.1, .12, .77, .76]
        ax = py.subplot(111, position=axpos)
        py.contourf(ddates, hrs, observability, cmap=py.cm.Greens)
        py.clim(0, 1.5)
        months = mdates.MonthLocator()  # every month
        ax.xaxis.set_major_locator(months)
        hfmt = ddates.DateFormatter('%b ')
        ax.xaxis.set_major_formatter(hfmt)
        yt = np.array([0, 4, 8, 12, 16, 20, 24])

        title = '%s: RA = %s, DEC = %s\nalt > %1.1f, sun < -%1.1f' % \
            (self.obs, str(self.ra), str(self.dec), self.minElev, self.twilight)
        ax.set_title(title, fontsize=self.fs * 1.2)
        ax.set_yticks(yt)
        ax.yaxis.set_ticks(range(25), minor=True)
        ax.set_yticklabels(yt % 24)
        ax.set_ylabel(ylabel, fontsize=self.fs)
        ax.grid(axis='x')

        ax2 = py.twinx()
        ax2.set_position(axpos)
        yt2 = np.arange(-24, 24, 3)
        yt2 = yt2[(yt2 >= dt) * (yt2 <= (24 + dt))]
        ax2.set_ylim(dt, 24 + dt)
        ax2.set_yticks(yt2)
        ax2.set_ylabel('Local Time: UTC %+1.1f' % dt, fontsize=fs)
        ax2.grid(axis='y')

        tlabs = yt2 % 12
        tlabs = []
        for yt in yt2:
            if (yt % 24) == 12:
                lab = 'noon'
            elif (yt % 24) == 0:
                lab = 'mdnt'
            elif (yt % 24) >= 12:
                lab = '%i pm' % (yt % 12)
            else:
                lab = '%i am' % (yt % 12)
            tlabs.append(lab)
        ax2.set_yticklabels(tlabs)
        ax2.yaxis.set_ticks(range(dt, dt + 25), minor=True)

        self.fig = fig
示例#4
0
    def movie(self):
        import matplotlib as mpl
        mpl.rcParams['axes.labelcolor'] = 'white'
        pl.close(1)
        pl.figure(1, (8, 4.5), facecolor='k')
        miv = np.ma.masked_invalid
        figpref.current()
        jd0 = pl.date2num(dtm(2005, 1, 1))
        jd1 = pl.date2num(dtm(2005, 12, 31))
        mp = projmaps.Projmap('glob')
        x, y = mp(self.llon, self.llat)
        for t in np.arange(jd0, jd1):
            print pl.num2date(t)
            self.load(t)

            pl.clf()
            pl.subplot(111, axisbg='k')
            mp.pcolormesh(x,
                          y,
                          miv(np.sqrt(self.u**2 + self.v**2)),
                          cmap=cm.gist_heat)
            pl.clim(0, 1.5)
            mp.nice()
            pl.title(
                '%04i-%02i-%02i' % (pl.num2date(t).year, pl.num2date(t).month,
                                    pl.num2date(t).day),
                color='w')
            pl.savefig('/Users/bror/oscar/norm/%03i.png' % t,
                       bbox_inches='tight',
                       facecolor='k',
                       dpi=150)
示例#5
0
def plot_figs():
    pylab.subplot(221, aspect="equal")
    X, Y = pylab.meshgrid(list(range(ins.num_atoms)), list(range(ins.num_atoms)))
    pylab.pcolor(X, Y, ins.norm_cross_correlation)
    pylab.colorbar()
    pylab.clim(-0.15, 0.15)
    pylab.title("Cross Correlations")

    pylab.subplot(222)
    pylab.plot(pdb_Bfactors, "bo-", label="ex.")
    pylab.plot(ins.Bfactors, "ro-", label="calc.")
    pylab.legend()
    pylab.xlabel("Residue")
#    pylab.ylabel("a.u.")
    pylab.title("B factors")
    pylab.grid()

    pylab.subplot(223, aspect="equal")
    X, Y = pylab.meshgrid(list(range(ins.num_atoms)), list(range(ins.num_atoms)))
    pylab.pcolor(X, Y, ins.adj_mat)
    pylab.colorbar()
    pylab.title("Adjacency Mat.")

    pylab.subplot(224)
    pylab.plot(ins.graph_eigvec[:, 1], "go-")
    pylab.xlabel("Residue")
    pylab.grid()

    pylab.show()
示例#6
0
def draw_astar_graph(obs_map, graph):
    """Debugging function which will show the current state of the m*
    graph
    """
    # Draw the obstacles
    pylab.hold(False)
    sizex = len(obs_map)
    sizey = len(obs_map[0])
    pylab.plot([-.5, sizex - .5, sizex - .5, -.5, -.5],
               [-.5, -.5, sizey - .5, sizey - .5, -.5], 'k')
    pylab.hold(True)
    pylab.matshow((1 - numpy.array(obs_map)).T, fignum=0)
    pylab.gray()
    pylab.clim(-2, 1)
    # Assemble the quiver
    X, Y, U, V = [[] for i in xrange(4)]
    for node in graph.graph.itervalues():
        x, y = node.coord
        u, v = map(lambda w, v: w - v, node.policy, node.coord)
        X.append(x)
        Y.append(y)
        U.append(u)
        V.append(v)
    pylab.quiver(X, Y, U, V)
    pylab.xlim([-.5, sizex - .5])
    pylab.ylim([-.5, sizey - .5])
    pylab.xticks([])
    pylab.yticks([])
    pylab.hold(False)
    pylab.show()
def plot_pairwise_corrcoef(data,ranklist=range(16,24),title="Correlation Coefficient"):
    array_byAttribRankRange=[]
    for attrib in attribList:
        array_byAttribRankRange.append(get_byAttribRankRange(data, attrib=attrib, ranklist=ranklist))
    Narray = len(array_byAttribRankRange)

    array_corrcoef=np.zeros((Narray,Narray),dtype='float')
    for i,elemi in enumerate(array_byAttribRankRange[::-1]):
        for j,elemj in enumerate(array_byAttribRankRange[::-1]):
            if i>j:
                    continue
            elif i==j:
                array_corrcoef[i,j]=1
            else:
                array_corrcoef[i,j]=np.corrcoef(elemi,elemj)[0,1]

    P.pcolor(np.transpose(array_corrcoef), cmap=P.cm.RdBu, alpha=0.8)
    P.title(title)
    P.xlim([0,23])
    P.ylim([0,23])
    P.clim([-1,1])
    P.xticks(range(len(attribList)), attribListAbrv[::-1],rotation='vertical')
    P.yticks(range(len(attribList)), attribListAbrv[::-1])
    P.subplots_adjust(bottom=0.35)
    P.subplots_adjust(left=0.25)
    P.colorbar()
    return array_corrcoef
示例#8
0
 def movie(self):
     import matplotlib as mpl
     mpl.rcParams['axes.labelcolor'] = 'white'
     pl.close(1)
     pl.figure(1,(8,4.5),facecolor='k')
     miv = np.ma.masked_invalid
     figpref.current()
     jd0 = pl.date2num(dtm(2005,1,1))
     jd1 = pl.date2num(dtm(2005,12,31))
     mp = projmaps.Projmap('glob')
     x,y = mp(self.llon,self.llat)
     for t in np.arange(jd0,jd1):
         print pl.num2date(t)
         self.load(t)
     
         pl.clf()
         pl.subplot(111,axisbg='k')
         mp.pcolormesh(x,y,
                       miv(np.sqrt(self.u**2 +self.v**2)),
                       cmap=cm.gist_heat)
         pl.clim(0,1.5)
         mp.nice()
         pl.title('%04i-%02i-%02i' % (pl.num2date(t).year,
                                      pl.num2date(t).month,
                                      pl.num2date(t).day),
                  color='w')
         pl.savefig('/Users/bror/oscar/norm/%03i.png' % t,
                    bbox_inches='tight',facecolor='k',dpi=150)
def plot_preds_orient(weights, plt_num=[1, 1, 1]):
    orients = ['Mean Horiz', 'Mean Vert', 'Mean Diag', 'Mean Diag 2']
    ax = plt.subplot(plt_num[0], plt_num[1], plt_num[2])
    x = 7
    mid = x / 2
    vals_hor = np.zeros([x, x])
    vals_ver = np.zeros([x, x])
    vals_diag = np.zeros([x, x])    
    delta = (mid / 2)
    vals_hor[mid, [mid - delta, mid + delta]] = 1
    vals_ver[[mid - delta, mid + delta], mid] = 1
    x, y = np.diag_indices_from(vals_diag)
    vals_diag[x[mid - delta], y[mid - delta]] = 1
    vals_diag[x[mid + delta], y[mid + delta]] = 1
    vals_diag2 = np.array(zip(*vals_diag[::-1])) 
    
#    delta = mid - mid / 2
#    vals_hor[mid, [mid - delta, mid + delta]] = 1
#    vals_ver[:, mid] = 1
#    np.fill_diagonal(vals_diag, 1)
#    np.fill_diagonal(vals_diag2, 1)
#    vals_diag2 = np.array(zip(*vals_diag2[::-1]))
    
    dat = (vals_hor * weights[0] + vals_ver * weights[1] + vals_diag
           * weights[2] + vals_diag2 * weights[3])
    dat = reverse_fft(dat)
    ext = mid
    _ = plt.imshow(dat, cmap=colors.CoolWarm,
                    interpolation='bilinear',
               extent=(-ext, ext, -ext, ext))
    ylims = np.array([0, np.abs(dat).max()])
    plt.clim(ylims)
    plt.colorbar()
    
    adjust_spines(ax, [])
示例#10
0
def plot_color_map_2d( data,  interpolation = None, limits = None, 
                       axis_labels = None, title = None, show = False ):
    """
    interpolation = None will default to using interpolation
    interpolation = 'none' will ensure no interpolation is performed
    """
    assert data.ndim == 2
    p = pylab.imshow( data, interpolation = interpolation )
    fig = pylab.gcf()
    pylab.clim()   # clamp the color limits
    pylab.colorbar() # add color bar to indicate scale
    
    if limits is not None:
        xlim = limits[:2]
        ylim = limits[2:]

        num_ticks = 11

        M, N = data.shape
        xticks = numpy.linspace( 0, M-1, num_ticks )
        yticks = numpy.linspace( 0, N-1, num_ticks )
        
        pylab.xticks( xticks, numpy.linspace( xlim[0], xlim[1], num_ticks ) )
        pylab.yticks( yticks, numpy.linspace( ylim[0], ylim[1], num_ticks ) )

    if axis_labels is not None:
        p.set_xlabel( axis_labels[0] )
        p.set_ylabel( axis_labels[1] )

    if title is not None:
        pylab.title( title )

    if show:
        pylab.show()
示例#11
0
文件: mrstools.py 项目: wk1984/gimli
def showqtresultfit(thk, wc, t2, datvec, resp, t,
                    islog=True, clim=None, nu=3, nv=2):
    ''' show mrs qt result and data fit
    showqtresultfit(thk,wc,t2,datvec,resp,t,islog=True,clim=None,nu=3,nv=2)
    '''
    if clim is None:
        cma = max(datvec)
        cmi = min(datvec)
        if islog:
            cma = N.log10(cma)
            cmi = cma - 1.5
        clim = (cmi, cma)

    nt = len(t)
    nq = len(datvec) / nt
    si = (nq, nt)

#    P.clf()
#    P.subplot(nu,nv,1)

    fig = P.figure(1)
    ax1 = fig.add_subplot(nu, nv, 1)

    draw1dmodel(wc, thk, islog=False, xlab=r'$\theta$')
#    P.subplot(nu,nv,3)
    ax3 = fig.add_subplot(nu, nv, 3)
    draw1dmodel(t2, thk, xlab='T2* in ms')
    ax3.set_xticks( [0.02, 0.05, 0.1, 0.2, 0.5] )
    ax3.set_xticklabels( ('0.02', '0.05', '0.1', '0.2', '0.5') )
#    P.subplot(nu,nv,2)
    ax2 = fig.add_subplot(nu, nv, 2)
    if islog:
        P.imshow(N.log10( N.array(datvec).reshape(si) ),
                 interpolation='nearest', aspect='auto')
    else:
        P.imshow(N.array(datvec).reshape(si),
                 interpolation='nearest', aspect='auto')
    P.clim(clim)
#    P.subplot(nu,nv,4)
    ax4 = fig.add_subplot(nu, nv, 4)
    if islog:
        P.imshow(N.log10(resp.reshape(si)),
                 interpolation='nearest',aspect='auto')
    else:
        P.imshow(resp.reshape(si),
                 interpolation='nearest',aspect='auto')
    misfit = N.array( datvec - resp )
    P.clim(clim)
#    P.subplot(nu,nv,5)
    ax5 = fig.add_subplot(nu, nv, 5)
    P.hist(misfit, bins=30)
    P.axis('tight')
    P.grid(which='both')
    P.text(P.xlim()[0], N.mean( P.ylim() ),
           ' std=%g nV' % rndig( N.std(misfit), 3 ) )
#    P.subplot(nu,nv,6)
    ax6 = fig.add_subplot(nu, nv, 6)
    P.imshow(misfit.reshape(si), interpolation='nearest', aspect='auto')
    ax = [ ax1, ax2, ax3, ax4, ax5, ax6 ]
    return ax
示例#12
0
def plotLayerwiseStates(states, idx=None):

    from utils.mscfuncs import imagesc
    import pylab

    if idx == None:
        idx = range(len(states))

    mx = 0.
    for i in idx:
        mx = numpy.max([states[i].X.max(), mx])

    handle_lst = []
    for i in idx:
        handle_lst.append(pylab.figure())

        for lay in range(states[0].X.shape[2]):
            ax = pylab.subplot(3, 3, lay + 1)
            imagesc(states[i].X[:, :, lay])
            pylab.title(
                'layer %s (%d) (t=%1.3fs)' %
                (states[i].layers[states[i].layeridx[lay]], lay, states[i].t),
                fontsize=8)
            pylab.clim([0, mx])
            pylab.setp(ax, 'xticklabels', [])
            pylab.setp(ax, 'yticklabels', [])

    return handle_lst
示例#13
0
    def __call__(self, n):
        if len(self.f.shape) == 3:
            # f = f[x,v,t], 2 dim in phase space
            ft = self.f[n,:,:]
            pylab.pcolormesh(self.X, self.V, ft.T, cmap = 'jet')
            pylab.colorbar()
            pylab.clim(0,0.38) # for Landau test case
            pylab.grid()
            pylab.axis([self.xmin, self.xmax, self.ymin, self.ymax])
            pylab.xlabel('$x$', fontsize = 18)
            pylab.ylabel('$v$', fontsize = 18)
            pylab.title('$N_x$ = %d, $N_v$ = %d, $t$ = %2.1f' % (self.x.N, self.v.N, self.it*self.t.width))
            pylab.savefig(self.path + self.filename)
            pylab.clf()
            return None

        if len(self.f.shape) == 2:
            # f = f[x], 1 dim in phase space
            ft = self.f[n,:]
            pylab.plot(self.x.gridvalues,ft,'ob')
            pylab.grid()
            pylab.axis([self.xmin, self.xmax, self.ymin, self.ymax])
            pylab.xlabel('$x$', fontsize = 18)
            pylab.ylabel('$f(x)$', fontsize = 18)
            pylab.savefig(self.path + self.filename)
            return None
    def plot_shear_stress_grid(self, grid):
        '''
            This method must follow a call to the flow_across_grid() method
            and requires the instance of the raster grid which was created
            when the DEM is read in.
            
            Shear stress is calculated at each interior node, to correspond with
            where water depths are calculated (interior nodes).
            This takes that node vector, converts it into a raster.
            
            Presently, all nodes the colorbar is blocked at intervals of ten, using
            the following function call:
                
                >>> cmap = plt.get_cmap('Spectral', 10)
                
            To change the interval at which color blocks are set, the value of 10 can
            be changed.
            
            To specify a particular range of shear stress values, the following call
            can be added to the function. Say we want the low values on the color bar to start at 10
            and increase to 100, which is currently the default setting:
                
                >>> pylab.clim(vmin=10, vmax=100)
                
            The colorbar is plotted using a blocked color map like those found here:
            http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps
            The Spectral map has small values starting at shades of pink while increasing
            values go over the color spectrum from orange, to yellow, to green, to blue and
            purple as the values increase.
            '''
        # First we create a new figure window to plot within
        plt.figure('Shear Stress raster')

        # And then we convert the shear stress node vector to raster format
        tn = grid.node_vector_to_raster(self.tau)

        # This call selects the color map and interval which it will be blocked by
        cmap = plt.get_cmap('Spectral', 10)

        # This sets the minimum on the color bar, anything beneath the lower clim() value is set to white.
        cmap.set_under('white')

        # Creating the grid image to show
        im2 = pylab.imshow(tn,
                           cmap=cmap,
                           extent=[
                               0, grid.number_of_node_columns * grid.dx, 0,
                               grid.number_of_node_rows * grid.dx
                           ])

        # Creating the colorbar for the grid image
        cb = pylab.colorbar(im2)

        # Sets the minimum and maximum values for the colorbar.
        pylab.clim(vmin=10, vmax=100)

        # Set titles for the figure and colorbar.
        cb.set_label('Shear Stress (Pa)', fontsize=12)
        pylab.title('Shear Stress')
        plt.show()
示例#15
0
def plot_tilt_freq(axis, tiltfft, axis_ev, label=None, ori='V', if_log=0):
    tiltfft = tiltfft / tiltfft.max()
    tiltfft = tiltfft + 1e-30
    if ori == 'V':
        alabel = 'y'
    else:
        alabel = 'x'
    title = 'spatial spectrum at ' + label
    if if_log == 1:
        tiltfft = np.log(tiltfft)
        title = title + ', log'
    plt.imshow(tiltfft,
               cmap='jet',
               extent=[
                   axis_ev.max(),
                   axis_ev.min(),
                   axis.min() * 1e6,
                   axis.max() * 1e6
               ])
    plt.colorbar()
    if if_log == 1:
        cmin = np.max(tiltfft) - 10
        plt.clim(cmin)
    plt.axis('tight')
    plt.title(title, fontsize=18)
    plt.xlabel('eV', fontsize=18)
    plt.ylabel(alabel + r'($\mu$m)', fontsize=18)
示例#16
0
def plot_modes_6(filename,modes=[0,1,2,3,49,499]):
    assert(len(modes)==6) 
    X = numpy.load(filename)
    evecs = X['evecs']
    print evecs.shape

    N = int( numpy.sqrt(evecs.shape[0]) )

    pylab.figure(figsize=(7,10))
    for i in range(6):
        evec = evecs[:,modes[i]]
        pylab.subplot(321+i)
        pylab.imshow(evec.reshape((N,N)),
                     origin='lower',
                     cmap=pylab.cm.RdGy,
                     extent=(0,60,0,60) )

        pylab.title('n=%i' % (modes[i]+1))
        pylab.colorbar()
        cmax = numpy.max(abs(evec))
        pylab.clim(-cmax,cmax)
        pylab.xlabel('arcmin')
        
        if i%2 == 1:
            pylab.gca().yaxis.set_major_formatter(NullFormatter())
        else:
            pylab.ylabel('arcmin')
示例#17
0
def saveslices3d(img, clim, title):
    '''Saves a single PNG image of 3D image array img, equalizes colormap with
    list object clim and saves it under filename title.'''
    nslices = img.shape[2]
    axis = np.ceil(math.sqrt(nslices))
    fig = pl.figure(num=None, figsize=(10, 6), dpi=80)
    fig.suptitle(title, fontsize=14)
    for n in range(nslices):
        if axis != 1:
            pl.subplot(axis - 1,
                       axis + 1,
                       n + 1,
                       frameon=False,
                       xticks=[],
                       yticks=[])
        else:
            pl.subplot(1, 1, n + 1, frameon=False, xticks=[], yticks=[])
        pl.imshow(rotateslice(img[:, :, n]), interpolation='nearest')
        stitle = "Slice %r" % (n + 1)
        pl.clim(clim)
        cb = pl.colorbar(shrink=.75,
                         ticks=range(0, int(round(clim[1])),
                                     int(round(clim[1])) / 4))
        for t in cb.ax.get_yticklabels():
            t.set_fontsize(8)
        pl.xlabel(stitle, fontsize=8)
    pl.tight_layout()
    pl.savefig(title + '.png', bbox_inches=0)
示例#18
0
def plotConn():
    # Create plot
    figh = figure(figsize=(8,6))
    figh.subplots_adjust(left=0.02) # Less space on left
    figh.subplots_adjust(right=0.98) # Less space on right
    figh.subplots_adjust(top=0.96) # Less space on bottom
    figh.subplots_adjust(bottom=0.02) # Less space on bottom
    figh.subplots_adjust(wspace=0) # More space between
    figh.subplots_adjust(hspace=0) # More space between
    h = axes()
    totalconns = zeros(shape(f.connprobs))
    for c1 in range(size(f.connprobs,0)):
        for c2 in range(size(f.connprobs,1)):
            for w in range(f.nreceptors):
                totalconns[c1,c2] += f.connprobs[c1,c2]*f.connweights[c1,c2,w]*(-1 if w>=2 else 1)
    imshow(totalconns,interpolation='nearest',cmap=bicolormap(gap=0))

    # Plot grid lines
    hold(True)
    for pop in range(f.npops):
        plot(array([0,f.npops])-0.5,array([pop,pop])-0.5,'-',c=(0.7,0.7,0.7))
        plot(array([pop,pop])-0.5,array([0,f.npops])-0.5,'-',c=(0.7,0.7,0.7))

    # Make pretty
    h.set_xticks(range(f.npops))
    h.set_yticks(range(f.npops))
    h.set_xticklabels(f.popnames)
    h.set_yticklabels(f.popnames)
    h.xaxis.set_ticks_position('top')
    xlim(-0.5,f.npops-0.5)
    ylim(f.npops-0.5,-0.5)
    clim(-abs(totalconns).max(),abs(totalconns).max())
    colorbar()
示例#19
0
def plotWeightChanges():
    if f.usestdp:
        # create plot
        figh = figure(figsize=(1.2*8,1.2*6))
        figh.subplots_adjust(left=0.02) # Less space on left
        figh.subplots_adjust(right=0.98) # Less space on right
        figh.subplots_adjust(top=0.96) # Less space on bottom
        figh.subplots_adjust(bottom=0.02) # Less space on bottom
        figh.subplots_adjust(wspace=0) # More space between
        figh.subplots_adjust(hspace=0) # More space between
        h = axes()

        # create data matrix
        wcs = [x[-1][-1] for x in f.allweightchanges] # absolute final weight
        wcs = [x[-1][-1]-x[0][-1] for x in f.allweightchanges] # absolute weight change
        pre,post,recep = zip(*[(x[0],x[1],x[2]) for x in f.allstdpconndata])
        ncells = int(max(max(pre),max(post))+1)
        wcmat = zeros([ncells, ncells])

        for iwc,ipre,ipost,irecep in zip(wcs,pre,post,recep):
            wcmat[int(ipre),int(ipost)] = iwc *(-1 if irecep>=2 else 1)

        # plot
        imshow(wcmat,interpolation='nearest',cmap=bicolormap(gap=0,mingreen=0.2,redbluemix=0.1,epsilon=0.01))
        xlabel('post-synaptic cell id')
        ylabel('pre-synaptic cell id')
        h.set_xticks(f.popGidStart)
        h.set_yticks(f.popGidStart)
        h.set_xticklabels(f.popnames)
        h.set_yticklabels(f.popnames)
        h.xaxif.set_ticks_position('top')
        xlim(-0.5,ncells-0.5)
        ylim(ncells-0.5,-0.5)
        clim(-abs(wcmat).max(),abs(wcmat).max())
        colorbar()
 def plot_discharge(self,grid):
     """This plots discharge across the raster"""
  
     grid._setup_active_inlink_and_outlink_matrices()
     outlink = grid.node_active_outlink_matrix
     inlink = grid.node_active_inlink_matrix
     outlink1 = outlink.tolist()
     inlink1 =inlink.tolist()
     newin0, newout0 = change_signs(inlink1[0], outlink1[0])
     newin1, newout1 = change_signs(inlink1[1], outlink1[1])
     in0 = np.array(newin0)
     in1 = np.array(newin1)
     out0 = np.array(newout0)
     out1 = np.array(newout1)
     self.q_node = self.q[in0]+self.q[in1]+self.q[out0]+self.q[out1] #((q[outlink[1]] -q[inlink[1]]))#+((q[outlink[0]]-(q[inlink[0]])))
     fixed_q = grid.zeros(centering='node')
     for each in self.interior_nodes:
         fixed_q[each] = self.q_node[each]
     plt.figure('DISCHARGE')
     hr = grid.node_vector_to_raster(fixed_q)
     palette = pylab.cm.RdYlBu
     im2 = pylab.imshow(hr, cmap=palette, extent=[0, grid.number_of_node_columns *grid.dx,0, grid.number_of_node_rows * grid.dx])
     pylab.clim(vmin=0.000001)#, mx)
     palette.set_under('w', 0.000001)
     cb = pylab.colorbar(im2)
     cb.set_label('DISCHARGE (m)', fontsize=12)
     pylab.title('DISCHARGE')
     plt.show()
示例#21
0
def plot_tilt(axis, tilt, axis_t, label=None, ori='V', if_log=0):
    tilt = tilt / tilt.max()
    tilt = tilt + 1e-30
    if ori == 'V':
        alabel = 'y'
    else:
        alabel = 'x'
    title = 'wavefront tilt at ' + label
    if if_log == 1:
        tilt = np.log(tilt)
        title = title + ', log'
    plt.imshow(tilt,
               cmap='jet',
               extent=[
                   axis_t.max() * 1e15,
                   axis_t.min() * 1e15,
                   axis.max() * 1e6,
                   axis.min() * 1e6
               ])
    plt.colorbar()
    if if_log == 1:
        cmin = np.max(tilt) - 10
        plt.clim(cmin)
    plt.axis('tight')
    plt.title(title, fontsize=18)
    plt.xlabel('time (fs)', fontsize=18)
    plt.ylabel(alabel + r' ($\mu$m)', fontsize=18)
示例#22
0
def transect(x, y, z, x0, y0, x1, y1, plots=0):
    #convert coord to pixel coord
    d0 = sqrt((x - x0)**2 + (y - y0)**2)
    i0 = d0.argmin()
    x0, y0 = unravel_index(i0, x.shape)
    #overwrite x0,y0

    d1 = plt.np.sqrt((x - x1)**2 + (y - y1)**2)
    i1 = d1.argmin()
    x1, y1 = unravel_index(i1, x.shape)
    #overwrite x1,y1
    #-- Extract the line...
    # Make a line with "num" points...
    length = int(plt.np.hypot(x1 - x0, y1 - y0))
    xi, yi = plt.np.linspace(x0, x1, length), plt.np.linspace(y0, y1, length)

    # Extract the values along the line
    #y is the first dimension and x is the second, row,col
    zi = z[xi.astype(plt.np.int), yi.astype(plt.np.int)]
    mz = nonaninf(z.ravel()).mean()
    sz = nonaninf(z.ravel()).std()
    if plots == 1:
        plt.matshow(z)
        plt.clim([mz - 2 * sz, mz + 2 * sz])
        plt.colorbar()
        plt.title('transect: (' + str(x0) + ',' + str(y0) + ') (' + str(x1) +
                  ',' + str(y1) + ')')
        plt.scatter(yi, xi, 5, c='r', edgecolors='none')
        plt.figure()
        plt.scatter(sqrt((xi - xi[0])**2 + (yi - yi[0])**2), zi)
        #plt.figure();plt.scatter(xi, zi)
        #plt.figure();plt.scatter(yi, zi)

    return (xi, yi, zi)
示例#23
0
def three_component_plot(c1, c2, c3, color, labels):
    pl.figure(figsize=(8,8))
    kwargs = dict(s=4, lw=0, c=color, vmin=2, vmax=6)
    ax1 = pl.subplot(221)
    pl.scatter(c1, c2, **kwargs)
    pl.ylabel('component 2')

    ax2 = pl.subplot(223, sharex=ax1)
    pl.scatter(c1, c3, **kwargs)
    pl.xlabel('component 1')
    pl.ylabel('component 3')

    ax3 = pl.subplot(224, sharey=ax2)
    pl.scatter(c2, c3, **kwargs)
    pl.xlabel('component 2')

    for ax in (ax1, ax2, ax3):
        ax.xaxis.set_major_formatter(ticker.NullFormatter())
        ax.yaxis.set_major_formatter(ticker.NullFormatter())

    pl.subplots_adjust(hspace=0.05, wspace=0.05)

    format = ticker.FuncFormatter(lambda i, *args: labels[i])
    pl.colorbar(ticks = range(2, 7), format=format,
                cax = pl.axes((0.52, 0.51, 0.02, 0.39)))
    pl.clim(1.5, 6.5)
示例#24
0
def plot_eigenmodes(evecs, evals, ax_list, mode_list, RArange, DECrange):
    """
    Plot KL eigenmodes associated with the COSMOS catalog
    """
    assert len(ax_list) == len(mode_list)

    NRA = len(RArange) - 1
    NDEC = len(DECrange) - 1

    for i in range(len(ax_list)):
        ax = ax_list[i]
        mode = mode_list[i]

        pylab.axes(ax)

        evec = evecs[:, i]

        pylab.imshow(
            evec.reshape((NRA, NDEC)).T,
            origin="lower",
            interpolation=None,  #'nearest',
            cmap=pylab.cm.RdGy,
            extent=(RArange[0], RArange[-1], DECrange[0], DECrange[-1]),
        )
        cmax = np.max(abs(evec))
        pylab.clim(-cmax, cmax)

        pylab.title(r"$\mathrm{mode\ %i}\ (v=%.3f)$" % (i + 1, evals[i]))

    return ax_list
示例#25
0
def main(argv):
    filename = argv[1]
    print filename
    data = np.loadtxt(filename)
    pl.imshow(data > 0.1)
    pl.title('natural')
    pl.figure()
    pl.imshow(data)
    pl.clim([-0.3, 0.3])
    pl.title('natural')
    pl.figure()
    pl.plot(data[50, :], 'b')
    pl.plot(data[:, 50], 'g')
    pl.ylim([-0.4, 0.4])
    pl.title('natural')

    pl.savefig(filename + ".linesamples.eps")

    pl.imsave(filename + ".gt0p1.png", data > 0.1)
    pl.imsave(filename + ".ltneg0p1.png", data < -0.1)
    pl.imsave(filename + ".data.png", data, vmin=-0.3, vmax=0.3)

    pl.show()

    exit()
示例#26
0
def transect(x,y,z,x0,y0,x1,y1,plots=0):
    #convert coord to pixel coord
    d0=sqrt( (x-x0)**2+ (y-y0)**2 );
    i0=d0.argmin();
    x0,y0=unravel_index(i0,x.shape); #overwrite x0,y0
    
    d1=plt.np.sqrt( (x-x1)**2+ (y-y1)**2 );
    i1=d1.argmin();
    x1,y1=unravel_index(i1,x.shape); #overwrite x1,y1    
    #-- Extract the line...    
    # Make a line with "num" points...
    length = int(plt.np.hypot(x1-x0, y1-y0))
    xi, yi = plt.np.linspace(x0, x1, length), plt.np.linspace(y0, y1, length) 
       
    # Extract the values along the line
    #y is the first dimension and x is the second, row,col
    zi = z[xi.astype(plt.np.int), yi.astype(plt.np.int)]
    mz=nonaninf(z.ravel()).mean()
    sz=nonaninf(z.ravel()).std()
    if plots==1:
        plt.matshow(z);plt.clim([mz-2*sz,mz+2*sz]);plt.colorbar();plt.title('transect: (' + str(x0) + ',' + str(y0) + ') (' +str(x1) + ',' +str(y1) + ')' );
        plt.scatter(yi,xi,5,c='r',edgecolors='none')
        plt.figure();plt.scatter(sqrt( (xi-xi[0])**2 + (yi-yi[0])**2 ) , zi)
        #plt.figure();plt.scatter(xi, zi)
        #plt.figure();plt.scatter(yi, zi)

    return (xi, yi, zi);
示例#27
0
def scatter_2D(x,
               y,
               t=None,
               cmap=pylab.cm.jet,
               clim=None,
               xlabel=None,
               ylabel=None,
               title=""):
    fig = pylab.figure()

    if t == None:
        cb = pylab.scatter(x, y, s=12.0, linewidths=0)
    else:
        cb = pylab.scatter(x, y, c=t, cmap=cmap, s=12.0, linewidths=0)

    if xlabel == None:
        xlabel = 'x'
    if ylabel == None:
        ylabel = 'y'

    pylab.xlabel(xlabel)
    pylab.ylabel(ylabel)
    pylab.title(title)

    pylab.colorbar(cb)

    if clim != None:
        pylab.clim(clim[0], clim[1])

    return fig
示例#28
0
文件: tools.py 项目: akr89/Thesis
def show_kappa(kappa,clabel=r'\kappa',part='r',clim=None,logplot=True):
    if part.lower()=='r':
        kappa = kappa.real
    elif part.lower()=='i':
        kappa = kappa.imag
    elif part.lower() in ['a','n']:
        kappa = abs(kappa)
    else:
        raise ValueError, "show_kappa : unrecognized part %s" % part
    
    pylab.figure(figsize=(14,9))

    if logplot:
        kappa = numpy.log(1+kappa)
    
    pylab.imshow(kappa.T,
                 origin = 'lower',
                 interpolation = 'nearest',
                 extent = params.RAlim+params.DEClim)
    cb = pylab.colorbar()
    if logplot:
        cb.set_label(r'$\rm{log}(1+%s)$' % clabel,
                     fontsize=14)
    else:
        cb.set_label(r'$%s$' % clabel,
                     fontsize=14)

    if clim is not None:
        pylab.clim(clim)
    
    pylab.xlabel('RA (deg)')
    pylab.ylabel('DEC (deg)')
    def plot_discharge(self, grid):
        """This plots discharge across the raster"""

        grid._setup_active_inlink_and_outlink_matrices()
        outlink = grid.node_active_outlink_matrix
        inlink = grid.node_active_inlink_matrix
        outlink1 = outlink.tolist()
        inlink1 = inlink.tolist()
        newin0, newout0 = change_signs(inlink1[0], outlink1[0])
        newin1, newout1 = change_signs(inlink1[1], outlink1[1])
        in0 = np.array(newin0)
        in1 = np.array(newin1)
        out0 = np.array(newout0)
        out1 = np.array(newout1)
        self.q_node = self.q[in0] + self.q[in1] + self.q[out0] + self.q[
            out1]  #((q[outlink[1]] -q[inlink[1]]))#+((q[outlink[0]]-(q[inlink[0]])))
        fixed_q = grid.zeros(centering='node')
        for each in self.interior_nodes:
            fixed_q[each] = self.q_node[each]
        plt.figure('DISCHARGE')
        hr = grid.node_vector_to_raster(fixed_q)
        palette = pylab.cm.RdYlBu
        im2 = pylab.imshow(hr,
                           cmap=palette,
                           extent=[
                               0, grid.number_of_node_columns * grid.dx, 0,
                               grid.number_of_node_rows * grid.dx
                           ])
        pylab.clim(vmin=0.000001)  #, mx)
        palette.set_under('w', 0.000001)
        cb = pylab.colorbar(im2)
        cb.set_label('DISCHARGE (m)', fontsize=12)
        pylab.title('DISCHARGE')
        plt.show()
示例#30
0
文件: rsa_fmri.py 项目: hanke/PyMVPA
def plot_mtx(mtx, labels, title):
    pl.figure()
    pl.imshow(mtx, interpolation='nearest')
    pl.xticks(range(len(mtx)), labels, rotation=-45)
    pl.yticks(range(len(mtx)), labels)
    pl.title(title)
    pl.clim((0,1))
    pl.colorbar()
示例#31
0
def rsa_result_plot(mtx, labels, title):
    pl.figure()
    pl.imshow(mtx, interpolation='nearest')
    pl.xticks(range(len(mtx)), labels, rotation=-45)
    pl.yticks(range(len(mtx)), labels)
    pl.title(title)
    pl.clim((0, 2))
    pl.colorbar()
示例#32
0
def plot_mtx(mtx, labels, title):
    pl.figure()
    pl.imshow(mtx, interpolation='nearest')
    pl.xticks(range(len(mtx)), labels, rotation=-90)
    pl.yticks(range(len(mtx)), labels)
    pl.title(title)
    pl.clim((0, 1))
    pl.colorbar()
示例#33
0
    def visualise_stamp(self,
                        i,
                        bands=['r', 'i'],
                        batch=0,
                        cmap='jet',
                        nstamp=0):
        psf = []
        gal = []
        mgal = []

        for band in bands:
            path1 = '%s/%c/galaxies-%d/' % (self.paths['cutouts'], band, batch)
            path1 = glob.glob(path1 + '%d-cutout-HSC-%c*.fits' %
                              (i, band.upper()))
            path1 = path1[0]

            ppath1 = '%s/%c/psf-%d/' % (self.paths['cutouts'], band, batch)
            ppath1 = glob.glob(ppath1 + '%d-psf-calexp*-HSC-%c*.fits' %
                               (i, band.upper()))
            ppath1 = ppath1[0]

            mpath1 = '%s/%c/galaxies-%d/' % (self.paths['cutouts'], band,
                                             batch)
            mpath1 = glob.glob(mpath1 + '%d-*masked*-HSC-%c*.fits' %
                               (i, band.upper()))
            mpath1 = mpath1[0]

            psf.append(fi.FITS(ppath1)[-1].read())
            gal.append(fi.FITS(path1)['IMAGE'].read())
            mgal.append(fi.FITS(mpath1)[-1].read())

        j = 1
        N = len(psf)
        gmax = gal[0].max()
        gmin = gal[0].min()
        mgmax = mgal[0].max()
        mgmin = mgal[0].min()
        for i, (p, g, masked) in enumerate(zip(psf, gal, mgal)):
            if nstamp > 0:
                x0 = g.shape[1] / 2
                y0 = g.shape[0] / 2
                dx = nstamp / 2
                dy = nstamp / 2

                g = g[y0 - dy:y0 + dy, x0 - dx:x0 + dx]
                masked = masked[y0 - dy:y0 + dy, x0 - dx:x0 + dx]
            plt.subplot(int('%d%d%d' % (N, 3, j)))
            plt.imshow(g, interpolation='none', cmap=cmap)
            plt.clim(mgmin, mgmax)
            print mgmin, mgmax
            j += 1
            plt.subplot(int('%d%d%d' % (N, 3, j)))
            plt.imshow(masked, interpolation='none', cmap=cmap)
            plt.clim(mgmin, mgmax)
            j += 1
            plt.subplot(int('%d%d%d' % (N, 3, j)))
            plt.imshow(p, interpolation='none', cmap=cmap)
            j += 1
示例#34
0
def plot_spectrogram(input_data,
                     windowfn=None,
                     channel_number=0,
                     filename=None,
                     coloraxis=None,
                     noverlap=0,
                     NFFT=None,
                     **kwargs):
    import pylab as pl

    if windowfn == None: windowfn = pl.window_hanning

    # look in the config file section Plots for NFFT = 1234
    # Dave - how about a method to allow this in one line
    # e.g. pyfusion.config.numgetdef('Plots','NFFT', 2048)
    # usage:
    # if (NFFT==None): NFFT = pyfusion.config.numgetdef('Plots','NFFT', 2048)
    #
    # also nice to have pyfusion.config.re-read()
    if NFFT == None:
        try:
            NFFT = (eval(pyfusion.config.get('Plots', 'NFFT')))
        except:
            NFFT = 2048

    pl.specgram(input_data.signal.get_channel(channel_number),
                NFFT=NFFT,
                noverlap=noverlap,
                Fs=input_data.timebase.sample_freq,
                window=windowfn,
                **kwargs)
    #accept multi or single channel data (I think?)

    if coloraxis != None: pl.clim(coloraxis)
    else:
        try:
            pl.clim(eval(pyfusion.config.get('Plots', 'coloraxis')))
        except:
            pass

    # look in the config file section Plots for a string like FT_Axis = [0,0.08,0,500]
    # don't quote
    try:
        pl.axis(eval(pyfusion.config.get('Plots', 'FT_Axis')))
    except:
        pass

    try:
        pl.title("%d, %s" % (input_data.meta['shot'],
                             input_data.channels[channel_number].name))
    except:
        pl.title("%d, %s" %
                 (input_data.meta['shot'], input_data.channels.name))

    if filename != None:
        pl.savefig(filename)
    else:
        pl.show()
示例#35
0
 def animate(i):
     im.set_array(data[i])
     if saturation is not None:
         saturate(saturation, im=im)
     else:
         plt.clim(clims)
     if label is not None:
         tx.set_text('{:2.0f} {:}'.format(label[i], label_caption))
     return [im]
示例#36
0
def output_plots(image_field, axis):
    arr = image_field.swapaxes(0, axis)
    for i in range(arr.shape[axis]):
        print i
        pylab.clf()
        pylab.imshow(arr[i,...], interpolation='nearest')
        pylab.colorbar()
        pylab.clim(image_field.min(), image_field.max())
        pylab.savefig("RT/image_%s_%04i.png" % (axis,i))
示例#37
0
def saltmovie(tr):
    mv = anim.Movie()
    ints = np.sort(np.unique(tr.ints))
    for i in ints[:40]:
        pl.pcolormesh(miv(tr.traj2grid('z',tr.jd==i)),cmap=cm.Paired)
        pl.clim(28,33)
        print i
        mv.image()
    mv.video(tr.projname+tr.casename+"_salt_mov.mp4")
示例#38
0
    def movie(self,fld,k=0,jd1=733342,jd2=733342+10):
        miv = np.ma.masked_invalid

        for n,jd in enumerate(np.arange(jd1,jd2,0.25)):
            self.load(fld,jd)
            pl.clf()
            pl.pcolormesh(miv(self.__dict__[fld][0,k,:,:]))
            pl.clim(-0.1,0.1)
            pl.savefig('%s_%05i.png' % (fld,n),dpi=150)
示例#39
0
文件: image.py 项目: quillan86/stmpy
 def animate(i):
     im.set_array(F[i].ravel())
     if saturation is not None:
         sp.saturate(saturation)
     else:
         plt.clim(clims)
     if label is not None:
         tx.set_text('{:2.0f} {:}'.format(label[i], label_caption))
     return [im]
示例#40
0
 def animate(i):
     im.set_array(data[i])
     if saturation is not None:
         saturate(saturation, im=im)
     else:
         plt.clim(clims)
     if label is not None:
         tx.set_text('{:2.1f} {:}'.format(label[i], label_caption))
     return [im]
示例#41
0
 def pcolor(self, field, jd=None):
     """Plot a map of a field using projmap"""
     self.add_mp()
     pl.clf()
     pl.subplot(111,axisbg='0.9')
     self.mp.pcolormesh(self.mpxll,self.mpyll,miv(field), cmap=GBRY())
     self.mp.nice()
     if jd: pl.title(pl.num2date(jd).strftime("%Y-%m-%d"))
     pl.clim(-10,10)
     pl.colorbar(aspect=40,shrink=0.95,pad=0,fraction=0.05)
示例#42
0
 def Bsf(self):
     if not hasattr(self, 'Br'):
         self.Bfeild()
     pl.streamplot(self.r,
                   self.z,
                   self.Br.T,
                   self.Bz.T,
                   color=self.Br.T,
                   cmap=pl.cm.RdBu)
     pl.clim([-1.5, 1.5])
示例#43
0
def plot_mtx(mtx, labels, title, skip=5):
    # little helper function to plot dissimilarity matrices
    # if using correlation-distance, we use colorbar range of [0,2]
    pl.figure()
    pl.imshow(mtx, interpolation='nearest')
    pl.xticks(range(len(mtx))[::skip], labels[::skip], rotation=90)
    pl.yticks(range(len(mtx))[::skip], labels[::skip])
    pl.title(title)
    pl.clim((0, 2))
    pl.colorbar()
示例#44
0
 def pcolor(self, field, jd=None):
     """Plot a map of a field using projmap"""
     self.add_mp()
     pl.clf()
     pl.subplot(111,axisbg='0.9')
     self.mp.pcolormesh(self.mpxll,self.mpyll,miv(field), cmap=GBRY())
     self.mp.nice()
     if jd: pl.title(pl.num2date(jd).strftime("%Y-%m-%d"))
     pl.clim(-10,10)
     pl.colorbar(aspect=40,shrink=0.95,pad=0,fraction=0.05)
示例#45
0
def interp(ps,intstart=6353):
    import figpref
    import projmaps
    figpref.current()
    
    ps.c.execute("SELECT distinct(ints) FROM casco__chlor_a " + 
                 "   WHERE intstart=%i" % intstart) 
    ints1,ints2 = ps.c.fetchall()

    sql = """SELECT t1.ntrac,t1.val,t2.val,p.x,p.y,p.ints
               FROM casco__chlor_a t1
               INNER JOIN casco__chlor_a t2 ON t1.ntrac=t2.ntrac
               INNER JOIN casco p ON t1.ntrac=p.ntrac
               WHERE t1.intstart=%i
                  AND t2.intstart=%i
                  AND p.intstart=%i
                  AND t1.ints=%i
                  AND t2.ints=%i;
                  """ % (intstart,intstart,intstart,ints1[0],ints2[0])
    ps.c.execute(sql)
    res = zip(*ps.c.fetchall())
    class trj: pass
    if len(res) > 0:
        for n,a in enumerate(['ntrac','t1val','t2val','x','y','ints']):
            trj.__dict__[a] = np.array(res[n])

    mask = (trj.ints.astype(np.float)/100-trj.ints/100)>0.5
    trj.ints[mask]=trj.ints[mask]+1
    tvec = np.unique(trj.ints)
    tvec = tvec[tvec<=ints2[0]]
    itvec = tvec-tvec.min()
    itvec = itvec.astype(np.float)/itvec.max()

    mp = projmaps.Projmap('casco')
    xl,yl = mp(ps.llon,ps.llat)
    for n,t in enumerate(tvec):
        fld = ps.cs.llat * 0
        cnt = ps.cs.llat * 0

        xvc = (trj.x[trj.ints==t].astype(np.int))
        yvc = (trj.y[trj.ints==t].astype(np.int))
        val = ( np.log(trj.t1val[trj.ints==t])*(1-itvec[n]) +
                np.log(trj.t2val[trj.ints==t])*(itvec[n]) )
        for x,y,v in zip(xvc,yvc,val):
            fld[y,x] += v
            cnt[y,x] += 1

        pl.clf()
        mp.pcolormesh(xl,yl,miv(fld/cnt))
        mp.nice()
        jd = (ps.base_iso +
              (float(t)-(intstart)/8*3600*24)/3600/24 + intstart/8) + 0.583
        pl.title(pl.num2date(jd).strftime("log(Chl) %Y-%m-%d %H:%M"))
        pl.clim(-2,2.5)
        pl.savefig("interp_%i_%03i.png" % (intstart,n), dpi=100)
示例#46
0
文件: plots.py 项目: dpretty/pyfusion
def plot_spectrogram(input_data, windowfn=None, units='kHz', channel_number=0, filename=None, coloraxis=None, noverlap=0,NFFT=None, **kwargs):
    import pylab as pl
    
    if windowfn == None: windowfn=pl.window_hanning

    # look in the config file section Plots for NFFT = 1234
    # Dave - how about a method to allow this in one line
    # e.g. pyfusion.config.numgetdef('Plots','NFFT', 2048)
    # usage:  
    # if (NFFT==None): NFFT = pyfusion.config.numgetdef('Plots','NFFT', 2048)
    # 
    # also nice to have pyfusion.config.re-read()
    if NFFT == None:
        try:
            NFFT=(int(pyfusion.config.get('Plots','NFFT')))
        except:
            NFFT = 2048

    print(NFFT)        
    if units.lower() == 'khz': ffact = 1000.
    else: ffact =1.        
    xextent=(min(input_data.timebase),max(input_data.timebase))

    pl.specgram(input_data.signal.get_channel(channel_number), NFFT=NFFT, noverlap=noverlap, Fs=input_data.timebase.sample_freq/ffact, window=windowfn, xextent=xextent, **kwargs)
    #accept multi or single channel data (I think?)
        
    if coloraxis != None: pl.clim(coloraxis)
    else:
        try:
            pl.clim(eval(pyfusion.config.get('Plots','coloraxis')))
        except:
            pass

    # look in the config file section Plots for a string like 
    # FT_Axis = [0,0.08,0,500e3]   don't quote
    try:
        #pl.axis(eval(pyfusion.config.get('Plots','FT_Axis')))
        # this is clumsier now we need to consider freq units.
        axt = eval(pyfusion.config.get('Plots','FT_Axis'))
        pl.axis([axt[0], axt[1], axt[2]/ffact, axt[3]/ffact])
    except:
        pass
    # but override X if we have zoomed in bdb
    if 'reduce_time' in input_data.history:
        pl.xlim(np.min(input_data.timebase),max(input_data.timebase))
        
    try:
        pl.title("%d, %s"%(input_data.meta['shot'], input_data.channels[channel_number].name))
    except:
        pl.title("%d, %s"%(input_data.meta['shot'], input_data.channels.name))
        
    if filename != None:
        pl.savefig(filename)
    else:
        pl.show()
示例#47
0
def interp(ps,intstart=6353):
    import figpref
    import projmaps
    figpref.current()
    
    ps.c.execute("SELECT distinct(ints) FROM casco__chlor_a " + 
                 "   WHERE intstart=%i" % intstart) 
    ints1,ints2 = ps.c.fetchall()

    sql = """SELECT t1.ntrac,t1.val,t2.val,p.x,p.y,p.ints
               FROM casco__chlor_a t1
               INNER JOIN casco__chlor_a t2 ON t1.ntrac=t2.ntrac
               INNER JOIN casco p ON t1.ntrac=p.ntrac
               WHERE t1.intstart=%i
                  AND t2.intstart=%i
                  AND p.intstart=%i
                  AND t1.ints=%i
                  AND t2.ints=%i;
                  """ % (intstart,intstart,intstart,ints1[0],ints2[0])
    ps.c.execute(sql)
    res = zip(*ps.c.fetchall())
    class trj: pass
    if len(res) > 0:
        for n,a in enumerate(['ntrac','t1val','t2val','x','y','ints']):
            trj.__dict__[a] = np.array(res[n])

    mask = (trj.ints.astype(np.float)/100-trj.ints/100)>0.5
    trj.ints[mask]=trj.ints[mask]+1
    tvec = np.unique(trj.ints)
    tvec = tvec[tvec<=ints2[0]]
    itvec = tvec-tvec.min()
    itvec = itvec.astype(np.float)/itvec.max()

    mp = projmaps.Projmap('casco')
    xl,yl = mp(ps.llon,ps.llat)
    for n,t in enumerate(tvec):
        fld = ps.cs.llat * 0
        cnt = ps.cs.llat * 0

        xvc = (trj.x[trj.ints==t].astype(np.int))
        yvc = (trj.y[trj.ints==t].astype(np.int))
        val = ( np.log(trj.t1val[trj.ints==t])*(1-itvec[n]) +
                np.log(trj.t2val[trj.ints==t])*(itvec[n]) )
        for x,y,v in zip(xvc,yvc,val):
            fld[y,x] += v
            cnt[y,x] += 1

        pl.clf()
        mp.pcolormesh(xl,yl,miv(fld/cnt))
        mp.nice()
        jd = (ps.base_iso +
              (float(t)-(intstart)/8*3600*24)/3600/24 + intstart/8) + 0.583
        pl.title(pl.num2date(jd).strftime("log(Chl) %Y-%m-%d %H:%M"))
        pl.clim(-2,2.5)
        pl.savefig("interp_%i_%03i.png" % (intstart,n), dpi=100)
 def plot_shear_stress_grid(self, grid):         
     '''
         This method must follow a call to the flow_across_grid() method
         and requires the instance of the raster grid which was created
         when the DEM is read in.
         
         Shear stress is calculated at each interior node, to correspond with
         where water depths are calculated (interior nodes).
         This takes that node vector, converts it into a raster.
         
         Presently, all nodes the colorbar is blocked at intervals of ten, using
         the following function call:
             
             >>> cmap = plt.get_cmap('Spectral', 10)
             
         To change the interval at which color blocks are set, the value of 10 can
         be changed.
         
         To specify a particular range of shear stress values, the following call
         can be added to the function. Say we want the low values on the color bar to start at 10
         and increase to 100, which is currently the default setting:
             
             >>> pylab.clim(vmin=10, vmax=100)
             
         The colorbar is plotted using a blocked color map like those found here:
         http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps
         The Spectral map has small values starting at shades of pink while increasing
         values go over the color spectrum from orange, to yellow, to green, to blue and
         purple as the values increase.
         '''
     # First we create a new figure window to plot within                                  
     plt.figure('Shear Stress raster')
     
     # And then we convert the shear stress node vector to raster format
     tn = grid.node_vector_to_raster(self.tau)
     
     # This call selects the color map and interval which it will be blocked by
     cmap=plt.get_cmap('Spectral', 10)
     
     # This sets the minimum on the color bar, anything beneath the lower clim() value is set to white.
     cmap.set_under('white')
     
     # Creating the grid image to show
     im2 = pylab.imshow(tn, cmap=cmap, extent=[0, grid.number_of_node_columns *grid.dx,0, grid.number_of_node_rows * grid.dx])
     
     # Creating the colorbar for the grid image
     cb = pylab.colorbar(im2)
     
     # Sets the minimum and maximum values for the colorbar.
     pylab.clim(vmin=10, vmax=100)
     
     # Set titles for the figure and colorbar.
     cb.set_label('Shear Stress (Pa)', fontsize=12)
     pylab.title('Shear Stress')
     plt.show()    
    def plot_water_depths(self, grid):
         '''
            This method must follow a call to either flow_at_one_node() or the
            flow_across_grid() methods and requires the instance of the raster
            grid which was created when the DEM is read in.
            
            Water depths are calculated at each interior node in both methods.
            This takes that node vector, converts it into a raster.
            
            Presently, all nodes with water depths less than 1 cm are considered to have
            no flow/no depth and are plotted as white in the raster, using the following call:
                
                >>>  palette.set_under('w', 0.01) 
              
            If this value is changed, the value in the pylab.clim()
            function MUST also be changed.
            
            Additionally, the maximum value for plotted water depths is 1 m,
            using the following call:
                
                >>> pylab.clim(0.01, 1)
                
            Changing the value of 1 will extend the colorbar to higher values.
            
            Depths are plotted using a continuous color map, like those
            found here: http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps
            The winter_r is simply a reverse of the winter colormap, so small values
            are shaded green while increasing values are shaded with increasingly dark
            shades of blue.
         '''
        
         plt.figure('Water Depth Raster')
         
         # This function takes the node vector and converts to a raster.
         hr = grid.node_vector_to_raster(self.h)
         
         # Setting color selections - this is a green to blue continuous colorbar
         palette = pylab.cm.winter_r
         
         # Anything beneath the float value in this argument is colored white.
         palette.set_under('w', 0.01) ## Hardcoded 1 cm min. depth.
         
         # Creates the grid image to show.
         im2 = pylab.imshow(hr, cmap=palette, extent=[0, grid.number_of_node_columns *grid.dx,0, grid.number_of_node_rows * grid.dx])
         
         # Sets the minimum and maximum values for the colorbar.
         pylab.clim(0.01, 1) # The left value or "min" must be equal to the value in the set_under() function call above. Currently
                            # hardcoded to 1 m. 
        # Creates the colorbar
         cb = pylab.colorbar(im2)

        # Labels for the colorbar and figure.
         cb.set_label('Water depth (m)', fontsize=12)
         pylab.title('Water depth')
         plt.show()
示例#50
0
    def plot_water_depths(self, grid):
         '''
            This method must follow a call to either flow_at_one_node() or the
            flow_across_grid() methods and requires the instance of the raster
            grid which was created when the DEM is read in.
            
            Water depths are calculated at each interior node in both methods.
            This takes that node vector, converts it into a raster.
            
            Presently, all nodes with water depths less than 1 cm are considered to have
            no flow/no depth and are plotted as white in the raster, using the following call:
                
                >>>  palette.set_under('w', 0.01) # doctest: +SKIP 
              
            If this value is changed, the value in the pylab.clim()
            function MUST also be changed.
            
            Additionally, the maximum value for plotted water depths is 1 m,
            using the following call:
                
                >>> pylab.clim(0.01, 1) # doctest: +SKIP
                
            Changing the value of 1 will extend the colorbar to higher values.
            
            Depths are plotted using a continuous color map, like those
            found here: http://wiki.scipy.org/Cookbook/Matplotlib/Show_colormaps
            The winter_r is simply a reverse of the winter colormap, so small values
            are shaded green while increasing values are shaded with increasingly dark
            shades of blue.
         '''
        
         plt.figure('Water Depth Raster')
         
         # This function takes the node vector and converts to a raster.
         hr = grid.node_vector_to_raster(self.h)
         
         # Setting color selections - this is a green to blue continuous colorbar
         palette = pylab.cm.winter_r
         
         # Anything beneath the float value in this argument is colored white.
         palette.set_under('w', 0.01) ## Hardcoded 1 cm min. depth.
         
         # Creates the grid image to show.
         im2 = pylab.imshow(hr, cmap=palette, extent=[0, grid.number_of_node_columns *grid.dx,0, grid.number_of_node_rows * grid.dx])
         
         # Sets the minimum and maximum values for the colorbar.
         pylab.clim(0.01, 1) # The left value or "min" must be equal to the value in the set_under() function call above. Currently
                            # hardcoded to 1 m. 
        # Creates the colorbar
         cb = pylab.colorbar(im2)

        # Labels for the colorbar and figure.
         cb.set_label('Water depth (m)', fontsize=12)
         pylab.title('Water depth')
         plt.show()
 def plot_shear_stress_grid(self, grid):                            
     plt.figure('Shear Stress raster')
     tn = grid.node_vector_to_raster(self.tau)
     cmap=plt.get_cmap('Spectral', 10)
     cmap.set_under('white')
     im2 = pylab.imshow(tn, cmap=cmap, extent=[0, grid.number_of_node_columns *grid.dx,0, grid.number_of_node_rows * grid.dx])
     cb = pylab.colorbar(im2)
     pylab.clim(vmin=10, vmax=100)
     cb.set_label('Shear Stress (Pa)', fontsize=12)
     pylab.title('Shear Stress')
     plt.show()    
示例#52
0
 def OnComputeOutput(self, e):
     plusl = self.im1array[:, :, 0, 0]
     negsl = self.im2array[:, :, 0, 0]
     self.subtr = ComputePercentDiff(plusl, negsl)
     #self.B0corrsubtr=CorrectB0(self.subtr, self.B0slice)
     outclim = [0, 5]
     figure, cb = plotGraph(self.subtr)
     pl.clim(outclim)
     cb.outline.set_linewidth(0.2)
     cb.ax.tick_params(size=1, labelsize=2, pad=0)
     self.OutputCanvas = FigureCanvas(self.window_6_pane_1, -1, figure)
def make_panel(image, color=cm.gray, zmin = None, zmax = None, pix_sz = 0.396):
    imshape_arcsec = np.array(image.shape)*pix_sz

    if zmin == None:
        zmin = np.min(image)
    if zmax == None:
        zmax = np.max(image)

    pl.imshow(image, cmap=color, interpolation = 'nearest', extent = (-imshape_arcsec[1]/2, imshape_arcsec[1]/2,-imshape_arcsec[1]/2, imshape_arcsec[1]/2), origin = 'lower')
    pl.clim(zmin,zmax)
    
    return zmin, zmax
 def test2(self):
     iqehist = hh.load(os.path.join(datadir, "V-iqe.h5"))
     newsqe = interp(iqehist, newE=np.arange(-50, 50, 1.))
     mask = dynamical_range_mask(newsqe, Ei=120)
     # plot
     if interactive:
         import pylab
         pylab.imshow(mask.T[::-1])
         pylab.clim(0, None)
         pylab.colorbar()
         pylab.show()
     return
 def plot_water_depths(self, grid):
      ''' This plots water depths across the raster. '''
      plt.figure('Water Depth Raster')
      hr = grid.node_vector_to_raster(self.h)
      palette = pylab.cm.winter_r
      palette.set_under('w', 0.01) ## right now these are hardcoded values. 
      im2 = pylab.imshow(hr, cmap=palette, extent=[0, grid.number_of_node_columns *grid.dx,0, grid.number_of_node_rows * grid.dx])
      pylab.clim(0.01, 1) ## hardcoded - need to think of something clever.
      cb = pylab.colorbar(im2)
      cb.set_label('Water depth (m)', fontsize=12)
      pylab.title('Water depth')
      plt.show()
示例#56
0
def read_data_doppler(filename='Off of Newton Exit 17.wav', Tp=0.25, fc=2590E6 ):
  FS,Y=readwav(filename)

  #constants 
  c = 3E8
  
  #radar parameters
  #Tp = 0.250  # (s) pulse time
  n = int(Tp*FS)   # number of samples per pulse
  print ['Number of samples per pulse:', n]
  #fc = 2590E6 # (Hz) Center frequency (connected VCO Vtune to +5)
  
  #the input appears to be inverted
  s = -1*Y[0] #Y[:,1]
  del Y
  
  #create doppler vs. time plot data set here
  #for ii =1:round(size(s,1)/N)-1
  nsif=int(round(s.shape[0]/n)-1)
  print ['nsif:', nsif]
  sif=N.zeros([nsif,n])
  for ii in xrange(0,nsif):
      sif[ii,:] = s[ii*n:(ii+1)*n]
      #sif(ii,:) = s(1+(ii-1)*N:ii*N)
       
  #subtract the average DC term here
  sif = sif-s.mean()       
  
  zpad = 8*n/2
  
  #doppler vs. time plot:
  v=dbv(N.fft.ifft(sif, zpad,1))
  v=v[:,0:v.shape[1]/2]
  mmax = v.max()
  #calculate velocity
  delta_f = N.linspace(0, FS, v.shape[1]) #(Hz) 
  wavelen=c/fc
  velocity = delta_f*wavelen/2.
  #calculate time
  time = N.linspace(0,Tp*v.shape[0],v.shape[0]) #(sec)

  #plot
  P.pcolormesh(velocity[0:512], time, v[:,0:512]-mmax, edgecolors = 'None')
  P.plt.gca().invert_yaxis()
  P.matshow(v[:,0:1024], extent=(velocity[0], velocity[1023], time[-1], time[0]))
  P.colorbar()
  P.clim([-40,0])  

  P.xlabel('Velocity (m/sec)')
  P.ylabel('time (sec)')    
  P.show();
  return v,velocity,time