示例#1
0
def plotDecisionBoundary(X, Y, scoreFn, values, title="", save_path=None):
    # Plot the decision boundary. For that, we will asign a score to
    # each point in the mesh [x_min, m_max]x[y_min, y_max].
    x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    h = max((x_max - x_min) / 200., (y_max - y_min) / 200.)
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                         np.arange(y_min, y_max, h))
    zz = np.array([scoreFn(x) for x in np.c_[xx.ravel(), yy.ravel()]])
    zz = zz.reshape(xx.shape)
    pl.figure()
    CS = pl.contour(xx,
                    yy,
                    zz,
                    values,
                    colors='cornflowerblue',
                    linestyles='solid',
                    linewidths=1)
    pl.clabel(CS, fontsize=9, inline=1)
    # Plot the training points
    pl.scatter(X[:, 0],
               X[:, 1],
               c=(1. - Y),
               s=50,
               cmap="coolwarm",
               marker=".",
               edgecolors="none")
    pl.title(title)

    if save_path:
        pl.savefig(save_path, format='pdf')

    pl.axis('tight')
示例#2
0
文件: show2.py 项目: ipbs/ipbs
def plotear(xi,yi,zi):
    # mask inner circle
    interior1 = sqrt(((xi+1.5)**2) + (yi**2)) < 1.0 
    interior2 = sqrt(((xi-1.5)**2) + (yi**2)) < 1.0
    zi[interior1] = ma.masked
    zi[interior2] = ma.masked
    p.figure(figsize=(16,10))
    pyplot.jet()
    max=2.8
    min=0.4
    steps = 50
    levels=list()
    labels=list()
    for i in range(0,steps):
	levels.append(int((max-min)/steps*100*i)*0.01+min)
    for i in range(0,steps/2):
	labels.append(levels[2*i])
    CSF = p.contourf(xi,yi,zi,levels,norm=colors.LogNorm())
    CS = p.contour(xi,yi,zi,levels, format='%.3f', labelsize='18')
    p.clabel(CS,labels,inline=1,fontsize=9)
    p.title('electrostatic potential of two spherical colloids, R=lambda/3',fontsize=24)
    p.xlabel('z-coordinate (3*lambda)',fontsize=18)
    p.ylabel('radial coordinate r (3*lambda)',fontsize=18)
    # add a vertical bar with the color values
    cbar = p.colorbar(CSF,ticks=labels,format='%.3f')
    cbar.ax.set_ylabel('potential (reduced units)',fontsize=18)
    cbar.add_lines(CS)
    p.show()
def plot_cost_func(data,
                   eq_idx,
                   mu_plot_step=0.1,
                   delta_plot_step=0.003,
                   number_of_contours=20,
                   mark_min_val=True):
    """
    Plot cost function generated from system of equations and marks minimum value in the grid.
    """
    mu_plot = np.arange(MIN_MU_VISUALIZATION,
                        MAX_MU_VISUALIZATION + mu_plot_step, mu_plot_step)
    delta_plot = np.arange(MIN_DELTA_VISUALIZATION, MAX_DELTA_VISUALIZATION,
                           delta_plot_step)
    MU, DELTA = np.meshgrid(mu_plot, delta_plot)
    vis_arr = np.zeros(MU.shape)
    for i in range(MU.shape[0]):
        for j in range(MU.shape[1]):
            vis_arr[i][j] = g((MU[i][j], DELTA[i][j]), data, eq_idx)
    im = plt.imshow(vis_arr, cmap=cm.RdBu)  # drawing the function
    print('vis_arr.shape:', vis_arr.shape)
    cset = contour(vis_arr, number_of_contours, linewidths=2, cmap=cm.Set2)
    clabel(cset, inline=True, fmt='%1.1f', fontsize=10)
    colorbar(im)
    plt.xlabel(r'$\mu$')
    plt.ylabel(r'$\delta$')
    print('Minimal value in plotting grid:', np.amin(vis_arr))
    # plot point we are looking for - point of function minimum
    if mark_min_val:
        delta_min_idx, mu_min_idx = divmod(vis_arr.argmin(), vis_arr.shape[1])
        plt.plot(mu_min_idx, delta_min_idx, 'wo')
    show()
示例#4
0
 def plot_thickness(self, levels, title):
     import pylab as plt
     cm = plt.contour(self.grid.x(), self.grid.y(),
                      self.geometry.ice_thickness.numpy(), levels=levels)
     plt.clabel(cm)
     plt.grid()
     plt.title(title)
示例#5
0
def graficaIntensidad(Z):

    'grafica curvas de nivel'

    #Se dibuja la funcion

    im = imshow(Z,cmap=cm.RdBu)

    

    #Se agrega el contorno de lineas con sus etiquetas

    cset = contour(Z,n.arange(-2.0,2.0,0.1),linewidths=2,cmap=cm.Set2)

    clabel(cset,inline=True,fmt='%1.1f',fontsize=10)

    

    #Se agrega la barra de colores a la derecha

    colorbar(im)



    show()
示例#6
0
def qplot(q):
	qpts = [Bra(coherent(x+y*1j)) for x in xs for y in ys]
	A = Matrix(gs, gs, [abs(a*q)**2 for a in qpts])
	conts = pylab.contour(xs, ys, A, colors='brown', alpha=0.5, linewidths=2)
	pylab.clabel(conts, **csty)
	pylab.axis([2-ext,2+ext,-ext,ext])
	pylab.axis('off')
示例#7
0
def plot_sat():
    global nan_index, sat_index, ns
    plt.figure(figsize=(12,5))
    plt.subplot(1,2,1)
    ax1 = plt.contourf(nan_index.T)
    plt.colorbar(ax1)
    ax = plt.gca()
    labels_x = ax.get_xticks().astype(int)
    labels_y = ax.get_yticks()
    lx, ly = set_ticks(labels_x,labels_y)
    ax.set_xticklabels(lx)
    ax.set_yticklabels(ly)
    plt.xlabel(r'$s_{init}$'+' entropy',fontsize=12)
    plt.ylabel(r'$q_t$ moisture',fontsize=12)
    plt.title('nan-index (1=qt*<0,0=qt*>0')
    plt.subplot(1,2,2)
    ax1 = plt.contourf(sat_index.T)
    ax2 = plt.contour(nan_index.T,'k',levels=[-1.0,1.0],linewidth=5)
#    ax3 = plt.contourf(nan_index, hatch="/")
#    ax3 = plt.fill(nan_index, fill=False, hatch='\\')
    plt.clabel(ax2,inline=1,fontsize=10)
    plt.colorbar(ax1)
    ax = plt.gca()
    labels_x = ax.get_xticks().astype(int)
    labels_y = ax.get_yticks()
    lx, ly = set_ticks(labels_x,labels_y)
    ax.set_xticklabels(lx)
    ax.set_yticklabels(ly)
    plt.xlabel(r'$s_{init}$'+' entropy',fontsize=12)
    plt.ylabel(r'$q_t$ moisture',fontsize=12)
    plt.title('sat-index (0=unsat,1=sat)')
    plt.savefig('figures/sat_index.png')
    plt.close()
示例#8
0
def plotContour(angles,freqs,mags,fig=-1,center=180,norm=False):

    if fig==-1:
        newFig = True
        print "making new figure"
        fig = lab.figure()
        ax = fig.add_subplot(111)
    else:
        newFig = False
        ax = fig.get_axes()[0]

    #the ytick labels should be around zero probably
    angles = np.array(angles,dtype=np.int) - center
    angles = np.array(angles,dtype=np.str)

    dFreq = freqs[1]-freqs[0]
    if norm:
        contours = (-20,-10,-6,-3,-1,-0.1)
        colors = ("lightgrey","silver","grey","red","black","green")
    else:
#    contours = (-20,-10,-6,-3,-0.1)
        contours = (-10,-3,0,3,6,9,12)
        colors = ("lightgrey","silver","grey","dimgrey","black","white","red")
    print "fart"
#    colors = ("lightgrey","silver","red","black","green")

    cs = ax.contour(freqs+dFreq/2.,angles,mags,contours,colors=colors)
    lab.clabel(cs, inline=1, fontsize=10)

    if newFig==False:
        fig.canvas.draw()
    else:
        fig.show()
示例#9
0
def plotSurface(pt, td, winds, map, stride, title, file_name):
    pylab.figure()
    pylab.axes((0.05, 0.025, 0.9, 0.9))

    u, v = winds

    nx, ny = pt.shape
    gs_x, gs_y = goshen_3km_gs
    xs, ys = np.meshgrid(gs_x * np.arange(nx), gs_y * np.arange(ny))   

    data_thin = tuple([ slice(None, None, stride) ] * 2)

    td_cmap = matplotlib.cm.get_cmap('Greens')
    td_cmap.set_under('#ffffff')
    pylab.contourf(xs, ys, td, levels=np.arange(40, 80, 5), cmap=td_cmap)
    pylab.colorbar()
    CS = pylab.contour(xs, ys, pt, colors='r', linestyles='-', linewidths=1.5, levels=np.arange(288, 324, 4))
    pylab.clabel(CS, inline_spacing=0, fmt="%d K", fontsize='x-small')
    pylab.quiver(xs[data_thin], ys[data_thin], u[data_thin], v[data_thin])

    drawPolitical(map, scale_len=75)

    pylab.suptitle(title)
    pylab.savefig(file_name)
    pylab.close()
    return
示例#10
0
def plotear(xi,yi,zi):
    # mask inner circle
    interior = sqrt((xi**2) + (yi**2)) < 1.0 
    zi[interior] = ma.zeros
    pylab.figure(figsize=(16,10))
    levels = [log(1e-9), log(5e-9), log(1e-8), log(5e-8), log(1e-7), log(5e-7), log(1e-6), log(5e-6), log(1e-5), log(5e-5), log(1e-4), log(2e-4), log(4e-4), log(8e-4), log(1.2e-3), log(2.4e-3), log(4.8e-3), log(9.6e-3)]
    matplotlib.rcParams['contour.negative_linestyle'] = 'solid'
    rc('text', usetex=True)
    scale = list()
    counter = 0
    labels = dict()
    for i in levels:
      scale.insert(counter,str(pow(e,i)))
      labels[levels[counter]] = scale[counter]
      counter = counter + 1
    matplotlib.rcParams['contour.negative_linestyle'] = 'solid'
    CS = pylab.contour(xi,yi,zi, levels, colors='black', lynestiles='solid')
    print str(labels)
    pylab.clabel(CS,levels[0::2], fmt=labels, fontsize=20, inline=1)
    #p.clabel(CS,levels[1::2], fmt={log(1e-9):'1e-9', log(5e-9):'5e-9', log(1e-8):'1e-8', log(5e-8):'5e-8', log(1e-7):'1e-7', log(5e-7):'5e-7', log(1e-6):'1e-6', log(5e-6):'5e-8', log(1e-5):'1e-5', log(5e-5):'5e-5', log(1e-4):'1e-4', log(2e-4):'2e-4', log(4e-4):'4e-4', log(8e-4):'8e-4', log(1.2e-3):'1.2e-3', log(2.4e-3):'2.4e-3', log(4.8e-3):'4.8e-3'}, fontsize=9, inline=1)
    pylab.xlim((-7.0,7.0))
    pylab.ylim((0, 7.0))
    pylab.title('iPBS absolute error', fontsize=25)
    pylab.xlabel(r'$\displaystyle z/\lambda_D$',fontsize=20)
    pylab.ylabel(r'$\displaystyle r/\lambda_D$',fontsize=20)
    #pylab.show()
    savefig('ipbs_abs_far')
    return xi, yi, zi
示例#11
0
    def plot(self):
        if self.X.shape[1] == 1:
            pb.figure()
            Xtest, xmin, xmax = GPy.util.plot.x_frame1D(self.X)
            mu, var = self._predict_raw(Xtest)

            #GPy.util.plot.gpplot(Xtest, mu, mu - 2*np.sqrt(var), mu + 2*np.sqrt(var))
            pb.plot(self.X, self.Y, 'kx', mew=1)
            pb.plot(Xtest,
                    0.5 * (1 + erf(mu / np.sqrt(2. * var))),
                    linewidth=2)
            pb.ylim(-.1, 1.1)
        elif self.X.shape[1] == 2:
            pb.figure()
            Xtest, xx, yy, xymin, xymax = GPy.util.plot.x_frame2D(self.X)
            p = self.predict(Xtest)
            c = pb.contour(xx,
                           yy,
                           p.reshape(*xx.shape), [0.1, 0.25, 0.5, 0.75, 0.9],
                           colors='k')
            pb.clabel(c)
            i1 = self.Y == 1
            pb.plot(self.X[:, 0][i1], self.X[:, 1][i1], 'rx', mew=2, ms=8)
            i2 = self.Y == 0
            pb.plot(self.X[:, 0][i2], self.X[:, 1][i2], 'wo', mew=2, mec='b')
示例#12
0
def plot_pairwise_contours(theta,nuvec,Cinv,lvls=(2.291,6.158,11.618)):
    """
    > theta is a (3,) vector that contains the model parameters
    > thetavecs is a (n,3) matrix that contains the values of the parameters 
        that will be plotted over
    """
    labels = ['A','nu0','sigma']
    fisher = fisher_matrix(theta,nuvec,Cinv)
    Finv = n.linalg.inv(fisher)
    thetavecs = n.zeros((50,theta.shape[0]))
    for ii in range(theta.shape[0]):
        thetavecs[:,ii] = n.linspace(theta[ii]-5*n.sqrt(Finv[ii,ii]),theta[ii]+5*n.sqrt(Finv[ii,ii]),num=50)
    print thetavecs
    for ii,jj in ((0,1),(0,2),(1,2)):
        print ii,jj
        ts = thetavecs[:,[ii,jj]]
        print thetavecs.shape
        print ts.shape
        fs = fisher_select_pair(fisher,ii,jj)
        print fs.shape
        t0,t1 = n.meshgrid(ts[:,0],ts[:,1])
        print t0.shape

        Z = fs[0,0]*(t0-theta[ii])*(t0-theta[ii]) + (fs[0,1]+fs[1,0])*(t0-theta[ii])*(t1-theta[jj]) + fs[1,1]*(t1-theta[jj])*(t1-theta[jj])

        p.pcolor(t0,t1,Z)
        p.colorbar()
        CS = p.contour(t0,t1,Z,levels=lvls) #levels=lvls
        p.clabel(CS, inline=1, fontsize=10)
        #p.contour(t0,t1,Z,lvls)
        p.xlabel(labels[ii])
        p.ylabel(labels[jj])
        p.savefig('./figures/fisher/contours_{0}_{1}.pdf'.format(labels[ii],labels[jj]))
        p.clf()
def plotDecisionBoundary(X, Y, scoreFn, values, title=""):
    # Plot the decision boundary. For that, we will asign a score to
    # each point in the mesh [x_min, m_max]x[y_min, y_max].
    x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    h = max((x_max - x_min) / 200., (y_max - y_min) / 200.)
    xx, yy = meshgrid(arange(x_min, x_max, h), arange(y_min, y_max, h))
    zz = array([scoreFn(x) for x in c_[xx.ravel(), yy.ravel()]])
    zz = zz.reshape(xx.shape)
    pl.figure()
    CS = pl.contour(xx,
                    yy,
                    zz,
                    values,
                    colors='green',
                    linestyles='solid',
                    linewidths=2)
    pl.clabel(CS, fontsize=9, inline=1)
    # Plot the training points
    pl.scatter(X[:, 0], X[:, 1], c=(1. - Y), s=50, cmap=pl.cm.cool)
    pl.title(title)
    pl.xlabel(r'$x_1$')
    pl.ylabel(r'$x_2$')
    pl.legend(loc='best')
    pl.axis('tight')
    pl.show()
示例#14
0
def draw_bandstructure(
    jobname, kspace, band, ext=".csv", format="pdf", filled=True, levels=15, lines=False, labeled=False, legend=False
):
    # clf()
    fig = figure(figsize=fig_size)
    ax = fig.add_subplot(111, aspect="equal")
    x, y, z = loadtxt(jobname + ext, delimiter=", ", skiprows=1, usecols=(1, 2, 4 + band), unpack=True)
    if kspace.dimensions == 1:
        pylab.plot(x, y, z)
    elif kspace.dimensions == 2:
        xi = linspace(-0.5, 0.5, kspace.x_res)
        yi = linspace(-0.5, 0.5, kspace.y_res)
        zi = griddata(x, y, z, xi, yi)
        if filled:
            cs = ax.contourf(xi, yi, zi, levels, **contour_filled)
            legend and colorbar(cs, **colorbar_style)
            cs = lines and ax.contour(xi, yi, zi, levels, **contour_lines)
            labeled and lines and clabel(cs, fontsize=8, inline=1)
        else:
            cs = ax.contour(xi, yi, zi, levels, **contour_plain)
            legend and colorbar(cs, **colorbar_style)
            labeled and clabel(cs, fontsize=8, inline=1)
        ax.set_xlim(-0.5, 0.5)
        ax.set_ylim(-0.5, 0.5)
    savefig(jobname + format, format=format, transparent=True)
示例#15
0
文件: gosl.py 项目: yunpeng1/gosl
def Contour(X,Y,Z, label='', levels=None, cmapidx=0, colors=None, fmt='%g', lwd=1, fsz=10,
        inline=0, wire=True, cbar=True, zorder=None, markZero='', clabels=True):
    """
    Plot contour
    ============
    """
    L = None
    if levels != None:
        if not hasattr(levels, "__iter__"): # not a list or array...
            levels = linspace(Z.min(), Z.max(), levels)
    if colors==None:
        c1 = contourf (X,Y,Z, cmap=Cmap(cmapidx), levels=levels, zorder=None)
    else:
        c1 = contourf (X,Y,Z, colors=colors, levels=levels, zorder=None)
    if wire:
        c2 = contour (X,Y,Z, colors=('k'), levels=levels, linewidths=[lwd], zorder=None)
        if clabels:
            clabel (c2, inline=inline, fontsize=fsz)
    if cbar:
        cb = colorbar (c1, format=fmt)
        cb.ax.set_ylabel (label)
    if markZero:
        c3 = contour(X,Y,Z, levels=[0], colors=[markZero], linewidths=[2])
        if clabels:
            clabel(c3, inline=inline, fontsize=fsz)
示例#16
0
文件: show_results.py 项目: ipbs/ipbs
def plotear(xi,yi,zi):
    # mask inner circle
    interior = sqrt((xi**2) + (yi**2)) < 5.0 
    zi[interior] = ma.zeros
    #exterior = sqrt((xi**2) + (yi**2)) > 25.0
    #zi[exterior] = ma.empty
    p.figure(figsize=(16,10))
    levels = [log(.75e-5), log(1.25e-4), log(2.5e-4), log(0.005), log(0.01), log(0.02), log(0.04), log(0.08), log(0.16), log(0.32), log(0.64)]
    scale = list()
    counter = 0
    for i in levels:
      scale.insert(counter, pow(e,i))
      counter = counter + 1
      #scale[i]=10^i
    #  scale[i] = pow(10,levels[i])
    #levels = [0.005, 0.01, 0.02, 0.04, 0.08, 0.16, 0.32, 0.64, 1.28, 2.56]
    #levels = [log(0.005), log(0.01), log(0.02),log(0.04), log(0.08), log(0.16), log(0.32), log(0.64), log(1.28), log(2.56)]
    #levels = [zi.min() , zi.max() , (zi.max()-zi.min())/10]
    #v = np.linspace(0., 1., 25, endpoint=True)
    #v = np.logspace(1e-8,1e-1, num=10, endpoint=True, base=2)
    #levels = (0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.)
    CSF = p.contourf(xi,yi,zi, levels, cmap=cm.jet)
    #CSF = p.contourf(xi,yi,zi)
    CS = p.contour(xi,yi,zi, levels)
    p.clabel(CS,levels, fmt={log(.75e-5):'hallo', log(1.25e-4):'3', log(2.5e-4):'4', log(0.005):'5', log(0.01):'6', log(0.02):'7', log(0.04):'8', log(0.08):'9', log(0.16):'10', log(0.32):'11', log(0.64):'12'})
    p.title('iPBS relative error')
    p.xlabel('x-coordinate',fontsize=12)
    p.ylabel('y-coordinate',fontsize=12)
    # add a vertical bar with the color values
    cbar = p.colorbar(CSF, ticks=levels, format='%g')
    cbar.ax.set_yticklabels(scale)
    cbar.ax.set_ylabel('Relative error in %',fontsize=12)
    cbar.add_lines(CS)
    p.show()
示例#17
0
def plot_T1_contour(model, metHb=0.005):
    """Given a model (defined according to fitting.py) will plot constant sO2 contours as a function of Hct for 
    a given esp (in seconds)"""
    Hct_full = np.arange(0.0, 1.01, 0.01)
    sO2_full = np.arange(-0.1, 1.1, 0.01)
    [Hct_mat, sO2_mat] = np.meshgrid(Hct_full, sO2_full)
    ij = itertools.product(range(Hct_mat.shape[0]), range(Hct_mat.shape[1]))
    R1_ans = np.zeros_like(Hct_mat)
    xx = np.zeros(3)
    for element in ij:
        xx = [Hct_mat[element], sO2_mat[element], metHb]
        R1_ans[element[0], element[1]] = model(xx)
    # plt.figure()
    #C = plt.contour(100*sO2_mat,1000/R1_ans,Hct_mat,np.arange(0.0,1.1,0.05),vmin=0,vmax=0.95,linewidths=1.5,cmap=matplotlib.cm.jet)
    C = plt.contour(100 * sO2_mat,
                    1000 / R1_ans,
                    Hct_mat,
                    np.r_[0:0.3:0.05, 0.3:1.1:0.1],
                    vmin=0,
                    vmax=0.95,
                    linewidths=1.5,
                    cmap=matplotlib.cm.jet)
    #C = plt.contour(Hct_mat,1000/R1_ans,sO2_mat,np.arange(-0.5,1.05,0.05),vmin=0,vmax=1.1,linewidths=1.5,cmap=matplotlib.cm.cool)
    plt.clabel(C,
               C.levels[::2],
               colors='k',
               inline=True,
               fmt="%0.2f",
               fontsize=14)
示例#18
0
def plot_T2_contour(esp, model):
    """Given a model (defined according to fitting.py) will plot constant sO2 contours as a function of Hct for 
    a given esp (in seconds)"""
    Hct_full = np.arange(0.0, 0.9, 0.005)
    sO2_full = np.arange(0.0, 1.1, 0.005)
    [Hct_mat, sO2_mat] = np.meshgrid(Hct_full, sO2_full)
    ij = itertools.product(range(Hct_mat.shape[0]), range(Hct_mat.shape[1]))
    R2_ans = np.zeros_like(Hct_mat)
    xx = np.zeros(3)
    for element in ij:
        xx = np.array([Hct_mat[element], sO2_mat[element], esp, 0.0])
        R2_ans[element[0], element[1]] = model(xx)
    # plt.figure()
    #C = plt.contour(Hct_mat,1000/R2_ans,100*sO2_mat,np.arange(0,110,10),vmin=0,vmax=110,linewidths=1.5,linestyles='solid',cmap=matplotlib.cm.jet)
    C = plt.contour(Hct_mat,
                    1000 / R2_ans,
                    100 * sO2_mat,
                    np.r_[0:40:20, 30:110:10],
                    vmin=0,
                    vmax=110,
                    linewidths=1.5,
                    linestyles='solid',
                    cmap=matplotlib.cm.cool)
    plt.clabel(C,
               C.levels[::2],
               colors='k',
               inline=True,
               fmt="%0.1f",
               fontsize=14)
示例#19
0
def main():
    zf = np.vectorize(z_function)
    find_extremum(1)
    x, y = np.arange(0.1, 7.0, 0.1), np.arange(0.1, 7.0, 0.1)
    X, Y = pl.meshgrid(x, y)
    Z = zf(X, Y, 1)
    im = pl.imshow(Z, cmap=pl.cm.RdBu)
    cset = pl.contour(Z, np.arange(21, 100, 10), linewidths=2, cmap=pl.cm.Set2)

    pl.clabel(cset, inline=True, fmt='%1.1f', fontsize=15)
    pl.colorbar(im)
    pl.title('z = x*y + 50/x + 20/y')
    pl.show()

    print()

    find_extremum(2)
    x, y = np.arange(0.1, 5.0, 0.1), np.arange(0.1, 5.0, 0.1)
    X, Y = pl.meshgrid(x, y)
    Z = zf(X, Y, 2)
    im = pl.imshow(Z, cmap=pl.cm.RdBu)
    cset = pl.contour(Z, np.arange(-10, 0, 1), linewidths=3, cmap=pl.cm.Set2)
    pl.clabel(cset, inline=True, fmt='%1.1f', fontsize=10)
    pl.colorbar(im)
    pl.title('z = x^2 + y^2 - 2*log(x) - 18*log(y)')
    pl.show()
    print()
    find_extremum(3)
def plot_ua_vvel(press):
    print("    %smb VVEL" % press)
    level = levid[str(press)]

    #Set Figure Size (1000 x 800)
    pylab.figure(figsize=(width, height), frameon=False)

    cdict_vvel = {
        'red': ((0.00, 0.50, 0.50), (0.10, 1.00, 1.00), (0.20, 1.00, 1.00),
                (0.35, 1.00, 1.00), (0.40, 1.00, 1.00), (0.45, 0.80, 0.80),
                (0.50, 0.72, 0.72), (0.55, 0.68, 0.68), (0.60, 0.64, 0.64),
                (0.65, 0.60, 0.70), (0.70, 0.40, 0.45), (0.80, 0.20, 0.20),
                (0.90, 0.00, 0.00), (1.00, 0.00, 0.00)),
        'green': ((0.00, 0.35, 0.35), (0.10, 0.45, 0.45), (0.20, 0.55, 0.55),
                  (0.35, 1.00, 1.00), (0.40, 1.00, 1.00), (0.45, 1.00, 1.00),
                  (0.50, 1.00, 1.00), (0.55, 1.00, 1.00), (0.60, 1.00, 1.00),
                  (0.65, 1.00, 1.00), (0.70, 1.00, 1.00), (0.80, 1.00, 1.00),
                  (0.90, 1.00, 1.00), (1.00, 0.80, 0.80)),
        'blue': ((0.00, 0.00, 0.00), (0.10, 0.00, 0.00), (0.20, 0.20, 0.20),
                 (0.35, 1.00, 1.00), (0.40, 1.00, 1.00), (0.45, 1.00, 1.00),
                 (0.50, 1.00, 1.00), (0.55, 1.00, 1.00), (0.60, 1.00, 1.00),
                 (0.65, 1.00, 1.00), (0.70, 1.00, 1.00), (0.80, 1.00, 1.00),
                 (0.90, 1.00, 1.00), (1.00, 0.80, 0.80))
    }

    vvel_coltbl = LinearSegmentedColormap('VVEL_COLTBL', cdict_vvel)

    vert_vel = np.multiply(w_wind_ua[time, level], 100)
    vert_vel = np.nan_to_num(vert_vel)

    VVEL = pylab.contourf(x,
                          y,
                          vert_vel,
                          vvel_clevs,
                          cmap=vvel_coltbl,
                          extend='both')

    # Contour the heights

    heights = hght_clevs[contlevid[str(press)]]
    phtotal = np.add(phb[time, level], ph[time, level])
    gheight = np.divide(phtotal, 9.81)
    #gheight = ght[time,level]

    HGHT = pylab.contour(x, y, gheight, heights, colors='k', linewidths=1.5)
    pylab.clabel(HGHT, inline=1, fontsize=8, fmt='%1.0f', inline_spacing=1)

    # Convert winds from m/s to kts and then draw barbs
    u_wind_kts = u_wind_ms_ua[time, level] * 1.94384449
    v_wind_kts = v_wind_ms_ua[time, level] * 1.94384449


    pylab.barbs(x_th,y_th,u_wind_kts[::thin,::thin],\
     v_wind_kts[::thin,::thin], length=5, sizes={'spacing':0.2},pivot='middle')

    title = '%s mb VVel, Height (m), Wind (kts)' % press
    prodid = '%smb_vert_vel' % press
    units = "cm/s"

    drawmap(VVEL, title, prodid, units)
示例#21
0
def plotSurface(pt, td, winds, map, stride, title, file_name):
    pylab.figure()
    pylab.axes((0.05, 0.025, 0.9, 0.9))

    u, v = winds

    nx, ny = pt.shape
    gs_x, gs_y = goshen_3km_gs
    xs, ys = np.meshgrid(gs_x * np.arange(nx), gs_y * np.arange(ny))

    data_thin = tuple([slice(None, None, stride)] * 2)

    td_cmap = matplotlib.cm.get_cmap('Greens')
    td_cmap.set_under('#ffffff')
    pylab.contourf(xs, ys, td, levels=np.arange(40, 80, 5), cmap=td_cmap)
    pylab.colorbar()
    CS = pylab.contour(xs,
                       ys,
                       pt,
                       colors='r',
                       linestyles='-',
                       linewidths=1.5,
                       levels=np.arange(288, 324, 4))
    pylab.clabel(CS, inline_spacing=0, fmt="%d K", fontsize='x-small')
    pylab.quiver(xs[data_thin], ys[data_thin], u[data_thin], v[data_thin])

    drawPolitical(map, scale_len=75)

    pylab.suptitle(title)
    pylab.savefig(file_name)
    pylab.close()
    return
def plot_ua_rhum(press):
    print("    %smb RHUM" % press)
    level = levid[str(press)]

    #Set Figure Size (1000 x 800)
    pylab.figure(figsize=(width, height), frameon=False)
    heights = hght_clevs[contlevid[str(press)]]

    cdict = {
        'red': ((0.00, 0.76, 0.76), (0.25, 0.64, 0.64), (0.50, 0.52, 0.52),
                (0.75, 0.42, 0.42), (1.00, 0.32, 0.32)),
        'green': ((0.00, 0.90, 0.90), (0.25, 0.80, 0.80), (0.50, 0.70, 0.70),
                  (0.75, 0.60, 0.60), (1.00, 0.50, 0.50)),
        'blue': ((0.00, 0.49, 0.49), (0.25, 0.32, 0.32), (0.50, 0.17, 0.17),
                 (0.75, 0.06, 0.06), (1.00, 0.05, 0.05))
    }

    rhum_coltbl = LinearSegmentedColormap('RHUM_COLTBL', cdict)

    # Temperature calculation here

    #TC = temps_ua[time,level] - 273
    TH_K = np.add(temps_ua[time, level], temps_base_ua)
    TK = np.multiply(TH_K, math.pow((float(press) / 1000.), (287.04 / 1004.)))
    TC = TK - 273

    # RHUM Calculation here
    es = 6.112 * np.exp(17.67 * TC / (TC + 243.5))
    w = np.divide(qvap[time, level], (1 - qvap[time, level]))
    e = (w * float(press)) / (0.622 + w)
    relh = e / es * 100.

    RHUM = pylab.contourf(x,
                          y,
                          relh,
                          rhum_clevs,
                          extend='max',
                          cmap=rhum_coltbl)

    # Contour the heights

    phtotal = np.add(phb[time, level], ph[time, level])
    gheight = np.divide(phtotal, 9.81)
    #gheight = ght[time,level]
    HGHT = pylab.contour(x, y, gheight, heights, colors='k', linewidths=1.5)
    pylab.clabel(HGHT, inline=1, fontsize=8, fmt='%1.0f', inline_spacing=1)

    # Convert winds from m/s to kts and then draw barbs
    u_wind_kts = u_wind_ms_ua[time, level] * 1.94384449
    v_wind_kts = v_wind_ms_ua[time, level] * 1.94384449


    pylab.barbs(x_th,y_th,u_wind_kts[::thin,::thin],\
     v_wind_kts[::thin,::thin], length=5, sizes={'spacing':0.2},pivot='middle')

    title = '%s mb RELH, Height (m), Wind (kts)' % press
    prodid = '%smb_rel_hum' % press
    units = "percent"

    drawmap(RHUM, title, prodid, units)
示例#23
0
def plot_s(s_,sd_,sv_,sc_,name):
    global nan_index, ns, plt_count
    plt.figure(figsize=(20,5))
    plt.subplot(1,4,1)
    ax1 = plt.contourf(s_.T)
    ax2 = plt.contour(sd_.T+sc_.T,levels=[0.0],linewidths=2)
    plt.clabel(ax2, inline=1, fontsize=10)#, text=r'$\alpha$')
    ax3 = plt.contour(nan_index.T,levels=[-1.0,1.0],linewidths=1)
    plt.clabel(ax3, inline=1, fontsize=10)#, text=r'$\alpha$')
    plt.colorbar(ax1)
    ax = plt.gca()
    labels_x = ax.get_xticks().astype(int)
    labels_y = ax.get_yticks()
    lx, ly = set_ticks(labels_x,labels_y)
    ax.set_xticklabels(lx)
    ax.set_yticklabels(ly)
    plt.xlabel(r'$s_{init}$'+' entropy',fontsize=12)
    plt.ylabel(r'$q_t$ moisture',fontsize=12)
    plt.title(name +' (cont=sd+sc, nan_index)')
    plt.subplot(1,4,2)
    ax1 = plt.contourf(sd_.T)
    ax2 = plt.contour(nan_index.T,levels=[-1.0,1.0],linewidth=2)
    plt.clabel(ax2, inline=1, fontsize=10)#, text=r'$\alpha$')
    plt.colorbar(ax1)
    plt.xlabel(r'$s_{init}$'+' entropy',fontsize=12)
    plt.title('s dry (cont=nan-ind)')
    ax = plt.gca()
    labels_x = ax.get_xticks().astype(int)
    labels_y = ax.get_yticks()
    lx, ly = set_ticks(labels_x,labels_y)
    ax.set_xticklabels(lx)
    plt.subplot(1,4,3)
    ax1 = plt.contourf(sv_.T)
    ax2 = plt.contour(s_.T,levels=[-4e5,0.0],colors='k',linewidths=2)
    plt.clabel(ax2, inline=1, fontsize=10)#, text=r'$\alpha$')
    plt.colorbar(ax1)
    plt.title('s vap (cont=s1)',fontsize=15)
    plt.xlabel(r'$s_{init}$'+' entropy',fontsize=12)
    ax = plt.gca()
    labels_x = ax.get_xticks().astype(int)
    labels_y = ax.get_yticks()
    lx, ly = set_ticks(labels_x,labels_y)
    ax.set_xticklabels(lx)
    plt.subplot(1,4,4)
    ax1 = plt.contourf(sc_.T)
    ax2 = plt.contour(s_.T,levels=[-4e5,0.0],colors='k',linewidths=2)
    plt.clabel(ax2, inline=1, fontsize=10)#, text=r'$\alpha$')
    plt.colorbar(ax1)
    plt.title('s liquid (cont=s1)',fontsize=15)
    plt.xlabel(r'$s_{init}$'+' entropy',fontsize=12)
    ax = plt.gca()
    labels_x = ax.get_xticks().astype(int)
    labels_y = ax.get_yticks()
    lx, ly = set_ticks(labels_x,labels_y)
    ax.set_xticklabels(lx)
    plt.savefig('figures/'+str(plt_count)+'_s1.png')
    plt.close()
    plt_count += 1
    return
def _contourPlotFMeasure():
    delta = 0.01
    x = sc.arange(0., 1., delta)
    y = sc.arange(0., 1., delta)
    X, Y = sc.meshgrid(x, y)
    cs = pl.contour(X, Y, fmeasure, sc.arange(
        0.1, 1.0, 0.1))  # FIXME: make an array out of fmeasure first
    pl.clabel(cs, inline=1, fontsize=10)
示例#25
0
def contourf_raster(raster, **kwargs):
    Z = raster.asarray()
    Z = numpy.flipud(Z)
    extent = (raster.llcorner[0], raster.llcorner[0] + raster.extent[0],
              raster.llcorner[1], raster.llcorner[1] + raster.extent[1])
    C = pylab.contourf(Z, extent=extent, **kwargs)
    pylab.clabel(C)
    pylab.axis('scaled')
示例#26
0
def plot_contour(Z):    
    fig2 = plt.figure(2)
    im = pl.imshow(Z)
    cset = pl.contour(Z)
    pl.clabel(cset,inline=True)
    pl.colorbar(im)
    plt.title('Contour')
    return fig2
示例#27
0
    def draw(self):
        (self.coord, self.stats, title, showLegend) = self.inputPorts

        stds, corrs = self.stats.values[:, 0], self.stats.values[:, 1]
        self.Xs = stds * corrs
        self.Ys = stds * np.sin(np.arccos(corrs))

        colors = pylab.cm.jet(np.linspace(0, 1, len(self.stats.ids)))

        pylab.clf()
        fig = pylab.figure(str(self))
        dia = taylor_diagram.TaylorDiagram(stds[0],
                                           corrs[0],
                                           fig=fig,
                                           label=self.stats.labels[0])
        dia.samplePoints[0].set_color(
            colors[0])  # Mark reference point as a red star
        if self.stats.ids[0] in self.selectedIds:
            dia.samplePoints[0].set_markeredgewidth(3)

        # add models to Taylor diagram
        for i, (_id, stddev, corrcoef) in enumerate(
                zip(self.stats.ids[1:], stds[1:], corrs[1:])):
            label = self.stats.labels[i + 1]
            size = 3 if _id in self.selectedIds else 1
            dia.add_sample(
                stddev,
                corrcoef,
                marker='o',  #self.markers[i],
                ls='',
                mfc=colors[i + 1],
                mew=size,
                label=label)

        # Add grid
        dia.add_grid()

        # Add RMS contours, and label them
        contours = dia.add_contours(levels=5, colors='0.5')  # 5 levels in grey
        pylab.clabel(contours, inline=1, fontsize=10, fmt='%.1f')

        # Add a figure legend and title
        if showLegend:
            fig.legend(dia.samplePoints,
                       [p.get_label() for p in dia.samplePoints],
                       numpoints=1,
                       prop=dict(size='small'),
                       loc='upper right')
        fig.suptitle(title, size='x-large')  # Figure title
        self.figManager.canvas.draw()

        self.rectSelector = RectangleSelector(pylab.gca(),
                                              self.onselect,
                                              drawtype='box',
                                              rectprops=dict(
                                                  alpha=0.4,
                                                  facecolor='yellow'))
        self.rectSelector.set_active(True)
示例#28
0
def show_2D(X, Y, Z):
    fig = pl.figure()
    cs = pl.contour(X, Y, Z, 30)
    pl.clabel(cs, fmt='%.1f', colors="black")
    # Add a color bar which maps values to colors.
    fig.colorbar(cs, shrink=0.5, aspect=5)
    pl.plot(n)
    pl.show()
    return 0
示例#29
0
def plot_CC_all(T,pv_star_1,qv_star_1):
    global ns
    plt.figure(figsize=(20,5))
    plt.subplot(1,4,1)
    ax1 = plt.contourf(T.T,levels=np.linspace(0,500,250))
    ax2 = plt.contour(p0-pv_star_1.T)#,levels=[0.0])
    plt.ylabel(r'$q_t$'+' moisture',fontsize=12)
    plt.xlabel(r'$s$'+' entropy',fontsize=12)
    plt.title('temperature (no ql)',fontsize=15)
    plt.colorbar(ax1)
    ax = plt.gca()
    labels_x = ax.get_xticks().astype(int)
    labels_y = ax.get_yticks()
    lx, ly = set_ticks(labels_x,labels_y)
    ax.set_xticklabels(lx)
    ax.set_yticklabels(ly)
    plt.subplot(1,4,2)
    plt.contourf(pv_star_1.T)
    plt.xlabel(r'$s$'+' entropy',fontsize=12)
    plt.title('Magnus Formula: '+r'$p_{v,1}^*$',fontsize=15)
    plt.colorbar()
    ax = plt.gca()
    labels_x = ax.get_xticks().astype(int)
    labels_y = ax.get_yticks()
    lx, ly = set_ticks(labels_x,labels_y)
    ax.set_xticklabels(lx)
    ax.set_yticklabels(ly)
    plt.subplot(1,4,3)
    ax1 = plt.contourf(p0-pv_star_1.T)#,levels=np.linspace(-9e6,1e6))
    ax2 = plt.contour(p0-pv_star_1.T, levels = [0.0])
    plt.clabel(ax2,inline=1)
    plt.xlabel(r'$s$'+' entropy',fontsize=12)
    plt.title('p0-pv_star',fontsize=15)
    plt.colorbar(ax1)
    ax = plt.gca()
    labels_x = ax.get_xticks().astype(int)
    labels_y = ax.get_yticks()
    lx, ly = set_ticks(labels_x,labels_y)
    ax.set_xticklabels(lx)
    ax.set_yticklabels(ly)
    plt.subplot(1,4,4)
    ax1 = plt.contourf(qv_star_1.T,levels=np.linspace(-10,10,250))
    ax2 = plt.contour(qv_star_1.T,levels=[-1,0,1],linewidth=2,fontsize=6)
    plt.clabel(ax2,inline=1)
    plt.xlabel(r'$s$'+' entropy',fontsize=12)
    plt.title('qv_star_1',fontsize=15)
    plt.colorbar(ax1)
    ax = plt.gca()
    labels_x = ax.get_xticks().astype(int)
    labels_y = ax.get_yticks()
    lx, ly = set_ticks(labels_x,labels_y)
    ax.set_xticklabels(lx)
    ax.set_yticklabels(ly)
    plt.savefig('figures/3_CC_all_Magnus_firstguess.png')
    #    plt.close()
    return
示例#30
0
def runanalysis():
    filename = ourgui.openFile(type="npz")

    data = np.load(filename, mmap_mode="r")
    Y = data["Y"]
    Z = data["Z"]
    BY = data["BY"]
    BZ = data["BZ"]
    coilpos = getdata(data, "coilpos")
    coilwidth = getdata(data, "coilwidth")
    nturns = getdata(data, "nturns")
    coilsize = getdata(data, "coilsize")

    infopiece = []
    if coilpos:
        infopiece += ['Cpos: %g"' % coilpos]
    if coilwidth:
        infopiece += ['Cwidth: %g"' % coilwidth]
    if coilsize:
        infopiece += ['Csize: %g"' % coilsize]
    if nturns:
        infopiece += ["Turns: %d" % nturns]
    infotitle = ", ".join(infopiece)

    fig = pl.figure(figsize=(11.69, 8.27), dpi=100)
    fig.text(0.4, 0.95, infotitle)

    pl.subplot(2, 2, 1)
    pl.quiver(Z, Y, BZ, BY)
    pl.xlabel("Z")
    pl.ylabel("Y")
    pl.title("Magnetic field direction")

    pl.subplot(2, 2, 2)
    CS = pl.contour(Z, Y, BY / BZ)
    pl.xlabel("Z")
    pl.ylabel("Y")
    pl.title("Y-strength/Z-strength")
    pl.clabel(CS, inline=1, fontsize=10)

    pl.subplot(2, 2, 3)
    zpos = Z[:, 0]
    zfield = BZ[:, 0] / BZ[0, 0]
    pl.plot(zpos, zfield)
    pl.xlabel("Z position")
    pl.ylabel("On axis field strength")

    pl.subplot(2, 2, 4)
    fieldstrength = np.sqrt(BY ** 2 + BZ ** 2)
    CS = pl.contour(Z, Y, fieldstrength)
    pl.xlabel("Z")
    pl.ylabel("Y")
    pl.title("Field strength", fontsize=10)
    pl.clabel(CS, inline=1, fontsize=10)

    pl.show()
示例#31
0
def plot_gaussian(mu, var, epsilon=0.089881552536):
    """ IDK what is happening here and why I have to divide epsilon by 3. 
    """
    X1, X2 = np.meshgrid(np.linspace(0, 35), np.linspace(0, 35))
    Z = get_probability(np.array([X1.flatten(), X2.flatten()]).T, mu, var)
    Z = np.reshape(Z, X1.shape)
    # Z[Z<epsilon] = 0
    # Z[Z>epsilon] = 1
    c = contour(X1, X2, Z, levels=[epsilon], lw=3, label="Gaussian Boundary")
    clabel(c, inline=1, fmt='Epsilon=%3.5e', colors='k', fontsize=8)
示例#32
0
def Contour (X,Y,Z, label='', nlevels=None, cmapidx=0, fmt='%g', wire=True, cbar=True):
    L = None
    if nlevels!=None: L = linspace(Z.min(), Z.max(), nlevels)
    c1 = contourf (X,Y,Z, cmap=Cmap(cmapidx), levels=L)
    if wire:
        c2 = contour (X,Y,Z, nlevels=nlevels, colors=('k'), levels=L)
        clabel (c2, inline=0)
    if cbar:
        cb = colorbar (c1, format=fmt)
        cb.ax.set_ylabel (label)
示例#33
0
def plot_contour(name, l, a, Z, ax=None):
    if ax is None:
        fig = pb.figure(name)
        ax = fig.add_subplot(111)
    extent = [l.min(),l.max(),a.min(),a.max()]
    c = ax.contour(l,a,Z,colors='k', linestyles='solid')
    pb.clabel(c)
    ax.imshow(Z, extent=extent, origin='lower', interpolation='bilinear')
    ax.set_xlabel('$\log(l)$')
    ax.set_ylabel('$\log(a)$')
    ax.figure.tight_layout()    
示例#34
0
def pre_plot(m, x, y, xhgt, height_res):
    pylab.figure(figsize=(11.02, 8.27), dpi=72, frameon=True)
    m.drawcoastlines(linewidth=1.5, color='black')
    m.readshapefile('joklar/joklar', 'joklar', linewidth=1.5, color='black')
    m.drawparallels(np.arange(63., 67., .1), labels=[1, 0, 0, 0])
    m.drawmeridians(np.arange(-26., -12., .2), labels=[0, 0, 0, 1])
    m.drawmapscale(-15., 63.5, -19., 65., 100., barstyle='fancy', fontsize=12)
    iso = np.arange(height_res, 2300, height_res)
    cs = m.contour(x, y, xhgt, iso, colors='#808080', linewidths=0.5)
    pylab.clabel(cs, fmt='%1.0f', colors='#808080', inline=1, fontsize=10)
    return m
示例#35
0
def plot(cfg, raw: RegionAndWeights, lats: np.ndarray, lons: np.ndarray,
         hgts: np.ndarray, weighed: np.ndarray):
    # Crop domain shape vars to slightly larger than the weight matrix
    pad = 1
    j0 = raw.offset[0] - pad
    i0 = raw.offset[1] - pad
    j1 = j0 + raw.weight_grid.shape[0] + 2 * pad
    i1 = i0 + raw.weight_grid.shape[1] + 2 * pad
    crop_lats = lats[j0:j1, i0:i1]
    crop_lons = lons[j0:j1, i0:i1]
    crop_hgts = hgts[j0:j1, i0:i1]

    # Pad weighted data to same size as above
    padded = np.zeros(shape=crop_lats.shape)
    padded[pad:-pad, pad:-pad] = weighed

    # Setup basemap
    m = setup_basemap(crop_lats, crop_lons)
    xs, ys = m(crop_lons, crop_lats)

    # Create static plot parts
    pylab.figure(figsize=(12, 10), dpi=100, frameon=True)
    m.drawcoastlines(linewidth=1.5, color='black')
    m.readshapefile('joklar/joklar', 'joklar', linewidth=1.5, color='black')
    plot_title = cfg.accumulation_plot_title_pattern.format(
        simulation=cfg.simulation, region=raw.region)

    # Plot elevation contours lines
    iso = np.arange(0, 2300, 100)
    cs = m.contour(xs, ys, crop_hgts, iso, colors='#808080', linewidths=0.5)
    pylab.clabel(cs, fmt='%1.0f', colors='#808080', inline=1, fontsize=10)
    pylab.title(plot_title)

    # Plot precipitation
    m.contourf(xs, ys, padded, levels=LEVELS, colors=COLORS, extend='neither')
    cs = m.contour(xs, ys, padded, levels=LEVELS, colors=COLORS_CONTOURS)
    pylab.axes().clabel(cs,
                        inline=1,
                        fontsize=10,
                        fmt='%g',
                        colors=COLORS_LABELS)

    # Plot a dot for each simulation cell
    m.plot(xs, ys, '.', ms=0.5, color=(0, 0, 0, 0.5))

    # Write PNG and SVG files.
    for ext in ('png', 'svg'):
        plot_file = cfg.accumulation_plot_file_pattern.format(
            simulation=cfg.simulation, region=raw.region, ext=ext)
        print('\nsave', plot_file)
        pylab.savefig(plot_file, pad_inches=0.2, bbox_inches='tight')

    pylab.clf()
    pylab.close()
示例#36
0
def plot_all(n, gext, grid, data0, data1, g0, g1, gavg):
    Z = np.exp(g0)+np.exp(g1)
    eg0 = np.exp(g0)/Z
    eg1 = np.exp(g1)/Z
    err = np.minimum(eg0,eg1)
    err = err.reshape(-1,n)

    lx,hx,ly,hy = gext
    asp = float(hx-lx) / (hy-ly)
    alp = 1.0
    ms = 8

    p.figure()
    p.subplot(2,2,1)
    p.plot(data0[:,0], data0[:,1], 'g^',label='0', markersize=ms, alpha=alp)
    p.plot(data1[:,0], data1[:,1], 'ro',label='1', markersize=ms, alpha=alp)
    p.legend(fontsize=8, loc='best')
    #p.contour(gavg, extent=gext, aspect=1, origin='lower', cmap = p.cm.gray)
    #p.contour(gavg, [0.0], extent=gext, aspect=1, origin='lower', cmap = p.cm.gray)
    #p.imshow(gavg, extent=gext, aspect=1, origin='lower')
    #p.imshow(g0.reshape(-1,n), extent=gext, aspect=asp, origin='lower')
    #p.colorbar()
    p.contour(g0.reshape(-1,n), extent=gext, aspect=asp, origin='lower', cmap = p.cm.Greens)

    p.subplot(2,2,2)
    p.plot(data0[:,0], data0[:,1], 'g^',label='0', markersize=ms, alpha=alp)
    p.plot(data1[:,0], data1[:,1], 'ro',label='1', markersize=ms, alpha=alp)
    p.legend(fontsize=8, loc='best')
    #p.contour(g0.reshape(-1,n), extent=gext, aspect=1, origin='lower', cmap = p.cm.Greens)
    #p.contour(g1.reshape(-1,n), extent=gext, aspect=1, origin='lower', cmap = p.cm.Reds)
    #p.contour((g1-g0).reshape(-1,n), [0.0], extent=gext, aspect=1, origin='lower', cmap = p.cm.gray)
    #p.imshow((g1-g0).reshape(-1,n), extent=gext, aspect=1, origin='lower')
    #p.imshow(g1.reshape(-1,n), extent=gext, aspect=asp, origin='lower')
    #p.colorbar()
    p.contour(g1.reshape(-1,n), extent=gext, aspect=asp, origin='lower', cmap = p.cm.Reds)

    p.subplot(2,2,3)
    p.plot(data0[:,0], data0[:,1], 'g^',label='0', markersize=ms, alpha=alp)
    p.plot(data1[:,0], data1[:,1], 'ro',label='1', markersize=ms, alpha=alp)
    p.legend(fontsize=8, loc='best')
    #p.imshow(err, extent=gext, origin='lower', aspect=asp)
    #p.colorbar()
    p.contour((g1-g0).reshape(-1,n), [0.0], extent=gext, aspect=asp, origin='lower', cmap = p.cm.gray)
    #p.contour(eg0.reshape(-1,n), extent=gext, aspect=1, origin='lower', cmap = p.cm.Greens)
    #p.contour(eg1.reshape(-1,n), extent=gext, aspect=1, origin='lower', cmap = p.cm.Reds)

    p.subplot(2,2,4)
    p.plot(data0[:,0], data0[:,1], 'g^',label='0', markersize=ms)
    p.plot(data1[:,0], data1[:,1], 'ro',label='1', markersize=ms)
    p.legend(fontsize=8, loc='best')
    p.contour((g1-g0).reshape(-1,n), [0.0], extent=gext, aspect=asp, origin='lower', cmap = p.cm.gray)
    CS = p.contour(err, [0.4, 0.3, 0.2, 0.1, 0.05], extent=gext, aspect=asp, origin='lower')
    p.clabel(CS, inline=1, fontsize=10, aspect=asp)
    p.show()
示例#37
0
文件: util.py 项目: blastbao/arsenal
def contour_plot(f, xdomain, ydomain, color=True):
    "Contour plot of a function of two variables."
    [xmin, xmax, _] = xdomain; [ymin, ymax, _] = ydomain
    X, Y = np.meshgrid(np.linspace(*xdomain), np.linspace(*ydomain))
    Z = np.array([f([x,y]) for (x,y) in zip(X.flat, Y.flat)]).reshape(X.shape)
    contours = pl.contour(X, Y, Z, 20, colors='black')
    pl.clabel(contours, inline=True, fontsize=8)
    if color:
        pl.imshow(Z, extent=[xmin, xmax, ymin, ymax], origin='lower', cmap='RdGy', alpha=0.5)
        pl.axis(aspect='scalar')
    pl.gcf().tight_layout()
    pl.xlim(xmin,xmax); pl.ylim(ymin,ymax)
def graf(x):
    reng = np.mean([math.fabs(np.mean(x[0])), math.fabs(np.mean(x[1]))])
    Yy = np.arange(-1 * reng - 10, reng + 10, 0.1)
    Xx = np.arange(-1 * reng - 10, reng + 10, 0.1)
    X, Y = np.meshgrid(Xx, Yy)
    pylab.figure(1)
    cs = pylab.contour(X, Y, f(X, Y))
    pylab.clabel(cs, colors="black", fmt='x=%.2f')
    pylab.plot(x[0], x[1], 'g-^')
    #pylab.plot(x[0], x[1], '*r')
    pylab.grid()
    pylab.show()
示例#39
0
文件: plt.py 项目: crocha700/popy
def TS_diagram(ss,ts,ax,dlev=0.1):
    from seawater import csiro as sw
    from numpy import linspace,meshgrid,arange
    from pylab import clabel
    t= linspace(ts.min(), ts.max(), 30)
    s= linspace(ss.min(), ss.max(), 30)
    s2d,t2d = meshgrid(s,t)
    
    #ax.scatter(ss,ts,c=colors, s=size, facecolor=facecolor, edgecolor = 'none', marker = marker)
    h=ax.contour(s2d,t2d,sw.pden(s2d,t2d,s2d*0)-1000,levels=arange(20,30,dlev),colors='k')
    clabel(h,inline=1,fontsize=9,fmt='%3.1f')
    return
示例#40
0
 def plot(X, cov, i_iter, save='pics'):
     pl.clf()
     pl.scatter(X[:, 0], X[:, 1], c='b', marker='+', alpha=0.3)
     x = np.linspace(X[:, 0].min(), X[:, 0].max(), 100)
     y = np.linspace(X[:, 1].min(), X[:, 1].max(), 100)
     x_ = np.vstack([_.reshape(1, -1) for _ in np.meshgrid(x, y)]).T
     p = np.exp(stats.multivariate_normal.logpdf(x_, m.data,
                                                 cov.data)).reshape(
                                                     x.size, -1)
     cs = pl.contour(x, y, p, levels=[0.001, 0.01, 0.1])
     pl.clabel(cs, inline=1, fontsize=10)
     pl.pause(0.001)
示例#41
0
def contour_plot(f, xdomain, ydomain, color='viridis', alpha=0.5, levels=None):
    "Contour plot of a function of two variables."
    [xmin, xmax, _] = xdomain; [ymin, ymax, _] = ydomain
    X, Y = np.meshgrid(np.linspace(*xdomain), np.linspace(*ydomain))
    Z = np.array([f(np.array([x,y])) for (x,y) in zip(X.flat, Y.flat)]).reshape(X.shape)
    contours = pl.contour(X, Y, Z, 20, colors='black', levels=levels)
    pl.clabel(contours, inline=True, fontsize=8)
    if color is not None:
        pl.imshow(Z, extent=[xmin, xmax, ymin, ymax], origin='lower', cmap=color, alpha=alpha)
        pl.axis(aspect='scalar')
    pl.gcf().tight_layout()
    pl.xlim(xmin,xmax); pl.ylim(ymin,ymax)
示例#42
0
def f5_cadence_plot(lsstpg,
                    band,
                    lims=None,
                    median_log_summary=None,
                    mag_range=(23., 26.5),
                    dt_range=(0.5, 15.),
                    target={}):
    #                    SNR=dict(zip(['LSSTPG::' + b for b in 'grizy'],
    #                                 [20., 20., 20., 20., 10.]))):

    dt = np.linspace(dt_range[0], dt_range[1], 100)
    m5 = np.linspace(mag_range[0], mag_range[1], 100)
    b = [band] * len(m5)
    f5 = lsstpg.mag_to_flux(m5, b)

    F5, DT = np.meshgrid(f5, dt)
    M5, DT = np.meshgrid(m5, dt)
    metric = np.sqrt(DT) * F5

    # draw limits
    pl.figure()
    pl.imshow(metric,
              extent=(mag_range[0], mag_range[1], dt_range[0], dt_range[1]),
              aspect='auto',
              alpha=0.25)

    if lims is not None:
        fmt = {}
        ll = [lims[zz][band] for zz in lims.keys()]
        cs = pl.contour(M5, DT, metric, ll, colors='k')

        strs = ['$z=%3.1f$' % zz for zz in lims.keys()]
        for l, s in zip(cs.levels, strs):
            fmt[l] = s
        pl.clabel(cs, inline=1, fmt=fmt, fontsize=16)

    if median_log_summary is not None:
        idx = median_log_summary['band'] == band
        m = median_log_summary[idx]
        pl.plot(m['m5'], m['cadence'], 'r+')

    t = target.get(band, None)
    print target, t
    if t is not None:
        pl.plot(t[0], t[1], color='r', marker='*', markersize=15)

    pl.xlabel('$m_{5\sigma}$', fontsize=18)
    pl.ylabel(r'Observer frame cadence $^{-1}$ [days]', fontsize=18)
    pl.title('$%s$' % band.split(':')[-1], fontsize=18)
    pl.xlim(mag_range)
    pl.ylim(dt_range)
    pl.grid(1)
示例#43
0
文件: robreg.py 项目: SheffieldML/TVB
 def plot(self):
     if self.X.shape[1]==1:
         pb.figure()
         Xtest, xmin, xmax = GPy.util.plot.x_frame1D(self.X)
         mu = self.predict(Xtest)
         pb.plot(Xtest.flatten(), mu.flatten(), 'b')
         pb.plot(self.X, self.Y, 'kx', mew=1)
     elif self.X.shape[1]==2:
         pb.figure()
         Xtest,xx,yy, xymin, xymax = GPy.util.plot.x_frame2D(self.X)
         p = self.predict(Xtest)
         c = pb.contour(xx,yy,p.reshape(*xx.shape), colors='k')
         pb.clabel(c)
示例#44
0
def graficaIntensidad(Z):

    'grafica curvas de nivel'

    im = imshow(Z,cmap=cm.RdBu)

    cset = contour(Z,n.arange(-2.0,2.0,0.1),linewidths=2,cmap=cm.Set2)

    clabel(cset,inline=True,fmt='%1.1f',fontsize=10)

    colorbar(im)

    show()
示例#45
0
文件: util.py 项目: timvieira/arsenal
def contour_plot(f, xdomain, ydomain, color='viridis', alpha=0.5, levels=None):
    "Contour plot of a function of two variables."
    from arsenal import iterview
    [xmin, xmax, _] = xdomain; [ymin, ymax, _] = ydomain
    X, Y = np.meshgrid(np.linspace(*xdomain), np.linspace(*ydomain))
    Z = np.array([f(np.array([x,y])) for (x,y) in iterview(zip(X.flat, Y.flat), length=len(X.flat))]).reshape(X.shape)
    contours = pl.contour(X, Y, Z, 20, colors='black', levels=levels)
    pl.clabel(contours, inline=True, fontsize=8)
    if color is not None:
        pl.imshow(Z, extent=[xmin, xmax, ymin, ymax], origin='lower', cmap=color, alpha=alpha)
        pl.axis(aspect='scalar')
    pl.gcf().tight_layout()
    pl.xlim(xmin,xmax); pl.ylim(ymin,ymax)
示例#46
0
 def plot(self):
     if self.X.shape[1] == 1:
         pb.figure()
         Xtest, xmin, xmax = GPy.util.plot.x_frame1D(self.X)
         mu = self.predict(Xtest)
         pb.plot(Xtest.flatten(), mu.flatten(), 'b')
         pb.plot(self.X, self.Y, 'kx', mew=1)
     elif self.X.shape[1] == 2:
         pb.figure()
         Xtest, xx, yy, xymin, xymax = GPy.util.plot.x_frame2D(self.X)
         p = self.predict(Xtest)
         c = pb.contour(xx, yy, p.reshape(*xx.shape), colors='k')
         pb.clabel(c)
示例#47
0
文件: gosl.py 项目: yidaneGolang/gosl
def Contour(X,
            Y,
            Z,
            label='',
            levels=None,
            cmapidx=0,
            colors=None,
            fmt='%g',
            lwd=1,
            fsz=10,
            inline=0,
            wire=True,
            cbar=True,
            zorder=None,
            markZero='',
            markZeroLWD=3,
            clabels=True):
    """
    Plot contour
    ============
    """
    L = None
    if levels != None:
        if not hasattr(levels, "__iter__"):  # not a list or array...
            levels = linspace(Z.min(), Z.max(), levels)
    if colors == None:
        c1 = contourf(X, Y, Z, cmap=Cmap(cmapidx), levels=levels, zorder=None)
    else:
        c1 = contourf(X, Y, Z, colors=colors, levels=levels, zorder=None)
    if wire:
        c2 = contour(X,
                     Y,
                     Z,
                     colors=('k'),
                     levels=levels,
                     linewidths=[lwd],
                     zorder=None)
        if clabels:
            clabel(c2, inline=inline, fontsize=fsz)
    if cbar:
        cb = colorbar(c1, format=fmt)
        cb.ax.set_ylabel(label)
    if markZero:
        c3 = contour(X,
                     Y,
                     Z,
                     levels=[0],
                     colors=[markZero],
                     linewidths=[markZeroLWD])
        if clabels:
            clabel(c3, inline=inline, fontsize=fsz)
示例#48
0
def my2d():
     """2D interpolation example.
    
     References:
     http://matplotlib.sourceforge.net/index.html
     http://www.scipy.org/doc/api_docs/SciPy.interpolate.interpolate.interp2d.html
     """
    
     # Scattered data points to be interpolated
     # These are arbitrary numbers for this exercise
     x = numpy.array([0.0, 1767.0, 1767.0, 0.0, -1767.0, -1767.0, -1767.0, 0.0, 1767.0])
     y = numpy.array([0.0, 0.0, 1767.0, 1767.0, 1767.0, 0.0, -1767.0, -1767.0, -1767.0])
     z = numpy.array([27, 16, 0, 12, 69, 128, 292, 332, 298])
    
     # Print the data to screen for checking
     print 'DATA USED FOR INTERPOLATION:'
     for val, tuple in enumerate(zip(x,y,z)):
         print val, ':', tuple[0], tuple[1], tuple[2]
    
     # Coordinates to fill with interpolated data
     xi = numpy.arange(numpy.min(x), numpy.max(x))
     yi = numpy.arange(numpy.min(y), numpy.max(y))
    
     # Perform 2D interpolation
     l = interpolate.interpolate.interp2d(x, y, z)
     im = l(xi, yi)
    
     # Get min/max to use same colorbar on for base and overlay
     pmin = im.min()
     pmax = im.max()
    
     # Show interpolated 2D image
     p = pylab.imshow(im, vmin=pmin, vmax=pmax, cmap = cm.gist_yarg,
                      origin = 'lower', extent=[numpy.min(x), numpy.max(x), numpy.min(y), numpy.max(y)])
    
     c = pylab.contour(im,origin = 'lower', extent=[numpy.min(x), numpy.max(x), numpy.min(y), numpy.max(y)])
    
     pylab.clabel(c, inline=1, fontsize=8)
    
     # Display colobar
     # Optional shrink to make it same width as display
     c = pylab.colorbar(p, orientation='horizontal', shrink=0.7)
     c.set_label('Raw Counts at Dwell Points')
    
     # Plot labels
     pylab.xlabel('Dispersion Offset (mas)')
     pylab.ylabel('Cross-Dispersion Offset (mas)')
     pylab.title('11531 Visit 7 Target Acquisition')
    
     #pylab.show()
     pylab.savefig('2dAcq.pdf')
示例#49
0
文件: sphere_rel.py 项目: kessel/ipbs
def plotear(xi, yi, zi):
    # mask inner circle
    interior = sqrt((xi ** 2) + (yi ** 2)) < 5.0
    zi[interior] = ma.empty
    # exterior = sqrt((xi**2) + (yi**2)) > 15.0
    # zi[exterior] = ma.empty
    p.figure(figsize=(16, 10))
    levels = [
        log(1.1e-3),
        log(1.12e-3),
        log(1.14e-3),
        log(1.18e-3),
        log(1.26e-3),
        log(1.42e-3),
        log(1.74e-3),
        log(1.29e-3),
    ]
    # levels = [log(3.25e-3),log(3.5e-3), log(4.0e-3), log(4.1e-3),log(4.2e-3),log(4.4e-3), log(4.6e-3)]
    # levels = [8e-4, 1e-3, 1.15e-3, 1.20e-3, 1.25e-3, 1.3e-3, 1.4e-3, 1.5e-3, 2e-3, 2.5e-3, 3e-3, 3.5e-3, 4e-3, 4.5e-3, 5e-3, 6e-3, 7e-3, 8e-3, 9e-3, 1e-2]
    # levels = [7e-4, 8e-4, 9e-4, 1e-3, 1.1e-3, 1.12e-3, 1.125e-3, 1.13e-3 ,1.14e-3, 1.16e-3, 1.2e-3, 1.22e-3, 1.24e-3, 1.26e-3, 1.28e-3, 1.3e-3, 1.4e-3, 1.5e-3, 2e-3, 2.5e-3, 3e-3, 3.5e-3, 4e-3, 4.5e-3, 5e-3, 6e-3, 7e-3, 8e-3, 9e-3, 1e-2]
    # levels = [log(2.8125e-7),log(5.625e-7), log(1.125e-6) , log(3.25e-6), log(.75e-5), log(1.25e-4), log(2.5e-4), log(0.005), log(0.01), log(0.02), log(0.04), log(0.08), log(0.16), log(0.32), log(0.64)]
    # levels = [log(.64), log(.32), log(.16), log(.08), log(.04), log(.02), log(.01), log(0.005), log(0.0025)]
    # levels = np.linspace(7.e-4, 1e-2, num=15, endpoint=True)
    # levels = np.logspace(-8,-1, num=20, endpoint=True, base=10)
    scale = list()
    counter = 0
    labels = dict()
    for i in levels:
        scale.insert(counter, str("%1.2e" % pow(e, i)))
        # scale.insert(counter,str(i))
        labels[levels[counter]] = scale[counter]
        counter = counter + 1
    # CSF = p.contourf(xi,yi,zi, levels, cmap=cm.jet)
    mp.rcParams["contour.negative_linestyle"] = "solid"
    CS = p.contour(xi, yi, zi, levels, colors="black", lynestiles="solid")
    print str(labels)
    p.clabel(CS, levels, fmt=labels, fontsize=12, inline=1, color="black")
    # p.clabel(CS)
    p.xlim((-6, 6))
    p.ylim((0, 6))
    # p.clabel(CS,levels[1::2], fmt='%1.1e', fontsize=14, inline=1, color='black')
    # p.clabel(CS,levels[1::2], fmt={log(1e-9):'1e-9', log(5e-9):'5e-9', log(1e-8):'1e-8', log(5e-8):'5e-8', log(1e-7):'1e-7', log(5e-7):'5e-7', log(1e-6):'1e-6', log(5e-6):'5e-8', log(1e-5):'1e-5', log(5e-5):'5e-5', log(1e-4):'1e-4', log(2e-4):'2e-4', log(4e-4):'4e-4', log(8e-4):'8e-4', log(1.2e-3):'1.2e-3', log(2.4e-3):'2.4e-3', log(4.8e-3):'4.8e-3'}, fontsize=9, inline=1)
    p.title("iPBS relative error")
    p.xlabel("z-coordinate", fontsize=14)
    p.ylabel("radial coordinate", fontsize=14)
    # add a vertical bar with the color values
    # cbar = p.colorbar(CSF, ticks=levels, format='%e')
    # cbar.ax.set_yticklabels(scale)
    # cbar.ax.set_ylabel('iPBS relative error',fontsize=12)
    # cbar.add_lines(CS)
    return xi, yi, zi
示例#50
0
    def plot_lines(self) -> None:
        x = np.arange(-1, 0.5, 0.05)
        y = np.arange(-1, 0.5, 0.05)
        xgrid, ygrid = np.meshgrid(x, y)

        zgrid = 4 * xgrid + ygrid + 4 * np.sqrt(1 + 3 * xgrid**2 + ygrid**2)

        cs = pylab.contour(xgrid, ygrid, zgrid, 15)
        pylab.plot(self.pointsX, self.pointsY, 'bX--')
        pylab.clabel(cs, colors="black")
        pylab.xlabel("x1")
        pylab.ylabel("x2")
        pylab.title("Линии уровня функции" + self.func_str)
        pylab.show()
示例#51
0
def contour_hmap(dat, levels, isys='e', lst=0., dec=aa.lat, mode='log', colors='m', linestyles='-'):
    d = proj_hmap(dat, mode=isys, lst=lst, dec=dec)
    if mode == 'log': d = n.log10(n.abs(d))
    elif mode == 'dB':
        d = 10*n.log10(n.abs(d))
        mx,drng = 10*mx, 10*drng
    elif mode == 'real': d = d.real
    lons,lats,x,y = m.makegrid(SIZE,SIZE, returnxy=True)
    cs = m.contour(x,y, d, levels, linewidth=8, linestyles=linestyles, colors=colors)
    p.clabel(cs, inline=1, fontsize=10, fmt='%4.2f')#, manual=manual)
    #m.drawmapboundary()
    #m.drawmeridians(n.arange(0,360,30))
    #m.drawparallels(n.arange(0,90,10))
    return cs
示例#52
0
def plot_contour(fname="../contour_plot.png", dpi=200):
    def f(x, y):
        return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)

    pl.clf()
    n = 256
    x = np.linspace(-3, 3, n)
    y = np.linspace(-3, 3, n)
    mx, my = np.meshgrid(x, y)

    pl.contourf(mx, my, f(mx, my), 8, alpha=0.75, cmap=pl.cm.hot)
    c = pl.contour(mx, my, f(mx, my), 8, colors="black", linewidth=0.5)
    pl.clabel(c, fontsize=9)
    pl.savefig(fname, dpi=dpi)
示例#53
0
def contour_xz(atoms,orb,bfs,y=0,npts=50,doshow=False,
               title="Contour plot of pyquante orbital"):
    bbox = atoms.bbox()
    x = np.linspace(bbox[0],bbox[1],npts)
    z = np.linspace(bbox[4],bbox[5],npts)
    f = np.zeros((npts,npts),'d')
    X,Z = np.meshgrid(x,z)
    for c,bf in zip(orb,bfs):
        f += c*bf(X,y,Z) # Can mesh bfs with arrays of points
    cp = pl.contour(X,Z,f,colors='k') # b&w
    pl.title(title)
    pl.clabel(cp,inline=1,fontsize=8)
    if doshow: pl.show()
    return
示例#54
0
def doOne(subplot_num, n_sources):
    truth = np.zeros(X1.shape)
    for i in range(n_sources):
        midx1,midx2 = rng.random() * N,  rng.random() * N
        intensity = rng.random()
        expsum =np.power((X1-midx1)*1.0/sigma,2.0) + np.power((X2-midx2)*1.0/sigma,2.0)
        truth = truth + intensity * np.exp(-0.5*expsum)
    noise = rng.normal(0,noise_size,X1.shape)
    y = truth + noise
    y = (y-np.min(y))/(np.max(y)-np.min(y)) + np.abs(rng.normal(0,0.01,X1.shape))


    # Evaluate the reversed KL score, throughout the image
    KLRevscore = -100000 * np.ones(X1.shape)
    KLscore = -100000 * np.ones(X1.shape)
    for midx1 in range(N):
        for midx2 in range(N):
            # make up a "model"
            expsum =np.power((X1-midx1)*1.0/model_sigma,2.0) + np.power((X2-midx2)*1.0/model_sigma,2.0)
            model = np.exp(-0.5*expsum)

            # score the model against the "image"
            KLRevscore[midx1][midx2] = np.sum(np.ravel(model*np.log(y)))/np.sum(np.ravel(model))

    # rescale to range in [0,1]
    KLRevscore = (KLRevscore-np.min(KLRevscore))/(np.max(KLRevscore)-np.min(KLRevscore))

    
    # draw the ground truth (as an image), 
    pl.figure('ground')
    pl.subplot(3,1,subplot_num)
    pl.imshow(truth,interpolation='nearest',cmap=cm.gray)
    pl.title('ground truth %s' % (subplot_num))

    # draw the noisy image.
    pl.figure('image')
    pl.subplot(3,1,subplot_num)
    pl.imshow(y,interpolation='nearest',cmap=cm.gray)
    pl.title('image %s' % (subplot_num))

    # draw the inferred source density (as contours).
    pl.figure('contours')
    pl.subplot(3,1,subplot_num)
    pl.imshow(truth*0.0,interpolation='nearest',cmap=cm.gray)
    CS = pl.contour(X2,X1,KLRevscore,5,linewidths=np.arange(5),
                 colors=((.2,.2,0),(.4,.4,0),(.6,.6,0),(.8,.8,0),(1,1,0)))
    pl.clabel(CS, inline=1, fontsize=10)
    pl.title('inferred density %s' % (subplot_num))
示例#55
0
def plot_T2_contour(esp, model):
    """Given a model (defined according to fitting.py) will plot constant sO2 contours as a function of Hct for 
    a given esp (in seconds)""" 
    Hct_full=np.arange(0.0,0.9,0.005)
    sO2_full=np.arange(0.0,1.1,0.005) 
    [Hct_mat,sO2_mat]=np.meshgrid(Hct_full,sO2_full)           
    ij=itertools.product(range(Hct_mat.shape[0]),range(Hct_mat.shape[1]))
    R2_ans=np.zeros_like(Hct_mat)
    xx=np.zeros(3)
    for element in ij:
        xx=np.array([Hct_mat[element],sO2_mat[element],esp,0.0])
        R2_ans[element[0],element[1]]=model(xx)    
    #plt.figure() 
    #C = plt.contour(Hct_mat,1000/R2_ans,100*sO2_mat,np.arange(0,110,10),vmin=0,vmax=110,linewidths=1.5,linestyles='solid',cmap=matplotlib.cm.jet)  
    C = plt.contour(Hct_mat,1000/R2_ans,100*sO2_mat,np.r_[0:40:20,30:110:10],vmin=0,vmax=110,linewidths=1.5,linestyles='solid',cmap=matplotlib.cm.cool)      
    plt.clabel(C, C.levels[::2], colors='k', inline=True, fmt="%0.1f", fontsize=14)                 
示例#56
0
def demo_contour():    

    n = 256
    x = np.linspace(-3,3,n)
    y = np.linspace(-3,3,n)
    X,Y = np.meshgrid(x,y)
    
    plt.axes([0.025,0.025,0.95,0.95])
    
    plt.contourf(X, Y, f(X,Y), 8, alpha=.75, cmap=plt.cm.hot)
    C = plt.contour(X, Y, f(X,Y), 8, colors='black', linewidth=.5)
    plt.clabel(C, inline=1, fontsize=10)
    
    plt.xticks([]), plt.yticks([])
    # savefig('../figures/contour_ex.png',dpi=48)
    plt.show()
示例#57
0
def runanalysis():
    filename = ourgui.openFile(type='npz')

    data = np.load(filename, mmap_mode='r')
    X = data['X']
    Y = data['Y']
    BX = data['BX']
    BY = data['BY']
    BZ = data['BZ']
    pitch = data['pitch']
    windnum = data['windnum']

    phi = np.linspace(0, np.pi*2, 100)

    pl.figure(figsize=(11.69, 8.27), dpi=100)

    BXBZ = np.zeros(BZ.shape)
    BYBZ = np.zeros(BZ.shape)
    for i in xrange(BZ.shape[0]):
        for j in xrange(BZ.shape[1]):
            if abs(BZ[i, j]) > 1e-14:
                BXBZ[i, j] = BX[i, j] / BZ[i, j]
                BYBZ[i, j] = BY[i, j] / BZ[i, j]

    
    pl.subplot(2, 2, 1, aspect='equal')
    pl.title("Pitch = %g, wind number = %d" %(pitch, windnum))
    pl.plot(np.cos(phi), np.sin(phi), linewidth=3)
    CS = pl.contour(X, Y, BXBZ*100, colors='k')
    pl.clabel(CS, inline=1, fontsize=10, fmt='%.1f%%')
    pl.xlabel("Bx / Bz")

    pl.subplot(2, 2, 2, aspect='equal')
    pl.plot(np.cos(phi), np.sin(phi), linewidth=3)
    CS = pl.contour(X, Y, BYBZ*100, colors='k')
    pl.clabel(CS, inline=1, fontsize=10, fmt='%.1f%%')
    pl.xlabel("By / Bz")

    pl.subplot(2, 2, 3, aspect='equal')
    pl.plot(np.cos(phi), np.sin(phi), linewidth=3)
    CS = pl.contour(X, Y, BZ / BZ.max()*100, 10, colors='k')
    pl.clabel(CS, inline=1, fontsize=10, fmt='%.1f%%')
    pl.xlabel("Bz (normalized)")

    pl.subplot(2, 2, 4, aspect='equal')
    FIELD = np.sqrt(BX**2 + BY**2 + BZ**2)
    pl.plot(np.cos(phi), np.sin(phi), linewidth=3)
    CS = pl.contour(X, Y, FIELD, colors='k')
    pl.clabel(CS, inline=1, fontsize=10)
    pl.xlabel("Total field strength")

    # import matplotlib.cm as cm
    # im = pl.imshow(FIELD, interpolation='bilinear', origin='lower',
    #                 cmap=cm.gray, extent=(-1,1,-1,1))
    # pl.plot(np.cos(phi), np.sin(phi), linewidth=3)
    # CS = pl.contour(X, Y, np.sqrt(BX**2 + BY**2 + BZ**2))
    pl.show()
示例#58
0
def plot_T1_contour(model,metHb=0.005):
    """Given a model (defined according to fitting.py) will plot constant sO2 contours as a function of Hct for 
    a given esp (in seconds)""" 
    Hct_full=np.arange(0.0,1.01,0.01)
    sO2_full=np.arange(-0.1,1.1,0.01) 
    [Hct_mat,sO2_mat]=np.meshgrid(Hct_full,sO2_full)           
    ij=itertools.product(range(Hct_mat.shape[0]),range(Hct_mat.shape[1]))
    R1_ans=np.zeros_like(Hct_mat)
    xx=np.zeros(3)
    for element in ij:
        xx=[Hct_mat[element],sO2_mat[element],metHb]
        R1_ans[element[0],element[1]]=model(xx)    
    #plt.figure() 
    #C = plt.contour(100*sO2_mat,1000/R1_ans,Hct_mat,np.arange(0.0,1.1,0.05),vmin=0,vmax=0.95,linewidths=1.5,cmap=matplotlib.cm.jet)  
    C = plt.contour(100*sO2_mat,1000/R1_ans,Hct_mat,np.r_[0:0.3:0.05,0.3:1.1:0.1],vmin=0,vmax=0.95,linewidths=1.5,cmap=matplotlib.cm.jet)  
    #C = plt.contour(Hct_mat,1000/R1_ans,sO2_mat,np.arange(-0.5,1.05,0.05),vmin=0,vmax=1.1,linewidths=1.5,cmap=matplotlib.cm.cool)     
    plt.clabel(C, C.levels[::2], colors='k', inline=True, fmt="%0.2f", fontsize=14)     
示例#59
0
 def plotBoundary(self, X, Y, scoreFN, values, title=""):
     # Plot the decision boundary. For that, we will asign a score to
     # each point in the mesh [x_min, m_max]x[y_min, y_max].
     x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
     y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
     h = max((x_max-x_min)/200., (y_max-y_min)/200.)
     xx, yy = meshgrid(arange(x_min, x_max, h),
                       arange(y_min, y_max, h))
     zz = array([scoreFn(x) for x in c_[xx.ravel(), yy.ravel()]])
     zz = zz.reshape(xx.shape)
     pl.figure()
     CS = pl.contour(xx, yy, zz, values, colors = 'green', linestyles = 'solid', linewidths = 2)
     pl.clabel(CS, fontsize=9, inline=1)
     # Plot the training points
     pl.scatter(X[:, 0], X[:, 1], c=(1.-Y), s=50, cmap = pl.cm.cool)
     pl.title(title)
     pl.axis('tight')