예제 #1
0
def display_coeff(data=None):
    betaAll,betaErrAll, R2adjAll = measure_stamp_coeff(data = data, zernike_max_order=20)
    ind = np.arange(len(betaAll[0]))
    momname = ('M20','M22.Real','M22.imag','M31.real','M31.imag','M33.real','M33.imag')
    fmtarr = ['bo-','ro-','go-','co-','mo-','yo-','ko-']
    pl.figure(figsize=(17,13))
    for i in range(7):
        pl.subplot(7,1,i+1)
        pl.errorbar(ind,betaAll[i],yerr = betaErrAll[i],fmt=fmtarr[i])
        pl.grid()
        pl.xlim(-1,21)
        if i ==0:
            pl.ylim(-10,65)
        elif i ==1:
            pl.ylim(-5,6)
        elif i ==2:
            pl.ylim(-5,6)
        elif i == 3:
            pl.ylim(-0.1,0.1)
        elif i == 4:
            pl.ylim(-0.1,0.1)
        elif i ==5:
            pl.ylim(-100,100)
        elif i == 6:
            pl.ylim(-100,100)
        pl.xticks(ind,('','','','','','','','','','','','','','','','','','','',''))
        pl.ylabel(momname[i])
    pl.xticks(ind,('0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19'))
    pl.xlabel('Zernike Coefficients')
    return '--- done ! ----'
예제 #2
0
def time_delays_plot(env, **kwargs):

    models = kwargs.pop('models', env.models)
    obj_index = kwargs.pop('obj_index', 0)
    src_index = kwargs.pop('src_index', 0)
    key = kwargs.pop('key', 'accepted')

    d = defaultdict(list)
    for m in models:
        obj,data = m['obj,data'][obj_index]
        t0 = data['arrival times'][src_index][0]
        for i,t in enumerate(data['arrival times'][src_index][1:]):
            d[i].append( float('%0.6f'%convert('arcsec^2 to days', t-t0, obj.dL, obj.z, data['nu'])) )
            t0 = t

    s = product(range(1,1+len(d)), ['solid', 'dashed', 'dashdot', 'dotted'])
    for k,v in d.iteritems():
        #print 'td plot', k, len(v)
        #print v
        lw,ls = s.next()
        pl.hist(v, bins=25, histtype='step', color='k', ls=ls, lw=lw, label='%s - %s' % (str(k+1),str(k+2)), **kwargs)

    #pl.xlim(xmin=0)
    pl.ylim(ymin=0)
    pl.xlim(xmin=pl.xlim()[0] - 0.01*(pl.xlim()[1] - pl.xlim()[0]))
    pl.legend()

    pl.xlabel(_time_delays_xlabel)
    pl.ylabel(r'Count')
예제 #3
0
def simulation1(numTrials, numSteps, loc):
    results = {'UsualDrunk': [], 'ColdDrunk': [], 'EDrunk': [], 'PhotoDrunk': [], 'DDrunk': []}
    drunken_types = {'UsualDrunk': UsualDrunk, 'ColdDrunk': ColdDrunk, 'EDrunk': EDrunk, 'PhotoDrunk': PhotoDrunk,
                     'DDrunk': DDrunk}
    for drunken in drunken_types.keys():
        #Create field
        initial_loc = Location(loc[0], loc[1])
        field = Field()
        print "Simu", drunken
        drunk = Drunk(drunken)
        drunk_man = drunken_types[drunken](drunk)
        field.addDrunk(drunk_man, initial_loc)
        #print drunk_man
        for trial in range(numTrials):
            distance = walkVector(field, drunk_man, numSteps)
            results[drunken].append((round(distance[0], 1), round(distance[1], 1)))
        print drunken, "=", results[drunken]
    for result in results.keys():
        # x, y = zip(*results[result])
        # print "x", x
        # print "y", y
        pylab.plot(*zip(*results[result]), marker='o', color='r', ls='')
        pylab.title(result)
        pylab.xlabel('X coordinateds')
        pylab.ylabel('Y coordinateds')
        pylab.xlim(-100, 100)
        pylab.ylim(-100, 100)
        pylab.figure()
    pylab.show
예제 #4
0
	def plot_frontier(self,frontier_only=False,plot_samples=True) :
		""" Plot the frontier"""
		frontier = self.frontier
		frontier_energy = self.frontier_energy
		feat1,feat2 = self.feats	
	
		pl.figure()
		if not frontier_only :	
			ll_list1,ll_list2 = zip(*self.all_seq_energy)
			pl.plot(ll_list1,ll_list2,'b*')
		if plot_samples :
			ll_list1,ll_list2 = zip(*self.sample_seq_energy)
			pl.plot(ll_list1,ll_list2,'g*')
					
		pl.plot(*zip(*sorted(frontier_energy)),color='magenta',\
			marker='*',	linestyle='dashed')
		ctr = dict(zip(set(frontier_energy),[0]*
			len(set(frontier_energy))))
		for i,e in enumerate(frontier_energy) : 
			ctr[e] += 1
			pl.text(e[0],e[1]+0.1*ctr[e],str(i),fontsize=10)
			pl.text(e[0]+0.4,e[1]+0.1*ctr[e],frontier[i],fontsize=9)	
		pl.xlabel('Energy:'+feat1)
		pl.ylabel('Energy:'+feat2)
		pl.title('Energy Plot')
		xmin,xmax = pl.xlim()
		ymin,ymax = pl.ylim()
		pl.xlim(xmin,xmax)
		pl.ylim(ymin,ymax)
		pic_dir = '../docs/tex/pics/'
		pl.savefig(pic_dir+self.name+'.pdf')
		pl.savefig(pic_dir+self.name+'.png')
예제 #5
0
def geweke_plot(data, name, format='png', suffix='-diagnostic', path='./', fontmap = None, 
    verbose=1):
    # Generate Geweke (1992) diagnostic plots

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

    # Generate new scatter plot
    figure()
    x, y = transpose(data)
    scatter(x.tolist(), y.tolist())

    # Plot options
    xlabel('First iteration', fontsize='x-small')
    ylabel('Z-score for %s' % name, fontsize='x-small')

    # Plot lines at +/- 2 sd from zero
    pyplot((nmin(x), nmax(x)), (2, 2), '--')
    pyplot((nmin(x), nmax(x)), (-2, -2), '--')

    # Set plot bound
    ylim(min(-2.5, nmin(y)), max(2.5, nmax(y)))
    xlim(0, nmax(x))

    # Save to file
    if not os.path.exists(path):
        os.mkdir(path)
    if not path.endswith('/'):
        path += '/'
    savefig("%s%s%s.%s" % (path, name, suffix, format))
예제 #6
0
def plotForce():
    figure(size=3,aspect=0.5)
    subplot(1,2,1)
    from EvalTraj import plotFF
    plotFF(vp=351,t=28,f=900,cm=0.6,foffset=8)
    subplot_annotate()
    
    subplot(1,2,2)
    for i in [1,2,3,4]:
        R=np.squeeze(np.load('Rdpse%d.npy'%i))
        R=stats.nanmedian(R,axis=2)[:,1:,:]
        dps=np.linspace(-1,1,201)[1:]
        plt.plot(dps,R[:,:,2].mean(0));
    plt.legend([0,0.1,0.2,0.3],loc=3) 
    i=2
    R=np.squeeze(np.load('Rdpse%d.npy'%i))
    R=stats.nanmedian(R,axis=2)[:,1:,:]
    mn=np.argmin(R,axis=1)
    y=np.random.randn(mn.shape[0])*0.00002+0.0438
    plt.plot(np.sort(dps[mn[:,2]]),y,'+',mew=1,ms=6,mec=[ 0.39  ,  0.76,  0.64])
    plt.xlabel('Displacement of Force Origin')
    plt.ylabel('Average Net Force Magnitude')
    hh=dps[mn[:,2]]
    err=np.std(hh)/np.sqrt(hh.shape[0])*stats.t.ppf(0.975,hh.shape[0])
    err2=np.std(hh)/np.sqrt(hh.shape[0])*stats.t.ppf(0.75,hh.shape[0])
    m=np.mean(hh)
    print m, m-err,m+err
    np.save('force',[m, m-err,m+err,m-err2,m+err2])
    plt.xlim([-0.5,0.5])
    plt.ylim([0.0435,0.046])
    plt.grid(b=True,axis='x')
    subplot_annotate()
예제 #7
0
def plot_sphere_x( s, fname ):
  """ put plot of ionization fractions from sphere `s` into fname """

  plt.figure()
  s.Edges.units = 'kpc'
  s.r_c.units = 'kpc'
  xx = s.r_c
  L = s.Edges[-1]

  plt.plot( xx, np.log10( s.xHe1 ),
            color='green', ls='-', label = r'$x_{\rm HeI}$' )
  plt.plot( xx, np.log10( s.xHe2 ),
            color='green', ls='--', label = r'$x_{\rm HeII}$' )
  plt.plot( xx, np.log10( s.xHe3 ),
            color='green', ls=':', label = r'$x_{\rm HeIII}$' )

  plt.plot( xx, np.log10( s.xH1 ),
            color='red', ls='-', label = r'$x_{\rm HI}$' )
  plt.plot( xx, np.log10( s.xH2 ),
            color='red', ls='--', label = r'$x_{\rm HII}$' )

  plt.xlim( -L/20, L+L/20 )
  plt.xlabel( 'r_c [kpc]' )

  plt.ylim( -4.5, 0.2 )
  plt.ylabel( 'log 10 ( x )' )

  plt.grid()
  plt.legend(loc='best', ncol=2)
  plt.tight_layout()
  plt.savefig( 'doc/img/x_' + fname )
예제 #8
0
def plotB2reg(prefix=''):
    w=loadStanFit(prefix+'revE2B2LHregCa.fit')
    px=np.array(np.linspace(-0.5,0.5,101),ndmin=2)
    a1=np.array(w['ma'][:,4],ndmin=2).T+1
    a0=np.array(w['ma'][:,3],ndmin=2).T
    printCI(w,'ma')
    y=np.concatenate([sap(a0+a1*px,97.5,axis=0),sap(a0+a1*px[:,::-1],2.5,axis=0)])
    x=np.squeeze(np.concatenate([px,px[:,::-1]],axis=1))
    man=np.array([-0.4,-0.2,0,0.2,0.4])
    plt.plot(px[0,:],np.median(a0)+np.median(a1)*px[0,:],'red')
    #plt.plot([-1,1],[0.5,0.5],'grey')
    ax=plt.gca()
    ax.set_aspect(1)
    ax.add_patch(plt.Polygon(np.array([x,y]).T,alpha=0.2,fill=True,fc='red',ec='w'))
    y=np.concatenate([sap(a0+a1*px,75,axis=0),sap(a0+a1*px[:,::-1],25,axis=0)])
    ax.add_patch(plt.Polygon(np.array([x,y]).T,alpha=0.2,fill=True,fc='red',ec='w'))
    mus=[]
    for m in range(len(man)):
        mus.append(loadStanFit(prefix+'revE2B2LHC%d.fit'%m)['ma4']+man[m])
    mus=np.array(mus).T
    errorbar(mus,x=man)
    ax.set_xticks(man)
    plt.xlim([-0.5,0.5])
    plt.ylim([-0.6,0.8])
    plt.xlabel('Pivot Displacement')
    plt.ylabel('Perceived Displacemet')
예제 #9
0
def plotB3reg():
    w=loadStanFit('revE2B3BHreg.fit')
    printCI(w,'mmu')
    printCI(w,'mr')
    for b in range(2):
        subplot(1,2,b+1)
        plt.title('')
        px=np.array(np.linspace(-0.5,0.5,101),ndmin=2)
        a0=np.array(w['mmu'][:,b],ndmin=2).T
        a1=np.array(w['mr'][:,b],ndmin=2).T
        y=np.concatenate([sap(a0+a1*px,97.5,axis=0),sap(a0+a1*px[:,::-1],2.5,axis=0)])
        x=np.squeeze(np.concatenate([px,px[:,::-1]],axis=1))
        plt.plot(px[0,:],np.median(a0)+np.median(a1)*px[0,:],'red')
        #plt.plot([-1,1],[0.5,0.5],'grey')
        ax=plt.gca()
        ax.set_aspect(1)
        ax.add_patch(plt.Polygon(np.array([x,y]).T,alpha=0.2,fill=True,fc='red',ec='w'))
        y=np.concatenate([sap(a0+a1*px,75,axis=0),sap(a0+a1*px[:,::-1],25,axis=0)])
        ax.add_patch(plt.Polygon(np.array([x,y]).T,alpha=0.2,fill=True,fc='red',ec='w'))
        man=np.array([-0.4,-0.2,0,0.2,0.4])
        mus=[]
        for m in range(len(man)):
            mus.append(loadStanFit('revE2B3BH%d.fit'%m)['mmu'][:,b])
        mus=np.array(mus).T
        errorbar(mus,x=man)
        ax.set_xticks(man)
        plt.xlim([-0.5,0.5])
        plt.ylim([-0.4,0.8])
        #plt.xlabel('Manipulated Displacement')
        if b==0:
            plt.ylabel('Perceived Displacemet')
            plt.gca().set_yticklabels([])
        subplot_annotate()
    plt.text(-1.1,-0.6,'Pivot Displacement',fontsize=8);
예제 #10
0
파일: rocs.py 프로젝트: cbare/dreamtools
    def plot_roc(self, roc=None):
        """Plot ROC curves

        .. plot::
            :include-source:
            :width: 80%

            from dreamtools import rocs
            r = rocs.ROC()
            r.scores = [.9,.5,.6,.7,.1,.2,.6,.4,.7,.9, .2]
            r.classes = [1,0,1,0,0,1,1,0,0,1,1]
            r.plot_roc()

        """
        if roc == None:
            roc = self.get_roc()
        from pylab import plot, xlim, ylim ,grid, title, xlabel, ylabel
        x = roc['fpr']
        plot(x, roc['tpr'], '-o')
        plot([0,1], [0,1],'r')
        ylim([0, 1])
        xlim([0, 1])
        grid(True)
        title("ROC curve (AUC=%s)" % self.compute_auc(roc))
        xlabel("FPR")
        ylabel("TPR")
예제 #11
0
    def rmsdSpreadSubplot(multiplier=1.0, layout=(-1, -1)):
        rmsd_data   = dict( (e, rad_data[e]['innov'][quant])  for e in rad_data.iterkeys() )
        spread_data = dict( (e, rad_data[e]['spread'][quant]) for e in rad_data.iterkeys() )

        times = temp.getTimes()
        n_t = len(times)

        for exp, exp_name in exp_names.iteritems():
            pylab.plot(sawtooth(times, times)[:(n_t + 1)], rmsd_data[exp][:(n_t + 1)], color=colors[exp], linestyle='-')
            pylab.plot(times[(n_t / 2):], rmsd_data[exp][n_t::2], color=colors[exp], linestyle='-')
 
        for exp, exp_name in exp_names.iteritems():
            pylab.plot(sawtooth(times, times)[:(n_t + 1)], spread_data[exp][:(n_t + 1)], color=colors[exp], linestyle='--')
            pylab.plot(times[(n_t / 2):], spread_data[exp][n_t::2], color=colors[exp], linestyle='--')

        ylim = pylab.ylim()
        pylab.plot(times, -1 * np.ones((len(times),)), color='#999999', linestyle='-', label="RMS Innovation")
        pylab.plot(times, -1 * np.ones((len(times),)), color='#999999', linestyle='--', label="Spread")

        pylab.axhline(y=7, color='k', linestyle=':')
        pylab.axvline(x=14400, color='k', linestyle=':')

        pylab.ylabel("RMS Innovation/Spread (dBZ)", size='large')

        pylab.xlim(times[0], times[-1])
        pylab.ylim(ylim)

        pylab.legend(loc=4)

        pylab.xticks(times[::2], [ "" for t in times[::2] ])
        pylab.yticks(size='x-large')
        return
def correlation_matrix(data, size=8.0):
    """ Calculates and shows the correlation matrix of the pandas data frame
        'data' as a heat map.
        Only the correlations between numerical variables are calculated!
    """
    # calculate the correlation matrix
    corr = data.corr()
    #print corr
    lc = len(corr.columns)
    # set some settings for plottin'
    pl.pcolor(corr, vmin = -1, vmax = 1, edgecolor = "black")
    pl.colorbar()
    pl.xlim([-5,lc])
    pl.ylim([0,lc+5])
    pl.axis('off')
    # anotate the rows and columns with their corresponding variables
    ax = pl.gca()            
    for i in range(0,lc):
        ax.annotate(corr.columns[i], (-0.5, i+0.5), \
            size='large', horizontalalignment='right', verticalalignment='center')
        ax.annotate(corr.columns[i], (i+0.5, lc+0.5),\
            size='large', rotation='vertical',\
            horizontalalignment='center', verticalalignment='right')
    # change the size of the image
    fig = pl.figure(num=1)    
    fig.set_size_inches(size+(size/4), size)     
    
    pl.show()
예제 #13
0
    def InitializePlot(self, goal_config):
        self.fig = pl.figure()
        lower_limits, upper_limits = self.boundary_limits
        pl.xlim([lower_limits[0], upper_limits[0]])
        pl.ylim([lower_limits[1], upper_limits[1]])
        pl.plot(goal_config[0], goal_config[1], 'gx')

        # Show all obstacles in environment
        for b in self.robot.GetEnv().GetBodies():
            if b.GetName() == self.robot.GetName():
                continue
            bb = b.ComputeAABB()
            pl.plot([bb.pos()[0] - bb.extents()[0],
                     bb.pos()[0] + bb.extents()[0],
                     bb.pos()[0] + bb.extents()[0],
                     bb.pos()[0] - bb.extents()[0],
                     bb.pos()[0] - bb.extents()[0]],
                    [bb.pos()[1] - bb.extents()[1],
                     bb.pos()[1] - bb.extents()[1],
                     bb.pos()[1] + bb.extents()[1],
                     bb.pos()[1] + bb.extents()[1],
                     bb.pos()[1] - bb.extents()[1]], 'r')
                    
                     
        pl.ion()
        pl.show()
예제 #14
0
def run(steps=10):
	for i in range(steps):
	    Q.time_step()
	    #Q.plot_links()
	    py.xlim((0,config['XSIZE']))
	    py.ylim((0,config['YSIZE']))
	    py.draw()
예제 #15
0
def plotFeatureImportance(featureImportance, title, originalImage=None, lim=0.06, colorate=None):
    """
    originalImage : the index of the original image. If None, ignore
    """
    indices = featureImportanceIndices(len(featureImportance), originalImage)
    pl.figure()
    pl.title(title)
    if colorate is not None:
        nbType = len(colorate)
        X = [[] for i in range(nbType)]
        Y = [[] for i in range(nbType)]
        for j, f in enumerate(featureImportance):
            X[j % nbType].append(j)
            Y[j % nbType].append(f)
        for i in range(nbType):
            pl.bar(X[i], Y[i], align="center", label=colorate[i][0], color=colorate[i][1])
        pl.legend()
    else:
        pl.bar(range(len(featureImportance)), featureImportance, align="center")
    #pl.xticks(pl.arange(len(indices)), indices, rotation=-90)
    pl.xlim([-1, len(indices)])
    pl.ylabel("Feature importance")
    pl.xlabel("Filter indices")
    pl.ylim(0, lim)
    pl.show()
예제 #16
0
파일: plot_shear.py 프로젝트: akr89/Thesis
def whiskerplot(shear,dRA=1.,dDEC=1.,scale=5, combine=1, offset=(0,0) ):
    if combine>1:
        s = (combine*int(shear.shape[0]/combine),
             combine*int(shear.shape[1]/combine))
        shear = shear[0:s[0]:combine, 0:s[1]:combine] \
                + shear[1:s[0]:combine, 0:s[1]:combine] \
                + shear[0:s[0]:combine, 1:s[1]:combine] \
                + shear[1:s[0]:combine, 1:s[1]:combine]
        shear *= 0.25

        dRA *= combine
        dDEC *= combine

    
    theta = shear**0.5
    RA = offset[0] + np.arange(shear.shape[0])*dRA
    DEC = offset[1] + np.arange(shear.shape[1])*dDEC

    pylab.quiver(RA,DEC,
                 theta.real.T,theta.imag.T,
                 pivot = 'middle',
                 headwidth = 0,
                 headlength = 0,
                 headaxislength = 0,
                 scale=scale)
    pylab.xlim(0,shear.shape[0]*dRA)
    pylab.ylim(0,shear.shape[1]*dDEC)
    pylab.xlabel('RA (arcmin)')
    pylab.ylabel('DEC (arcmin)')
예제 #17
0
def drunkTest(numTrials = 1000):
    #stepsTaken = [10, 100, 1000, 10000]
    stepsTaken = 1000
    
    for dClass in (UsualDrunk, ColdDrunk, EDrunk, PhotoDrunk, DDrunk):
        #initialize field
        field = Field()
        origin = Location(0, 0)
        
        # initialize drunk 
        drunk = dClass('Drunk')
        field.addDrunk(drunk, origin)

        x_pos, y_pos = [], [] # initialize to empty
        x, y = 0.0, 0.0
        
        for trial in range(numTrials): # trials 
            x, y = walkVector(field, drunk, stepsTaken)
            x_pos.append(x)
            y_pos.append(y)
            
        #pylab.plot(x_pos, y_pos, 'ro', s=5,
        #           label = dClass.__name__)
        pylab.scatter(x_pos, y_pos,s=5, color='red')
        pylab.title(str(dClass))
        pylab.xlabel('x')
        pylab.grid()
        pylab.xlim(-100, 100)
        pylab.ylim(-100,100)
        pylab.ylabel('y')
        pylab.show()
예제 #18
0
    def plotMean(self, Channel, listPops, colors = [], ylabel = "Fluorescence (a.u.)"):
        """
        missing doc
        """

        if type(listPops) != type([]): listPops = [listPops]

        maxf = 0.
        minf = 1.e10
        maxx = 0.0
        minx = -1.0

        for pop in listPops:
            F = np.array( self.getFluorescence(pop, Channel).mean(axis=1) )
            plot.simplePlot( F, fillcolor=self.colors[pop], label = pop )

            if maxf < F.max().max() : maxf = F.max().max()
            if minf > F.min().min() : minf = F.min().min()

            maxx = max(maxx, F.shape[0])


        # setting labels and axes
        pl.xlabel('Time (h)')
        pl.ylabel(ylabel)
        pl.ylim(0.3*minf, 1.2*maxf)
        pl.xlim(minx, maxx)

        #pl.tight_layout()

        return
예제 #19
0
def makeimg(wav):
	global callpath
	global imgpath

	fs, frames = wavfile.read(os.path.join(callpath, wav))
	
	pylab.ion()

	# generate specgram
	pylab.figure(1)
	
	# generate specgram
	pylab.specgram(
		frames,
		NFFT=256, 
		Fs=22050, 
		detrend=pylab.detrend_none,
		window=numpy.hamming(256),
		noverlap=192,
		cmap=pylab.get_cmap('Greys'))
	
	x_width = len(frames)/fs
	
	pylab.ylim([0,11025])
	pylab.xlim([0,round(x_width,3)-0.006])
	
	img_path = os.path.join(imgpath, wav.replace(".wav",".png"))

	pylab.savefig(img_path)
	
	return img_path
def plot_importances(imp, clfName, obj):
    imp=np.vstack(imp)
    print imp
    mean_importance = np.mean(imp,axis=0)
    std_importance = np.std(imp,axis=0)
    indices = np.argsort(mean_importance)[::-1]
    print indices
    print featureNames
    featureList = []
    # num_features = len(featureNames)
    print("Feature ranking:")
    for f in range(num_features):
        featureList.append(featureNames[indices[f]])
        print("%d. feature %s (%.2f)" % (f, featureNames[indices[f]], mean_importance[indices[f]]))
    fig = pl.figure(figsize=(8,6),dpi=150)
    pl.title("Feature importances",fontsize=30)
    pl.bar(range(num_features), mean_importance[indices],
            yerr = std_importance[indices], color=paired[0], align="center",
            edgecolor=paired[0],ecolor=paired[1])
    pl.xticks(range(num_features), featureList, size=15,rotation=90)
    pl.ylabel("Importance",size=30)
    pl.yticks(size=20)
    pl.xlim([-1, num_features])
    # fix_axes()
    pl.tight_layout()
    save_path = 'plots/'+obj+'/'+clfName+'_feature_importances.pdf'
    fig.savefig(save_path)
def plotCoeff(X, y, obj, featureNames, whichReg):
    """ Plot Regression's Coeff
    """
    clf = classifiers[whichReg]
    clf,_,_ = fitAlgo(clf, X,y, opt= True, param_dict = param_dist_dict[whichReg])
    if whichReg == "LogisticRegression":
    	coeff = np.absolute(clf.coef_[0])
    else:
    	coeff = np.absolute(clf.coef_)
    print coeff
    indices = np.argsort(coeff)[::-1]
    print indices
    print featureNames
    featureList = []
    # num_features = len(featureNames)
    print("Feature ranking:")
    for f in range(num_features):
        featureList.append(featureNames[indices[f]])
        print("%d. feature %s (%.2f)" % (f, featureNames[indices[f]], coeff[indices[f]]))
    fig = pl.figure(figsize=(8,6),dpi=150)
    pl.title("Feature importances",fontsize=30)
    # pl.bar(range(num_features), coeff[indices],
    #         yerr = std_importance[indices], color=paired[0], align="center",
    #         edgecolor=paired[0],ecolor=paired[1])
    pl.bar(range(num_features), coeff[indices], color=paired[0], align="center",
            edgecolor=paired[0],ecolor=paired[1])
    pl.xticks(range(num_features), featureList, size=15,rotation=90)
    pl.ylabel("Importance",size=30)
    pl.yticks(size=20)
    pl.xlim([-1, num_features])
    # fix_axes()
    pl.tight_layout()
    save_path = 'plots/'+obj+'/'+whichReg+'_feature_importances.pdf'
    fig.savefig(save_path)
    def InitializePlot(self, goal_config):  # default
        self.fig = pl.figure()
        pl.xlim([self.lower_limits[0], self.upper_limits[0]])
        pl.ylim([self.lower_limits[1], self.upper_limits[1]])
        pl.plot(goal_config[0], goal_config[1], "gx")

        # Show all obstacles in environment
        for b in self.robot.GetEnv().GetBodies():
            if b.GetName() == self.robot.GetName():
                continue
            bb = b.ComputeAABB()
            pl.plot(
                [
                    bb.pos()[0] - bb.extents()[0],
                    bb.pos()[0] + bb.extents()[0],
                    bb.pos()[0] + bb.extents()[0],
                    bb.pos()[0] - bb.extents()[0],
                    bb.pos()[0] - bb.extents()[0],
                ],
                [
                    bb.pos()[1] - bb.extents()[1],
                    bb.pos()[1] - bb.extents()[1],
                    bb.pos()[1] + bb.extents()[1],
                    bb.pos()[1] + bb.extents()[1],
                    bb.pos()[1] - bb.extents()[1],
                ],
                "r",
            )

        pl.ion()
        pl.show()
예제 #23
0
    def updatePlot(self):
        """ Updates the antenna config plot"""
                
        self.sp_ax.clear()
        self.sp_fig.clear()
        
        row = self.slider.value()
        self.spinner.setValue(row)
        
        data_x    = self.fits_data[row,0,0,0,:]
        data_y    = self.fits_data[row,0,0,1,:]
        flagged_x = self.fits_flagged[row,0,0,0,:]
        flagged_y = self.fits_flagged[row,0,0,1,:]        
        freqs     = self.fits_freqs
        tsys      = self.fits_tsys[row,:]
        
        #plt.plot(freqs, data_x)
        plt.plot(freqs[flagged_x == 0], data_x[flagged_x == 0], color='#333333', label='Pol A [%2.1f Jy]'%tsys[0])  
        plt.plot(freqs[flagged_y == 0], data_y[flagged_y == 0], color='#CC0000', label='Pol B [%2.1f Jy]'%tsys[1])         
        
        
        plt.ylabel('%s [%s]'%(self.fits_data_name, self.fits_data_unit))
        plt.xlabel('%s [%s]'%(self.fits_freq_type, self.fits_freq_unit))
        plt.title('Beam %s: %s %s'%(self.fits_beam[row], self.fits_date[row], self.fits_time[row]))
        plt.xlim(np.min(freqs[flagged_x == 0]), np.max(freqs[flagged_x == 0]))
        plt.legend()
        plt.show()

        
        self.sp_fig.canvas.draw()
              
        self.lab_info.setText(self.fits_filename)       
예제 #24
0
def plot_file_color(base, thin=True, start=0, size=14, save=False):
    conf, track, pegs = load(base)

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

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

    #pl.scatter(x, y, c=np.arange(len(x)),linestyle='-',cmap=pl.cm.coolwarm)
    #pl.plot(track[-1000000:,0], track[-1000000:,1], '-', linewidth=0.0125, alpha=0.8)
    for peg in pegs:
        pl.gca().add_artist(pl.Circle(peg, conf['radius'], color='k', alpha=0.3))
    pl.xlim(0, conf['wall'])
    pl.ylim(0, conf['top'])
    pl.xticks([])
    pl.yticks([])
    pl.tight_layout()
    pl.show()
    if save:
        pl.savefig(base+".png", dpi=200)
예제 #25
0
def tracks_movie(base, skip=1, frames=500, size=10):
    """
    A movie of each particle as a point
    """
    conf, track, pegs = load(base)

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

    for t in xrange(1,max(frames, track.shape[1]/skip)):
        tmp = track[:,t*skip,:]
        if not ((tmp[:,0] > 0) & (tmp[:,1] > 0) & (tmp[:,0] < conf['wall']) & (tmp[:,1] < conf['top'])).any():
            continue

        if plot is None:
            plot = pl.plot(tmp[:,0], tmp[:,1], 'k,', alpha=1.0, ms=0.1)[0]
            pl.xticks([])
            pl.yticks([])
            pl.xlim(0,conf['wall'])
            pl.ylim(0,conf['top'])
            pl.tight_layout()
        else:
            plot.set_xdata(tmp[:,0])
            plot.set_ydata(tmp[:,1])
        pl.draw()
        pl.savefig(base+'-movie-%05d.png' % (t-1))
예제 #26
0
파일: VOI.py 프로젝트: toscanosaul/SBO
    def plotVOI(self,n,points,L,data,kern,temp1,temp2,a,m,path):
        z=np.zeros(m)
        
        for i in xrange(m):
            z[i]=self.VOIfunc(n,points[i,:],L,data,kern,temp1,temp2,False,a,False)
            
        fig=plt.figure()
        fig.set_size_inches(21, 21)
        plt.plot(points,z,'-')
        plt.xlabel('x',fontsize=60)
        Xp=data.Xhist[0:self._numberTraining,0]
        pylab.plot(Xp,np.zeros(len(Xp))+0.00009,'o',color='red',markersize=40,label="Training point")
        if n>0:
            Xp=data.Xhist[self._numberTraining:self._numberTraining+n,0]
            pylab.plot(Xp,np.zeros(len(Xp))+0.00009,'o',color='firebrick',markersize=40,label="Chosen point")
        ax = plt.subplot(111)
        box = ax.get_position()
        ax.set_position([box.x0, box.y0+box.height*0.1, box.width, box.height*0.9])

        # Put a legend to the right of the current axis
        ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.09),ncol=2,fontsize=50)
        
        pylab.xlim([-0.5,0.5])
      #  plt.legend()
        plt.savefig(os.path.join(path,'%d'%n+"VOI_n.pdf"))
        plt.close(fig)
예제 #27
0
파일: sgt.py 프로젝트: panand/Ling248_2016
def plotFreqVsGoodTuring(counts, confidence=1.96, loglog=False):
    """
    Draws a scatterplot of the empirical frequencies of the counted species
    versus their Simple Good Turing smoothed values, in rank order. Depends on
    pylab and matplotlib.
    """
    import pylab
    from matplotlib import rc

    tot = float(sum(counts.values()))
    freqs = dict([(species, cnt/tot) for species, cnt in counts.iteritems()])
    sgt, p0 = simpleGoodTuringProbs(counts, confidence)

    if loglog:
        plotFunc = pylab.loglog
    else:
        plotFunc = pylab.plot
    plotFunc(sorted(freqs.values(), reverse=True), 'kD', mfc='white',
            label="Observed")
    plotFunc(sorted(sgt.values(), reverse=True), 'k+', 
            label="Simple Good-Turing Estimate")
    pylab.xlim(-0.5, len(freqs)+0.5)
    pylab.xlabel("Rank")
    pylab.ylabel("Frequency")
    pylab.legend(numpoints=1)
예제 #28
0
    def draw(self):

        print self.edgeno

        pos = 0
        dy = 8
        edgeno = self.edgeno
        edge = self.edges[edgeno]
        edgeprev = self.edges[edgeno-1]
        p = np.round(edge["top"](1024))
        top = min(p+2*dy, 2048)
        bot = min(p-2*dy, 2048)
        self.cutout = self.flat[1][bot:top,:].copy()

        pl.figure(1)
        pl.clf()
        start = 0
        dy = 512
        for i in xrange(2048/dy):
            pl.subplot(2048/dy,1,i+1)
            pl.xlim(start, start+dy)

            if i == 0: pl.title("edge %i] %s|%s" % (edgeno,
                edgeprev["Target_Name"], edge["Target_Name"]))


            pl.subplots_adjust(left=.07,right=.99,bottom=.05,top=.95)

            pl.imshow(self.flat[1][bot:top,start:start+dy], extent=(start,
                start+dy, bot, top), cmap='Greys', vmin=2000, vmax=6000)

            pix = np.arange(start, start+dy)
            pl.plot(pix, edge["top"](pix), 'r', linewidth=1)
            pl.plot(pix, edgeprev["bottom"](pix), 'r', linewidth=1)
            pl.plot(edge["xposs_top"], edge["yposs_top"], 'o')
            pl.plot(edgeprev["xposs_bot"], edgeprev["yposs_bot"], 'o')


            hpp = edge["hpps"]
            pl.axvline(hpp[0],ymax=.5, color='blue', linewidth=5)
            pl.axvline(hpp[1],ymax=.5, color='red', linewidth=5)

            hpp = edgeprev["hpps"]
            pl.axvline(hpp[0],ymin=.5,color='blue', linewidth=5)
            pl.axvline(hpp[1],ymin=.5,color='red', linewidth=5)


            if False:
                L = top-bot
                Lx = len(edge["xposs"])
                for i in xrange(Lx):
                    xp = edge["xposs"][i]
                    frac1 = (edge["top"](xp)-bot-1)/L
                    pl.axvline(xp,ymin=frac1)

                for xp in edgeprev["xposs"]: 
                    frac2 = (edgeprev["bottom"](xp)-bot)/L
                    pl.axvline(xp,ymax=frac2)

            start += dy
def plot_prob_effector(sens, fpr, xmax=1, baserate=0.1):
    """Plots a line graph of P(effector|positive test) against
    the baserate of effectors in the input set to the classifier.
        
    The baserate argument draws an annotation arrow
    indicating P(pos|+ve) at that baserate
    """
    assert 0.1 <= xmax <= 1, "Max x axis value must be in range [0,1]"
    assert 0.01 <= baserate <= 1, "Baserate annotation must be in range [0,1]"
    baserates = pylab.arange(0, 1.05, xmax * 0.005)  
    probs = [p_correct_given_pos(sens, fpr, b) for b in baserates]
    pylab.plot(baserates, probs, 'r')
    pylab.title("P(eff|pos) vs baserate; sens: %.2f, fpr: %.2f" % (sens, fpr))
    pylab.ylabel("P(effector|positive)")
    pylab.xlabel("effector baserate")
    pylab.xlim(0, xmax)
    pylab.ylim(0, 1)
    # Add annotation arrow
    xpos, ypos = (baserate, p_correct_given_pos(sens, fpr, baserate))
    if baserate < xmax:
        if xpos > 0.7 * xmax:
            xtextpos = 0.05 * xmax
        else:
            xtextpos = xpos + (xmax-xpos)/5.
        if ypos > 0.5:
            ytextpos = ypos - 0.05
        else:
            ytextpos = ypos + 0.05
        pylab.annotate('baserate: %.2f, P(pos|+ve): %.3f' % (xpos, ypos), 
                       xy=(xpos, ypos), 
                       xytext=(xtextpos, ytextpos),
                       arrowprops=dict(facecolor='black', shrink=0.05))
    else:
        pylab.text(0.05 * xmax, 0.95, 'baserate: %.2f, P(pos|+ve): %.3f' % \
                   (xpos, ypos))
예제 #30
0
def plot_spectrum():
    #get the data...    
    a_0=struct.unpack('>1024l',fpga.read('even',1024*4,0))
    a_1=struct.unpack('>1024l',fpga.read('odd',1024*4,0))

    interleave_a=[]

    for i in range(1024):
        interleave_a.append(a_0[i])
        interleave_a.append(a_1[i])

    pylab.figure(num=1,figsize=(10,10))
    pylab.ioff()
    pylab.plot(interleave_a)
    #pylab.semilogy(interleave_a)
    pylab.title('Integration number %i.'%prev_integration)
    pylab.ylabel('Power (arbitrary units)')
    pylab.grid()
    pylab.xlabel('Channel')
    pylab.xlim(0,2048)
    pylab.ioff()

    pylab.hold(False)
    pylab.show()
    pylab.draw()
        NETarr_sus140 / NETarr_sus140[0],
        '-',
        label='140GHz')
py.plot(hwp_temperature_arr,
        NETarr_sus166 / NETarr_sus166[0],
        '-',
        label='166GHz')
py.plot(hwp_temperature_arr,
        NETarr_sus195 / NETarr_sus195[0],
        '-',
        label='195GHz')
py.plot(hwp_temperature_arr,
        NETarr_sus235 / NETarr_sus235[0],
        '-',
        label='235GHz')
py.xlim([1, 35])
py.ylim([0.9, 2])
#py.xlabel('Temperature [K]',fontsize=17)
py.ylabel('$NET_{\\nu}(T)/NET(5K)$', fontsize=17)
py.xticks(color='k', size=17)
py.yticks(color='k', size=17)
#py.legend(loc='best')

py.subplot(212)
py.plot(hwp_temperature_arr,
        NETarr_sus280 / NETarr_sus280[0],
        '-',
        label='280GHz')
py.plot(hwp_temperature_arr,
        NETarr_sus337 / NETarr_sus337[0],
        '-',
def derive_wifes_calibration(cube_fn_list,
                             calib_out_fn,
                             stdstar_name_list=None,
                             extract_in_list=None,
                             airmass_list=None,
                             ref_dir=metadata_dir,
                             ref_fname_list=None,
                             plot_stars=False,
                             plot_sensf=False,
                             norm_stars=False,
                             method='poly',
                             polydeg=30,
                             excise_cut=0.5,
                             wave_min=None,
                             wave_max=None,
                             extinction_fn=None,
                             ytrim=5):
    if plot_stars or plot_sensf:
        import pylab
    # get extinction curve
    if extinction_fn == None:
        extinct_interp = sso_extinct_interp
    else:
        ext_data = numpy.loadtxt(extinction_fn)
        extinct_interp = scipy.interpolate.interp1d(ext_data[:, 0],
                                                    ext_data[:, 1],
                                                    bounds_error=False,
                                                    fill_value=numpy.nan)
    # first extract stdstar spectra and compare to reference
    fratio_results = []
    for i in range(len(cube_fn_list)):
        f = pyfits.open(cube_fn_list[i])
        cube_hdr = f[1].header
        f.close()
        #------------------------------------
        # figure out which star it is
        # NEW VERSION 0.7.0: smart star name lookup!
        #
        # top priority: user forces the name
        if stdstar_name_list != None:
            star_name = stdstar_name_list[i]
            # if you forced an unknown star name, reset name to None
            if star_name not in ref_fname_lookup.keys():
                star_name = None
        else:
            star_name = None
        # try to find the nearest standard in the list
        if star_name == None:
            try:
                star_name, dist = find_nearest_stdstar(cube_fn_list[i])
                if dist > 200.0:
                    star_name = None
            except:
                # last resort: use the object name from the fits header
                # and pray it's correct
                star_name = cube_hdr['OBJECT']
        #------------------------------------
        #print star_name
        if airmass_list != None:
            secz = airmass_list[i]
        else:
            try:
                secz = cube_hdr['AIRMASS']
            except:
                print 'AIRMASS header missing for %s' % cube_fn_list[i].split(
                    '/')[-1]
                secz = 1.0
        # check if there is a calib spectrum...
        if ref_fname_list != None:
            ref_fname = ref_name_list[i]
        elif star_name in ref_fname_lookup.keys():
            ref_fname = ref_fname_lookup[star_name]
        else:
            continue
        # get observed data
        if extract_in_list == None:
            obs_wave, obs_flux = extract_wifes_stdstar(cube_fn_list[i],
                                                       ytrim=ytrim)
        else:
            ex_data = numpy.loadtxt(extract_in_list[i])
            obs_wave = ex_data[:, 0]
            obs_flux = ex_data[:, 1]
        if wave_min == None:
            wave_min = numpy.min(obs_wave)
        if wave_max == None:
            wave_max = numpy.max(obs_wave)
        # get reference data
        ref_data = numpy.loadtxt(ref_dir + ref_fname)
        ref_interp = scipy.interpolate.interp1d(ref_data[:, 0],
                                                ref_data[:, 1],
                                                bounds_error=False,
                                                fill_value=numpy.nan)
        ref_flux = ref_interp(obs_wave)
        std_ext = extinct_interp(obs_wave)
        good_inds = numpy.nonzero(
            (ref_flux == ref_flux) * (std_ext == std_ext) *
            (obs_wave >= wave_min) * (obs_wave <= wave_max) *
            (obs_flux > 0.0))[0]
        init_flux_ratio = -2.5 * numpy.log10(
            obs_flux[good_inds] / ref_flux[good_inds])
        flux_ratio = init_flux_ratio + (secz - 1.0) * std_ext[good_inds]
        fratio_results.append([obs_wave[good_inds], init_flux_ratio])
        if plot_stars:
            scaled_flux = obs_flux[good_inds] / numpy.mean(
                10.0**(-0.4 * flux_ratio))
            pylab.figure()
            pylab.plot(obs_wave,
                       ref_flux,
                       color='b',
                       label='Reference star flux')
            pylab.plot(obs_wave[good_inds],
                       scaled_flux,
                       color='r',
                       label='Scaled observed flux')
            pylab.title(star_name)
            pylab.xlabel(r'Wavelength [$\AA$]')
            pylab.legend(loc='lower right', fancybox=True, shadow=True)
    # from all comparisons, derive a calibration solution
    # EVENTUALLY WILL FIT AN EXTINCTION TERM TOO
    if norm_stars:
        i_mid = len(fratio_results[0][0]) / 2
        fscale_max = min([x[1][i_mid] for x in fratio_results])
        init_full_y = numpy.concatenate(
            [x[1] - x[1][i_mid] + fscale_max for x in fratio_results])
    else:
        init_full_y = numpy.concatenate([x[1] for x in fratio_results])
    init_full_x = numpy.concatenate([x[0] for x in fratio_results])
    init_good_inds = numpy.nonzero(
        (init_full_y == init_full_y) *
        (init_full_y < numpy.median(init_full_y) + 20.0) *
        (strong_telluric_mask(init_full_x)) * (halpha_mask(init_full_x)))[0]
    # do a first fit
    next_full_y = init_full_y[init_good_inds]
    next_full_x = init_full_x[init_good_inds]
    sort_order = next_full_x.argsort()
    temp_full_x = next_full_x[sort_order]
    temp_full_y = next_full_y[sort_order]
    # ----------- Fred's update 3 -------------------
    if method == 'smooth_SG':
        # Savitzky-Golay requires continuous data. ->need to fill the 'holes'
        # It is a problem for red spectra (at this point at least)
        # Check if there are gaps (telluric, Halpha, etc ...)
        init_bad_inds = \
            numpy.nonzero(1-
                          ((init_full_y == init_full_y)*
                           (init_full_y < numpy.median(init_full_y)+20.0)*
                           (telluric_mask(init_full_x))*
                           (halpha_mask(init_full_x))))[0]
        if len(init_bad_inds) > 0:
            # if yes, first fit a polynomial, then use it to 'fill the gaps.
            temp_calib = numpy.polyfit(temp_full_x, temp_full_y, polydeg)
            temp_fvals = numpy.polyval(temp_calib, init_full_x)
            init_full_y[init_bad_inds] = temp_fvals[init_bad_inds]
            temp_full_y = init_full_y  # to ensure this case is then compatible
            temp_full_x = init_full_x
            # Fails if multiple stars ... need to order the array !
            this_sort_order = temp_full_x.argsort()
            temp_full_x = temp_full_x[this_sort_order]
            temp_full_y = temp_full_y[this_sort_order]
        # Then fit SG normally
        temp_fvals = savitzky_golay(temp_full_y, 101, 1, 0)
        excise_cut = 0.003
    else:
        temp_best_calib = numpy.polyfit(temp_full_x, temp_full_y, polydeg)
        temp_fvals = numpy.polyval(temp_best_calib, temp_full_x)
    # excise outliers
    final_good_inds = numpy.nonzero(
        numpy.abs(temp_fvals - temp_full_y) /
        numpy.abs(temp_fvals) < excise_cut)[0]
    full_x = temp_full_x[final_good_inds]
    full_y = temp_full_y[final_good_inds]
    # ------------ Fred's update 3 ----------------
    if method == 'smooth_SG':  # Fails if multiple stars ... need to order the array !
        this_sort_order = full_x.argsort()
        full_x = full_x[this_sort_order]
        full_y = full_y[this_sort_order]
        final_fvals = savitzky_golay(full_y, 101, 1, 0)
        this_f = scipy.interpolate.interp1d(full_x,
                                            final_fvals,
                                            bounds_error=False,
                                            kind='linear')
        all_final_fvals = this_f(init_full_x)
        final_x = full_x
        final_y = full_y
    else:
        best_calib = numpy.polyfit(full_x, full_y, polydeg)
        final_fvals = numpy.polyval(best_calib, full_x)
        final_x = numpy.arange(
            numpy.min(full_x), 1.000001 * numpy.max(full_x),
            0.0001 * (numpy.max(full_x) - numpy.min(full_x)))
        final_y = numpy.polyval(best_calib, final_x)
    # plot if requested
    if plot_sensf:
        pylab.figure()
        # MC update - raw fit on top
        pylab.axes([0.10, 0.35, 0.85, 0.60])
        pylab.plot(temp_full_x,
                   temp_full_y,
                   'r.',
                   markerfacecolor='none',
                   markeredgecolor='r',
                   label='Raw sensitivity (initial regions)')
        pylab.plot(full_x,
                   full_y,
                   color='b',
                   label='Raw sensitivity (valid regions)')
        pylab.plot(temp_full_x,
                   temp_fvals,
                   color=r'#FF6103',
                   lw=2,
                   label='Initial fit')
        if method == 'smooth_SG':
            pylab.plot(init_full_x,
                       all_final_fvals,
                       color=r'#00FF00',
                       lw=2,
                       label='Final fit')
        else:
            pylab.plot(full_x,
                       final_fvals,
                       color=r'#00FF00',
                       lw=2,
                       label='Final fit')
        #pylab.hlines(-37.5,numpy.min(full_x),numpy.max(full_x), 'k')
        pylab.xlim([numpy.min(full_x), numpy.max(full_x)])
        curr_ylim = pylab.ylim()
        curr_xlim = pylab.xlim()
        pylab.ylim(curr_ylim[::-1])
        pylab.title('Derived sensitivity function')
        pylab.legend(loc='lower right', fancybox=True, shadow=True)
        # lower plot - residuals!
        pylab.axes([0.10, 0.10, 0.85, 0.25])
        pylab.plot(full_x,
                   full_y - final_fvals,
                   'k.',
                   mec=r'#666666',
                   markerfacecolor='none',
                   label='Residuals')
        pylab.axhline(0.0, color='k')
        pylab.xlim(curr_xlim)
        pylab.ylim([-0.2, 0.2])
        pylab.xlabel(r'Wavelength [$\AA$]')
        pylab.ylabel('Residuals')
    if plot_stars or plot_sensf:
        pylab.show()
    # Fred's update ... now, careful, because that's dirty ...
    # the function does not always return the same thing !
    # SAVE IN THE PICKLE FILE THE WAVELENGTH AND CALIB FVAL ARRAYS
    save_calib = {'wave': final_x, 'cal': final_y}
    f1 = open(calib_out_fn, 'w')
    pickle.dump(save_calib, f1)
    f1.close()
    return
예제 #33
0
fp.close()

layers=['l23','l4']
colors={'pyr':'r','pv':'b'}
celltypes=['pyr','pv']
sub_fig_num=len(layers)

pylab.figure(1)
for xi, xin in enumerate(layers):
    pylab.subplot(sub_fig_num,1,xi+1)
    if xi==0:
        pylab.title('V1_1')
    for yin in celltypes:
        spks=spikes['V1_1'+xin+yin]
        pylab.scatter(spks[0],spks[1],c=colors[yin], s=5, edgecolors='none')
        pylab.xlim([0.0,simtime])
    pylab.ylabel(xin)

pylab.savefig('../figs/zoom_raster_pref'+str(top_down_pyr)+'_'+str(top_down_pv)+'_'+str(msd)+'_'+str(fraction)+'_'+sim_len+'.eps')

pylab.figure(2)

for xi, xin in enumerate(layers):
    pylab.subplot(sub_fig_num,1,xi+1)
    if xi==0:
        pylab.title('V1_2')
    for yin in celltypes:
        spks=spikes['V1_2'+xin+yin]
        pylab.scatter(spks[0],spks[1],c=colors[yin], s=5, edgecolors='none')
        pylab.xlim([0.0,simtime])
    pylab.ylabel(xin)
예제 #34
0
import pylab as plt
from roadprofile import *
from scipy.signal import periodogram
testprofile = RoadProfile()
profile = testprofile.get_profile_by_class("A", 100, 0.1)
plt.loglog(*periodogram(profile[1], fs=10))
plt.xlabel("Spatial frequency")
plt.ylabel("PSD")
plt.grid("on")
plt.ylim([1E-8, 0.01])
plt.xlim([0.01, 5])
plt.show()
    pylab.loglog(cl[:, 0], cl[:, 1 + i], spec[i], lw=2, label=str(label[i]))

for i in range(len(cl)):
    covariance = linalg.inv(inverse[i * 6:(i + 1) * 6, :])
    #	print linalg.eigh(covariance*1e25,eigvals_only=True)
    delta = numpy.random.multivariate_normal(cl[i, 1:7], covariance)
    cl[i, 1:7] = delta
#	print i,cl[i,1:7]
numpy.savetxt(filename2, cl)

#c1 = 'cp %s %s'%(filename1,filename1+'temp')
#c2 = 'cp %s %s'%(filename2,filename2+'temp')
#c3 = 'mv %s %s'%(filename2+'temp',filename1)
#c4 = 'mv %s %s'%(filename1+'temp',filename2)

#subprocess.call(c1,shell=True)
#subprocess.call(c2,shell=True)
#subprocess.call(c3,shell=True)
#subprocess.call(c4,shell=True)

for i in range(6):
    pylab.loglog(cl[:, 0], cl[:, 1 + i], '--' + spec[i], lw=2)

pylab.legend(loc=3, fontsize=18)
pylab.xlabel('$\mathtt{\ell}$', fontsize=22)
pylab.ylabel('$\mathtt{C_{\ell}}$', fontsize=22)
pylab.xlim(min(cl[:, 0]), max(cl[:, 0]))
pylab.ylim(ymax=2e-7)
pylab.savefig(filename2.replace('txt', 'eps'))
pylab.show()
예제 #36
0
 def plotAgainstTime(self, pend=-1):
     plt.figure()
     plt.xlim([-0.05, self.t])
     plt.plot(self.allCoords[pend, :, -1], self.allCoords[pend, :, 0])
     plt.show()
예제 #37
0
def J(m, x):
    s = f(m, x, a) + f(m, x, b)
    for i in range(1, N):
        theta = a + i * h
        if i % 2 == 1:
            s += 4 * f(m, x, theta)
        else:
            s += 2 * f(m, x, theta)
    return (s*h/3)

xpoints = []
ypoints0 = []
ypoints1 = []
ypoints2 = []

for x in linspace(0,20,1000):
    xpoints.append(x)
    ypoints0.append(J(0,x))
    ypoints1.append(J(1,x))
    ypoints2.append(J(2,x))
    
xlim(0,20)
ylim(-1,1)
plot(xpoints,ypoints0,"k-",label="m=0")
plot(xpoints,ypoints1,"k--",label="m=1")
plot(xpoints,ypoints2,"ko",label="m=2")
legend(loc = 'best')
xlabel('x')
ylabel('J(m,x)')
title('Plot of Bessel functions')
show()
예제 #38
0
파일: EMD.py 프로젝트: yanpan2017/PyEMD
    print("Input S.dtype: " + str(S.dtype))

    # Prepare and run EMD
    emd = EMD()
    emd.FIXE_H = 5
    emd.nbsym = 2
    emd.spline_kind = 'cubic'
    emd.DTYPE = DTYPE

    nIMF = emd.emd(S, T, max_imf)
    imfNo = nIMF.shape[0]

    # Plot results
    c = 1
    r = np.ceil((imfNo + 1) / c)

    plt.ioff()
    plt.subplot(r, c, 1)
    plt.plot(T, S, 'r')
    plt.xlim((tMin, tMax))
    plt.title("Original signal")

    for num in range(imfNo):
        plt.subplot(r, c, num + 2)
        plt.plot(T, nIMF[num], 'g')
        plt.xlim((tMin, tMax))
        plt.ylabel("Imf " + str(num + 1))

    plt.tight_layout()
    plt.show()
예제 #39
0
# did the user request an x-axis limit below the maximum death value found in the input?
if xLimit < maxDeath:
    print 'Requested xLimit (' + str(
        xLimit) + ') value is lower than max death value (' + str(
            maxDeath) + ')...aborting'
    sys.exit()

# are there more dimensions in the data then we have colors for?
if len(colorPalette) < np.max(rawData[:, 0]):
    print 'The current colormap has insufficient colors to represent all the dimensions in the data...aborting'
    sys.exit()

# build barcode plot

pylab.grid(True, which='both')
pylab.xlim(-.025, xLimit + .025)
pylab.xlabel('Time')
pylab.ylabel('Index')

for i in range(len(rawData)):
    mpl.pyplot.hlines(i + 1,
                      rawData[i, 1],
                      rawData[i, 2],
                      colors=colorPalette[int(rawData[i, 0])])

# build the legend
dimensions = []
for i in range(int(np.max(rawData[:, 0])) + 1):
    dimensions.append(
        mpl.patches.Patch(color=colorPalette[i], label=r'$H_{}$'.format(i)))
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 29 21:03:22 2017

@author: XMKZ
"""

import numpy
import pylab as py
N=1000
delta=0.01
Time=0
a=15
b=0.015
x=[0]
y=[0]
while Time<=0.999:
    Time=Time+delta
    N=N+(a*N-b*N**2)*delta
    x.append(Time)
    y.append(N)
else:
    plot=py.plot(x,y,'.',label='N')
    py.title('model')
    py.xlabel('Time')
    py.ylabel('N')
    py.xlim(0,1)
    py.ylim(0,2000)
    py.legend(loc='best')
    py.show()
예제 #41
0
threshold = 2.5
T_obs, clusters, cluster_p_values, H0 = \
                   permutation_cluster_1samp_test(epochs_power,
                               n_permutations=100, threshold=threshold, tail=0)

###############################################################################
# View time-frequency plots
import pylab as pl
pl.clf()
pl.subplots_adjust(0.12, 0.08, 0.96, 0.94, 0.2, 0.43)
pl.subplot(2, 1, 1)
pl.plot(times, evoked_data.T)
pl.title('Evoked response (%s)' % ch_name)
pl.xlabel('time (ms)')
pl.ylabel('Magnetic Field (fT/cm)')
pl.xlim(times[0], times[-1])
pl.ylim(-100, 250)

pl.subplot(2, 1, 2)

# Create new stats image with only significant clusters
T_obs_plot = np.nan * np.ones_like(T_obs)
for c, p_val in zip(clusters, cluster_p_values):
    if p_val <= 0.05:
        T_obs_plot[c] = T_obs[c]

vmax = np.max(np.abs(T_obs))
vmin = -vmax
pl.imshow(T_obs,
          cmap=pl.cm.gray,
          extent=[times[0], times[-1], frequencies[0], frequencies[-1]],
예제 #42
0
                          extent=[x_min, x_max, y_min, y_max],
                          cmap=pl.cm.gnuplot,
                          origin='lower')
    levels[f] = contours.levels
    pl.clabel(contours, inline=1, fmt=super_fmt, fontsize=14)

    pl.plot(all_x_i, all_y_i, 'b-', linewidth=2)
    pl.plot(all_x_i, all_y_i, 'k+')

    pl.plot(logging_f.all_x_i, logging_f.all_y_i, 'k.', markersize=2)

    pl.plot([0], [0], 'rx', markersize=12)

    pl.xticks(())
    pl.yticks(())
    pl.xlim(x_min, x_max)
    pl.ylim(y_min, y_max)
    pl.draw()

    pl.figure(index + 100, figsize=(4, 3))
    pl.clf()
    pl.semilogy(np.maximum(np.abs(all_f_i), 1e-30),
                linewidth=2,
                label='# iterations')
    pl.ylabel('Error on f(x)')
    pl.semilogy(logging_f.counts,
                np.maximum(np.abs(logging_f.all_f_i), 1e-30),
                linewidth=2,
                color='g',
                label='# function calls')
    pl.legend(loc='upper right',
예제 #43
0
        plt.hlines(y, vis, ini, lw=3, color=cm.Dark2(y / (maxy + 5)))

    if ii > maxy: break
    else: ii += 1

labels = ['%s (%2.1f)' % (wt.name, wt.mag) for wt in worthy_targets[0:maxy]]

ax.set_yticklabels(labels)

ax.set_ylim(-0.5, maxy - 0.5)

# convert epoch to matplotlib float format
labels = np.linspace(minute_ini, minute_end + 1,
                     12) * 60. + const.timestamp_2018_01_01

plt.xlim([minute_ini, minute_end + 1])
ax.xaxis.set_major_locator(MultipleLocator((minute_end - minute_ini + 1) / 11))

# to human readable date
pre = map(time.gmtime, labels)
labels = map(figures.format_second, pre)

ax.set_xticklabels(labels)
fig.autofmt_xdate()

if save:
    threshold_obs_time -= t_acquisition
    if SAA: note = '_SAA'
    else: note = ''
    fname = '%svisibility_stars_obs_%d_o_%d_to_%d%s' % (
        folder_figures, threshold_obs_time, fo, lo, note)
예제 #44
0
x4 = gl.addSpecies ('X4', 0, False)

rxa1 = gl.addFirstOrderReaction (x1, 0.1)
gl.addProduct (rxa1, x2, 1)

rxa2 = gl.addFirstOrderReaction (x2, 0.65)
gl.addProduct (rxa2, x3, 1)

rxa3 = gl.addFirstOrderReaction (x3, 0.2)
gl.addProduct (rxa3, x4, 1)

#r = gl.setSeedUsingTime()
gl.setSeed (1503793684)

pylab.figure(figsize=(8,5)) 
pylab.xlim((0, 200))

m1 = gl.executeOnGrid (0, 100, 100)
gl.setRateConstant (rxa1, 0.2)
m2 = gl.executeOnGrid (100, 200, 100)  
 
m3 = np.vstack ((m1, m2))

pylab.plot (m3[:,0], m3[:,1], color='r', label='$x_2$')
pylab.plot (m3[:,0], m3[:,2], color='b', label='$x_3$')

pylab.xlabel ('Time')
pylab.legend()
pylab.savefig ('eventExample.pdf')

gl.free()
예제 #45
0
    def normalized_plot(what,
                        alphaGammaName,
                        N=1000,
                        stride=50,
                        aHi=[],
                        legendAlpha=.5):
        '''
		Create normalized plot as it appears in :cite:`Maugis1992` including range of axes with normalized quantities. This function is mainly useful for documentation of Woo itself.

		:param what: one of ``a(delta)``, ``F(delta)``, ``a(F)``
		:param alphaGammaName: list of (alpha,gamma,name) tuples which are passed to the :obj:`SchwarzModel` constructor
		:param N: numer of points in linspace for each axis
		:param stride: stride for plotting inverse relationships (with points)
		:param aHi: with ``what==a(delta)``, show upper bracket for $a$ for i-th model, if *i* appears in the list
		'''
        assert what in ('a(delta)', 'F(delta)', 'a(F)')
        import pylab
        invKw = dict(linewidth=4, alpha=.3)
        kw = dict(linewidth=2)
        pylab.figure()
        for i, (alpha, gamma, name) in enumerate(alphaGammaName):
            m = SchwarzModel.makeDefault(alpha=alpha, gamma=gamma, name=name)
            if what == 'a(delta)':
                ddHat = numpy.linspace(-1.3, 2., num=N)
                aaHat = numpy.linspace(0, 2.1, num=N)
                pylab.plot(m.deltaHat_aHat(aaHat),
                           aaHat,
                           label='$\\alpha$=%g %s' % (m.alpha, m.name),
                           **kw)
                ddH = m.deltaHat_aHat(aaHat)
                if i in aHi:
                    pylab.plot(
                        ddH, [m.aHat(m.aHi(m.deltaUnhat(dh))) for dh in ddH],
                        label='$\\alpha$=%g $a_{\mathrm{hi}}$' % m.alpha,
                        linewidth=1,
                        alpha=.4)
                pylab.plot(ddHat[::stride],
                           m.aHat_deltaHat(ddHat[::stride], loading=True), 'o',
                           **invKw)
                pylab.plot(ddHat[::stride],
                           m.aHat_deltaHat(ddHat[::stride], loading=False),
                           'o', **invKw)
            elif what == 'F(delta)':
                ffHat = numpy.linspace(-2.1, 1.5, num=N)
                ddHat = numpy.linspace(-1.3, 2., num=N)
                pylab.plot(ddHat,
                           m.fHat_aHat(m.aHat_deltaHat(ddHat)),
                           label='$\\alpha$=%g %s' % (m.alpha, m.name),
                           **kw)
                pylab.plot(ddHat,
                           m.fHat_aHat(m.aHat_deltaHat(ddHat, loading=False)),
                           **kw)
                pylab.plot([
                    m.deltaHat(m.delta_a(m.a_F(m.fUnhat(fh))[0]))
                    for fh in ffHat[::stride]
                ], ffHat[::stride], 'o', **invKw)
                pylab.plot([
                    m.deltaHat(m.delta_a(m.a_F(m.fUnhat(fh))[1]))
                    for fh in ffHat[::stride]
                ], ffHat[::stride], 'o', **invKw)
            elif what == 'a(F)':
                aaHat = numpy.linspace(0, 2.5, num=N)
                ffHat = numpy.linspace(-3, 4, num=N)
                pylab.plot(ffHat, [a[0] for a in m.aHat_fHat(ffHat)],
                           label='$\\alpha$=%g %s' % (m.alpha, m.name),
                           **kw)
                pylab.plot(ffHat, [a[1] for a in m.aHat_fHat(ffHat)], **kw)
                pylab.plot(m.fHat_aHat(aaHat[::stride]),
                           aaHat[::stride],
                           'o',
                           label=None,
                           **invKw)
        if what == 'a(delta)':
            ddH = [
                m.deltaHat(HertzModel.delta_a(m, m.aUnhat(a))) for a in aaHat
            ]
            pylab.plot(ddH, aaHat, label='Hertz', **kw)
            pylab.xlabel('$\hat\delta$')
            pylab.ylabel('$\hat a$')
            pylab.ylim(ymax=2.1)
            pylab.xlim(xmax=2.)
        elif what == 'F(delta)':
            pylab.plot(ddHat, [
                m.fHat(HertzModel.F_delta(m, m.deltaUnhat(d))) for d in ddHat
            ],
                       label='Hertz',
                       **kw)
            pylab.xlabel('$\hat\delta$')
            pylab.ylabel('$\hat P$')
            pylab.xlim(-1.3, 2)
            pylab.ylim(-2.1, 2)
            pylab.axhline(color='k')
            pylab.axvline(color='k')
        elif what == 'a(F)':
            pylab.plot(ffHat,
                       [m.aHat(HertzModel.a_F(m, m.fUnhat(f))) for f in ffHat],
                       label='Hertz',
                       **kw)
            pylab.xlabel('$\hat P$')
            pylab.ylabel('$\hat a$')
            pylab.xlim(xmax=4)
        pylab.grid(True)
        try:
            pylab.legend(loc='best', framealpha=legendAlpha)
        except:
            pylab.legend(loc='best')
with open("results/avg_clustering.txt", "w+") as f:
    f.write("Average Clustering: {}\n".format(clustering_sum / 2394385))
    f.write("Number of nodes with Clustering Coefficient of 0 {}\n".format(
        hist[0]))
    f.write("Number of nodes with Clustering Coefficient of 1 {}\n".format(
        hist[-1]))

width = 0.7 * (bins[2] - bins[1])
center = (bins[:-1] + bins[1:]) / 2

plt.figure()
plt.grid(True)
plt.bar(center[1:-1], hist[1:-1], align='center', width=width)
plt.xlabel('Clustering Coefficient')
plt.xlim([0, 1])
plt.ylabel('Number of Nodes')
plt.savefig('results/figures/clustering_hist.pdf')
plt.close()

log_hist = list()
for n in hist:
    if n == 0:
        log_hist.append(0)
    else:
        log_hist.append(log10(n))

plt.figure()
plt.grid(True)
plt.bar(center, log_hist, align='center', width=width)
plt.xlabel('Clustering Coefficient')
예제 #47
0
    Tstim=1.0
#    Tstim=0.2
    nTimeSteps = len(stmframes)
    
#    letters = ['A','B','E']
    letters=['A']
    dims = numpy.r_[dim, nTimeSteps]
    stim = generateLetterStim(dims, stmframes, letters)
    
    lgn = LGN(dt=Tstim/60.0)
    lgn.processStimulus(stim, Tstim=Tstim)
    
    ind = numpy.arange(0, 60, 2)
    plotResults(lgn, stim, ind)
    
    pylab.xticks([pylab.xlim()[0], pylab.xlim()[1]/2.0, pylab.xlim()[1]], ['0.0', str(Tstim/2.0), str(Tstim)+' s'])
# Example with spot stimulus
#===============================================================================
#    Tsim=0.2xxx
#    stmframes = numpy.r_[numpy.zeros(1), numpy.ones(15), numpy.zeros(39)]
#    nTimeSteps = len(stmframes)
#    
#    ret = Retina()
#    spot = numpy.ones(ret.k.shape)*(ret.k>0)
#    
#    nBitmaps = 1
#    bitmaps = numpy.zeros((ret.k.shape[0], ret.k.shape[1], nBitmaps))
#    bitmaps[:,:,0]=spot
#    
#    stim = generateBitmapStim(bitmaps, stmframes)
#    
예제 #48
0
                    x1_ = glob_cent_centroid[1] - patch_size
                    y1_ = glob_cent_centroid[0] - patch_size
                    x2_ = x1_ + 2 * patch_size
                    y2_ = y1_ + 2 * patch_size

                    plt.text(x1_ - 1,
                             y1_ - 2,
                             str(i + 1).zfill(3),
                             fontsize=1.2,
                             color='w')
                    plt.plot([x1_, x2_, x2_, x1_, x1_],
                             [y1_, y1_, y2_, y2_, y1_],
                             lw=0.2,
                             color='w')

                plt.xlim([0, ncols])
                plt.ylim([nrows, 0])
                """
                saving out the global file too. 
                """
                plt.savefig(os.path.join(
                    saveimgfolder,
                    basename.replace('.pkl',
                                     '_full-image-cnn-detections.svg')),
                            dpi=height)
                plt.close()
                """
                save out the global mask. 
                """
                fig = plt.figure()
                fig.set_size_inches(width / height, 1, forward=False)
예제 #49
0
layer1 = reflectivity.Epitaxial_Layer(struct2, thickness)
layer1.calc_orientation(v_par, v_perp)
crystal = reflectivity.Sample(Sub, layer1)
crystal.set_Miller(R)
crystal.calc_g0_gH(Energy)
thBragg = float(Sub.calc_Bragg_angle(Energy).subs(Sub.structure.subs).evalf())
angle = pl.linspace(0.975, 1.006, 501) * thBragg

# XRl = layer1.calc_reflection_amplitude(angle, Energy)
#XRs = Sub.calc_reflection_amplitude(angle, Energy)
#
# XT = layer1.calc_transmission_amplitude(angle, Energy)

XR = crystal.calc_reflectivity(angle, Energy)

crystal.print_values(angle, Energy)

pl.plot(*data.T, label='GID_sl', color='red')
#pl.plot(angle-thBragg,abs(XT)**2)
pl.plot(pl.degrees(angle - thBragg), abs(XR)**2, label='dynXRD', color='black')
#pl.plot(pl.degrees(angle-thBragg),abs(Sub.XR)**2, label='dynXRD', color='blue')
#pl.plot(angle-thBragg,1 - abs(XT)**2 - abs(XRl)**2)
pl.yscale('log')
pl.xlabel('Angle (degrees)')
pl.ylabel('Reflectivity')
pl.xlim(-0.25, 0.1)
pl.rc('font', size=18)
pl.legend(loc="upper left", prop={'size': 19})

pl.savefig('pics/test12.eps')
pl.show()
import pylab as pl
import numpy as np

x = np.arange(-10, 10, 0.1)

f1 = (x - 1)**2
f2 = np.exp(-(x - 1)**2) * 50

pl.plot(x, f1, label='f1: Behavioral feature 1')
pl.plot(x, f2, label='f2: Behavioral feature 2')
pl.xlabel("x")
pl.ylabel("Error function value")
pl.legend()
pl.ylim(0, 120)
pl.savefig("Example1.png")

pl.figure()
f2 = np.exp(-(np.sqrt(f1) + 1 - 1)**2) * 50
pl.plot(f1, f2, label='Pareto front')
pl.xlabel("f1")
pl.ylabel("f2")
pl.legend()

pl.xlim(0, 20)
pl.ylim(0, 20)
pl.savefig("Example_pareto.png")
예제 #51
0
    xs = np.linspace(0, length, 101)

    plt.figure(1)
    plt.clf()
    ax1 = plt.subplot(2, 1, 1)
    c = plt.scatter(xp[:, 0],
                    xp[:, 1],
                    s=0.1,
                    c=np.log10(np.maximum(pstrain, 1e-16)),
                    vmin=-4,
                    vmax=1)
    cbar1 = plt.colorbar(c)
    cbar1.set_ticks([-4, 1])
    plt.axis('equal')
    plt.title(title_str)
    plt.xlim([0, max_length])
    ax2 = plt.subplot(2, 1, 2)
    c = plt.scatter(xp[:, 0],
                    xp[:, 1],
                    s=0.1,
                    c=np.log10(pepsII / material.time_factor + 1e-16),
                    vmin=-8,
                    vmax=-5)
    cbar2 = plt.colorbar(c)
    plt.axis('equal')
    #plt.plot(xx,bed_fun_np(xx),'--k',linewidth=2)
    #plt.plot(xs,surf_fun(xs),'--',color='gray')
    cbar2.set_ticks([-8, -5])
    #plt.title(title_str)
    plt.xlim([0, max_length])
    plt.xlabel('Distance (km)')
예제 #52
0
    volume, flooded = x_iterate(t=times[i])
    volume *= M0
    if flooded:
        z_array[i:] = zmax
        z_covered[i:] = zmax
        break
    else:
        z, c = get_z(volume)
        z_array[i] = z
        if c:
            z_covered[i] = z
        else:
            z_uncovered[i] = z
            c_array[i] = 0

# Set up plot
pylab.semilogx(t_array, [zmax] * N,
               color='k',
               linestyle="dashed",
               label="top of vessel")
pylab.semilogx(t_array, z_covered, color='b', marker="o", label="water level")
pylab.semilogx(t_array, z_uncovered, color='r', marker="x")
pylab.semilogx(t_array, [ztop] * N, color='g', label="top of core")
pylab.legend(loc="center right")
pylab.xlabel("t (hours)")
pylab.ylabel("z (m)")
pylab.xlim([0, TIME / 3600])
pylab.ylim([R_VESSEL, zmax + 1])
pylab.title("Height of water in core", {"fontsize": 16, "fontweight": "bold"})
pylab.show()
    v[1] -= alpha * u[0]
    v[N-1] -= gamma * u[N]
    #forward sweep
    u[1] = v[1] / beta
    v[1] = gamma / beta
    for j in range(2,N):
        den = beta - alpha*v[j-1]
        u[j] = (v[j] - alpha*u[j-1])/den
        v[j] = gamma / den
    #backward sweep
    for j in reversed(range(1,N-1)):
        u[j] -= u[j+1] * v[j]
    t += dt
    if t >= p*tstep:
        pylab.plot(x, [z  for z in u], label='t (s)='+str(round(t,4)) )
        pylab.xlim(-L/2,L/2)
        pylab.xlabel('x(m)')
        pylab.ylabel('Temperature (Celcius)')
        pylab.legend(loc=(1.03,0.2))
        p += 1

pylab.show()
        







예제 #54
0
def plot_results(pilot_dir, subj, channel, alpha_band=(9, 14), theta_band=(3, 6), drop_channels=None, dc=False,
                 reject_alpha=True, normalize_by='opened'):
    drop_channels = drop_channels or []
    cm = get_colors()
    fg = plt.figure(figsize=(30, 6))
    for j_s, experiment in enumerate(subj):
        with h5py.File('{}\\{}\\{}'.format(pilot_dir, experiment, 'experiment_data.h5')) as f:
            rejections, top_alpha, top_ica = load_rejections(f, reject_alpha=reject_alpha)
            fs, channels, p_names = get_info(f, drop_channels)
            ch = channels.index(channel)
            #plt.plot(fft_filter(f['protocol6/raw_data'][:, ch], fs, band=(3, 35)))
            #plt.plot(fft_filter(np.dot(f['protocol6/raw_data'], rejections)[:, ch], fs, band=(3, 35)))
            #plt.show()
            #from scipy.signal import welch
            #plt.plot(*welch(f['protocol1/raw_data'][:60*500//2, channels.index('C3')], fs, nperseg=1000))
            #plt.plot(*welch(f['protocol1/raw_data'][60*500//2:, channels.index('C3')], fs, nperseg=1000))

            #plt.plot(*welch(f['protocol2/raw_data'][:30*500//2, channels.index('C3')], fs, nperseg=1000))
            #plt.plot(*welch(f['protocol2/raw_data'][30*500//2:, channels.index('C3')], fs, nperseg=1000))
            #plt.legend(['Close', 'Open', 'Left', 'Right'])
            #plt.show()

            # collect powers
            powers = OrderedDict()
            raw = OrderedDict()
            alpha = OrderedDict()
            pow_theta = []
            for j, name in enumerate(p_names):
                pow, alpha_x, x = get_protocol_power(f, j, fs, rejections, ch, alpha_band, dc=dc)
                if 'FB' in name:
                    pow_theta.append(get_protocol_power(f, j, fs, rejections, ch, theta_band, dc=dc)[0].mean())
                powers = add_data(powers, name, pow, j)
                raw = add_data(raw, name, x, j)
                alpha = add_data(alpha, name, alpha_x, j)

            # plot rejections
            n_tops = top_ica.shape[1] + top_alpha.shape[1]
            for j_t in range(top_ica.shape[1]):
                ax = fg.add_subplot(4, n_tops * len(subj), n_tops * len(subj) * 3 + n_tops * j_s + j_t + 1)
                ax.set_xlabel('ICA{}'.format(j_t + 1))
                labels, fs = get_lsl_info_from_xml(f['stream_info.xml'][0])
                channels = [label for label in labels if label not in drop_channels]
                pos = ch_names_to_2d_pos(channels)
                plot_topomap(data=top_ica[:, j_t], pos=pos, axes=ax, show=False)
            for j_t in range(top_alpha.shape[1]):
                ax = fg.add_subplot(4, n_tops * len(subj),
                                    n_tops * len(subj) * 3 + n_tops * j_s + j_t + 1 + top_ica.shape[1])
                ax.set_xlabel('CSP{}'.format(j_t + 1))
                labels, fs = get_lsl_info_from_xml(f['stream_info.xml'][0])
                channels = [label for label in labels if label not in drop_channels]
                pos = ch_names_to_2d_pos(channels)
                plot_topomap(data=top_alpha[:, j_t], pos=pos, axes=ax, show=False)

            # plot powers
            if normalize_by == 'opened':
                norm = powers['1. Opened'].mean()
            elif normalize_by == 'beta':
                norm = np.mean(pow_theta)
            else:
                print('WARNING: norm = 1')
            print('norm', norm)

            ax1 = fg.add_subplot(3, len(subj), j_s + 1)
            ax = fg.add_subplot(3, len(subj), j_s + len(subj) + 1)
            t = 0
            for j_p, ((name, pow), (name, x)) in enumerate(zip(powers.items(), raw.items())):
                if name == '2228. FB':
                    from scipy.signal import periodogram
                    fff = plt.figure()
                    fff.gca().plot(*periodogram(x, fs, nfft=fs * 3), c=cm[name.split()[1]])
                    plt.xlim(0, 80)
                    plt.ylim(0, 3e-11)
                    plt.show()
                print(name)
                time = np.arange(t, t + len(x)) / fs
                color = cm[''.join([i for i in name.split()[1] if not i.isdigit()])]
                ax1.plot(time, fft_filter(x, fs, (2, 45)), c=color, alpha=0.4)
                ax1.plot(time, alpha[name], c=color)
                t += len(x)
                ax.plot([j_p], [pow.mean() / norm], 'o', c=color, markersize=10)
                ax.errorbar([j_p], [pow.mean() / norm], yerr=pow.std() / norm, c=color, ecolor=color)
            fb_x = np.hstack([[j] * len(pows) for j, (key, pows) in enumerate(powers.items()) if 'FB' in key])
            fb_y = np.hstack([pows for key, pows in powers.items() if 'FB' in key]) / norm
            sns.regplot(x=fb_x, y=fb_y, ax=ax, color=cm['FB'], scatter=False, truncate=True)

            ax1.set_xlim(0, t / fs)
            ax1.set_ylim(-40, 40)
            plt.setp(ax.xaxis.get_majorticklabels(), rotation=70)
            ax.set_xticks(range(len(powers)))
            ax.set_xticklabels(powers.keys())
            ax.set_ylim(0, 3)
            ax.set_xlim(-1, len(powers))
            ax1.set_title('Day {}'.format(j_s + 1))
    return fg
예제 #55
0
MX_c = MX - MX_m[:, None]
U, S, V = numpy.linalg.svd(MX_c, full_matrices=0)

#determine value along principal axis
UMX = numpy.dot(U, MX_c)

#scatterplot, color-coded by principal axis value
pylab.scatter(MX[0], MX[1], c=UMX[0], s=9, lw=0)
pylab.colorbar()

#plot principal axis
x = numpy.linspace(min(MX[0]), max(MX[0]), 10)
y = MX_m[1] + (x - MX_m[0]) * U[0, 1] / U[0, 0]
pylab.plot(x, y, '-k')

#set axes limits so x and y scales are equal
xlim = pylab.xlim()
ylim = pylab.ylim()

x0 = numpy.mean(xlim)
y0 = numpy.mean(ylim)
xr = xlim[1] - xlim[0]
yr = ylim[1] - ylim[0]

d = 0.5 * max(xr, yr)

pylab.xlim(x0 - d, x0 + d)
pylab.ylim(y0 - d, y0 + d)

pylab.show()
예제 #56
0
    # plot
print("data range: " + str(min) + " - " + str(max))
if options.verbose:
    print("Plotting...")
if options.time_coloring:
    scatter(xs, ys, color=c, s=1)
else:
    plot(xs, ys, ',k')
# set axes
if options.xticks != "":
    (xb, xe, xd, xs) = options.xticks.split(",")
    xticks(arange(xb, xe, xd), size=xs)
if options.yticks != "":
    (yb, ye, yd, ys) = options.yticks.split(",")
    yticks(arange(yb, ye, yd), size=ys)
if options.xlim != "":
    (xb, xe) = options.xlim.split(",")
    xlim(int(xb), int(xe))
else:
    xlim(min, max)
if options.ylim != "":
    (yb, ye) = options.ylim.split(",")
    ylim(int(yb), int(ye))
else:
    ylim(min, max)
# show/save
if options.show:
    show()
if options.output:
    savefig(options.output)
예제 #57
0
# Plot filters in color with a single spectrum
pl.figure()
pl.plot(Xref[:, 0], Xref[:, 1], '-k', lw=2)

for f, c in zip('ugriz', 'bgrmk'):
    X = fetch_filter(f)
    pl.fill(X[:, 0], X[:, 1], ec=c, fc=c, alpha=0.4)

kwargs = dict(fontsize=20, ha='center', va='center', alpha=0.5)
pl.text(3500, 0.02, 'u', color='b', **kwargs)
pl.text(4600, 0.02, 'g', color='g', **kwargs)
pl.text(6100, 0.02, 'r', color='r', **kwargs)
pl.text(7500, 0.02, 'i', color='m', **kwargs)
pl.text(8800, 0.02, 'z', color='k', **kwargs)

pl.xlim(3000, 11000)

pl.title('SDSS Filters and Reference Spectrum')
pl.xlabel('Wavelength (Angstroms)')
pl.ylabel('normalized flux / filter transmission')

#----------------------------------------------------------------------
# Plot filters in gray with several redshifted spectra
pl.figure()

redshifts = [0.0, 0.4, 0.8]
colors = 'bgr'

for z, c in zip(redshifts, colors):
    pl.plot((1. + z) * Xref[:, 0], Xref[:, 1], color=c)
gnc = evolve(nx, C, tmax, conservative=0, init="rarefaction")

pylab.plot(gc.x, gc.u, color="r", label="conservative")
pylab.plot(gnc.x, gnc.u, color="b", label="non-conservative")

tmax = 0.1

gc = evolve(nx, C, tmax, conservative=1, init="rarefaction")
gnc = evolve(nx, C, tmax, conservative=0, init="rarefaction")

pylab.plot(gc.x, gc.u, color="r", ls="--")
pylab.plot(gnc.x, gnc.u, color="b", ls="--")

pylab.plot(gnc.x, gc.uinit, color="0.5", label="initial conditions")

pylab.xlim(0, 1)

#pylab.legend(loc=3, frameon=False, fontsize="small")

pylab.xlabel("x")
pylab.ylabel("u")

pylab.savefig("burger-rarefaction.png")

#-----------------------------------------------------------------------------
tmax = 0.3

pylab.clf()

gc = evolve(nx, C, tmax, conservative=1, init="shock")
gnc = evolve(nx, C, tmax, conservative=0, init="shock")
예제 #59
0
def execs_timeit_2vector(exprs, fname=None):
    """
    exprs is a list of list of expr to evaluate
    The first level of list is put into different graph section in the same graph.
    The second level is the expression to put in each section
    """
    #exp = [(1,100000),(1e1,100000),(1e2,100000),(1e3,100000), (5e3,50000),
    exp = [(1e3,100000),(5e3,50000), \
           (1e4,10000),(5e4,5000),(1e5,2000),(1e6,200),(1e7,10)
           ]
    ### TO TEST UNCOMMENT THIS LINE
    # exp = [(1,1000),(1e1,1000),(1e2,1000),]
    times = []
    str_expr = []
    for g_exprs in exprs:
        for expr in g_exprs:
            nb_call_scal = 1
            if isinstance(expr, tuple):
                nb_call_scal = expr[1]
                expr = expr[0]
            str_expr.append(expr)
            time = []
            for nb_e, nb_c in exp:
                time.append(
                    timeit_2vector(nb_element=nb_e,
                                   nb_repeat=3,
                                   nb_call=nb_c * nb_call_scal,
                                   expr=expr,
                                   do_amd=False))
            times.append(time)
    if 'pylab' not in globals():
        return

    nb_calls = [e[0] for e in exp]
    legends = []
    colors = ['b', 'r', 'g', 'c', 'm', 'y']
    assert len(colors) >= len(times)
    fig = pylab.figure()
    for idx, (time, expr) in enumerate(zip(times, str_expr)):

        ###
        ###
        ###
        # Creating each subplot
        ###
        ###
        ###
        ###
        pylab.subplot(220 + idx + 1)
        pylab.subplots_adjust(wspace=0.25, hspace=0.25)
        #legend=[]
        #plot = fig.add_subplot(1,len(exprs),idx)
        speedup = [t["numpy"].min() / t["numexpr"].min() for t in time]

        pylab.semilogx(nb_calls, speedup, linewidth=1.0, color='r')
        speedup = [t["numpy"].min() / t["theano"].min() for t in time]
        pylab.semilogx(nb_calls, speedup, linewidth=1.0, color='b')
        pylab.grid(True)
        if (idx == 2) or (idx == 3):
            pylab.xlabel('Dimension of vectors a and b', fontsize=15)
        if (idx == 0) or (idx == 2):
            pylab.ylabel('Speed up vs NumPy', fontsize=15)
        pylab.axhline(y=1, linewidth=1.0, color='black')
        pylab.xlim(1e3, 1e7)
        pylab.xticks([1e3, 1e5, 1e7], ['1e3', '1e5', '1e7'])
        pylab.title(expr)

    if fname:
        fig.savefig(fname)
        pylab.clf()
    else:
        pylab.show()
	pl.plot(z_after,  (100*np.abs((xp_after-xp_before)-(xp[ii+1, :]-xp[0, :]))/np.std(xp[ii+1, :]-xp[0, :])), '.r', markersize = 2)
	pl.grid('on')
	pl.ylabel('''error($\Delta$x')/$\Delta$x' [%]''')
	pl.subplot(2,3,4, sharex=sp1)
	pl.plot(z_after,  (xp[ii+1, :]-xp[0, :]), '.r', label='HT', markersize = 2)
	pl.plot(z_after,  (xp_after-xp_before), '.b', label='PyHT', markersize = 2)
	ms.sciy()
	pl.grid('on')
	pl.ylabel("$\Delta$x'")
	pl.xlabel('z[m]')
	pl.legend(prop = {'size':14})
	pl.subplot(2,3,3)
	pl.hist((100*np.abs((xp_after-xp_before)-(xp[ii+1, :]-xp[0, :]))/np.std(xp[ii+1, :]-xp[0, :])), bins=100, range=(0,100))
	pl.xlabel('Error_x [%]')
	pl.ylabel('Occurrences')
	pl.xlim(0,100)
	rms_err_x = np.std(100*np.abs((xp_after-xp_before)-(xp[ii+1, :]-xp[0, :]))/np.std(xp[ii+1, :]-xp[0, :]))

	sp1 = pl.subplot(2,3,2)
	pl.plot(z_after,  (100*np.abs((yp_after-yp_before)-(yp[ii+1, :]-yp[0, :]))/np.std(yp[ii+1, :]-yp[0, :])), '.r', markersize = 2)
	pl.grid('on')
	pl.ylabel('''error($\Delta$y')/$\Delta$y' [%]''')
	pl.subplot(2,3,5, sharex=sp1)
	pl.plot(z_after,  (yp[ii+1, :]-yp[0, :]), '.r', label='HT', markersize = 2)
	pl.plot(z_after,  (yp_after-yp_before), '.b', label='PyHT', markersize = 2)
	ms.sciy()
	pl.grid('on')
	pl.ylabel("$\Delta$y'")
	pl.xlabel('z[m]')
	pl.legend(prop = {'size':14})
	pl.subplot(2,3,6)