def main(): SAMPLE_NUM = 10 degree = 9 x, y = sin_wgn_sample(SAMPLE_NUM) fig = pylab.figure(1) pylab.grid(True) pylab.xlabel('x') pylab.ylabel('y') pylab.axis([-0.1,1.1,-1.5,1.5]) # sin(x) + noise # markeredgewidth mew # markeredgecolor mec # markerfacecolor mfc # markersize ms # linewidth lw # linestyle ls pylab.plot(x, y,'bo',mew=2,mec='b',mfc='none',ms=8) # sin(x) x2 = linspace(0, 1, 1000) pylab.plot(x2,sin(2*x2*pi),'#00FF00',lw=2,label='$y = \sin(x)$') # polynomial fit reg = exp(-18) w = curve_poly_fit(x, y, degree,reg) #w = polyfit(x, y, 3) po = poly1d(w) xx = linspace(0, 1, 1000) pylab.plot(xx, po(xx),'-r',label='$M = 9, \ln\lambda = -18$',lw=2) pylab.legend() pylab.show() fig.savefig("poly_fit9_10_reg.pdf")
def plot_rclist(rclist,order='az',showfig=False): RCspecsA50 = [[0.71, 0.83], [0.67, 0.79], [0.59, 0.73], [0.53, 0.68], [0.38, 0.52], [0.25, 0.35]] RCspecsMax = [[0.88, 1.08], [0.85, 1.05], [0.77, 1.01], [0.75, 0.94], [0.51, 0.74], [0.29, 0.46]] data = [(key,rclist[key]) for key in rclist.keys()] X,Y = zip(*data) if order == 'za': X = sorted(X,reverse=True) for elem in range(len(RCspecsA50)): l = plt.axvline(x=elem+1, ymin=RCspecsA50[elem][0], ymax= RCspecsA50[elem][1], linewidth=5, color='r') fig = plt.figure() ax1 = fig.add_subplot(111) plt.plot( X , Y ) plt.xtitle = "Sphere index" plt.ytitle = "RC coefficient" plt.grid(True) if showfig==True: plt.show() return fig
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 drawPrfastscore(tp,fp,scr,tot,show=True): tp=numpy.cumsum(tp) fp=numpy.cumsum(fp) rec=tp/tot prec=tp/(fp+tp) #dif=numpy.abs(prec[1:]-rec[1:]) dif=numpy.abs(prec[::-1]-rec[::-1]) pos=dif.argmin() pos=len(dif)-pos-1 ap=0 for t in numpy.linspace(0,1,11): pr=prec[rec>=t] if pr.size==0: pr=0 p=numpy.max(pr); ap=ap+p/11; if show: pylab.plot(rec,prec,'-g') pylab.title("AP=%.3f EPRthr=%.3f"%(ap,scr[pos])) pylab.xlabel("Recall") pylab.ylabel("Precision") pylab.grid() pylab.show() pylab.draw() return rec,prec,scr,ap,scr[pos]
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 ! ----'
def drawPr(tp,fp,tot,show=True): """ draw the precision recall curve """ det=numpy.array(sorted(tp+fp)) atp=numpy.array(tp) afp=numpy.array(fp) #pylab.figure() #pylab.clf() rc=numpy.zeros(len(det)) pr=numpy.zeros(len(det)) #prc=0 #ppr=1 for i,p in enumerate(det): pr[i]=float(numpy.sum(atp>=p))/numpy.sum(det>=p) rc[i]=float(numpy.sum(atp>=p))/tot #print pr,rc,p ap=0 for c in numpy.linspace(0,1,num=11): if len(pr[rc>=c])>0: p=numpy.max(pr[rc>=c]) else: p=0 ap=ap+p/11 if show: pylab.plot(rc,pr,'-g') pylab.title("AP=%.3f"%(ap)) pylab.xlabel("Recall") pylab.ylabel("Precision") pylab.grid() pylab.show() pylab.draw() return rc,pr,ap
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 testTelescope(self): import matplotlib matplotlib.use('AGG') import matplotlib.mlab as ml import pylab as pl import time w0 = 8.0 k = 2*np.pi/3.0 gb = GaussianBeam(w0, k) lens = ThinLens(150, 150) gb2 = lens*gb self.assertAlmostEqual(gb2._z0, gb._z0 + 2*150.0) lens2 = ThinLens(300, 600) gb3 = lens2*gb2 self.assertAlmostEqual(gb3._z0, gb2._z0 + 2*300.0) self.assertAlmostEqual(gb._w0, gb3._w0/2.0) z = np.arange(0, 150) z2 = np.arange(150, 600) z3 = np.arange(600, 900) pl.plot(z, gb.w(z, k), z2, gb2.w(z2, k), z3, gb3.w(z3, k)) pl.grid() pl.xlabel('z') pl.ylabel('w') pl.savefig('testTelescope1.png') time.sleep(0.1) pl.close('all')
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 plot_number_alteration_by_tissue(self, fontsize=10, width=0.9): """Plot number of alterations .. plot:: :width: 100% :include-source: from gdsctools import * data = gdsctools_data("test_omnibem_genomic_alterations.csv.gz") bem = OmniBEMBuilder(data) bem.filter_by_gene_list(gdsctools_data("test_omnibem_genes.txt")) bem.plot_number_alteration_by_tissue() """ count = self.unified.groupby(['TISSUE_TYPE'])['GENE'].count() try: count.sort_values(inplace=True, ascending=False) except: count.sort(inplace=True, ascending=False) count.plot(kind="bar", width=width) pylab.grid() pylab.xlabel("Tissue Type", fontsize=fontsize) pylab.ylabel("Total number of alterations in cell lines", fontsize=fontsize) try:pylab.tight_layout() except:pass
def plot_signal(x,y,title,labelx,labley,position): pylab.subplot (9, 1, position) pylab.plot(x,y) pylab.title(title) pylab.xlabel(labelx) pylab.ylabel(labley) pylab.grid(True)
def __call__(self, n): if len(self.f.shape) == 3: # f = f[x,v,t], 2 dim in phase space ft = self.f[n,:,:] pylab.pcolormesh(self.X, self.V, ft.T, cmap = 'jet') pylab.colorbar() pylab.clim(0,0.38) # for Landau test case pylab.grid() pylab.axis([self.xmin, self.xmax, self.ymin, self.ymax]) pylab.xlabel('$x$', fontsize = 18) pylab.ylabel('$v$', fontsize = 18) pylab.title('$N_x$ = %d, $N_v$ = %d, $t$ = %2.1f' % (self.x.N, self.v.N, self.it*self.t.width)) pylab.savefig(self.path + self.filename) pylab.clf() return None if len(self.f.shape) == 2: # f = f[x], 1 dim in phase space ft = self.f[n,:] pylab.plot(self.x.gridvalues,ft,'ob') pylab.grid() pylab.axis([self.xmin, self.xmax, self.ymin, self.ymax]) pylab.xlabel('$x$', fontsize = 18) pylab.ylabel('$f(x)$', fontsize = 18) pylab.savefig(self.path + self.filename) return None
def update(self): if self.pose != []: plt.figure(1) clf() self.fig1 = plt.figure(num=1, figsize=(self.window_size, \ self.window_size), dpi=80, facecolor='w', edgecolor='w') title (self.title) xlabel('Easting [m]') ylabel('Northing [m]') axis('equal') grid (True) poseT = zip(*self.pose) pose_plt = plot(poseT[1],poseT[2],'#ff0000') if self.wptnav != []: mode = self.wptnav[-1][MODE] if not (self.wptnav[-1][B_E] == 0 and self.wptnav[-1][B_N] == 0 and self.wptnav[-1][A_E] == 0 and self.wptnav[-1][A_N] == 0): b_dot = plot(self.wptnav[-1][B_E],self.wptnav[-1][B_N],'ro',markersize=8) a_dot = plot(self.wptnav[-1][A_E],self.wptnav[-1][A_N],'go',markersize=8) ab_line = plot([self.wptnav[-1][B_E],self.wptnav[-1][A_E]],[self.wptnav[-1][B_N],self.wptnav[-1][A_N]],'g') target_dot = plot(self.wptnav[-1][TARGET_E],self.wptnav[-1][TARGET_N],'ro',markersize=5) if mode == -1: pose_dot = plot(self.wptnav[-1][POSE_E],self.wptnav[-1][POSE_N],'b^',markersize=8) elif mode == 1: pose_dot = plot(self.wptnav[-1][POSE_E],self.wptnav[-1][POSE_N],'bs',markersize=8) elif mode == 2: pose_dot = plot(self.wptnav[-1][POSE_E],self.wptnav[-1][POSE_N],'bo',markersize=8) if self.save_images: self.fig1.savefig ('plot_map%05d.jpg' % self.image_count) self.image_count += 1 draw()
def plot_datasets(dataset_ids, title=None, legend=True, labels=True): """ Plots one or more dataset. :param dataset_ids: list of datasets to plot :type dataset_ids: list of integers :param title: title of the plot :type title: string :param legend: whether or not to show legend :type legend: boolean :param labels: whether or not to plot point labels :type labels: boolean """ title = title if title else "Datasets " + ",".join( [str(d) for d in dataset_ids]) pl.title(title) data = {k: v for k, v in npoints.items() if k in dataset_ids} lines = [pl.plot(zip(*p)[0], zip(*p)[1], 'o-')[0] for p in data.values()] if legend: pl.legend(lines, data.keys()) if labels: for x, y, l in [i for s in data.values() for i in s]: pl.annotate(str(l), xy=(x, y), xytext=(x, y + 0.1)) pl.grid(True) return pl
def plot_1d(profile, title_fig, title_x, title_y): # pylab.figure() pylab.plot(profile[0], profile[1]) pylab.xlabel(title_x) pylab.ylabel(title_y) pylab.title(title_fig) pylab.grid(True)
def TestOverIntDim(): nDim = 10 numOfParticles = 20 maxIteration = 200 minX = array([-100.0]*nDim) maxX = array([100.0]*nDim) maxV = 0.2*(maxX - minX) minV = -1.0*maxV numOfTrial = 20 alpha = 0.0 for intDim in xrange(0,11,2): gBest = array([0.0]*maxIteration) for i in xrange(numOfTrial): p1 = AUPSO.PSOProblem(nDim, numOfParticles, maxIteration, minX, maxX, minV, maxV, AUPSO.Griewank,intDim,alpha) p1.run() gBest = gBest + p1.gBestArray[:maxIteration] gBest = gBest / numOfTrial pylab.plot(range(maxIteration), log10(gBest),label='intDim='+str(intDim)) pylab.title('$G_{best}$ over 20 trials'+' alpha='+str(alpha)) pylab.xlabel('The $N^{th}$ Iteratioin') pylab.ylabel('Average gBest over '+str(numOfTrial)+' runs') pylab.grid(True) # pylab.yscale('log') ylim = [-6, 1] ystep = 1.0 # pylab.ylim(ylim[0], ylim[1]) # yticks = linspace(ylim[0], ylim[1], int((ylim[1]-ylim[0])/ystep+1)) # pylab.yticks(tuple(yticks), tuple(map(str,yticks))) pylab.legend(loc='lower left') pylab.show()
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 main(): # The Wiener process parameter. delta = 2 # Total time. T = 10.0 # Number of steps. N = 1000 # Time step size dt = T/N # Initial value of x. x0 = 100.0 time0 = time.time() xa = random_walk(x0, N, dt, delta) time1 = time.time() xb = random_walk_loop(x0, N, dt, delta) time2 = time.time() print "numpy cumsum: %.3g seconds" % (time1-time0) print "python loop: %.3g seconds" % (time2-time1) print "ratio: %.2f" % ((time2-time1)/(time1-time0)) t = numpy.linspace(0.0, N*dt, N+1) plot(t, xa, 'g') plot(t, xb, 'b') xlabel('t', fontsize=16) ylabel('x',fontsize=16) grid(True) show()
def TestOverAlpha(): nDim = 5 numOfParticles = 10 maxIteration = 2000 minX = array([-100.0]*nDim) maxX = array([100.0]*nDim) maxV = 1.0*(maxX - minX) minV = -1.0*maxV numOfTrial = 10 intDim = 4 alpha = 0.3 while alpha<1.0: gBest = array([0.0]*maxIteration) for i in xrange(numOfTrial): p1 = AUPSO.PSOProblem(nDim, numOfParticles, maxIteration, minX, maxX, minV, maxV, AUPSO.Sphere,intDim,alpha) p1.run() gBest = gBest + p1.gBestArray[:maxIteration] gBest = gBest / numOfTrial pylab.plot(range(maxIteration), gBest,label='alpha='+str(alpha)) print 'alpha = ', alpha alpha += 0.3 print 'now drawing' pylab.title('$G_{best}$ over 20 trials'+' intDim='+str(intDim)) pylab.xlabel('The $N^{th}$ Iteratioin') pylab.ylabel('Average gBest over '+str(numOfTrial)+' runs') pylab.grid(True) pylab.yscale('log') ylim = [-6, 1] ystep = 1.0 # pylab.ylim(ylim[0], ylim[1]) # yticks = linspace(ylim[0], ylim[1], int((ylim[1]-ylim[0])/ystep+1)) # pylab.yticks(tuple(yticks), tuple(map(str,yticks))) pylab.legend(loc='lower left') pylab.show()
def plot_cumulative_score(smod, seqs, size=(6, 2), fname=None): """plot_cumulative_score.""" sig = cumulative_score(seqs, smod) plt.figure(figsize=size) sigp = np.copy(sig) sigp[sigp < 0] = 0 plt.bar(range(len(sigp)), sigp, alpha=0.3, color='g') sign = np.copy(sig) sign[sign >= 0] = 0 plt.bar(range(len(sign)), sign, alpha=0.3, color='r') plt.grid() plt.xlabel('Position') plt.ylabel('Importance score') if fname: plt.draw() figname = '%s_importance.png' % (fname) plt.savefig( figname, bbox_inches='tight', transparent=True, pad_inches=0) else: figname = None plt.show() plt.close() return figname
def plot_ch(): for job in jobs_orig: print "plane of", job.path pylab.clf() x_center = int((job.position(0)[0] + job.position(1)[0])/2) x_final = 50 + x_center #plane = np.concatenate((job.plane(y=50)[:, x_final:], # job.plane(y=50)[:, :x_final]), axis=1) plane = job.plane(y=50) myplane = plane[plane < 0.0] p0 = myplane.min() p12 = np.median(myplane) p14 = np.median(myplane[myplane<p12]) p34 = np.median(myplane[myplane>p12]) p1 = myplane.max() contour_values = (p0, p14, p12, p34, p1) pylab.title(r'$u_x=%.4f,\ D_{-}=%.4f,\ D_{+}=%.4f,\ ch=%i$ ' % (job.u_x, job.D_minus, job.D_plus, job.ch_objects)) car = pylab.imshow(plane, vmin=-0.001, vmax=0.0, interpolation='nearest') pylab.contour(plane, contour_values, linestyles='dashed', colors='white') pylab.grid(True) pylab.colorbar(car) #imgfilename = 'plane_r20-y50-u_x%.4fD%.4fch%03i.png' % \ # (job.u_x, job.D_minus, job.ch_objects) imgfilename = 'plane_%s.png' % job.job_id pylab.savefig(imgfilename)
def plot_location(needle, haystack, cluster_id=None, nbins=20, size=(17, 2), fname=None): """plot_location.""" locs = [] for h, s in haystack: for match in re.finditer(needle, s): s = match.start() e = match.end() m = s + (e - s) / 2 locs.append(m) plt.figure(figsize=size) n, bins, patches = plt.hist( locs, nbins, normed=0, facecolor='blue', alpha=0.3) plt.grid() plt.title(needle) plt.xlabel('Position') plt.ylabel('Num occurrences') if fname: plt.draw() figname = '%s_loc_%d.png' % (fname, cluster_id) plt.savefig( figname, bbox_inches='tight', transparent=True, pad_inches=0) else: figname = None plt.show() plt.close() return figname
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()
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 analyze(self,igroup): # to get the sourcedata database=self.gettmpdata('database'); spectra=database[0]['resultdatatablegroups'][igroup]; spectranew=spectra.getemptyinstance(); #the real calculation spectraall=database[0]['datalist'][0]; spectraall.plot(); #spectraall.show(); pylab.grid(True); formulastr=eval(self['formulastr'].get()); for k in spectra.keys(): spect=spectra[k]; spectnew=spect.copyxy(); spectnew.update(formulastr); spectnew.log({"Operation":"set column value","formulastr":formulastr}); spectranew.insert(spectnew,k); spectra=database[0]['resultdatatablegroups'][igroup]=spectranew; #pylab.figure(); XpyFigure(); spectraall.plot(); spectranew.plot('o');
def pr_curve(mean_precision, mean_recall, title='20-newsgroups', prefix='', suffix='', save_path=''): """ Parameters ---------- mean_precision: numpy.ndarry,一维 记录平均精度的向量. mean_recall: numpy.ndarray,一维 记录平均召回率向量. prefix, duffix: 同rsm_query() save_path: str, 保存图片的目录,注意一定要使用绝对路径,支持以'/'结尾或没有 """ #color_list = ['blue', 'red', 'green', 'cyan', 'yellow', 'black', 'magenta', (0.5,0.5,0.5)] y_vector = mean_precision * 100. x_vector = mean_recall * 100 #** (1./6.) pylab.figure(figsize=(8, 8)) pylab.grid() #在做标系中显示网格 pylab.plot(x_vector, y_vector, label='$r-p curve$', color='blue', linewidth=1) pylab.xlabel('recall(%)') pylab.ylabel('precision(%)') pylab.title(title) #pylab.xlim(0., 60) #x轴长度限制 #pylab.ylim(0., 30) #y轴长度限制 pylab.legend() #在图像中显示标记说明 #pylab.show() # 显示图像 if save_path != '': if platform.system() == 'Linux' and save_path[-1] != '/': save_path += '/' if platform.system() == 'Windows' and save_path[-1] != '\\': save_path += '\\' save_path += 'plots/' check_path(save_path) #检测路径,如果目录不存在,支持递归建立 pylab.savefig(save_path + prefix + 'r-p' + suffix + '.png', dpi=240) #保存图像,可以人为指定所保存的图像的分辨率
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 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_distance(cluster_id_i, cluster_id_j, regex_i, regex_j, distances, nbins=5, size=(6, 2), fname=None): """plot_distance.""" ds = distances[(cluster_id_i, cluster_id_j)] plt.figure(figsize=size) n, bins, patches = plt.hist( ds, nbins, normed=0, facecolor='green', alpha=0.3) plt.grid() plt.title('%s vs %s' % (regex_i, regex_j)) plt.xlabel('Relative position') plt.ylabel('Num occurrences') if fname: plt.draw() figname = '%s_dist_%d_vs_%d.png' % (fname, cluster_id_i, cluster_id_j) plt.savefig( figname, bbox_inches='tight', transparent=True, pad_inches=0) else: figname = None plt.show() plt.close() return figname
pylab.xlabel("x") pylab.ylabel("Thermal Efficiency") my_title = 'Fit with poly degree = ' + str( m) + '; green dot is 2000 projection' pylab.title(my_title) pylab.xlim( (1710, 2015)) # x-axis values should range from 1710 to 2015 pylab.plot(2000, proj, 'go') # plot Year 2000 projection as a green dot pylab.plot(xData, yData, 'ro') # plot the original data given in the xData and yData # arrays as red dots pylab.plot(xData, ys, 'b') # plot polynomial curve using xData and ys arrays # and make it blue. pylab.grid() pylab.show() else: # Prints the thermal efficiency and that it is not viable print('{:3d}\t{:5.3f}\t{:5.3f}\t{:s}'.format(m, stdev, proj, 'not viable')) #-------------------------------------------------------------------------------------- # Table to stdout should look similar to this... # # Degree Stdev 2000P # 1 2.855 34.986 viable # 2 2.768 45.419 viable # 3 2.266 -6.602 not viable # 4 2.234 112.391 not viable # 5 2.496 113.726 not viable #--------------------------------------------------------------------------------------
def PlotTestData(self, fig=1, TorqueLimit=None, PowerLimit=None, CurrentLimit=None): """ Plots Torque and Power along with test data Inputs: fig - Figure number """ if self.TestData is None: raise ACMotorrError("No test data has been given") TestData = npy.array(self.TestData) Nmax = max(max(TestData[:, 0]) / RPM, self.Nmax / RPM) N = npy.linspace(0, Nmax, 20) * RPM Tb = self.Tb(0, N) Pb = self.Pb(0, N) Pin = self.Pin(N) Ib = self.Ib(N) eta = self.Efficiency(N=N) Em = self.Effmax() NEm = self.N_Effmax() TbEm = self.Tb(0, NEm) PbEm = self.Pb(0, NEm) IEm = self.I_Effmax() # N /= self.GearRatio # NEm /= self.GearRatio N /= RPM Tb /= (IN * OZF) Pb /= self.PowerUnit Pin /= self.PowerUnit Ib /= A NEm /= RPM TbEm /= (IN * OZF) PbEm /= self.PowerUnit IEm /= A Ntest = self.ToUnumList(TestData[:, 0], RPM) Ttest = self.ToUnumList(TestData[:, 1], IN * OZF) Itest = self.ToUnumList(TestData[:, 2], A) Vtest = self.ToUnumList(TestData[:, 3], V) Ptest = (Ntest * Ttest) / self.PowerUnit Pintest = (Vtest * Itest) / self.PowerUnit Ntest = Ntest / RPM Ttest = Ttest / (IN * OZF) Itest = Itest / A Vtest = Vtest / V etatest = Ptest / Pintest * 100 ylabel_offset = -0.1 pyl.figure(fig) ax = pyl.subplot(221) ax.xaxis.get_major_formatter().set_powerlimits((-3, 3)) junk, Mechanical, MaxEffPnt = pyl.plot(N, Tb, 'b', Ntest, Ttest, 'ob', NEm, TbEm, 'or') pyl.xlabel('RPM') pyl.ylabel('Torque (in*ozf)') pyl.gca().yaxis.set_label_coords(ylabel_offset, 0.5) pyl.grid() #pyl.legend(['Model', 'Measured', 'Max Eff.'], loc = 'best') pyl.ylim(ymin=0) if TorqueLimit is not None: pyl.ylim(ymax=TorqueLimit) ax = pyl.subplot(222) ax.xaxis.get_major_formatter().set_powerlimits((-3, 3)) MechModel, ElecModel, Electric, MaxLim, junk, junk \ = pyl.plot( N,Pb, 'b' , N,Pin,'g' , Ntest,Pintest,'og' , [min(N), max(N)],[self.Wmax/self.PowerUnit, self.Wmax/self.PowerUnit],'r' , Ntest,Ptest,'ob' , NEm,PbEm,'or') pyl.figlegend( [MechModel, ElecModel, Mechanical, Electric, MaxEffPnt, MaxLim], [ 'Mech. Model', 'Elec. Model', 'Mech. Test Data', 'Elec. Test Data', 'Max Eff.', 'Limit' ], loc='upper center', numpoints=1, ncol=3, frameon=False, labelspacing=0.1) pyl.xlabel('RPM') pyl.ylabel('Power (' + self.PowerUnitName + ')') pyl.gca().yaxis.set_label_coords(-0.12, 0.5) pyl.grid() #pyl.legend(['Break', 'Input'], loc = 'best') pyl.ylim(ymin=0) if PowerLimit is None: PowerLimit = self.Wmax / self.PowerUnit * 1.1 pyl.ylim(ymax=PowerLimit) ax = pyl.subplot(223) ax.xaxis.get_major_formatter().set_powerlimits((-3, 3)) pyl.plot([min(N), max(N)], [self.Imax / A, self.Imax / A], 'r') pyl.plot(N, Ib, 'b') pyl.plot(Ntest, Itest, 'og') pyl.plot(NEm, IEm, 'or') pyl.xlabel('RPM') pyl.ylabel('Current (A)') pyl.gca().yaxis.set_label_coords(ylabel_offset, 0.5) pyl.grid() #pyl.legend(['Max'], loc = 'best') pyl.ylim(ymin=0) if CurrentLimit is not None: pyl.ylim(ymax=CurrentLimit) ax = pyl.subplot(224) ax.xaxis.get_major_formatter().set_powerlimits((-3, 3)) pyl.plot(N, eta) pyl.plot(Ntest, etatest, 'og') pyl.plot(NEm, Em, 'or') pyl.xlabel('RPM') pyl.ylabel('Efficiency') pyl.ylim((0, 100)) pyl.gca().yaxis.set_label_coords(ylabel_offset, 0.5) pyl.grid()
# -*- coding: utf-8 -*- """ Created on Thu Apr 12 14:31:28 2018 @author: user """ import numpy as np import pylab as pl lamb_list = [0.6, 1.01, -0.98, -1.005] pl.figure(1) for lamb in lamb_list: y=[10] for k in range(1,50): y.append(lamb**k*y[0]) pl.plot(y, label='$\lambda$ = '+str(lamb)) pl.ylabel('$y_k$') pl.xlabel('$k$') pl.grid() pl.legend() pl.show()
# set string constants for output plots, current time, mesh size pname = 'solution.' + repr(tstep).zfill(3) + '.png' tstr = repr(tstep) nxstr = repr(nx) # plot current solution and save to disk plt.figure(1) plt.plot(mesh, udata[tstep, :], label="u") plt.plot(mesh, vdata[tstep, :], label="v") plt.plot(mesh, wdata[tstep, :], label="w") plt.xlabel('x') plt.ylabel('solution') plt.title('Solutions at output ' + tstr + ', mesh = ' + nxstr) plt.axis((0.0, xmax, minval, maxval)) plt.grid() plt.legend(loc='upper right', shadow=True) plt.savefig(pname) plt.close() # set string constants for output plots, current time, mesh size pname = 'solution_at_x0.png' xstr = repr(mesh[0]) # plot current solution and save to disk plt.figure(1) plt.plot(times, udata[:, 0], label="u") plt.plot(times, vdata[:, 0], label="v") plt.plot(times, wdata[:, 0], label="w") plt.xlabel('t') plt.ylabel('solution')
na = np.array pl.close('all') ms.mystyle_arial(fontsz=16, dist_tick_lab=10) pl.figure(1) pl.plot(1000*ob_ref.xmax_test_list, err_abs_list) pl.xlim(0,1000*ob_ref.x_aper) pl.figure(2) pl.plot(1000*(ob_ref.xmax_test_list), 100*na(err_rel_list)) pl.plot(1000*(ob_ref.xmax_test_list), 100*na(err_rel_list_old), 'r') pl.xlim(0,1000*ob_ref.x_aper) pl.figure(3) pl.plot(1000*(ob_ref.x_aper-ob_ref.xmax_test_list), 100*na(err_rel_list), '.-') pl.plot(1000*(ob_ref.x_aper-ob_ref.xmax_test_list), 100*na(err_rel_list_old), '.-r') pl.grid('on') pl.xlim(0,None) pl.figure(30) pl.plot(1000*(ob_ref.x_aper-ob_ref.xmax_test_list), 100*na(err_rel_list_old), '.-r', label = 'Old SC routine', linewidth = linew, markersize=mksz) pl.plot(1000*(ob_ref.x_aper-ob_ref.xmax_test_list), 100*na(err_rel_list), '.-', label = 'New SC routine', linewidth = linew, markersize=mksz) pl.grid('on') pl.xlim(0,3) pl.ylim(0,20) pl.xlabel('Distance from edge [mm]') pl.ylabel('Rms error [%]') pl.legend(prop={'size':16}) fname = label_plots+'error_at_boudary_Dh%.1fmm'%Dh_mm pl.suptitle(fname) pl.savefig(fname+'.png', dpi=200)
# Generate signals before and after #------------------------------------------------ iirFilter = IIRFilter() b = iirFilter.IIRFilterConf[chose_filter]['numerator'] a = iirFilter.IIRFilterConf[chose_filter]['denominator'] #------------------------------------------------ # Plot the IIR filter coefficients and # the magnitude response of the filter. #------------------------------------------------ figure(1) w, h = signal.freqz(b, a, 8000) plt.plot((w / pi) * nyq_rate, absolute(h), linewidth=2) plt.plot([0, 0.5 * sample_rate], [GAIN * sqrt(0.5), GAIN * sqrt(0.5)], '--') xlabel('Frequency (Hz)') ylabel('Gain') title('Frequency Response') ylim(-0.05, 1.5 * GAIN) grid(True) subplots_adjust(hspace=.5) squareWave = signal.square(2 * pi * ffs[0] * squareInterval) filtered_squarewave = iirFilter.filter(chose_filter, squareWave) plotSignal(squareWave, filtered_squarewave, squareInterval, 'Square wave', ffs[0]) for ff in ffs: sineWave = sin(2 * pi * ff * sineInterval) filtered_sinewave = iirFilter.filter(chose_filter, sineWave) plotSignal(sineWave, filtered_sinewave, sineInterval, 'Sine wave', ff)
def eval_gwas(pv, i_causal, out_fn=None, plot=False): """ """ pv_thresholds = [1e-3, 5e-4, 1e-4, 5e-5, 1e-5, 5e-6, 1e-6, 5e-7, 1e-7, 5e-8, 1e-8] # compute lambda on all p-values? #lambda_gc = estimate_lambda(p_values) lambda_gc = estimate_lambda(pv) n_causal = i_causal.sum() #compute power and Type-1 error power = np.zeros_like(pv_thresholds) t1err = np.zeros_like(pv_thresholds) power_corr = np.zeros_like(pv_thresholds) t1err_corr = np.zeros_like(pv_thresholds) pvcorr = stats.chi2.sf(stats.chi2.isf(pv,1)/lambda_gc,1) for i_t, t in enumerate(pv_thresholds): #compute uncorrected power and T1 i_lower = pv<t power[i_t] = i_causal[i_lower].sum()/(1.0*(n_causal)) t1err[i_t] = (~i_causal[i_lower]).sum()/(1.0*(len(i_causal)-n_causal)) #compute GC corrected Power and T1 i_lower_corr = pvcorr<t power_corr[i_t] = i_causal[i_lower_corr].sum()/(1.0*(n_causal)) t1err_corr[i_t] = (~i_causal[i_lower_corr]).sum()/(1.0*(len(i_causal)-n_causal)) if plot == True: import pylab pylab.figure() pylab.title("lambda_gc=%f" % lambda_gc) pylab.plot(pv_thresholds, power, "-o") pylab.yscale("log") pylab.xscale("log") pylab.xlabel("pv threshold") pylab.ylabel("power") pylab.grid(True) pylab.plot(pv_thresholds, power_corr, "-o") if not out_fn is None: pow_fn = out_fn.replace(".pickle", "_pow.pdf") pylab.savefig(pow_fn) else: pylab.show() pylab.figure() pylab.title("lambda_gc=%f" % lambda_gc) pylab.plot(pv_thresholds, t1err, "-o", label="t1err") pylab.plot(pv_thresholds, t1err_corr, "-o", label="t1err_gc") pylab.yscale("log") pylab.xscale("log") pylab.xlabel("pv threshold") pylab.ylabel("t1err") pylab.grid(True) pylab.plot(pv_thresholds, pv_thresholds, "-", label="thres") pylab.legend(loc="upper left") if not out_fn is None: t1err_fn = out_fn.replace(".pickle", "_t1err.pdf") pylab.savefig(t1err_fn) else: pylab.show() # plot auROC if out_fn is None: roc_fn = None else: roc_fn = out_fn.replace(".pickle", "_roc.pdf") plot_roc(i_causal, -pv, label='lambda_gc=%0.4f' % (lambda_gc), out_fn=roc_fn) # plot auPRC if out_fn is None: prc_fn = None else: prc_fn = out_fn.replace(".pickle", "_prc.pdf") plot_prc(i_causal, -pv, label='lambda_gc=%0.4f' % (lambda_gc), out_fn=prc_fn) # wrap up metrics res = {} res["lambda"] = lambda_gc res["pv_thresholds"] = pv_thresholds res["power"] = power res["power_corr"] = power_corr res["t1err"] = t1err res["t1err_corr"] = t1err_corr return res
histEuler10.theta, label="Euler's method", color="m", lw=2) pylab.plot(histEC10.t, histEC10.theta, label="Euler-Cromer's method", color="b", lw=2) pylab.plot(time, ana, 'g*', label="Analytic Approximation") pylab.xlabel('Time (s)') pylab.ylabel('$\Theta$ (degrees)') pylab.title("Simple Pendulum: $\Theta_0$ = $10^o$, $\Delta$t = %s" % (str(CONST_dt[i]))) pylab.grid(True) leg = pylab.legend(loc=3, labelspacing=0.005) ltext = leg.get_texts() pylab.setp(ltext, fontsize='small') leg.draw_frame(1) ax = pylab.gca() pylab.savefig("plots/theta_vs_t_for_theta0-10_dt-%s.png" % (str(CONST_dt[i]))) # plotting theta vs t, theta0 = 100 time = histEC100.t ana = CONST_theta0[0] * np.cos((2 * math.pi / T100) * time) pylab.clf() pylab.cla()
import pylab # Load the data from the file. t, s, ds = pylab.loadtxt('data/scatter_plot.txt', unpack=True) # Format the plot. pylab.rc('font', size=18) pylab.title('Law of motion', y=1.02) pylab.xlabel('t [s]') pylab.ylabel('s [m]', labelpad=25) pylab.xlim(0, 10) pylab.ylim(0, 18) pylab.grid(color='gray') # Create the scatter plot. pylab.errorbar(t, s, ds, linestyle='', color='black', marker='o') # Save the plot to a pdf file for later use (maybe in a writeup?). pylab.savefig('scatter_plot_fancier.pdf') # Finally: show the plot on the screen. pylab.show()
def main(): """ 위 0, 1, 2 차 함수의 적분 :return: """ # rect0 함수의 도움말을 표시 # 도움말은 def rect0()바로 아래의 문자열 help(rect0) # 적분 구간 시작점 x_begin = 0.0 # 적분 구간 끝 점 x_end = 1.0 # 적분 구간을 몇개의 구획으로 나눌 것인가 n_interval = 8 # 이론적 엄밀해 exact = (g(x_end)) - g(x_begin) print "exact solution=", exact # 함수 rect0 를 호출하여 수치 적분을 계산 integraction_0 = rect0(f, x_begin, x_end, n_interval) print "integration_0 =", integraction_0, "err =", integraction_0 - exact # 함수 trapzoid1 을 호출하여 수치 적분을 계산 integraction_1 = trapezoid1(f, x_begin, x_end, n_interval) print "integration_1 =", integraction_1, "err =", integraction_1 - exact # 함수 simpson2를 호출하여 수치 적분을 계산 integraction_2 = simpson2(f, x_begin, x_end, n_interval) print "integration_2 =", integraction_2, "err =", integraction_2 - exact # 적분 결과를 그림으로 표시하기 위하여 pylab 모둘로 부터 특정 기능을 불러 들임 from pylab import fill, bar, show, xlim, ylim, grid # 엄밀해 그림 시작 n_plot = 100 delta_x_plot = (float(x_end) - x_begin) / n_plot x = [x_begin + k * delta_x_plot for k in xrange(n_plot)] y = [f(x[k]) for k in xrange(n_plot)] x += [x_end, x_end, x_begin] y += [f(x_end), 0.0, 0.0] fill(x, y) #엄밀해 그림 끝 # rect0() # 0차 적분 그림 시작 n_plot = n_interval delta_x_plot = (float(x_end) - x_begin) / n_plot x = [x_begin + k * delta_x_plot for k in xrange(n_plot)] y = [f(xk + 0.5 * delta_x_plot) for xk in x] x += [x_end] y += [0] bar(x, y, width=delta_x_plot, color='g', alpha=0.3) # 0차 적분 그림 끝 # trapezoid1() # 1차 적분 그림 시작 n_plot = n_interval delta_x_plot = (float(x_end) - x_begin) / n_plot x = [x_begin + k * delta_x_plot for k in xrange(n_plot)] y = [f(xk) for xk in x] x += [x_end, x_end, x_begin] y += [f(x_end), 0.0, 0.0] fill(x, y, color='r', alpha=0.2) # 1차 적분 그림 끝 xlim(x_begin, x_end) ylim(0.0, ylim()[1]) grid() show()
return s #%% if False: x = linspace(0, 50, 10000) f = p.figure() #p.plot(x, birthrate_small_pop_penalty(x, 2)*birthrate_large_pop_penalty(x, 15, 3, 0.5)) p.plot(x, deathrate_malnutrition_penalty(2, x, 10, 3, 4)) p.plot(x, birthrate_malnutrition_penalty(2, x, 10)) p.plot( x, -deathrate_malnutrition_penalty(2, x, 10, 3, 4) + 3 * birthrate_malnutrition_penalty(2, x, 10)) #p.plot(x, birthrate(x, 2, 500, 1, 30, 400, 400/5, 0.5)) p.grid() #x = linspace(1,100) #p.plot(x, kills(5, x, 0.1, 2)) if False: reset_data() s = get_system(0) t_end = 50 dt = 1 t = linspace(0, t_end, dt * t_end) X0 = s.get_pop() dX_dt = build_derivative(X0, s) X, infodict = integrate.odeint(dX_dt, X0, t, full_output=True)
def err_plot(err_list, a, b): if type(err_list) == gp.garray: err = err.as_numpy_array() plt.grid(True) plt.plot(np.arange(a, b), err_list[a:b])
def main(): min_x = float("inf") max_x = float("-inf") values = {} for filename in sys.argv[1:]: f = open(filename, 'r') line = f.readline() f.close() directory = re.search('(^.*[^/]+)/+[^/]*$', filename).group(0) name = re.search('([^/]+)/+[^/]*$', filename).group(1) index = int(re.search('-([^-]+)\.txt$', filename).group(1)) time = math.log( float(re.search('= ([^ ]+) ', line).group(1)) * 10000.0, 10.0) if index < min_x: min_x = index if index > max_x: max_x = index try: values[name][index] = time except KeyError: values[name] = {} values[name][index] = time x = [] for i in range(min_x, max_x + 1): x.append(i) fig = plt.figure() fig.canvas.set_window_title('Blocks World Rete Performance') pylab.axes([0.2, 0.15, 0.7725, 0.82]) remap_names = collections.OrderedDict() remap_names['dup-flu'] = 'Full Deoptimization' remap_names['dup'] = 'Disabled Node Sharing' remap_names['flu'] = 'Flushing WMEs' remap_names['opt'] = 'Optimized' labels = [] y_labels = [] yss = [] for agent, name in remap_names.items(): y = [] for index in x: try: y.append(values[agent][index]) except KeyError: y.append(0) y_labels.append(remap_names[agent]) yss.append(y) color = 'black' linestyle = '' if agent is 'opt': color = 'blue' linestyle = '-' elif agent is 'dup': color = 'orange' linestyle = '--' elif agent is 'flu': color = 'orange' linestyle = ':' elif agent is 'dup-flu': color = 'red' linestyle = '-.' labels += pylab.plot(x, y, label=remap_names[agent], color=color, linestyle=linestyle) pylab.grid(False) pylab.xlabel('Number of Blocks', fontsize=8) pylab.ylabel('CPU Time Per Step (s)', fontsize=8) pylab.xlim(xmax=100) # if len(sys.argv) > 1: # pylab.ylim(ymin=-500, ymax=0) pylab.ylim(ymin=0, ymax=10) fig.axes[0].xaxis.set_major_formatter(CommaFormatter()) fig.axes[0].yaxis.set_major_formatter(ExpFormatter()) xlabels = fig.axes[0].xaxis.get_ticklabels() last_xlabel = xlabels[len(xlabels) - 1] last_xlabel.set_horizontalalignment('right') last_xlabel.set_x(0) #fig.axes[0].yaxis.set_scale('log') #print last_xlabel.get_size() #print last_xlabel.get_position() #print last_xlabel.get_text() #print last_xlabel # lower right pylab.legend(labels, [l.get_label() for l in labels], loc=4, handlelength=4.2, numpoints=2) splitd = directory.rsplit('/', 2) m = hashlib.md5() for name in remap_names: m.update(name) filename = str(m.hexdigest()) if not os.path.exists(splitd[0] + '/csv'): os.makedirs(splitd[0] + '/csv') write_to_csv(splitd[0] + '/csv/' + filename + '.csv', 'Step Number', x, y_labels, yss) if not os.path.exists(splitd[0] + '/eps'): os.makedirs(splitd[0] + '/eps') pylab.savefig(splitd[0] + '/eps/' + filename + '.eps') if not os.path.exists(splitd[0] + '/png'): os.makedirs(splitd[0] + '/png') pylab.savefig(splitd[0] + '/png/' + filename + '.png', dpi=1200) if not os.path.exists(splitd[0] + '/svg'): os.makedirs(splitd[0] + '/svg') pylab.savefig(splitd[0] + '/svg/' + filename + '.svg')
def plotdata(x, y=None, yerr=None, numblocks=10, numerrbars=50, colors=('blue', 'green'), clear=False, plottitle=None, xaxislabel=None, yaxislabel=None, description='', grid=False): """ Our standard plotting routine. - The first argument is the data. We try to extract x and y data from it if possible. - Plot 50 error bars if we're given errors. - Do block averaging. - description gets added to the legend and title. """ txt = '' # Figure out x,y,err if y is None: if len(x.shape) > 1: x, y = x[:, 0], x[:, 1] else: x, y = array(range(len(x))), x if clear: clf() if len(x) >= 100000: step = divmod(len(x), 100000)[0] else: step = 1 plot(x[::step], y[::step], color=colors[0], zorder=10, alpha=0.5, label=description + 'raw data') xmin, xmax, ymin, ymax = x.min(), x.max(), y.min(), y.max() #print y if yerr is not None: error_step = int(len(x) / numerrbars) if error_step == 0: error_step = len(x) errorbar(x[::error_step], y[::error_step], yerr[::error_step], color=colors[0], zorder=20, label='FLUC>') ymin = ymin - abs(yerr.max()) ymax = ymax + abs(yerr.max()) else: ymin = ymin - abs(.1 * ymin) ymax = ymax - abs(.1 * ymax) if numblocks <= len(x): blocksize = int(len(x) / numblocks) else: blocksize = 1 numblocks = len(x) print "Not enough data points, setting blocksize to", blocksize, "and numblocks to", numblocks blocksizes = [len(i) for i in splitseq(x, blocksize)] x = [average(i) for i in splitseq(x, blocksize)][:numblocks] yerr = array([std(i) for i in splitseq(y, blocksize)])[:numblocks] y = array([average(i) for i in splitseq(y, blocksize)])[:numblocks] txt += 'Avg: %.4f' % average(y) txt += ', std err: %.4f, avg err: %.4f' % (std(y), average(yerr)) txt += '\nblocks of length %s' % blocksize if len(blocksizes) > numblocks: txt += ' discarding %s points at the end' % sum(blocksizes[numblocks:]) txt += '\nslope of best-fit line to block averages: %s' % u.fitline(x, y)[0] #print y #errorbar(x,y,yerr,elinewidth=20,color=colors[1],barsabove=True,zorder=30) errorbar(x, y, yerr, color=colors[1], barsabove=True, zorder=30, label=description + 'block averages') # After the last plotting, we need to set the axis explicitly, # due to the fact that someone might have previously plotted # raw data in plotaver(). In that case, we still want to be # zoomed in on the average data. axis([xmin, xmax, ymin, ymax]) if plottitle: title(description + plottitle) if xaxislabel: xlabel(xaxislabel) if yaxislabel: ylabel(yaxislabel) if grid: P.grid('on') else: P.grid('off') annotation_location = (min(x) + (max(x) - min(x)) * 0.1, min(y) + (max(y) - min(y)) * 0.1) annotation_location = (xmin + (xmax - xmin) * 0.1, ymin + (ymax - ymin) * 0.1) #print annotation_location,max(y) annotate(txt, annotation_location) legend(shadow=True)
[plot['MedianHeight'] for plot in summaryPlots.values()]) sumHeightHa = np.array([plot['SumHeightHa'] for plot in summaryPlots.values()]) areaHa = np.array([plot['AreaHa'] for plot in summaryPlots.values()]) volHa = np.array([plot['VolHa'] for plot in summaryPlots.values()]) n = np.array([plot['N'] for plot in summaryPlots.values()]) id = np.array([plot['ID'] for plot in summaryPlots.values()]) pylab.close('all') fig = pylab.figure() ScatterD(volHa / 1.e6, ycHa, regress=True, labels=ids, xlabel='vol (m3/ha)', ylabel='yc (t/ha)') pylab.grid() fig = pylab.figure() ScatterD((volHa**1) / 1.e6, agbHa, regress=True, labels=ids, xlabel='vol (m3/ha)', ylabel='AGB (t/ha)') pylab.grid() fig = pylab.figure() ScatterD(areaHa, ycHa, regress=True, xlabel='area (m2/ha)', ylabel='yc (t/ha)') pylab.grid() fig = pylab.figure()
def run(self): if self.debug: import pdb pdb.set_trace() db = Stock_250kDB.Stock_250kDB(drivername=self.drivername, username=self.db_user, password=self.db_passwd, hostname=self.hostname, database=self.dbname, schema=self.schema) db.setup(create_tables=False) session = db.session header_phen, strain_acc_list_phen, category_list_phen, data_matrix_phen = read_data( self.phenotype_fname, turn_into_integer=0) phenData = SNPData( header=header_phen, strain_acc_list=strain_acc_list_phen, data_matrix=data_matrix_phen ) #row label is that of the SNP matrix, because the phenotype matrix is gonna be re-ordered in that way phenData.data_matrix = Kruskal_Wallis.get_phenotype_matrix_in_data_matrix_order( phenData.row_id_ls, strain_acc_list_phen, phenData.data_matrix) #tricky, using strain_acc_list_phen phenotype_col_index1 = self.findOutWhichPhenotypeColumn( phenData, Set([self.phenotype_method_id1]))[0] phenotype_col_index2 = self.findOutWhichPhenotypeColumn( phenData, Set([self.phenotype_method_id2]))[0] x_ls = [] y_ls = [] for i in range(phenData.data_matrix.shape[0]): if not numpy.isnan( phenData.data_matrix[i] [phenotype_col_index1]) and not numpy.isnan( phenData.data_matrix[i][phenotype_col_index2]): x_ls.append(phenData.data_matrix[i][phenotype_col_index1]) y_ls.append(phenData.data_matrix[i][phenotype_col_index2]) pylab.clf() pylab.title('Phenotype Contrast') pylab.plot(x_ls, y_ls, '.', alpha=0.6) pylab.grid(alpha=0.3) phenotype_method1 = Stock_250kDB.PhenotypeMethod.get( self.phenotype_method_id1) phenotype_method2 = Stock_250kDB.PhenotypeMethod.get( self.phenotype_method_id2) pylab.xlabel(phenotype_method1.short_name) pylab.ylabel(phenotype_method2.short_name) #draw diagonal line to show perfect correlation max_min_value = max(min(x_ls), min(y_ls)) min_max_value = min(max(x_ls), max(y_ls)) pylab.plot([max_min_value, min_max_value], [max_min_value, min_max_value], c='g', alpha=0.7) png_output_fname = '%s.png' % self.output_fname_prefix pylab.savefig(png_output_fname, dpi=400) pylab.savefig('%s.svg' % self.output_fname_prefix)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Enter a doc string here..... ------------------------------------------------------ Created on Fri Mar 1 15:05:11 2013 @author: Piotr Bentkowski - [email protected] ------------------------------------------------------ """ import pylab as p import re import linecache as ln theLine = -1 hist = p.genfromtxt("AvaregeGenotype.dat") l = re.split(" ", ln.getline("ModelParams.dat", 7)) U_res = float(l[6]) numOfBins = 1.0 / U_res x = p.arange(0.0, 1.0, U_res) hist[:, 0] = 0.0 p.figure(1, figsize=(10, 6)) p.bar(x, hist[-1, :], width=U_res, color='k', linewidth=0) p.grid(True) p.show()
# Для воспроизводимости результата, создавайте генератор KFold с фиксированным параметром random_state=42. # В качестве меры качества используйте долю верных ответов (accuracy). # Найдите точность классификации на кросс-валидации для метода k ближайших соседей (sklearn.neighbors.KNeighborsClassifier), при k от 1 до 50. # При каком k получилось оптимальное качество? Чему оно равно (число в интервале от 0 до 1)? Данные результаты и будут ответами на вопросы 1 и 2. kf = KFold(classes.size, n_folds=5, shuffle=True, random_state=42) a_max = 0. kn_max = 0 results = [] # data = sklearn.preprocessing.scale(data) for kn in range(1, 50, 1): neigh = KNeighborsClassifier(n_neighbors=kn) r = cv.cross_val_score(estimator=neigh, X=data, y=classes, cv=kf) accuracy = r.mean() # подсчет точности # альтернатиный подсчет точности # preds = neigh.predict(data[test_index]) # accuracy = np.where(preds == classes[test_index], 1, 0).sum() / float(len(test_index)) if accuracy > a_max: a_max = accuracy kn_max = kn results.append([kn, accuracy]) # ответ на задание 4 print('answer: кол-во соседей = {}, точность = {:.2f}'.format(kn_max, a_max)) # рисую график results = pandas.DataFrame(results, columns=["kn", "accuracy"]) pl.plot(results.kn, results.accuracy) pl.grid(True) pl.title("accuracy vs Kn") pl.show()
def plot(self, x, vars, testname, plot_title): # This mask lets us choose data corresponding to a particular test: test = array(map(chr, self.nc.variables['test'][:])) mask = (test == testname) # If we have less than 2 points to plot, then bail. if (sum(mask) < 2): print "Skipping Test %s %s (not enough data to plot)" % (testname, plot_title) return # Get the independent variable and transform it. Note that everywhere here # I assume that neither dx (dy, dz) nor errors can be zero or negative. dx = self.nc.variables[x][mask] dim = log10(dx) figure(figsize=(10, 6)) clf() hold(True) colors = ['red', 'blue', 'green', 'black', 'brown', 'cyan'] for (v, c) in zip(vars, colors): # Get a particular variable, transform and fit a line through it: data = log10(self.nc.variables[v][mask]) p = polyfit(dim, data, 1) # Try to get the long_name, use short_name if it fails: try: name = self.nc.variables[v].long_name except: name = v # Create a label for the independent variable: if (x == "dx"): dim_name = "\Delta x" if (x == "dy"): dim_name = "\Delta y" if (x == "dz"): dim_name = "\Delta z" if (x == "dzb"): dim_name = "\Delta z_{bed}" # Variable label: var_label = "%s, $O(%s^{%1.2f})$" % (name, dim_name, p[0]) # Plot errors and the linear fit: plot(dim, data, label=var_label, marker='o', color=c) plot(dim, polyval(p, dim), ls="--", color=c) # Shrink axes, then expand vertically to have integer powers of 10: axis('tight') _, _, ymin, ymax = axis() axis(ymin=floor(ymin), ymax=ceil(ymax)) # Switch to km if dx (dy, dz) are big: units = self.nc.variables[x].units if (dx.min() > 1000.0 and (units == "meters")): dx = dx / 1000.0 units = "km" # Round grid spacing in x-ticks: xticks(dim, map(lambda(x): "%d" % x, dx)) xlabel("$%s$ (%s)" % (dim_name, units)) # Use default (figured out by matplotlib) locations, but change labels for y-ticks: loc, _ = yticks() yticks(loc, map(lambda(x): "$10^{%1.1f}$" % x, loc)) # Make sure that all variables given have the same units: try: ylabels = array(map(lambda(x): self.nc.variables[x].units, vars)) if (any(ylabels != ylabels[0])): print "Incompatible units!" else: ylabel(ylabels[0]) except: pass # Legend, grid and the title: legend(loc='best', borderpad=1, labelspacing=0.5, handletextpad=0.75, handlelength=0.02) # prop = FontProperties(size='smaller'), grid(True) title("Test %s %s (%s)" % (testname, plot_title, self.nc.source)) if self.save_figures: filename = "%s_%s_%s.%s" % (self.nc.source.replace(" ", "_"), testname.replace(" ", "_"), plot_title.replace(" ", "_"), self.file_format) savefig(filename)
dB_o = 8.7 * dA_o / A_o logf_o = pylab.log10(f_o) dlogf_o = (1 / pylab.log(10)) * df_o / f_o print(dlogf_o) print(dB_o) pylab.figure(1) pylab.title('Bode diagram of low-pass RC filter') pylab.xlabel('frequency [kHz]') pylab.ylabel('gain [dB]') pylab.ylim(-50, 2) pylab.xlim(1, 7) pylab.grid(color="gray") pylab.grid(color="gray") pylab.errorbar(logf_o, B_o, dB_o, dlogf_o, "o", color="black") init = numpy.array([0.0, 0.0]) par_o, cov_o = curve_fit(linear, logf_o, B_o, init, pylab.sqrt(dB_o * dB_o + 20.0 * dlogf_o * dlogf_o)) print(par_o, cov_o) chisq = (((dB_o - linear(logf_o, par_o[0], par_o[1])) / (pylab.sqrt(dB_o * dB_o + 20.0 * dlogf_o * dlogf_o)))**2).sum() ndof = len(logf_o) - 2 #Tolgo due parametri estratti dal fit p = 1.0 - scipy.stats.chi2.cdf(chisq, ndof) print("Chisquare/ndof = %f/%d" % (chisq, ndof)) print("p = ", p)
def plot_dynamics_of_search(): fieldnames = [ 'date', 'time', 'x1', 'x2', 'Q', 'F', 'step', 'label', 'dick' ] # pd_data = pd.read_csv("../data/simple_gradient_method_1300.csv", header=None, names=fieldnames) pd_data = pd.read_csv("../data/data_1320/search_method_1320.log", header=None, names=fieldnames) print(pd_data.shape) # print(pd_data.head()) useful_rows = ['dF'] useful_rows = ['the_only_one'] filtered_pd = pd_data[pd_data['label'].isin(useful_rows)] # print(filtered_pd) print(filtered_pd.shape) print(filtered_pd.head()) print(filtered_pd.tail()) print(filtered_pd['x1'].head()) print(filtered_pd['x2'].head()) x1 = pd.to_numeric(filtered_pd['x1']) x2 = pd.to_numeric(filtered_pd['x2']) F = pd.to_numeric(filtered_pd['F']) Q = pd.to_numeric(filtered_pd['Q']) # Q_true = Q/(0.08*1.8*1000) # TODO corrected due to error in adjustment module (remove after) Q_true = Q Qmax = Q_true.max() Q_true = Q_true / Qmax # Q_true = Q_true[np.abs(Q_true - Q_true.mean()) <= (3 * Q_true.std())] # keep only the ones that are within +3 to -3 standard deviations in the column 'Data'. # Q_true = Q_true[~(np.abs(Q_true - Q_true.mean()) > (3 * Q_true.std()))] print(Q_true) # for step = pd.to_numeric(filtered_pd['step']) dates = filtered_pd['date'] t = range(len(dates)) t_ticks = np.linspace(0, len(dates) - 1, 20) # pl.xticks(t[0::1000], times[0::1000], rotation='vertical') fig, axs = pl.subplots(4, sharex=True) # fig.suptitle('Search dynamics') pl.xticks(t[0::11], dates[0::11], rotation='vertical') axs[0].plot(t, x1, '-r', label="x1 coordinates of search steps") axs[0].grid() axs[0].set_ylabel("Total PPFD, mkmoles/m2*sec") # axs[0]. axs[1].plot(t, x2, '-b', label="x2 coordinates of search steps") axs[1].grid() axs[1].set_ylabel("Red/White") axs[2].plot(t, Q_true, '-g', label="Q values for search steps") axs[2].set_ylabel("Q_search, kg ESM / kg biomass") axs[2].grid() axs[3].plot(t, F, '-c', label="F values for search steps") # axs[3].plot(t, Q_true, '-c', label="F values for search steps") axs[3].set_ylabel("F, mgCO2/sec") axs[3].grid() pl.show() # only Q fig = pl.figure() pl.xticks(t[0::11], dates[0::11], rotation='vertical') # pl.plot(t, Q_true, '-g', label="Q_search, kg ESM / kg biomass ") pl.plot(t, Q_true, '-g', label="G_search, отн. ед.") # pl.plot(t, fr_fw, '-b', label="FARred/FARwhite") # pl.plot(t, far/10, '-r', label="FAR summ, mkmoles") pl.ylabel('G / Gmax') # pl.ylim(bottom=300, top=550) pl.xlabel('Time') # pl.title("Q, kg ESM / kg biomass") pl.legend() pl.grid() pl.show()
label='JADE') scatter(planilha['Pluto']['x'], planilha['Pluto']['y'], color='red', label='PLUTO') scatter(planilha['Tasso']['x'], planilha['Tasso']['y'], color='lime', label='TASSO') scatter(planilha['MarkJ']['x'], planilha['MarkJ']['y'], color='violet', label='MARK-J') yscale('log') grid(True, linestyle='--') legend() xlabel('$\sqrt{s}$ (GeV)', fontsize=20) ylabel('$\sigma$ (pb)', fontsize=20) show() # Parte 2 -------------------------------------------------------------------------------- barber = read_csv('barber.csv') y = (10**(-3)) * (4 * pi * hc2 * alpha2 / 3) * (x**(-2)) plot(x, y, color='navy', label='Previsão do Modelo') errorbar(barber['x'], barber['y'],
def plot_learning_curve(estimator, title, X, y, ylim=[0.2, 1.1], cv=None, n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)): """ Generate a simple plot of the test and traning learning curve. Parameters ---------- estimator : object type that implements the "fit" and "predict" methods An object of that type which is cloned for each validation. title : string Title for the chart. X : array-like, shape (n_samples, n_features) Training vector, where n_samples is the number of samples and n_features is the number of features. y : array-like, shape (n_samples) or (n_samples, n_features), optional Target relative to X for classification or regression; None for unsupervised learning. ylim : tuple, shape (ymin, ymax), optional Defines minimum and maximum yvalues plotted. cv : integer, cross-validation generator, optional If an integer is passed, it is the number of folds (defaults to 3). Specific cross-validation objects can be passed, see sklearn.cross_validation module for the list of possible objects n_jobs : integer, optional Number of jobs to run in parallel (default 1). """ fig = plt.figure() ax = plt.subplot(111) plt.title(title) if ylim is not None: plt.ylim(*ylim) plt.xlabel("Training examples") plt.ylabel("Score") #plt.xticks(color='w') #plt.yticks(color='w') train_sizes, train_scores, test_scores = learning_curve( estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes) train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.std(train_scores, axis=1) test_scores_mean = np.mean(test_scores, axis=1) test_scores_std = np.std(test_scores, axis=1) plt.grid(color='k') plt.fill_between(train_sizes, train_scores_mean - train_scores_std, train_scores_mean + train_scores_std, alpha=0.3, color="r") plt.fill_between(train_sizes, test_scores_mean - test_scores_std, test_scores_mean + test_scores_std, alpha=0.3, color="g") plt.plot(train_sizes, train_scores_mean, 'o-', color="r", label="Training score") plt.plot(train_sizes, test_scores_mean, 'o-', color="g", label="Cross-validation score") #ax.patch.set_color('k') ax.patch.set_linewidth = 2.5 axis = plt.gca().xaxis for line in axis.get_ticklines(): #line.set_color('w') line.set_markersize(10) line.set_markeredgewidth(1.5) #ax.set_edgecolor='w' #ax.patch.set_edgecolor='w' #fig.show() plt.legend(loc="best") #plt.savefig(title,facecolor='black') plt.savefig(title)
def plot(eof, pc, nmode, varfrac, filename, data, limits=None, cumvarfrac=None): """ Plot one mode of the CEOF """ import pylab import matplotlib if limits == None: #LatIni = self['Lat'].min() #LatFin = self['Lat'].max() #LonIni = self['Lon'].min() #LonFin = self['Lon'].max() pass else: LatIni = limits['LatIni'] LatFin = limits['LatFin'] LonIni = limits['LonIni'] LonFin = limits['LonFin'] # ---- cdict = { 'red': ((0.0, 0.0, 0.0), (0.5, 0.879, 0.879), (1.0, 0.0, 0.0)), 'green': ((0.0, 0.281, 0.281), (0.5, 0.418, 0.418), (1.0, 0.281, 0.281)), 'blue': ((0.0, 0.195, 0.195), (0.5, 0.184, 0.184), (1.0, 0.281, 0.281)) } um_sym_cmap = matplotlib.colors.LinearSegmentedColormap( 'um_sym_colormap', cdict, 256) cdict = { 'red': ((0.0, 0.879, 0.879), (1.0, 0.0, 0.0)), 'green': ((0.0, 0.418, 0.418), (1.0, 0.281, 1.0)), 'blue': ((0.0, 0.184, 0.184), (1.0, 0.281, 0.281)) } um_cmap = matplotlib.colors.LinearSegmentedColormap( 'um_colormap', cdict, 256) #cdict = {'red': ((0.0, 0.879, 0.879), # (0.5, 0.0, 0.0), # (1.0, 0.879, 0.879)), # 'green': ((0.0, 0.418, 0.418), # (0.5, 0.281, 0.281), # (1.0, 0.418, 0.418)), # 'blue': ((0.0, 0.184, 0.184), # (0.5, 0.195, 0.195), # (1.0, 0.184, 0.184))} #um_cmap = matplotlib.colors.LinearSegmentedColormap('um_colormap',cdict,256) cdict = { 'red': ((0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)), 'green': ((0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)), 'blue': ((0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 0.0, 0.0)) } bw_cmap = matplotlib.colors.LinearSegmentedColormap( 'bw_colormap', cdict, 256) cdict = { 'red': ((0.0, 0.45, 0.45), (0.5, 0.95, 0.95), (1.0, 0.45, 0.45)), 'green': ((0.0, 0.45, 0.45), (0.5, 0.95, 0.95), (1.0, 0.45, 0.45)), 'blue': ((0.0, 0.45, 0.45), (0.5, .95, 0.95), (1.0, 0.45, 0.45)) } grey_cmap = matplotlib.colors.LinearSegmentedColormap( 'grey_colormap', cdict, 256) # ---- parallels = np.arange(-5, 20.1, 5) meridians = np.arange(300, 340, 10) margin = 0.08 left = margin bottom = margin height_eof = (1 - 4 * margin) * .44 width_eof = (1 - 3 * margin) * .5 height_pc = (1 - 4 * margin) * .28 width_pc = (1 - 2 * margin) * 1 # ---- eof_amp = (eof.real**2 + eof.imag**2)**0.5 eof_phase = np.arctan2(eof.imag, eof.real) pc_amp = (np.real(pc)**2 + np.imag(pc)**2)**0.5 pc_phase = np.arctan2(np.imag(pc), np.real(pc)) fig = pylab.figure(figsize=(14, 10.5), dpi=300) cumvarfrac = None if cumvarfrac != None: title = "Mode: %i (%i%%) (cumulative %i%%)" % (nmode, varfrac * 1e2, cumvarfrac * 1e2) else: title = "Mode: %i (%i%%)" % (nmode, varfrac * 1e2) #if 'halfpower_period' in self: #if 'prefilter' in self.metadata: # if type(self.halfpower_period) == str: # halfpower_period = self.halfpower_period # else: # halfpower_period = round(self.halfpower_period) # title = "%s (%s half power:%s days)" % (title,self.metadata['prefilter']['type'], halfpower_period) fig.text(.5, .95, title, horizontalalignment='center', fontsize=16) # pylab.axes( [left, bottom + 2 * height_pc + 2 * margin, width_eof, height_eof]) map = Basemap(projection='merc', lat_ts=0, llcrnrlon=LonIni, llcrnrlat=LatIni, urcrnrlon=LonFin, urcrnrlat=LatFin, resolution='l', area_thresh=1000.) X, Y = map(*pylab.meshgrid(data['lon'], data['lat'])) map.contourf(X, Y, eof_amp * 1e2) pylab.title("CEOF amplitude") cbar = pylab.colorbar() cbar.set_label('[cm]') map.drawcoastlines() map.fillcontinents(color='0.0') map.drawparallels(parallels, labels=[1, 0, 0, 1]) map.drawmeridians(meridians, labels=[1, 0, 0, 1]) pylab.axes([ left + width_eof + margin, bottom + 2 * height_pc + 2 * margin, width_eof, height_eof ]) map = Basemap(projection='merc', lat_ts=0, llcrnrlon=LonIni, llcrnrlat=LatIni, urcrnrlon=LonFin, urcrnrlat=LatFin, resolution='l', area_thresh=1000.) X, Y = map(*pylab.meshgrid(data['lon'], data['lat'])) V = [-180, -150, -120, -90, -60, -30, 0, 30, 60, 90, 120, 150, 180] #V = range(-180,181,20) #import matplotlib.cm as cm #map.pcolor(X[0,:],Y[:,0],eof_phase*180/np.pi,cmap=um_sym_cmap) #map.contourf(X,Y,eof_phase*180/np.pi,V,cmap=um_sym_cmap) #from scipy.stats import scoreatpercentile #scoreatpercentile(x.flatten(),15) from numpy import ma #ind_sig = eof_amp<0.01 #eof_phase_deg = eof_phase*180/np.pi map.contourf(X, Y, eof_phase * 180 / np.pi, V, cmap=grey_cmap) map.contourf(X, Y, ma.masked_array(eof_phase * 180 / np.pi, mask=eof_amp < 0.01), V, cmap=um_sym_cmap) cbar = pylab.colorbar() cbar.set_label('[degrees]') pylab.title("CEOF phase") map.drawcoastlines() map.fillcontinents(color='0.0') map.drawparallels(parallels, labels=[1, 0, 0, 1]) map.drawmeridians(meridians, labels=[1, 0, 0, 1]) # ---- #pylab.subplot(2,2,2) pylab.axes([left, bottom + margin + height_pc, width_pc, height_pc]) pylab.plot_date(pylab.date2num(data['datetime']), pc_amp, '-') fig.autofmt_xdate() pylab.title("PC amplitude") pylab.ylabel('[dimensionless]') pylab.grid() # ---- #pylab.subplot(2,2,4) pylab.axes([left, bottom, width_pc, height_pc]) pylab.plot_date(pylab.date2num(data['datetime']), pc_phase * 180 / np.pi, '.') fig.autofmt_xdate() v = pylab.axis() pylab.axis((v[0], v[1], -181, 181)) pylab.title("PC phase") pylab.ylabel('[degrees]') pylab.grid() # ---- #pylab.subplot(2,2,4) #pylab.axes([left + margin + width_l, bottom, width_r, height_r]) #pylab.plot(np.absolute(scipy.fftpack.fft(pc_amp))[1:pc_amp.shape[0]/2]) #pylab.title("PC FFT") #pylab.grid() # ---- #pylab.show() print "Saving figure %s" % filename #fig.savefig(filename) pylab.savefig(filename) pylab.close()
pops = z0 # Rename z0 ## Plot the model t, prey, predators = pops.T # Split 'pops' into 3 arrays. # 'pops.T' transposes 'pops' - swaps columns and rows. f1 = p.figure() # Open empty figure object p.plot(t, prey, 'g-', label='Resource density') # Plot p.plot(t, predators, 'b-', label='Consumer density') # 'g-' specifies line colour as green. p.grid() # Show grid lines. p.legend(loc='best') p.xlabel('Time') p.ylabel('Population') p.title('Consumer-Resource population dynamics') p.annotate('r = %r, a = %r, z = %r, e = %r, K = %r' % (r, a, z, e, K), xy=(0, 0), xytext=(4, 15)) # Annotate plot - show the parameter values in the plot. # '%r' is a placeholder for an exact representation of the item. # 'xy=' - position of the element to annotate - irrelevant here. # 'xytext=' - position of the label. f1.savefig('../Results/prey_and_predators_3.pdf') # Save figure.
def main(): sort_type1 = "" sort_type2 = "" comp = "" file_name1 = "" file_name2 = "" k = 0 stat = False if len(sys.argv) == 10: if sys.argv[1] == "--type" and sys.argv[4] == "--comp" and sys.argv[ 6] == "--stat": sort_type1 = sys.argv[2] sort_type2 = sys.argv[3] comp = sys.argv[5] file_name1 = sys.argv[7] file_name2 = sys.argv[8] k = int(sys.argv[9]) stat = True else: if sys.argv[3] == "--type" and sys.argv[ 1] == "--comp" and sys.argv[6] == "--stat": sort_type1 = sys.argv[4] sort_type2 = sys.argv[5] comp = sys.argv[2] file_name1 = sys.argv[7] file_name2 = sys.argv[8] k = int(sys.argv[9]) stat = True else: print("Wrong format of arguments!") sys.exit() else: print("Wrong number of arguments!") sys.exit() if stat == True: const_n = 0 x = [i for i in range(100, 10001, 100)] y1, y2, y3, y4, y5 = [], [], [], [], [] write_file = open(file_name1, "w") for i in range(100, 10001, 100): y1.append(0) y2.append(0) y3.append(0) ind = int(i / 100 - 1) for j in range(k): tab = [random.randint(0, 10000) for l in range(i)] if sort_type1 == "insert": sorted_tab, func_time = time_decorator( insertion_sort, [tab, comp]) if sort_type1 == "merge": sorted_tab, func_time = time_decorator( merge_sort, [tab, comp]) if sort_type1 == "quick": sorted_tab, func_time = time_decorator( quick_sort, [tab, comp]) if sort_type1 == "dual-pivot": sorted_tab, func_time = time_decorator( dual_pivot_sort, [tab, comp]) if sort_type1 == "hybrid": sorted_tab, func_time = time_decorator( hybrid_sort, [tab, comp]) if sort_type1 == "select-quick": sorted_tab, func_time = time_decorator( select_quick_sort, [tab, comp]) write_file.write("n = " + str(i) + "\n") write_file.write("t = " + str(func_time) + "\n") write_file.write("c = " + str(compare_num) + "\n") write_file.write("s = " + str(shift_num) + "\n") y1[ind] += compare_num y2[ind] += shift_num y3[ind] += func_time y1[ind] /= k y2[ind] /= k y3[ind] /= k y4.append(y1[ind] / i) y5.append(y2[ind] / i) y11, y22, y33, y44, y55 = [], [], [], [], [] write_file2 = open(file_name2, "w") for i in range(100, 10001, 100): y11.append(0) y22.append(0) y33.append(0) ind = int(i / 100 - 1) for j in range(k): tab = [random.randint(0, 10000) for l in range(i)] if sort_type2 == "insert": sorted_tab, func_time = time_decorator( insertion_sort, [tab, comp]) if sort_type2 == "merge": sorted_tab, func_time = time_decorator( merge_sort, [tab, comp]) if sort_type2 == "quick": sorted_tab, func_time = time_decorator( quick_sort, [tab, comp]) if sort_type2 == "dual-pivot": sorted_tab, func_time = time_decorator( dual_pivot_sort, [tab, comp]) if sort_type2 == "hybrid": sorted_tab, func_time = time_decorator( hybrid_sort, [tab, comp]) if sort_type1 == "select-quick": sorted_tab, func_time = time_decorator( select_quick_sort, [tab, comp]) write_file2.write("n = " + str(i) + "\n") write_file2.write("t = " + str(func_time) + "\n") write_file2.write("c = " + str(compare_num) + "\n") write_file2.write("s = " + str(shift_num) + "\n") y11[ind] += compare_num y22[ind] += shift_num y33[ind] += func_time y11[ind] /= k y22[ind] /= k y33[ind] /= k y44.append(y11[ind] / i) y55.append(y22[ind] / i) pylab.subplot(2, 2, 1) pylab.plot(x, y1, 'r', label="c select quick sort") pylab.plot(x, y2, 'm', label="s select quick sort") pylab.plot(x, y11, 'b', label="c quick sort") pylab.plot(x, y22, 'c', label="s quick sort") pylab.legend() pylab.ylabel("c, s") pylab.xlabel("n ∈ {100,200,300, . . . ,10000}") pylab.grid(True) pylab.subplot(2, 2, 2) pylab.plot(x, y3, 'r', label="czas select quick sort") pylab.plot(x, y33, 'g', label="czas quick sort") pylab.legend() pylab.grid(True) pylab.ylabel("czas") pylab.xlabel("n ∈ {100,200,300, . . . ,10000}") pylab.subplot(2, 2, 3) pylab.plot(x, y4, 'r', label="c / n select quick sort") pylab.plot(x, y44, 'g', label="c / n quick sort") pylab.legend() pylab.grid(True) pylab.ylabel("c / n") pylab.xlabel("n ∈ {100,200,300, . . . ,10000}") pylab.subplot(2, 2, 4) pylab.plot(x, y5, 'r', label="s / n select quick sort") pylab.plot(x, y55, 'g', label="s / n quick sort") pylab.legend() pylab.ylabel("s / n") pylab.xlabel("n ∈ {100,200,300, . . . ,10000}") pylab.grid(True) pylab.show() write_file.close() const_n = sum(i for i in y1) / sum(i for i in y11)
pb.ylabel('Frequency (Hz)') #tests on high pass filtering order=10 fc=2000. b, a = sp.signal.butter(order, fc / (fs/2.), btype='high') h, w = sp.signal.freqz(b,a) pb.figure() pb.title('Digital filter frequency response') pb.semilogy(h*((fs/2.)/np.pi), np.abs(w), 'b') pb.ylabel('Amplitude (dB)') pb.xlabel('Frequency (Hz)') pb.grid() pb.legend() #filter x2 = signal.lfilter(b, a, x1) pb.figure() Pxx, freqs, t, plot = pb.specgram( x2, NFFT=512, Fs=fs, noverlap=int(512 * 0.4)) pb.xlabel('Time (s)') pb.ylabel('Frequency (Hz)') wavwrite(x2,'test.wav',fs)
def plot_delays(runid, coincid, exp_delays=None, rec_source=None, rec_dir=None, ant_pos=None): # Plot expected vs measured trig delays # Load arrays of delays if not in argument if exp_delays is None: print("Processing recons", coincid, " in run", runid) coincid = int(coincid) # Exp delays cfile = txtdir + "R" + runid + "_coinctable.txt" c = np.loadtxt(cfile) coincids = c[:, 3] ind = np.argwhere(coincids == coincid) ants = np.array(c[ind, 1]).T[0] exp_delays = np.array(c[ind, 4]).T[0] else: ants = ant_pos[:, 0] # Load antenna positions if not in argument if ant_pos is None: uid, x, y, z = getPos() for a in ants: ind = np.argwhere(uid == a)[0] # Makes me crazy ant_pos.append([a, x[ind][0], y[ind][0], z[ind][0]]) #Northing, Westing, # Up ant_pos = np.array(ant_pos) # Load sph recons if not in argument if rec_source is None: sfile = txtdir + "R" + str(runid) + "_sphrecons.txt" a = np.loadtxt(sfile) coincids = a[:, 0] ind = np.argwhere(coincids == coincid)[0] rec_source = np.array([a[ind, 4], -a[ind, 3], a[ind, 5]]).T[0] #Now build expected delays for spherical hypothesis disv = ant_pos[:, 1:4] - rec_source recs_delays = np.linalg.norm(disv, axis=1) / c0 * 1e9 recs_delays = [recs_delays - np.min(recs_delays)][0] # Compute Chi2 chi2s = np.sum(np.square(recs_delays - exp_delays) / (sigma_t * sigma_t)) ndf = len(ants) - 3 chi2sndf = chi2s / ndf # Load plane recons if not in argument if rec_dir is None: pfile = txtdir + "R" + str(runid) + "_planerecons.txt" a = np.loadtxt(pfile) coincids = a[:, 0] ind = np.argwhere(coincids == coincid)[0] rec_dir = [a[ind, 3][0], a[ind, 5][0]] # Now build expected delays for plane hypothesis # First build wavefront vector st = np.sin(np.radians(rec_dir[0])) ct = np.cos(np.radians(rec_dir[0])) sp = np.sin(np.radians(rec_dir[1])) cp = np.cos(np.radians(rec_dir[1])) k = np.array([st * cp, st * sp, ct]) # Now build delay vector disv = np.matmul(ant_pos[:, 1:4], k) recp_delays = disv / c0 * 1e9 recp_delays = recp_delays - np.min(recp_delays) # Compute Chi2 chi2p = np.sum(np.square(recp_delays - exp_delays) / (sigma_t * sigma_t)) ndf = len(ants) - 2 chi2pndf = chi2p / ndf # Display if DISPLAY and len(ants) > 30: # and len(ants)>4 and chi2sndf>100: # and exp_delays[0]==103: # and len(ants)>4 and chi2sndf>100: print("Coinc", coincid, "R", runid, ":") print("Experimental delays:", exp_delays) print("Reconstructed delays:", recs_delays) print("for point source reconstructed at location:", rec_source) print("Chi2/ndf =", chi2sndf) print("Reconstructed delays:", recp_delays) print("for reconstructed wave propag direction:", rec_dir) print("Chi2/ndf =", chi2pndf) pl.figure(1) pl.subplot(1, 2, 1) pl.plot(exp_delays, recp_delays, 'sk') pl.title("Plane recons") pl.grid(True) pl.xlabel("Experimental trigger delays (ns)") pl.ylabel("Reconstructed trigger delays (ns)") xl = [-100, max(exp_delays), max(exp_delays)] pl.plot(xl, xl, 'r') for i in range(len(ants)): pl.text(exp_delays[i] + 100, recp_delays[i], str(int(ants[i]))) textmax = max(max(exp_delays), max(recp_delays)) pl.text( 0, textmax * 0.95, "($\Theta$,$\phi$)=({0},{1}) deg".format(round(rec_dir[0], 1), round(rec_dir[1], 1))) pl.text(0, textmax * 0.9, "$\chi^2$/ndf = {0}".format(round(chi2pndf), 1)) pl.subplot(1, 2, 2) pl.plot(exp_delays, recs_delays, 'sk') pl.plot(xl, xl, 'r') pl.grid(True) pl.xlabel("Experimental trigger delays (ns)") pl.ylabel("Reconstructed trigger delays (ns)") for i in range(len(ants)): pl.text(exp_delays[i] + 100, recs_delays[i], str(int(ants[i]))) textmax = max(max(exp_delays), max(recs_delays)) pl.text( 0, textmax * 0.95, "Source position=({0},{1},{2})m".format(round(rec_source[0], 1), round(rec_source[1], 1), round(rec_source[2], 2))) pl.text(0, textmax * 0.9, "$\chi^2$/ndf = {0}".format(round(chi2sndf, 1))) pl.title("Spherical recons") pl.suptitle('Coinc {0} R{1}'.format(coincid, runid)) input() pl.close('all') return chi2sndf, chi2pndf
Z += [scans.z[i]] EDGE += [scans.offset[i]] offset = scan.offset if "offset" in scan.columns else scan["0"] fom = scan.FOM if "FOM" in scan.columns else scan["1"] OFFSET += [offset] FOM += [fom] from pylab import figure,plot,title,xlim,ylim,grid,legend,xlabel,ylabel,\ gca,arange,array,scatter fig = figure() title("Phi and GonZ where scan were done") scatter(Z, PHI, marker="o", c=range(0, len(PHI))) xlabel("GonZ [mm]") ylabel("Phi [deg]") grid() xmin, xmax = min(Z), max(Z) ymin, ymax = min(PHI), max(PHI) xmin, xmax = xmin - 0.05 * (xmax - xmin), xmax + 0.05 * (xmax - xmin) ymin, ymax = ymin - 0.05 * (ymax - ymin), ymax + 0.05 * (ymax - ymin) xlim(xmin=xmin, xmax=xmax) ylim(ymin=ymin, ymax=ymax) PDF_file.savefig(fig) xmin, xmax = min(min(x) for x in OFFSET), max(max(x) for x in OFFSET) ymin, ymax = min(min(y) for y in FOM), max(max(y) for y in FOM) xmin, xmax = xmin - 0.05 * (xmax - xmin), xmax + 0.05 * (xmax - xmin) ymin, ymax = ymin - 0.05 * (ymax - ymin), ymax + 0.05 * (ymax - ymin) for i in range(0, len(FOM)):
total_rewards.append(total_reward) # The more we learn, the less we take random actions epsilon -= decay * epsilon if steps == 100 and TM == 1: print("\nWalked so long and killed by toxic mist in", steps, "steps...".format(steps)) print("\nReward = ", reward, " gold...") plt.figure(1) plt.subplot(121) plt.plot(scores) plt.title( "Followed path for this epoch (Get lost and killed by toxic mist)") plt.xlabel('Steps') plt.ylabel('States for corresponding steps') plt.grid(True) plt.subplot(122) plt.plot(bounties) plt.title("Taken rewards for each step in this epoch") plt.xlabel('Steps') plt.ylabel('Taken rewards for corresponding steps') plt.grid(True) plt.show() time.sleep(1.2) elif steps == 100: print("\nFailed to find basilisk in", steps, "steps...".format(steps)) print("\nReward = ", reward, " gold...") plt.figure(1) plt.subplot(121)