def hist_Ne(sel_coinc_ids, coords, data, n): global histNe2 c_index = data.root.coincidences.c_index observ = data.root.coincidences.observables core_rec = data.root.core_reconstructions.reconstructions histNe = core_rec.readCoordinates(coords, field='reconstructed_shower_size') #histNe = [x for x in histNe if x > 0] # for showersize smaller than 0 d = 10**10.2 histNe2 = [x*d for x in histNe] #histNe *= 10 ** 10.2 pylab.hist(np.log10(histNe2), 100, log=True) # histtype="step" pylab.xlabel('Showerenergy log(eV)') pylab.ylabel('count') pylab.title('showersize bij N==%s' %n) pylab.ylim(ymin=1) pylab.grid(True) pylab.show() return histNe2
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')
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))
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')
def param_set_averages_plot(results): averages_ocr = [ a[1] for a in sorted( param_set_averages(results, metric='ocr').items(), key=lambda x: int(x[0].split('-')[1])) ] averages_q = [ a[1] for a in sorted( param_set_averages(results, metric='q').items(), key=lambda x: int(x[0].split('-')[1])) ] averages_mse = [ a[1] for a in sorted( param_set_averages(results, metric='mse').items(), key=lambda x: int(x[0].split('-')[1])) ] fig = plt.figure(figsize=(6, 4)) # plt.tight_layout() plt.plot(averages_ocr, label='OCR', linewidth=2.0) plt.plot(averages_q, label='Q', linewidth=2.0) plt.plot(averages_mse, label='MSE', linewidth=2.0) plt.ylim([0, 1]) plt.xlabel(u'Paslėptų neuronų skaičius') plt.ylabel(u'Vidurinė Q įverčio pokyčio reikšmė') plt.grid(True) plt.tight_layout() plt.legend(loc='lower right') plt.show()
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
def trace(data, name, format='png', datarange=(None, None), suffix='', path='./', rows=1, columns=1, num=1, last=True, fontmap = None, verbose=1): """ Generates trace plot from an array of data. :Arguments: data: array or list Usually a trace from an MCMC sample. name: string The name of the trace. datarange: tuple or list Preferred y-range of trace (defaults to (None,None)). format (optional): string Graphic output format (defaults to png). suffix (optional): string Filename suffix. path (optional): string Specifies location for saving plots (defaults to local directory). fontmap (optional): dict Font map for plot. """ if fontmap is None: fontmap = {1:10, 2:8, 3:6, 4:5, 5:4} # Stand-alone plot or subplot? standalone = rows==1 and columns==1 and num==1 if standalone: if verbose>0: print_('Plotting', name) figure() subplot(rows, columns, num) pyplot(data.tolist()) ylim(datarange) # Plot options title('\n\n %s trace'%name, x=0., y=1., ha='left', va='top', fontsize='small') # Smaller tick labels tlabels = gca().get_xticklabels() setp(tlabels, 'fontsize', fontmap[rows/2]) tlabels = gca().get_yticklabels() setp(tlabels, 'fontsize', fontmap[rows/2]) if standalone: if not os.path.exists(path): os.mkdir(path) if not path.endswith('/'): path += '/' # Save to file savefig("%s%s%s.%s" % (path, name, suffix, format))
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()
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 )
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')
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);
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")
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()
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()
def psfplots(): tpsf = wise.get_psf_model(1, pixpsf=True) psfp = tpsf.getPointSourcePatch(0, 0) psf = psfp.patch psf /= psf.sum() plt.clf() plt.imshow(np.log10(np.maximum(1e-5, psf)), interpolation='nearest', origin='lower') plt.colorbar() ps.savefig() h,w = psf.shape cx,cy = w/2, h/2 X,Y = np.meshgrid(np.arange(w), np.arange(h)) R = np.sqrt((X - cx)**2 + (Y - cy)**2) plt.clf() plt.semilogy(R.ravel(), psf.ravel(), 'b.') plt.xlabel('Radius (pixels)') plt.ylabel('PSF value') plt.ylim(1e-8, 1.) ps.savefig() plt.clf() plt.loglog(R.ravel(), psf.ravel(), 'b.') plt.xlabel('Radius (pixels)') plt.ylabel('PSF value') plt.ylim(1e-8, 1.) ps.savefig() print('PSF norm:', np.sqrt(np.sum(np.maximum(0, psf)**2))) print('PSF max:', psf.max())
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()
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()
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()
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 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)')
def test_anns(results): data = read_metrics(results) split = int(len(data) * 0.8) num_input = len(data[0]) - 1 random.shuffle(data) test_data = data[split:] # Read ANNs ann_dir = '/home/tomas/Dropbox/Git/ga_sandbox/projects/denoising/neural/trained_anns' trained_anns = [] for filename in os.listdir(ann_dir): if filename.endswith('.net'): ann_path = os.path.join(ann_dir, filename) ann = libfann.neural_net() ann.create_from_file(ann_path) trained_anns.append(ann) points = [] for row in test_data: actual_output = row[num_input] ann_mean_output = np.mean([ ann.run(row[:num_input]) for ann in trained_anns ]) points.append([ann_mean_output, actual_output]) print "actual: " + str(actual_output) + ", predicted: " + str(ann_mean_output) points = sorted(points, key=lambda p: p[1]) fig = plt.figure(figsize=(6, 4)) plt.plot([p[0] for p in points]) plt.plot([p[1] for p in points]) plt.ylim([0, 1.2]) plt.show()
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()
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))
def test_seq(self): sleep(1) self.cmd_logger(0) self.takeoffpub.publish(Empty()) ;print 'takeoff' #takeoff sleep(12); print '4'; sleep(1); print '3'; sleep(1); print '2'; sleep(1); print '1'; sleep(1) self.cmd_logger(0) self.twist.linear.z = self.vzcmd self.cmd_logger(self.vzcmd) self.cmdpub.publish(self.twist) ;print 'vzcmd' #set vzcmd sleep(self.vzdur) #wait for vzdur self.cmd_logger(self.vzcmd) self.clear_twist() self.cmd_logger(0) self.cmdpub.publish(self.twist) ;print 'clear vz' #clear vz sleep(4) self.cmd_logger(0) self.landpub.publish(Empty()) ;print 'land' #land sleep(1) if not raw_input('show and save?') == 'n': pl.xlabel('time (s)') pl.ylim(0,2400) pl.plot(self.cmd_log['tm'],self.cmd_log['cmd'], 'b-s') pl.plot(self.nd_log['tm'],self.nd_log['vz'], 'g-+') pl.plot(self.nd_log['tm'],self.nd_log['al'], 'r-+') pl.grid(True) pl.show()
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))
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)
def RosenbrockTest(): nDim = 3 numOfParticles = 20 maxIteration = 200 minX = array([-5.0]*nDim) maxX = array([5.0]*nDim) maxV = 0.2*(maxX - minX) minV = -1.0*maxV numOfTrial = 20 gBest = array([0.0]*maxIteration) for i in xrange(numOfTrial): p1 = RPSO.PSOProblem(nDim, numOfParticles, maxIteration, minX, maxX, minV, maxV, RPSO.Rosenbrock) p1.run() gBest = gBest + p1.gBestArray[:maxIteration] gBest = gBest / numOfTrial pylab.title('$G_{best}$ over 20 trials') pylab.xlabel('The $N^{th}$ Iteratioin') pylab.ylabel('Average gBest over '+str(numOfTrial)+' runs (logscale)') pylab.grid(True) # pylab.yscale('log') ymin, ymax = -1.5, 2.5 ystep = 0.5 pylab.ylim(ymin, ymax) yticks = linspace(ymin, ymax, (ymax-ymin)/ystep+1) pylab.yticks(tuple(yticks),tuple(map(str,yticks))) pylab.plot(range(maxIteration), log10(gBest),'-', label='Global best') pylab.legend() pylab.show()
def pseudoSystem(): #The corrolations discovered when answering this question shows the emergent effects of component evolution on CSE. #We can further study these correlations by creating an example component system consisting of many components where a a different component has a new version released every day. #By looking at users who Upgrade the system at different frequencies over 100 days, we present two graphs, Upgrade frequency to uttd and change. l = 100 uttdxy = [] chxy = [] for uf in range(1,20): uttd = range(uf)*(l*2/uf) uttd = uttd[1:l+1] uttdxy.append((uf,numpy.mean(uttd))) sh = [0]*(uf-1) + [uf] sh = sh*l sh = sh[:l] chxy.append((uf,sum(sh))) pylab.figure(20) x,y = zip(*sorted(uttdxy)) pylab.plot(x,y) pylab.scatter(x,y) saveFigure("q1bpseudouttd") pylab.figure(21) x,y = zip(*sorted(chxy)) pylab.plot(x,numpy.array(y)) pylab.scatter(x,numpy.array(y)) pylab.ylim([0,l+10]) saveFigure("q1bpseudochange")
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
def data_preprocessing_result_box_plot(result_dict, model_list, data_preprocessing_list, metrics_name_list, data_preprocessing_show_list, metrics_show_list, title='', x_label='', xlim_range=(0, 15), ylim_range=(0.2, 0.6), plot_baseline=True, baseline_value_tuple=None, baseline_legend_tuple=None, baseline_colour_tuple=None): box_widths = 0.3 box_gap = 0.5 category_gap = 1.5 position_now = 0 category_pos_list = [] fig = figure() ax = axes() hold(True) # Some fake data to plot # model_result_dict = result_dict[model_list] for data_preprocessing in data_preprocessing_list: X = [] for metric in metrics_name_list: model_metric_list = [] for model in model_list: model_metric_list.extend( result_dict[model][data_preprocessing][metric]) X.append(model_metric_list) # first boxplot pair position_now += category_gap positions_list, position_now = get_positions(metrics_name_list, position_now, box_gap) category_pos_list.append(np.average(positions_list)) bp = boxplot(X, positions=positions_list, widths=box_widths, sym='+') setBoxColors(bp, metrics_name_list) # set axes limits and labels xlim(*xlim_range) ylim(*ylim_range) ax.set_xticklabels(data_preprocessing_show_list) ax.set_xticks(category_pos_list) ax.set_xlabel(x_label) ax.set_title(title) # draw temporary red and blue lines and use them to create a legend h_list = [] shape = '-' legend_list = [ 'b{}'.format(shape), 'r{}'.format(shape), 'g{}'.format(shape), 'c{}'.format(shape), 'y{}'.format(shape), 'm{}'.format(shape) ] for i, _ in enumerate(metrics_show_list): h, = plot([1, 1], legend_list[i]) h_list.append(h) # h.set_visible(False) # hB, = plot([1, 1], 'b-') # hR, = plot([1, 1], 'r-') if plot_baseline and baseline_value_tuple: for i, baseline_value in enumerate(baseline_value_tuple): baseline_plot = plt.plot((0, 99), (baseline_value, baseline_value), '{}-'.format(baseline_colour_tuple[i]), dashes=[2, 5])[0] h_list.append(baseline_plot) metrics_show_list.append('{}'.format(baseline_legend_tuple[i])) legend(h_list, metrics_show_list) for i, h in enumerate(h_list): if i >= len(baseline_legend_tuple): pass else: h.set_visible(False) show()
if this_dx > 0: horizontalalignment = 'left' x = x + .002 else: horizontalalignment = 'right' x = x - .002 if this_dy > 0: verticalalignment = 'bottom' y = y + .002 else: verticalalignment = 'top' y = y - .002 pl.text(x, y, name, size=10, horizontalalignment=horizontalalignment, verticalalignment=verticalalignment, bbox=dict(facecolor='w', edgecolor=pl.cm.spectral(label / float(n_labels)), alpha=.6)) pl.xlim( embedding[0].min() - .15 * embedding[0].ptp(), embedding[0].max() + .10 * embedding[0].ptp(), ) pl.ylim(embedding[1].min() - .03 * embedding[1].ptp(), embedding[1].max() + .03 * embedding[1].ptp()) pl.show()
# INDUCED VOLTAGE FROM IMPEDANCE ---------------------------------------------- imp_list = [resonator] ind_volt_freq = InducedVoltageFreq(beam, slice_beam, imp_list, RFParams=RF_sct_par, frequency_resolution=5e2, multi_turn_wake=True, mtw_mode='time') total_ind_volt = TotalInducedVoltage(beam, slice_beam, [ind_volt_freq]) f_rf = RF_sct_par.omega_rf[0,0] / 2.0 / np.pi plt.figure() plt.plot(ind_volt_freq.freq*1e-6, np.abs(ind_volt_freq.total_impedance * \ slice_beam.bin_size), lw=2) plt.plot([f_rf*1e-6]*2, plt.ylim(), 'k', lw=2) plt.plot([f_rf*1e-6 + fs*1e-6]*2, plt.ylim(), 'k--', lw=2) plt.plot([f_rf*1e-6 - fs*1e-6]*2, plt.ylim(), 'k--', lw=2) plt.xlim(1.74,1.76) plt.legend(('Impedance','RF frequency','Synchrotron sidebands'), loc=0, fontsize='medium') plt.xlabel('Frequency [MHz]') plt.ylabel(r'Impedance [$\Omega$]') plt.savefig(this_directory + '../output_files/EX_18_fig/impedance.png') plt.close() # BEAM GENERATION ------------------------------------------------------------- matched_from_distribution_function(beam, full_tracker, distribution_type=distribution_type,
) # pl.errorbar(MockCat[:,0] + 0.001, MockCat[:,1], MockCat[:,5], label='Monopole, predicted errors', fmt='', color='k') # pl.errorbar(MockCat[:,0] - 0.001, MockCat[:,2], MockCat[:,6], label='Quadrupole, predicted errors', fmt='', color='r') pl.loglog(MockCat[:, 0], MockCat[:, 5], 'k-', label='predicted monopole error') pl.loglog(MockCat[:, 0], MockCat[:, 6], 'r-', label='predicted quadrupole error') pl.loglog(kvals, np.sqrt(MonoVar), 'g-', label='monopole error from mocks') pl.loglog(kvals, np.sqrt(QuadVar), 'b-', label='quadrupole error from mocks') pl.xscale('log') pl.yscale('log', nonposy='clip') pl.xlabel(r'$k [h Mpc^{-1}]$') # pl.ylabel(r'P(k) e$^{-9k^2/2}$') pl.xlim(10.**-2., 0.4) pl.ylim(10.**0., 10.**5.) pl.legend(loc=1) pl.savefig( '/disk1/mjw/HOD_MockRun/Plots/Windowfunc/31JulyOnwards/quadrupoleError.pdf' )
def main(): option_parser, opts, args =\ parse_command_line_parameters(**script_info) input_fp = opts.input_fp output_dir = opts.output_dir if opts.num_fraction_for_core_steps < 2: option_parser.error("Must perform at least two steps. Increase --num_fraction_for_core_steps.") fractions_for_core = linspace(opts.min_fraction_for_core, opts.max_fraction_for_core, opts.num_fraction_for_core_steps) otu_md = opts.otu_md valid_states = opts.valid_states mapping_fp = opts.mapping_fp create_dir(output_dir) if valid_states and opts.mapping_fp: sample_ids = sample_ids_from_metadata_description(open(mapping_fp,'U'), valid_states) if len(sample_ids) < 1: option_parser.error(\ "--valid_states pattern didn't match any entries in mapping file: \"%s\"" %\ valid_states) else: # get core across all samples if user doesn't specify a subset of the # samples to work with sample_ids = None input_table = parse_biom_table(open(input_fp,'U')) otu_counts = [] summary_figure_fp = join(output_dir,'core_otu_size.pdf') for fraction_for_core in fractions_for_core: # build a string representation of the fraction as that gets used # several times fraction_for_core_str = "%1.0f" % (fraction_for_core * 100.) # prep output files output_fp = join(output_dir,'core_otus_%s.txt' % fraction_for_core_str) output_table_fp = join(output_dir,'core_table_%s.biom' % fraction_for_core_str) output_f = open(output_fp,'w') try: core_table = filter_table_to_core(input_table, sample_ids, fraction_for_core) except TableException: output_f.write("# No OTUs present in %s %% of samples." % fraction_for_core_str) output_f.close() continue # write some header information to file if sample_ids == None: output_f.write("# Core OTUs across %s %% of samples.\n" % fraction_for_core_str) else: output_f.write(\ "# Core OTUs across %s %% of samples matching the sample metadata pattern \"%s\":\n# %s\n" %\ (fraction_for_core_str, valid_states,' '.join(sample_ids))) # write the otu id and corresponding metadata for all core otus otu_count = 0 for value, id_, md in core_table.iterObservations(): output_f.write('%s\t%s\n' % (id_,md[otu_md])) otu_count += 1 output_f.close() # write the core biom table output_table_f = open(output_table_fp,'w') output_table_f.write(format_biom_table(core_table)) output_table_f.close() # append the otu count to the list of counts otu_counts.append(otu_count) plot(fractions_for_core, otu_counts) xlim(min(fractions_for_core),max(fractions_for_core)) ylim(0,max(otu_counts)+1) xlabel("Fraction of samples that OTU must be observed in to be considered 'core'") ylabel("Number of OTUs") savefig(summary_figure_fp)
#Question 2 a_2 = np.fft.rfft(a1) #fast fourier transform function for amplitude a2 = np.abs(a_2) * 1 / N T = 1 / 4000 #frequency f = np.linspace(0, N, len(a2)) #plotting frequency vs. amplitude plt.bar(f, a2) xlim(0, 100) ylim(0, 1.0) xlabel("Frequency [Hz]") ylabel("Amplitude") plt.show() #plot 2 #Question 3 print("Lengths: time =", len(t), " time-domain function =", len(a1), " FFT =", len(a2)) print("Sample rate =", T, " Frequency =", 1 / T) print("Lengths: f =", N, " abs(f) =", len(a2)) print("Lengths: f(N/2) =", N / 2, " abs(fft(N/2)) =", N / 2, "\n\n") #filtering f = 40 Hz out of bar graph for i in range(0, 26): print(i)
def model_result_box_plot(result_dict, model_list, data_preprocessing_list, metrics_name_list, title='', x_label='', xlim_range=(0, 15), ylim_range=(0.2, 0.6), metrics_print_list='', plot_baseline=False, baseline_value_tuple=None, baseline_legend_tuple=None, baseline_colour_tuple=None): box_widths = 0.3 box_gap = 0.5 category_gap = 1.5 position_now = 0 category_pos_list = [] fig = figure() ax = axes() hold(True) # Some fake data to plot for model in model_list: X = [] model_result_dict = result_dict[model] for metric in metrics_name_list: metric_value_list = [] for data_preprocessing in data_preprocessing_list: value_list = model_result_dict[data_preprocessing][metric] metric_value_list.extend(value_list) X.append(metric_value_list) # print the highest result for i, metrics_list in enumerate(X): if metrics_list: metric = metrics_name_list[i] if metric == 'rmse_list': max_value = sorted(metrics_list)[0] else: max_value = sorted(metrics_list, reverse=True)[0] print("{}-best {}: {}".format(model, metric, max_value)) # # first boxplot pair position_now += category_gap positions_list, position_now = get_positions(metrics_name_list, position_now, box_gap) category_pos_list.append(np.average(positions_list)) bp = boxplot(X, positions=positions_list, widths=box_widths, sym='+') setBoxColors(bp, metrics_name_list) # set axes limits and labels xlim(*xlim_range) ylim(*ylim_range) ax.set_xticklabels(x_label) ax.set_xticks(category_pos_list) #ax.set_xlabel(x_label) ax.set_title(title) # draw temporary red and blue lines and use them to create a legend h_list = [] shape = '-' legend_list = [ 'b{}'.format(shape), 'r{}'.format(shape), 'g{}'.format(shape), 'c{}'.format(shape), 'y{}'.format(shape), 'm{}'.format(shape) ] if not metrics_print_list: metrics_print_list = metrics_name_list for i, _ in enumerate(metrics_print_list): h = plot([1, 1], legend_list[i])[0] h_list.append(h) #h.set_visible(False) # hB, = plot([1, 1], 'b-') # hR, = plot([1, 1], 'r-') if plot_baseline and baseline_value_tuple: for i, baseline_value in enumerate(baseline_value_tuple): baseline_plot = plt.plot((0, 99), (baseline_value, baseline_value), '{}-'.format(baseline_colour_tuple[i]), dashes=[2, 5])[0] h_list.append(baseline_plot) metrics_print_list.append('{}'.format(baseline_legend_tuple[i])) #legend(baseline_plot, 'baseline' legend(h_list, metrics_print_list) for i, h in enumerate(h_list): if i >= len(baseline_legend_tuple): pass else: h.set_visible(False) # hB.set_visible(False) # hR.set_visible(False) else: print("Check plot baseline and baseline_value_tuple") show()
t = data4['t'] yr = np.array((np.mod(t, 365)), dtype=int) day4 = (t - yr) * 365 plt.close('all') width = 3.5 height = width / 2.5 fig = plt.figure(num=1, figsize=(width, height), facecolor='w', edgecolor='k') fig.set_size_inches(width, height, forward=True) ax = fig.add_axes([0.2, 0.3, 0.75, 0.6]) p4 = ax.plot(day4, (data4['L'] - L) / 1e3, '-', color='slateblue', linewidth=2) p3 = ax.plot(day3, (data3['L'] - L) / 1e3, '--', color='gray', linewidth=2) p2 = ax.plot(day2, (data2['L'] - L) / 1e3, '-.', linewidth=2, color='crimson') plt.xlabel('Time (day)') plt.ylabel(r'$\Delta L$ (km)') plt.ylim([-2, 1]) plt.ylim([-0.5, 0.5]) plt.xlim([0.0, 0.2 * 365]) plt.text(0.13 * 365, 0.3, u'-5\u00B0C', color=p2[0].get_color(), fontsize=10, fontweight='bold') plt.text((0.05 + 0.11) * 365, 0.1, u'-15\u00B0C', color=p3[0].get_color(), fontsize=10, fontweight='bold') plt.text(0.125 * 365,
def plot(self, filename=None): """ Plot vrep and derivative together with fit info. parameters: =========== filename: graphics output file name """ try: import pylab as pl except: raise AssertionError('pylab could not be imported') r = np.linspace(0, self.r_cut) v = [self(x, der=0) for x in r] vp = [self(x, der=1) for x in r] rmin = 0.95 * min([d[0] for d in self.deriv]) rmax = 1.1 * self.r_cut fig = pl.figure() pl.subplots_adjust(wspace=0.25) # Vrep pl.subplot(1, 2, 1) pl.ylabel(r'$V_{rep}(r)$ (eV)') pl.xlabel(r'$r$ ($\AA$)') if self.r_dimer != None: pl.axvline(x=self.r_dimer, c='r', ls=':') pl.axvline(x=self.r_cut, c='r', ls=':') pl.plot(r, v) pl.ylim(ymin=0, ymax=self(rmin)) pl.xlim(xmin=rmin, xmax=self.r_cut) # Vrep' pl.subplot(1, 2, 2) pl.ylabel(r'$dV_{rep}(r)/dr$ (eV/$\AA$)') pl.xlabel(r'$r$ ($\AA$)') pl.plot(r, vp, label=r'$dV_{rep}(r)/dr$') for s in self.deriv: pl.scatter([s[0]], [s[1]], s=100 * s[2], c=s[3], label=s[4]) pl.axvline(x=self.r_cut, c='r', ls=':') if self.r_dimer != None: pl.axvline(x=self.r_dimer, c='r', ls=':') ymin = 0 for point in self.deriv: if rmin <= point[0] <= rmax: ymin = min(ymin, point[1]) ymax = np.abs(ymin) * 0.1 pl.axhline(0, ls='--', c='k') if self.r_dimer != None: pl.text(self.r_dimer, ymax, r'$r_{dimer}$') pl.text(self.r_cut, ymax, r'$r_{cut}$') pl.xlim(xmin=rmin, xmax=rmax) pl.ylim(ymin=ymin, ymax=ymax) #pl.subtitle('Fitting for %s and %s' % (self.sym1, self.sym2)) pl.rc('font', size=10) pl.rc('legend', fontsize=8) pl.legend(loc=4) file = '%s_%s_repulsion.pdf' % (self.sym1, self.sym2) if filename != None: file = filename pl.savefig(file) pl.clf()
# Reta tangente no ponto P tan = f(a) + fprime * (x - a) # Inclinacao da reta secante m = (Qy - f(a)) / (Qx - a) # Reta secante que cruza os pontos P e Q sec = m * (x - a) + f(a) # Imprime informacoes print('Inclinacao da reta secante que une os P(a) e P(b): ', format(m)) print('Inclinacao da reta tangente no ponto P(a): ', format(fprime)) # Plota a funcao, ponto e retas plot(x, y, 'b', label='y(x)') plot(x, tan, '--r', label='tan') plot(x, sec, '--g', label='sec') plot(a, f(a), 'om', label='P') plot(Qx, Qy, 'og', label='Q') # Legenda legend(loc='upper left') # Limites dos eixos xlim(xlim_inf - 0.25, xlim_sup + 0.25) ylim(ylim_inf, ylim_sup) # Imprime quadriculado e exibe grid() show()
def upload(self, fname, gracedb_server=None, testing=True, extra_strings=None): """Upload this trigger to gracedb Parameters ---------- fname: str The name to give the xml file associated with this trigger gracedb_server: string, optional URL to the GraceDB web API service for uploading the event. If omitted, the default will be used. testing: bool Switch to determine if the upload should be sent to gracedb as a test trigger (True) or a production trigger (False). """ from ligo.gracedb.rest import GraceDb import matplotlib matplotlib.use('Agg') import pylab # first of all, make sure the event is saved on disk # as GraceDB operations can fail later self.save(fname) if self.snr_series is not None: if fname.endswith('.xml.gz'): snr_series_fname = fname.replace('.xml.gz', '.hdf') else: snr_series_fname = fname.replace('.xml', '.hdf') snr_series_plot_fname = snr_series_fname.replace('.hdf', '_snr.png') psd_series_plot_fname = snr_series_fname.replace('.hdf', '_psd.png') pylab.figure() for ifo in sorted(self.snr_series): curr_snrs = self.snr_series[ifo] curr_snrs.save(snr_series_fname, group='%s/snr' % ifo) pylab.plot(curr_snrs.sample_times, abs(curr_snrs), c=ifo_color(ifo), label=ifo) if ifo in self.ifos: snr = self.coinc_results['foreground/%s/%s' % (ifo, 'snr')] endt = self.coinc_results['foreground/%s/%s' % (ifo, 'end_time')] pylab.plot([endt], [snr], c=ifo_color(ifo), marker='x') pylab.legend() pylab.xlabel('GPS time (s)') pylab.ylabel('SNR') pylab.savefig(snr_series_plot_fname) pylab.close() pylab.figure() for ifo in sorted(self.snr_series): # Undo dynamic range factor curr_psd = self.psds[ifo].astype(numpy.float64) curr_psd /= pycbc.DYN_RANGE_FAC ** 2.0 curr_psd.save(snr_series_fname, group='%s/psd' % ifo) # Can't plot log(0) so start from point 1 pylab.loglog(curr_psd.sample_frequencies[1:], curr_psd[1:]**0.5, c=ifo_color(ifo), label=ifo) pylab.legend() pylab.xlim([10, 1300]) pylab.ylim([3E-24, 1E-20]) pylab.xlabel('Frequency (Hz)') pylab.ylabel('ASD') pylab.savefig(psd_series_plot_fname) gid = None try: # try connecting to GraceDB gracedb = GraceDb(gracedb_server) \ if gracedb_server is not None else GraceDb() # create GraceDB event group = 'Test' if testing else 'CBC' r = gracedb.createEvent(group, "pycbc", fname, "AllSky").json() gid = r["graceid"] logging.info("Uploaded event %s", gid) if self.is_hardware_injection: gracedb.writeLabel(gid, 'INJ') logging.info("Tagging event %s as an injection", gid) # upload PSDs. Note that the PSDs are already stored in the # original event file and we just upload a copy of that same file # here. This keeps things as they were in O2 and can be removed # after updating the follow-up infrastructure psd_fname = 'psd.xml.gz' if fname.endswith('.gz') else 'psd.xml' gracedb.writeLog(gid, "PyCBC PSD estimate from the time of event", psd_fname, open(fname, "rb").read(), "psd") logging.info("Uploaded PSDs for event %s", gid) # add other tags and comments gracedb.writeLog( gid, "Using PyCBC code hash %s" % pycbc_version.git_hash) extra_strings = [] if extra_strings is None else extra_strings for text in extra_strings: gracedb.writeLog(gid, text, tag_name=['analyst_comments']) # upload SNR series in HDF format and plots if self.snr_series is not None: gracedb.writeLog(gid, 'SNR timeseries HDF file upload', filename=snr_series_fname) gracedb.writeLog(gid, 'SNR timeseries plot upload', filename=snr_series_plot_fname, tag_name=['background'], displayName=['SNR timeseries']) gracedb.writeLog(gid, 'PSD plot upload', filename=psd_series_plot_fname, tag_name=['psd'], displayName=['PSDs']) except Exception as exc: logging.error('Something failed during the upload/annotation of ' 'event %s on GraceDB. The event may not have been ' 'uploaded!', fname) logging.error(str(exc)) return gid
mag = {} mag['g'] = data['decam_g'] - 3.186 * data['ebv'] mag['r'] = data['decam_r'] - 2.140 * data['ebv'] mag['i'] = data['decam_i'] - 1.569 * data['ebv'] mag['z'] = data['decam_z'] - 1.196 * data['ebv'] pylab.figure() pylab.scatter(mag['g'][cut] - mag['r'][cut], mag['r'][cut] - mag['z'][cut], c=data['feh50'][cut], s=2, vmin=-3.5, vmax=0.5) pylab.colorbar(label='[Fe/H]') pylab.xlim(0.2, 1.1) pylab.ylim(0.0, 0.6) pylab.xlabel('g - r (mag)') pylab.ylabel('r - z (mag)') d = (1 / data.parallax) pylab.figure() pylab.scatter(mag['g'][cut] - mag['r'][cut], mag['r'][cut] - mag['z'][cut], c=d[cut], s=2, vmin=0., vmax=15.) pylab.colorbar(label='distance') pylab.xlim(0.2, 1.1) pylab.ylim(0.0, 0.6) pylab.xlabel('g - r (mag)')
if True: errs_dn = n.where(errs >= C_l1 - 1e-6, C_l1 - 1e-6, Errs) p.errorbar(ells, C_l1, [errs_dn, errs], fmt='.-', label='ch%fcl' % ch, color=color) else: p.plot(ells, C_l1, '.-', label='ch%fcl' % ch, color=color) p.plot(ells, C_l2, '-.', label='ch%ftherm' % ch, color=color) #p.plot(ells, .5*errs, 'k-.') #p.plot(ells, c_l3, ':', label='ch%ffit' % ch, color=color) #p.plot(ells, wgts, 'r-') print '}' p.plot(ells, 10**n.polyval(C_l_sim, n.log10(ells)), 'k-', label='z=9.2_santos2005', linewidth=4) p.plot(ells, C_l_sync(ells, 147.), 'k:', label='sync') ax = p.gca() ax.set_xscale('log') ax.set_yscale('log') #p.xlim(60,1e3) p.xlim(1e2, 1e3) p.ylim(1e-1, 1e11) p.xlabel(r'$\ell=2\pi u$', fontsize=20) p.ylabel(r'$\ell(\ell+1)C_\ell/2\pi\ \ (mK^2)$', fontsize=20) p.show()
def display_filename(pickle_filename, name=None): print "Loading data to display..." data = pickle.load(open(pickle_filename, 'rb')) coll, xlabel, ylabel = data if not name: name = pickle_filename.split('/')[3] def normalize(val, low, high): return (val - low) / (high - low) num_features = actual.NUM_FEATURES ms = [] ss = [] for i in range(num_features): ms.append([]) ss.append([]) # find ranges of values for value in coll: (bp, force, i, j, means, stds) = value #(bp, force, i, j, sfmm, sfmstd) = value for i in range(num_features): ms[i].append(means[i]) ss[i].append(stds[i]) #ms[0].append(sfmm) #ss[0].append(sfmstd) print "Generating plots..." #m = 0 ### for schelleng force ri = 7 gi = 0 bi = 7 ### for accel? #ri = 0 #gi = 1 #bi = 7 power = 0.5 invert = False #invert = True if PLOT_PNG_BARE: fig = pylab.figure() fig.set_size_inches(4, 3) ax = pylab.Axes(fig, [ 0., 0., 1., 1., ]) else: fig = pylab.figure() pylab.title("%s" % (name)) fig.set_size_inches(16, 12) numx = xlabel.num numy = ylabel.num img = numpy.zeros((numy, numx, 3), dtype=numpy.float32) min_ms_ri = min(ms[ri]) min_ms_gi = min(ms[gi]) min_ms_bi = min(ms[bi]) max_ms_ri = max(ms[ri]) max_ms_gi = max(ms[gi]) max_ms_bi = max(ms[bi]) min_ss_ri = min(ms[ri]) max_ss_ri = max(ms[ri]) print "got min/max" for value in coll: (bp, force, i, j, means, stds) = value #(bp, force, i, j, sfmm, sfmstd) = value x = bp y = force #r = normalize(means[ri], min(ms[ri]), max(ms[ri])) g = normalize(means[gi], min_ms_gi, max_ms_gi) b = normalize(means[bi], min_ms_bi, max_ms_bi) r = normalize(stds[ri], min_ss_ri, max_ss_ri) if invert: r = 1. - r**power g = 1. - g**power b = 1. - b**power else: r = r**power g = g**power b = b**power #text = "%.3f\t%.3f\t%.3f\t%.3f\t%.3f" % (x,y,r,g,b) #out.write(text + "\n") #pylab.plot(x,y, '.', color=(r,g,b), markersize=10) #pylab.semilogy(x,y, '.', color=(r,g,b), markersize=10) img[i][j][0] = r img[i][j][1] = g img[i][j][2] = b print "start imshow" if PLOT_PNG_BARE: ax.imshow( img, #interpolation='bilinear', aspect="auto", origin="lower", ) ax.set_xlim(0, numx - 1) ax.set_ylim(0, numy - 1) else: pylab.imshow( img, #interpolation='bilinear', aspect="auto", origin="lower", ) pylab.xlim(0, numx - 1) pylab.ylim(0, numy - 1) print "end imshow" for m in range(5, 10): modal = 1.0 / m relpos = 1.0 - (xlabel.high - modal) / (xlabel.high - xlabel.low) abspos = relpos * (numx - 1) print abspos, if xlabel.log: abspos = numpy.log(abspos) print abspos #print m, modal, relpos, abspos if PLOT_PNG_BARE: pass #ax.axvline(abspos, color="yellow") else: #pylab.axvline(abspos, color="yellow") pass xlocs = numpy.linspace(0, numx - 1, 11) ylocs = numpy.linspace(0, numy - 1, 11) if xlabel.log: xticks = map( lambda d: str("%.3f" % d), numpy.exp( numpy.linspace(numpy.log(xlabel.low), numpy.log(xlabel.high), len(xlocs)))) else: xticks = map(lambda d: str("%.3f" % d), numpy.linspace(xlabel.low, xlabel.high, len(xlocs))) if ylabel.log: yticks = map( lambda d: str("%.2f" % d), numpy.exp( numpy.linspace(numpy.log(ylabel.low), numpy.log(ylabel.high), len(ylocs)))) else: yticks = map(lambda d: str("%.2f" % d), numpy.linspace(ylabel.low, ylabel.high, len(ylocs))) if True: pylab.xticks(xlocs, xticks) pylab.xlabel(xlabel.title) pylab.yticks(ylocs, yticks) pylab.ylabel(ylabel.title) if PLOT_STD: pylab.figure() pylab.title("Standard deviations for %s" % (name)) pylab.xlim(XB_MIN, XB_MAX) power = 0.5 for value in coll: (bp, force, i, j, means, stds) = value x = bp y = force r = normalize(stds[ri], min(ss[ri]), max(ss[ri])) g = normalize(stds[gi], min(ss[gi]), max(ss[gi])) b = normalize(stds[bi], min(ss[bi]), max(ss[bi])) r = r**power g = g**power b = b**power pylab.plot(x, y, '.', color=(r, g, b), markersize=10) if PLOT_COMBO: pylab.figure() pylab.title("Combo for %s" % (name)) pylab.xlim(XB_MIN, XB_MAX) power = 0.5 ri = 0 gi = 3 bi = 3 for value in coll: (bp, force, i, j, means, stds) = value x = bp y = force r = normalize(means[ri], min(ms[ri]), max(ms[ri])) g = normalize(stds[gi], min(ss[gi]), max(ss[gi])) b = normalize(means[bi], min(ms[bi]), max(ms[bi])) r = r**power g = g**power b = b**power pylab.plot(x, y, '.', color=(r, g, b), markersize=10) #pylab.axis('off') #pylab.yscale('log') filename = name + ".png" if PLOT_PNG_BARE: ax.set_axis_off() fig.add_axes(ax) #pylab.title('') #pylab.savefig(name+".png", bbox_inches='tight', pad_inches=0) extent = ax.get_window_extent().transformed( fig.dpi_scale_trans.inverted()) pylab.savefig(filename, bbox_inches=extent) print "filename:\tX:", xlabel.title, xlabel.low, xlabel.high print "\t\tY:", ylabel.title, ylabel.low, ylabel.high else: pylab.savefig(filename) print "... done"
pl.subplot(2, 2, 1) a = pendulums(9.8, 3 * math.pi / 1000) a.calculation(0.5, 0.2, 0, 1.4, 2 / 3, 3 * math.pi * 2000) showangle = [] showomega = [] for i in range(10000, len(a.t)): if ((2 / 3) * (a.t[i])) % (2 * (math.pi)) < 0.001: showangle.append(a.angle[i]) showomega.append(a.omega[i]) pl.plot(showangle, showomega, '.', label='$2/3t=2\pi n$') pl.xlabel('Angle ($rad$)') pl.ylabel('Angular ($rad/s$)') pl.xlim(-4, 4) pl.ylim(-2, 2) pl.legend(loc='best') pl.subplot(2, 2, 2) a = pendulums(9.8, 3 * math.pi / 1000) a.calculation(0.5, 0.2, 0, 1.4, 2 / 3, 3 * math.pi * 2000) showangle = [] showomega = [] for i in range(10000, len(a.t)): if ((2 / 3) * (a.t[i]) - math.pi / 4) % (2 * (math.pi)) < 0.001: showangle.append(a.angle[i]) showomega.append(a.omega[i]) pl.plot(showangle, showomega, '.', label='$2/3t=2\pi n+\pi/4$') pl.xlabel('Angle ($rad$)') pl.ylabel('Angular ($rad/s$)') pl.xlim(-4, 4)
def main(argv=None): """script main. parses command line options in sys.argv, unless *argv* is given. """ if argv is None: argv = sys.argv parser = E.OptionParser( version= "%prog version: $Id: plot_matrix.py 2782 2009-09-10 11:40:29Z andreas $" ) parser.add_option("-c", "--columns", dest="columns", type="string", help="columns to take from table.") parser.add_option("-a", "--hardcopy", dest="hardcopy", type="string", help="write hardcopy to file.", metavar="FILE") parser.add_option("-f", "--file", dest="input_filename", type="string", help="filename with table data.", metavar="FILE") parser.add_option("-p", "--plot", dest="plot", type="string", help="plots to plot.", action="append") parser.add_option("-t", "--threshold", dest="threshold", type="float", help="min threshold to use for counting method.") parser.add_option("-o", "--colours", dest="colours", type="int", help="column with colour information.") parser.add_option("-l", "--plot-labels", dest="labels", type="string", help="column labels for x and y in matched plots.") parser.add_option("-e", "--header-names", dest="headers", action="store_true", help="headers are supplied in matrix.") parser.add_option("--no-headers", dest="headers", action="store_false", help="headers are not supplied in matrix.") parser.add_option("--normalize", dest="normalize", action="store_true", help="normalize matrix.") parser.add_option("--palette", dest="palette", type="choice", choices=("rainbow", "gray", "blue-white-red", "autumn", "bone", "cool", "copper", "flag", "gray", "hot", "hsv", "jet", "pink", "prism", "spring", "summer", "winter", "spectral", "RdBu", "RdGy", "BrBG", "BuGn", "Blues", "Greens", "Reds", "Oranges", "Greys"), help="colour palette [default=%Default]") parser.add_option("--reverse-palette", dest="reverse_palette", action="store_true", help="reverse the palette [default=%default].") parser.add_option("", "--xrange", dest="xrange", type="string", help="xrange.") parser.add_option("", "--yrange", dest="yrange", type="string", help="yrange.") parser.add_option("", "--zrange", dest="zrange", type="string", help="zrange.") parser.add_option("", "--xticks", dest="xticks", type="string", help="xticks.") parser.add_option("", "--yticks", dest="yticks", type="string", help="yticks.") parser.add_option("--bar-format", dest="bar_format", type="string", help="format for ticks on colourbar.") parser.add_option("--title", dest="title", type="string", help="title to use.") parser.add_option("--missing-value", dest="missing", type="float", help="value to use for missing data.") parser.add_option( "--subplots", dest="subplots", type="string", help= "split matrix into several subplots. Supply number of rows and columns separated by a comma." ) parser.set_defaults(hardcopy=None, input_filename="-", columns="all", statistics=[], plot=[], threshold=0.0, labels="x,y", colours=None, xrange=None, yrange=None, zrange=None, palette=None, reverse_palette=False, xticks=None, yticks=None, normalize=False, bar_format="%1.1f", headers=True, missing=None, title=None, subplots=None) (options, args) = E.start(parser) # import matplotlib/pylab. Has to be done here # for batch scripts without GUI. import matplotlib if options.hardcopy: matplotlib.use("cairo") import pylab if len(args) > 0: options.input_filename = ",".join(args) if options.xticks: options.xticks = options.xticks.split(",") if options.yticks: options.yticks = options.yticks.split(",") if options.xrange: options.xrange = list(map(float, options.xrange.split(","))) if options.yrange: options.yrange = list(map(float, options.yrange.split(","))) if options.columns != "all": options.columns = [int(x) - 1 for x in options.columns.split(",")] filenames = options.input_filename.split(",") if len(filenames) > 1: nsubrows = (len(filenames) / 3) + 1 nsubcols = 3 elif options.subplots: nsubrows, nsubcols = [int(x) for x in options.subplots.split(",")] else: nsubrows, nsubcols = 1, 1 nsubplots = nsubrows * nsubcols # Setting up color maps if options.palette: if options.palette == "gray": _gray_data = { 'red': ((0., 1, 1), (1., 0, 0)), 'green': ((0., 1, 1), (1., 0, 0)), 'blue': ((0., 1, 1), (1., 0, 0)) } LUTSIZE = pylab.rcParams['image.lut'] colors_gray = matplotlib.colors.LinearSegmentedColormap( 'gray', _gray_data, LUTSIZE) plot_id = 0 for filename in filenames: plot_id += 1 pylab.subplot(nsubrows, nsubcols, plot_id) if filename == "-": infile = sys.stdin else: infile = IOTools.open_file(filename, "r") matrix, row_headers, col_headers = MatlabTools.readMatrix( infile, numeric_type=numpy.float32, take=options.columns, headers=options.headers, missing=options.missing) if min(matrix.flat) == max(matrix.flat): options.stderr.write("matrix is uniform - no plotting done.\n") sys.exit(0) if options.normalize: v = max(matrix.flat) matrix = matrix / v if options.zrange: options.zrange = GetRange(matrix, options.zrange) nrows, ncols = matrix.shape if options.palette: if options.palette == "gray": color_scheme = colors_gray else: if options.reverse_palette: color_scheme = eval("pylab.cm.%s_r" % options.palette) else: color_scheme = eval("pylab.cm.%s" % options.palette) else: color_scheme = None if options.zrange: vmin, vmax = options.zrange matrix[matrix < vmin] = vmin matrix[matrix > vmax] = vmax else: vmin, vmax = None, None if options.subplots: if nsubcols > 1: increment_x = int(float(nrows + 1) / nsubcols) increment_y = nrows x = 0 y = 0 for n in range(nsubplots): pylab.subplot(nsubrows, nsubcols, plot_id) plot_id += 1 print(n, "rows=", nsubrows, "cols=", nsubcols, y, y + increment_y, x, x + increment_x) print(matrix[y:y + increment_y, x:x + increment_x].shape) print(matrix.shape) plotMatrix(matrix[y:y + increment_y, x:x + increment_x], color_scheme, row_headers[y:y + increment_y], col_headers[x:x + increment_x], 0, 100, options) x += increment_x elif nsubrows > 1: increment_x = int(float(ncols + 1) / nsubrows) x = 0 for n in range(nsubplots): pylab.subplot(nsubrows, nsubcols, plot_id) plot_id += 1 plotMatrix(matrix[0:nrows, x:x + increment_x], color_scheme, row_headers, col_headers[x:x + increment_x], vmin, vmax, options) x += increment_x else: plotMatrix(matrix, color_scheme, row_headers, col_headers, vmin, vmax, options) if options.xrange: pylab.xlim(options.xrange) if options.yrange: pylab.ylim(options.yrange) if options.labels: xlabel, ylabel = options.labels.split(",") pylab.xlabel(xlabel) pylab.ylabel(ylabel) if not options.subplots: pylab.colorbar(format=options.bar_format) if options.title is None or options.title != "": pylab.title(filename) if options.hardcopy: pylab.savefig(os.path.expanduser(options.hardcopy)) else: pylab.show() E.stop()
h = .02 # step size in the mesh clf = svm.SVC(C=1.0, kernel='linear') # we create an instance of SVM Classifier and fit the data. clf.fit(X, Y) # Plot the decision boundary. For that, we will assign a color to each # point in the mesh [x_min, m_max]x[y_min, y_max]. x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5 y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) pl.figure(1, figsize=(4, 3)) pl.pcolormesh(xx, yy, Z, cmap=pl.cm.Paired) # Plot also the training points pl.scatter(X[:, 0], X[:, 1], c=Y, cmap=pl.cm.Paired) pl.xlabel('Sepal length') pl.ylabel('Sepal width') pl.xlim(xx.min(), xx.max()) pl.ylim(yy.min(), yy.max()) pl.xticks(()) pl.yticks(()) pl.show()
def save_HDF5_to_plot(h5fname, img_path=None, axis_unit=None, map_unit=None, cmap="jet", cmap_range=None,\ fraction=None, save_into_png=True, discrete=False, verbose=True):#{{{ r""" Function that plots the map with axis + colorbar from an HDF5 file Parameters ---------- h5fname : the name of the HDF5 file containing the map img_path : the path in wich the plot img file is to be saved axis_unit : a (length_unit_label, axis_scale_factor) tuple containing : * the label of the u/v axes unit * the scaling factor of the u/v axes unit, or a Unit instance map_unit : a (map_unit_label, map_scale_factor) tuple containing : * the label of the map unit * the scaling factor of the map unit, or a Unit instance cmap : a Colormap object or any default python colormap string cmap_range : a [vmin, vmax] array for map values clipping (linear scale) fraction : fraction of the total map values below the min. map range (in percent) save_into_png: whether the plot is saved into an png file or not (default True) discrete : wheter the map values are discrete integer values (default False). for colormap """ h5f = tables.openFile(h5fname, 'r') cam = Camera.from_HDF5(h5f) map = h5f.getNode("/map/map").read() if cam.log_sensitive and pymses.__revision__ >= '$Revision: 705$': map = apply_log_scale(map) map_unit_label = None if map_unit is not None: map_unit_label, map_scale_factor = map_unit if isinstance(map_scale_factor, Unit): try: d = h5f.getNode("/map/unit/dimensions").read() v = h5f.getNode("/map/unit/val").read() except: raise ValueError( "map unit record not found in '%s' HDF5 file" % h5fname) mu = Unit(d, v) map_scale_factor = mu.express(map_scale_factor) if cam.log_sensitive: map = map + numpy.log10(map_scale_factor) else: map = map * map_scale_factor nx, ny = map.shape map = map.transpose() vmin, vmax = get_map_range(map, cam.log_sensitive, cmap_range, fraction) colormap, vmin, vmax = get_Colormap(cmap, discrete, (vmin, vmax)) vrange = [vmin, vmax] if cam.log_sensitive: vrange = [10.**vmin, 10.**vmax] if verbose: print("Colormap range is : [%e, %e]" % (vrange[0], vrange[1])) map = numpy.clip(map, vmin, vmax) uedges, vedges = cam.get_pixels_coordinates_edges() uaxis, vaxis, zaxis = cam.get_camera_axis() ulabel = 'u' vlabel = 'v' ax_dict = {'x': 0, 'y': 1, 'z': 2} for axname, axis in list(Camera.special_axes.items()): if (numpy.abs(uaxis) == numpy.abs(axis)).all(): ulabel = axname uedges = uedges + cam.center[ax_dict[axname]] if (uaxis != axis).any(): uedges = uedges[::-1] break for axname, axis in list(Camera.special_axes.items()): if (numpy.abs(vaxis) == numpy.abs(axis)).all(): vlabel = axname vedges = vedges + cam.center[ax_dict[axname]] if (vaxis != axis).any(): vedges = vedges[::-1] break uvaxis_unit_label = 'box size unit' if axis_unit is not None: uvaxis_unit_label, axis_scale_factor = axis_unit if isinstance(axis_scale_factor, Unit): try: d = h5f.getNode("/map/length_unit/dimensions").read() v = h5f.getNode("/map/length_unit/val").read() except: raise ValueError( "length_unit record not found in '%s' HDF5 file" % h5fname) au = Unit(d, v) axis_scale_factor = au.express(axis_scale_factor) uedges = uedges * axis_scale_factor vedges = vedges * axis_scale_factor fig = pylab.figure() pylab.pcolormesh(uedges, vedges, map, cmap=colormap, vmin=vmin, vmax=vmax) pylab.xlabel("%s (%s)" % (ulabel, uvaxis_unit_label)) pylab.xlim(uedges[0], uedges[-1]) pylab.ylabel("%s (%s)" % (vlabel, uvaxis_unit_label)) pylab.ylim(vedges[0], vedges[-1]) pylab.gca().set_aspect('equal') # Pretty user-defined colorbar if cam.log_sensitive: fo = pylab.matplotlib.ticker.FormatStrFormatter("$10^{%d}$") offset = numpy.ceil(vmin) - vmin lo = pylab.matplotlib.ticker.IndexLocator(1.0, offset) cb = pylab.colorbar(ticks=lo, format=fo) else: if discrete: fo = pylab.matplotlib.ticker.FormatStrFormatter("%d") ncol = int(round(vmax - vmin)) ti = numpy.linspace(vmin + 0.5, vmax - 0.5, ncol) cb = pylab.colorbar(format=fo, ticks=ti) else: cb = pylab.colorbar() if map_unit_label is not None: cb.set_label(map_unit_label) if img_path is None: h5f.close() return fig else: if save_into_png: fname = "%s.png" % h5f.getNode("/name").read() fname = os.path.join(img_path, fname) print("Saving plot into '%s'" % fname) try: pylab.savefig(fname) except: os.mkdir(img_path) pylab.savefig(fname) h5f.close() return
# SOURCE: https://gist.github.com/andrewgiessel/5684769 # good discussion here: http://stackoverflow.com/questions/4308168/sigmoidal-regression-with-scipy-numpy-python-etc # curve_fit() example from here: http://permalink.gmane.org/gmane.comp.python.scientific.user/26238 # other sigmoid functions here: http://en.wikipedia.org/wiki/Sigmoid_function import numpy as np import pylab from scipy.optimize import curve_fit def sigmoid(x, x0, k): y = 1 / (1 + np.exp(-k * (x - x0))) return y xdata = np.array([0.0, 1.0, 3.0, 4.3, 7.0, 8.0, 8.5, 10.0, 12.0]) ydata = np.array([0.01, 0.02, 0.04, 0.11, 0.43, 0.7, 0.89, 0.95, 0.99]) popt, pcov = curve_fit(sigmoid, xdata, ydata) print(popt) x = np.linspace(-1, 15, 50) print(x) y = sigmoid(x, *popt) print(y) pylab.plot(xdata, ydata, 'o', label='data') pylab.plot(x, y, label='fit') pylab.ylim(0, 1.05) pylab.legend(loc='best') pylab.show()
#labels = ['feed alone 3ft above ground','feed alone 3ft above absorber','feed in cage on ground','feed in cage on absorber','feed in cage upsidedown'] valids = ['C_NC41', 'C_NC41_AB'] labels = ['feed in cage on ground', 'feed in cage on absorber'] fig, ax = p.subplots(nrows=1, ncols=1) for i, v in enumerate(valids): fq, amps = fromcsv(file_base + str(v) + amp_end) fq, phs = fromcsv(file_base + str(v) + phs_end) #bandwidth = n.where(n.logical_and(fq>.05 ,fq<.25)) #HERA bandwidth #bandwidth = n.where(n.logical_and(fq>.1,fq<.2)) #PAPER bandwidth bandwidth = n.where(n.logical_and(fq > .05, fq < .5)) #full bandwidth dw, d, tau = take_delay(amps[bandwidth], phs[bandwidth], fq[bandwidth]) # p.plot(tau, 10*n.log10(n.abs(dw)**2), linewidth=2, label=('%s'%v)+'ft', color=colors[i]) ax.plot(tau, 10 * n.log10(n.abs(dw)**2), linewidth=2, label=labels[i], color=colors[i]) p.xlim(-30, 350) p.ylim(-100, 1) p.vlines(60, -100, 100, linestyle='--', linewidth=2) p.hlines(-60, -100, 500, linestyle='--', linewidth=2) p.xlabel('delay (ns)') p.ylabel('return loss (dB)') p.grid(1) p.legend() fig.subplots_adjust(left=.08, top=.95, bottom=.10, right=0.92) p.show()
colors = 'brgkcmbrgkcm' lines, names = [], [] for fileN, thisStair in enumerate(allIntensities): #lines.extend(pylab.plot(thisStair)) #names = files[fileN] pylab.plot(thisStair, label=files[fileN]) #pylab.legend() #get combined data combinedInten, combinedResp, combinedN = \ data.functionFromStaircase(allIntensities, allResponses, 5) #fit curve - in this case using a Weibull function fit = data.FitFunction('weibullTAFC',combinedInten, combinedResp, \ guess=[0.2, 0.5]) smoothInt = pylab.arange(min(combinedInten), max(combinedInten), 0.001) smoothResp = fit.eval(smoothInt) thresh = fit.inverse(0.8) print thresh #plot curve pylab.subplot(122) pylab.plot(smoothInt, smoothResp, '-') pylab.plot([thresh, thresh], [0, 0.8], '--')pylab.plot([0, thresh],\ [0.8,0.8],'--') pylab.title('threshold = %0.3f' % (thresh)) #plot points pylab.plot(combinedInten, combinedResp, 'o') pylab.ylim([0, 1]) pylab.show()
# top_edge - mean(right-edge) sensor_1_array = density_hydro[q2_index, q1_index] - np.mean(density_hydro[:, -1]) sensor_2_array = density_ballistic[q2_index, q1_index] - np.mean( density_ballistic[:, -1]) sensor_3_array = density_ohmic[q2_index, q1_index] - np.mean(density_ohmic[:, -1]) np.savetxt("R_vs_L_hydro.txt", sensor_1_array) np.savetxt("R_vs_L_ballistic.txt", sensor_2_array) np.savetxt("R_vs_L_ohmic.txt", sensor_3_array) np.savetxt("bottom_edge.txt", x[q1_index, q2_index]) pl.plot(x[q1_index, q2_index], sensor_1_array, label="Hydro") pl.plot(x[q1_index, q2_index], sensor_2_array, label="Ballistic") pl.plot(x[q1_index, q2_index], sensor_3_array, label="Ohmic") pl.axhline(0, color='k', ls='--') pl.ylim(ymax=150) #pl.gca().set_aspect('equal') pl.ylabel(r'$n$') pl.xlabel(r'x ($\mu$m)') pl.legend(loc='best') #pl.suptitle('$\\tau_\mathrm{mc} = \infty$, $\\tau_\mathrm{mr} = \infty$') #pl.suptitle('$\\tau_\mathrm{mc} = 0.1$, $\\tau_\mathrm{mr} = \infty$') pl.savefig('images/iv.png') pl.clf()
import scipy as SP import pylab as PL import os #import cPickle import scipy.misc import sys import pdb #import pyplot #from models import * if __name__ == '__main__': X = SP.linspace(-5, 5, 100) y_res = 0.5 + 0.5 * SP.exp(-SP.absolute(X)) y_sus = 0.5 - 0.2 * SP.exp(-SP.absolute(X)) PL.figure(figsize=[10, 3]) p0 = PL.plot(X, y_res, linewidth=2) p1 = PL.plot(X, y_sus, 'k-', linewidth=2) PL.ylim([0, 1]) PL.yticks([0, 0.25, 0.5, 0.75, 1.0]) PL.legend([p0, p1], ['res', 'sus']) PL.xlabel('Distance') PL.ylabel('Frequency, resistant parent') #PL.savefig('freq_parent.pdf') PL.show()
def test2(self): """A 1-d example, to test the stray-flux assignment. """ H, W = 1, 100 fpbb = geom.Box2I(geom.Point2I(0, 0), geom.Point2I(W - 1, H - 1)) afwimg = afwImage.MaskedImageF(fpbb) img = afwimg.getImage().getArray() var = afwimg.getVariance().getArray() var[:, :] = 1. y = 0 img[y, 1:-1] = 10. img[0, 1] = 20. img[0, -2] = 20. fakepsf_fwhm = 1. fakepsf = gaussianPsf(1, 1, fakepsf_fwhm) # Run the detection code to get a ~ realistic footprint thresh = afwDet.createThreshold(5., 'value', True) fpSet = afwDet.FootprintSet(afwimg, thresh, 'DETECTED', 1) fps = fpSet.getFootprints() self.assertEqual(len(fps), 1) fp = fps[0] # WORKAROUND: the detection alg produces ONE peak, at (1,0), # rather than two. self.assertEqual(len(fp.getPeaks()), 1) fp.addPeak(W - 2, y, float("NaN")) # print 'Added peak; peaks:', len(fp.getPeaks()) # for pk in fp.getPeaks(): # print ' ', pk.getFx(), pk.getFy() # Change verbose to False to quiet down the meas_deblender.baseline logger deb = deblend( fp, afwimg, fakepsf, fakepsf_fwhm, verbose=True, fitPsfs=False, ) if doPlot: XX = np.arange(W + 1).repeat(2)[1:-1] plt.clf() p1 = plt.plot(XX, img[y, :].repeat(2), 'g-', lw=3, alpha=0.3) for i, dpk in enumerate(deb.peaks): print(dpk) port = dpk.fluxPortion.getImage() bb = port.getBBox() YY = np.zeros(XX.shape) YY[bb.getMinX() * 2:(bb.getMaxX() + 1) * 2] = port.getArray()[0, :].repeat(2) p2 = plt.plot(XX, YY, 'r-') simg = afwImage.ImageF(fpbb) dpk.strayFlux.insert(simg) p3 = plt.plot(XX, simg.getArray()[y, :].repeat(2), 'b-') plt.legend((p1[0], p2[0], p3[0]), ('Parent Flux', 'Child portion', 'Child stray flux')) plt.ylim(-2, 22) plt.savefig(plotpat % 3) strays = [] for i, dpk in enumerate(deb.deblendedParents[0].peaks): simg = afwImage.ImageF(fpbb) dpk.strayFlux.insert(simg) strays.append(simg.getArray()) ssum = reduce(np.add, strays) starget = np.zeros(W) starget[2:-2] = 10. self.assertFloatsEqual(ssum, starget) X = np.arange(W) dx1 = X - 1. dx2 = X - (W - 2) f1 = (1. / (1. + dx1**2)) f2 = (1. / (1. + dx2**2)) strayclip = 0.001 fsum = f1 + f2 f1[f1 < strayclip * fsum] = 0. f2[f2 < strayclip * fsum] = 0. s1 = f1 / (f1 + f2) * 10. s2 = f2 / (f1 + f2) * 10. s1[:2] = 0. s2[-2:] = 0. if doPlot: p4 = plt.plot(XX, s1.repeat(2), 'm-') plt.plot(XX, s2.repeat(2), 'm-') plt.legend((p1[0], p2[0], p3[0], p4[0]), ('Parent Flux', 'Child portion', 'Child stray flux', 'Expected stray flux')) plt.ylim(-2, 22) plt.savefig(plotpat % 4) # test abs diff d = np.max(np.abs(s1 - strays[0])) self.assertLess(d, 1e-6) d = np.max(np.abs(s2 - strays[1])) self.assertLess(d, 1e-6) # test relative diff self.assertLess(np.max(np.abs(s1 - strays[0]) / np.maximum(1e-3, s1)), 1e-6) self.assertLess(np.max(np.abs(s2 - strays[1]) / np.maximum(1e-3, s2)), 1e-6)
def MultiBatteryBarChart(report_list, interactive=False, legenddata=(), title=""): """Create a bar chart with that places similar conditions together for comparison. Reports with matching metadata should be grouped together in the list. """ import pylab from matplotlib.font_manager import FontProperties from matplotlib import colors if not interactive: pylab.ioff() build = report_list[0].metadata.build N = len(report_list) barwidth = 1.0 / 8.0 patches = [] labels = [] thefig = pylab.gcf() thefig.set_size_inches((11, 7)) thefig.set_dpi(80.0) pylab.title("Battery Life (%s) %s" % (build.id, title)) pylab.subplots_adjust(left=0.07, bottom=0.05, right=0.55, top=0.95) group = 0 last_report = None for index, battery_report in enumerate(report_list): lifetime = float(battery_report.lifetime.hours) blue = aid.IF(battery_report.byvoltage, 0.0, 0.5) color = colors.rgb2hex( (aid.IF(battery_report.estimated, 1.0, 0.0), (index * 0.05) % 1.0, (group * 0.1) % 1.0)) if last_report and \ last_report.metadata.CompareData(battery_report.metadata, legenddata, missingok=True): label = "(%s) - (%.2f h)" % (index + 1, lifetime) else: label = "(%s) %s (%.2f h)" % ( index + 1, battery_report.metadata.GetStateString(*legenddata), lifetime) group += 1 #pylab.bar(index + group, 0, width=barwidth) # spacer patchlist = pylab.bar(index + group, lifetime, width=barwidth, color=color, label=label) labels.append(label) patches.extend(patchlist) last_report = battery_report pylab.ylim(0.0, 200.0) pylab.xlim(-barwidth, N) # label index is origin 1. x_range = pylab.arange(N) pylab.xticks(x_range + (barwidth / 2.0), map(str, x_range + 1), fontsize=10) pylab.ylabel('Time (h)') if legenddata: font = FontProperties(size=9) pylab.figlegend(patches, labels, "upper right", prop=font) if interactive: pylab.show() else: fname = "batterylife_group-%s.png" % ( report_list[0].metadata.timestamp.strftime("%m%d%H%M%S")) pylab.savefig(fname, format="png") return fname
'figure.figsize': fig_size } pl.rcParams.update(params) pl.figure(1) pl.axes([0.125, 0.15, 0.95 - 0.125, 0.95 - 0.15]) pl.plot(eVV - muVV, dVV, 'b-', label='V 0K') pl.plot(eVV - muVV300, dVVep300, 'g-', label='V 300K') pl.plot(eVV - muVV1000, dVVep1000, 'r-', label='V 1000K') pl.legend() pl.plot(eVV, dVVep300, 'g--', label=None) pl.plot(eVV, dVVep1000, 'r--', label=None) pl.xlabel('$E-\mu(T)$ (eV)') pl.ylabel('(states/eV/at.)') pl.xlim((-0.7, 0.7)) pl.ylim((0, 3.0)) pl.grid(True) pl.figure(2) pl.axes([0.125, 0.15, 0.95 - 0.125, 0.95 - 0.15]) pl.ylim((0, 3.0)) pl.plot(eVCo - muVCo, dVCo, 'b-', label='V$_{15}$Co$_1$ 0K') pl.plot(eVCo - muVCo300, dVCoep300, 'g-', label='V$_{15}$Co$_1$ 300K') pl.plot(eVCo - muVCo1000, dVCoep1000, 'r-', label='V$_{15}$Co$_1$ 1000K') pl.legend() pl.plot(eVCo, dVCoep300, 'g--', label=None) pl.plot(eVCo, dVCoep1000, 'r--', label=None) pl.xlabel('$E-\mu(T)$ (eV)') pl.ylabel('(states/eV/at.)') pl.xlim((-0.7, 0.7)) pl.ylim((0, 3.0))
range=((7, 12), (0, 0.4)), bins=60) plt.savefig( '/home/ssamurof/massive_black_ii/plots/sanity/2dhist-satellite-bmoffset-barmass.png' ) exit() Hc, xc = np.histogram(dr[select & cflag] / 1000, range=(0, 0.4), bins=65, normed=1) Hs, xs = np.histogram(dr[select & np.invert(cflag)] / 1000, range=(0, 0.4), bins=65, normed=1) x = (xs[:-1] + xs[1:]) / 2 plt.fill_between(x, Hc, color='purple', alpha=0.2, lw=1.5, label='Centrals') plt.plot(x, Hs, color='royalblue', lw=1.5, label='Satellites') plt.legend(loc='upper right', fontsize=18) plt.xlabel('Baryon - Matter offset $\delta r$ / Mpc $h^{-1}$', fontsize=18) plt.yticks(visible=False) plt.subplots_adjust(bottom=0.14) plt.ylim(ymin=0) plt.savefig( '/home/ssamurof/massive_black_ii/plots/sanity/baryon-matter_offset-subhalos.png' )
def MultiBuildBatteryBarChart(report_list, interactive=False, autoscale=False, legenddata=()): """Create a bar chart given a list of battery life reports.""" # same as above. import pylab from matplotlib.font_manager import FontProperties from matplotlib import colors if not interactive: pylab.ioff() N = len(report_list) barwidth = 1.0 / N + 0.1 thefig = pylab.gcf() thefig.set_size_inches((11, 6)) thefig.set_dpi(80.0) pylab.subplots_adjust(left=0.07, bottom=0.05, right=0.75, top=0.95) max_lifetime = 0.0 patches = [] labels = [] pylab.title("Battery comparison: %s" % (report_list[0].metadata.GetStateString(*legenddata)), fontsize="small") for index, battery_report in enumerate(report_list): lifetime = float(battery_report.lifetime.hours) max_lifetime = max(lifetime, max_lifetime) blue = aid.IF(battery_report.byvoltage, 0.0, 0.5) color = colors.rgb2hex( aid.IF(battery_report.estimated, ((index * 0.1) % 1.0, 0.5, blue), ((index * 0.1) % 1.0, 1.0, blue))) label = "(%s) %s (%.2f h)" % (index + 1, battery_report.metadata.build.id, battery_report.lifetime.hours) patchlist = pylab.bar(index, lifetime, width=barwidth, color=color, label=label) labels.append(label) patches.extend(patchlist) if autoscale: pylab.ylim(0.0, max_lifetime + 20.0) else: pylab.ylim(0.0, 200.0) pylab.xlim(-barwidth, N) # labels are position offset by +1. pylab.xticks(pylab.arange(N) + (barwidth / 2.0), map(str, pylab.arange(N) + 1), fontsize=10) pylab.ylabel('Time (h)') if legenddata: font = FontProperties(size=9) pylab.figlegend(patches, labels, "upper right", prop=font) if interactive: pylab.show() else: fname = "batterylife_builds-%s.png" % ( report_list[0].metadata.timestamp.strftime("%m%d%H%M%S")) pylab.savefig(fname, format="png") return fname
C, S = np.cos(X), np.sin(X) # Graficar la función coseno con una línea continua azul de 1 pixel de grosor pl.plot(X, C, color="blue", linewidth=1.0, linestyle="-") # Graficar la función seno con una línea continua verde de 1 pixel de grosor pl.plot(X, S, color="green", linewidth=1.0, linestyle="-") # Establecer límites del eje x (Divisiones en X) pl.xlim(-8.0, 8.0) # Ticks en x(Impresión de intervalos, cantidad de datos mostrados en el eje) pl.xticks(np.linspace(-8, 8, 17, endpoint=True)) # Establecer límites del eje y (Divisiones en Y) pl.ylim(-1.0, 1.0) # Ticks en y (Impresión de intervalos, cantidad de datos mostrados en el eje) pl.yticks(np.linspace(-1, 1, 5, endpoint=True)) '''Otra opcion de determinar los limites a imprimir pl.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi]) pl.yticks([-1, 0, +1]) ''' #AGREGAR LINEAS DE EJES Y QUITAR EL RECUADRO: ax = pl.gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('data',0)) ax.yaxis.set_ticks_position('left')
def extract_plr(t, dr, flash_time, scan_id='1234', which_eye='LEFT'): # Extract PLR parameters from provided time series. flash_time = flash_time[1] t = t - (flash_time - 1) flash_time = 1.0 # Find valid points idx = q(t > 0) t = t[idx] dr = dr[idx] * 1000 t_start = t.min() t -= t_start dr = taut_string(dr, 0.01) # Fit with cubic splines t_mn = 0 t_mx = 5 idx = q((t > t_mn) * (t < t_mx)) t_ = t[idx] dr_ = dr[idx] f = Fit(t_, 100, basis_type='cubic-spline', reg_coefs=[0, 1e-2, 9e-3]) r = f.fit(dr_) # Grab the latency time. try: roc = 1 / ((2 + 1 + (r.dy)**2)**(3 / 2) / np.abs(r.d2y)) except: roc = inf roc = taut_string(roc, 0.10) g = Fit(t_, 100, basis_type='cubic-spline', reg_coefs=[0, 1e-2, 1e-3]) rc = g.fit(roc) roc = rc.y peaks = [] for itr, val in enumerate(roc): if (itr < 1) or (itr == len(roc) - 1): continue if val > roc[itr - 1] and (val > roc[itr + 1]): peaks.append(t_[itr]) # Light flash time. closest_index = np.abs(r.x - flash_time) flash_idx = np.argmin(closest_index) # Starting amplitude. starting_amplitude = r.y[flash_idx] # Find the peak in the curvature. peaks = np.array(peaks) peaks -= flash_time peaks = peaks[peaks > 0.150] peak_time = peaks[0] + flash_time med_amplitude = np.median(dr_) std_amplitude = dr_.std() roc -= mean(roc) roc = roc * roc.std() * std_amplitude / 2 roc += med_amplitude latency = peak_time - flash_time print('Latency is {:0.3f}'.format(latency)) # Minimum amplitude. idx_min, idx_max, t_min, t_max, v_min, v_max =\ extrema_in_range(r.x, r.y, t_mn, t_mx-2) minimum_amplitude = v_min minimum_time = t_min delta_amplitude = starting_amplitude - minimum_amplitude average_speed = (delta_amplitude) / (minimum_time - flash_time) # Find the recovery time. recovery_amplitude = 0.75 * delta_amplitude + minimum_amplitude idx_after_min = q(t > minimum_time) t_after_min = t[idx_after_min] amp_after_min = dr[idx_after_min] recovery_idx = q(amp_after_min >= recovery_amplitude)[0] if recovery_idx: recovery_time = t_after_min[recovery_idx] - flash_time time_of_recovery = t_after_min[recovery_idx] else: recovery_time = -1 time_of_recovery = 5 package = {} package['latency'] = latency package['starting_diameter'] = starting_amplitude package['minimum_diameter'] = minimum_amplitude package['absolute_diameter_change'] = delta_amplitude package['relative_diameter_change'] = delta_amplitude / starting_amplitude package['average_speed'] = average_speed package['recovery_time'] = recovery_time plt.ioff() plt.close('all') plt.plot(r.x, r.y, color='#c62828', linewidth=3) plt.plot(t_, roc, color='#305580', linewidth=3, alpha=0.5) y_lim = plt.ylim( [med_amplitude - 3 * std_amplitude, med_amplitude + 2 * std_amplitude]) plt.plot([0, 5], [starting_amplitude, starting_amplitude], ':', color='#2f2f2f') plt.plot([0, 5], [minimum_amplitude, minimum_amplitude], ':', color='#2f2f2f') plt.plot([time_of_recovery, time_of_recovery], [0, 20], '--', color='#c62828') plt.plot([flash_time, flash_time], [0, 20], '--', color='#000000') plt.plot([peak_time, peak_time], [0, 20], '--', color='#4caf50') plt.xlim([t_mn, t_mx]) plt.xlabel('Time (Seconds)') plt.ylabel('Pupil Diameter (mm)') location = './plots' plt.savefig('{}/{}_{}.png'.format(location, scan_id, which_eye)) return package