Ejemplo n.º 1
0
    def plotDgGnPh(self, higherFrqAg = 0.5, lowerFrqAg = -0.5):
        """'  plot Gain/Phase diagram of discrete system using matplotlib
            The angular at the right side is pi
            Drawing Gain/Phase plot by H(z) ==> H(epx(j ω))
            Default angular width is 3 decades
            Frequencey Range: [lowerFrqAg , higherFrqAg]
        '"""
        import pylab as py
        N = 128

        lstThetaAt = [sc.exp( 2*sc.pi*1j*(lowerFrqAg
                    + (higherFrqAg-lowerFrqAg) *float(k)/N) )    for k in range(N)]

        t          = [lowerFrqAg+ (higherFrqAg-lowerFrqAg) *float(k)/N
                                    for k in range(N)]

        py.subplot(211)
        py.plot( t, abs(self(lstThetaAt))  )
        py.ylabel('gain')
        py.grid(True)

        py.subplot(212)
        py.plot( t, [sc.arctan2(zz.imag, zz.real)
                            for zz in self(lstThetaAt)])
        py.ylabel('phase')
        py.grid(True)
        py.gca().xaxis.grid(True, which='minor')  # minor grid on too
        py.show()
Ejemplo n.º 2
0
	def plot_stress(self, block_ids=None, fignum=0):
		block_ids = self.check_block_ids_list(block_ids)
		#
		plt.figure(fignum)
		ax1=plt.gca()
		plt.clf()
		plt.figure(fignum)
		plt.clf()
		ax0=plt.gca()

		#
		for block_id in block_ids:
			rws = numpy.core.records.fromarrays(zip(*filter(lambda x: x['block_id']==block_id, self.shear_stress_sequences)), dtype=self.shear_stress_sequences.dtype)
			stress_seq = []
			for rw in rws:
				stress_seq += [[rw['sweep_number'], rw['shear_init']]]
				stress_seq += [[rw['sweep_number'], rw['shear_final']]]
			X,Y = zip(*stress_seq)
			#
			ax0.plot(X,Y, '.-', label='block_id: %d' % block_id)
			#
			plt.figure(fignum+1)
			plt.plot(rws['sweep_number'], rws['shear_init'], '.-', label='block_id: %d' % block_id)
			plt.plot(rws['sweep_number'], rws['shear_final'], '.-', label='block_id: %d' % block_id)
			plt.figure(fignum)
		ax0.plot([min(self.shear_stress_sequences['sweep_number']), max(self.shear_stress_sequences['sweep_number'])], [0., 0.], 'k-')
		ax0.legend(loc=0, numpoints=1)
		plt.figure(fignum)
		plt.title('Block shear_stress sequences')
		plt.xlabel('sweep number')
		plt.ylabel('shear stress')
Ejemplo n.º 3
0
def plotB3reg():
    w=loadStanFit('revE2B3BHreg.fit')
    printCI(w,'mmu')
    printCI(w,'mr')
    for b in range(2):
        subplot(1,2,b+1)
        plt.title('')
        px=np.array(np.linspace(-0.5,0.5,101),ndmin=2)
        a0=np.array(w['mmu'][:,b],ndmin=2).T
        a1=np.array(w['mr'][:,b],ndmin=2).T
        y=np.concatenate([sap(a0+a1*px,97.5,axis=0),sap(a0+a1*px[:,::-1],2.5,axis=0)])
        x=np.squeeze(np.concatenate([px,px[:,::-1]],axis=1))
        plt.plot(px[0,:],np.median(a0)+np.median(a1)*px[0,:],'red')
        #plt.plot([-1,1],[0.5,0.5],'grey')
        ax=plt.gca()
        ax.set_aspect(1)
        ax.add_patch(plt.Polygon(np.array([x,y]).T,alpha=0.2,fill=True,fc='red',ec='w'))
        y=np.concatenate([sap(a0+a1*px,75,axis=0),sap(a0+a1*px[:,::-1],25,axis=0)])
        ax.add_patch(plt.Polygon(np.array([x,y]).T,alpha=0.2,fill=True,fc='red',ec='w'))
        man=np.array([-0.4,-0.2,0,0.2,0.4])
        mus=[]
        for m in range(len(man)):
            mus.append(loadStanFit('revE2B3BH%d.fit'%m)['mmu'][:,b])
        mus=np.array(mus).T
        errorbar(mus,x=man)
        ax.set_xticks(man)
        plt.xlim([-0.5,0.5])
        plt.ylim([-0.4,0.8])
        #plt.xlabel('Manipulated Displacement')
        if b==0:
            plt.ylabel('Perceived Displacemet')
            plt.gca().set_yticklabels([])
        subplot_annotate()
    plt.text(-1.1,-0.6,'Pivot Displacement',fontsize=8);
Ejemplo n.º 4
0
def plotBode(f*g, lowerFreq, higherFreq = None):
    """'  plot Bode diagram using matplotlib
        Default frequency width is 3 decades
    '"""
    import pylab as py
    #import pdb; pdb.set_trace()
    if ( higherFreq == None):
        rangeAt = 1000.0  # 3 decade
    else:
        assert higherFreq > lowerFreq
        rangeAt = float(higherFreq)/lowerFreq

    N = 128
    lstScannAngFreqAt = [2*sc.pi*1j*lowerFreq*sc.exp(
                                                sc.log(rangeAt)*float(k)/N)
                                for k in range(N)]

    t              = [        lowerFreq*sc.exp(sc.log(rangeAt)*float(k)/N)
                                for k in range(N)]

    py.subplot(211)
    py.loglog( t, [(abs(f*g(x))) for x in lstScannAngFreqAt]  )
    py.ylabel('gain')
    py.grid(True)

    py.subplot(212)
    py.semilogx( t, [sc.arctan2(f*g(zz).imag, f*g(zz).real)
                        for zz in lstScannAngFreqAt])
    py.ylabel('phase')
    py.grid(True)
    py.gca().xaxis.grid(True, which='minor')  # minor grid on too
    py.show()
Ejemplo n.º 5
0
def trace(data, name, format='png', datarange=(None, None), suffix='', path='./', rows=1, columns=1, 
    num=1, last=True, fontmap = None, verbose=1):
    """
    Generates trace plot from an array of data.

    :Arguments:
        data: array or list
            Usually a trace from an MCMC sample.

        name: string
            The name of the trace.
            
        datarange: tuple or list
            Preferred y-range of trace (defaults to (None,None)).

        format (optional): string
            Graphic output format (defaults to png).

        suffix (optional): string
            Filename suffix.

        path (optional): string
            Specifies location for saving plots (defaults to local directory).
            
        fontmap (optional): dict
            Font map for plot.

    """

    if fontmap is None: fontmap = {1:10, 2:8, 3:6, 4:5, 5:4}

    # Stand-alone plot or subplot?
    standalone = rows==1 and columns==1 and num==1

    if standalone:
        if verbose>0:
            print_('Plotting', name)
        figure()

    subplot(rows, columns, num)
    pyplot(data.tolist())
    ylim(datarange)

    # Plot options
    title('\n\n   %s trace'%name, x=0., y=1., ha='left', va='top', fontsize='small')

    # Smaller tick labels
    tlabels = gca().get_xticklabels()
    setp(tlabels, 'fontsize', fontmap[rows/2])

    tlabels = gca().get_yticklabels()
    setp(tlabels, 'fontsize', fontmap[rows/2])

    if standalone:
        if not os.path.exists(path):
            os.mkdir(path)
        if not path.endswith('/'):
            path += '/'
        # Save to file
        savefig("%s%s%s.%s" % (path, name, suffix, format))
Ejemplo n.º 6
0
 def test_set_plot_limits_no_args(self):
     """set_limits() properly does nothing when nothing specified
     """
     args = MagicMock(savefig="", xlim=[], ylim=[])
     plot_lib.set_limits(args)
     self.assertEqual(pl.gca().get_xlim(), (0.0, 9.0))
     self.assertEqual(pl.gca().get_ylim(), (0.0, 9.0))
Ejemplo n.º 7
0
 def test_set_plot_limits(self):
     """set_limits() properly sets limits
     """
     args = MagicMock(savefig="", xlim=[-2, 2], ylim=[-3, 3])
     plot_lib.set_limits(args)
     self.assertEqual(pl.gca().get_xlim(), (-2.0, 2.0))
     self.assertEqual(pl.gca().get_ylim(), (-3.0, 3.0))
Ejemplo n.º 8
0
 def plot(self):
     if not pylabInstalled: 
         raise SpaceFuncsException('to plot you should have matplotlib installed')
     cir = pylab.Circle(self.center, radius=self.radius, alpha = 1.0 - self.transparency, lw = self.linewidth, fc='w', fill=self.fill, \
                        ec = self.edgecolor, color = self.color, linestyle = self.linestyle)
     pylab.gca().add_patch(cir)
     if self.plotCenter: self.center.plot()
def show_image(*imgs): 
    for idx, img in enumerate(imgs):
        subplot = 101 + len(imgs)*10 +idx
        pl.subplot(subplot)
        pl.imshow(img, cmap=pl.cm.gray)   
        pl.gca().set_axis_off()    
    pl.subplots_adjust(0.02, 0, 0.98, 1, 0.02, 0)        
Ejemplo n.º 10
0
def plot_commerror(name1,logfile1,name2,logfile2):

  file1 = open(str(logfile1),'r').readlines()
  data1 = [float(line.split()[1]) for line in file1]
  iso1 = data1[0::3]
  aniso1 = data1[1::3]
  ml1 = data1[2::3]

  file2 = open(str(logfile2),'r').readlines()
  data2 = [float(line.split()[1]) for line in file2]
  iso2 = data2[0::3]
  aniso2 = data2[1::3]
  ml2 = data2[2::3]

  # x axis
  x=[8,16,32,64,128]
  xlabels=['A','B','C','D','E']
  orderone = [1,.5,.25,.125,.0625]
  ordertwo = [i**2 for i in orderone]
  plot1 = pylab.figure(figsize = (6, 6.5))
  size = 15
  ax = pylab.subplot(111)
  ax.plot(x,iso1, linestyle='solid',color='red',lw=2)
  ax.plot(x,aniso1, linestyle='dashed',color='red',lw=2)
  ax.plot(x,ml1, linestyle='dashdot',color='red',lw=2)
  ax.plot(x,iso2, linestyle='solid',color='blue',lw=2)
  ax.plot(x,aniso2, linestyle='dashed',color='blue',lw=2)
  ax.plot(x,ml2, linestyle='dashdot',color='blue',lw=2)
  #ax.plot(x,orderone, linestyle='solid',color='black',lw=2)
  #ax.plot(x,ordertwo, linestyle='dashed',color='black')
  #pylab.legend((str(name1)+'_iso',str(name1)+'_aniso',str(name2)+'_iso',str(name2)+'_aniso','order 1'),loc="best")
  pylab.legend((str(name1)+'_iso',str(name1)+'_aniso',str(name1)+'_ml',str(name2)+'_iso',str(name2)+'_aniso',str(name2)+'_ml'),loc="best")
  leg = pylab.gca().get_legend()
  ltext = leg.get_texts()
  pylab.setp(ltext, fontsize = size, color = 'black')
  frame=leg.get_frame()
  frame.set_fill(False)
  frame.set_visible(False)

  #ax.grid("True")
  for tick in ax.xaxis.get_major_ticks():
    tick.label1.set_fontsize(size)
  for tick in ax.yaxis.get_major_ticks():
    tick.label1.set_fontsize(size)

  # set axes to logarithmic
  pylab.gca().set_xscale('log',basex=2)
  pylab.gca().set_yscale('log',basex=2)

  pylab.axis([8,128,1.e-4,2])
  ax.set_xticks(x)
  ax.set_xticklabels(xlabels)

  #pylab.axis([1,5,1.e-6,1.])
  ax.set_xlabel('Mesh resolution', ha="center",fontsize=size)
  ax.set_ylabel('commutation error',fontsize=size)
  pylab.savefig('commerrorplot.eps')
  pylab.savefig('commerrorplot.pdf')

  return
Ejemplo n.º 11
0
def plot_file_color(base, thin=True, start=0, size=14, save=False):
    conf, track, pegs = load(base)

    fig = pl.figure(figsize=(size,size*conf['top']/conf['wall']))

    track = track[start:]
    x = track[:,0];   y = track[:,1]
    t = np.linspace(0,1,x.shape[0])
    points = np.array([x,y]).transpose().reshape(-1,1,2)
    segs = np.concatenate([points[:-1],points[1:]],axis=1)
    lc = LineCollection(segs, linewidths=0.25, cmap=pl.cm.coolwarm)
    lc.set_array(t)
    pl.gca().add_collection(lc)

    #pl.scatter(x, y, c=np.arange(len(x)),linestyle='-',cmap=pl.cm.coolwarm)
    #pl.plot(track[-1000000:,0], track[-1000000:,1], '-', linewidth=0.0125, alpha=0.8)
    for peg in pegs:
        pl.gca().add_artist(pl.Circle(peg, conf['radius'], color='k', alpha=0.3))
    pl.xlim(0, conf['wall'])
    pl.ylim(0, conf['top'])
    pl.xticks([])
    pl.yticks([])
    pl.tight_layout()
    pl.show()
    if save:
        pl.savefig(base+".png", dpi=200)
Ejemplo n.º 12
0
def plot_features(im, features, num_to_plot=100, colors=["blue"]):

  plt.imshow(im)

  for i in range(min(features.shape[0], num_to_plot)):
    x = features[i,0]
    y = features[i,1]
    scale = features[i,2]
    rot = features[i,3]


    color = colors[i % len(colors)]

    box = patches.Rectangle((-scale/2,-scale/2), scale, scale, 
      edgecolor=color, facecolor="none", lw=1)
    arrow = patches.Arrow(0, -scale/2, 0, scale, 
      width=10, edgecolor=color, facecolor="none")
    t_start = plt.gca().transData
    transform = mpl.transforms.Affine2D().rotate(rot).translate(x,y) + t_start

    box.set_transform(transform)
    arrow.set_transform(transform)
    plt.gca().add_artist(box)
    plt.gca().add_artist(arrow)


  plt.axis('off')
  plt.set_cmap('gray')
  plt.show()
Ejemplo n.º 13
0
def auto_shift(offset):
    """
    Return a y-offset coordinate transform for the current axes.

    Each call to auto_shift increases the y-offset for the next line by
    the given number of points (with 72 points per inch).

    Example::

        from matplotlib import pyplot as plt
        from bumps.plotutil import auto_shift
        trans = auto_shift(plt.gca())
        plot(x, y, hold=True, trans=trans)
    """
    from matplotlib.transforms import ScaledTranslation
    import pylab
    ax = pylab.gca()
    if ax.lines and hasattr(ax, '_auto_shift'):
        ax._auto_shift += offset
    else:
        ax._auto_shift = 0
    trans = pylab.gca().transData
    if ax._auto_shift:
        trans += ScaledTranslation(0, ax._auto_shift/72.,
                                   pylab.gcf().dpi_scale_trans)
    return trans
Ejemplo n.º 14
0
 def plot_surface(self, debug=debug, nu=150, phi=0, hold=True, linecolor='gray', marker=',',**plkwargs):
     (r,z)=self.make_curve(nu=nu, phi=phi)
     plkwargs.update({'color':linecolor, 'linewidth':0.3})
     if (linecolor != None) and (linecolor != ''): 
         pl.plot(r,z, hold=hold, **plkwargs)
     pl.gca().set_aspect('equal')
     if marker != '': pl.plot(r,z,marker, hold=1)        
Ejemplo n.º 15
0
def _plotResults(naDist1, naDist2, lfOneKnn, lf5Knn):
    plt.clf()

    plt.subplot(311)
    plt.scatter(naDist1[:, 0], naDist1[:, 1])

    plt.scatter(naDist2[:, 0], naDist2[:, 1], color="r")

    # plt.ylabel( 'Feature 2' )
    # plt.xlabel( 'Feature 1' )
    # gca().annotate( '', xy=( .8, 0 ), xytext=( -.3 , 0 ), arrowprops=dict(facecolor='red', shrink=0.05) )
    gca().annotate("", xy=(0.7, 0), xytext=(1.5, 0), arrowprops=dict(facecolor="black", shrink=0.05))
    plt.title("Data Distribution")

    plt.subplot(312)

    plt.plot(range(len(lfOneKnn)), lfOneKnn)

    plt.ylabel("1-KNN Value")
    # plt.xlabel( 'Distribution Merge' )

    plt.title("1-KNN Performance")

    plt.subplot(313)

    plt.plot(range(len(lf5Knn)), lf5Knn)

    plt.ylabel("% Correct Classification")
    # plt.xlabel( 'Distribution Merge' )

    plt.title("5-KNN Performance")

    plt.subplots_adjust()

    plt.show()
Ejemplo n.º 16
0
 def plot_mass_magnitude(self, mag, savefile=None):
     """
     Make a standard mass-luminosity relation plot for this isochrone.
     
     Parameters
     ----------
     mag : string
         The name of the magnitude column to be plotted.
     savefile : string (default None)
         If a savefile is specified, then the plot will be saved to that file. 
     """
     plt.clf()
     plt.semilogx(self.points['mass'], self.points[mag], 'k.')
     plt.gca().invert_yaxis()
     plt.xlabel(r'Mass (M$_\odot$)')
     plt.ylabel(mag + ' (mag)')
     
     fmt_title = 'logAge={0:.2f}, d={1:.2f} kpc, AKs={2:.2f}'
     plt.title(fmt_title.format(self.points.meta['LOGAGE'],
                               self.points.meta['DISTANCE']/1e3,
                               self.points.meta['AKS']))
     
     if savefile != None:
         plt.savefig(savefile)
     
     return
Ejemplo n.º 17
0
def plot_descur(RBC, RBS, ZBC, ZBS, max_m, max_n, phi_plane=0., nu=150, debug=1, **plkwargs):
    """ Companion plotting routine to read_descur_data
    """
    theta_arr = linspace(0,2*pi,nu,endpoint=True)
    r_c = 0*theta_arr
    z_c = 0*theta_arr
    r_c2 = 0*theta_arr
    z_c2 = 0*theta_arr
    for (i,theta) in enumerate(theta_arr):
        for ixm in range(0, max_m):
            if ixm==0: start_n=0
            else: start_n = -max_n
            for ixn in range(start_n, 1+max_n):
                arg = ixn*phi_plane + ixm*theta
                sinarg = sin(arg)
                cosarg = cos(arg)
                r_c[i] += (RBC[ixn,ixm]*cosarg) + (RBS[ixn,ixm]*sinarg)
                z_c[i] += (ZBC[ixn,ixm]*cosarg) + (ZBS[ixn,ixm]*sinarg)
                r_c2[i] += (RBC[ixn,ixm]*cosarg) #Shaun modification to show the stellarator symetric version
                z_c2[i] += (ZBS[ixn,ixm]*sinarg) #Shaun modification to show the stellarator symetric version

    pl.plot(r_c, z_c, **plkwargs)
    pl.plot(r_c2, z_c2, **plkwargs)
    pl.gca().set_aspect('equal')
    pl.show()
    if debug>3:
        import pdb; pdb.set_trace()
        'debugging, c to continue'
def visualize_log():
    logs = []
    predicts = []
    observes = []
    with open(workdir + '/learn-log.txt','r') as fp:
        for l in iter(fp.readline, ''):
            ws = l.split()
            t = datetime.datetime.strptime(ws[0],"%Y-%m-%dT%H:%M")
            p = float(ws[1])
            o = float(ws[2])
            predicts.append(p)
            observes.append(o)

    pylab.rcParams['figure.figsize'] = (6.4,6.4)
    pylab.gca().set_xscale('log')
    pylab.gca().set_yscale('log')
    pylab.scatter(predicts,observes, color=(1,0,0), zorder = 100,marker='.',s=1)
    pylab.scatter(predicts[-100:],observes[-100:], color=(1,0,0), zorder = 200,marker='o',s=5)
    pylab.scatter(predicts[-10:],observes[-10:], color=(1,0,0), zorder = 300,marker='o',s=10)

    pylab.gca().set_xlabel('prediction')
    pylab.gca().set_ylabel('observation')
    pylab.gca().grid()
    pylab.savefig(workdir+'/log.png')
    pylab.close('all')
Ejemplo n.º 19
0
    def plot_CMD(self, mag1, mag2, savefile=None):
        """
        Make a CMD with mag1 vs. mag1 - mag2

        Parameters
        ----------
        mag1 : string
            The name of the first magnitude column to be plotted.
        mag2 : string
            The name of the second magnitude column to be plotted.
        savefile : string (default None)
            If a savefile is specified, then the plot will be saved to that file. 
        """
        plt.clf()
        plt.plot(self.points[mag1] - self.points[mag2], self.points[mag1],
                 color='black', linestyle='solid', marker='+')
        plt.gca().invert_yaxis()
        plt.xlabel(mag1 + ' - ' + mag2 + ' (mag)')
        plt.ylabel(mag1 + ' (mag)')
        
        fmt_title = 'logAge={0:.2f}, d={1:.2f} kpc, AKs={2:.2f}'
        plt.title(fmt_title.format(self.points.meta['LOGAGE'],
                                  self.points.meta['DISTANCE']/1e3,
                                  self.points.meta['AKS']))

        if savefile != None:
            plt.savefig(savefile)
        
        return
Ejemplo n.º 20
0
def plotLL(fname='out4.npy'):
    plt.figure()
    h= np.linspace(0,1,21)
    g= np.linspace(0,1,21)
    m=np.linspace(0,2,21)
    d=np.linspace(0,2,21)
    out=np.load(fname)
    print np.nanmax(out),np.nanmin(out)
    rang=np.nanmax(out)-np.nanmin(out)
    maxloc= np.squeeze(np.array((np.nanmax(out)==out).nonzero()))
    H,G=np.meshgrid(h,g)
    print maxloc
    for mm in range(m.size/2):
        for dd in range(d.size/2):
            plt.subplot(10,10,(9-mm)*10+dd+1)
            plt.pcolormesh(h,g,out[:,:,mm*2,dd*2].T,
                           vmax=np.nanmax(out),vmin=np.nanmax(out)-rang/4.)
            plt.gca().set_xticks([])
            plt.gca().set_yticks([])
            if mm==maxloc[2]/2 and dd==maxloc[3]/2:
                plt.plot(h[maxloc[0]],g[maxloc[1]],'ow',ms=8)
            if dd==0:
                print mm,dd
                plt.ylabel('%.1f'%m[mm*2])
            if mm==0: plt.xlabel('%.1f'%d[dd*2])
    plt.title(fname[:6])
Ejemplo n.º 21
0
Archivo: LD.py Proyecto: airanmehr/bio
def plotLDDecaySpaceTime2d(ld0=1):
    T=np.arange(0,1500+1,500)
    L=1e6+1
    pos=500000
    r=2*1e-8
    s=0.01;x0=0.005
    # s=0.05;x0=1e-3

    positions=np.arange(0,L,1000)
    dist=abs(positions - pos)
    def getColor(n):
        color=['k','red','blue','g','m','c','coral']
        return color[:n]
    plt.figure(figsize=(25,12))
    for t,color in zip(T,getColor(len(T))):
        LD(t,ld0,s,x0,r,dist,positions).plot(ax=plt.gca(),linewidth=2, color=color,label='t={}'.format(t))
    for t,color in zip(T,getColor(len(T))):
        if not t :continue
        pd.Series(ld0*np.exp(-r*t*(dist)),index=positions).plot(ax=plt.gca(),style='--',color=color,linewidth=2)
    plt.legend(map(lambda x: 't={}'.format(x),T),loc='best');

    plt.axvline(500000,color='k',linewidth=2)
    plt.gca().axvspan(475000, 525000, alpha=0.25, color='black')
    plt.grid();plt.ylim([-0.05,1.1]);plt.xlabel('Position');plt.ylabel('LD to Position 500K');plt.title('Space-Time Decay of LD under Neutral Evolution');
    # plt.savefig(Simulation.paperFiguresPath+'LDDecay2d')
    plt.show()
Ejemplo n.º 22
0
    def plot_fixed_x(self, x_values, x_derivative=0, steps=1000, smooth=0, simple='auto', ymin="auto", ymax="auto", format=True, clear=1):
        """
        plots the data at fixed x-value, so z vs x
        """
        if simple=='auto': simple=self.simple
        
        # get the min and max
        if ymin=="auto": ymin = self.ymin
        if ymax=="auto": ymax = self.ymax
        if clear: _pylab.gca().clear()

        if not type(x_values) in [type([]), type(_pylab.array([]))]: x_values = [x_values]

        for x in x_values:
    
            # define a new simple function to plot, then plot it
            def f(y): return self.evaluate(x, y, x_derivative, smooth, simple)
            _pylab_help.plot_function(f, ymin, ymax, steps, 0, False)

            # label it
            a = _pylab.gca()
            a.set_xlabel(self.ylabel)
            if x_derivative: a.set_ylabel(str(x_derivative)+" "+str(self.xlabel)+" derivative of "+self.zlabel)
            else:            a.set_ylabel(self.zlabel)
            a.set_title(self._path+"\nSpline array plot at fixed x = "+self.xlabel)
            a.get_lines()[-1].set_label("x ("+self.xlabel+") = "+str(x))

        if format: _s.format_figure()
        return a
Ejemplo n.º 23
0
def plotNumVariants(depth):
    plt.figure(figsize=(7, 5), dpi=300)
    depth.apply(lambda x: x.dropna().size / 1000.0).unstack("POP").plot.bar(ax=plt.gca())
    plt.gcf().subplots_adjust(bottom=0.30)
    plt.ylabel(r"Num of variants ($\times$1000)")
    renameLegend(ax=plt.gca())
    plt.savefig(pathPlots + "numVariants.pdf")
Ejemplo n.º 24
0
def _show_rates(rate, wo, wt, attenuator, tau_NP, tau_P):
    import pylab

    #pylab.figure()
    pylab.errorbar(rate, wt[0], yerr=wt[1], fmt='g.', label='attenuated')
    pylab.errorbar(rate, wo[0], yerr=wo[1], fmt='b.', label='unattenuated')

    pylab.xscale('log')
    pylab.yscale('log')
    pylab.xlabel('incident rate (counts/second)')
    pylab.ylabel('observed rate (counts/second)')
    pylab.legend(loc='best')
    pylab.grid(True)
    pylab.plot(rate, rate/attenuator, 'g-', label='target')
    pylab.plot(rate, rate, 'b-', label='target')

    Ipeak, Rpeak = peak_rate(tau_NP=tau_NP, tau_P=tau_P)
    if rate[0] <= Ipeak <= rate[-1]:
        pylab.axvline(x=Ipeak, ls='--', c='b')
        pylab.text(x=Ipeak, y=0.05, s=' %g'%Ipeak,
                   ha='left', va='bottom',
                   transform=pylab.gca().get_xaxis_transform())
    if False:
        pylab.axhline(y=Rpeak, ls='--', c='b')
        pylab.text(y=Rpeak, x=0.05, s=' %g\n'%Rpeak,
                   ha='left', va='bottom',
                   transform=pylab.gca().get_yaxis_transform())
Ejemplo n.º 25
0
def learning_curve_plot(
    predictors, valid_X, valid_Y, valid_W=None, train_X=None, train_Y=None, train_W=None, log_scale=False
):

    if hasattr(valid_W, "values"):
        valid_W = valid_W.values
    if train_W != None and hasattr(train_W, "values"):
        train_W = weights.values

    with_train = True if (train_X != None and valid_X != None) else False

    try:
        predictors = predictors.items()
    except:
        predictors = {"": predictors}.items()

    for name, predictor in predictors:
        iterations = np.arange(1, predictor.n_estimators + 1)
        p, = plt.plot(
            iterations, _step_wise_performance(predictor, valid_X, valid_Y, valid_W), "-", label=name + " (test)"
        )

        if with_train:
            plt.plot(
                iterations,
                _step_wise_performance(predictor, train_X, train_Y, train_W),
                "--",
                color=p.get_color(),
                label=name + " (train)",
            )

        plt.legend(loc="best")

    if log_scale:
        plt.gca().set_xscale("log")
Ejemplo n.º 26
0
def plot_INT_footprint(center_ra,center_dec):
    #using full detector sizes for now because 
    detector_dra = 4100.*0.33/3600. # 2154 pixels * 0.33"/pix, /3600 to get deg
    detector_ddec = 2048.*0.33/3600. # 2154 pixels * 0.33"/pix, /3600 to get deg
    # draw footprint of chip 4
    rect= plt.Rectangle((center_ra-detector_dra/2.,center_dec-detector_ddec/2.), detector_dra, detector_ddec,fill=False, color='k')
    plt.gca().add_artist(rect)
    # draw footprint of chip 3
    # assuming chip 3 is NORTH and a smidge WEST of chip 4
    offset_dec = detector_ddec+17./3600. # 17 arcsec gap in RA between 
    offset_ra = -9.5/3600. # 9.5 arcsec offset toward N
    rect= plt.Rectangle((center_ra+offset_ra-detector_dra/2.,center_dec+offset_dec-detector_ddec/2.), detector_dra, detector_ddec,fill=False, color='k')
    plt.gca().add_artist(rect)

    # draw footprint of chip 1
    # assuming chip 1 is SOUTH and a smidge EAST of chip 4
    offset_dec = -1*detector_ddec-22.7/3600. # 17 arcsec gap in RA between 
    offset_ra = +3.18/3600. # 9.5 arcsec offset toward N
    rect= plt.Rectangle((center_ra+offset_ra-detector_dra/2.,center_dec+offset_dec-detector_ddec/2.), detector_dra, detector_ddec,fill=False, color='k')
    plt.gca().add_artist(rect)

    # draw footprint of chip 2
    # assuming chip 2 is WEST of chip 4
    offset_dec = detector_ddec/2.-detector_dra-19.2/3600. # hard to explain
    offset_ra =  -.5*detector_dra-23.8/3600.# hard to explain
    # this chip is rotated 90 deg, so detecter_dra and detector_ddec are interchanged
    rect= plt.Rectangle((center_ra+offset_ra,center_dec+offset_dec), -1.*detector_ddec, detector_dra,fill=False, color='k')
    plt.gca().add_artist(rect)

    # adding guide camera
    offset_dec = -2*detector_ddec-(22.7+98.1)/3600. # hard to explain
    offset_ra =  detector_dra/2-(3.18+649.9)/3600.# hard to explain
    # this chip is rotated 90 deg, so detecter_dra and detector_ddec are interchanged
    rect= plt.Rectangle((center_ra+offset_ra,center_dec+offset_dec), -7./60., 7./60,fill=False, color='k')
    plt.gca().add_artist(rect)
Ejemplo n.º 27
0
def plot(D,title):
    im=plt.imshow(D,interpolation='nearest',cmap='Reds')
    plt.gca().xaxis.tick_top()
    x=np.arange(D.index.shape[0])
    plt.colorbar(im)
    plt.gca().tick_params(axis='both', which='major', labelsize=10)
    plt.title(title,y=1.03)
Ejemplo n.º 28
0
def plot(filename):
    """
    Read and print all command line arguments
    """
    import pylab

    canvas = pylab.gcf().canvas
    d = data(filename)
    if len(d.v.shape) > 2:
        pylab.gca().pcolormesh(d.v[0, :, :])
        pylab.xlabel(d.xlabel)
        pylab.ylabel(d.ylabel)
    elif len(d.v.shape) > 1:
        if filename.lower().endswith('bt4'):
            offset = 1
        else:
            offset = 0
        pylab.gca().pcolorfast(d.v[:, offset:])
        pylab.xlabel(d.xlabel)
        pylab.ylabel(d.ylabel)
    else:
        pylab.plot(d.x, d.v)
        pylab.xlabel(d.xlabel)
        pylab.ylabel(d.vlabel)
    pylab.show()
Ejemplo n.º 29
0
def validate_vs_jwpsf_nircam():

    models = [ ('NIRCam','F200W', 'f200w_perfect_offset', '/Users/mperrin/software/jwpsf_v3.0/data/NIRCam/OPD/perfect_opd.fits', 0.034,True),
            ('NIRCam','F200W', 'f200w_perfect', '/Users/mperrin/software/jwpsf_v3.0/data/NIRCam/OPD/perfect_opd.fits', 0.034,False),
            ('NIRCam','F200W', 'f200w', '/Users/mperrin/software/jwpsf_v3.0/data/NIRCam/OPD/nircam_obs_w_rsrv1.fits', 0.034,True),
                ('MIRI','F1000W', 'f1000w', '/Users/mperrin/software/jwpsf_v3.0/data/MIRI/OPD/MIRI_OPDisim1.fits', 0.11,True)]


    fig = P.figure(1, figsize=(13,8.5), dpi=80)
    oversamp=4
    for params in models:

        nc = webbpsf_core.Instrument(params[0])
        nc.filter = params[1]
        nc.pupilopd = params[3] #'/Users/mperrin/software/jwpsf_v3.0/data/NIRCam/OPD/nircam_obs_w_rsrv1.fits'
        nc.pixelscale = params[4] #0.034 # this is wrong, but compute this way to match JWPSF exactly
        if params[5]:
            # offset by half a pixel to match the JWPSF convention
            nc.options['source_offset_r'] = params[4]/2 * N.sqrt(2)/oversamp  # offset half a pixel each in X and Y
            nc.options['source_offset_theta'] = -45


        jw_fn = 'jwpsf_%s_%s.fits' % (params[0].lower(), params[2].lower())
        my_fn = 'test_vs_' + jw_fn

        if not os.path.exists( my_fn):
            my_psf = nc.calcPSF(my_fn, oversample=oversamp, fov_pixels=512./oversamp)
        else:
            my_psf = fits.open(my_fn)

        jw_psf = fits.open(jw_fn)
        jw_psf[0].header.update('PIXELSCL', jw_psf[0].header['CDELT1']*3600)


        P.clf()
        #P.subplots_adjust(top=0.95, bottom=0.05, left=0.01, right=0.99)
        P.subplot(231)
        titlestr = "%s %s, \n"%  (params[0], params[2])
        poppy.display_PSF(my_psf, title=titlestr+"computed with WebbPSF" , colorbar=False)
        P.subplot(232)
        poppy.display_PSF(jw_psf, title=titlestr+"computed with JWPSF" , colorbar=False)
        P.subplot(233)
        poppy.display_PSF_difference(my_psf,jw_psf, title=titlestr+'Difference Image', colorbar=False)

        imagecrop = 30*params[4]

        P.subplot(234)
        poppy.display_PSF(my_psf, title=titlestr+"computed with WebbPSF", colorbar=False, imagecrop=imagecrop)
        centroid = poppy.measure_centroid(my_psf)
        P.gca().set_xlabel("centroid = (%.3f,%.3f)" % centroid)

        P.subplot(235)
        poppy.display_PSF(jw_psf, title=titlestr+"computed with JWPSF", colorbar=False, imagecrop=imagecrop)
        centroid = poppy.measure_centroid(jw_psf)
        P.gca().set_xlabel("centroid = (%.3f,%.3f)" % centroid)

        P.subplot(236)
        poppy.display_PSF_difference(my_psf,jw_psf, title='Difference Image', colorbar=False, imagecrop=imagecrop)

        P.savefig("results_vs_jwpsf_%s_%s.pdf" % (params[0], params[2]))
Ejemplo n.º 30
0
    def plot_fixed_y(self, y_values, x_derivative=0, steps=1000, smooth=0, simple='auto', xmin="auto", xmax="auto", format=True, clear=1):
        """
        plots the data at a fixed y-value, so z vs y
        """
        if simple=='auto': simple=self.simple


        # get the min and max
        if xmin=="auto": xmin = self.xmin
        if xmax=="auto": xmax = self.xmax
        if clear: _pylab.gca().clear()

        if not type(y_values) in [type([]), type(_pylab.array([]))]: y_values = [y_values]

        for y in y_values:
            # define a new simple function to plot, then plot it
            def f(x): return self.evaluate(x, y, x_derivative, smooth, simple)
            _pylab_help.plot_function(f, xmin, xmax, steps, 0, True)

            # label it
            a = _pylab.gca()
            th = "th"
            if x_derivative == 1: th = "st"
            if x_derivative == 2: th = "nd"
            if x_derivative == 3: th = "rd"
            if x_derivative: a.set_ylabel(str(x_derivative)+th+" "+self.xlabel+" derivative of "+self.zlabel+" spline")
            else:            a.set_ylabel(self.zlabel)
            a.set_xlabel(self.xlabel)
            a.set_title(self._path+"\nSpline array plot at fixed y "+self.ylabel)
            a.get_lines()[-1].set_label("y ("+self.ylabel+") = "+str(y))
        if format: _s.format_figure()
        return a
Ejemplo n.º 31
0
def plot_contours(A,
                  Cn,
                  thr=None,
                  thr_method='max',
                  maxthr=0.2,
                  nrgthr=0.9,
                  display_numbers=True,
                  max_number=None,
                  cmap=None,
                  swap_dim=False,
                  colors='w',
                  vmin=None,
                  vmax=None,
                  **kwargs):
    """Plots contour of spatial components against a background image and returns their coordinates

     Parameters:
     -----------
     A:   np.ndarray or sparse matrix
               Matrix of Spatial components (d x K)

     Cn:  np.ndarray (2D)
               Background image (e.g. mean, correlation)

     thr_method: [optional] string
              Method of thresholding:
                  'max' sets to zero pixels that have value less than a fraction of the max value
                  'nrg' keeps the pixels that contribute up to a specified fraction of the energy

     maxthr: [optional] scalar
                Threshold of max value

     nrgthr: [optional] scalar
                Threshold of energy

     thr: scalar between 0 and 1
               Energy threshold for computing contours (default 0.9)
               Kept for backwards compatibility. If not None then thr_method = 'nrg', and nrgthr = thr

     display_number:     Boolean
               Display number of ROIs if checked (default True)

     max_number:    int
               Display the number for only the first max_number components (default None, display all numbers)

     cmap:     string
               User specifies the colormap (default None, default colormap)

     Returns:
     --------
     Coor: list of coordinates with center of mass, contour plot coordinates and bounding box for each component
    """
    if issparse(A):
        A = np.array(A.todense())
    else:
        A = np.array(A)

    if swap_dim:
        Cn = Cn.T
        print('Swapping dim')

    d1, d2 = np.shape(Cn)
    d, nr = np.shape(A)
    if max_number is None:
        max_number = nr

    if thr is not None:
        thr_method = 'nrg'
        nrgthr = thr
        warn(
            "The way to call utilities.plot_contours has changed. Look at the definition for more details."
        )

    x, y = np.mgrid[0:d1:1, 0:d2:1]

    ax = pl.gca()
    if vmax is None and vmin is None:
        pl.imshow(Cn,
                  interpolation=None,
                  cmap=cmap,
                  vmin=np.percentile(Cn[~np.isnan(Cn)], 1),
                  vmax=np.percentile(Cn[~np.isnan(Cn)], 99))
    else:
        pl.imshow(Cn, interpolation=None, cmap=cmap, vmin=vmin, vmax=vmax)

    coordinates = []
    cm = com(A, d1, d2)
    for i in range(np.minimum(nr, max_number)):
        pars = dict(kwargs)
        if thr_method == 'nrg':
            indx = np.argsort(A[:, i], axis=None)[::-1]
            cumEn = np.cumsum(A[:, i].flatten()[indx]**2)
            cumEn /= cumEn[-1]
            Bvec = np.zeros(d)
            Bvec[indx] = cumEn
            thr = nrgthr

        else:  # thr_method = 'max'
            if thr_method != 'max':
                warn("Unknown threshold method. Choosing max")
            Bvec = A[:, i].flatten()
            Bvec /= np.max(Bvec)
            thr = maxthr

        if swap_dim:
            Bmat = np.reshape(Bvec, np.shape(Cn), order='C')
        else:
            Bmat = np.reshape(Bvec, np.shape(Cn), order='F')
        cs = pl.contour(y, x, Bmat, [thr], colors=colors)
        # this fix is necessary for having disjoint figures and borders plotted correctly
        p = cs.collections[0].get_paths()
        v = np.atleast_2d([np.nan, np.nan])
        for pths in p:
            vtx = pths.vertices
            num_close_coords = np.sum(np.isclose(vtx[0, :], vtx[-1, :]))
            if num_close_coords < 2:
                if num_close_coords == 0:
                    # case angle
                    newpt = np.round(old_div(vtx[-1, :], [d2, d1])) * [d2, d1]
                    #import ipdb; ipdb.set_trace()
                    vtx = np.concatenate((vtx, newpt[np.newaxis, :]), axis=0)

                else:
                    # case one is border
                    vtx = np.concatenate((vtx, vtx[0, np.newaxis]), axis=0)
                    #import ipdb; ipdb.set_trace()

            v = np.concatenate((v, vtx, np.atleast_2d([np.nan, np.nan])),
                               axis=0)

        pars['CoM'] = np.squeeze(cm[i, :])
        pars['coordinates'] = v
        pars['bbox'] = [
            np.floor(np.min(v[:, 1])),
            np.ceil(np.max(v[:, 1])),
            np.floor(np.min(v[:, 0])),
            np.ceil(np.max(v[:, 0]))
        ]
        pars['neuron_id'] = i + 1
        coordinates.append(pars)

    if display_numbers:
        for i in range(np.minimum(nr, max_number)):
            if swap_dim:
                ax.text(cm[i, 0], cm[i, 1], str(i + 1), color=colors)
            else:
                ax.text(cm[i, 1], cm[i, 0], str(i + 1), color=colors)

    return coordinates
Ejemplo n.º 32
0
    pl.ylabel ("number of bins in intrinsic and observable parameters:\n" + 
               r"$N_\mathcal{B} \times N_{\mathcal{A}_{j,q}}$", 
               multialignment='center')
    pl.savefig(filename)

plotImage (Ls, bins, N_objs, "L_vs_N.eps")
plotImage (Ls_std, bins, N_objs, "L_vs_N_std.eps")

if args.plot_N_objs:
    print (Ls[N_objs == args.plot_N_objs]).shape
    print Ls[N_objs == args.plot_N_objs]
    Ls_plot = Ls[N_objs == args.plot_N_objs][0].reshape((len(bins_obs), len(bins_int)))
    pl.clf()
    pl.subplots_adjust(bottom=0.15)
    pl.imshow(Ls_plot.transpose(), interpolation = "nearest", vmin = 0.1, vmax = 0.35)
    pl.gca().invert_yaxis()
    pl.colorbar()
    pl.xticks (np.arange(len(bins_obs)), bins_obs, rotation = "60")
    pl.yticks (np.arange(len(bins_int)), 2**bins_int)
    pl.xlabel ("number of bins in observables")
    pl.ylabel ("number of bins in intrinsic", 
               multialignment='center')
    pl.savefig("L_vs_bins_2D_" + str(args.plot_N_objs) + "_Niter" + str (N_iter) + ".eps")

if not args.plot_N_bins_int is None:
    print args.plot_N_bins_int
    crit = np.zeros(bins.shape[0], dtype = bool)
    sel_bins = np.array(args.plot_N_bins_int, dtype = int)
    for i in range (len(crit)):
        for j in range (sel_bins.shape[0]):
            if np.all(bins[i] == sel_bins[j]):
Ejemplo n.º 33
0
%matplotlib inline
import time
import numpy as np
import pylab as plt
from IPython.display import display, clear_output

fig = plt.figure(figsize=(5,5))
ax = plt.gca()
ax.set_xlim((-2,2))
ax.set_ylim((-2,2))

th = np.pi/90.
A = 0.999*np.mat([[np.cos(th),np.sin(th)],[-np.sin(th),np.cos(th)]])
X = np.mat([[1,-1],[1,-1]])

ln = plt.Line2D(xdata=(X[0,0], X[0,1]), ydata=(X[1,0], X[1,1]), marker='o',linewidth=1)
ax.add_line(ln)
ax.set_axis_off()
plt.close(fig)

for i in range(500):
    X = A*X
    ln.set_xdata((X[0,0], X[0,1]))
    ln.set_ydata((X[1,0], X[1,1]))
    display(fig)
    #display(plt.gcf())
    time.sleep(0.05)
    clear_output(wait=True)
Ejemplo n.º 34
0
print(
    "Decay function with parameters {0:.2f} and {1:.2f} results in daily reduction of {2:.2f} points with zero precipitation."
    .format(a, b,
            decay_func(0, a, b) * 24))

x = np.arange(0, 20.0, 0.1)
res = decay_func(x, a, b)

plt.scatter(new_snow_1h_decay_cat, new_snow_1h_decay_score)
plt.plot(x, res)

plt.xlabel('Hourly new snow amount (mm w.e.)')
plt.ylabel('Decay')
plt.xlim(0, 20)
plt.ylim(0, 10)
plt.gca().add_patch(
    Rectangle((0, 0), 40, 100, edgecolor="lightgrey", facecolor="lightgrey"))

# ### Main control factors

# In[3]:

# New snow amount last 24 h 0-60 cm [10 cm intervals]
new_snow_24h_cat = np.array([0, 20, 40, 60, 80, 100, 120])
new_snow_24h_score = np.array([0.5, 8.0, 15.0, 19., 21.0, 27.0, 33.3])

# Wind speed 0-100 km/h [0,10,20,30,40,50,60,80,100]
wind_speed_cat = np.array([-1.5, 0, 2.5, 5, 7.5, 10, 15, 20, 25, 30,
                           40])  # m/s
wind_speed_score = np.array(
    [-1.0, 0.8, 2.0, 2.9, 3.2, 3.0, 1.1, 0.6, 0.4, 0.2, 0.0])
Ejemplo n.º 35
0
               c=es[cut].astype(np.float),
               marker='^',
               cmap=cmap,
               norm=norm)

    plt.text(1.35, 23.1, EW + r'$\AA$')

    pl.xlim(np.unique(TRUEZS)[0], np.unique(TRUEZS)[-1])
    pl.ylim(
        np.unique(TRUEMAGS[np.isfinite(TRUEMAGS)])[0],
        np.unique(TRUEMAGS[np.isfinite(TRUEMAGS)])[-1])

    pl.xlabel(r'$z$')
    pl.ylabel(r'$g_{AB}$')

    ax = pl.gca()
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)

    cb      = mpl.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm, spacing='proportional', ticks=bounds+0.5,\
                                        boundaries=bounds, format='%.2lf')

    cb.set_ticklabels(bounds, update_ticks=True)
    cb.set_label('Exposure time [1500 s]', rotation=270, labelpad=20)

    plt.tight_layout()

    pl.savefig(os.environ['BEAST'] + '/redrock/plots/%s/%s/expgrid_%s.pdf' %
               (survey, target, str(EW).replace('.', 'p')),
               bbox_inches='tight')
Ejemplo n.º 36
0
    def test_radius_indexes_2d_graphical(self):
        raise SkipTest
        #uc = UnitCell(np.array([
        #    [2.0, 1.0, 0.0],
        #    [0.0, 0.2, 0.0],
        #    [0.0, 0.0, 10.0],
        #]))
        #radius = 0.8
        uc = UnitCell(
            np.array([
                [1.0, 1.0, 0.0],
                [0.0, 1.0, 0.0],
                [0.0, 0.0, 10.0],
            ]))
        radius = 5.3
        #uc = UnitCell(np.array([
        #    [1.0, 1.0, 0.0],
        #    [0.0, 1.0, 0.0],
        #    [0.0, 0.0, 1.0],
        #]))
        #radius = 0.9

        fracs = np.arange(-0.5, 0.55, 0.1)
        import pylab
        from matplotlib.patches import Circle, Polygon
        from matplotlib.lines import Line2D
        pylab.clf()
        for i0 in fracs:
            for i1 in fracs:
                center = uc.to_cartesian([i0, i1, 0.0])
                pylab.gca().add_artist(
                    Circle((center[0], center[1]),
                           radius,
                           fill=True,
                           fc='#7777AA',
                           ec='none'))
        pylab.gca().add_artist(
            Circle((0, 0), radius, fill=True, fc='#0000AA', ec='none'))

        ranges = uc.get_radius_ranges(radius)
        indexes = uc.get_radius_indexes(radius)

        for i in range(-ranges[0] - 1, ranges[0] + 1):
            start = uc.to_cartesian([i + 0.5, -ranges[1] - 0.5, 0])
            end = uc.to_cartesian([i + 0.5, ranges[1] + 0.5, 0])
            pylab.gca().add_artist(
                Line2D([start[0], end[0]], [start[1], end[1]],
                       color="k",
                       linewidth=1))

        for i in range(-ranges[1] - 1, ranges[1] + 1):
            start = uc.to_cartesian([-ranges[0] - 0.5, i + 0.5, 0])
            end = uc.to_cartesian([ranges[0] + 0.5, i + 0.5, 0])
            pylab.gca().add_artist(
                Line2D([start[0], end[0]], [start[1], end[1]],
                       color="k",
                       linewidth=1))

        for i in range(-ranges[0], ranges[0] + 1):
            start = uc.to_cartesian([i, -ranges[1] - 0.5, 0])
            end = uc.to_cartesian([i, ranges[1] + 0.5, 0])
            pylab.gca().add_artist(
                Line2D([start[0], end[0]], [start[1], end[1]],
                       color="k",
                       linewidth=0.5,
                       linestyle="--"))

        for i in range(-ranges[1], ranges[1] + 1):
            start = uc.to_cartesian([-ranges[0] - 0.5, i, 0])
            end = uc.to_cartesian([ranges[0] + 0.5, i, 0])
            pylab.gca().add_artist(
                Line2D([start[0], end[0]], [start[1], end[1]],
                       color="k",
                       linewidth=0.5,
                       linestyle="--"))

        for i0, i1, i2 in indexes:
            if i2 != 0:
                continue
            corners = uc.to_cartesian(
                np.array([
                    [i0 - 0.5, i1 - 0.5, 0.0],
                    [i0 - 0.5, i1 + 0.5, 0.0],
                    [i0 + 0.5, i1 + 0.5, 0.0],
                    [i0 + 0.5, i1 - 0.5, 0.0],
                ]))
            pylab.gca().add_artist(
                Polygon(corners[:, :2],
                        fill=True,
                        ec='none',
                        fc='r',
                        alpha=0.5))

        corners = uc.to_cartesian(
            np.array([
                [-ranges[0] - 0.5, -ranges[1] - 0.5, 0.0],
                [-ranges[0] - 0.5, +ranges[1] + 0.5, 0.0],
                [+ranges[0] + 0.5, +ranges[1] + 0.5, 0.0],
                [+ranges[0] + 0.5, -ranges[1] - 0.5, 0.0],
            ]))
        pylab.xlim(1.1 * corners[:, :2].min(), 1.1 * corners[:, :2].max())
        pylab.ylim(1.1 * corners[:, :2].min(), 1.1 * corners[:, :2].max())
                (cf_comp_turb, k_comp_t,
                 k_reyn_t) = compressible_turbulent_flat_plate(Re, 0.0, 216.0)
            ii = ii + 1

        cf_comp_empirical = np.array([[.0073, .0045, .0031, .0022, .0016],
                                      [.0074, .0044, .0029, .0020, .0015],
                                      [.0073, .0041, .0026, .0018, .0014],
                                      [.0070, .0038, .0024, .0017, .0013],
                                      [.0067, .0036, .0021, .0015, .0011],
                                      [.0064, .0033, .0020, .0013, .0009],
                                      [.0060, .0029, .0017, .0011, .0007],
                                      [.0052, .0022, .0011, .0006, .0004],
                                      [.0041, .0013, .0004, .0001, .00005]])

        plt.figure("Skin Friction Coefficient v. Reynolds Number")
        axes = plt.gca()
        for i in range(len(cf_comp[:, 0])):
            axes.semilogx(Re, cf_comp_empirical[i, :], 'ro-')
            axes.semilogx(Re, cf_comp[i, :], 'bo-')
            axes.semilogx(Re, cf_comp_turb, 'go-')
        axes.set_xlabel('Reynolds Number')
        axes.set_ylabel('Cf')
        axes.grid(True)
        plt.show()

    else:

        Re = 10**7
        Ma = 2.0
        Tc = 216.0
        xt = 0.6
Ejemplo n.º 38
0
sigma = 0.4  # sigma and s_map are needed for the graphical output
s_map = [(1.0, 1.0), (2.0, 1.0), (3.0, 1.0), 
         (1.0, 2.0), (2.0, 2.0), (3.0, 2.0), 
         (1.0, 3.0), (2.0, 3.0), (3.0, 3.0)] 
neighbor =  [[1, 3, 0, 0], [2, 4, 0, 1], [2, 5, 1, 2],
             [4, 6, 3, 0], [5, 7, 3, 1], [5, 8, 4, 2],
             [7, 6, 6, 3], [8, 7, 6, 4], [8, 8, 7, 5]]
site = 8
N_runs = 10
for run in range(N_runs):
    if run < 10: number_string = '0'+str(run)
    else: number_string = str(run)
    # Begin of graphical output
    cir = pylab.Circle(s_map[site], radius=sigma, fc='r')
    pylab.gca().add_patch(cir)
    pylab.plot([0.5, 3.5], [1.5, 1.5], 'b')
    pylab.plot([0.5, 3.5], [2.5, 2.5], 'b')
    pylab.plot([1.5, 1.5], [0.5, 3.5], 'b')
    pylab.plot([2.5, 2.5], [0.5, 3.5], 'b')
    pylab.title('t = '+ number_string)
    pylab.axis('scaled')
    pylab.axis([0.5, 3.5, 0.5, 3.5])
    pylab.xticks([])
    pylab.yticks([])
    # pylab.savefig('pebble_basic_movie_'+number_string+'.png', transparent=False)
    pylab.show()
    pylab.clf()
    # End of graphical output
    site = neighbor[site][ random.randint(0, 3)]
Ejemplo n.º 39
0
    # Figure out where the redshift bins are for f(z)
    # A, bHI, f(z), sigma_NL, aperp(z), apar(z); zfns = [5, 4, 2]
    sigma_f = sigmas[2:2 + zc.size]
    ff = f(zc)

    # Plot errors
    P.plot(zc, sigma_f / ff, lw=1.5, label=str(bHI[j]), marker='.')

P.xlabel("$z$", fontdict={'fontsize': '20'})
P.ylabel("Fractional error", fontdict={'fontsize': '20'})

P.ylim((0., 0.064))
P.xlim((0.9 * np.min(zc), 1.005 * np.max(zc)))

# Legend
P.legend(loc='upper left', prop={'size': 'x-large'}, ncol=2)

# Shaded regions in different redshift regimes
#P.axvspan(np.max(zclist[0]), 3., ec='none', fc='#f2f2f2')
#P.axvspan(0., np.min([np.min(_zc) for _zc in zclist]), ec='none', fc='#cdcdcd')
#P.axvspan(np.min([np.min(_zc) for _zc in zclist]), np.min(zc), ec='none', fc='#f2f2f2')

# Display options
fontsize = 18.
for tick in P.gca().yaxis.get_major_ticks():
    tick.label1.set_fontsize(fontsize)
for tick in P.gca().xaxis.get_major_ticks():
    tick.label1.set_fontsize(fontsize)
P.tight_layout()
P.show()
Ejemplo n.º 40
0
        theta  = p2.copy()

        x = (radius + 5.)*np.cos(theta)
        y = (radius + 5.)*np.sin(theta)
        
        x_bg = 5*np.cos(theta)
        y_bg = 5*np.sin(theta)

        print ('p2 : ', p2.shape)
        #pl.plot(p2, f_at_desired_q)
        pl.plot(x, y, color='r', linestyle = '-', lw=3)
        pl.plot(x_bg, y_bg, color='k', alpha=0.5, lw=3)
        #pl.contourf(p1_meshgrid, p2_meshgrid, f_at_desired_q, 100, cmap='bwr')

        #np.savetxt('data/f_vs_theta_%d_%d.txt'%(index_1, index_2), f_at_desired_q)
        #f = np.loadtxt('data/f_vs_theta_%d_%d.txt'%(index_1, index_2))
    
    
        #pl.contourf(p_x, p_y, f_at_desired_q, 100, cmap='bwr')
        #pl.title(r'Time = ' + "%.2f"%(time_array[file_number]) + " ps")
        pl.xlabel('$p_x$')
        pl.ylabel('$p_y$')

        pl.xlim([-6.5, 6.5])
        pl.ylim([-6.5, 6.5])

        pl.gca().set_aspect('equal')
        pl.savefig('images/dist_func_at_a_point_%d_%d.png'%(index_1, index_2))       
        pl.clf()

Ejemplo n.º 41
0
def xy_data(xdata, ydata, eydata=None, exdata=None, label=None, xlabel='', ylabel='',               \
            title='', shell_history=1, xshift=0, yshift=0, xshift_every=1, yshift_every=1,        \
            coarsen=0, style=None,  clear=True, axes=None, xscale='linear', yscale='linear', grid=False,       \
            legend='best', legend_max=20, autoformat=True, tall=False, draw=True, **kwargs):
    """
    Plots specified data.

    xdata, ydata        Arrays (or arrays of arrays) of data to plot
    eydata, exdata      Arrays of x and y errorbar values
    label               string or array of strings for the line labels
    xlabel=''           label for the x-axis
    ylabel=''           label for the y-axis
    title=''            title for the axes; set to None to have nothing.
    shell_history=1     how many commands from the pyshell history to include
                        with the title
    xshift=0, yshift=0  progressive shifts on the data, to make waterfall plots
    xshift_every=1      perform the progressive shift every 1 or n'th line.
    yshift_every=1      perform the progressive shift every 1 or n'th line.
    style               style cycle object.
    clear=True          if no axes are specified, clear the figure, otherwise
                        clear just the axes.
    axes=None           which axes to use, or "gca" for the current axes
    xscale,yscale       'linear' by default. Set either to 'log' for log axes
    grid=False          Should we draw a grid on the axes?
    legend='best'       where to place the legend (see pylab.legend())
                        Set this to None to ignore the legend.
    legend_max=20       number of legend entries before it's truncated with '...'
    autoformat=True     Should we format the figure for printing?
    False               Should the format be tall?
    draw=True           whether or not to draw the plot after plotting


    **kwargs are sent to pylab.errorbar()
    """

    _pylab.ioff()

    # make sure everything is at least iterable.
    if not _fun.is_iterable(xdata): xdata = [xdata]
    if not _fun.is_iterable(exdata): exdata = [exdata]
    if not _fun.is_iterable(ydata): ydata = [ydata]
    if not _fun.is_iterable(eydata): eydata = [eydata]

    # make sure at least xdata and ydata are 2-D
    if _fun.is_a_number(xdata[0]): xdata = [xdata]
    if _fun.is_a_number(ydata[0]): ydata = [ydata]

    # make sure the number of data sets agrees
    N = max(len(xdata), len(ydata))
    for n in range(N - len(xdata)):
        xdata.append(xdata[0])
    for n in range(N - len(ydata)):
        ydata.append(ydata[0])
    for n in range(N - len(exdata)):
        exdata.append(exdata[0])
    for n in range(N - len(eydata)):
        eydata.append(eydata[0])

    # loop over each x and y data set, making sure None's are all converted
    # to counting arrays
    for n in range(N):

        # clean up the [None]'s
        if _fun.is_iterable(xdata[n]) and xdata[n][0] is None: xdata[n] = None
        if _fun.is_iterable(ydata[n]) and ydata[n][0] is None: ydata[n] = None

        if xdata[n] is None and ydata[n] is None:
            print "ERROR: " + str(n) + "'th data set is (None, None)."
            return

        if xdata[n] is None: xdata[n] = _n.arange(len(ydata[n]))
        if ydata[n] is None: ydata[n] = _n.arange(len(xdata[n]))

    # check that the labels is a list of strings of the same length
    if not _fun.is_iterable(label): label = [label] * N
    while len(label) < len(ydata):
        label.append(label[0])

    # concatenate if necessary
    if len(label) > legend_max:
        label[legend_max - 2] = '...'
        for n in range(legend_max - 1, len(label) - 1):
            label[n] = "_nolegend_"

    # clear the figure?
    if clear and not axes: _pylab.gcf().clear()  # axes cleared later

    # setup axes
    if axes == "gca" or axes is None: axes = _pylab.gca()

    # if we're clearing the axes
    if clear: axes.clear()

    # set the current axes
    _pylab.axes(axes)

    # now loop over the list of data in xdata and ydata
    for n in range(0, len(xdata)):
        # get the label
        if label: l = str(label[n])
        else: l = str(n)

        # calculate the x an y progressive shifts
        dx = xshift * (n / xshift_every)
        dy = yshift * (n / yshift_every)

        # if we're supposed to coarsen the data, do so.
        x = _fun.coarsen_array(xdata[n], coarsen)
        y = _fun.coarsen_array(ydata[n], coarsen)
        ey = _fun.coarsen_array(eydata[n], coarsen, 'quadrature')
        ex = _fun.coarsen_array(exdata[n], coarsen, 'quadrature')

        # update the style
        if not style is None: kwargs.update(style.next())
        axes.errorbar(x + dx, y + dy, label=l, yerr=ey, xerr=ex, **kwargs)

    _pylab.xscale(xscale)
    _pylab.yscale(yscale)
    if legend: axes.legend(loc=legend)
    axes.set_xlabel(xlabel)
    axes.set_ylabel(ylabel)

    # for some arguments there should be no title.
    if title in [None, False, 0]:
        axes.set_title('')

    # add the commands to the title
    else:
        title = str(title)
        history = _fun.get_shell_history()
        for n in range(0, min(shell_history, len(history))):
            title = title + "\n" + history[n].split('\n')[0].strip()

        title = title + '\nPlot created ' + _time.asctime()
        axes.set_title(title)

    if grid: _pylab.grid(True)

    if autoformat:
        _pt.format_figure(draw=False)
        _pt.auto_zoom(axes=axes, draw=False)

    # update the canvas
    if draw:
        _pylab.ion()
        _pylab.draw()
        _pylab.show()

    return axes
Ejemplo n.º 42
0
def plot_mission(results, line_style='bo-'):

    # ------------------------------------------------------------------
    #   Throttle
    # ------------------------------------------------------------------
    plt.figure("Throttle History")
    axes = plt.gca()
    for i in range(len(results.segments)):
        time = results.segments[
            i].conditions.frames.inertial.time[:, 0] / Units.min
        eta = results.segments[i].conditions.propulsion.throttle[:, 0]
        axes.plot(time, eta, line_style)
    axes.set_xlabel('Time (mins)')
    axes.set_ylabel('Throttle')
    axes.grid(True)

    # ------------------------------------------------------------------
    #   Angle of Attack
    # ------------------------------------------------------------------

    plt.figure("Angle of Attack History")
    axes = plt.gca()
    for i in range(len(results.segments)):
        time = results.segments[
            i].conditions.frames.inertial.time[:, 0] / Units.min
        aoa = results.segments[
            i].conditions.aerodynamics.angle_of_attack[:, 0] / Units.deg
        axes.plot(time, aoa, line_style)
    axes.set_xlabel('Time (mins)')
    axes.set_ylabel('Angle of Attack (deg)')
    axes.grid(True)

    # ------------------------------------------------------------------
    #   Fuel Burn Rate
    # ------------------------------------------------------------------
    plt.figure("Fuel Burn Rate")
    axes = plt.gca()
    for i in range(len(results.segments)):
        time = results.segments[
            i].conditions.frames.inertial.time[:, 0] / Units.min
        mdot = results.segments[i].conditions.weights.vehicle_mass_rate[:, 0]
        axes.plot(time, mdot, line_style)
    axes.set_xlabel('Time (mins)')
    axes.set_ylabel('Fuel Burn Rate (kg/s)')
    axes.grid(True)

    # ------------------------------------------------------------------
    #   Altitude
    # ------------------------------------------------------------------
    plt.figure("Altitude")
    axes = plt.gca()
    for i in range(len(results.segments)):
        time = results.segments[
            i].conditions.frames.inertial.time[:, 0] / Units.min
        altitude = results.segments[
            i].conditions.freestream.altitude[:, 0] / Units.km
        axes.plot(time, altitude, line_style)
    axes.set_xlabel('Time (mins)')
    axes.set_ylabel('Altitude (km)')
    axes.grid(True)

    # ------------------------------------------------------------------
    #   Vehicle Mass
    # ------------------------------------------------------------------
    plt.figure("Vehicle Mass")
    axes = plt.gca()
    for i in range(len(results.segments)):
        time = results.segments[
            i].conditions.frames.inertial.time[:, 0] / Units.min
        mass = results.segments[i].conditions.weights.total_mass[:, 0]
        axes.plot(time, mass, line_style)
    axes.set_xlabel('Time (mins)')
    axes.set_ylabel('Vehicle Mass (kg)')
    axes.grid(True)

    # ------------------------------------------------------------------
    #   Aerodynamics
    # ------------------------------------------------------------------
    fig = plt.figure("Aerodynamic Forces")
    for segment in results.segments.values():

        time = segment.conditions.frames.inertial.time[:, 0] / Units.min
        Lift = -segment.conditions.frames.wind.lift_force_vector[:, 2]
        Drag = -segment.conditions.frames.wind.drag_force_vector[:, 0]
        Thrust = segment.conditions.frames.body.thrust_force_vector[:, 0]

        axes = fig.add_subplot(4, 1, 1)
        axes.plot(time, Lift, line_style)
        axes.set_xlabel('Time (min)')
        axes.set_ylabel('Lift (N)')
        axes.grid(True)

        axes = fig.add_subplot(4, 1, 2)
        axes.plot(time, Drag, line_style)
        axes.set_xlabel('Time (min)')
        axes.set_ylabel('Drag (N)')
        axes.grid(True)

        axes = fig.add_subplot(4, 1, 3)
        axes.plot(time, Thrust, line_style)
        axes.set_xlabel('Time (min)')
        axes.set_ylabel('Thrust (N)')
        axes.grid(True)

        LD = Lift / Drag
        axes = fig.add_subplot(4, 1, 4)
        axes.plot(time, LD, line_style)
        axes.set_xlabel('Time (min)')
        axes.set_ylabel('L/D')
        axes.grid(True)

    # ------------------------------------------------------------------
    #   Aerodynamics 2
    # ------------------------------------------------------------------
    fig = plt.figure("Aerodynamic Coefficients")
    for segment in results.segments.values():

        time = segment.conditions.frames.inertial.time[:, 0] / Units.min
        CLift = segment.conditions.aerodynamics.lift_coefficient[:, 0]
        CDrag = segment.conditions.aerodynamics.drag_coefficient[:, 0]
        Drag = -segment.conditions.frames.wind.drag_force_vector[:, 0]
        Thrust = segment.conditions.frames.body.thrust_force_vector[:, 0]

        axes = fig.add_subplot(3, 1, 1)
        axes.plot(time, CLift, line_style)
        axes.set_xlabel('Time (min)')
        axes.set_ylabel('CL')
        axes.grid(True)

        axes = fig.add_subplot(3, 1, 2)
        axes.plot(time, CDrag, line_style)
        axes.set_xlabel('Time (min)')
        axes.set_ylabel('CD')
        axes.grid(True)

        axes = fig.add_subplot(3, 1, 3)
        axes.plot(time, Drag, line_style)
        if line_style == 'bo-':
            axes.plot(time, Thrust, 'ro-')
        else:
            axes.plot(time, Thrust, line_style)
        axes.set_xlabel('Time (min)')
        axes.set_ylabel('Drag and Thrust (N)')
        axes.grid(True)

    # ------------------------------------------------------------------
    #   Aerodynamics 2
    # ------------------------------------------------------------------
    fig = plt.figure("Drag Components")
    axes = plt.gca()
    for i, segment in enumerate(results.segments.values()):

        time = segment.conditions.frames.inertial.time[:, 0] / Units.min
        drag_breakdown = segment.conditions.aerodynamics.drag_breakdown
        cdp = drag_breakdown.parasite.total[:, 0]
        cdi = drag_breakdown.induced.total[:, 0]
        cdc = drag_breakdown.compressible.total[:, 0]
        cdm = drag_breakdown.miscellaneous.total[:, 0]
        cd = drag_breakdown.total[:, 0]

        if line_style == 'bo-':
            axes.plot(time, cdp, 'ko-', label='CD_P')
            axes.plot(time, cdi, 'bo-', label='CD_I')
            axes.plot(time, cdc, 'go-', label='CD_C')
            axes.plot(time, cdm, 'yo-', label='CD_M')
            axes.plot(time, cd, 'ro-', label='CD')
            if i == 0:
                axes.legend(loc='upper center')
        else:
            axes.plot(time, cdp, line_style)
            axes.plot(time, cdi, line_style)
            axes.plot(time, cdc, line_style)
            axes.plot(time, cdm, line_style)
            axes.plot(time, cd, line_style)

    axes.set_xlabel('Time (min)')
    axes.set_ylabel('CD')
    axes.grid(True)

    # ------------------------------------------------------------------
    #   Concorde Debug
    # ------------------------------------------------------------------

    fig = plt.figure("Velocity and Density")
    dist_base = 0.0
    for segment in results.segments.values():

        time = segment.conditions.frames.inertial.time[:, 0] / Units.min
        velocity = segment.conditions.freestream.velocity[:, 0]
        density = segment.conditions.freestream.density[:, 0]
        mach_number = segment.conditions.freestream.mach_number[:, 0]

        axes = fig.add_subplot(3, 1, 1)
        axes.plot(time, velocity, line_style)
        axes.set_xlabel('Time (min)')
        axes.set_ylabel('Velocity (m/s)')
        axes.grid(True)

        axes = fig.add_subplot(3, 1, 2)
        axes.plot(time, mach_number, line_style)
        axes.set_xlabel('Time (min)')
        axes.set_ylabel('Mach')
        axes.grid(True)

        distance = np.array([dist_base] * len(time))
        distance[1:] = integrate.cumtrapz(velocity * 1.94,
                                          time / 60.0) + dist_base
        dist_base = distance[-1]

        axes = fig.add_subplot(3, 1, 3)
        axes.plot(time, distance, line_style)
        axes.set_xlabel('Time (min)')
        axes.set_ylabel('Distance (nmi)')

    # ------------------------------------------------------------------
    #   SUAVE Paper Chart
    # ------------------------------------------------------------------

    # This is chart provided in paper presented at Aviation 2015

    fig = plt.figure("SUAVE Paper Chart")
    fig.set_figheight(10)
    fig.set_figwidth(6.5)
    axes = fig.add_subplot(3, 1, 1)
    for segment in results.segments.values():
        time = segment.conditions.frames.inertial.time[:, 0] / Units.min
        altitude = segment.conditions.freestream.altitude[:, 0] / Units.km
        axes.plot(time, altitude, line_style)
    axes.set_xlabel('Time (mins)')
    axes.set_ylabel('Altitude (km)')
    axes.grid(True)

    axes = fig.add_subplot(3, 1, 2)
    for segment in results.segments.values():
        time = segment.conditions.frames.inertial.time[:, 0] / Units.min
        mach_number = segment.conditions.freestream.mach_number[:, 0]
        axes.plot(time, mach_number, line_style)
    axes.set_xlabel('Time (min)')
    axes.set_ylabel('Mach')
    axes.grid(True)

    axes = fig.add_subplot(3, 1, 3)
    for segment in results.segments.values():
        time = segment.conditions.frames.inertial.time[:, 0] / Units.min
        Lift = -segment.conditions.frames.wind.lift_force_vector[:, 2]
        Drag = -segment.conditions.frames.wind.drag_force_vector[:, 0]
        LD = Lift / Drag
        axes.plot(time, LD, line_style)
    axes.set_xlabel('Time (min)')
    axes.set_ylabel('L/D')
    axes.grid(True)
    #plt.savefig('Concorde_data.pdf')

    return
Ejemplo n.º 43
0
def waveAccPlot(wave_obs,
                pix_obs,
                wave_zmx,
                pix_zmx,
                disp_coef,
                obsid=None,
                acc=None,
                order=None,
                wheelpos=200,
                figureno=1,
                legloc=[1, 2]):
    '''Plots of the accuracy of the wavelength solution from zemax compared to
   the observed wavelengths.
     
   Parameters
   ----------  
   wave_obs,  pix_obs : ndarray 
      observed wavelengths points (green circles)
      
   wave_zmx ,pix_zmx : ndarray
      calculated zemax points (or the interpolated solution (red crosses) 
      
   disp_coef : ndarray
      dispersion coefficients
      
   disp_coef : list
      coefficients in reverse order: if p is of length N, this the polynomial
     is as follows for coeff named p:
     
          y(x) = p[0]*(x**N-1) + p[1]*(x**N-2) + ... + p[N-2]*x + p[N-1]
   
   kwargs : dict
   
    - **acc** : accuracy in wavelength 
      
    - **order** : order of polynomial disp_coef (default len(coef) )
    
    - **obsid** : if given, append to  title                      
   
   Notes
   -----
   
   **Figure description**
   
   x-axis :  pix - pixel number referenced to [260nm in first order]

   *Top panel only*
    
   y-axis: lambda - lambda_linear
   
   *linear term in the dispersion*
   a linear term is fit to the wavelengths 
   
      $\lambda_{lin}$ = coef[0]+coef[1]*pix
   
   *Bottom panel only*
   
   y-axis: residuals
     
      wave_obs, pix_obs - wave(pix_obs)  (green circles)
      wave_zmx, pix_zmx - wave(pix_zmx)  (red crosses)
      
   '''
    if wheelpos < 500:
        ref_wave = 2600.
        titl = 'Wavelength accuracy UV grism - '
        textstart = 1600
    else:
        ref_wave = 4200.
        titl = 'Wavelength accuracy V grism - '
        textstart = 2700
    # zero of pix_obs forced to ref_wave (2600.or 4200.) for initial plot
    if order == None:
        order = len(disp_coef)
    dcoef = polyfit(wave_obs, pix_obs, order)
    doff = polyval(dcoef, ref_wave)
    pix_obs = pix_obs - doff
    print("fit through observations pixel position of anchor = ", doff)

    n1, n2 = len(pix_obs), len(pix_zmx)
    pix1 = N.zeros((n1 + n2))
    pix1[0:n1, ] = pix_obs
    pix1[n1:(n1 + n2), ] = pix_zmx
    pix2 = pix1.min()
    pix3 = pix1.max()
    pix = N.arange(pix2, pix3)
    wav = polyval(disp_coef, pix)
    #           wavlin = disp_coef[-1]+disp_coef[-2]*xxx_pix
    #           linear term in dispersion:
    w_obs = wave_obs - (disp_coef[-1] + disp_coef[-2] * pix_obs)
    w_zmx = wave_zmx - (disp_coef[-1] + disp_coef[-2] * pix_zmx)
    wavlin = wav - (disp_coef[-1] + disp_coef[-2] * pix)
    zero_offset = (wave_obs - polyval(disp_coef, pix_obs + doff)).mean()
    zo = zero_offset
    if acc == None:
        wave_off = (wave_obs - polyval(disp_coef, pix_obs + doff))
        acc = wave_off.std()
        print(' initial acc (all points) = ', acc)
        # remove outlyers
        q_in = N.where(abs(wave_off - zo) < 3. * acc)
        acc = (wave_off[q_in]).std()
        print(' after removing outliers: acc = ', acc)
        print('accuracy of the fit = ', acc, ' angstrom')
    stracc = str(old_div(((10 * acc + 0.5).__int__()), 10.)) + '$\AA$'
    zero_offset = old_div(((10 * zero_offset + 0.5).__int__()), 10.)
    txt = '<$\Delta\lambda$> = ' + str(
        zero_offset) + '$\AA\ \ \ \sigma_{observed-model}$ = ' + stracc

    figure(num=figureno)

    subplot(211)
    plot(pix, wavlin, '-')
    plot(pix_obs, w_obs, 'ob')
    plot(pix_zmx, w_zmx, '+r')
    ylabel('$\lambda$ - $\lambda_{linear}$  ($\AA$)')
    xlabel('pixels')
    if order == 4:
        sord = 'fourth '
    elif order == 3:
        sord = 'third '
    elif order == 2:
        sord = 'second '
    elif order == 1:
        sord = 'first '
    else:
        sord = 'unknown '
    legend((sord + 'order fit', 'observed data', 'model'), loc=legloc[1])
    if obsid == None: obsid = ''
    title(titl + obsid)
    # a = getp( gca )
    # setp(a, xlim=(pix1,pix2), xticks=[])

    subplot(212)
    w1 = wave_obs - polyval(disp_coef, pix_obs + doff)
    w2 = wave_zmx - polyval(disp_coef, pix_zmx)
    plot(wave_obs, w1, 'ob', label='_nolegend_')
    plot(wave_zmx, w2, '+r', label='_nolegend_')
    p0 = pix * 0.
    p1 = p0 - acc + zo
    p2 = p0 + acc + zo
    plot(wav, p0, '-r', label='_nolegend_')
    plot(wav, p1, '--b', label='1-$\sigma$ limits')
    plot(wav, p2, '--b', label='_nolegend_')
    ylabel('$\Delta\lambda$ ($\AA$)')
    xlabel('$\lambda$ ($\AA$)')
    a = gca()
    ylim = a.get_ylim()
    #if (ylim[0] > -16.0): ylim=(-16.0,ylim[1])
    ylim = (zo - 2.1 * acc, zo + 2.1 * acc)
    a.set_ylim(ylim)
    legend(loc=legloc[0])
    text(textstart, ylim[0] * 0.9, txt)
    #a = getp( gca )
    #lim1, lim2 = 1.1*max(w1), 1.1*min(w1)
    #setp(a, xlim=(lim1,lim2)) #, xticks=[])
    savefig('accuracy.png')
    return acc, zero_offset
Ejemplo n.º 44
0
def image_data(Z,
               X=[0, 1.0],
               Y=[0, 1.0],
               aspect=1.0,
               zmin=None,
               zmax=None,
               clear=1,
               clabel='z',
               autoformat=True,
               colormap="Last Used",
               shell_history=1,
               **kwargs):
    """
    Generates an image or 3d plot

    X                       1-d array of x-values
    Y                       1-d array of y-values
    Z                       2-d array of z-values

    X and Y can be something like [0,2] or an array of X-values

    kwargs are sent to pylab.imshow()
    """
    global _colormap

    _pylab.ioff()

    fig = _pylab.gcf()
    if clear:
        fig.clear()
        _pylab.axes()

    # generate the 3d axes
    X = _n.array(X)
    Y = _n.array(Y)
    Z = _n.array(Z)

    # assume X and Y are the bin centers and figure out the bin widths
    x_width = abs(float(X[-1] - X[0]) / (len(Z[0]) - 1))
    y_width = abs(float(Y[-1] - Y[0]) / (len(Z) - 1))

    # reverse the Z's
    Z = Z[-1::-1]

    # get rid of the label and title kwargs
    xlabel = ''
    ylabel = ''
    title = ''
    if kwargs.has_key('xlabel'): xlabel = kwargs.pop('xlabel')
    if kwargs.has_key('ylabel'): ylabel = kwargs.pop('ylabel')
    if kwargs.has_key('title'): title = kwargs.pop('title')

    _pylab.imshow(Z,
                  extent=[
                      X[0] - x_width / 2.0, X[-1] + x_width / 2.0,
                      Y[0] - y_width / 2.0, Y[-1] + y_width / 2.0
                  ],
                  **kwargs)
    cb = _pylab.colorbar()
    _pt.image_set_clim(zmin, zmax)
    _pt.image_set_aspect(aspect)
    cb.set_label(clabel)

    a = _pylab.gca()
    a.set_xlabel(xlabel)
    a.set_ylabel(ylabel)

    #_pt.close_sliders()
    #_pt.image_sliders()

    # title
    history = _fun.get_shell_history()
    for n in range(0, min(shell_history, len(history))):
        title = title + "\n" + history[n].split('\n')[0].strip()

    title = title + '\nPlot created ' + _time.asctime()
    a.set_title(title.strip())

    if autoformat: _pt.image_format_figure(fig)

    _pylab.ion()
    _pylab.show()
    #_pt.raise_figure_window()
    #_pt.raise_pyshell()
    _pylab.draw()

    # add the color sliders
    if colormap:
        if _colormap: _colormap.close()
        _colormap = _pt.image_colormap(colormap, image=a.images[0])
Ejemplo n.º 45
0
def plot_smith(z,
               smith_r=1,
               chart_type='z',
               x_label='Real',
               y_label='Imaginary',
               title='Complex Plane',
               show_legend=True,
               axis='equal',
               ax=None,
               force_chart=False,
               *args,
               **kwargs):
    '''
    plot complex data on smith chart

    Parameters
    ------------
    z : array-like, of complex data
        data to plot
    smith_r : number
        radius of smith chart
    chart_type : ['z','y']
        Contour type for chart.
         * *'z'* : lines of constant impedance
         * *'y'* : lines of constant admittance
    x_label : string
        x-axis label
    y_label : string
        y-axis label
    title : string
        plot title
    show_legend : Boolean
        controls the drawing of the legend
    axis_equal: Boolean
        sets axis to be equal increments (calls axis('equal'))
    force_chart : Boolean
        forces the re-drawing of smith chart 
    ax : :class:`matplotlib.axes.AxesSubplot` object
        axes to draw on
    *args,**kwargs : passed to pylab.plot

    See Also
    ----------
    plot_rectangular : plots rectangular data
    plot_complex_rectangular : plot complex data on complex plane
    plot_polar : plot polar data
    plot_complex_polar : plot complex data on polar plane
    plot_smith : plot complex data on smith chart
    '''

    if ax is None:
        ax = plb.gca()

    # test if smith chart is already drawn
    if not force_chart:
        if len(ax.patches) == 0:
            smith(ax=ax, smithR=smith_r, chart_type=chart_type)

    plot_complex_rectangular(z,
                             x_label=x_label,
                             y_label=y_label,
                             title=title,
                             show_legend=show_legend,
                             axis=axis,
                             ax=ax,
                             *args,
                             **kwargs)

    ax.axis(smith_r * npy.array([-1.1, 1.1, -1.1, 1.1]))
    if plb.isinteractive():
        plb.draw()
Ejemplo n.º 46
0
def plot_mission(results, line_style='bo-'):

    # ------------------------------------------------------------------
    #   Throttle
    # ------------------------------------------------------------------
    plt.figure("Throttle History")
    axes = plt.gca()
    for i in range(len(results.segments)):
        time = results.segments[
            i].conditions.frames.inertial.time[:, 0] / Units.min
        eta = results.segments[i].conditions.propulsion.throttle[:, 0]
        axes.plot(time, eta, line_style)
    axes.set_xlabel('Time (mins)')
    axes.set_ylabel('Throttle')
    axes.grid(True)

    # ------------------------------------------------------------------
    #   Angle of Attack
    # ------------------------------------------------------------------

    plt.figure("Angle of Attack History")
    axes = plt.gca()
    for i in range(len(results.segments)):
        time = results.segments[
            i].conditions.frames.inertial.time[:, 0] / Units.min
        aoa = results.segments[
            i].conditions.aerodynamics.angle_of_attack[:, 0] / Units.deg
        axes.plot(time, aoa, line_style)
    axes.set_xlabel('Time (mins)')
    axes.set_ylabel('Angle of Attack (deg)')
    axes.grid(True)

    # ------------------------------------------------------------------
    #   Fuel Burn Rate
    # ------------------------------------------------------------------
    plt.figure("Fuel Burn Rate")
    axes = plt.gca()
    for i in range(len(results.segments)):
        time = results.segments[
            i].conditions.frames.inertial.time[:, 0] / Units.min
        mdot = results.segments[i].conditions.weights.vehicle_mass_rate[:, 0]
        axes.plot(time, mdot, line_style)
    axes.set_xlabel('Time (mins)')
    axes.set_ylabel('Fuel Burn Rate (kg/s)')
    axes.grid(True)

    ##    # ------------------------------------------------------------------
    ##    #   Engine SFC
    ##    # ------------------------------------------------------------------
    ##    plt.figure("Engine SFC")
    ##    axes = plt.gca()
    ##    for i in range(len(results.segments)):
    ##        time = results.segments[i].conditions.frames.inertial.time[:,0] / Units.min
    ##        mdot = results.segments[i].conditions.weights.vehicle_mass_rate[:,0] * 360.
    ##        Thrust = results.segments[i].conditions.frames.body.thrust_force_vector[:,0] / 9.81
    ##        sfc = np.divide(mdot,Thrust)
    ##        axes.plot(time, sfc, line_style)
    ##    axes.set_xlabel('Time (mins)')
    ##    axes.set_ylabel('Engine SFC (kg/kg)')
    ##    axes.grid(True)

    # ------------------------------------------------------------------
    #   Altitude
    # ------------------------------------------------------------------
    plt.figure("Altitude")
    axes = plt.gca()
    for i in range(len(results.segments)):
        time = results.segments[
            i].conditions.frames.inertial.time[:, 0] / Units.min
        altitude = results.segments[
            i].conditions.freestream.altitude[:, 0] / Units.km
        axes.plot(time, altitude, line_style)
    axes.set_xlabel('Time (mins)')
    axes.set_ylabel('Altitude (km)')
    axes.grid(True)

    # ------------------------------------------------------------------
    #   Vehicle Mass
    # ------------------------------------------------------------------
    plt.figure("Vehicle Mass")
    axes = plt.gca()
    for i in range(len(results.segments)):
        time = results.segments[
            i].conditions.frames.inertial.time[:, 0] / Units.min
        mass = results.segments[i].conditions.weights.total_mass[:, 0]
        axes.plot(time, mass, line_style)
    axes.set_xlabel('Time (mins)')
    axes.set_ylabel('Vehicle Mass (kg)')
    axes.grid(True)

    # ------------------------------------------------------------------
    #   Aerodynamics
    # ------------------------------------------------------------------
    fig = plt.figure("Aerodynamic Forces")
    for segment in list(results.segments.values()):

        time = segment.conditions.frames.inertial.time[:, 0] / Units.min
        Lift = -segment.conditions.frames.wind.lift_force_vector[:, 2]
        Drag = -segment.conditions.frames.wind.drag_force_vector[:, 0]
        Thrust = segment.conditions.frames.body.thrust_force_vector[:, 0]

        axes = fig.add_subplot(4, 1, 1)
        axes.plot(time, Lift, line_style)
        axes.set_xlabel('Time (min)')
        axes.set_ylabel('Lift (N)')
        axes.grid(True)

        axes = fig.add_subplot(4, 1, 2)
        axes.plot(time, Drag, line_style)
        axes.set_xlabel('Time (min)')
        axes.set_ylabel('Drag (N)')
        axes.grid(True)

        axes = fig.add_subplot(4, 1, 3)
        axes.plot(time, Thrust, line_style)
        axes.set_xlabel('Time (min)')
        axes.set_ylabel('Thrust (N)')
        axes.grid(True)

        try:
            Pitching_moment = segment.conditions.stability.static.cm_alpha[:,
                                                                           0]
            axes = fig.add_subplot(4, 1, 4)
            axes.plot(time, Pitching_moment, line_style)
            axes.set_xlabel('Time (min)')
            axes.set_ylabel('Pitching_moment (~)')
            axes.grid(True)
        except:
            pass

    # ------------------------------------------------------------------
    #   Aerodynamics 2
    # ------------------------------------------------------------------
    fig = plt.figure("Aerodynamic Coefficients")
    for segment in list(results.segments.values()):

        time = segment.conditions.frames.inertial.time[:, 0] / Units.min
        CLift = segment.conditions.aerodynamics.lift_coefficient[:, 0]
        CDrag = segment.conditions.aerodynamics.drag_coefficient[:, 0]
        Drag = -segment.conditions.frames.wind.drag_force_vector[:, 0]
        Thrust = segment.conditions.frames.body.thrust_force_vector[:, 0]

        axes = fig.add_subplot(3, 1, 1)
        axes.plot(time, CLift, line_style)
        axes.set_xlabel('Time (min)')
        axes.set_ylabel('CL')
        axes.grid(True)

        axes = fig.add_subplot(3, 1, 2)
        axes.plot(time, CDrag, line_style)
        axes.set_xlabel('Time (min)')
        axes.set_ylabel('CD')
        axes.grid(True)

        axes = fig.add_subplot(3, 1, 3)
        axes.plot(time, Drag, line_style)
        axes.plot(time, Thrust, 'ro-')
        axes.set_xlabel('Time (min)')
        axes.set_ylabel('Drag and Thrust (N)')
        axes.grid(True)

    # ------------------------------------------------------------------
    #   Aerodynamics 2
    # ------------------------------------------------------------------
    fig = plt.figure("Drag Components")
    axes = plt.gca()
    for i, segment in enumerate(results.segments.values()):

        time = segment.conditions.frames.inertial.time[:, 0] / Units.min
        drag_breakdown = segment.conditions.aerodynamics.drag_breakdown
        cdp = drag_breakdown.parasite.total[:, 0]
        cdi = drag_breakdown.induced.total[:, 0]
        cdc = drag_breakdown.compressible.total[:, 0]
        cdm = drag_breakdown.miscellaneous.total[:, 0]
        cd = drag_breakdown.total[:, 0]

        if line_style == 'bo-':
            axes.plot(time, cdp, 'ko-', label='CD_P')
            axes.plot(time, cdi, 'bo-', label='CD_I')
            axes.plot(time, cdc, 'go-', label='CD_C')
            axes.plot(time, cdm, 'yo-', label='CD_M')
            axes.plot(time, cd, 'ro-', label='CD')
            if i == 0:
                axes.legend(loc='upper center')
        else:
            axes.plot(time, cdp, line_style)
            axes.plot(time, cdi, line_style)
            axes.plot(time, cdc, line_style)
            axes.plot(time, cdm, line_style)
            axes.plot(time, cd, line_style)

    axes.set_xlabel('Time (min)')
    axes.set_ylabel('CD')
    axes.grid(True)

    return
Ejemplo n.º 47
0
# plot all requested depths
for depth in range(mindepth, maxdepth + 1):
    # select data for this depth
    idx = data["depth"] == depth

    # create a bar plot
    bar = [(line["start"], line["end"] - line["start"]) for line in data[idx]]
    colors = ["C{0}".format(i % 10) for i in range(len(data[idx]))]
    pl.broken_barh(bar, (depth - 0.4, 0.8),
                   facecolors=colors,
                   edgecolor="none")
    # add labels
    labels = [line["label"] for line in data[idx]]
    for i in range(len(labels)):
        pl.text(
            bar[i][0] + 0.5 * bar[i][1],
            depth - 0.2 + 0.4 * (i % 2),
            labels[i],
            ha="center",
            bbox=dict(facecolor="white", alpha=0.9),
        )

# disable vertical ticks
pl.gca().set_yticks([])
# set the x axis label
pl.xlabel("run time (s)")

# save the plot
pl.tight_layout()
pl.savefig(args.output, dpi=300, bbox_inches="tight")
Ejemplo n.º 48
0
def smith(smithR=1, chart_type='z', draw_labels=False, border=False, ax=None):
    '''
    plots the smith chart of a given radius

    Parameters
    -----------
    smithR : number
            radius of smith chart
    chart_type : ['z','y']
            Contour type. Possible values are
             * *'z'* : lines of constant impedance
             * *'y'* : lines of constant admittance
    draw_labels : Boolean
             annotate real and imaginary parts of impedance on the 
             chart (only if smithR=1)
    border : Boolean
        draw a rectangular border with axis ticks, around the perimeter 
        of the figure. Not used if draw_labels = True
    
    ax : matplotlib.axes object
            existing axes to draw smith chart on


    '''
    ##TODO: fix this function so it doesnt suck
    if ax == None:
        ax1 = plb.gca()
    else:
        ax1 = ax

    # contour holds matplotlib instances of: pathes.Circle, and lines.Line2D, which
    # are the contours on the smith chart
    contour = []

    # these are hard-coded on purpose,as they should always be present
    rHeavyList = [0, 1]
    xHeavyList = [1, -1]

    #TODO: fix this
    # these could be dynamically coded in the future, but work good'nuff for now
    if not draw_labels:
        rLightList = plb.logspace(3, -5, 9, base=.5)
        xLightList = plb.hstack([
            plb.logspace(2, -5, 8, base=.5),
            -1 * plb.logspace(2, -5, 8, base=.5)
        ])
    else:
        rLightList = plb.array([0.2, 0.5, 1.0, 2.0, 5.0])
        xLightList = plb.array(
            [0.2, 0.5, 1.0, 2.0, 5.0, -0.2, -0.5, -1.0, -2.0, -5.0])

    # cheap way to make a ok-looking smith chart at larger than 1 radii
    if smithR > 1:
        rMax = (1. + smithR) / (1. - smithR)
        rLightList = plb.hstack([plb.linspace(0, rMax, 11), rLightList])

    if chart_type is 'y':
        y_flip_sign = -1
    else:
        y_flip_sign = 1
    # loops through Light and Heavy lists and draws circles using patches
    # for analysis of this see R.M. Weikles Microwave II notes (from uva)
    for r in rLightList:
        center = (r / (1. + r) * y_flip_sign, 0)
        radius = 1. / (1 + r)
        contour.append(Circle(center, radius, ec='grey', fc='none'))
    for x in xLightList:
        center = (1 * y_flip_sign, 1. / x)
        radius = 1. / x
        contour.append(Circle(center, radius, ec='grey', fc='none'))

    for r in rHeavyList:
        center = (r / (1. + r) * y_flip_sign, 0)
        radius = 1. / (1 + r)
        contour.append(Circle(center, radius, ec='black', fc='none'))
    for x in xHeavyList:
        center = (1 * y_flip_sign, 1. / x)
        radius = 1. / x
        contour.append(Circle(center, radius, ec='black', fc='none'))

    # clipping circle
    clipc = Circle([0, 0], smithR, ec='k', fc='None', visible=True)
    ax1.add_patch(clipc)

    #draw x and y axis
    ax1.axhline(0, color='k', lw=.1, clip_path=clipc)
    ax1.axvline(1 * y_flip_sign, color='k', clip_path=clipc)
    ax1.grid(0)
    #set axis limits
    ax1.axis('equal')
    ax1.axis(smithR * npy.array([-1.1, 1.1, -1.1, 1.1]))

    if not border:
        ax1.yaxis.set_ticks([])
        ax1.xaxis.set_ticks([])
        for loc, spine in ax1.spines.iteritems():
            spine.set_color('none')

    if draw_labels:
        #Clear axis
        ax1.yaxis.set_ticks([])
        ax1.xaxis.set_ticks([])
        for loc, spine in ax1.spines.iteritems():
            spine.set_color('none')

        #Will make annotations only if the radius is 1 and it is the impedance smith chart
        if smithR is 1 and y_flip_sign is 1:
            #Make room for annotation
            ax1.axis(smithR * npy.array([-1., 1., -1.2, 1.2]))

            #Annotate real part
            for value in rLightList:
                rho = (value - 1) / (value + 1)
                ax1.annotate(str(value), xy=((rho-0.12)*smithR, 0.01*smithR), \
                    xytext=((rho-0.12)*smithR, 0.01*smithR))

            #Annotate imaginary part
            deltax = plb.array(
                [-0.17, -0.14, -0.06, 0., 0.02, -0.2, -0.2, -0.08, 0., 0.03])
            deltay = plb.array(
                [0., 0.03, 0.01, 0.02, 0., -0.02, -0.06, -0.09, -0.08, -0.05])
            for value, dx, dy in zip(xLightList, deltax, deltay):
                #Transforms from complex to cartesian and adds a delta to x and y values
                rhox = (-value**2 + 1) / (-value**2 -
                                          1) * smithR * y_flip_sign + dx
                rhoy = (-2 * value) / (-value**2 - 1) * smithR + dy
                #Annotate value
                ax1.annotate(str(value) + 'j',
                             xy=(rhox, rhoy),
                             xytext=(rhox, rhoy))

            #Annotate 0 and inf
            ax1.annotate('0.0', xy=(-1.15, -0.02), xytext=(-1.15, -0.02))
            ax1.annotate('$\infty$', xy=(1.02, -0.02), xytext=(1.02, -0.02))

    # loop though contours and draw them on the given axes
    for currentContour in contour:
        cc = ax1.add_patch(currentContour)
        cc.set_clip_path(clipc)
Ejemplo n.º 49
0
def _plot_param_table(parameters, web=False):
    storm_dir, storm_spd = parameters['storm_motion']
    trans = pylab.gca().transAxes
    line_space = 0.033
    start_x = 1.02
    start_y = 1.0 - line_space

    line_y = start_y

    kwargs = {
        'color': 'k',
        'fontsize': 10,
        'clip_on': False,
        'transform': trans
    }

    pylab.text(start_x + 0.175,
               start_y,
               "Parameter Table",
               ha='center',
               fontweight='bold',
               **kwargs)

    spacer = Line2D([start_x, start_x + 0.361],
                    [line_y - line_space * 0.48] * 2,
                    color='k',
                    linestyle='-',
                    transform=trans,
                    clip_on=False)
    pylab.gca().add_line(spacer)
    line_y -= line_space * 1.5

    pylab.text(start_x + 0.095,
               line_y - 0.0025,
               "BWD (kts)",
               fontweight='bold',
               **kwargs)
    if not web:
        pylab.text(start_x + 0.22,
                   line_y - 0.0025,
                   "SRH (m$^2$s$^{-2}$)",
                   fontweight='bold',
                   **kwargs)
    else:
        # Awful, awful hack for matplotlib without a LaTeX distribution
        pylab.text(start_x + 0.22,
                   line_y - 0.0025,
                   "SRH (m s  )",
                   fontweight='bold',
                   **kwargs)
        pylab.text(start_x + 0.305,
                   line_y + 0.009,
                   "2   -2",
                   fontweight='bold',
                   color='k',
                   fontsize=6,
                   clip_on=False,
                   transform=trans)

    line_y -= line_space

    pylab.text(start_x, line_y, "0-1 km", fontweight='bold', **kwargs)
    val = "--" if np.isnan(parameters['shear_mag_1km']) else "%d" % int(
        parameters['shear_mag_1km'])
    pylab.text(start_x + 0.095, line_y, val, **kwargs)
    val = "--" if np.isnan(
        parameters['srh_1km']) else "%d" % int(parameters['srh_1km'])
    pylab.text(start_x + 0.22, line_y, val, **kwargs)

    line_y -= line_space

    pylab.text(start_x, line_y, "0-3 km", fontweight='bold', **kwargs)
    val = "--" if np.isnan(parameters['shear_mag_3km']) else "%d" % int(
        parameters['shear_mag_3km'])
    pylab.text(start_x + 0.095, line_y, val, **kwargs)
    val = "--" if np.isnan(
        parameters['srh_3km']) else "%d" % int(parameters['srh_3km'])
    pylab.text(start_x + 0.22, line_y, val, **kwargs)

    line_y -= line_space

    pylab.text(start_x, line_y, "0-6 km", fontweight='bold', **kwargs)
    val = "--" if np.isnan(parameters['shear_mag_6km']) else "%d" % int(
        parameters['shear_mag_6km'])
    pylab.text(start_x + 0.095, line_y, val, **kwargs)

    spacer = Line2D([start_x, start_x + 0.361],
                    [line_y - line_space * 0.48] * 2,
                    color='k',
                    linestyle='-',
                    transform=trans,
                    clip_on=False)
    pylab.gca().add_line(spacer)
    line_y -= 1.5 * line_space

    pylab.text(start_x, line_y, "Storm Motion:", fontweight='bold', **kwargs)
    val = "--" if np.isnan(
        parameters['storm_motion']).any() else "%03d/%02d kts" % (storm_dir,
                                                                  storm_spd)
    pylab.text(start_x + 0.26, line_y + 0.001, val, **kwargs)

    line_y -= line_space

    bl_dir, bl_spd = parameters['bunkers_left']
    pylab.text(start_x,
               line_y,
               "Bunkers Left Mover:",
               fontweight='bold',
               **kwargs)
    val = "--" if np.isnan(
        parameters['bunkers_left']).any() else "%03d/%02d kts" % (bl_dir,
                                                                  bl_spd)
    pylab.text(start_x + 0.26, line_y + 0.001, val, **kwargs)

    line_y -= line_space

    br_dir, br_spd = parameters['bunkers_right']
    if not web:
        pylab.text(start_x,
                   line_y,
                   "Bunkers Right Mover:",
                   fontweight='bold',
                   **kwargs)
    else:
        pylab.text(start_x,
                   line_y - 0.005,
                   "Bunkers Right Mover:",
                   fontweight='bold',
                   **kwargs)
    val = "--" if np.isnan(
        parameters['bunkers_right']).any() else "%03d/%02d kts" % (br_dir,
                                                                   br_spd)
    if not web:
        pylab.text(start_x + 0.26, line_y + 0.001, val, **kwargs)
    else:
        pylab.text(start_x + 0.26, line_y - 0.001, val, **kwargs)

    line_y -= line_space

    mn_dir, mn_spd = parameters['mean_wind']
    pylab.text(start_x,
               line_y,
               "0-6 km Mean Wind:",
               fontweight='bold',
               **kwargs)
    val = "--" if np.isnan(
        parameters['mean_wind']).any() else "%03d/%02d kts" % (mn_dir, mn_spd)
    pylab.text(start_x + 0.26, line_y + 0.001, val, **kwargs)

    spacer = Line2D([start_x, start_x + 0.361],
                    [line_y - line_space * 0.48] * 2,
                    color='k',
                    linestyle='-',
                    transform=trans,
                    clip_on=False)
    pylab.gca().add_line(spacer)
    line_y -= 1.5 * line_space

    if not web:
        pylab.text(start_x,
                   line_y,
                   "Critical Angle:",
                   fontweight='bold',
                   **kwargs)
        val = "--" if np.isnan(
            parameters['critical']) else "%d$^{\circ}$" % int(
                parameters['critical'])
        pylab.text(start_x + 0.18, line_y - 0.0025, val, **kwargs)
    else:
        pylab.text(start_x,
                   line_y - 0.0075,
                   "Critical Angle:",
                   fontweight='bold',
                   **kwargs)
        val = "--" if np.isnan(
            parameters['critical']) else "%d deg" % int(parameters['critical'])
        pylab.text(start_x + 0.18, line_y - 0.0075, val, **kwargs)
Ejemplo n.º 50
0
def plot_polar(theta,
               r,
               x_label=None,
               y_label=None,
               title=None,
               show_legend=True,
               axis_equal=False,
               ax=None,
               *args,
               **kwargs):
    '''
    plots polar data on a polar plot and optionally label axes.

    Parameters
    ------------
    theta : array-like
        data to plot
    r : array-like
        
    x_label : string
        x-axis label
    y_label : string
        y-axis label
    title : string
        plot title
    show_legend : Boolean
        controls the drawing of the legend
    ax : :class:`matplotlib.axes.AxesSubplot` object
        axes to draw on
    *args,**kwargs : passed to pylab.plot
    
    See Also
    ----------
    plot_rectangular : plots rectangular data
    plot_complex_rectangular : plot complex data on complex plane
    plot_polar : plot polar data
    plot_complex_polar : plot complex data on polar plane
    plot_smith : plot complex data on smith chart

    '''
    if ax is None:
        ax = plb.gca(polar=True)

    ax.plot(theta, r, *args, **kwargs)

    if x_label is not None:
        ax.set_xlabel(x_label)

    if y_label is not None:
        ax.set_ylabel(y_label)

    if title is not None:
        ax.set_title(title)

    if show_legend:
        # only show legend if they provide a label
        if 'label' in kwargs:
            ax.legend()

    if axis_equal:
        ax.axis('equal')

    if plb.isinteractive():
        plb.draw()
Ejemplo n.º 51
0
def _plot_data(data, parameters):
    storm_dir, storm_spd = parameters['storm_motion']
    bl_dir, bl_spd = parameters['bunkers_left']
    br_dir, br_spd = parameters['bunkers_right']
    mn_dir, mn_spd = parameters['mean_wind']

    u, v = vec2comp(data['wind_dir'], data['wind_spd'])
    alt = data['altitude']

    storm_u, storm_v = vec2comp(storm_dir, storm_spd)
    bl_u, bl_v = vec2comp(bl_dir, bl_spd)
    br_u, br_v = vec2comp(br_dir, br_spd)
    mn_u, mn_v = vec2comp(mn_dir, mn_spd)

    seg_idxs = np.searchsorted(alt, _seg_hghts)
    try:
        seg_u = np.interp(_seg_hghts, alt, u, left=np.nan, right=np.nan)
        seg_v = np.interp(_seg_hghts, alt, v, left=np.nan, right=np.nan)
        ca_u = np.interp(0.5, alt, u, left=np.nan, right=np.nan)
        ca_v = np.interp(0.5, alt, v, left=np.nan, right=np.nan)
    except ValueError:
        seg_u = np.nan * np.array(_seg_hghts)
        seg_v = np.nan * np.array(_seg_hghts)
        ca_u = np.nan
        ca_v = np.nan

    mkr_z = np.arange(16)
    mkr_u = np.interp(mkr_z, alt, u, left=np.nan, right=np.nan)
    mkr_v = np.interp(mkr_z, alt, v, left=np.nan, right=np.nan)

    for idx in range(len(_seg_hghts) - 1):
        idx_start = seg_idxs[idx]
        idx_end = seg_idxs[idx + 1]

        if not np.isnan(seg_u[idx]):
            pylab.plot([seg_u[idx], u[idx_start]], [seg_v[idx], v[idx_start]],
                       '-',
                       color=_seg_colors[idx],
                       linewidth=1.5)

        if idx_start < len(
                data['rms_error']) and data['rms_error'][idx_start] == 0.:
            # The first segment is to the surface wind, draw it in a dashed line
            pylab.plot(u[idx_start:(idx_start + 2)],
                       v[idx_start:(idx_start + 2)],
                       '--',
                       color=_seg_colors[idx],
                       linewidth=1.5)
            pylab.plot(u[(idx_start + 1):idx_end],
                       v[(idx_start + 1):idx_end],
                       '-',
                       color=_seg_colors[idx],
                       linewidth=1.5)
        else:
            pylab.plot(u[idx_start:idx_end],
                       v[idx_start:idx_end],
                       '-',
                       color=_seg_colors[idx],
                       linewidth=1.5)

        if not np.isnan(seg_u[idx + 1]):
            pylab.plot([u[idx_end - 1], seg_u[idx + 1]],
                       [v[idx_end - 1], seg_v[idx + 1]],
                       '-',
                       color=_seg_colors[idx],
                       linewidth=1.5)

        for upt, vpt, rms in list(zip(u, v,
                                      data['rms_error']))[idx_start:idx_end]:
            rad = np.sqrt(2) * rms
            circ = Circle((upt, vpt), rad, color=_seg_colors[idx], alpha=0.05)
            pylab.gca().add_patch(circ)

    pylab.plot(mkr_u, mkr_v, 'ko', ms=10)
    for um, vm, zm in zip(mkr_u, mkr_v, mkr_z):
        if not np.isnan(um):
            pylab.text(um,
                       vm - 0.1,
                       str(zm),
                       va='center',
                       ha='center',
                       color='white',
                       size=6.5,
                       fontweight='bold')

    try:
        pylab.plot([storm_u, u[0]], [storm_v, v[0]], 'c-', linewidth=0.75)
        pylab.plot([u[0], ca_u], [v[0], ca_v], 'm-', linewidth=0.75)
    except IndexError:
        pass

    if not (np.isnan(bl_u) or np.isnan(bl_v)):
        pylab.plot(bl_u, bl_v, 'ko', markersize=5, mfc='none')
        pylab.text(bl_u + 0.5,
                   bl_v - 0.5,
                   "LM",
                   ha='left',
                   va='top',
                   color='k',
                   fontsize=10)

    if not (np.isnan(br_u) or np.isnan(br_v)):
        pylab.plot(br_u, br_v, 'ko', markersize=5, mfc='none')
        pylab.text(br_u + 0.5,
                   br_v - 0.5,
                   "RM",
                   ha='left',
                   va='top',
                   color='k',
                   fontsize=10)

    if not (np.isnan(mn_u) or np.isnan(mn_v)):
        pylab.plot(mn_u, mn_v, 's', color='#a04000', markersize=5, mfc='none')
        pylab.text(mn_u + 0.6,
                   mn_v - 0.6,
                   "MEAN",
                   ha='left',
                   va='top',
                   color='#a04000',
                   fontsize=10)

    smv_is_brm = (storm_u == br_u and storm_v == br_v)
    smv_is_blm = (storm_u == bl_u and storm_v == bl_v)
    smv_is_mnw = (storm_u == mn_u and storm_v == mn_v)

    if not (np.isnan(storm_u) or np.isnan(storm_v)) and not (
            smv_is_brm or smv_is_blm or smv_is_mnw):
        pylab.plot(storm_u, storm_v, 'k+', markersize=6)
        pylab.text(storm_u + 0.5,
                   storm_v - 0.5,
                   "SM",
                   ha='left',
                   va='top',
                   color='k',
                   fontsize=10)
Ejemplo n.º 52
0
def plot_vwp(data,
             times,
             parameters,
             fname=None,
             add_hodo=False,
             fixed=False,
             web=False,
             archive=False):
    img_title = "%s VWP valid ending %s" % (
        data[0].rid, times[0].strftime("%d %b %Y %H%M UTC"))
    if fname is not None:
        img_file_name = fname
    else:
        img_file_name = "%s_vwp.png" % data[0].rid

    sat_age = 6 * 3600
    now = datetime.utcnow()
    img_age = now - times[0]
    age_cstop = min(_total_seconds(img_age) / sat_age, 1) * 0.4
    age_color = mpl.cm.get_cmap('hot')(age_cstop)[:-1]

    age_str = "Image created on %s (%s old)" % (
        now.strftime("%d %b %Y %H%M UTC"), _fmt_timedelta(img_age))

    fig_aspect = 2.5714
    fig_wid = 24
    fig_hght = fig_wid / fig_aspect
    pylab.figure(figsize=(fig_wid, fig_hght), dpi=200)

    axes_left = 0.01
    axes_bot = 0.02
    axes_hght = 0.94
    axes_wid = axes_hght / fig_aspect
    pylab.axes((axes_left, axes_bot, 0.99, axes_hght))

    _plot_vwp_background(times)
    _plot_vwp_data(data)
    #_plot_param_table(parameters, web=web)

    pylab.xlim(0, 1.)
    pylab.ylim(0, 1.)
    pylab.xticks([])
    pylab.yticks([])
    pylab.box(False)

    if not archive:
        pylab.title(img_title, color=age_color)
        pylab.text(x_start,
                   1.03,
                   age_str,
                   transform=pylab.gca().transAxes,
                   ha='left',
                   va='top',
                   fontsize=9,
                   color=age_color)
    else:
        pylab.title(img_title)

    if web:
        web_brand = "http://www.autumnsky.us/vad/"
        pylab.text(1.0,
                   -0.01,
                   web_brand,
                   transform=pylab.gca().transAxes,
                   ha='right',
                   va='top',
                   fontsize=9)

    if add_hodo:
        inset_ax = inset_axes(pylab.gca(),
                              width="30%",
                              height="55%",
                              loc='upper left',
                              bbox_to_anchor=(0.63, 0, 0.85, 1),
                              bbox_transform=pylab.gca().transAxes)
        u, v = vec2comp(data[0]['wind_dir'], data[0]['wind_spd'])

        if fixed or len(u) == 0:
            ctr_u, ctr_v = 20, 20
            size = 120
        else:
            ctr_u = u.mean()
            ctr_v = v.mean()
            size = max(u.max() - u.min(), v.max() - v.min()) + 20
            size = max(120, size)

        min_u = ctr_u - size / 2
        max_u = ctr_u + size / 2
        min_v = ctr_v - size / 2
        max_v = ctr_v + size / 2

        _plot_background(min_u, max_u, min_v, max_v)
        _plot_data(data[0], parameters)
        _plot_param_table(parameters, web=web)

        inset_ax.set_xlim(min_u, max_u)
        inset_ax.set_ylim(min_v, max_v)
        inset_ax.set_xticks([])
        inset_ax.set_yticks([])

    pylab.savefig(img_file_name, dpi=pylab.gcf().dpi)
    pylab.close()

    if web:
        bounds = {
            'min_u': min_u,
            'max_u': max_u,
            'min_v': min_v,
            'max_v': max_v
        }
        print(json.dumps(bounds))
Ejemplo n.º 53
0
def auc_plot(x,
             y,
             flag,
             file=None,
             cutoff=None,
             show=None,
             linestyle='rx-.',
             include_baseline=True,
             equal_aspect=True):
    """ Method that generates a plot of the ROC curve
            Parameters:
                title: Title of the chart
                include_baseline: Add the baseline plot line if it's True
                equal_aspect: Aspects to be equal for all plot
    """
    try:
        fpr, tpr, thresholds_roc = roc(x, y)
        if not cutoff:
            precision, recall, thresholds = precision_recall_curve(x, y)
            precision[np.where(precision == 0)] = 0.000000001
            recall[np.where(recall == 0)] = 0.000000001
            F_score = 2 * (precision * recall) / (precision + recall)
            aucvalue, cutoff = round(auc(fpr, tpr), 3), round(
                thresholds[np.where(F_score == max(F_score))][0], 3)

        TPR = round(
            tpr[np.where((thresholds_roc - cutoff) == min(thresholds_roc -
                                                          cutoff))][0], 5)
        FPR = round(
            fpr[np.where((thresholds_roc - cutoff) == min(thresholds_roc -
                                                          cutoff))][0], 5)
        import pylab
        from matplotlib import pyplot
        pyplot.figure()
        pylab.clf()
        pylab.plot([x1 for x1 in np.hstack((0, fpr))],
                   [y1 for y1 in np.hstack((0, tpr))],
                   color='red',
                   linewidth=8.0)
        #    pylab.plot([x1 for x1 in precision], [y1 for y1 in recall],color='blue',linewidth=2.0)
        if include_baseline:
            pylab.plot([0.0, 1.0], [0.0, 1.0], 'k--')
            pylab.ylim((0, 1))
            pylab.xlim((0, 1))
            pylab.xticks(pylab.arange(0, 1.1, .1), fontsize=16)
            pylab.yticks(pylab.arange(0, 1.1, .1), fontsize=16)
            pylab.grid(True, alpha=0.5)
            if equal_aspect:
                cax = pylab.gca()
                cax.set_aspect('equal')
        #pylab.xlabel('1 - Specificity(red)/Precision(blue)')
        pylab.xlabel('1 - Specificity', fontsize=16)
        pylab.ylabel('Sensitivity', fontsize=16)

        if 'Train' == flag or 'Validation' == flag:
            pylab.plot(FPR, TPR, 'o', color='black')
            pylab.figtext(
                FPR + 0.08, TPR - 0.08,
                str(cutoff) + "(" + ",".join(map(str, [1 - FPR, TPR])) + ")")

        pylab.title(flag + ' AUC=' + "%4.3f" % aucvalue + ' N=' +
                    '%1.0f' % len(x))
        pyplot.savefig(file + '_' + flag + '_aucplot.pdf', format='pdf')

    except:
        print("Failed to generate AUC plots")
Ejemplo n.º 54
0
def plot_hodograph(data,
                   parameters,
                   fname=None,
                   web=False,
                   fixed=False,
                   archive=False):
    img_title = "%s VWP valid %s" % (
        data.rid, data['time'].strftime("%d %b %Y %H%M UTC"))
    if fname is not None:
        img_file_name = fname
    else:
        img_file_name = "%s_vad.png" % data.rid

    u, v = vec2comp(data['wind_dir'], data['wind_spd'])

    sat_age = 6 * 3600
    if fixed or len(u) == 0:
        ctr_u, ctr_v = 20, 20
        size = 120
    else:
        ctr_u = u.mean()
        ctr_v = v.mean()
        size = max(u.max() - u.min(), v.max() - v.min()) + 20
        size = max(120, size)

    min_u = ctr_u - size / 2
    max_u = ctr_u + size / 2
    min_v = ctr_v - size / 2
    max_v = ctr_v + size / 2

    now = datetime.utcnow()
    img_age = now - data['time']
    age_cstop = min(_total_seconds(img_age) / sat_age, 1) * 0.4
    age_color = mpl.cm.get_cmap('hot')(age_cstop)[:-1]

    age_str = "Image created on %s (%s old)" % (
        now.strftime("%d %b %Y %H%M UTC"), _fmt_timedelta(img_age))

    pylab.figure(figsize=(10, 7.5), dpi=150)
    fig_wid, fig_hght = pylab.gcf().get_size_inches()
    fig_aspect = fig_wid / fig_hght

    axes_left = 0.05
    axes_bot = 0.05
    axes_hght = 0.9
    axes_wid = axes_hght / fig_aspect
    pylab.axes((axes_left, axes_bot, axes_wid, axes_hght))

    _plot_background(min_u, max_u, min_v, max_v)
    _plot_data(data, parameters)
    _plot_param_table(parameters, web=web)

    pylab.xlim(min_u, max_u)
    pylab.ylim(min_v, max_v)
    pylab.xticks([])
    pylab.yticks([])

    if not archive:
        pylab.title(img_title, color=age_color)
        pylab.text(0.,
                   -0.01,
                   age_str,
                   transform=pylab.gca().transAxes,
                   ha='left',
                   va='top',
                   fontsize=9,
                   color=age_color)
    else:
        pylab.title(img_title)

    if web:
        web_brand = "http://www.autumnsky.us/vad/"
        pylab.text(1.0,
                   -0.01,
                   web_brand,
                   transform=pylab.gca().transAxes,
                   ha='right',
                   va='top',
                   fontsize=9)

    pylab.savefig(img_file_name, dpi=pylab.gcf().dpi)
    pylab.close()

    if web:
        bounds = {
            'min_u': min_u,
            'max_u': max_u,
            'min_v': min_v,
            'max_v': max_v
        }
        print(json.dumps(bounds))
Ejemplo n.º 55
0
def plot_mass_luminosity():
    clust_m = pickle.load(open(propdir + 'clust_arches_multi.pickle', 'rb'))
    clust_s = pickle.load(open(propdir + 'clust_arches_single.pickle', 'rb'))

    color_m = clust_m.magJ - clust_m.magKp
    color_s = clust_s.magJ - clust_s.magKp
    
    py.figure(3)
    py.clf()
    py.plot(color_m, clust_m.magKp, 'k.')
    py.gca().invert_yaxis()
    py.ylim(22, 8)
    py.xlabel('J - Kp (mag)')
    py.ylabel('Kp (mag)')
    py.savefig(propdir + 'plots/arches_syn_cmd.png')
    
    py.figure(1, figsize=(7, 6))
    py.clf()
    #py.scatter(clust_s.magKp, clust_s.mass, c='black', s=10)
    py.scatter(clust_m.mass, clust_m.magKp, c=color_m, edgecolor='none', s=10)
    py.gca().set_xscale('log')
    py.gca().invert_yaxis()
    py.ylim(22, 8)
    py.xlim(0.1, 100)
    cbar = py.colorbar()
    cbar.set_label('J - Kp (mag)')
    py.ylabel('Kp (mag)')
    py.xlabel('Mass ' + r'(M$_\odot$)')
    py.savefig(propdir + 'plots/arches_syn_mass_lum.png')

    # Select out a slice of stars at a luminosity of Kp=19 and see what
    # range of masses they have. This represents intrisic uncertainty.
    # Can we resolve this with color?
    dmag = 0.1
    idx_m = np.where((clust_m.magKp > (19-dmag)) & (clust_m.magKp < (19+dmag)))[0]
    idx_s = np.where((clust_s.magKp > (19-dmag)) & (clust_s.magKp < (19+dmag)))[0]

    
    merr1 = 0.04
    merr2 = 0.1
    cerr1 = np.hypot(merr1, merr1)
    cerr2 = np.hypot(merr2, merr2)
    dmag1 = merr1
    dmag2 = merr2
    idx_1 = np.where((clust_m.magKp > (19-dmag1)) & (clust_m.magKp < (19+dmag1)))[0]
    idx_2 = np.where((clust_m.magKp > (19-dmag2)) & (clust_m.magKp < (19+dmag2)))[0]
    
    py.close(5)
    py.figure(5, figsize=(10,10))
    py.clf()
    py.subplots_adjust(left=0.1, bottom=0.1)
    py.subplot(1, 2, 1)
    py.errorbar(color_m[idx_1], clust_m.mass[idx_1], xerr=cerr1, fmt='ko')
    py.xlim(5.1, 6.0)
    py.xlabel('J - Kp (mag)')
    py.ylabel('Mass ' + r'(M$_\odot$)')
    py.title(r'$\sigma_{photo}$ = 0.04 mag')

    py.subplot(1, 2, 2)
    py.errorbar(color_m[idx_2], clust_m.mass[idx_2], xerr=cerr2, fmt='ko')
    py.xlim(5.1, 6.0)
    py.xlabel('J - Kp (mag)')
    # py.ylabel('Mass ' + r'(M$_\odot$)')
    py.title(r'$\sigma_{photo}$ = 0.1 mag')
        
    py.savefig(propdir + 'plots/arches_syn_mass_color.png')

    
    return
Ejemplo n.º 56
0
    if (plotEvent == True):
        # Plot Electron hit/miss positions
        pylab.figure(1)
        pylab.scatter(electronArrayX,
                      electronArrayY,
                      s=5,
                      facecolor='magenta',
                      alpha=0.15)  # s=size, alpha=Transparency
        pylab.title('Electron Cloud Projection onto Readout Plane')
        pylab.xlabel('x position (um)')
        pylab.ylabel('y position (um)')
        pylab.grid(False)

        # Draw pixels
        # NOTE: Rectangle((x,y), width, height, angle=0.0, **kwargs); where (x,y) is lower left corner
        currentAxis = pylab.gca()

        for i in range(0, NCOLUMNS):
            for j in range(0, NROWS):
                xEdge = -NROWS * PIXELWIDTH / 2 + j * PIXELWIDTH
                yEdge = -NCOLUMNS * PIXELWIDTH / 2 + i * PIXELWIDTH
                currentAxis.add_patch(
                    Rectangle((xEdge, yEdge),
                              PIXELWIDTH,
                              PIXELWIDTH,
                              facecolor='blue',
                              alpha=0.10))
                currentAxis.annotate(
                    str(int(pixelCountArray[i * NCOLUMNS + j])),
                    (xEdge + PIXELWIDTH / 2, yEdge + PIXELWIDTH / 2),
                    color='black',
Ejemplo n.º 57
0
def execute(self, parameters, messages):

    positives_param, negatives_param, models_param, output_param = parameters

    arcpy.env.workspace = output_param.valueAsText

    positives_descr = arcpy.Describe(positives_param.valueAsText)
    positives_x, positives_y = FetchCoordinates(positives_descr.catalogPath).T
    positives_sref = positives_descr.spatialReference

    if negatives_param.valueAsText:
        negatives_descr = arcpy.Describe(negatives_param.valueAsText)
        negatives_sref = positives_descr.spatialReference
        if not SpatialReferencesAreEqual(positives_sref, negatives_sref,
                                         messages):
            raise ValueError(
                "Positives and negatives have different spatial references: '%s' and '%s'."
                % (positives_sref.name, negatives_sref.name))
    else:
        negatives_descr = None

    pylab.figure()
    handle, = pylab.plot([0, 1], [0, 1], "k--", lw=2)

    legend_items = ["Random guess"]
    plot_handles = [handle]

    # Iterates through each model and calculates and plots ROC curves for them.

    max_rows = 0
    model_names, roc_curves, auc_values, auc_confints = [], [], [], []

    tokens = models_param.valueAsText.split(";")

    for i in range(len(tokens)):

        raster_descr = arcpy.Describe(tokens[i])
        raster_sref = raster_descr.spatialReference
        if not SpatialReferencesAreEqual(positives_sref, raster_sref,
                                         messages):
            raise ValueError(
                "Positives and %s have different spatial references: '%s' and '%s'."
                % (raster_descr.name, positives_sref.name, raster_sref.name))

        color = COLOR_TABLE[i % NUM_COLORS]

        _roc_curve, _roc_confints, _auc_value, _auc_confints = CalculateROCCurveAndAUCValueForModel(
            messages, raster_descr, negatives_descr, positives_x, positives_y)

        if _roc_confints:
            pylab.fill_between(_roc_confints[0][:, 0],
                               _roc_confints[0][:, 1],
                               _roc_confints[1][:, 1],
                               color=color,
                               alpha=0.1)
        handle, = pylab.plot(_roc_curve[:, 0],
                             _roc_curve[:, 1],
                             lw=2,
                             color=color)

        plot_handles.append(handle)
        legend_items.append("%s (AUC = %.3f)" %
                            (raster_descr.name, _auc_value))

        messages.addMessage("%s: AUC = %.3f." %
                            (raster_descr.name, _auc_value))
        if _auc_confints:
            messages.addMessage(
                "%s: 95%% confidence interval = %.3f-%.3f." %
                (raster_descr.name, _auc_confints[0], _auc_confints[1]))

        model_names.append(raster_descr.name)
        roc_curves.append(_roc_curve)
        auc_values.append(_auc_value)
        auc_confints.append(_auc_confints)
        max_rows = numpy.max([max_rows, len(_roc_curve)])

    # Configures the plot and saves it.

    png_path = arcpy.CreateUniqueName("results.png")

    pylab.gca().set_xlim([0, 1])
    pylab.gca().set_ylim([0, 1])

    pylab.xlabel("False Positive Rate")
    pylab.ylabel("True Positive Rate")

    pylab.legend(plot_handles, legend_items, 4)

    pylab.savefig(png_path)

    messages.addMessage("Saved ROC curve plot to '%s'." % png_path)

    # Creates a database table for storing the essential results.

    table_path = arcpy.CreateUniqueName("results.dbf")
    dbf_path, dbf_name = os.path.split(table_path)

    arcpy.CreateTable_management(dbf_path, dbf_name)

    arcpy.AddField_management(table_path, "MODEL", "TEXT", field_length=10)
    arcpy.AddField_management(table_path, "AUC", "TEXT", field_length=10)

    if not negatives_descr:
        arcpy.AddField_management(table_path,
                                  "AUC_LO",
                                  "TEXT",
                                  field_length=10)
        arcpy.AddField_management(table_path,
                                  "AUC_HI",
                                  "TEXT",
                                  field_length=10)

    for i in range(len(model_names)):
        arcpy.AddField_management(table_path,
                                  "FPR_%d" % (i + 1),
                                  "DOUBLE",
                                  20,
                                  10,
                                  field_length=10)
        arcpy.AddField_management(table_path,
                                  "TPR_%d" % (i + 1),
                                  "DOUBLE",
                                  20,
                                  10,
                                  field_length=10)

    arcpy.DeleteField_management(table_path,
                                 "Field1")  # Deletes a nuisance field!?

    # Populates the database table.

    cursor = arcpy.InsertCursor(table_path)

    for i in range(max_rows):

        row = cursor.newRow()

        if i < len(model_names):
            row.setValue("MODEL", model_names[i])
            row.setValue("AUC", "%.3f" % auc_values[i])
            if not negatives_descr:
                row.setValue("AUC_LO", "%.3f" % auc_confints[i][0])
                row.setValue("AUC_HI", "%.3f" % auc_confints[i][1])

        for j in range(len(model_names)):
            if len(roc_curves[j]) > i:
                row.setValue("FPR_%d" % (j + 1), roc_curves[j][i, 0])
                row.setValue("TPR_%d" % (j + 1), roc_curves[j][i, 1])

        cursor.insertRow(row)

    del cursor, row

    messages.addMessage("Saved results database table to '%s'." % table_path)
Ejemplo n.º 58
0
    grid_square = zeros(grid_shape)
    block_low = int(grid_shape[0] * .4)
    block_high = int(grid_shape[0] * .5)
    grid_square[block_low:block_high, block_low:block_high] = 0.005

    grid_python = 1 - py.imread(
        request.urlopen(
            "http://a4.mzstatic.com/us/r30/Purple4/v4/e8/20/fd/e820fded-8a78-06ac-79d0-f1d140346976/mzl.huoealqj.png"
        )).mean(2)
    grid_python = asarray(grid_python, dtype='float64')
    scratch_python = empty(grid_python.shape)

    py.subplot(3, 2, 1)
    py.imshow(grid_square.copy())
    py.ylabel("t = 0 seconds")
    py.gca().get_xaxis().set_ticks([])
    py.gca().get_yaxis().set_ticks([])
    py.subplot(3, 2, 2)
    py.imshow(grid_python.copy())
    py.gca().get_xaxis().set_ticks([])
    py.gca().get_yaxis().set_ticks([])

    for i in range(500):
        evolve(grid_square, 0.1, scratch_square)
        grid_square, scratch_square = scratch_square, grid_square

        evolve(grid_python, 0.1, scratch_python)
        grid_python, scratch_python = scratch_python, grid_python

    py.subplot(3, 2, 3)
    py.imshow(grid_square.copy())
Ejemplo n.º 59
0
Archivo: mpl.py Proyecto: yokeldd/vaex
def heatmap(self, x=None, y=None, z=None, what="count(*)", vwhat=None, reduce=["colormap"], f=None,
            normalize="normalize", normalize_axis="what",
            vmin=None, vmax=None,
            shape=256, vshape=32, limits=None, grid=None, colormap="afmhot",  # colors=["red", "green", "blue"],
            figsize=None, xlabel=None, ylabel=None, aspect="auto", tight_layout=True, interpolation="nearest", show=False,
            colorbar=True,
            colorbar_label=None,
            selection=None, selection_labels=None, title=None,
            background_color="white", pre_blend=False, background_alpha=1.,
            visual=dict(x="x", y="y", layer="z", fade="selection", row="subspace", column="what"),
            smooth_pre=None, smooth_post=None,
            wrap=True, wrap_columns=4,
            return_extra=False, hardcopy=None):
    """Viz data in a 2d histogram/heatmap.

    Declarative plotting of statistical plots using matplotlib, supports subplots, selections, layers.

    Instead of passing x and y, pass a list as x argument for multiple panels. Give what a list of options to have multiple
    panels. When both are present then will be origanized in a column/row order.

    This methods creates a 6 dimensional 'grid', where each dimension can map the a visual dimension.
    The grid dimensions are:

     * x: shape determined by shape, content by x argument or the first dimension of each space
     * y:   ,,
     * z:  related to the z argument
     * selection: shape equals length of selection argument
     * what: shape equals length of what argument
     * space: shape equals length of x argument if multiple values are given

     By default, this its shape is (1, 1, 1, 1, shape, shape) (where x is the last dimension)

    The visual dimensions are

     * x: x coordinate on a plot / image (default maps to grid's x)
     * y: y   ,,                         (default maps to grid's y)
     * layer: each image in this dimension is blended togeher to one image (default maps to z)
     * fade: each image is shown faded after the next image (default mapt to selection)
     * row: rows of subplots (default maps to space)
     * columns: columns of subplot (default maps to what)

    All these mappings can be changes by the visual argument, some examples:

    >>> df.plot('x', 'y', what=['mean(x)', 'correlation(vx, vy)'])

    Will plot each 'what' as a column.

    >>> df.plot('x', 'y', selection=['FeH < -3', '(FeH >= -3) & (FeH < -2)'], visual=dict(column='selection'))

    Will plot each selection as a column, instead of a faded on top of each other.





    :param x: Expression to bin in the x direction (by default maps to x), or list of pairs, like [['x', 'y'], ['x', 'z']], if multiple pairs are given, this dimension maps to rows by default
    :param y:                          y           (by default maps to y)
    :param z: Expression to bin in the z direction, followed by a :start,end,shape  signature, like 'FeH:-3,1:5' will produce 5 layers between -10 and 10 (by default maps to layer)
    :param what: What to plot, count(*) will show a N-d histogram, mean('x'), the mean of the x column, sum('x') the sum, std('x') the standard deviation, correlation('vx', 'vy') the correlation coefficient. Can also be a list of values, like ['count(x)', std('vx')], (by default maps to column)
    :param reduce:
    :param f: transform values by: 'identity' does nothing 'log' or 'log10' will show the log of the value
    :param normalize: normalization function, currently only 'normalize' is supported
    :param normalize_axis: which axes to normalize on, None means normalize by the global maximum.
    :param vmin: instead of automatic normalization, (using normalize and normalization_axis) scale the data between vmin and vmax to [0, 1]
    :param vmax: see vmin
    :param shape: shape/size of the n-D histogram grid
    :param limits: list of [[xmin, xmax], [ymin, ymax]], or a description such as 'minmax', '99%'
    :param grid: if the binning is done before by yourself, you can pass it
    :param colormap: matplotlib colormap to use
    :param figsize: (x, y) tuple passed to pylab.figure for setting the figure size
    :param xlabel:
    :param ylabel:
    :param aspect:
    :param tight_layout: call pylab.tight_layout or not
    :param colorbar: plot a colorbar or not
    :param interpolation: interpolation for imshow, possible options are: 'nearest', 'bilinear', 'bicubic', see matplotlib for more
    :param return_extra:
    :return:
    """
    import pylab
    import matplotlib
    n = _parse_n(normalize)
    if type(shape) == int:
        shape = (shape,) * 2
    binby = []
    x = _ensure_strings_from_expressions(x)
    y = _ensure_strings_from_expressions(y)
    for expression in [y, x]:
        if expression is not None:
            binby = [expression] + binby
    fig = pylab.gcf()
    if figsize is not None:
        fig.set_size_inches(*figsize)
    import re

    what_units = None
    whats = _ensure_list(what)
    selections = _ensure_list(selection)
    selections = _ensure_strings_from_expressions(selections)

    if y is None:
        waslist, [x, ] = vaex.utils.listify(x)
    else:
        waslist, [x, y] = vaex.utils.listify(x, y)
        x = list(zip(x, y))
        limits = [limits]

    # every plot has its own vwhat for now
    vwhats = _expand_limits(vwhat, len(x))  # TODO: we're abusing this function..
    logger.debug("x: %s", x)
    limits, shape = self.limits(x, limits, shape=shape)
    shape = shape[0]
    logger.debug("limits: %r", limits)

    # mapping of a grid axis to a label
    labels = {}
    shape = _expand_shape(shape, 2)
    vshape = _expand_shape(shape, 2)
    if z is not None:
        match = re.match("(.*):(.*),(.*),(.*)", z)
        if match:
            groups = match.groups()
            import ast
            z_expression = groups[0]
            logger.debug("found groups: %r", list(groups))
            z_limits = [ast.literal_eval(groups[1]), ast.literal_eval(groups[2])]
            z_shape = ast.literal_eval(groups[3])
            # for pair in x:
            x = [[z_expression] + list(k) for k in x]
            limits = np.array([[z_limits] + list(k) for k in limits])
            shape = (z_shape,) + shape
            vshape = (z_shape,) + vshape
            logger.debug("x = %r", x)
            values = np.linspace(z_limits[0], z_limits[1], num=z_shape + 1)
            labels["z"] = list(["%s <= %s < %s" % (v1, z_expression, v2) for v1, v2 in zip(values[:-1], values[1:])])
        else:
            raise ValueError("Could not understand 'z' argument %r, expected something in form: 'column:-1,10:5'" % facet)
    else:
        z_shape = 1

    # z == 1
    if z is None:
        total_grid = np.zeros((len(x), len(whats), len(selections), 1) + shape, dtype=float)
        total_vgrid = np.zeros((len(x), len(whats), len(selections), 1) + vshape, dtype=float)
    else:
        total_grid = np.zeros((len(x), len(whats), len(selections)) + shape, dtype=float)
        total_vgrid = np.zeros((len(x), len(whats), len(selections)) + vshape, dtype=float)
    logger.debug("shape of total grid: %r", total_grid.shape)
    axis = dict(plot=0, what=1, selection=2)
    xlimits = limits

    grid_axes = dict(x=-1, y=-2, z=-3, selection=-4, what=-5, subspace=-6)
    visual_axes = dict(x=-1, y=-2, layer=-3, fade=-4, column=-5, row=-6)
    # visual_default=dict(x="x", y="y", z="layer", selection="fade", subspace="row", what="column")
    # visual: mapping of a plot axis, to a grid axis
    visual_default = dict(x="x", y="y", layer="z", fade="selection", row="subspace", column="what")

    def invert(x): return dict((v, k) for k, v in x.items())
    # visual_default_reverse = invert(visual_default)
    # visual_ = visual_default
    # visual = dict(visual) # copy for modification
    # add entries to avoid mapping multiple times to the same axis
    free_visual_axes = list(visual_default.keys())
    # visual_reverse = invert(visual)
    logger.debug("1: %r %r", visual, free_visual_axes)
    for visual_name, grid_name in visual.items():
        if visual_name in free_visual_axes:
            free_visual_axes.remove(visual_name)
        else:
            raise ValueError("visual axes %s used multiple times" % visual_name)
    logger.debug("2: %r %r", visual, free_visual_axes)
    for visual_name, grid_name in visual_default.items():
        if visual_name in free_visual_axes and grid_name not in visual.values():
            free_visual_axes.remove(visual_name)
            visual[visual_name] = grid_name
    logger.debug("3: %r %r", visual, free_visual_axes)
    for visual_name, grid_name in visual_default.items():
        if visual_name not in free_visual_axes and grid_name not in visual.values():
            visual[free_visual_axes.pop(0)] = grid_name

    logger.debug("4: %r %r", visual, free_visual_axes)

    visual_reverse = invert(visual)
    # TODO: the meaning of visual and visual_reverse is changed below this line, super confusing
    visual, visual_reverse = visual_reverse, visual
    # so now, visual: mapping of a grid axis to plot axis
    # visual_reverse: mapping of a grid axis to plot axis
    move = {}
    for grid_name, visual_name in visual.items():
        if visual_axes[visual_name] in visual.values():
            index = visual.values().find(visual_name)
            key = visual.keys()[index]
            raise ValueError("trying to map %s to %s while, it is already mapped by %s" % (grid_name, visual_name, key))
        move[grid_axes[grid_name]] = visual_axes[visual_name]

    # normalize_axis = _ensure_list(normalize_axis)

    fs = _expand(f, total_grid.shape[grid_axes[normalize_axis]])
    # assert len(vwhat)
    # labels["y"] = ylabels
    what_labels = []
    if grid is None:
        grid_of_grids = []
        for i, (binby, limits) in enumerate(zip(x, xlimits)):
            grid_of_grids.append([])
            for j, what in enumerate(whats):
                if isinstance(what, vaex.stat.Expression):
                    grid = what.calculate(self, binby=binby, shape=shape, limits=limits, selection=selections, delay=True)
                else:
                    what = what.strip()
                    index = what.index("(")
                    import re
                    groups = re.match("(.*)\((.*)\)", what).groups()
                    if groups and len(groups) == 2:
                        function = groups[0]
                        arguments = groups[1].strip()
                        if "," in arguments:
                            arguments = arguments.split(",")
                        functions = ["mean", "sum", "std", "var", "correlation", "covar", "min", "max", "median_approx"]
                        unit_expression = None
                        if function in ["mean", "sum", "std", "min", "max", "median"]:
                            unit_expression = arguments
                        if function in ["var"]:
                            unit_expression = "(%s) * (%s)" % (arguments, arguments)
                        if function in ["covar"]:
                            unit_expression = "(%s) * (%s)" % arguments
                        if unit_expression:
                            unit = self.unit(unit_expression)
                            if unit:
                                what_units = unit.to_string('latex_inline')
                        if function in functions:
                            grid = getattr(self, function)(arguments, binby=binby, limits=limits, shape=shape, selection=selections, delay=True)
                        elif function == "count":
                            grid = self.count(arguments, binby, shape=shape, limits=limits, selection=selections, delay=True)
                        else:
                            raise ValueError("Could not understand method: %s, expected one of %r'" % (function, functions))
                    else:
                        raise ValueError("Could not understand 'what' argument %r, expected something in form: 'count(*)', 'mean(x)'" % what)
                if i == 0:  # and j == 0:
                    what_label = str(whats[j])
                    if what_units:
                        what_label += " (%s)" % what_units
                    if fs[j]:
                        what_label = fs[j] + " " + what_label
                    what_labels.append(what_label)
                grid_of_grids[-1].append(grid)
        self.execute()
        for i, (binby, limits) in enumerate(zip(x, xlimits)):
            for j, what in enumerate(whats):
                grid = grid_of_grids[i][j].get()
                total_grid[i, j, :, :] = grid[:, None, ...]
        labels["what"] = what_labels
    else:
        dims_left = 6 - len(grid.shape)
        total_grid = np.broadcast_to(grid, (1,) * dims_left + grid.shape)

    #           visual=dict(x="x", y="y", selection="fade", subspace="facet1", what="facet2",)
    def _selection_name(name):
        if name in [None, False]:
            return "selection: all"
        elif name in ["default", True]:
            return "selection: default"
        else:
            return "selection: %s" % name
    if selection_labels is None:
        labels["selection"] = list([_selection_name(k) for k in selections])
    else:
        labels["selection"] = selection_labels

    # visual_grid = np.moveaxis(total_grid, move.keys(), move.values())
    # np.moveaxis is in np 1.11 only?, use transpose
    axes = [None] * len(move)
    for key, value in move.items():
        axes[value] = key
    visual_grid = np.transpose(total_grid, axes)

    logger.debug("grid shape: %r", total_grid.shape)
    logger.debug("visual: %r", visual.items())
    logger.debug("move: %r", move)
    logger.debug("visual grid shape: %r", visual_grid.shape)

    xexpressions = []
    yexpressions = []
    for i, (binby, limits) in enumerate(zip(x, xlimits)):
        xexpressions.append(binby[0])
        yexpressions.append(binby[1])
    if xlabel is None:
        xlabels = []
        ylabels = []
        for i, (binby, limits) in enumerate(zip(x, xlimits)):
            if z is not None:
                xlabels.append(self.label(binby[1]))
                ylabels.append(self.label(binby[2]))
            else:
                xlabels.append(self.label(binby[0]))
                ylabels.append(self.label(binby[1]))
    else:
        Nl = visual_grid.shape[visual_axes['row']]
        xlabels = _expand(xlabel, Nl)
        ylabels = _expand(ylabel, Nl)
    #labels[visual["x"]] = (xlabels, ylabels)
    labels["x"] = xlabels
    labels["y"] = ylabels

    # grid = total_grid
    # print(grid.shape)
    # grid = self.reduce(grid, )
    axes = []
    # cax = pylab.subplot(1,1,1)

    background_color = np.array(matplotlib.colors.colorConverter.to_rgb(background_color))

    # if grid.shape[axis["selection"]] > 1:#  and not facet:
    #   rgrid = vaex.image.fade(rgrid)
    #   finite_mask = np.any(finite_mask, axis=0) # do we really need this
    #   print(rgrid.shape)
    # facet_row_axis = axis["what"]
    import math
    facet_columns = None
    facets = visual_grid.shape[visual_axes["row"]] * visual_grid.shape[visual_axes["column"]]
    if visual_grid.shape[visual_axes["column"]] == 1 and wrap:
        facet_columns = min(wrap_columns, visual_grid.shape[visual_axes["row"]])
        wrapped = True
    elif visual_grid.shape[visual_axes["row"]] == 1 and wrap:
        facet_columns = min(wrap_columns, visual_grid.shape[visual_axes["column"]])
        wrapped = True
    else:
        wrapped = False
        facet_columns = visual_grid.shape[visual_axes["column"]]
    facet_rows = int(math.ceil(facets / facet_columns))
    logger.debug("facet_rows: %r", facet_rows)
    logger.debug("facet_columns: %r", facet_columns)
    # if visual_grid.shape[visual_axes["row"]] > 1: # and not wrap:
    #   #facet_row_axis = axis["what"]
    #   facet_columns = visual_grid.shape[visual_axes["column"]]
    # else:
    #   facet_columns = min(wrap_columns, facets)
    # if grid.shape[axis["plot"]] > 1:#  and not facet:

    # this loop could be done using axis arguments everywhere
    # assert len(normalize_axis) == 1, "currently only 1 normalization axis supported"
    grid = visual_grid * 1.
    fgrid = visual_grid * 1.
    ngrid = visual_grid * 1.
    # colorgrid = np.zeros(ngrid.shape + (4,), float)
    # print "norma", normalize_axis, visual_grid.shape[visual_axes[visual[normalize_axis]]]
    vmins = _expand(vmin, visual_grid.shape[visual_axes[visual[normalize_axis]]], type=list)
    vmaxs = _expand(vmax, visual_grid.shape[visual_axes[visual[normalize_axis]]], type=list)
    # for name in normalize_axis:
    visual_grid
    if smooth_pre:
        grid = vaex.grids.gf(grid, smooth_pre)
    if 1:
        axis = visual_axes[visual[normalize_axis]]
        for i in range(visual_grid.shape[axis]):
            item = [slice(None, None, None), ] * len(visual_grid.shape)
            item[axis] = i
            item = tuple(item)
            f = _parse_f(fs[i])
            with np.errstate(divide='ignore', invalid='ignore'):  # these are fine, we are ok with nan's in vaex
                fgrid.__setitem__(item, f(grid.__getitem__(item)))
            # print vmins[i], vmaxs[i]
            if vmins[i] is not None and vmaxs[i] is not None:
                nsubgrid = fgrid.__getitem__(item) * 1
                nsubgrid -= vmins[i]
                nsubgrid /= (vmaxs[i] - vmins[i])
            else:
                nsubgrid, vmin, vmax = n(fgrid.__getitem__(item))
                vmins[i] = vmin
                vmaxs[i] = vmax
            # print "    ", vmins[i], vmaxs[i]
            ngrid.__setitem__(item, nsubgrid)

    if 0:  # TODO: above should be like the code below, with custom vmin and vmax
        grid = visual_grid[i]
        f = _parse_f(fs[i])
        fgrid = f(grid)
        finite_mask = np.isfinite(grid)
        finite_mask = np.any(finite_mask, axis=0)
        if vmin is not None and vmax is not None:
            ngrid = fgrid * 1
            ngrid -= vmin
            ngrid /= (vmax - vmin)
            ngrid = np.clip(ngrid, 0, 1)
        else:
            ngrid, vmin, vmax = n(fgrid)
            # vmin, vmax = np.nanmin(fgrid), np.nanmax(fgrid)
    # every 'what', should have its own colorbar, check if what corresponds to
    # rows or columns in facets, if so, do a colorbar per row or per column

    rows, columns = int(math.ceil(facets / float(facet_columns))), facet_columns
    colorbar_location = "individual"
    if visual["what"] == "row" and visual_grid.shape[1] == facet_columns:
        colorbar_location = "per_row"
    if visual["what"] == "column" and visual_grid.shape[0] == facet_rows:
        colorbar_location = "per_column"
    # values = np.linspace(facet_limits[0], facet_limits[1], facet_count+1)
    logger.debug("rows: %r, columns: %r", rows, columns)
    import matplotlib.gridspec as gridspec
    column_scale = 1
    row_scale = 1
    row_offset = 0
    if facets > 1:
        if colorbar_location == "per_row":
            column_scale = 4
            gs = gridspec.GridSpec(rows, columns * column_scale + 1)
        elif colorbar_location == "per_column":
            row_offset = 1
            row_scale = 4
            gs = gridspec.GridSpec(rows * row_scale + 1, columns)
        else:
            gs = gridspec.GridSpec(rows, columns)
    facet_index = 0
    fs = _expand(f, len(whats))
    colormaps = _expand(colormap, len(whats))

    # row
    for i in range(visual_grid.shape[0]):
        # column
        for j in range(visual_grid.shape[1]):
            if colorbar and colorbar_location == "per_column" and i == 0:
                norm = matplotlib.colors.Normalize(vmins[j], vmaxs[j])
                sm = matplotlib.cm.ScalarMappable(norm, colormaps[j])
                sm.set_array(1)  # make matplotlib happy (strange behavious)
                if facets > 1:
                    ax = pylab.subplot(gs[0, j])
                    colorbar = fig.colorbar(sm, cax=ax, orientation="horizontal")
                else:
                    colorbar = fig.colorbar(sm)
                if "what" in labels:
                    label = labels["what"][j]
                    if facets > 1:
                        colorbar.ax.set_title(label)
                    else:
                        colorbar.ax.set_ylabel(colorbar_label or label)

            if colorbar and colorbar_location == "per_row" and j == 0:
                norm = matplotlib.colors.Normalize(vmins[i], vmaxs[i])
                sm = matplotlib.cm.ScalarMappable(norm, colormaps[i])
                sm.set_array(1)  # make matplotlib happy (strange behavious)
                if facets > 1:
                    ax = pylab.subplot(gs[i, -1])
                    colorbar = fig.colorbar(sm, cax=ax)
                else:
                    colorbar = fig.colorbar(sm)
                label = labels["what"][i]
                colorbar.ax.set_ylabel(colorbar_label or label)

            rgrid = ngrid[i, j] * 1.
            # print rgrid.shape
            for k in range(rgrid.shape[0]):
                for l in range(rgrid.shape[0]):
                    if smooth_post is not None:
                        rgrid[k, l] = vaex.grids.gf(rgrid, smooth_post)
            if visual["what"] == "column":
                what_index = j
            elif visual["what"] == "row":
                what_index = i
            else:
                what_index = 0

            if visual[normalize_axis] == "column":
                normalize_index = j
            elif visual[normalize_axis] == "row":
                normalize_index = i
            else:
                normalize_index = 0
            for r in reduce:
                r = _parse_reduction(r, colormaps[what_index], [])
                rgrid = r(rgrid)

            row = facet_index // facet_columns
            column = facet_index % facet_columns

            if colorbar and colorbar_location == "individual":
                # visual_grid.shape[visual_axes[visual[normalize_axis]]]
                norm = matplotlib.colors.Normalize(vmins[normalize_index], vmaxs[normalize_index])
                sm = matplotlib.cm.ScalarMappable(norm, colormaps[what_index])
                sm.set_array(1)  # make matplotlib happy (strange behavious)
                if facets > 1:
                    ax = pylab.subplot(gs[row, column])
                    colorbar = fig.colorbar(sm, ax=ax)
                else:
                    colorbar = fig.colorbar(sm)
                label = labels["what"][what_index]
                colorbar.ax.set_ylabel(colorbar_label or label)

            if facets > 1:
                ax = pylab.subplot(gs[row_offset + row * row_scale:row_offset + (row + 1) * row_scale, column * column_scale:(column + 1) * column_scale])
            else:
                ax = pylab.gca()
            axes.append(ax)
            logger.debug("rgrid: %r", rgrid.shape)
            plot_rgrid = rgrid
            assert plot_rgrid.shape[1] == 1, "no layers supported yet"
            plot_rgrid = plot_rgrid[:, 0]
            if plot_rgrid.shape[0] > 1:
                plot_rgrid = vaex.image.fade(plot_rgrid[::-1])
            else:
                plot_rgrid = plot_rgrid[0]
            extend = None
            if visual["subspace"] == "row":
                subplot_index = i
            elif visual["subspace"] == "column":
                subplot_index = j
            else:
                subplot_index = 0
            extend = np.array(xlimits[subplot_index][-2:]).flatten()
            #   extend = np.array(xlimits[i]).flatten()
            logger.debug("plot rgrid: %r", plot_rgrid.shape)
            plot_rgrid = np.transpose(plot_rgrid, (1, 0, 2))
            im = ax.imshow(plot_rgrid, extent=extend.tolist(), origin="lower", aspect=aspect, interpolation=interpolation)
            # v1, v2 = values[i], values[i+1]

            def label(index, label, expression):
                if label and _issequence(label):
                    return label[i]
                else:
                    return self.label(expression)
            if visual_reverse["x"] =='x':
                labelsx = labels['x']
                pylab.xlabel(labelsx[subplot_index])
            if visual_reverse["x"] =='x':
                labelsy = labels['y']
                pylab.ylabel(labelsy[subplot_index])
            if visual["z"] in ['row']:
                labelsz = labels['z']
                ax.set_title(labelsz[i])
            if visual["z"] in ['column']:
                labelsz = labels['z']
                ax.set_title(labelsz[j])

            max_labels = 10
            xexpression = xexpressions[subplot_index]
            if self.iscategory(xexpression):
                labels = self.category_labels(xexpression)
                step = max(len(labels) // max_labels, 1)
                pylab.xticks(np.arange(len(labels))[::step], labels[::step], size='small')
            yexpression = yexpressions[subplot_index]
            if self.iscategory(yexpression):
                labels = self.category_labels(yexpression)
                step = max(len(labels) // max_labels, 1)
                pylab.yticks(np.arange(len(labels))[::step], labels[::step], size='small')
            facet_index += 1
    if title:
        fig.suptitle(title, fontsize="x-large")
    if tight_layout:
        if title:
            pylab.tight_layout(rect=[0, 0.03, 1, 0.95])
        else:
            pylab.tight_layout()
    if hardcopy:
        pylab.savefig(hardcopy)
    if show:
        pylab.show()
    if return_extra:
        return im, grid, fgrid, ngrid, rgrid
    else:
        return im
Ejemplo n.º 60
0
def energy():

    #===============================================================================
    # Magnetic and electric energies

    data = numpy.loadtxt(".././Zeltron2D/data/Eem.dat")
    emag = data[:, 0]
    eelc = data[:, 1]

    plt.plot(emag, color='blue', lw=2)
    plt.plot(eelc, color='red', lw=2)

    plt.xlabel('Time step', fontsize=18)
    plt.ylabel('Energy', fontsize=18)

    #===============================================================================
    # Particle kinetic energies

    # Electrons
    ekineb = numpy.loadtxt(".././Zeltron2D/data/Ekin_electrons_bg.dat")
    ekined = numpy.loadtxt(".././Zeltron2D/data/Ekin_electrons_drift.dat")

    # Ions
    ekinpb = numpy.loadtxt(".././Zeltron2D/data/Ekin_ions_bg.dat")
    ekinpd = numpy.loadtxt(".././Zeltron2D/data/Ekin_ions_drift.dat")

    plt.plot(ekineb + ekined + ekinpb + ekinpd, ls='--', lw=2, color='green')

    #===============================================================================
    # Radiative energies

    # Synchrotron
    # Electrons
    esyne = numpy.loadtxt(".././Zeltron2D/data/Esyn_electrons.dat")
    # Ions
    esynp = numpy.loadtxt(".././Zeltron2D/data/Esyn_electrons.dat")

    plt.plot(esyne + esynp, ls='--', lw=2, color='magenta')

    # Inverse Compton
    # Electrons
    eicse = numpy.loadtxt(".././Zeltron2D/data/Eics_electrons.dat")
    # Ions
    eicsp = numpy.loadtxt(".././Zeltron2D/data/Eics_electrons.dat")

    plt.plot(eicse + eicsp, ls=':', lw=2, color='magenta')

    #===============================================================================
    # Total energy

    etot = emag + eelc + ekineb + ekined + ekinpb + ekinpd + esyne + esynp + eicse + eicsp
    plt.plot(etot, ls='-', lw=3, color='black')

    error = (etot[len(etot) - 1] - etot[0]) / etot[0] * 100.0

    # Relative error
    print ""
    print "********************************"
    print "Total energy relative error:"
    print error, "%"
    print "********************************"

    # Plot legend
    pylab.legend(('Magnetic', 'Electric', 'Particles', 'Synchrotron',
                  'Inv. Compton', 'Total'),
                 shadow=False,
                 loc=(0.65, 0.27))
    ltext = pylab.gca().get_legend().get_texts()
    pylab.setp(ltext[0], fontsize=15)
    pylab.setp(ltext[1], fontsize=15)
    pylab.setp(ltext[2], fontsize=15)
    pylab.setp(ltext[3], fontsize=15)
    pylab.setp(ltext[4], fontsize=15)
    pylab.setp(ltext[5], fontsize=15)

    plt.title("Error= %+2.3f " % error + "%", fontsize=20)

    #===============================================================================

    plt.show()