Exemplo n.º 1
0
    def test_fit_gaussian_2d(self):
        import matplotlib.pylab as plt
        # Create the gaussian data
        Xin, Yin = plt.mgrid[0:201, 0:201]
        data = self._gaussian(3, 100, 100, 20, 40)(Xin, Yin) + \
            np.random.random(Xin.shape)

        plt.clf()
        ax2 = plt.axes([0, 0.52, 1.0, 0.4])
        ax2.matshow(data, cmap=plt.cm.gist_earth_r)

        params = ap.fitGaussianImage(data)
        fit = self._gaussian(*params)

        ax2.contour(fit(*np.indices(data.shape)), cmap=plt.cm.cool)
        (height, x, y, width_x, width_y) = params

        plt.text(0.95, 0.05, """
        x : %.1f
        y : %.1f
        width_x : %.1f
        width_y : %.1f""" %(x, y, width_x, width_y),
             fontsize=16, horizontalalignment='right',
             verticalalignment='bottom', transform=ax2.transAxes)

        ax1 = plt.axes([0, 0.08, 1.0, 0.4])
Exemplo n.º 2
0
def propagate_el_den_TB(Nx=50, Ny=40, mu=0.05, frame_num=100):
    
    ham = envtb.ldos.hamiltonian.HamiltonianTB(Ny, Nx)
    
    wf_final = wf_init_from_electron_density(ham, mu = mu)
    
    maxel =  1.2 * np.max(wf_final.wf1d)
    wf_final.plot_wave_function(maxel)
    plt.axes().set_aspect('equal')
    plt.savefig('../../../../Desktop/pics_2d/TB/0%d_2d.png' % 0)
    plt.close()
                    
    for i in xrange(frame_num):
        
        potential = envtb.ldos.potential.Potential1DFromFunction(
            lambda x: -5. * (Ny/2 - x) * 2. / Ny * np.sin(0.1 * i))
        
        ham2 = ham.apply_potential(potential)
        
        envtb.ldos.plotter.Plotter().plot_potential(
            ham2, ham, maxel = 5, minel = -5)
        
        plt.axes().set_aspect('equal')
        plt.savefig('../../../../Desktop/pics_2d/TB/pot%03d_2d.png' % i)
        plt.close()
        
        
        wf_init = wf_final
        wf_final = propagate_wave_function(wf_init, ham2, maxel = maxel, 
            file_out = '../../../../Desktop/pics_2d/TB/f%03d_2d.png' % i)
    
    return None
Exemplo n.º 3
0
def display_grid(grid, **kwargs):
    fig = plt.figure()
    plt.axes().set_aspect('equal')

    if kwargs.get('mark_core_cells', True):
        core_cell_coords = grid._cell_nodes[1:-1, 1:-1]
        cellx, celly = core_cell_coords[:, :, 0], core_cell_coords[:, :, 1]
        plt.plot(cellx, celly, '-o', np.transpose(cellx), np.transpose(celly), '-o', color='red')

    if kwargs.get('mark_boundary_cells', True):
        boundary_cell_coords = grid._cell_nodes[0, :], \
                               grid._cell_nodes[-1, :], \
                               grid._cell_nodes[1:-1, 0], \
                               grid._cell_nodes[1:-1, -1]

        for coords in boundary_cell_coords:
            plt.plot(coords[:, 0], coords[:, 1], '-x', color='blue')

    if kwargs.get('show', False):
        plt.show()

    f = BytesIO()
    plt.savefig(f)

    return f
Exemplo n.º 4
0
def propagate_gauss_graphene(Nx=30, Ny=30, frame_num=100):
    
    ham = envtb.ldos.hamiltonian.HamiltonianGraphene(Ny, Nx)
    
    ic = Nx/2 * Ny + Ny/2 + 2
    
    wf_final = wf_init_gaussian_wave_packet(
        ham.coords, ic, p0=[1.0, 0.0], sigma=7.)
    
    maxel = 0.8 * np.max(wf_final.wf1d)
    wf_final.plot_wave_function(maxel)
    plt.axes().set_aspect('equal')
    plt.savefig('../../../../Desktop/pics_2d/graphene/0%d_2d.png' % 0)
    plt.close()
    
    dt_new = 0.5
    NK_new = 12
    
    for i in xrange(frame_num):
        print 'frame %(i)d' % vars()
        wf_init = wf_final
        wf_final, dt_new, NK_new = propagate_wave_function(
            wf_init, ham, NK=NK_new, dt=dt_new, maxel = maxel, regime='SIL', 
            file_out = '../../../../Desktop/pics_2d/graphene/f%03d_2d.png'
            % i)
     
    return None
Exemplo n.º 5
0
def plot_fig(data):
    nullfmt = NullFormatter()
    x, y = data[:, 0], data[:, 1]
    left, width = 0.1, 0.65
    bottom, height = 0.1, 0.65
    bottom_h = left_h = left + width + 0.02

    rect_scatter = [left, bottom, width, height]
    rect_histx = [left, bottom_h, width, 0.2]
    rect_histy = [left_h, bottom, 0.2, height]

    plt.figure(1, figsize=(8, 8))

    axScatter = plt.axes(rect_scatter)
    plt.xlabel("eruptions")
    plt.ylabel("waiting")
    axHistx = plt.axes(rect_histx)
    axHisty = plt.axes(rect_histy)
    axHistx.xaxis.set_major_formatter(nullfmt)
    axHisty.yaxis.set_major_formatter(nullfmt)

    axScatter.scatter(x, y)

    # now determine nice limits by hand:
    axHistx.hist(x, bins=20)
    axHisty.hist(y, bins=20, orientation="horizontal")

    plt.savefig("Scatter_Plot.png")
    plt.show()
Exemplo n.º 6
0
def plot(frame,dirname,clim=None,axis_limits=None):
    if not os.path.exists('./figures'):
        os.makedirs('./figures')
        
    try:
        sol=Solution(frame,file_format='petsc',read_aux=False,path='./saved_data/'+dirname+'/_p/',file_prefix='claw_p')
    except IOError:
        'Data file not found; please unzip the files in saved_data/.'
        return
    x=sol.state.grid.x.centers; y=sol.state.grid.y.centers
    mx=len(x); my=len(y)
    
    mp=sol.state.num_eqn    
    yy,xx = np.meshgrid(y,x)

    p=sol.state.q[0,:,:]
    if clim is not None:
        pl.pcolormesh(xx,yy,p,cmap=cm.RdBu_r)
    else:
        pl.pcolormesh(xx,yy,p,cmap=cm.Reds)
    pl.title("t= "+str(sol.state.t),fontsize=20)
    pl.xticks(size=20); pl.yticks(size=20)
    cb = pl.colorbar();

    if clim is not None:
        pl.clim(clim[0],clim[1]);
    imaxes = pl.gca(); pl.axes(cb.ax)
    pl.yticks(fontsize=20); pl.axes(imaxes)
    pl.axis('equal')
    if axis_limits is None:
        pl.axis([np.min(x),np.max(x),np.min(y),np.max(y)])
    else:
        pl.axis([axis_limits[0],axis_limits[1],axis_limits[2],axis_limits[3]])
    pl.savefig('./figures/'+dirname+'.png')
    pl.close()
def plot_p(frame):
    sol=Solution(frame,file_format='petsc',read_aux=False,path='./_output/_p/',file_prefix='claw_p')
    x=sol.state.grid.x.centers; y=sol.state.grid.y.centers
    mx=len(x); my=len(y)
    
    mp=sol.state.num_eqn    
    yy,xx = np.meshgrid(y,x)

    p=sol.state.q[0,:,:]
    fig = pl.figure(figsize=(8, 3.5))
    #pl.title("t= "+str(sol.state.t),fontsize=20)
    pl.xticks(size=20); pl.yticks(size=20)
    pl.xlabel('x',fontsize=20); pl.ylabel('y',fontsize=20)
    #pl.pcolormesh(xx,yy,p_subxy,cmap=cm.OrRd)
    pl.pcolormesh(xx,yy,p,cmap='RdBu_r')
    pl.autoscale(tight=True)
    cb = pl.colorbar(ticks=[0.5,1,1.5,2]);
    
    #pl.clim(ticks=[0.5,1,1.5,2])
    imaxes = pl.gca(); pl.axes(cb.ax)
    pl.yticks(fontsize=20); pl.axes(imaxes)
    #pl.xticks(fontsize=20); pl.axes(imaxes)
    #pl.axis('equal')
    pl.axis('tight')
    fig.tight_layout()
    pl.savefig('./_plots_to_paper/sound-speed_FV_t'+str(frame)+'_pcolor.png')
    pl.close()
Exemplo n.º 8
0
    def _stacking(self, star_list, x_list, y_list):
        """

        :param star_list:
        :return:
        """
        n_stars = len(star_list)

        shifteds = []
        for i in range(n_stars):
            xc, yc = x_list[i], y_list[i]
            data = star_list[i]
            x_shift = int(xc) - xc
            y_shift = int(yc) - yc
            shifted = interp.shift(data, [-y_shift, -x_shift], order=1)
            shifteds.append(shifted)
            print('=== object ===', i)
            import matplotlib.pylab as plt
            fig, ax1 = plt.subplots()
            im = ax1.matshow(np.log10(shifted), origin='lower')
            plt.axes(ax1)
            fig.colorbar(im)
            plt.show()

        combined = sum(shifteds)
        new=np.empty_like(combined)
        max_pix = np.max(combined)
        p = combined[combined>=max_pix/10**6]  #in the SIS regime
        new[combined < max_pix/10**6] = 0
        new[combined >= max_pix/10**6] = p
        kernel = util.kernel_norm(new)
        return kernel
Exemplo n.º 9
0
def propagate_gauss_graphene_W90(Nx=30, Ny=20, magnetic_B=None,
                                 frame_num=100):
    
    ham_w90 = define_zigzag_ribbon_w90(
        "../../exampledata/02_graphene_3rdnn/graphene3rdnnlist.dat", 
        Ny, Nx, magnetic_B=magnetic_B)
    
    ham = envtb.ldos.hamiltonian.HamiltonianFromW90(ham_w90, Nx)
    
    ic = ham.Nx/2 * ham.Ny + ham.Ny/2 + 2 
    
    wf_final = wf_init_gaussian_wave_packet(ham.coords, ic, sigma = 10.)
    
    maxel = 0.8 * np.max(wf_final.wf1d)
    wf_final.plot_wave_function(maxel)
    plt.axes().set_aspect('equal')
    plt.savefig('../../../../Desktop/pics_2d/grapheneW90/0%d_2d.png' % 0)
    plt.close()

    for i in xrange(frame_num):
    
        wf_init = wf_final
        wf_final = propagate_wave_function(wf_init, ham, maxel=maxel,
            file_out='../../../../Desktop/pics_2d/grapheneW90/f%03d_2d.png' % i)[0]
    
    return None
Exemplo n.º 10
0
def plot_decision_surface(axes, clusters, X, Y=None):
    import matplotlib.pylab as pylab
    import numpy as np

    def kmeans_predict(clusters, X):
        from ..core import distance
        dist_m = distance.minkowski_dist(clusters, X)
        print 'dist_m:', dist_m.shape
        pred = np.argmin(dist_m, axis=0)
        print 'pred:', pred.shape
        return pred

    # step size in the mesh
    h = (np.max(X, axis=0) - np.min(X, axis=0)) / 100.0
    # create a mesh to plot in
    x_min = np.min(X, axis=0) - 1
    x_max = np.max(X, axis=0) + 1
    xx, yy = np.meshgrid(np.arange(x_min[0], x_max[0], h[0]),
                         np.arange(x_min[1], x_max[1], h[1]))
    Z = kmeans_predict(clusters, np.c_[xx.ravel(), yy.ravel()])
    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    pylab.set_cmap(pylab.cm.Paired)
    pylab.axes(axes)
    pylab.contourf(xx, yy, Z, cmap=pylab.cm.Paired)
    pylab.xlim(np.min(xx), np.max(xx))
    pylab.ylim(np.min(yy), np.max(yy))
    #pylab.axis('off')

    # Plot also the training points
    if Y is not None:
        pylab.scatter(X[:,0], X[:,1], c=Y)
    else:
        pylab.scatter(X[:,0], X[:,1])
    pylab.scatter(clusters[:,0], clusters[:,1], s=200, marker='x', color='white')
    def __init__(self, ax, collection, mmc, img):
        self.colornormalizer = Normalize(vmin=0, vmax=1, clip=False)
        self.scat = plt.scatter(img[:, 0], img[:, 1], c=mmc.classvec)
        plt.gray()
        plt.setp(ax.get_yticklabels(), visible=False)
        ax.yaxis.set_tick_params(size=0)
        plt.setp(ax.get_xticklabels(), visible=False)
        ax.xaxis.set_tick_params(size=0)
        self.img = img
        self.canvas = ax.figure.canvas
        self.collection = collection
        #self.alpha_other = alpha_other
        self.mmc = mmc
        self.prevnewclazz = None

        self.xys = collection
        self.Npts = len(self.xys)
        
        self.lockedset = set([])

        self.lasso = LassoSelector(ax, onselect=self.onselect)#, lineprops = {:'prism'})
        self.lasso.disconnect_events()
        self.lasso.connect_event('button_press_event', self.lasso.onpress)
        self.lasso.connect_event('button_release_event', self.onrelease)
        self.lasso.connect_event('motion_notify_event', self.lasso.onmove)
        self.lasso.connect_event('draw_event', self.lasso.update_background)
        self.lasso.connect_event('key_press_event', self.onkeypressed)
        #self.lasso.connect_event('button_release_event', self.onrelease)
        self.ind = []
        self.slider_axis = plt.axes(slider_coords, visible = False)
        self.slider_axis2 = plt.axes(obj_fun_display_coords, visible = False)
        self.in_selection_slider = None
        newws = list(set(range(len(self.collection))) - self.lockedset)
        self.mmc.new_working_set(newws)
        self.lasso.line.set_visible(False)
Exemplo n.º 12
0
def plotLFP ():
    print('Plotting LFP power spectral density...')

    colorspsd=array([[0.42,0.67,0.84],[0.42,0.83,0.59],[0.90,0.76,0.00],[0.90,0.32,0.00],[0.34,0.67,0.67],[0.42,0.82,0.83],[0.90,0.59,0.00],[0.33,0.67,0.47],[1.00,0.85,0.00],[0.71,0.82,0.41],[0.57,0.67,0.33],[1.00,0.38,0.60],[0.5,0.2,0.0],[0.0,0.2,0.5]]) 

    lfpv=[[] for c in range(len(sim.lfppops))]    
    # Get last modified .mat file if no input and plot
    for c in range(len(sim.lfppops)):
        lfpv[c] = sim.lfps[:,c]    
    lfptot = sum(lfpv)
        
    # plot pops separately
    plotPops = 0
    if plotPops:    
        figure() # Open a new figure
        for p in range(len(sim.lfppops)):
            psd(lfpv[p],Fs=200, linewidth= 2,color=colorspsd[p])
            xlabel('Frequency (Hz)')
            ylabel('Power')
            h=axes()
            h.set_yticklabels([])
        legend(['L2/3','L5A', 'L5B', 'L6'])

    # plot overall psd
    figure() # Open a new figure
    psd(lfptot,Fs=200, linewidth= 2)
    xlabel('Frequency (Hz)')
    ylabel('Power')
    h=axes()
    h.set_yticklabels([])

    show()
Exemplo n.º 13
0
def plot_p_leading_order(frame):
    mat = scipy.io.loadmat('sound-speed_2D-wave.mat')
    T=5; nt=T/0.5
    pp=mat['U'][nt,:,:]
    xx=mat['xx']
    yy=mat['yy']

    fig=pl.figure(figsize=(8, 3.5))
    #pl.title("t= "+str(sol.state.t),fontsize=20)
    pl.xticks(size=20); pl.yticks(size=20)
    pl.xlabel('x',fontsize=20); pl.ylabel('y',fontsize=20)
    #pl.pcolormesh(xx,yy,p_subxy,cmap=cm.OrRd)
    pl.pcolormesh(xx,yy,pp,cmap='RdBu_r')
    pl.autoscale(tight=True)
    cb = pl.colorbar(ticks=[0.5,1,1.5,2]);
    
    #pl.clim(ticks=[0.5,1,1.5,2])
    imaxes = pl.gca(); pl.axes(cb.ax)
    pl.yticks(fontsize=20); pl.axes(imaxes)
    #pl.xticks(fontsize=20); pl.axes(imaxes)
    #pl.axis('equal')
    pl.axis('tight')
    fig.tight_layout()
    pl.savefig('./_plots_to_paper/sound-speed_LO_t'+str(frame)+'_pcolor.png')
    pl.close()
Exemplo n.º 14
0
    def plot(self, data, topn):
        """ Plot data fit and residuals """
        from matplotlib import pylab as pl
        pl.axes([0.1, 0.4, 0.8, 0.4])   # leave room above the axes for the table
        self.fit_plot(data, topn=topn)

        pl.axes([0.1, 0.05, 0.8, 0.3]) 
        self.residual_plot(data, topn=topn)
Exemplo n.º 15
0
def newCreateAndSaveMultilineFig(xDataList, yDataList, xLabel="", yLabel="",
                                 figFileRoot="", fileExt='.png', xMin=0,
                                 xMax=0, yMin=0, yMax=0, legendFlag=1,
                                 legendFont=12, traceNameList=[],
                                 legLoc=(0, 0)):
    """This subroutine saves a figure with multiple lines."""

    figFileName = figFileRoot + fileExt
    colorDict = createColorDictWithDashes()

    if xMax == 0:
        curMax = 0
        for n in range(0, len(xDataList)):
            if type(xDataList[n]) == list:
                if max(xDataList[n]) > curMax:
                    curMax = max(xDataList[n])
            else:
                if xDataList[n].any() > curMax:
                    curMax = max(xDataList[n])
        xMax = curMax

    if yMax == 0:
        curMax = 0
        for n in range(0, len(yDataList)):
            if type(yDataList[n]) == list:
                if max(yDataList[n]) > curMax:
                    curMax = max(yDataList[n])
            else:
                if yDataList[n].any() > curMax:
                    curMax = max(yDataList[n])
        yMax = curMax

    plt.axes([0.1, 0.1, 0.71, 0.8])
    if traceNameList == []:
        for n in range(0, len(xDataList)):
            traceNameList.append("Trace_" + str(n))

    for n in range(0, len(xDataList)):
        xData = convert_list_to_array(xDataList[n])
        yData = convert_list_to_array(yDataList[n])
        tempPlot = plt.plot(
            xData, yData, colorDict[str(n + 1)], hold="True",
            label=traceNameList[n])

    plt.xlabel(xLabel)
    plt.ylabel(yLabel)
    plt.xlim(xMin, xMax)
    plt.ylim(yMin, yMax)
    plt.rc("legend", fontsize=legendFont)

    if legendFlag == 1:
        if legLoc != (0, 0):
            print(legLoc)
            plt.legend(loc=legLoc)
        else:
            plt.legend()
    plt.savefig(figFileName, dpi=300)
    plt.clf()
Exemplo n.º 16
0
def plot_scatter(x,y,show=1,nbins=100,xrange=None,yrange=None,title="",xtitle="",ytitle=""):

    from matplotlib.ticker import NullFormatter

    # the random data

    nullfmt   = NullFormatter()         # no labels

    # definitions for the axes
    left, width    = 0.1, 0.65
    bottom, height = 0.1, 0.65
    bottom_h = left_h = left+width+0.02

    rect_scatter = [left, bottom, width, height]
    rect_histx   = [left, bottom_h, width, 0.2]
    rect_histy   = [left_h, bottom, 0.2, height]

    # start with a rectangular Figure
    fig = plt.figure(figsize=(8,8))

    axScatter = plt.axes(rect_scatter)
    axHistx = plt.axes(rect_histx)
    axHisty = plt.axes(rect_histy)

    # no labels
    axHistx.xaxis.set_major_formatter(nullfmt)
    axHisty.yaxis.set_major_formatter(nullfmt)

    # now determine nice limits by hand:
    binwidth = np.array([x.max() - x.min(), y.max() - y.min()]).max() / nbins

    if xrange == None:
        xrange = np.array((x.min(), x.max()))
    if yrange == None:
        yrange = np.array((y.min(), y.max()))

    # the scatter plot:
    axScatter.scatter(x, y, marker='.', edgecolor='b', s=.1)

    axScatter.set_xlabel(xtitle)
    axScatter.set_ylabel(ytitle)

    axScatter.set_xlim( xrange )
    axScatter.set_ylim( yrange )

    bins_x = np.arange(xrange[0], xrange[1] + binwidth, binwidth)
    axHistx.hist(x, bins=nbins)
    axHisty.hist(y, bins=nbins, orientation='horizontal')

    axHistx.set_xlim( axScatter.get_xlim() )

    axHistx.set_title(title)
    axHisty.set_ylim( axScatter.get_ylim() )


    if show: plt.show()

    return fig
Exemplo n.º 17
0
    def save_wave_function_pic(self, pic_out, maxel=None, figuresize=(20,10), **kwrds):
        if figuresize:
            plt.figure(figsize=figuresize) # in inches!

        self.plot_wave_function(maxel)
        plt.axes().set_aspect('equal')
        plt.savefig(pic_out)
        plt.close()
        return None
Exemplo n.º 18
0
def image(Z,xnew,ynew,my_cmap=None,aspect='equal'):
	"""
Creates pretty image. You need to specify:
	"""
	imshow(log10(Z),extent=[xnew[0],xnew[-1],ynew[0],ynew[-1]], cmap=my_cmap)
	pylab.axes().set_aspect('equal')
	colorbar()
	circle2=Circle((0,0),1,color='k')
	gca().add_artist(circle2)
	savefig('tmp.png',transparent=True,dpi=150)
Exemplo n.º 19
0
def plot_q(frame,file_prefix='claw',path='./_output/',plot_pcolor=True,plot_slices=True,slices_xlimits=None):
    import sys
    sys.path.append('.')
    import sw_eqns

    sol=Solution(frame,file_format='petsc',read_aux=False,path=path,file_prefix=file_prefix)
    x=sol.state.grid.x.centers; y=sol.state.grid.y.centers
    mx=len(x); my=len(y)

    h=sol.state.q[0,:,:]
    b=sw_eqns.bathymetry(x,y)[0,:,:]
    eta=h+b

    yy,xx = np.meshgrid(y,x)

    if frame < 10:
        str_frame = "000"+str(frame)
    elif frame < 100:
        str_frame = "00"+str(frame)
    elif frame < 1000:
        str_frame = "0"+str(frame)
    else:
        str_frame = str(frame)

    if plot_pcolor:
        pl.pcolormesh(xx,yy,eta)
        pl.title("t= "+str(sol.state.t),fontsize=20)
        pl.xlabel('x',fontsize=20); pl.ylabel('y',fontsize=20)
        pl.xticks(size=20); pl.yticks(size=20)
        cb = pl.colorbar(); 
        #pl.clim(colorbar_min,colorbar_max); 
        imaxes = pl.gca(); pl.axes(cb.ax)
        pl.yticks(fontsize=20); pl.axes(imaxes)
        pl.axis([np.min(x),np.max(x),np.min(y),np.max(y)])
        pl.savefig('./_plots/eta_'+str_frame+'.png')
        #pl.show()
        pl.close()
    if plot_slices:
        pl.figure(figsize=(8,3))
        pl.plot(x,eta[:,3*my/4.],'-r',lw=1)
        pl.plot(x,eta[:,my/4.],'--b',lw=1)
        #pl.plot(x,b[:,my/4],'-k',lw=1)
        #pl.plot(x,b[:,3*my/4],'--k',lw=1)
        pl.title("t= "+str(sol.state.t),fontsize=20)
        pl.xlabel('x',fontsize=20)
        pl.ylabel('Surface',fontsize=20)
        pl.xticks(size=20); pl.yticks(size=20)
        #pl.ylim([0.9998,1.0002])
        pl.xlim([0.0,20])
        if slices_xlimits is not None:
            pl.axis([slices_xlimits[0],slices_xlimits[1],np.min(p),np.max(p)])
        pl.savefig('./_plots/eta_'+str_frame+'_slices.png')
        pl.close()
Exemplo n.º 20
0
def ana():
    pl.figure()
    pl.clf()
    pl.axes([0.16,0.2,0.95-0.15,0.95-0.2])
    pl.plot(x,y1,'g:',label=r'$\psi$')
    pl.plot(x,y2,'-b',label=r'$\psi^*\psi$')
    pl.xlabel(r'$y$ [nm]')
    pl.ylabel(r'$\pi$ [arb. units]')
    ax = pl.gca()
    ax.yaxis.set_label_coords(xshift, 0.5)
    # pl.legend()
    pl.savefig('images/analytical3.pdf',transparent='true')
Exemplo n.º 21
0
def plot_p(frame,file_prefix='claw_p',path='./_output/_p',plot_slices=True,plot_pcolor=True,slices_limits=None,xshift=0.0,name='',title=True):
    sol_ref=Solution(frame+450,file_format='petsc',read_aux=False,path='_output/reference/_p/',file_prefix=file_prefix)
    sol=Solution(frame,file_format='petsc',read_aux=False,path=path,file_prefix=file_prefix)
    x=sol.state.grid.x.centers; y=sol.state.grid.y.centers
    x=x+xshift
    mx=len(x); my=len(y)    
    yy,xx = np.meshgrid(y,x)

    if frame < 10:
        str_frame = "00"+str(frame)
    elif frame < 100:
        str_frame = "0"+str(frame)
    else:
        str_frame = str(frame)

    p=sol.state.q[0,:,:]
    p_ref=sol_ref.state.q[0,:,:]

    if plot_pcolor:
        pl.pcolormesh(xx,yy,p,cmap=cm.OrRd)
        pl.title("t= "+str(sol.state.t),fontsize=20)
        pl.xlabel('x',fontsize=20); pl.ylabel('y',fontsize=20)
        pl.xticks(size=20); pl.yticks(size=20)
        cb = pl.colorbar();
        #pl.clim(colorbar_min,colorbar_max);
        imaxes = pl.gca(); pl.axes(cb.ax)
        pl.yticks(fontsize=20); pl.axes(imaxes)
        pl.axis([np.min(x),np.max(x),np.min(y),np.max(y)])
        #pl.axis([0.25,60.25,0.25,60.25])
        pl.savefig('./_plots_to_paper/co-interaction_'+str_frame+name+'.png')
        #pl.show()                            
        pl.close()
    if plot_slices:
        pl.figure(figsize=(8,3))
        pl.gcf().subplots_adjust(left=0.10)
        # plot reference
        pl.plot(x,p_ref[:,my/4.],'--b',linewidth=1)
        pl.plot(x,p_ref[:,3*my/4.],'--r',linewidth=1)
        # plot solution of interaction
        pl.plot(x,p[:,3*my/4.],'-r',linewidth=2)
        pl.plot(x,p[:,my/4.],'-b',linewidth=2)
        pl.title("t= "+str(sol.state.t),fontsize=20)
        pl.xlabel('x',fontsize=20)
        if title:
            pl.ylabel('Stress',fontsize=20)
        pl.xticks(size=20); pl.yticks(size=20)
        if slices_limits is not None:
            pl.axis([slices_limits[0]+xshift,slices_limits[1]+xshift,slices_limits[2],slices_limits[3]])
        pl.savefig('./_plots_to_paper/co-interaction_'+str_frame+name+'.eps')
        pl.close()
Exemplo n.º 22
0
 def plot_wave_function(self, maxel=None, **kwrds):
     '''
     The funciton plots the wave function
     
     In:
     maxel: maximum value
     **kwrds: keywords for the plot function
     
     Return:
     None
     '''
     envtb.ldos.plotter.Plotter().plot_density(
         np.abs(self.wf1d), self.coords, max_el=maxel, **kwrds)
     plt.axes().set_aspect('equal')
Exemplo n.º 23
0
def overlay():
    pl.figure()
    pl.clf()
    pl.axes([0.16,0.2,0.95-0.15,0.95-0.2])
    pl.plot(x,y4,'-b',label='$n1_{ana}$')
    pl.plot(x,y3,'r2',label='$n1_{sim}$',markersize=3)
    pl.xlabel(r'$y$ [nm]')
    pl.ylabel(r'$n$ [1/m$^2$] $\times 10^{17}$')
    ax = pl.gca()
    ax.yaxis.set_label_coords(xshift, 0.5)
    locs,labels = pl.yticks()
    pl.yticks(locs, map(lambda x: r"$ %.1f $" % x, locs*1e-17))
    # pl.text(-0.17, 0.9, r'$\times 10^{17}$', fontsize=10, transform = pl.gca().transAxes)
    # pl.legend()
    pl.savefig('images/overlay1.pdf',transparent='true')
Exemplo n.º 24
0
def error():
    pl.figure()
    pl.clf()
    error=(y4-y3)*100/(sum(y3)/len(x))
    pl.axes([0.16,0.2,0.95-0.15,0.95-0.2])
    pl.plot(x,error,'-r',label=r'Error')
    pl.xlabel(r'$y$ [nm]')
    pl.ylabel(r'relative error [\%]')
    ax = pl.gca()
    ax.yaxis.set_label_coords(xshift, 0.5)
    # locs,labels = pl.yticks()
    # pl.yticks(locs, map(lambda x: r"$ %.1f $" % x, locs*1))
    # pl.text(-0.19, 0.86, r'$\times 10^{-1}$', fontsize=10, transform = pl.gca().transAxes)
    # pl.legend()
    pl.savefig('images/error3.pdf',transparent='true')
Exemplo n.º 25
0
def plot_peak_isoerror(
    epsilon=[0.5, 0.2, 0.1, 0.05, 0.01, 0.001],
    wlim=(pi / 32, pi / 4),
    fmt="-",
    ax=None,
    legend=True,
    degrees=False,
    **kwargs
):
    """Plot iso-error (iso-epsilon) curves of feedback peak across cue size 
    
    Additional keyword arguments are passed to error.gamma().
    """
    epsilon = np.asarray(epsilon)
    if ax is None:
        f = plt.figure()
        ax = plt.axes()
    else:
        f = ax.get_figure()
    sigma = np.linspace(wlim[0], wlim[1], N)

    # Plot width curves
    conv = degrees and 180 / pi or 1.0
    for eps in epsilon:
        plt.plot(conv * sigma, gamma(sigma=sigma, epsilon=eps, **kwargs), fmt, label=r"$\epsilon=%.3f$" % eps)

    # Set axis attributes
    plt.title(r"$A/\sigma,\epsilon$")
    plt.xlabel(r"$\sigma$")
    plt.ylabel("A")
    plt.xlim(xmin=conv * wlim[0], xmax=conv * wlim[1])
    if legend:
        plt.legend()
    return f
Exemplo n.º 26
0
def validate(X_test, y_test, pipe, title, fileName):
    
    print('Test Accuracy: %.3f' % pipe.score(X_test, y_test))

    y_predict = pipe.predict(X_test)

    confusion_matrix = np.zeros((9,9))

    for p,r in zip(y_predict, y_test):
        confusion_matrix[p-1,r-1] = confusion_matrix[p-1,r-1] + 1

    print (confusion_matrix) 

    confusion_normalized = confusion_matrix.astype('float') / confusion_matrix.sum(axis=1)[:, np.newaxis]
    print (confusion_normalized)

    pylab.clf()
    pylab.matshow(confusion_normalized, fignum=False, cmap='Blues', vmin=0.0, vmax=1.0)
    ax = pylab.axes()
    ax.set_xticks(range(len(families)))
    ax.set_xticklabels(families,  fontsize=4)
    ax.xaxis.set_label_position('top') 
    ax.xaxis.set_ticks_position("top")
    ax.set_yticks(range(len(families)))
    ax.set_yticklabels(families, fontsize=4)
    pylab.title(title)
    pylab.colorbar()
    pylab.grid(False)
    pylab.grid(False)
    pylab.savefig(fileName, dpi=900)
Exemplo n.º 27
0
def plot_alpha_vs_peak(peaks=[0.1, 0.25, 0.5, 1, 2, 5], tlim=(-5, 5), ax=None, norm=True, legend=True, **kwargs):
    """Plot alpha (phase error) across time for different peak feedback gains
    
    Additional keyword arguments are passed to error.alpha().
    """
    peaks = np.asarray(peaks)
    if ax is None:
        f = plt.figure()
        ax = plt.axes()
    else:
        f = ax.get_figure()
    t = np.linspace(tlim[0], tlim[1], N)

    # Plot time curves
    for peak in peaks:
        err = alpha(t, A=peak, **kwargs)
        if norm:
            err /= err[0]
        plt.plot(t, err, "-", label="A = %.2f" % peak)

    # Set axis attributes
    plt.title(r"$\alpha(t)$")
    plt.xlabel("t (s)")
    plt.ylabel("error")
    plt.xlim(tlim)
    if legend:
        plt.legend()
    return f
Exemplo n.º 28
0
def plot_peak_isowidth(
    width=[pi / 32, pi / 16, pi / 8, pi / 4, pi / 2], elim=(0.001, 0.9), fmt="-", ax=None, legend=True, **kwargs
):
    """Plot iso-width (iso-sigma) curves of feedback peak across phase error
    
    Additional keyword arguments are passed to error.gamma().
    """
    width = np.asarray(width)
    if ax is None:
        f = plt.figure()
        ax = plt.axes()
    else:
        f = ax.get_figure()
    eps = np.linspace(elim[0], elim[1], N)

    # Plot width curves
    for sigma in width:
        plt.plot(eps, gamma(sigma=sigma, epsilon=eps, **kwargs), fmt, label=r"$\sigma=%.3f$" % sigma)

    # Set axis attributes
    plt.title(r"$A/\epsilon,\sigma$")
    plt.xlabel(r"$\epsilon$")
    plt.ylabel("A")
    plt.xlim(elim)
    if legend:
        plt.legend()
    return f
Exemplo n.º 29
0
def plot_alpha_vs_width(
    widths=[pi / 24, pi / 12, pi / 9, pi / 6, pi / 4, pi / 2], tlim=(-5, 5), ax=None, norm=True, legend=True, **kwargs
):
    """Plot alpha (phase error) across time for different cue sizes (widths)
    
    Additional keyword arguments are passed to error.alpha().
    """
    widths = np.asarray(widths)
    if ax is None:
        f = plt.figure()
        ax = plt.axes()
    else:
        f = ax.get_figure()
    t = np.linspace(tlim[0], tlim[1], N)

    # Plot time curves
    for width in widths:
        err = alpha(t, sigma=width, **kwargs)
        if norm:
            err /= err[0]
        plt.plot(t, err, "-", label=r"$\sigma = %.3f$" % width)

    # Set axis attributes
    plt.title(r"$\alpha(t)$")
    plt.xlabel("t (s)")
    plt.ylabel("error")
    plt.xlim(tlim)
    if legend:
        plt.legend()
    return f
Exemplo n.º 30
0
def plotWeightChanges():
    if f.usestdp:
        # create plot
        figh = figure(figsize=(1.2*8,1.2*6))
        figh.subplots_adjust(left=0.02) # Less space on left
        figh.subplots_adjust(right=0.98) # Less space on right
        figh.subplots_adjust(top=0.96) # Less space on bottom
        figh.subplots_adjust(bottom=0.02) # Less space on bottom
        figh.subplots_adjust(wspace=0) # More space between
        figh.subplots_adjust(hspace=0) # More space between
        h = axes()

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

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

        # plot
        imshow(wcmat,interpolation='nearest',cmap=bicolormap(gap=0,mingreen=0.2,redbluemix=0.1,epsilon=0.01))
        xlabel('post-synaptic cell id')
        ylabel('pre-synaptic cell id')
        h.set_xticks(f.popGidStart)
        h.set_yticks(f.popGidStart)
        h.set_xticklabels(f.popnames)
        h.set_yticklabels(f.popnames)
        h.xaxif.set_ticks_position('top')
        xlim(-0.5,ncells-0.5)
        ylim(ncells-0.5,-0.5)
        clim(-abs(wcmat).max(),abs(wcmat).max())
        colorbar()
Exemplo n.º 31
0
    def _plot_seasonality(self, alpha, plot_kwargs):
        #two_tailed_alpha = int(alpha / 2 * 100)
        periods = list(set([float(i.split("_")[1]) for i in self.seasonality]))

        additive_ts, multiplicative_ts = self._fit_seasonality()

        all_seasonalities = [('additive', additive_ts)]
        if len(self.multiplicative_data):
            all_seasonalities.append(('multiplicative', multiplicative_ts))
        for sn, ts in all_seasonalities:
            if (sn == 'multiplicative' and np.sum(ts) == 1) or (sn == 'additive' and np.sum(ts) == 0):
                continue
            ddf = pd.DataFrame(
                np.vstack([
                    np.percentile(ts[:, :, self.skip_first:], 50, axis=-1),
                    np.percentile(ts[:, :, self.skip_first:], alpha / 2 * 100, axis=-1),
                    np.percentile(ts[:, :, self.skip_first:], (1 - alpha / 2) * 100, axis=-1)
                ]).T,
                columns=["%s_%s" % (p, l) for l in ['mid', 'low', 'high'] for p in periods[::-1]]
            )
            ddf.loc[:, 'ds'] = self.data['ds']
            for period in periods:
                if int(period) == 0:
                    step = int(self.data['ds'].diff().mean().total_seconds() // float(period))
                else:
                    step = int(period)
                graph = ddf.head(step)
                if period == 7:
                    ddf.loc[:, 'dow'] = [i for i in ddf['ds'].dt.weekday]
                    graph = ddf[['dow', '%s_low' % period, '%s_mid' % period, '%s_high' % period]].groupby(
                        'dow').mean().sort_values('dow')
                    graph.loc[:, 'ds'] = [['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][i]
                                          for i in graph.index]
                    graph = graph.sort_index()
                plt.figure(**plot_kwargs)
                graph.plot(
                    y="%s_mid" % period,
                    x='ds',
                    color='C0',
                    legend=False,
                    ax=plt.gca()
                )
                plt.grid()

                if period == 7:
                    plt.xticks(range(7), graph['ds'].values)
                    plt.fill_between(
                        np.arange(0, 7),
                        graph["%s_low" % period].values.astype(float),
                        graph["%s_high" % period].values.astype(float),
                        alpha=.3,
                    )
                else:
                    plt.fill_between(
                        graph['ds'].values,
                        graph["%s_low" % period].values.astype(float),
                        graph["%s_high" % period].values.astype(float),
                        alpha=.3,
                    )

                plt.title("Model Seasonality (%s) for period: %s days" % (sn, period))
                plt.axes().xaxis.label.set_visible(False)
                plt.show()
Exemplo n.º 32
0
def correlator_online(fileinput='input.txt',dark_file='default',mask_file='default',plot='yes'):
   global datreg, nq, corf, n, sl, sr, nchannels, nchannels2, index_in_q, lind, dt, norm, srr, sll, nc, oneq, I_avg, I_avg2, lm1, lm2, lm1b, lm2b, ax1,ax1b, ax2, ax2b, ccd_img, ttdata,tcalc_cum, tplot_cum, tread_cum, tdrop_cum, tI_avg,q_2tcf, I_avgs, rch, rcr,totsaxs,input_info,l,y,v, sst, xnq, wtotmask

   time1=time.time()
   p.rc('image',origin = 'lower')
   p.rc('image',interpolation = 'nearest')
   
   print 'reading input...'
   input_info=get_input(fileinput)
##########################processing input file###############################
   dir= input_info['dir']
   dir_dark= input_info['dark dir']
   if dir_dark=='none':
      dir_dark=dir
   file_prefix=input_info['file_prefix']
   ext = input_info['file_suffix']
#####New version has capabilities of reading also .gz files####
   if ext == '.edf.gz':
     dataread=EdfFile.EdfGzipFile
   else:
     dataread=EdfFile.EdfFile
##################################################
   firstfile=int(input_info['n_first_image'])
   lastfile=int(input_info['n_last_image'])+1
   firstdark=input_info['n_first_dark']
   if firstdark.lower() != 'none':
      firstdark=int(input_info['n_first_dark'])
      lastdark=int(input_info['n_last_dark'])+1
   geometry=input_info['geometry'].lower()
   tolerance=float32(float(input_info['tolerance']))
   avgt = input_info['lag time'].lower()
   dt=find_lagt(avgt,input_info,dataread)
   print 'lag time =', dt 
   q_2tcf=(input_info['q for TRC']).lower()
   if q_2tcf!='none':
      q_2tcf=int(q_2tcf)
   
   out_dir=get_dir(input_info['output directory'])
   out_prefix=get_prefix(input_info['output filename prefix'])
   out_tot=out_dir+out_prefix
   print '...done'
##################end processing input file###################################  
   firstname=dir+file_name(file_prefix,ext,firstfile)
   f=dataread(firstname)
   ccd_info=f.GetStaticHeader(0)
   ncol=int(ccd_info['Dim_1'])
   nrows=int(ccd_info['Dim_2'])
   
   static=out_tot+'static.edf'
   static_data=asfarray(loadedf(static),dtype=float32)
   if input_info['n_first_dark'].lower()=='none':
      print 'not using darks'
      tot_darks=0*static_data
   else:
      print 'using darks'
      if dark_file=='default': 
         dark_file=out_tot+'dark.edf'
      print 'using dark file:', dark_file
      tot_darks=asfarray(loadedf(dark_file),dtype=float32)
   toplot=static_data+.001 #to avoid zeros in plotting logarithm###
   print '...done'
   print '...reading mask'
   if mask_file=='default':
      mask_file=out_tot+'mask.edf'
   print 'using mask file:', mask_file
   totmask=loadedf(mask_file,0)+loadedf(mask_file,1)
   wtotmask=where(totmask==0)
   p.ion()
   fileq=out_tot+'qmask.edf'
   q=loadedf(fileq)
   maxval=int(amax(q)+2)
   detector=input_info['detector']
   flatfield_file=input_info['flatfield file']
   if detector=='medipix':
      flat_field=flatfield(detector,flatfield_file)
   else:
      flat_field=1.0
   print '...done'
   if geometry=='saxs':
      print '...correcting static for baseline'
      xbeam=int(input_info['x direct beam'])
      ybeam=int(input_info['y direct beam'])
      static_data=rad_average(static_data,totmask,xbeam,ybeam)

   qaxis_list=[]
   npix_per_q=[]
   oneq=[]
   index_in_q=[]
   firstq=float32(float(input_info['first q']))
   deltaq=float32(float(input_info['delta q']))
   stepq=float32(float(input_info['step q']))
   qvalue=firstq+deltaq/2
   static_corrected=ones(shape(static_data),dtype=float32)
   q*=abs(totmask-1)
   for i in range(2,maxval,2):
      indices=where(q==i)
      index_in_q.append(indices)#gives the indices of pixels that are not masked at this q
      if geometry=='saxs':
         static_corrected[indices]=mean(static_data[indices])/static_data[indices]
      npixel=len(static_data[indices])
      npix_per_q.append(npixel)
      oneq.append(ones((1,npixel)))
      qaxis_list.append(qvalue)
      qvalue+=deltaq+stepq
   print '...done'
   nq=len(npix_per_q)
   xnq=xrange(nq)
   tmpdat=loadtxt(out_tot+'1Dstatic.dat')
   qaxis=tmpdat[:,0]
   I_q=tmpdat[:,1]
   del tmpdat



   ##FINISHED INITIALIZING PART OF THE CODE######
   ##START MAIN PART FOR CORRELATION#####
   nchannels=16.
   nchannels2=nchannels/2
   nfile=lastfile-firstfile
   datregt=[]
   datreg=[]
   rch=int(ceil(log(nfile/nchannels)/log(2))+1)
   ###2time
   if q_2tcf!='none':
         ttdata=zeros((nfile,npix_per_q[q_2tcf-1]),dtype=float32)
   ###2time
   for ir in xrange(rch):
       for iq in xnq:
           datregt.append(zeros((npix_per_q[iq],nchannels),dtype=float32))
       datreg.append(datregt)
       datregt=[]
   del datregt
   rcr=nchannels+nchannels2*ceil(log(nfile/nchannels)/log(2))
   corf=zeros((nq,rcr),dtype=float32)
   lag=zeros((1,rcr),dtype=float32)
   data_shape=p.shape(toplot)
   smatr=zeros(data_shape,dtype=float32)
   matr=zeros(data_shape,dtype=float32)
   sl=zeros((nq,rcr),dtype=float32)
   sr=zeros((nq,rcr),dtype=float32)
   norm=zeros((1,rcr),dtype=float32)
   sll=[]
   srr=[]
   sst=[]

   for ir in xrange(rch):
       if ir==0:
           lag[0,:nchannels]=dt*arange(1,nchannels+1,1)
           norm[0,:nchannels]=1./arange(nfile-2,nfile-nchannels-2,-1)
       else:
           lag[0,nchannels2*(ir+1):nchannels2*(ir+2)]=(dt*2**ir)*arange(1+nchannels2,nchannels+1)
           norm[0,nchannels2*(ir+1):nchannels2*(ir+2)]=1./arange((nfile-1)/(2**ir)-nchannels2-1,(nfile-1)/(2**ir)-nchannels-1,-1)
       sll.append(zeros((nq,nchannels),dtype=float32))
       srr.append(zeros((nq,nchannels),dtype=float32))
       sst.append(arange(nq)*0.0)

   #END of declaring and initializing variables####
   #READING FILES 
   filenames=[]
   for k in xrange(firstfile,lastfile):
       filenames.append(file_name(file_prefix,ext,k))
   n=0
   lind=npix_per_q
   if plot!='no':
      ax1=p.axes([0.11, 0.08, 0.75, 0.57])
      ax1.set_xlabel('t [sec]')
      ax1.set_ylabel('g^2(q,t)')
      ax1b=p.twinx(ax1)
      ax1b.yaxis.tick_right()
      ax2=p.axes([0.11, 0.73, 0.75, 0.19])
      ax2.xaxis.tick_bottom()
      ax2.set_xlabel('t [sec]')
      ax2.set_ylabel('I(q,t) [a.u.]')

      ax2b=p.gcf().add_axes(ax2.get_position(),frameon=False)
      ax2b.xaxis.tick_top()
      ax2b.yaxis.tick_right()
      ax2b.xaxis.set_label_position('top')
      ax2b.set_xlabel('Image no.')
      label1='q= %2.1e 1/Ang' % qaxis_list[0]
      label2='q= %2.1e 1/Ang' % qaxis_list[nq/2]
      lm1,=ax1.semilogx((1,),(1,),'ro-',label=label1)
      lm1b,=ax1b.semilogx((1,),(1,),'bo-',label=label2)
      ax1.legend(loc='lower left')
      ax1b.legend(loc=(0.02,0.1))
      lm2,=ax2.plot((1,),(1,),'r-')
      lm2b,=ax2b.plot((1,),(1,),'b-')
      p.setp(ax1.get_yticklabels(), color='r')
      p.setp(ax1b.get_yticklabels(), color='b')
      p.setp(ax2.get_yticklabels(), color='r')
      p.setp(ax2b.get_yticklabels(), color='b')
   tplot_cum=0
   tread_cum=0
   tdrop_cum=0
   tcalc_cum=0
   I_avg=zeros((1,nfile),float32)
   I_avg2=zeros((1,nfile),float32)
   I_avgs=zeros((nq,nfile),float32)
   tI_avg=zeros((1,nfile),float32)
   mon=zeros((1,nfile),int)
   totsaxs=0*static_data
   
   detector=input_info['detector'].lower()
   Mythread=Thread
   #Mythread=Process
   checkfile=os.path.exists
   n=0
   firstdata=dir+filenames[n]
   f=dataread(firstdata)
   dread(f,n,tot_darks,flat_field,static_corrected)
   goodsize=os.path.getsize(dir+filenames[n])
   nnfile=nfile-1
   stop=0
   if input_info['normalize'].lower()!= 'none':
      print "normalizing to ", input_info['normalize']
   else:
      print "not normalizing"
   while n<nnfile:
       #nc=n+1.
       nc=n+1 
       ccd_imgn=ccd_img
       file=filenames[n+1]
       tempfile=dir+file
       wait=0
       t0=time.time()
       while checkfile(tempfile) is False:
          p.draw()
          sys.stdout.write(50*'\x08')
          sys.stdout.write('waiting for file'+ file+'...')
          sys.stdout.flush()
          t1=time.time()
          wait+=t1-t0
          time.sleep(1)
          t0=t1
          if wait>10*dt:
            print nfile 
            ans=raw_input('\n will this file ever arrive? (y/N)')
            if ans.lower()=='y':
               print '\n keep waiting...\n'
               time.sleep(3*dt)
               wait=0
            else:
               stop=1
               nfile=n+1 
               break
       if stop==1:
         break
       if ext=='.edf': #cannot do the check for gz files as their size are not to be equal.
          filesize=os.path.getsize(tempfile)
          while filesize!=goodsize:
             sys.stdout.write(50*'\x08')
             sys.stdout.write('file '+ file+'still not ready...')
             sys.stdout.flush()
             time.sleep(2)
             filesize=os.path.getsize(tempfile)
       tmf=dataread(tempfile)
       thrd=Mythread(target=dread,args=([tmf,n+1,tot_darks,flat_field,static_corrected]))
       thcor=Mythread(target=correlator,args=([0,ccd_imgn]))
       mon[0,n]= monitor
    #for plot. TO be faster, I only updated plot each nchannels files.
       if nc%nchannels==0:
          pct=float32(n)/float32(nfile)*100
          sys.stdout.write(50*'\x08')
          sys.stdout.write('read '+str(int(pct))+'% of files'+32*' ')
          sys.stdout.flush()
          if plot!='no':
            ttplot(corf,sr,sl,norm,n+1, I_avg[0,:n+1], I_avg2[0,:n+1],lag) 
            #thplot.join()
            #thplot=Mythread(target=ttplot,args=([corf,sr,sl,norm,n+1, I_avg[0,:n+1], I_avg2[0,:n+1]]))
            #thplot.start()
       thrd.start()
       thcor.start()
       thrd.join()
       thcor.join() 
       n+=1   
   #END OF MAIN LOOP
   #calculate 2 times correlation function
   sys.stdout.write(50*'\x08')
   sys.stdout.flush()
   print "read 100% of files"
   #calculate correlation functions
   if stop==1:
     print nfile, shape(I_avgs)
     tI_avg=tI_avg[:,:nfile] 
     mon=mon[:,:nfile]
     I_avgs=I_avgs[:,:nfile]
     rch=int(ceil(log(nfile/nchannels)/log(2))+1)
     for ir in xrange(rch):
       if ir==0:
         norm[0,:nchannels]=1./arange(nfile-2,nfile-nchannels-2,-1)
       else:
         norm[0,nchannels2*(ir+1):nchannels2*(ir+2)]=1./arange((nfile-1)/(2**ir)-nchannels2-1,(nfile-1)/(2**ir)-nchannels-1,-1)
   indt=int(nchannels+nchannels2*log(nfile/nchannels)/log(2))-2
   cc=zeros((indt,nq+1),float32)
   q_title='#q values:'
   trace_title='#file_no. ,   time, monitor,  q values:'
   for cindex in xnq:
       q_title=q_title+' '+str(qaxis_list[cindex])
       trace_title=trace_title+' '+str(qaxis_list[cindex])
       cc[:,cindex+1]=corf[cindex,:indt]/(sl[cindex,:indt]*sr[cindex,:indt])/\
       norm[0,:indt]
   cc[:,0]=lag[0,:indt]
   q_title=q_title+'\n'
   trace_title=trace_title+'\n'
   del indt
   f=open(out_tot+'cf.dat','w')
   f.write(q_title)
   savetxt(f, cc)
   f.close()
   del cc
   f=open(out_tot+'trace.dat','w')
   f.write(trace_title)
   traces=zeros((nfile,nq+3),float32)
   traces[:,0]=tI_avg/dt+firstfile
   traces[:,1]=tI_avg
   traces[:,2]=mon
   traces[:,3:]=transpose(I_avgs[:,:])
   savetxt(f,traces)
   f.close()
   del traces 
   static=out_tot+'static.edf'
   totsaxs=totsaxs/nfile-tot_darks
   totsaxs[totsaxs<=0]=0
   saveedf(static,totsaxs)
   del static
   del totsaxs
   del tot_darks 
   print 'correlation functions are saved to ', out_tot+'cf.dat'
   print 'traces are saved to ', out_tot+'trace.dat'
   if input_info['normalize'].lower()!= 'none':
      print "data normalized to ", input_info['normalize']
   else:
      print "data not normalized"
   if input_info['dropletize'].lower()=='yes':
      print   "data dropletized: !!!!CAUTION this is valid only for andor 13 micron and dark subtracted images (adu per photon = 1930 +/- 100, zero photon = 0 +/- 200)"
   #if plot!='no':
   #   p.hold(True)
   #   raw_input('Press enter to close window')
   #   p.close()
   p.hold(True)
   p.close()

   if q_2tcf!='none':
      print "calculating time resolved cf and chi4..."
      if nfile>6000:  #this is for 4 GB RAM PC
         nfile=6000
         n=6000
   if q_2tcf!='none':
      lind2=npix_per_q[q_2tcf-1]/16
      l=arange(5)*0
      y=[]
      v=[]
      for i in range(5):
         y.append([])
         v.append([])
      ib=0
      for i in xrange(16):
         sys.stdout.write(50*'\x08')
         sys.stdout.write('done '+str(int(i/16.*100))+'% of data'+32*' ')
         sys.stdout.flush()
         ie=ib+lind2
         y[0].append(trc(ttdata[:n-1,ib:ie]))
         v[0].append(vartrc(y[0][-1]))
         if l[0]==1:
            recurf(0)
         else:
            l[0]+=1
         ib+=lind2
      vm=[]
      for i in range(4,-1,-1):
         vm.append(mean(v[i],0))
      vm=array(vm)
      del ttdata
      del v
      sys.stdout.write(50*'\x08')
      sys.stdout.flush()
      file_2times=out_tot+'2times_q_'+str(q_2tcf)+'.edf'
      ytrc.write(file_2times,y[4][0])
      print 'Time resolved CF is saved to '+ out_tot+'2times_q_'+str(q_2tcf)+'.edf'
      N=array([[1],[2],[4],[8],[16]])/float(npix_per_q[q_2tcf-1])
      data=concatenate((N,vm),1).T
      #print 'number of pixels ',lind[ttcf_par] 
      #print 'q value=', qv[ttcf_par]
      p0=[0.0,1.0]
      it=range(len(data[1:,0]))
      p1=zeros((len(data[1:,0]),len(p0)+1))
      p1[:,0]=(asfarray(it)+1.0)*dt 
      xdata=data[0,:]
      for i in it:
         ydata=data[i+1,:]
         p1[i,1:],success=leastsq(errfunc,p0,args=(xdata,ydata))
      outfile=out_tot+'fitchi4_q_'+str(q_2tcf)+'.dat'
      f=open(outfile,'w')
      f.write("#time chi4 error q value:"+str(qaxis_list[q_2tcf-1])+"\n")
      savetxt(f,p1)
      f.close()
      print 'file is saved to '+outfile
   print "saving results..."
   time2=time.time()
   print 'elapsed time', time2-time1
   if plot!='no':
      print 'elapsed time for plotting', tplot_cum
   print 'elapsed time for reading', tread_cum-tdrop_cum
   if input_info['dropletize'].lower()=='yes':
      print 'elapsed time for dropletizing', tdrop_cum
   print 'elapsed time for correlating', tcalc_cum
   print 'calculations have finished:)'
Exemplo n.º 33
0
# Use the outermost moon to calculate the length of one full orbit duration
orbit_duration = math.sqrt(
    (4 * math.pi**2 * thirdmoon.px**3) / (G * (thirdmoon.mass + planet.mass)))
orbit_duration = orbit_duration * 1.005

# Run simulation. Make sure to add/remove the moons you want to simulate!
ttv_array, tdv_array = run_sim(R_star, transit_duration,
                               [planet, firstmoon, secondmoon, thirdmoon])

# Output information
print 'TTV amplitude =', numpy.amax(ttv_array), \
    '[min] = ', numpy.amax(ttv_array) * 60, '[sec]'
print 'TDV amplitude =', numpy.amax(tdv_array), \
    '[min] = ', numpy.amax(tdv_array) * 60, '[sec]'

ax = plt.axes()
plt.plot(ttv_array, tdv_array, color='k')
plt.rc('font', **{'family': 'serif', 'serif': ['Computer Modern']})
plt.rc('text', usetex=True)
plt.tick_params(axis='both', which='major', labelsize=16)
plt.xlabel('transit timing variation [minutes]', fontsize=16)
plt.ylabel('transit duration variation [minutes]', fontsize=16)
ax.tick_params(direction='out')
plt.ylim([numpy.amin(tdv_array) * 1.2, numpy.amax(tdv_array) * 1.2])
plt.xlim([numpy.amin(ttv_array) * 1.2, numpy.amax(ttv_array) * 1.2])
plt.plot((0, 0), (numpy.amax(tdv_array) * 10., numpy.amin(tdv_array) * 10.),
         'k',
         linewidth=0.5)
plt.plot((numpy.amin(ttv_array) * 10., numpy.amax(ttv_array) * 10.), (0, 0),
         'k',
         linewidth=0.5)
Exemplo n.º 34
0
    if opts.show:
        pylab.show()
    else:
        pylab.close()

##Plotting waterfall
if opts.verb: print 'Plotting occupancy waterfall'
#Set-up plot format
left, width = 0.1, 0.65
bottom, height = 0.1, 0.65
bottom_h = left_h = left + width + 0.02
rect_imshow = [left, bottom, width, height]
rect_histx = [left, bottom_h, width, 0.2]
rect_histy = [left_h, bottom, 0.2, height]
pylab.figure(1, figsize=(8, 8))
axImshow = pylab.axes(rect_imshow)
axHistx = pylab.axes(rect_histx)
axHisty = pylab.axes(rect_histy)
axHistx.xaxis.set_major_formatter(nullfmt)
axHisty.yaxis.set_major_formatter(nullfmt)

#actuallly interact with data
axImshow.imshow(flg_arr,
                aspect='auto',
                interpolation='nearest',
                cmap='binary',
                extent=[100., 200., t_arr[len(t_arr) - 1], t_arr[0]])
axHistx.plot(fqs, pcnt_f)
axHistx.fill_between(fqs, 0, pcnt_f, color='blue', alpha=0.3)
axHisty.plot(pcnt_t, tms, 'b-')
Exemplo n.º 35
0
#!/usr/bin/env python
import matplotlib
matplotlib.rcParams.update({'font.size': 22})

nprocs = [1, 2, 4, 8, 16, 32]

#  exLaplace3d 512 20
times = [2 * 60 + 21.4, 60 + 23.4, 48.4, 29.6, 19.7, 15.1]

speedup = [times[0] / t for t in times]

from matplotlib import pylab
pylab.plot(nprocs, speedup, 'ko', nprocs, speedup, 'b-', [1, 10], [1, 10],
           'c--')
pylab.title('Pan Ivy Bridge exLaplace3d 512 20')
pylab.xlabel('number of MPI processes')
pylab.ylabel('speedup')
pylab.axes([1, 32, 1, 10])

pylab.show()
Exemplo n.º 36
0
lon = nc.variables['lon'][:]
lat = nc.variables['lat'][:]
nc.close()

cmap = plt.cm.Spectral_r

cmaplist = [cmap(i) for i in range(cmap.N)]

cmap = mpl.colors.LinearSegmentedColormap.from_list('Custom cmap', cmaplist,
                                                    cmap.N)
# define the bins and normalize
bounds = np.linspace(0, 42, 7)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

projection = ccrs.PlateCarree(central_longitude=180)
ax = plt.axes(projection=projection)
ax.set_global()
ax.coastlines(resolution='50m', lw=0.5, zorder=4)
gl = ax.gridlines(draw_labels=True,
                  linestyle='--',
                  xlocs=[-120, -60, 0, 60, 120, 180, 240],
                  zorder=6)
gl.xlabels_top = gl.ylabels_right = False
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
# ax.add_feature(cartopy.feature.LAND, facecolor='0.5', zorder=3)

ax.add_feature(cfeature.NaturalEarthFeature(
    'physical',
    'land',
    '50m',
Exemplo n.º 37
0
    p = sns.lineplot(x=data.index, y=data, color='b')
    p.tick_params(labelsize=10, rotation=45)
    plt.setp(p.lines, linewidth=2)

ani = animation.FuncAnimation(fig, animate, frames=45, repeat=True)
ani.save('load.mp4', writer=writer)

# alternative animation
series_ani = joined
series_ani_onemon = series_ani['2010-01']
series_ani_onemon = pd.concat([pd.Series(series_ani_onemon.values),
                               pd.Series(range(series_ani_onemon.shape[0]))],
                              axis=1)

fig = plt.figure(figsize=(16, 10))
ax = plt.axes(xlim=(0, 47), ylim=(6.5, 14.5))
ax.set_xlabel('Hour', fontsize=20)
ax.set_ylabel('GW', fontsize=20)
ax.tick_params(labelsize=15)
line, = ax.plot([], [], lw=2)

def init():
    line.set_data([], [])
    return line,

# x_data, y_data = [], []

def animate(i):  # called sequentially, staring with 0
    idx_start = int(i) + 48
    x = list(range(0, 48))
    y = list(series_ani_onemon.iloc[:, 0][(idx_start-48):idx_start].values)
Exemplo n.º 38
0
plt.plot(idc2010_hi_x,
         idc2010_hi_y,
         linewidth=2,
         label='IDC2010-HI High Noise Model')
plt.plot(idc2010_li_x,
         idc2010_li_y,
         linewidth=2,
         label='IDC2010-LI Low Noise Model')
plt.xlim(0.01, 50)  # Hz
plt.xscale('log')
title = 'AM.BKSVL.01.BDF'
subtitle = 'Microbarometer Power Spectral Density. 24 hours @ %.1f SPS. AD7746 CAPCHOP=0.' % (
    fs)
titlestr = r'\begin{center}{\textbf{%s\\}}%s\end{center}' % (title, subtitle)
plt.title(titlestr)
plt.xlabel('Frequency (Hz)')
plt.ylabel('dB Pa\u00b2/Hz')
plt.axes().xaxis.grid(True, which='both')
plt.axes().yaxis.grid(True)
plt.legend()
at = AnchoredText(
    'RMS noise @ 1 Hz: %.2f \u00b5Pa\u00b2/Hz (%.1f dB Pa\u00b2/Hz)\n' \
    'Bandlimited RMS noise 0.5 - 2 Hz: %.1f milliPascal\n' \
    'Bandlimited RMS noise 0.1 - 50 Hz: %.1f milliPascal' \
        % (noise_1hz*1e6, noise_1hz_db, noise_nb*1e3, noise_wb*1e3),
    frameon=True, loc='lower left')
at.patch.set_ec('lightgrey')
at.patch.set_alpha(0.75)
plt.gca().add_artist(at)
plt.show()
Exemplo n.º 39
0
        ax2.text(pos[tick], medians[tick] + 0.1, median_labels[tick], 
                horizontalalignment='center', size='medium', color = color[i], weight='semibold')
        i+=1
    x1, x2, x3 = 0, 1, 2
    ax2.text(x1, matrix_box.min().min().round()-0.5 , "1971-2000", ha='center', va='bottom', size='medium', color='black', weight='semibold')   
    ax2.text((x2+x3)*.5, matrix_box.min().median()-0.5 , "2071-2100", ha='center', va='bottom', size='medium', color='black', weight='semibold')
    ax2.set(xlabel='')
    
    plt.yticks( fontsize=14)
        
    plt.savefig('K:/PROJETS/PROJET_CLIMHUNOR/figures/Mean_tasmax/VI_MONTH_'+m+'_Mean_tasmax.png', bbox_inches='tight', format='png', dpi=1000)
    plt.show()  
    plt.close()

fig = plt.figure(figsize=(28,16))   
ax = plt.axes(projection=ccrs.PlateCarree())
ax.set_extent([-72,-64,47,51])


ax.add_feature(cfeature.OCEAN.with_scale('50m'))      # couche ocean
ax.add_feature(cfeature.LAND.with_scale('50m'))       # couche land
ax.add_feature(cfeature.LAKES.with_scale('50m'))      # couche lac

ax.add_feature(cfeature.BORDERS.with_scale('50m'))    # couche frontieres
ax.add_feature(cfeature.RIVERS.with_scale('50m'))     # couche rivières      
coast = cfeature.NaturalEarthFeature(category='physical', scale='10m',     # ajout de la couche cotière 
                    facecolor='none', name='coastline')
ax.add_feature(coast, edgecolor='black')
states_provinces = cfeature.NaturalEarthFeature(
    category='cultural',
    name='admin_1_states_provinces_lines',
Exemplo n.º 40
0
    def forceChain(self,
                   axis=(0, 2),
                   alpha=numpy.pi / 4,
                   plot_stress=True,
                   plot_parts=False,
                   peters=True,
                   threshold=1):
        """ Computes the force chain based on an algorithm published in Phys. Rev. E. 72, 041307 (2005):
		'Characterization of force chains in granular material'.

		@ axis: a tuple of size 2 that specifies the two axis to use for computing the force chain, e.g. axis=(0,1) -> (x,y)
		@ alpha: the angle (in radians) that controls the deviation of the force chain. A value of 0 means a perfectly linear chain.
		Thus, alpha is a measure of the 'curvature' of the force chain. See page 5 of the paper cited above.
		"""

        stress = numpy.zeros((self._Particles.natoms, 2, 2))
        stress_prin = numpy.zeros((self._Particles.natoms,
                                   3))  # 2 stress components + angle = 4 dims

        coords = numpy.array(
            [self._Particles.x, self._Particles.y, self._Particles.z])
        x, y = coords[axis[0]], coords[axis[1]]

        # Compute net stresses on all particles
        for contact in self._overlaps:

            i, j = int(contact[1]), int(contact[2])
            overlap = self._Particles.radius[i] + self._Particles.radius[
                j] + numpy.array([x[i] - x[j], y[i] - y[j]])

            vi = 4.0 / 3.0 * numpy.pi * self._Particles.radius[i]**3.0
            vj = 4.0 / 3.0 * numpy.pi * self._Particles.radius[j]**3.0

            stress_i = numpy.outer(
                self._model.normalForce(overlap, self._Particles.radius[i]),
                overlap) / vi
            stress_j = numpy.outer(
                self._model.normalForce(overlap, self._Particles.radius[j]),
                overlap) / vj

            stress[i] += stress_i
            stress[j] += stress_j

        # Faster to loop over all particles
        for i in range(self._Particles.natoms):

            # Compute principal stress
            stress_i = stress[i]

            stress_p = 0.5 * (stress_i[0, 0] + stress_i[1, 1]) + numpy.sqrt( (0.5 * (stress_i[0, 0] - \
             stress_i[1, 1]))**2.0 + stress_i[0, 1] )

            if stress_i[0, 0] - stress_i[
                    1, 1]:  # otherwise this is prolly a boundary particle

                # Compute angle
                stress_prin[i,2] = 0.5 * numpy.arctan( 2.0 * stress_i[0,1] / (stress_i[0,0] \
                      - stress_i[1,1]) )

                # compute principal stress
                stress_prin[i, 0] = stress_p * numpy.cos(stress_prin[i, 2])
                stress_prin[i, 1] = stress_p * numpy.sin(stress_prin[i, 2])

        stress_norm = norm(stress_prin[:, :-1], axis=1)

        if not peters:  # plot all particle stresses

            indices = numpy.where(stress_norm > 0)[0]
            Particles = self._Particles[indices]

            coords = numpy.array([Particles.x, Particles.y, Particles.z])
            x, y = coords[axis[0]], coords[axis[1]]

            stress_prin = stress_prin[indices, :]
            stress_norm = stress_norm[indices]

            stress_norm /= stress_norm.max() * 0.3

            plt.axes()

            for i in range(coords.shape[1]):
                theta = stress_prin[i, -1]
                xi = [
                    x[i] - Particles.radius[i] * numpy.cos(theta),
                    x[i] + Particles.radius[i] * numpy.cos(theta)
                ]
                yi = [
                    y[i] - Particles.radius[i] * numpy.sin(theta),
                    y[i] + Particles.radius[i] * numpy.sin(theta)
                ]

                if plot_stress:
                    plt.plot(xi, yi, linewidth=stress_norm[i], color='black')

                if plot_parts:
                    circle = plt.Circle((x[i], y[i]),
                                        radius=Particles.radius[i],
                                        fill=False,
                                        color='blue',
                                        linewidth=0.5,
                                        linestyle='dotted')
                    plt.gca().add_patch(circle)

                    circle = plt.Circle((x[i], y[i]),
                                        radius=Particles.radius[i],
                                        fill=False,
                                        color='blue',
                                        linewidth=0.5,
                                        linestyle='dotted')
                    plt.gca().add_patch(circle)

            plt.axis('scaled')
            plt.show()

            return stress_prin

        else:  # use Peters' algorithm for computing force chain propagation
            # Section V. THE ALGORITHM (page 4)
            # Step 1: filter out particles with less than the mean principal stress
            indices = numpy.where(
                stress_norm >= threshold * stress_norm.mean(axis=0))[0]

            stress_norm = stress_norm[indices]

            # Step 2: filter out particles which are in contact with 1 or less 'highly stressed' particles
            # Construct an nns list
            coords = self._coords[indices, :][:, axis]
            stress_prin = stress_prin[indices, :]
            radii = self._Particles.radius[indices]

            tree = spatial.cKDTree(coords)

            nns = tree.query_ball_point(
                coords, self._Particles[indices].radius.max() * 2.0)
            self._nns = [[] for i in range(len(nns))]

            # Update the nns indices so that only overlapping neighbors remain
            count = 0

            for ns in nns:
                for index in ns:
                    if index != count:

                        dist = norm(coords[index] - coords[count])

                        if dist <= (radii[index] + radii[count]):
                            self._nns[count].append(index)

                self._nns[count].insert(0, count)
                count += 1

            cosAlpha = numpy.cos(alpha)
            chain = []

            # Step 3: Remove overlapping particles with 2 or less neighbors
            remInd = []
            for nns in self._nns:
                if len(
                        nns
                ) <= 2:  # select only particles surrounded by 2 or more highly stressed particles
                    remInd.append(nns)

            for ind in remInd:
                self._nns.remove(ind)

            # Step 4: compute the force chain per particle and make plots if requested by the user
            plt.axes()

            for nns in self._nns:

                index = nns[0]
                # Begin loop over each neighboring particle
                for ni in nns[1:]:

                    # check for angle compliance
                    angle_i = stress_prin[index, -1]
                    angle_j = stress_prin[ni, -1]

                    dist = coords[ni] - coords[index]

                    term1 = numpy.fabs(numpy.dot(dist,
                                                 stress_prin[index, :-1]))
                    term2 = norm(dist) * stress_norm[index]

                    term3 = numpy.fabs(numpy.dot(-dist, stress_prin[ni, :-1]))
                    term4 = norm(-dist) * stress_norm[ni]

                    # Search in the forward direction
                    if (term1 <= term2) and (cosAlpha * term2) < term1:
                        if (term3 <= term4) and (cosAlpha * term4) < term3:
                            chain.append((index, ni))

                            x = [coords[index, 0], coords[ni, 0]]
                            y = [coords[index, 1], coords[ni, 1]]

                            if plot_stress:
                                plt.plot(x,
                                         y,
                                         linewidth=max(
                                             1.2 * stress_norm[i] /
                                             stress_norm.max(), 0.01),
                                         color='black')

                            if plot_parts:
                                circle = plt.Circle(
                                    (coords[index, 0], coords[index, 1]),
                                    radius=radii[index],
                                    fill=False,
                                    color='blue',
                                    linewidth=0.5,
                                    linestyle='dotted')
                                plt.gca().add_patch(circle)

                                circle = plt.Circle(
                                    (coords[ni, 0], coords[ni, 1]),
                                    radius=radii[ni],
                                    fill=False,
                                    color='blue',
                                    linewidth=0.5,
                                    linestyle='dotted')
                                plt.gca().add_patch(circle)

                    # Search in the reverse direction
                    # I dont understand what Im doing here
                    #if (term1 <= term2) and (-cosAlpha * term2) > term1: # TODO: double check the math on this one
                    #if (term3 <= term4) and (-cosAlpha * term4) > term3: # TODO: double check the math on this one
                    #chain.append((index,ni))
                    #print (index,ni)

            print('Natoms highly stressed = {} out of {} particles'.format(
                len(chain), self._Particles.natoms))

            plt.axis('scaled')
            plt.show()

            return chain, stress_prin
Exemplo n.º 41
0

print "integral"
print f(2, 2, 2)

na = np.ogrid[0:1:24j]
nb = np.ogrid[0:1:12j]
nc = np.ogrid[0:1:6j]
# 24 12 6
na3 = na.reshape((24, 1, 1))
nb3 = nb.reshape((1, 12, 1))
nc3 = nc.reshape((1, 1, 6))
print f(na3, nb3, nc3).mean()  # 0.1931 ...

print str(na3.ravel().data)
'''
from matplotlib import pyplot as plt
data = np.loadtxt('/Users/ahnyoungho/GitHub/scipy-lecture-notes/data/populations.txt')
print data.T
year, hares, lynxes, carrots = data.T

plt.axes([0.2, 0.1, 0.5, 0.8])
plt.plot(year, hares, year, lynxes, year, carrots)
plt.legend(('Hare', 'Lynx', 'Carrot'), loc=(1.05, 0.5))
#plt.show()

print data
sub_pop = data[:,1:] # without year
print sub_pop.mean(axis=0)
print np.argmax(sub_pop, axis=1)
print np.argmin(sub_pop, axis=1)
Exemplo n.º 42
0
# -*- coding: utf-8 -*-
"""
Created on Sat Feb  9 14:44:27 2019

@author: adrie
"""

import matplotlib.pylab as plt
from matplotlib.animation import FuncAnimation


fig = plt.figure(facecolor = 'k')
ax = plt.axes(facecolor = 'k')


def DistanceEuclidienne(A,B):
	xa,ya = A
	xb,yb = B
	return (((xa - xb)**2) + ((ya - yb)**2))**0.5


def FindC(A,B):
	xa,ya = A
	xb,yb = B
	xc = xa + (xb - xa)/2 - (yb - ya)/2
	yc = ya + (xb - xa)/2 + (yb - ya)/2
	return xc,yc


def Plotable(l):
	lx,ly = [],[]
Exemplo n.º 43
0
    yData = delete(yData, Indx, 0)

    thisline.set_data(xData, yData)
    pylab.draw()

    if thisline == MaximaGraph:
        MaxMask = delete(MaxMask, Indx, 0)

    if thisline == MinimaGraph:
        MinMask = delete(MinMask, Indx, 0)


cid = Fig.canvas.mpl_connect('pick_event', on_pick)

axcolor = 'lightgoldenrodyellow'
resetax = pylab.axes([0.85, 0.10, 0.1, 0.04])
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')


def reset(event):
    global MaxMask
    global MinMask

    MaxMask = arange(len(MaximaData))
    MinMask = arange(len(MinimaData))

    MaximaGraph.set_data(MaximaIndx, MaximaData)
    MinimaGraph.set_data(MinimaIndx, MinimaData)


button.on_clicked(reset)
Exemplo n.º 44
0
dmin = 0.5 * 10**(-1)
dmax = 2 * 10**4

# Customisation
plt.rc('path', simplify=True)
plt.rc('savefig', dpi=300, format='png')
plt.rc('axes', linewidth=lw, labelpad=lblpad)
plt.rc('xtick', labelsize=tick, direction='inout')
plt.rc('xtick.major', size=tickh, width=lw, pad=pad)
plt.rc('ytick', labelsize=tick, direction='inout')
plt.rc('ytick.major', size=tickh, width=lw, pad=pad)

# Set up the plot
plt.figure(figsize=(24, 12))

ax = plt.axes(xlim=(tmin, tmax))  #,ylim=(dmin,dmax))
ax.plot(t, deltap, ls='solid', lw=1, color='b')
ax.plot(t, deltan, ls='solid', lw=1, color='r')

ax.hlines(0., tmin, tmax, linestyles='dashed', lw=1.2)

#ax.set_xscale('log')
ax.set_yscale('log')

# Set axes labels
plt.xlabel('t/tdyn', size=txt)
plt.ylabel(r'$\delta$', size=1.3 * txt)

# Set plot titles
ax.set_title('Growth Rate - ' + File, size=1.5 * txt)
Exemplo n.º 45
0
    def stacking(self,
                 star_list,
                 mean_list,
                 mean,
                 psf_type,
                 restrict_psf=None,
                 symmetry=1,
                 inverse_shift=True,
                 vmax=None,
                 vmin=None,
                 verbose=True):
        """

        :param star_list:
        :return:
        """
        num_stars = len(star_list)
        if restrict_psf is None:
            restrict_psf = [True] * num_stars
        shifteds = []
        mean_list_select = []
        for i in range(num_stars):
            if restrict_psf[i] is True:
                data = star_list[i] - mean
                if psf_type == 'gaussian' or psf_type == 'pixel':
                    amp, sigma, center_x, center_y = mean_list[i]
                elif psf_type == 'moffat':
                    amp, alpha, beta, center_x, center_y = mean_list[i]
                else:
                    raise ValueError('psf type %s not valid' % psf_type)
                data[data < 0] = 0
                if inverse_shift is True:
                    shifted = util.de_shift_kernel(data,
                                                   shift_x=-center_x - 0.5,
                                                   shift_y=-center_y - 0.,
                                                   iterations=10)
                else:
                    shifted = interp.shift(data,
                                           [-center_y - 0.5, -center_x - 0.5],
                                           order=1)
                sym_shifted = util.symmetry_average(shifted, symmetry)
                shifteds.append(sym_shifted)
                mean_list_select.append(mean_list[i])
                if verbose is True:
                    print('=== object ===', i, center_x, center_y)
                    import matplotlib.pylab as plt
                    fig, ax1 = plt.subplots()
                    im = ax1.matshow(np.log10(sym_shifted),
                                     origin='lower',
                                     vmax=vmax,
                                     vmin=vmin)

                    #v_max = np.max(np.nan_to_num(np.log10(sym_shifted)))
                    #v_min = np.min(np.nan_to_num(np.log10(sym_shifted)))

                    #v_min = max(v_max-5, v_min)
                    #im = ax1.matshow(np.log10(sym_shifted), origin='lower',vmin=v_min, vmax=v_max)
                    plt.axes(ax1)
                    fig.colorbar(im)
                    plt.show()

        combined = sum(shifteds)
        mean_list_select = np.mean(mean_list_select[:])
        """
        new = np.empty_like(combined)
        max_pix = np.max(combined)
        p = combined[combined >= max_pix/10**6]  #in the SIS regime
        new[combined < max_pix/10**6] = 0
        new[combined >= max_pix/10**6] = p
        """
        kernel = util.kernel_norm(combined)
        return kernel, mean_list_select, restrict_psf, shifteds
import numpy as np
import matplotlib.pylab as plt
from mpl_toolkits import mplot3d

data = np.genfromtxt("difusionfijas.dat")
x = data[:, 0]
y = data[:, 1]
X, Y = np.meshgrid(x, y)
foto1 = data[:, 2:103]
foto2 = data[:, 103:204]
foto3 = data[:, 204:305]

fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot_surface(Y,
                X,
                foto1,
                rstride=1,
                cstride=1,
                cmap='viridis',
                edgecolor='none')
ax.set_xlabel('x(m)')
ax.set_ylabel('y(m)')
ax.set_zlabel('T(Celcius)')
ax.set_title('frontera fija t=0')
plt.savefig("difusionFijas0.png")

fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot_surface(Y,
                X,
Exemplo n.º 47
0
# 只要程序处于活动状态,就不断的模拟随机漫步
while True:
    # 创建一个RandomWalk实例,并将其包含的点都绘制出来
    rw = RandomWalk(5000)
    rw.fill_walk()

    # 设置绘制窗口尺寸
    plt.figure(dpi=128, figsize=(10, 6))

    plt.plot(rw.x_values, rw.y_values, linewidth=1)

    # 突出起点和终点
    plt.scatter(0, 0, c='green', edgecolors='none', s=100)
    plt.scatter(rw.x_values[-1],
                rw.y_values[-1],
                c='red',
                edgecolors='none',
                s=100)

    # 隐藏坐标轴
    plt.axes().get_xaxis().set_visible(False)
    plt.axes().get_yaxis().set_visible(False)

    plt.show()
    # 保存图片
    # plt.savefig('water_visual2.png', bbox_inches='tight')

    keep_running = input("Make anther walk? (y/n):")
    if keep_running == 'n':
        break
Exemplo n.º 48
0
    def drawFig(self, img_grid):
        # figure properties
        fig = pb.figure(figsize=(10, 6))
        row_length = len(out_row_vals)
        col_length = len(out_col_vals)
        gs = matplotlib.gridspec.GridSpec(
            row_length, col_length, wspace=.05,
            hspace=.05)  # +1 for the colormap area
        """figure processing"""
        img_grid_list = img_grid.tolist()
        # get min and max to set up colormap scale, and loop all again to plot images
        MIN = pb.array(img_grid).min()
        MAX = pb.array(img_grid).max()
        for out_row_index in range(len(out_row_vals)):
            for out_col_index in range(len(out_col_vals)):
                ax = fig.add_subplot(gs[row_length - 1 - out_row_index,
                                        out_col_index])
                ax.hold(True)

                img_grid_list[out_row_index][out_col_index] = ax.contourf(
                    img_grid[out_row_index][out_col_index],
                    levels=pb.linspace(MIN, MAX, 50),
                    extent=[
                        in_col_vals.min(),
                        in_col_vals.max(),
                        in_row_vals.min(),
                        in_row_vals.max()
                    ],
                    vmin=MIN,
                    vmax=MAX)

                # set ticks and labels of axis (no number in legend for graphs not on borders):
                # for the x axis:
                xticks = in_col_vals
                ax.set_xticks(xticks)
                if (out_row_index > 0):  #< row_length - 1):
                    ax.set_xticklabels([])
                else:
                    ax.set_xlabel(in_col_label + "\n\n" + out_col_label + "=" +
                                  str(out_col_vals[out_col_index])
                                  )  # , fontsize='xx-large')
                    ax.set_xticklabels(map(
                        str, xticks))  # , fontsize='xx-large') #in_col_val

                # for the y axis:
                yticks = in_row_vals  # from in_row_val
                ax.set_yticks(yticks)
                if (out_col_index > 0):
                    ax.set_yticklabels([])
                else:
                    ax.set_ylabel(
                        "|" + out_row_label + "|=" +
                        str(out_row_vals[out_row_index]) + '      ' +
                        in_row_label,
                        rotation='horizontal')  # , fontsize='xx-large')
                    ax.set_yticklabels(map(
                        str, yticks))  # , fontsize='xx-large') #in_row_val

        # setup colorbar
        ax = pb.axes([0.92, 0.1, 0.01,
                      0.8])  # guess [left, bottom, width, heigth]. in percents
        cbar = pb.colorbar(img_grid_list[0][0], ax)  # , ticks=ticksValues)
        pb.ion()
        return fig
Exemplo n.º 49
0

def energies_on_path(path, TB, n_pts, n_orb=1):
    E = zeros((n_orb, n_pts * (len(path) - 1)))
    for i in range(len(path) - 1, 0, -1):
        energies = energies_on_bz_path(TB, path[i - 1], path[i], n_pts)
        for orb in range(n_orb):
            E[orb, (i - 1) * n_pts:(i) * n_pts] = energies[orb, :]
        print "index of point #" + str(i - 1) + " = " + str((i - 1) * n_pts)

    return E


E_1 = energies_on_path(path_1, TB_1, n_pts, 1)
E_2 = energies_on_path(path_2, TB_2, n_pts, 2)
E_4 = energies_on_path(path_4, TB_4, n_pts, 4)

from matplotlib import pylab as plt
plt.plot(E_1[0], '--k', linewidth=4, label="1 at/unit cell")
plt.plot(E_2[0], '-.g', linewidth=4, label="2 ats/unit cell")
plt.plot(E_2[1], '-.g', linewidth=4)
plt.plot(E_4[0], '-r', label="4 ats/unit cell")
plt.plot(E_4[1], '-r')
plt.plot(E_4[2], '-r')
plt.plot(E_4[3], '-r')
plt.grid()
plt.legend()
plt.axes().set_xticks([0, 50, 100, 150])
plt.axes().set_xticklabels([r'$\Gamma_1$', r'$M_1$', r'$X_1$', r'$\Gamma_1$'])
plt.ylabel(r"$\epsilon$")
def plot_end_pos(end_poses):
    for end_pos in end_poses:
        plt.figure()
        ax = plt.axes(projection='3d')
        ax.plot(end_pos[0], end_pos[1], end_pos[2], '-b')
        plt.show()
def slice_rasterize(mesh):

    #print("Current model: {0} \n".format(mesh))
    
    print("Current model centroid {0} \n".format(mesh.centroid))
    
    '''
    # facets are groups of coplanar adjacent faces
    # set each facet to a random color
    # colors are 8 bit RGBA by default (n, 4) np.uint8
    for facet in mesh.facets:
        mesh.visual.face_colors[facet] = trimesh.visual.random_color()

    # preview mesh in an opengl window if you installed pyglet with pip
    mesh.show()
    '''
    

    # Take a bunch of parallel slices,
    # slice the mesh into evenly spaced chunks along z
    # this takes the (2,3) bounding box and slices it into [minz, maxz]
    heights = heights_generator(mesh, 0.125, 2)
    
    print(heights)
    
    print(mesh.bounds)
    
    print("Scanning model along Z depth axis with {0} parallel planes...\n".format(len(heights)))

    #print(mesh.bounds[0][2])
    
    #print(mesh.bounds[0])
    
    # construct a set of scanning plane origins
    #plane_origin_array = np.array([mesh.bounds[0],]*len(heights))
    
    plane_origin_array = np.array([mesh.centroid,]*len(heights))
    
    #plane_origin_array = repeat(mesh.centroid[newaxis,:], 3, 0)
   
    plane_origin_array[:,2] = heights
    
    #print(plane_origin_array[0])
    
    fig = plt.figure()
    
    #plt.axes().set_aspect('equal', 'datalim')
    
    plt.axes().set_aspect('equal')

    
    offset_x = abs(mesh.bounds[0][0] - mesh.bounds[1][0]) * 0.15
    offset_y = abs(mesh.bounds[0][1] - mesh.bounds[1][1]) * 0.15
    
    for idx, value in enumerate(plane_origin_array):
     
     
        #print("plane {0} is {1} \n".format(idx))
        # get a single cross section of the mesh
        slice_3d = mesh.section(plane_origin = plane_origin_array[idx], plane_normal = [0,0,1])
        
        print("plane {0} is {1} \n".format(idx, slice_3d))

        
        # the section will be in the original mesh frame
        #slice.show()
        if not (slice_3d is None):
            # we can move the 3D curve to a Path2D object easily
            slice_2D, to_3D = slice_3d.to_planar()
            
            #slice_2D.show()
            #(slice_2D + slice_2D.medial_axis()).show()
            
            #Save 2d slice as image file
            filename = save_path + 'slice_' + str(idx).zfill(4) + '.png'
            
            #for p in slice_2D.polygons_full:
            for p in slice_2D.polygons_closed:
                if not (p is None):
                    plt.plot(*(p.exterior.xy),'k')
                    for r in p.interiors:
                        plt.plot(*zip(*r.coords), 'b')
            
            #plt.axes().set_aspect('equal')
            
            plt.xlim([mesh.bounds[0][0] - offset_x, mesh.bounds[1][0] + offset_x])
            plt.ylim([mesh.bounds[0][1] - offset_y, mesh.bounds[1][1] + offset_y])
            
            plt.axis('off')
                    
            plt.savefig(filename)
            
            plt.cla()
        
    plt.close()
    
    
    
    '''
Exemplo n.º 52
0
                other_envs_bs < clone_fit) / len(other_envs_bs)
        bs_stat = bs_stat / len(evol_env_bs)

        competition_stat_bs.append(bs_stat)
    col_stat.append(stat)
    #col_stat.append(numpy.percentile(competition_stat_bs,50))
    col_stat_err.append([
        stat - numpy.percentile(competition_stat_bs, 5),
        numpy.percentile(competition_stat_bs, 95) - stat
    ])

###Construct axes to plot

fig = pt.figure(figsize=(6, 5.8))

ax = pt.axes([.16, .16, .74, .74])
cb_ax = pt.axes([.94, .16, .04, .74])
ax_v = pt.axes([0, .16, .14, .74])
ax_h = pt.axes([.16, 0., .74, .14])

row_stat_err = numpy.array(row_stat_err).T
col_stat_err = numpy.array(col_stat_err).T

ax_v.barh(numpy.arange(8),
          numpy.array(row_stat)[::-1],
          .7,
          xerr=row_stat_err[::-1],
          color='grey')
ax_h.bar(numpy.arange(8), col_stat, .7, yerr=col_stat_err, color='grey')

ax_v.set_ylim(-.5, 7.5)
Exemplo n.º 53
0

plt.fill_between(px3,py3,py4,color='c')
plt.fill_between(px5,py5,py6,color='c')

plt.plot(px1,py1, 'k-', linewidth=1.0,label=r"$pp$")
plt.plot(px2,py2, 'k--', linewidth=1.0,label=r"$\bar{p}p$")

plt.xlabel(r"$\sqrt{s}$ [GeV]", fontdict=font)
plt.ylabel(r"$\sigma_{tot}(s)$ [mb]", fontdict=font)

leg = plt.legend(loc=4, ncol=1, shadow=False, fancybox=False, frameon=False, numpoints=1)
leg.get_frame().set_alpha(0.5)

###########################################
sub_axes = plt.axes([.2, .55, .35, .35])
plt.grid(False)
plt.semilogx()
plt.xlim(5000,15000)
plt.ylim(90,120)

plt.errorbar(x1,y1,yerr=erry1,fmt='wo',ecolor='k', capthick=0.5)
plt.errorbar(x2,y2,yerr=erry2,fmt='ko',ecolor='k', capthick=0.5)
plt.errorbar(x3,y3,yerr=erry3,fmt='bs',ecolor='b', markeredgecolor='blue', capthick=0.5)
plt.errorbar(x4,y4,yerr=erry4,fmt='r^',ecolor='r', markeredgecolor='red', capthick=0.5)

plt.fill_between(px3,py3,py4,color='c')
plt.fill_between(px5,py5,py6,color='c')

plt.plot(px1,py1, 'k-', linewidth=1.0)
plt.plot(px2,py2, 'k--', linewidth=1.0)
Exemplo n.º 54
0
    def plot_3d(
        self,
        x_axis: Union[int, str, Embedding] = 0,
        y_axis: Union[int, str, Embedding] = 1,
        z_axis: Union[int, str, Embedding] = 2,
        x_label: Optional[str] = None,
        y_label: Optional[str] = None,
        z_label: Optional[str] = None,
        title: Optional[str] = None,
        color: str = None,
        axis_metric: Optional[Union[str, Callable, Sequence]] = None,
        annot: bool = True,
    ):
        """
        Creates a 3d visualisation of the embedding.

        Arguments:
            x_axis: the x-axis to be used, must be given when dim > 3; if an integer, the corresponding
                dimension of embedding is used.
            y_axis: the y-axis to be used, must be given when dim > 3; if an integer, the corresponding
                dimension of embedding is used.
            z_axis: the z-axis to be used, must be given when dim > 3; if an integer, the corresponding
                dimension of embedding is used.
            x_label: an optional label used for x-axis; if not given, it is set based on value of `x_axis`.
            y_label: an optional label used for y-axis; if not given, it is set based on value of `y_axis`.
            z_label: an optional label used for z-axis; if not given, it is set based on value of `z_axis`.
            title: an optional title for the plot.
            color: the property to user for the color
            axis_metric: the metric used to project each embedding on the axes; only used when the corresponding
                axis is a string or an `Embedding` instance. It could be a string (`'cosine_similarity'`,
                `'cosine_distance'` or `'euclidean'`), or a callable that takes two vectors as input and
                returns a scalar value as output. To set different metrics of the three different axes,
                you can pass a list/tuple of size three that describes the metrics you're interested in.
                By default (`None`), normalized scalar projection (i.e. `>` operator) is used.
            annot: drawn points should be annotated

        **Usage**

        ```python
        from whatlies.language import SpacyLanguage
        from whatlies.transformers import Pca

        words = ["prince", "princess", "nurse", "doctor", "banker", "man", "woman",
                 "cousin", "neice", "king", "queen", "dude", "guy", "gal", "fire",
                 "dog", "cat", "mouse", "red", "bluee", "green", "yellow", "water",
                 "person", "family", "brother", "sister"]

        lang = SpacyLanguage("en_core_web_sm")
        emb = lang[words]

        emb.transform(Pca(3)).plot_3d(annot=True)
        emb.transform(Pca(3)).plot_3d("king", "dog", "red")
        emb.transform(Pca(3)).plot_3d("king", "dog", "red", axis_metric="cosine_distance")
        ```
        """
        if isinstance(x_axis, str):
            x_axis = self[x_axis]
        if isinstance(y_axis, str):
            y_axis = self[y_axis]
        if isinstance(z_axis, str):
            z_axis = self[z_axis]

        if isinstance(axis_metric, (list, tuple)):
            x_axis_metric = axis_metric[0]
            y_axis_metric = axis_metric[1]
            z_axis_metric = axis_metric[2]
        else:
            x_axis_metric = axis_metric
            y_axis_metric = axis_metric
            z_axis_metric = axis_metric

        # Determine axes values and labels
        if isinstance(x_axis, int):
            x_val = self.to_X()[:, x_axis]
            x_lab = "Dimension " + str(x_axis)
        else:
            x_axis_metric = Embedding._get_plot_axis_metric_callable(
                x_axis_metric)
            x_val = self.compare_against(x_axis, mapping=x_axis_metric)
            x_lab = x_axis.name
        x_lab = x_label if x_label is not None else x_lab

        if isinstance(y_axis, int):
            y_val = self.to_X()[:, y_axis]
            y_lab = "Dimension " + str(y_axis)
        else:
            y_axis_metric = Embedding._get_plot_axis_metric_callable(
                y_axis_metric)
            y_val = self.compare_against(y_axis, mapping=y_axis_metric)
            y_lab = y_axis.name
        y_lab = y_label if y_label is not None else y_lab

        if isinstance(z_axis, int):
            z_val = self.to_X()[:, z_axis]
            z_lab = "Dimension " + str(z_axis)
        else:
            z_axis_metric = Embedding._get_plot_axis_metric_callable(
                z_axis_metric)
            z_val = self.compare_against(z_axis, mapping=z_axis_metric)
            z_lab = z_axis.name
        z_lab = z_label if z_label is not None else z_lab

        # Save relevant information in a dataframe for plotting later.
        plot_df = pd.DataFrame({
            "x_axis":
            x_val,
            "y_axis":
            y_val,
            "z_axis":
            z_val,
            "name": [v.name for v in self.embeddings.values()],
            "original": [v.orig for v in self.embeddings.values()],
        })

        # Deal with the colors of the dots.
        if color:
            plot_df["color"] = [
                getattr(v, color) if hasattr(v, color) else ""
                for v in self.embeddings.values()
            ]

            color_map = {k: v for v, k in enumerate(set(plot_df["color"]))}
            color_val = [
                color_map[k] if not isinstance(k, float) else k
                for k in plot_df["color"]
            ]
        else:
            color_val = None

        ax = plt.axes(projection="3d")
        ax.scatter3D(plot_df["x_axis"],
                     plot_df["y_axis"],
                     plot_df["z_axis"],
                     c=color_val,
                     s=25)

        # Set the labels, titles, text annotations.
        ax.set_xlabel(x_lab)
        ax.set_ylabel(y_lab)
        ax.set_zlabel(z_lab)

        if annot:
            for i, row in plot_df.iterrows():
                ax.text(row["x_axis"], row["y_axis"], row["z_axis"] + 0.05,
                        row["original"])
        if title:
            ax.set_title(label=title)
        return ax
Exemplo n.º 55
0
        fig = plt.figure(figsize=(7, 7))
        ax = fig.add_subplot(111)

        M, target = 200, 100
        ax.plot(mean[:M], 'b', lw=2)
        ax.plot(mean[:M] + std[:M], 'r', ls='--', lw=1.3)
        ax.plot(mean[:M] - std[:M], 'r', ls='--', lw=1.3)
        # ax.plot(median[:M], 'k', lw=2)
        # ax.plot(mmad[:M], 'm', lw=2)
        ax.set_xlabel('Epochs')
        ax.set_ylabel('Mean (SD)')
        plt.xticks([0, 50, 100, 150, 200],
                   ('0', '2500', '5000', '7500', '10000'))
        plt.title('Evolution of' + r'$\mathbb{E}\{w_f\}$')

        bx = plt.axes([.19, .70, .15, .15], axisbg='y')
        W = np.load(base + 'weights000000.npy')[target].reshape(n, n)
        bx.imshow(W, interpolation='bicubic', cmap=plt.cm.Purples)
        plt.title(r'epoch=0')
        plt.setp(bx, xticks=[], yticks=[])

        cx = plt.axes([.27, .45, .15, .15], axisbg='y')
        W = np.load(base + 'weights002500.npy')[target].reshape(n, n)
        cx.imshow(W, interpolation='bicubic', cmap=plt.cm.Purples)
        plt.title(r'epoch=2500')
        plt.setp(cx, xticks=[], yticks=[])

        dx = plt.axes([.63, .3, .15, .15], axisbg='y')
        W = np.load(base + 'weights007500.npy')[target].reshape(n, n)
        dx.imshow(W, interpolation='bicubic', cmap=plt.cm.Purples)
        plt.title(r'epoch=7500')
Exemplo n.º 56
0
    def _plot_seasonality(self, alpha: float, plot_kwargs: bool):
        # two_tailed_alpha = int(alpha / 2 * 100)
        periods = list(set([float(i.split("_")[1]) for i in self.seasonality]))

        additive_ts, multiplicative_ts = self._fit_seasonality()

        all_seasonalities = [("additive", additive_ts)]
        if len(self.multiplicative_data):
            all_seasonalities.append(("multiplicative", multiplicative_ts))
        for sn, ts in all_seasonalities:
            if (sn == "multiplicative"
                    and np.sum(ts) == 1) or (sn == "additive"
                                             and np.sum(ts) == 0):
                continue
            ddf = pd.DataFrame(
                np.vstack([
                    np.percentile(ts[:, :, self.skip_first:], 50, axis=-1),
                    np.percentile(ts[:, :, self.skip_first:],
                                  alpha / 2 * 100,
                                  axis=-1),
                    np.percentile(ts[:, :, self.skip_first:],
                                  (1 - alpha / 2) * 100,
                                  axis=-1),
                ]).T,
                columns=[
                    "%s_%s" % (p, l) for l in ["mid", "low", "high"]
                    for p in periods[::-1]
                ],
            )
            ddf.loc[:, "ds"] = self.data["ds"]
            for period in periods:
                if int(period) == 0:
                    step = int(self.data["ds"].diff().mean().total_seconds() //
                               float(period))
                else:
                    step = int(period)
                graph = ddf.head(step)
                if period == 7:
                    ddf.loc[:, "dow"] = [i for i in ddf["ds"].dt.weekday]
                    graph = (ddf[[
                        "dow",
                        "%s_low" % period,
                        "%s_mid" % period,
                        "%s_high" % period,
                    ]].groupby("dow").mean().sort_values("dow"))
                    graph.loc[:, "ds"] = [[
                        "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
                    ][i] for i in graph.index]
                    graph = graph.sort_index()
                plt.figure(**plot_kwargs)
                graph.plot(y="%s_mid" % period,
                           x="ds",
                           color="C0",
                           legend=False,
                           ax=plt.gca())
                plt.grid()

                if period == 7:
                    plt.xticks(range(7), graph["ds"].values)
                    plt.fill_between(
                        np.arange(0, 7),
                        graph["%s_low" % period].values.astype(float),
                        graph["%s_high" % period].values.astype(float),
                        alpha=0.3,
                    )
                else:
                    plt.fill_between(
                        graph["ds"].values,
                        graph["%s_low" % period].values.astype(float),
                        graph["%s_high" % period].values.astype(float),
                        alpha=0.3,
                    )

                plt.title("Model Seasonality (%s) for period: %s days" %
                          (sn, period))
                plt.axes().xaxis.label.set_visible(False)
                plt.show()
Exemplo n.º 57
0
    #------

    rho = [0.1, 1]
    r2, z2 = eqm.rho2rz(rho, t_in=3, coord_in='rho_pol')
    n_theta = len(r2[0][0])
    theta = np.linspace(0, 2 * np.pi, 1000)
    r1, z1 = eqm.rhoTheta2rz(rho,
                             theta,
                             t_in=3,
                             coord_in='rho_pol',
                             n_line=1000)

    plt.figure(5, figsize=(10, 12))

    plt.axes().set_aspect('equal')
    plt.plot(r2[0][0], z2[0][0], 'go')
    plt.plot(r1[0, :, 0], z1[0, :, 0], 'r+')
    R, Z = np.meshgrid(eqm.Rmesh, eqm.Zmesh)
    plt.plot(R, Z, ",k")

    #plt.figure(6, figsize=(10, 12))

    plt.axes().set_aspect('equal')
    plt.plot(r2[0][1], z2[0][1], 'go')
    plt.plot(r1[0, :, 1], z1[0, :, 1], 'r+')

    rgrid, zgrid, theta_star = eqm.mag_theta_star(3)

    plt.figure()
    plt.pcolor(rgrid, zgrid, theta_star)
Exemplo n.º 58
0
    def plot_results(
        self,
        datasource,
        from_date,
        to_date,
        num_cpus=1,
        num_gpus=0,
        x_dim=-1,
        y_dim=-1,
        output=None,
    ):
        """

        # Arguments:
            models (tuple): encoder and decoder models
            data (tuple): test data and label
            model_name (string): which model is using this function
        """
        global g_mc_batch_size
        # Agg = Anti-grain geometry engine
        # running inside a Docker image. No Xwindow
        import matplotlib
        matplotlib.use('Agg')
        import matplotlib.pyplot as plt

        period = self.build_date_range(from_date, to_date)

        logging.info("plot_results(%s) range=%s", self.name, period)

        self.load(num_cpus, num_gpus)
        _, latent_dim = self._encoder_model.outputs[0].get_shape()

        # Build history time range
        # Extra data are required to predict first buckets
        _window = self._window - 1

        hist = DateRange(
            period.from_ts - _window * self.bucket_interval,
            period.to_ts,
        )

        # Prepare dataset
        nb_buckets = int((hist.to_ts - hist.from_ts) / self.bucket_interval)
        dataset = np.full((nb_buckets, ), np.nan, dtype=float)

        # Fill dataset
        logging.info("extracting data for range=%s", hist)
        data = datasource.get_times_data(self, hist.from_ts, hist.to_ts)

        # Only a subset of history will be used for computing the prediction
        X_until = None  # right bound for prediction
        i = None

        for i, (_, val, timeval) in enumerate(data):
            dataset[i] = val

            dt = make_datetime(timeval)
            ts = dt.timestamp()
            if ts < period.to_ts:
                X_until = i + 1

        if i is None:
            raise errors.NoData("no data found for time range {}".format(hist))

        self.apply_defaults(dataset)

        nb_buckets_found = i + 1
        if nb_buckets_found < nb_buckets:
            dataset = np.resize(dataset, (nb_buckets_found, ))

        logging.info("found %d time periods", nb_buckets_found)

        norm_dataset = self.scale_dataset(dataset)
        X_miss_val, X_test = self._format_dataset(norm_dataset[:X_until])
        if len(X_test) == 0:
            raise errors.LoudMLException("not enough data for prediction")

        # display a 2D plot of the digit classes in the latent space
        z_mean, _, _ = self._encoder_model.predict([X_test, X_miss_val],
                                                   batch_size=g_mc_batch_size)

        if x_dim < 0 or y_dim < 0:
            mses = []
            for (x, y) in itertools.combinations(range(0, latent_dim), 2):
                _mean = np.mean(z_mean, axis=0)[[x, y]]
                mse = ((z_mean[:, [x, y]] - _mean)**2).mean(axis=0)
                mses.append([x, y, mse[0] + mse[1]])

            mses = sorted(mses, key=lambda x: x[2])
            x_dim = mses[0][0]
            y_dim = mses[0][1]

        excl = [x for x in range(latent_dim) if x != x_dim and x != y_dim]

        plt.figure(figsize=(12, 10))
        if latent_dim > 3:
            ax = plt.axes(projection='3d')
            ax.set_zticks([])
        else:
            ax = plt.axes()

        # Hide grid lines
        ax.grid(False)
        # Hide axes ticks
        ax.set_xticks([])
        ax.set_yticks([])

        if latent_dim > 3:
            zc = np.array(
                [[z_mean[i, excl[0]], z_mean[i, excl[1]], z_mean[i, excl[2]]]
                 for i, _ in enumerate(z_mean)])
            # (x-min(x))/(max(x)-min(x)). RGBA values should be within 0-1 range
            zc = (zc - np.min(zc, axis=0)) / \
                (np.max(zc, axis=0) - np.min(zc, axis=0))
            if latent_dim > 5:
                ax.set_zlabel("z[{}]".format(excl[3]))
                ax.scatter(z_mean[:, x_dim],
                           z_mean[:, y_dim],
                           z_mean[:, excl[3]],
                           c=zc)
            else:
                zc[:, 0] = 0
                ax.set_zlabel("z[{}]".format(excl[0]))
                ax.scatter(z_mean[:, x_dim],
                           z_mean[:, y_dim],
                           z_mean[:, excl[0]],
                           c=zc)
        else:
            plt.scatter(z_mean[:, x_dim],
                        z_mean[:, y_dim],
                        c=z_mean[:, excl[0]])
            plt.colorbar()

        plt.xlabel("z[{}]".format(x_dim))
        plt.ylabel("z[{}]".format(y_dim))
        if output is None:
            plt.show()
        else:
            plt.savefig(output)
Exemplo n.º 59
0
def main():
    '''
    command line arguments: how many inner streamlines to ignore and how many to count in
    '''

    #command line args
    if len(sys.argv) != 2:
        ignore, count = 3, 3
    else:
        ignore = int(sys.argv[1])
        count = int(sys.argv[2])

    #What to plot:
    #[streamlines, magnetopause, poynting vectors, surface]
    plotting = [False, False, False, True]

    streams = make_streamlines()
    pause_by_slice, pause_by_x = get_magnetopause(streams, ignore, count)

    ax = plt.axes(projection='3d',
                  xlabel='X (Re)',
                  ylabel='Y (Re)',
                  zlabel='Z (Re)')

    if plotting[0]:  #plot streamlines
        for s in np.arange(0, len(streams.streamlines)):
            stream_pos = streams.streamlines[s]
            ax.scatter(stream_pos[:, 0], stream_pos[:, 1], stream_pos[:, 2])

    if plotting[1]:  #plot magnetopause by coordinates

        coords = []
        for sl in pause_by_slice:
            if len(sl) == 0:
                continue  #if slice is empty(works on nested lists?)
            sl = np.array(sl)
            ax.plot3D(sl[:, 0], sl[:, 1], sl[:, 2])

            coords.append([sl[:, 0], sl[:, 1], sl[:, 2]])

        for plane in pause_by_x:
            plane = np.array(plane)
            ax.plot3D(plane[:, 0], plane[:, 1], plane[:, 2])

    if plotting[2]:  #plot Poynting vetors (not working!)
        coords = np.array(coords)
        poynting = np.array(poynting)

        ax.quiver(coords[:, 0], coords[:, 1], coords[:, 2], P[:, 0], P[:, 1],
                  P[:, 2])

    if plotting[3]:  #plot surface
        print('Making the surface...')
        verts, faces = make_surface(pause_by_x)
        verts = np.array(verts)

        ax.plot_trisurf(verts[:, 0],
                        verts[:, 1],
                        faces,
                        verts[:, 2],
                        linewidth=0.2,
                        antialiased=True)

    plt.savefig('magnetopause3d.png')

    #save 2d projection
    #ax.view_init(azim=45, elev=0)
    #plt.savefig('magnetopause3dprojection.png')

    print('Ready!')
Exemplo n.º 60
0
tmin = min(t) - max(t) / 50.
tmax = max(t) + max(t) / 50.

# Customisation
plt.rc('path', simplify=True)
plt.rc('savefig', dpi=300, format='png')
plt.rc('axes', linewidth=lw, labelpad=lblpad)
plt.rc('xtick', labelsize=tick, direction='inout')
plt.rc('xtick.major', size=tickh, width=lw, pad=pad)
plt.rc('ytick', labelsize=tick, direction='inout')
plt.rc('ytick.major', size=tickh, width=lw, pad=pad)

# Set up the plot
plt.figure(figsize=(24, 12))

ax = plt.axes(xlim=(tmin, tmax), ylim=(dtmin, dtmax))
plot = ax.plot(t, dt, marker='.', linestyle='none', markersize=s)
ax.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e'))
ax.axhline(y=min(dt), linestyle='dashed', color='k', lw=lw)
#ax.set_yscale('log')
#ax.set_xscale('log')

# Set axes labels
plt.xlabel('t/tdyn', size=txt)
plt.ylabel('dt [Gyr]', size=txt)

# Set plot titles
ax.set_title('Timestep', size=1.5 * txt)

print '====Plots Generated==='
# Save the figure