def drawPlots(folder): #names = os.listdir(folder) names = ['Query_Errors_Base', 'Query_Errors_Naive', 'Comm_Query_Error', "QError_Base_vs_Naive",'Comm_Matrix_Error','True_H_vs_Emp', 'True_Ax_vs_Emp', '(Ax)^2_v.s A(x^2)', 'ConditionalError','ConditionalEmp','ConditionalTrue', 'Base_Errors', 'BaseComp_Area', "MinError_Dif_Bases", "ArgMin_Dif_Bases" , "Multiple_Trials_ModelError"] l = len(names) i = 1 s = math.ceil(l**0.5) L = '' for n in names: d = getDataFromFile(folder+"/" + n) plt.subplot(s,s,i) for j in range(len(d[2])): if j == 0: L = 'Abs' else: L = 'Non-Abs' plt.plot(d[2][j],d[3][j], colorsOther[j%4], label=L) plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) #plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, # ncol=2, mode="expand", borderaxespad=0.) plt.xlabel(d[0]) plt.ylabel(d[1]) plt.title(n) i += 1 plt.subplots_adjust( hspace=0.88 ) #plt.tight_layout() plt.show()
def plot_fgmax_grid(): fg = fgmax_tools.FGmaxGrid() fg.read_input_data('fgmax_grid1.txt') fg.read_output() #clines_zeta = [0.01] + list(numpy.linspace(0.05,0.3,6)) + [0.5,1.0,10.0] clines_zeta = [0.001] + list(numpy.linspace(0.05,0.25,10)) colors = geoplot.discrete_cmap_1(clines_zeta) plt.figure(1) plt.clf() zeta = numpy.where(fg.B>0, fg.h, fg.h+fg.B) # surface elevation in ocean plt.contourf(fg.X,fg.Y,zeta,clines_zeta,colors=colors) plt.colorbar() plt.contour(fg.X,fg.Y,fg.B,[0.],colors='k') # coastline # plot arrival time contours and label: arrival_t = fg.arrival_time/3600. # arrival time in hours #clines_t = numpy.linspace(0,8,17) # hours clines_t = numpy.linspace(0,2,5) # hours #clines_t_label = clines_t[::2] # which ones to label clines_t_label = clines_t[::1] # which ones to label clines_t_colors = ([.5,.5,.5],) con_t = plt.contour(fg.X,fg.Y,arrival_t, clines_t,colors=clines_t_colors) plt.clabel(con_t, clines_t_label) # fix axes: plt.ticklabel_format(format='plain',useOffset=False) plt.xticks(rotation=20) plt.gca().set_aspect(1./numpy.cos(fg.Y.mean()*numpy.pi/180.)) plt.title("Maximum amplitude / arrival times (hrs)")
def multi_plot_grid(sig, num = 4, path = None, changes = None): """ Plot in a grid structure. If path "/.../Plot.png" is provided then output plot will be saved into the file. If the list changes is provided thet vertical red lines will be plotted to mark locations. """ n =len(sig) md = n % num wdth = n / num for i in range(1, num+1): plt.subplot(num/2, num/2, i) plt.plot(sig) if changes != None: for j,e in enumerate(changes): plt.axvline(x = e, color = "red") if i == num: plt.xlim((i-1)*wdth, i * wdth + md) else: plt.xlim((i-1)*wdth, i * wdth) plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0)) if path: plt.savefig(path, dpi = 700) print "Figure is saved into " + path else: plt.show()
def check_enron_outliers(data_dict): fname="enron_salary_outlier.png" features_list = ["poi", "salary", "exercised_stock_options"] #features_list = ["poi", "from_this_person_to_poi", "shared_receipt_with_poi"] data = featureFormat(data_dict, features_list) midx = data[:, 2].argmax() feature_2_max = max(data[:, 2]) print "idx of max ", features_list[2], " = ", midx print "max " , features_list[2], " = ", feature_2_max, ", ", data[:, 2][midx] plt.subplot(1,2,1) colors=map(lambda x: 'red' if x else 'grey', data[:, 0]) plt.scatter(data[:, 1], data[:, 2], s=40+data[:,0], c=colors, alpha=0.5, lw=0.) plt.xlabel(features_list[1]) plt.ylabel(features_list[2]) # Now remove one outlier data_dict.pop("TOTAL", 0) data = featureFormat(data_dict, features_list) plt.subplot(1,2,2) colors=map(lambda x: 'red' if x else 'grey', data[:, 0]) plt.scatter(data[:, 1], data[:, 2], s=40+data[:,0], c=colors, alpha=0.5, lw=0.) #plt.ticklabel_format(axis([-0.2e7, 1.2e7, -0.5, 4.0]) plt.ticklabel_format(useOffset=True) plt.xlabel(features_list[1]) plt.ylabel(features_list[2]) plt.title("{0} vs {1} Plots before and after Outlier Removal.".format(features_list[1], features_list[2]), x=-0.1, y=1.05) plt.show()
def plot_minos_fit(self,p,decay="X",title="Fit Results",erange=9,step=4.07,lum=4200): fig = plt.figure(figsize=(8,6)) plt.errorbar(self.x,self.y,self.yerr,fmt='o') M = p[0][0] G = p[1][0] B = p[2][0] dMl = p[0][1] dMu = p[0][2] dGl = p[1][1] dGu = p[1][2] dBl = p[2][1] dBu = p[2][2] x_fit = np.linspace(min(self.x),max(self.x),num=100) plt.plot(x_fit,self.convBWG(x_fit,M,G,B)) plt.xlabel("$\sqrt{\hat{s}} (MeV)$",fontsize=16) plt.ticklabel_format(useOffset=False) plt.ylabel("Counts",fontsize=16) plt.title(title,fontsize=16) lbl1 = "Input:\n$\mathcal{L}=%d pb^{-1}$\n$\Delta=%.3f\ MeV$\n$\delta\sqrt{\hat{s}} = %.3f MeV$" % (lum,step,self.beam) lbl1 = lbl1 + "\n$M_h = 125.0 GeV$\n$\Gamma_h = 4.07 MeV$\n$Br(h^0\\rightarrow$%s$) = %.3f$" % (decay, self.higgs[2]) lbl1 = lbl1 + "\n$\sigma_{bkg} = %.2f pb^{-1}$" % (self.bkg) lbl2 = "\nFit results:\n" lbl2 = lbl2 + "$\Delta M_h = %.3f_{-%.3f}^{+%.3f}\ MeV$\n" % (M-self.higgs[0], -1*dMl, dMu) lbl2 = lbl2 + "$\Gamma_h = %.3f_{-%.3f}^{+%.3f} \ MeV$\n" % (G, -1*dGl, dGu) lbl2 = lbl2 + "$Br(h^0\\rightarrow$%s$) = %.3f_{-%.3f}^{+%.3f}$\n" % (decay, B, -1*dBl, dBu) plt.annotate(lbl1, [0.1,0.6], xycoords='axes fraction',fontsize=15) plt.annotate(lbl2, [0.7,0.6], xycoords='axes fraction',fontsize=15) return plt
def getQsoCatalogueAllQSO(): cat = pyfits.open('/home/gpfs/manip/mnt0607/bao/hdumasde/Data/Catalogue/QSO_DR7_DR12_EBOSS_2016_01_08.fits', memmap=True )[1].data print cat.size cat = cat[ cat['RA']!=0. ] print cat.size col_ra = pyfits.Column(name='RA', format='D', array=cat['RA'], unit='deg') col_de = pyfits.Column(name='DEC', format='D', array=cat['DEC'], unit='deg') col_zz = pyfits.Column(name='Z', format='D', array=cat['Z'] ) ## Map plt.ticklabel_format(style='sci', axis='z', scilimits=(0,0)) plt.grid() plt.plot(cat["RA"], cat["DEC"], linestyle="", marker="o") plt.xlabel("Right Ascension (degree)") plt.ylabel("Declination (degree)") plt.title("BOSS DR12") plt.show() ## Distribution redshift plt.ticklabel_format(style='sci', axis='z', scilimits=(0,0)) plt.grid() plt.hist(cat['Z'][ cat['Z']>1.7 ], bins=50) plt.xlabel("Z") plt.ylabel("#") plt.title("BOSS DR12") plt.show() tbhdu = pyfits.BinTableHDU.from_columns([col_ra, col_de, col_zz]) tbhdu.writeto('/home/gpfs/manip/mnt0607/bao/hdumasde/Data/Catalogue/QSO_DR7_DR12_EBOSS_2016_01_08.fits', clobber=True)
def getQsoCatalogueAllObjects(): ''' ''' path = '/home/gpfs/manip/mnt0607/bao/hdumasde/Data/Catalogue/' listPAth = [path+'QSO_DR7_DR12_EBOSS_2016_01_08.fits', path+'DLA_all.fits', path+'all_Britt.fits', path+'VIPERS.fits', path+'QSO_3DHST.fits', path+'LOWZ_all.fits', path+'CMASS_all.fits'] name = ['QSO','DLA','Britt','VIPERS','3DHST','LOWZ','CMASS'] ## Distribution redshift for i in numpy.arange(len(listPAth)): cat = pyfits.open(listPAth[i], memmap=True )[1].data cat = cat[ (cat['Z']>0.1) ] cat = cat[ (cat['Z']<7.) ] if (cat.size==0): continue plt.hist(cat['Z'], bins=100,histtype='step',label=name[i]) plt.xlabel("Z") plt.ylabel("#") myTools.deal_with_plot(False,False,True) plt.show() ### Merge everyThing cat = pyfits.open(listPAth[0], memmap=True )[1].data ra = cat['RA'] de = cat['DEC'] zz = cat['Z'] for i in numpy.arange(1,len(listPAth)): cat = pyfits.open(listPAth[i], memmap=True )[1].data ra = numpy.append(ra, cat['RA']) de = numpy.append(de, cat['DEC']) zz = numpy.append(zz, cat['Z']) ## Map plt.ticklabel_format(style='sci', axis='z', scilimits=(0,0)) plt.grid() plt.plot(ra, de, linestyle="", marker="o") plt.xlabel("Right Ascension (degree)") plt.ylabel("Declination (degree)") plt.show() ## Distribution redshift plt.ticklabel_format(style='sci', axis='z', scilimits=(0,0)) plt.grid() plt.hist(zz, bins=200) plt.xlabel("Z") plt.ylabel("#") plt.show() ### Save col_ra = pyfits.Column(name='RA', format='D', array=ra, unit='deg') col_de = pyfits.Column(name='DEC', format='D', array=de, unit='deg') col_zz = pyfits.Column(name='Z', format='D', array=zz) tbhdu = pyfits.BinTableHDU.from_columns([col_ra, col_de, col_zz]) tbhdu.writeto('/home/gpfs/manip/mnt0607/bao/hdumasde/Data/Catalogue/ALL_EVERY_OBJECTS_2016_01_08.fits', clobber=True)
def plot_noisy_means(graph_title, means, bands, series, xvals=None, xlabel=None, ylabel=None, subtitle=None, data=None, filename='results.pdf'): colors = ['blue','red','green', 'black', 'orange', 'purple', 'brown', 'yellow'] # max 8 lines assert(means.shape == bands.shape) assert(xvals is None or xvals.shape[0] == means.shape[1]) assert(means.shape[0] <= len(colors)) if xvals is None: xvals = np.arange(means.shape[0]) ax = plt.axes([.1,.1,.8,.7]) plt.ticklabel_format(axis='y', style='plain', useOffset=False) for i,mean in enumerate(means): plt.plot(xvals, mean, label=series[i], color=colors[i]) plt.fill_between(xvals, mean + bands[i], mean - bands[i], facecolor=colors[i], alpha=0.2) if xlabel is not None: plt.xlabel(xlabel) if ylabel is not None: plt.ylabel(ylabel) if subtitle is not None: plt.figtext(.40,.9, graph_title, fontsize=18, ha='center') plt.figtext(.40,.85, subtitle, fontsize=10, ha='center') else: plt.title('{0}'.format(graph_title)) # Shink current axis by 20% box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) # Put a legend to the right of the current axis ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=12) plt.savefig(filename) plt.clf()
def get_QSO_cat_DR14(): path = '/home/gpfs/manip/mnt0607/bao/Spectra/DR14Q_v1_0.fits' cat = pyfits.open(path, memmap=True)[1].data print cat.size cat = cat[(cat['RA']!=0.)] cat = cat[(cat['DEC']!=0.)] cat = cat[(cat['Z']>0.)] ## Map plt.ticklabel_format(style='sci', axis='z', scilimits=(0,0)) plt.grid() plt.plot(cat["RA"], cat["DEC"], linestyle="", marker="o") plt.xlabel("Right Ascension (degree)") plt.ylabel("Declination (degree)") plt.title("BOSS DR12") plt.show() ## Distribution redshift plt.ticklabel_format(style='sci', axis='z', scilimits=(0,0)) plt.grid() plt.hist(cat['Z'], bins=50) plt.xlabel("Z") plt.ylabel("#") plt.title("BOSS DR14") plt.show() ### Save col_ra = pyfits.Column(name='RA', format='D', array=cat['RA'], unit='deg') col_de = pyfits.Column(name='DEC', format='D', array=cat['DEC'], unit='deg') col_zz = pyfits.Column(name='Z', format='D', array=cat['Z']) tbhdu = pyfits.BinTableHDU.from_columns([col_ra, col_de, col_zz]) tbhdu.writeto('/home/gpfs/manip/mnt0607/bao/hdumasde/Data/Catalogue/QSO_DR14_v1_0.fits', clobber=True) return
def waterfallCoarse(): """ Plots CCPWRS over time. Color indicates Power. """ plt.figure() plt.figure(figsize=(10,10)) plt.subplot(2,1,1) xpol = [row[0] for table in ccpwrs for row in table] imgX = np.array(xpol) imgX = imgX.reshape(len(ccpwrs),512) plt.imshow(imgX.astype(int), origin='lower', aspect='auto', cmap = cm.hot) plt.title('X-Pole CCPWRS') plt.ylabel('No. Time Steps (Time/Time Step)') plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) plt.xlabel('Coarse Channel ID') plt.subplot(2,1,2) ypol = [row[1] for table in ccpwrs for row in table] imgY = np.array(ypol) imgY = imgY.reshape(len(ccpwrs),512) plt.imshow(imgY.astype(int), origin='lower', aspect='auto', cmap = cm.hot) plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) plt.title('Y-Pole CCPWRS') plt.ylabel('No. Time Steps (Time/Time Step)') plt.xlabel('Coarse Channel ID') plt.subplots_adjust(hspace=0.4)
def plotDataMatrix(fig, dataMatrix, abcissaValue, yLabels, xlims, cols): dataShape = np.shape(dataMatrix) nMetrics = dataShape[0] assert nMetrics == len(yLabels) plt.figure(fig.number) nCols = np.ceil(nMetrics / 2.0) nRows = 2 for metricInd in range(nMetrics): subplotInd = metricInd + 1 nNrns = dataShape[1] plt.subplot(nRows, nCols, subplotInd) for nrnInd in range(nNrns): plt.plot(abcissaValue, dataMatrix[metricInd, nrnInd], marker='o', \ color=cols[nrnInd], ms=5, mfc=cols[nrnInd]) plt.ylabel(yLabels[metricInd]) plt.xlim(xlims) plt.ticklabel_format(style='sci', scilimits=(-2, 3), axis='y') plt.draw() return nRows, nCols
def plot_32_smooth_evo(pixnr, fig_name="combinedFlag"): """ Plot evolution of one pixel in SDMF3.0 smoothmask. Parameters ---------- pixnr : int detector pixel number [0..8191] """ import matplotlib.pyplot as plt fname = "sdmf_smooth_pyxelmask.h5" fid30 = h5py.File(fname, "r") grpname = "" ds_orbits = fid30[grpname+"orbits"] orbits = ds_orbits[:] ds_combined30 = fid30[grpname+fig_name] plt.cla() fig = plt.subplot(111) fig.set_ylim([-.1,1.1]) fig.set_title("SDMF3.2 smooth mask, Pixel "+str(pixnr-7*1024)) plt.ticklabel_format(useOffset=False) plt.plot(orbits, ds_combined30[:,pixnr-7*1024], 'bo') plt.show() return
def propplot(frames, plotsexes, age, ages = conf['ages'], causes = conf['causes'], countries = conf['countries'], sexes = conf['sexes'], types = conf['ptypes']): for sex in plotsexes: frames[sex][age].plot(label = sexes[sex]['alias']) plt.plot(smoother(frames[sex], age)[:, 0], smoother(frames[sex], age)[:, 1], label = sexes[sex]['alias'] + ' jämnad') icdlist = frames[random.randint(min(plotsexes), max(plotsexes))]['List'] plt.xlabel('År') plt.legend(framealpha = 0.5) plt.ylim(ymin = 0) plt.title(types[frames['type']]['alias']+' '+causes[frames['cause']]['alias'] + ' ' + countries[frames['country']]['alias'] + ' ' + str(frames['startyear']) + '\u2013' + str(frames['endyear']), y = 1.02) plt.ticklabel_format(scilimits = (-4, 0), axis = 'y') if 'note' in ages[age]: agenote = ' (' + ages[age]['note'] + ')' else: agenote = '' plt.ylabel(types[frames['type']]['alias'] + ' ' + ages[age]['alias'] + agenote) for index, value in icdlist.iteritems(): if (index == frames['startyear'] or (index-1 in icdlist and value != icdlist.loc[index-1])) and pd.notnull(value) : plt.text(index, 0, value, rotation = 90, va = 'bottom', ha = 'center', color = 'red')
def loadBootMap(): ''' ''' path = '/home/gpfs/manip/mnt0607/bao/hdumasde/Results/Txt/map.txt' data = numpy.loadtxt(path) re = data[:,0].astype(int) ra = data[:,1] de = data[:,2] for i in range(0,numpy.amax(re)+1): cut = (re==i) plt.plot(ra[cut], de[cut], linestyle="", marker="o") #plt.xlim([0,360.]) #plt.ylim([-90.,90.]) plt.ticklabel_format(style='sci', axis='z', scilimits=(0,0)) plt.grid() plt.xlabel(r'$R.A. (\degree)$') plt.ylabel(r'$Dec. (\degree)$') myTools.deal_with_plot(False,False,True) plt.show() return
def plot3dWireFrame(x_data,y_data,z_data, xyz_labels, title, fig_fname): matplotlib.rcParams['ps.useafm'] = True matplotlib.rcParams['pdf.use14corefonts'] = True matplotlib.rcParams['text.usetex'] = True rcParams["font.size"] = 11 fig = plt.figure() #ax = fig.add_subplot(111, projection='3d') ## Thibauth's code ax = fig.add_subplot(111, projection='3d') ax.plot_wireframe(x_data, y_data, z_data, linewidth=0.1) plt.ticklabel_format(style='sci', axis='z', scilimits=(0, 0)) ax.invert_xaxis() ## ax.set_xlabel(xyz_labels[0]) ax.set_ylabel(xyz_labels[1]) ax.set_zlabel(xyz_labels[2]) ax.set_title(title) plt.savefig(fig_fname, format = 'pdf', bbox_inches='tight')
def plot_fig(x, y, labels=('$x$', '$y$'), xlim=(0, 0), ylim=(0, 0), title='Figure', sci=True, equal=True, show=False, figname='data.txt', figtype='png'): """Read two columns of data from DATAFILE and plot.""" rc('text', usetex=True) pl.rc('font', family='serif') fig = pl.figure(figsize=(8, 6)) pl.plot(x, y, marker='.', markersize=1.0, color='r', linestyle='None') pl.xlabel(labels[0], fontsize=16) pl.ylabel(labels[1], fontsize=16) if not (xlim[0] == xlim[1]): pl.xlim(xlim) if not (ylim[0] == ylim[1]): pl.ylim(ylim) if sci: pl.ticklabel_format(style='sci', scilimits=(0, 0)) if equal: pl.axis('equal') if len(title) > 0: pl.title(title, fontsize=16) fig_name = figname + '.' + figtype pl.savefig(fig_name) if show: pl.show() pl.close(fig)
def plotandsave(): x = [] u = [] plt.figure(1) for i in range(len(files)): filename = files[i] x.append([]) u.append([]) f = open(filename) for line in f: numbers = line.split() if not float(numbers[1]) == 0: x[i].append(float(numbers[0])) u[i].append(float(numbers[1])) f.close() x[i] = np.array(x[i]) u[i] = np.array(u[i]) plt.plot(x[i], u[i], label='$\mathrm{%s}$' % (filename[7:-remove_back])) u_analytic = np.zeros(len(x[0])) for n in range(1, 1000): u_analytic += -2/(n*np.pi)*np.sin(n*np.pi*x[0])*np.exp(-n**2*np.pi**2*T) u_analytic = u_analytic + 1 - x[0] plt.plot(x[0], u_analytic, label='$\mathrm{Analytic}$') plt.xlabel('$x \ \ \mathrm{[Rel.\ units]}$', fontsize=18) plt.ylabel('$u\ \ \mathrm{[Rel.\ units]}$', fontsize=18) plt.legend(loc='best', fontsize=16) plt.text(0.2,0.2,'$\Delta x = %s$\n$T=%s$'%(dx,str(T)), fontsize=20,bbox=dict(facecolor='white', alpha=1)) # finding the errors by least squares for method in range(len(files)): # err = 0 # for i in range(len(x)): # err += (u_analytic[i] - u[method][i])**2 print files[method], '%.2e' % (np.std(np.abs(u_analytic - u[method]))*100) plt.figure(2) for method in range(len(files)): plt.plot(x[method], abs(np.array(u_analytic) - np.array(u[method]))/(np.array(u_analytic)), label='$\mathrm{%s}$'%str(files[method][7:-remove_back])) plt.xlabel('$x\ \ \mathrm{[Rel. \ units]}$', fontsize=18) plt.ylabel('$\mathrm{Absolute \ Relative \ error \ \ [\%]}$', fontsize=18) plt.legend(loc='best', fontsize = 16) plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) plt.ylim([-plt.ylim()[1]*0.05, plt.ylim()[1]]) plt.figure(1); plt.savefig(filename1) plt.close() plt.figure(2); plt.savefig(filename2) plt.close()
def plotXi(rescale): cut = (xi1D_[:,2] != 0.) xxx = xi1D_[:,0][cut] yyy = xi1D_[:,1][cut] yer = xi1D_[:,2][cut] #yyy -= yyy[-1] if (rescale==0): plt.errorbar(xxx, yyy, yerr=yer, fmt='o') plt.ylabel(r'$\xi^{ff} (|s|)$', fontsize=40) if (rescale==1): plt.errorbar(xxx, xxx*yyy, yerr=xxx*yer, fmt='o') plt.ylabel(r'$|s|.\xi^{ff} (|s|) \, [h^{-1}.Mpc]$', fontsize=40) if (rescale==2): plt.errorbar(xxx, xxx*xxx*yyy, yerr=xxx*xxx*yer, fmt='o') plt.ylabel(r'$|s|^{2}.\xi^{ff} (|s|) \, [(h^{-1}.Mpc)^{2}]$', fontsize=40) plt.title(r'$\delta_{'+forest__+'} \, - \, \delta_{'+forest__+'}$', fontsize=40) plt.xlabel(r'$|s| \, [h^{-1}.Mpc]$', fontsize=40) myTools.deal_with_plot(False,False,False) plt.xlim([ numpy.min(xxx)-10., numpy.max(xxx)+10. ]) plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) plt.show() return
def draw_figure(self, outname, title, xlabel, ylabel, datas, **kwargs): plt.cla() ls = [] # for data in datas: # l, = plt.plot(data) # ls.append(l) # l, = plt.plot(datas[0], "b-") ls.append(l) l, = plt.plot(datas[1], "g-") ls.append(l) #plt.legend([l], ["Optimal\nPayload Size"], loc="upper left", prop={'size':18}) #print ps #plt.ylim(ymin=0.0, ymax=1) plt.ticklabel_format(style='sci', axis='x', scilimits=(3,3)) plt.ticklabel_format(style='sci', axis='y', scilimits=(-2,0)) plt.grid(True) plt.xlabel(xlabel) if ylabel != None: plt.ylabel(ylabel) plt.title(title) outpath = "%s/%s.png" %(self.out_dir, outname) plt.savefig(outpath) if self.out_extension != "png": outpath = "%s/%s.%s" %(self.out_dir, outname, self.out_extension) plt.savefig(outpath)
def cover_freq(tile, cover=None, out=''): flnm = tile + '_cover_freq.npy' if os.path.isfile(flnm): return np.load(flnm) if cover is None: cover = cover_read(tile) his = np.bincount(cover.flat) freq = np.argsort(his)[::-1] mpl.use('PDF') import matplotlib.pyplot as plt, prettyplotlib as ppl #plt.figure(figsize=(11, 6), dpi=300) fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(11, 6)) ppl.bar(ax, range(len(his)), his, width = 1) plt.xticks(range(len(his)), sorted(veg_dict , key=veg_dict.get), rotation=30, fontsize=14) plt.ylabel('Pixel Number', fontsize=14) plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) plt.title('Vegetation Type ' + ' @' + tileCord(tile), fontsize=16) plt.tight_layout() plt.savefig(out+tile+'_cover_freq.pdf', dpi=300) plt.close() np.save(flnm,freq) return freq
def print_save_plot_skyline(tt, n_std=2.0, screen=True, save='', plot=''): if plot: import matplotlib.pyplot as plt skyline, conf = tt.merger_model.skyline_inferred(gen=50, confidence=n_std) if save: fh = open(save, 'w') header1 = "Skyline assuming 50 gen/year and approximate confidence bounds (+/- %f standard deviations of the LH)\n"%n_std header2 = "date \tN_e \tlower \tupper" if screen: print('\t'+header1+'\t'+header2) if save: fh.write("#"+ header1+'#'+header2+'\n') for (x,y, y1, y2) in zip(skyline.x, skyline.y, conf[0], conf[1]): if screen: print("\t%1.1f\t%1.1f\t%1.1f\t%1.1f"%(x,y, y1, y2)) if save: fh.write("%1.1f\t%1.1f\t%1.1f\t%1.1f\n"%(x,y, y1, y2)) if save: print("\n --- written skyline to %s\n"%save) fh.close() if plot: plt.figure() plt.fill_between(skyline.x, conf[0], conf[1], color=(0.8, 0.8, 0.8)) plt.plot(skyline.x, skyline.y, label='maximum likelihood skyline') plt.yscale('log') plt.legend() plt.ticklabel_format(axis='x',useOffset=False) plt.savefig(plot)
def plot_deviance(sol, save=False, draw=True, save_as_png=False, dpi=None): """ Plots the model deviance trace """ ext = ['png' if save_as_png else 'pdf'][0] fig, ax = plt.subplots(figsize=(4,3)) deviance = sol.MDL.trace('deviance')[:] sampler_state = sol.MDL.get_state()["sampler"] x = np.arange(sampler_state["_burn"]+1, sampler_state["_iter"]+1, sampler_state["_thin"]) plt.plot(x, deviance, "-", color="C3", label="DIC = %d\nBPIC = %d" %(sol.MDL.DIC,sol.MDL.BPIC)) plt.xlabel("Iteration") plt.ylabel("Model deviance") plt.legend(numpoints=1, loc="best", fontsize=9) plt.grid('on') if sampler_state["_burn"] == 0: plt.xscale('log') else: plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0)) ax.yaxis.set_major_locator(MaxNLocator(integer=True)) fig.tight_layout() if save: fn = 'MDEV-%s-%s.%s'%(sol.model_type_str,sol.filename,ext) save_figure(fig, subfolder='ModelDeviance', fname=fn, dpi=dpi) plt.close(fig) if draw: return fig else: return None
def plot_Category(train_df): cat_Count = train_df.groupby("Category").count() plt.figure() cat_Count.sort(columns="Dates", ascending=1)["Dates"].plot(kind="barh") plt.ticklabel_format(style='plain', axis='x', scilimits=(0, 0)) plt.tight_layout() plt.show()
def plot_District(train_df): dist_count = train_df.PdDistrict.value_counts() plt.figure() dist_count.plot(kind="barh") plt.ticklabel_format(style='plain', axis='x', scilimits=(0, 0)) plt.tight_layout() plt.show()
def plot_Dayofweek(train_df): day_count = train_df.groupby("DayOfWeek").count() plt.figure() day_count.sort(columns="Dates", ascending=1)["Dates"].plot(kind="barh") plt.ticklabel_format(style='plain', axis='x', scilimits=(0, 0)) plt.tight_layout() plt.show()
def make_1g_xs_graphs(nuc, sig): global burn_times nuc_zz = nucname.zzaaam(nuc) plt.clf() reactions = ['sigma_t', 'sigma_s', 'sigma_a', 'sigma_f'] markers = ['-', 'o', 's', 'x'] ncol = 2 if nuc_zz < 860000: reactions = reactions[:-1] markers = markers[:-1] ncol = 3 for reaction, marker in zip(reactions, markers): r, s, diff = sig[reaction, nuc] plt.plot(burn_times, s, color='k', marker=marker, linestyle='-', label="Serpent $\\{0}$".format(reaction)) #plt.errorbar(burn_times, r, diff*r, color='r', marker=marker, linestyle='-', label="RMG $\\{0}$".format(reaction)) plt.plot(burn_times, r, color='r', marker=marker, linestyle='-', label="RMG $\\{0}$".format(reaction)) plt.xlabel("burn time [days]") plt.ylabel(nuc + " One-Group Cross Sections [barns]") plt.ticklabel_format(scilimits=(-5, 5)) plt.legend(loc=0, ncol=ncol) plt.savefig(nuc + '_1g_xs.png') plt.savefig(nuc + '_1g_xs.eps') plt.clf()
def two_scale(t, s1, s2, fname = ""): plt.ticklabel_format(sytle='sci') fig = plt.figure(figsize=(8,4)) ax1 = plt.gca() ax1handle = ax1.plot(t, s1, 'b-', label="MI") ax1.set_xlabel('Translation') # Make the y-axis label and tick labels match the line color. ax1.set_ylabel('MI', color='b') ax1.ticklabel_format(style='sci') for tl in ax1.get_yticklabels(): tl.set_color('b') ax2 = ax1.twinx() ax2handle = ax2.plot(t, s2, 'r.',label="NMI") ax2.set_ylabel('NMI', color='r') ax2.ticklabel_format(style='sci') plt.legend([ax1handle, (ax1handle, ax2handle)], ("MI", "NMI")) for tl in ax2.get_yticklabels(): tl.set_color('r') if fname == "": plt.show() else: plt.savefig(fname)
def plot_KDE(sol, var1, var2, fig=None, ax=None, draw=True, save=False, save_as_png=False, dpi=None): """ Like the hexbin plot but a 2D KDE Pass mcmcinv object and 2 variable names as strings """ ext = ['png' if save_as_png else 'pdf'][0] if fig == None or ax == None: fig, ax = plt.subplots(figsize=(3,3)) MDL = sol.MDL if var1 == "R0": stoc1 = "R0" else: stoc1 = ''.join([i for i in var1 if not i.isdigit()]) stoc_num1 = [int(i) for i in var1 if i.isdigit()] try: x = MDL.trace(stoc1)[:,stoc_num1[0]-1] except: x = MDL.trace(stoc1)[:] if var2 == "R0": stoc2 = "R0" else: stoc2 = ''.join([i for i in var2 if not i.isdigit()]) stoc_num2 = [int(i) for i in var2 if i.isdigit()] try: y = MDL.trace(stoc2)[:,stoc_num2[0]-1] except: y = MDL.trace(stoc2)[:] xmin, xmax = min(x), max(x) ymin, ymax = min(y), max(y) # Peform the kernel density estimate xx, yy = np.mgrid[xmin:xmax:100j, ymin:ymax:100j] positions = np.vstack([xx.ravel(), yy.ravel()]) values = np.vstack([x, y]) kernel = gaussian_kde(values) kernel.set_bandwidth(bw_method='silverman') # kernel.set_bandwidth(bw_method=kernel.factor * 2.) f = np.reshape(kernel(positions).T, xx.shape) ax.set_xlim(xmin, xmax) ax.set_ylim(ymin, ymax) plt.sca(ax) # Contourf plot plt.grid(None) plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0)) plt.xticks(rotation=90) plt.locator_params(axis = 'y', nbins = 7) plt.locator_params(axis = 'x', nbins = 7) ax.contourf(xx, yy, f, cmap=plt.cm.viridis, alpha=0.8) ax.scatter(x, y, color='k', s=1, zorder=2) plt.ylabel("%s" %var2) plt.xlabel("%s" %var1) if save: fn = 'KDE-%s-%s.%s'%(sol.model_type_str,sol.filename,ext) save_figure(fig, subfolder='2D-KDE', fname=fn, dpi=dpi) plt.close(fig) if draw: return fig else: return None
def make_graphs(r, s, diff, serr=None, name="", r2=False): global burn_times plt.clf() # make the compare plot if serr is None: plt.plot(burn_times, s, 'k-', label="Serpent") else: plt.errorbar(burn_times, s, serr, color='k', label="Serpent") #plt.errorbar(burn_times, r, diff*r, color='r', label="RMG") plt.plot(burn_times, r, color='r', label="RMG") plt.xlabel("burn time [days]") plt.ylabel(name) plt.ticklabel_format(scilimits=(-5, 5)) plt.legend(loc=0) plt.savefig(name.split('[')[0].replace(' ', '_') + '.png') plt.savefig(name.split('[')[0].replace(' ', '_') + '.eps') plt.clf() plt.hist(burn_times, weights=diff, align='mid', color='g', rwidth=0.95) plt.xlabel("burn time [days]") plt.ylabel(name + " Relative Error") plt.savefig(name.split('[')[0].replace(' ', '_') + '_rel_err.png') plt.savefig(name.split('[')[0].replace(' ', '_') + '_rel_err.eps') plt.clf()
def plot_logp(sol, save=False, draw=True, save_as_png=False, dpi=None): """ Plots the model log-likelihood """ ext = ['png' if save_as_png else 'pdf'][0] fig, ax = plt.subplots(figsize=(4,3)) logp = logp_trace(sol.MDL) sampler_state = sol.MDL.get_state()["sampler"] x = np.arange(sampler_state["_burn"]+1, sampler_state["_iter"]+1, sampler_state["_thin"]) plt.plot(x, logp, "-") plt.xlabel("Iteration") plt.ylabel("Log-likelihood") plt.grid('on') if sampler_state["_burn"] == 0: plt.xscale('log') else: plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0)) ax.yaxis.set_major_locator(MaxNLocator(integer=True)) fig.tight_layout() if save: fn = 'LOGP-%s-%s.%s'%(sol.model_type_str,sol.filename,ext) save_figure(fig, subfolder='LogLikelihood', fname=fn, dpi=dpi) plt.close(fig) if draw: return fig else: return None
# print(type(tas_scaled[:,0,0])) # ds = xr.open_dataset(nc_spat_avg) # NetCDF or OPeNDAP URL # #ds is of type <class 'xarray.core.dataset.Dataset'> # # select a variable to plot # ds['tas'].plot() # plt.show() # ############# A plot of tas_scaled (region 1)############## fig = plt.figure() plt.plot(date, tas_scaled[:, 0, 0], c='r') plt.ylabel("%s (%s)" % (data_spat_avg.variables['tas'].long_name, data_spat_avg.variables['tas'].units)) plt.ticklabel_format(useOffset=False, axis='y') plt.xlabel("Time") plt.title("Colombia Temperature") plt.grid() # ############### A plot of tas_scaled (region 2) ############# fig2 = plt.figure() plt.plot(date2, tas_scaled2[:, 0, 0], c='r') plt.ylabel("%s (%s)" % (data_spat_avg2.variables['tas'].long_name, data_spat_avg2.variables['tas'].units)) plt.ticklabel_format(useOffset=False, axis='y') plt.xlabel("Time") plt.title("Alpin Region Temperature") plt.grid()
def plot_wake_states(plot_dict, cosmetics, fig_name, individual_state=None, fig_num=None): # read in inputs variables_dict = plot_dict['variables_dict'] integral_variables = plot_dict['integral_variables'] tgrid_ip = plot_dict['time_grids']['ip'] if individual_state == None: variables_to_plot = list(variables_dict['xd'].keys()) integral_variables_to_plot = integral_variables else: if individual_state in list(variables_dict['xd'].keys()): variables_to_plot = [individual_state] integral_variables_to_plot = [] elif individual_state in integral_variables: variables_to_plot = [] integral_variables_to_plot = [individual_state] counter = 0 for name in variables_to_plot: if is_wake_variable(name): counter += 1 counter += len(integral_variables) if individual_state == None: plot_table_r = 4 plot_table_c = int(np.ceil(np.float(counter) / np.float(plot_table_r))) else: plot_table_r = len(variables_to_plot + integral_variables_to_plot) plot_table_c = 1 # create new figure if desired if fig_num is not None: fig = plt.figure(num = fig_num) axes = fig.axes if len(axes) == 0: # if figure does not exist yet fig, axes = plt.subplots(num = fig_num, nrows = plot_table_r, ncols = plot_table_c) else: fig, axes = plt.subplots(nrows = plot_table_r, ncols = plot_table_c) # make vertical column array or list of all axes if type(axes) == np.ndarray: axes = axes.reshape(plot_table_r*plot_table_c,) elif type(axes) is not list: axes = [axes] counter = 0 for name in variables_to_plot: if is_wake_variable(name): counter += 1 ax = plt.axes(axes[counter-1]) for jdx in range(variables_dict['xd'][name].shape[0]): p = plt.plot(tgrid_ip, plot_dict['xd'][name][jdx]) if cosmetics['plot_ref']: plt.plot(plot_dict['time_grids']['ref']['ip'], plot_dict['ref']['xd'][name][jdx], linestyle= '--', color = p[-1].get_color() ) plt.title(name) for name in integral_variables_to_plot: counter += 1 ax = plt.axes(axes[counter-1]) if plot_dict['discretization'] == 'multiple_shooting': out_values, tgrid_out = tools.merge_integral_output_values(plot_dict['integral_outputs_final'],name, plot_dict, cosmetics) p = plt.plot(tgrid_out, out_values) else: p = plt.plot(tgrid_ip, plot_dict['integral_outputs'][name][0]) plt.title(name) ax.tick_params(axis='both', which='major') plt.subplots_adjust(wspace=0.3, hspace=2.0) plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 3)) plt.suptitle(fig_name)
def ifft_on_VTA_array(name_sol,d,FREQ_vector_signal,Xs_signal_normalized,t_vect,T,i_start_octv,arrays_shape): #in mm, in MRI space start_IFFT=time_lib.time() num_segments=sum(arrays_shape) Max_signal_for_point=np.zeros(num_segments,float) hf = h5py.File('/opt/Patient/'+name_sol[:-4]+'.h5', 'r') solution_sort_octv = hf.get('dataset_1') solution_sort_octv = np.array(solution_sort_octv) hf.close() Fr_corresp_ar = np.genfromtxt('/opt/Patient/Stim_Signal/Fr_corresp_array'+str(d["trunc_param"]*1.0)+'.csv', delimiter=' ') #Fr_octave_vect = np.genfromtxt('Stim_Signal/Fr_octave_vector_'+str(d["trunc_param"]*1.0)+'.csv', delimiter=' ') FR_vec_sign_octv = np.genfromtxt('/opt/Patient/Stim_Signal/FR_vector_signal_octaves'+str(d["trunc_param"]*1.0)+'.csv', delimiter=' ') Fr_corresp_ar=np.round(Fr_corresp_ar,6) #Fr_octave_vect=np.round(Fr_octave_vect,6) N_freq_octv=(FR_vec_sign_octv.shape[0]) for i_point in range(num_segments): Xs_Tr=np.vectorize(complex)(solution_sort_octv[(i_point)*N_freq_octv:(i_point*N_freq_octv+N_freq_octv),3],solution_sort_octv[i_point*N_freq_octv:(i_point*N_freq_octv+N_freq_octv),4]) #real and im parts for the first point in VTA Xs_Tr_full_real=np.zeros(FREQ_vector_signal.shape[0],float) Xs_Tr_full_imag=np.zeros(FREQ_vector_signal.shape[0],float) stepper=0 for i_inx in range(Xs_Tr.shape[0]): if i_inx>=i_start_octv: rslt=np.where(Fr_corresp_ar[:,0]==np.round(FR_vec_sign_octv[i_inx],6)) step_octv=rslt[0].shape[0] #size of the freq. pack in the octave Xs_Tr_full_real[stepper:stepper+step_octv]=(Xs_Tr[i_inx].real) Xs_Tr_full_imag[stepper:stepper+step_octv]=(Xs_Tr[i_inx].imag) stepper=stepper+step_octv else: Xs_Tr_full_real[stepper]=(Xs_Tr[i_inx].real) Xs_Tr_full_imag[stepper]=(Xs_Tr[i_inx].imag) stepper=stepper+1 if i_point==0: np.savetxt('/opt/Patient/Field_solutions/Xs_Tr_full_real.csv', Xs_Tr_full_real, delimiter=" ") np.savetxt('/opt/Patient/Field_solutions/Xs_Tr_full_imag.csv', Xs_Tr_full_imag, delimiter=" ") Xs_Tr_full_complex=np.vectorize(complex)(Xs_Tr_full_real,Xs_Tr_full_imag) Xs_conv=Xs_signal_normalized*Xs_Tr_full_complex if np.mod(t_vect.shape[0], 2): # if the FT vector is odd fv_conj = np.conjugate(Xs_conv[-1:0:-1]) else: # if the FT vector is even fv_conj = np.conjugate(Xs_conv[-2:0:-1]) Y = np.concatenate((Xs_conv, fv_conj), axis=0) Signal_t_conv=np.fft.ifft(Y).real Max_signal_for_point[i_point]=abs(max(Signal_t_conv[:], key=abs)) if i_point==1: plt.figure(11111234) plt.plot(t_vect,Signal_t_conv) plt.xlim(0.000,T*5) plt.grid(True) plt.xlabel('t, sec') plt.ylabel('Potential, V') plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0)) plt.savefig('/opt/Patient/Images/Signal_convoluted_1st_point.png', format='png', dpi=500) np.save('/opt/Patient/Points_in_time/Signal_t_conv'+str(i_point), Signal_t_conv.real) minutes=int((time_lib.time() - start_IFFT)/60) secnds=int(time_lib.time() - start_IFFT)-minutes*60 print("----- IFFT took ",minutes," min ",secnds," s -----") return(Max_signal_for_point)
def diag_multiple_DAfields_comp(refField, expField, lon2d, lat2d, dt_curr, RMSE=None, itime=0, name_RefFields='True state', name_DAfields=None, prefixe='', var='SSH', name_var=None, ncentred=None, var_range=None, cmap='RdBu_r', save=False, path_save=None, plot_err_from_ref=False, xlabel='time (days)', ylabel='RMSE'): Nexp, NY, NX = expField.shape if var_range is None: if ncentred is not None: min_ = expField[:, ncentred:-(ncentred + 1), ncentred:-(ncentred + 1)].min() max_ = expField[:, ncentred:-(ncentred + 1), ncentred:-(ncentred + 1)].max() else: min_ = expField.min() max_ = expField.max() else: min_ = var_range[0] max_ = var_range[1] # Create 2xNda sub plots if RMSE is not None: gs = gridspec.GridSpec(2, Nexp + 2, width_ratios=[ 1, ] * (Nexp + 1) + [0.1]) fig = plt.figure(figsize=(Nexp * 10, 5 * Nexp)) else: gs = gridspec.GridSpec(1, Nexp + 2, width_ratios=[ 1, ] * (Nexp + 1) + [0.1]) fig = plt.figure(figsize=(Nexp * 10, int(2.5 * Nexp))) fig.suptitle(dt_curr.strftime("%Y-%m-%d"), fontsize=20) # Compute error from reference if this option is activated if plot_err_from_ref: expField = expField - refField # Plot Reference ax0 = plt.subplot(gs[0, 0]) ax0.pcolormesh(lon2d, lat2d, refField, cmap=plt.cm.get_cmap(cmap), vmin=min_, vmax=max_) ax0.set_title(name_RefFields, fontsize=20) # Plot subarea where RMSE is computed if ncentred is not None: ax0.plot([ lon2d[ncentred, ncentred], lon2d[ncentred, NX - ncentred - 1], lon2d[NY - ncentred - 1, NX - ncentred - 1], lon2d[NY - ncentred - 1, ncentred], lon2d[ncentred, ncentred] ], [ lat2d[ncentred, ncentred], lat2d[ncentred, NX - ncentred - 1], lat2d[NY - ncentred - 1, NX - ncentred - 1], lat2d[NY - ncentred - 1, ncentred], lat2d[ncentred, ncentred] ], '-k') # Plot Da fields for iexp in range(Nexp): ax = plt.subplot(gs[0, iexp + 1]) im = ax.pcolormesh(lon2d, lat2d, expField[iexp], cmap=plt.cm.get_cmap(cmap), vmin=min_, vmax=max_) if name_DAfields is not None: ax.set_title(name_DAfields[iexp], fontsize=20) else: ax.set_title('DA product nb ' + str(iexp), fontsize=20) # Plot subarea where RMSE is computed if ncentred is not None: ax.plot([ lon2d[ncentred, ncentred], lon2d[ncentred, NX - ncentred - 1], lon2d[NY - ncentred - 1, NX - ncentred - 1], lon2d[NY - ncentred - 1, ncentred], lon2d[ncentred, ncentred] ], [ lat2d[ncentred, ncentred], lat2d[ncentred, NX - ncentred - 1], lat2d[NY - ncentred - 1, NX - ncentred - 1], lat2d[NY - ncentred - 1, ncentred], lat2d[ncentred, ncentred] ], '-k') # Colorbar cax = plt.subplot(gs[0, -1]) cbar = fig.colorbar(im, cax=cax, format='%.0e') cbar.ax.set_ylabel(var, fontsize=15) if RMSE is not None: Nt = RMSE.shape[1] # Plot RMSE ax1 = plt.subplot(gs[1, :]) for iexp in range(Nexp): rmse_t = np.zeros_like(RMSE[0]) rmse_t[:itime] = RMSE[iexp, :itime] rmse_t[itime:] = np.nan ax1.plot(rmse_t, label=name_DAfields[iexp]) ax1.set_xlabel(xlabel, fontsize=15) ax1.set_ylabel(ylabel, fontsize=15) plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0)) ax1.legend(fontsize=15) ax1.set_ylim([RMSE.min(), RMSE.max()]) ax1.set_xlim([0, Nt]) # Save figure if save: if name_var is not None: string = name_var else: string = var title = "comparison_" + string + '_' + prefixe + '_' + dt_curr.strftime( "%Y-%m-%d-%H%M") + '.png' plt.savefig(path_save + title) plt.axis('off') plt.close() return title else: plt.show() return
with open("result.txt",'w') as f: print('djds', djds, file = f) print('interval, +-', interval, file = f) c2, djds2, interval2, C1mid, Kmid = pickle.load(open("../change_u_mid_resolution/change_u_mid_reso.p", "rb")) normalize( djds2, interval2, c2, C1mid ) # plot history of two djds yl = ['$[d\langle D_r \\rangle / dU] \,/\, [F_0/U_0]$', '$[d\langle S_b \\rangle / dU] \,/\, [P_0/U_0]$','',''] for i in range(4): fig = plt.figure(figsize=(8,6)) # gcf().subplots_adjust(bottom=0.15) plt.plot(xx, c[start_seg_4compute:,i], label='finer mesh', linewidth=4, linestyle='solid', color='k') plt.plot(xx, djds[i]+C1[i]*xx**-0.5, 'k--') plt.plot(xx, djds[i]-C1[i]*xx**-0.5, 'k--') plt.plot(xx, c2[start_seg_4compute:,i], label='coarser mesh', linewidth=4, linestyle='dashdot', color='k') plt.plot(xx, djds2[i]+C1mid[i]*xx**-0.5, 'k--') plt.plot(xx, djds2[i]-C1mid[i]*xx**-0.5, 'k--') plt.grid plt.legend(loc=3) plt.xlabel('$T/t_0$') plt.ylabel(yl[i]) plt.ylim([0.5* max(c[start_seg_4compute:,i]), 1.2* max(c[start_seg_4compute:,i])]) plt.ticklabel_format(style='sci', axis='y', scilimits=(3,3)) plt.tight_layout() plt.savefig('dJds_history' + str(i) + suffix[i]) plt.close(fig)
def DrawFigure(x_values, y_values, legend_labels, x_label, y_label, filename, allow_legend): # you may change the figure size on your own. fig = plt.figure(figsize=(9, 3)) figure = fig.add_subplot(111) FIGURE_LABEL = legend_labels if not os.path.exists(FIGURE_FOLDER): os.makedirs(FIGURE_FOLDER) # values in the x_xis index = np.arange(len(x_values)) # the bar width. # you may need to tune it to get the best figure. width = 0.5 # draw the bars bottom_base = np.zeros(len(y_values[0])) bars = [None] * (len(FIGURE_LABEL)) for i in range(len(y_values)): bars[i] = plt.bar(index + width / 2, y_values[i], width, hatch=PATTERNS[i], color=LINE_COLORS[i], label=FIGURE_LABEL[i], bottom=bottom_base, edgecolor='black', linewidth=3) bottom_base = np.array(y_values[i]) + bottom_base # sometimes you may not want to draw legends. if allow_legend == True: plt.legend( bars, FIGURE_LABEL # mode='expand', # shadow=False, # columnspacing=0.25, # labelspacing=-2.2, # borderpad=5, # bbox_transform=ax.transAxes, # frameon=False, # columnspacing=5.5, # handlelength=2, ) if allow_legend == True: handles, labels = figure.get_legend_handles_labels() if allow_legend == True: leg = plt.legend( handles[::-1], labels[::-1], loc='center', prop=LEGEND_FP, ncol=1, # bbox_to_anchor=(0.5, 1.25), bbox_to_anchor=(1.19, 0.5), handletextpad=0.1, borderaxespad=0.0, handlelength=1.8, labelspacing=0.3, columnspacing=0.3, ) leg.get_frame().set_linewidth(2) leg.get_frame().set_edgecolor("black") # you may need to tune the xticks position to get the best figure. plt.xticks(index + 0.5 * width, x_values) yfmt = ScalarFormatterForceFormat() yfmt.set_powerlimits((0, 0)) figure.get_yaxis().set_major_formatter(yfmt) plt.ticklabel_format(axis="y", style="sci", scilimits=(0, 0), useMathText=True) plt.grid(axis='y', color='gray') figure.yaxis.set_major_locator(LinearLocator(3)) # figure.yaxis.set_major_locator(LinearLocator(6)) # figure.yaxis.set_major_locator(LogLocator(base=10)) figure.get_xaxis().set_tick_params(direction='in', pad=10) figure.get_yaxis().set_tick_params(direction='in', pad=10) plt.xlabel(x_label, fontproperties=LABEL_FP) plt.ylabel(y_label, fontproperties=LABEL_FP) size = fig.get_size_inches() dpi = fig.get_dpi() plt.savefig(FIGURE_FOLDER + "/" + filename + ".pdf", bbox_inches='tight', format='pdf')
plt.plot(rr_n, kflux_int / lstar, label=r'$\rm{F}_{KE}$', linewidth=lw) plt.plot(rr_n, vflux_int / lstar, label=r'$\rm{F}_{visc}$', linewidth=lw) plt.plot(rr_n, tflux_int/lstar, label= r'$\rm{F}_{total}$',\ linewidth=lw, color='black') if magnetism: plt.plot(rr_n, mflux_int/lstar, label=r'$\rm{F}_{Poynting}$',\ linewidth=lw) # Mark zero line plt.plot(rr_n, np.zeros_like(rr_n), 'k--', linewidth=lw) # Get the y-axis in scientific notation plt.ticklabel_format(useMathText=True, axis='y', scilimits=(0, 0)) # Get ticks everywhere plt.minorticks_on() plt.tick_params(top=True, right=True, direction='in', which='both') # Set the x limits if xminmax_was_None: xminmax = np.min(rr_n), np.max(rr_n) # If user set -rminwindow or -rmaxwindow, this trumps the bounds if not rminwindow is None: rmin = np.min(rr_n) rmax = np.max(rr_n) Delta_r = rmax - rmin xminmax = rmin - rminwindow * Delta_r, rmin + rminwindow * Delta_r if not rmaxwindow is None:
def FracArea(fpath_in_fracNodes, fpath_in_dispVec, plotting=False, norm_by_len=False): """ Created on Tue May 7 15:22:48 2019 calculates area of polygons created from combined roxol crack nodes and displacement vectors, i.e. in effect fracture area inputs: fpath_in_fracNodes: file path for fracture nodes in format (x0 y0 x1 y1 ... for node coordinates) per fracture, and of the form " path + '*_fracNodes.txt' " fpath_in_dispVec: file path for fracture displacement Vectors in format (dx00 dy00 dx01 dy01 dx10 dy10 dx11 dy11 ... for bidirectional node displacement) per fracture, and of the form " path + '*_dispVec.txt' " plotting: True/False input. displays plots or not. Standard: False norm_by_len = True/False input. normalizes fracture area by respective fracture length or not. Standard: True @author: olerab """ files_fracNodes = sorted(glob.glob(fpath_in_fracNodes)) files_dispVec = sorted(glob.glob(fpath_in_dispVec)) if len(files_fracNodes) != len(files_dispVec): raise Exception( 'Error, need same number of files containing "fracNodes" and "displacementVectors"' ) cnt = 0 frac_area_lib = {} frac_area = list() frac_area_max = list() frac_area_min = list() frac_area_avg = list() frac_area_med = list() frac_area_std = list() frac_length = list() # read frac nodes and displacement vectors, and store them as doubles #create figure for boxplots for cnt in range(0, len(files_fracNodes)): #fnodes = np.genfromtxt(fracNodeFile, delimiter = "\t") file_fracNodes = open(files_fracNodes[cnt], 'r') i = 0 fracNodes = {} for line in file_fracNodes: data = line.split() fracNodes[i] = np.array(np.float_(data)) i += 1 file_fracNodes.close() #fnodes = np.genfromtxt(fracNodeFile, delimiter = "\t") file_dispVec = open(files_dispVec[cnt], 'r') i = 0 dispVec = {} for line in file_dispVec: data = line.split() dispVec[i] = np.array(np.float_(data)) i += 1 file_dispVec.close() # calculate length of each fracture in a result step to normalize area at a later stage fraclen = list() for i in range(0, len(fracNodes)): segments = list() for k in range(0, int(len(fracNodes[i]) / 2 - 2)): segments.append( SegmentLength(fracNodes[i][2 * k], fracNodes[i][2 * k + 2], fracNodes[i][2 * k + 1], fracNodes[i][2 * k + 3])) fraclen.append(np.sum(segments)) # build polygon nodes by combining frac nodes and displacement vectors polyNodes = {} polyarea = list() #extract pairwise displacement vectors for j in range(0, len(fracNodes)): disp1 = np.empty_like(fracNodes[j]) disp2 = np.empty_like(fracNodes[j]) disp1[0::2] = dispVec[j][0::4] disp1[1::2] = dispVec[j][1::4] disp2[0::2] = dispVec[j][2::4] disp2[1::2] = dispVec[j][3::4] #for k in range (0,len(fracNodes[j])): polyNodes[j] = np.append(fracNodes[j] + disp1, np.flip(fracNodes[j] + disp2)) polyNodesx = np.append(polyNodes[j][0:len(fracNodes[j]):2], polyNodes[j][len(fracNodes[j]) + 1::2]) polyNodesy = np.append(polyNodes[j][1:len(fracNodes[j]):2], polyNodes[j][len(fracNodes[j])::2]) # calculate polunomial area, normalizeby the length (if desired) polyarea.append(PolyArea(polyNodesx, polyNodesy)) # plot polygons # if you need... #plt.plot(polyNodesx,polyNodesy) #plt.show() frac_area_max.append(np.max(polyarea)) frac_area_min.append(np.min(polyarea)) frac_area_avg.append(np.mean(polyarea)) frac_area_med.append(np.median(polyarea)) frac_area_std.append(np.std(polyarea)) if norm_by_len == True: frac_area.append(np.sum(polyarea) / np.sum(fraclen)) else: frac_area.append(np.sum(polyarea)) frac_area_lib[cnt] = frac_area frac_length.append(np.sum(fraclen)) #plotting if plotting == True: # -------------------- total fracture area at each step fig1 = plt.figure(figsize=(10, 5)) ax1 = fig1.add_subplot(111) line, = ax1.plot(frac_area, lw=2, marker='o', color='mediumvioletred') ax1.set_title(fpath_in_fracNodes[35:-16], fontsize=18) ax1.set_xlabel("Simulation Step", fontsize=18) ax1.set_ylabel("Total Fracture Area", fontsize=18) plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0)) plt.grid(True) plt.show() fig1.savefig(fpath_in_fracNodes[:-15] + 'plot_TotalFracArea.png') # --------------------- max, min, mean, standard deviation at each step fig2 = plt.figure(figsize=(10, 5)) ax2 = fig2.add_subplot(111) #line, = ax2.plot(frac_area, lw=2) ax2.errorbar(np.linspace(0, len(frac_area_avg) - 1, len(frac_area_avg)), frac_area_avg, yerr=[frac_area_min, frac_area_max], fmt='o', color='mediumvioletred') ax2.set_title(fpath_in_fracNodes[35:-16], fontsize=18) ax2.set_xlabel("Simulation Step", fontsize=18) ax2.set_ylabel("Mean Fracture Area", fontsize=18) ax2.plot(frac_area_med, lw=2, marker='o', color='red') plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0)) plt.grid(True) plt.show() fig2.savefig(fpath_in_dispVec[:-13] + 'plot_MeanMaxFracArea.png') else: print('PLOTTING DISABLED. use arg plotting = True to show plots') # return fracture area value return frac_area, frac_length
def MyScatter(xx, yy, yy_pred, name, stress_scale=1.0e3, strain_scale=1.0e-1, Test_or_Train="Train"): s, ls = 35, 33 mke = 20 plt.figure(figsize=(12, 10)) ax = plt.axes() plt.ticklabel_format(axis="y", style="sci", scilimits=(0, 0)) plt.scatter(xx[0:-1:mke, 0] * strain_scale, yy[0:-1:mke, 0] * stress_scale / th, label="Reference", facecolors='none', edgecolors='black') plt.scatter(xx[0:-1:mke, 0] * strain_scale, yy_pred[0:-1:mke, 0] * stress_scale / th, label=name + " model", facecolors='none', edgecolors='red') plt.xlabel(r"$E_{0}^{(11)}$", size=s, labelpad=21) plt.ylabel(r"$S_{0}^{(11)}$", size=s, labelpad=21) plt.tick_params(axis='both', labelsize=ls) plt.tick_params(axis='both', labelsize=ls) ax.yaxis.get_offset_text().set_fontsize(ls) plt.legend(prop={'size': ls}) plt.tight_layout() plt.savefig(Test_or_Train + "_sigma_xx_" + name + ".png") plt.close("all") plt.figure(figsize=(12, 10)) ax = plt.axes() plt.ticklabel_format(axis="y", style="sci", scilimits=(0, 0)) plt.scatter(xx[0:-1:mke, 1] * strain_scale, yy[0:-1:mke, 1] * stress_scale / th, label="Reference", facecolors='none', edgecolors='black') plt.scatter(xx[0:-1:mke, 1] * strain_scale, yy_pred[0:-1:mke, 1] * stress_scale / th, label=name + " model", facecolors='none', edgecolors='red') plt.xlabel(r"$E_{0}^{(22)}$", size=s, labelpad=21) plt.ylabel(r"$S_{0}^{(22)}$", size=s, labelpad=21) plt.tick_params(axis='both', labelsize=ls) plt.tick_params(axis='both', labelsize=ls) ax.yaxis.get_offset_text().set_fontsize(ls) plt.legend(prop={'size': ls}) plt.tight_layout() plt.savefig(Test_or_Train + "sigma_yy_" + name + ".png") plt.close("all") plt.figure(figsize=(12, 10)) ax = plt.axes() plt.ticklabel_format(axis="y", style="sci", scilimits=(0, 0)) plt.scatter(xx[0:-1:mke, 2] * strain_scale, yy[0:-1:mke, 2] * stress_scale / th, label="Reference", facecolors='none', edgecolors='black') plt.scatter(xx[0:-1:mke, 2] * strain_scale, yy_pred[0:-1:mke, 2] * stress_scale / th, label=name + " model", facecolors='none', edgecolors='red') plt.xlabel(r"$2E_{0}^{(12)}$", size=s, labelpad=21) plt.ylabel(r"$S_{0}^{(12)}$", size=s, labelpad=21) plt.tick_params(axis='both', labelsize=ls) plt.tick_params(axis='both', labelsize=ls) ax.yaxis.get_offset_text().set_fontsize(ls) plt.legend(prop={'size': ls}) plt.tight_layout() plt.savefig(Test_or_Train + "sigma_xy_" + name + ".png") plt.close("all")
#!/usr/bin/env python2 import matplotlib matplotlib.use("agg") import matplotlib.pyplot as plt import sys import numpy as np # Estimate delay is argv1 title = "ECDF of TX interval (s)" filename = 'tcp-tx.pdf' f = open(sys.argv[1]) a = np.array([]) throughput = [] for line in f: columns = line.split() a = np.append(a, float(columns[1])) f.close() x = np.sort(a) y = np.arange(len(x)) / float(len(x)) plt.xlabel('Interarrival (s)') plt.ylabel('ECDF') plt.title(title, fontdict={'fontsize': 20}) plt.plot(x, y, marker='', color='black', label='ecdf') plt.legend(loc='lower right') plt.ticklabel_format(useOffset=False) #plt.show() plt.savefig(filename, format='pdf') plt.close()
time_list.append(end - start) step_size_list.append(step_size) yt_list.append(error_training) yv_list.append(error_validation) i += 1 one3 = np.ones(len(time_list)) * 0.0000003 pt.figure(1) pt.scatter(step_size_list, yt_list, s=15, color='b') pt.plot(one3, yt_list, 'k-', color='r') axes = pt.gca() axes.set_xlim([min(step_size_list), max(step_size_list)]) axes.set_ylim([min(yt_list), max(yt_list)]) pt.ticklabel_format(style='sci', axis='x', scilimits=(-9, -7)) pt.ylabel('Error') pt.xlabel('Step Size') pt.title( 'Mean-squared error on the training set as a function of \u03B2 step size') pt.figure(2) pt.scatter(step_size_list, yv_list, s=15, color='b') pt.plot(one3, yv_list, 'k-', color='r') axes = pt.gca() axes.set_xlim([min(step_size_list), max(step_size_list)]) axes.set_ylim([min(yv_list), max(yv_list)]) pt.ticklabel_format(style='sci', axis='x', scilimits=(-9, -7)) pt.xlabel('Step_size') pt.ylabel('Error') pt.title(
def plot_data(data, xaxis='Epoch', value="AverageEpRet", condition="Condition1", smooth=1, no_legend=False, legend_loc='best', **kwargs): if smooth > 1: """ smooth data with moving window average. that is, smoothed_y[t] = average(y[t-k], y[t-k+1], ..., y[t+k-1], y[t+k]) where the "smooth" param is width of that window (2k+1) """ y = np.ones(smooth) for datum in data: x = np.asarray(datum[value]) z = np.ones(len(x)) smoothed_x = np.convolve(x,y,'same') / np.convolve(z,y,'same') datum[value] = smoothed_x if isinstance(data, list): data = pd.concat(data, ignore_index=True) sns.set(style="darkgrid", font_scale=1.5) # sns.set_palette('bright') print("##############") # print("##############") # xaxis_column_index = data.columns.get_loc(xaxis) # value_column_index = data.columns.get_loc(value) # data.index += 1 # data['Epoch'] += 1 # data = pd.concat([first_row, data]) # data.iloc[-1] = data.iloc[0] # data[xaxis] += 5000 # data.iloc[-1, column_index] = 0 # # data = data.sort_index() # print(data.loc[0]) sns.tsplot(data=data, time=xaxis, value=value, unit="Unit", condition=condition, legend=(not no_legend), ci='sd', **kwargs) plt.xlabel('environment interactions') plt.ylabel('average test return') """ If you upgrade to any version of Seaborn greater than 0.8.1, switch from tsplot to lineplot replacing L29 with: sns.lineplot(data=data, x=xaxis, y=value, hue=condition, ci='sd', **kwargs) Changes the colorscheme and the default legend style, though. """ if not no_legend: plt.legend(loc=legend_loc).draggable() """ For the version of the legend used in the Spinning Up benchmarking page, swap L38 with: plt.legend(loc='upper center', ncol=6, handlelength=1, mode="expand", borderaxespad=0., prop={'size': 13}) """ xscale = np.max(np.asarray(data[xaxis])) > 5e3 if xscale: # Just some formatting niceness: x-axis scale in scientific notation if max x is large plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0)) plt.tight_layout(pad=0.5)
num_bins, histtype=u'step', cumulative=1, density=1, facecolor='tab:blue', linewidth=2.5, alpha=0.6) n, bins, patches = plt.hist(after_x, num_bins, histtype=u'step', cumulative=1, density=1, facecolor='tab:orange', linewidth=2.5, alpha=0.6) plt.ticklabel_format(axis='y', style='sci', scilimits=(0, 0)) plt.axis([0, 350, 0, 1.05]) plt.ticklabel_format(axis='y', style='sci', scilimits=(0, 0)) plt.xlabel('Position along axis', size=16) plt.ylabel('Cumulative distribution function', size=16) #plt.title(r'Cell Distribution', size=16) legend_elements = [ Line2D([0], [0], marker='o', color='w', label='100nM fMLP', markerfacecolor='tab:blue', markersize=10), Line2D([0], [0], marker='o',
def auto_report(time_range, fig_nr, copied_file): print_file = open(copied_file, "r") lines = print_file.readlines() temp_list_1 = [] temp_list_2 = [] press_list = [] time_list = [] date_list = [] interval_val = 60 #append value for every x seconds if interval_val % (3600 * 24) == 0: int_in = int(interval_val / (3600 * 24)) interval_print = str(int_in) + " d" elif interval_val % 3600 == 0: int_in = int(interval_val / 3600) interval_print = str(int_in) + " h" elif interval_val % 60 == 0: int_in = int(interval_val / 60) interval_print = str(int_in) + " min" else: interval_print = str(interval_val) + " s" for i in range(0, int(time_range / interval_val)): temp_list_1.append(lines[-1 * time_range + i * interval_val - 1][2:8]) temp_list_2.append(lines[-1 * time_range + i * interval_val - 1][33:39]) press_list.append(lines[-1 * time_range + i * interval_val - 1][61:69]) time_list.append(lines[2 + i * 30][79:87].replace(":", ".")) date_list.append(lines[2 + i * 30][92:].replace("/", ".")) plt.figure(fig_nr) plt.plot(temp_list_1, label="Base Plate") plt.plot(temp_list_2, label="Sensor RTD") plt.title("Temperature history \n from " + str(lines[-1 * time_range - 1][92:102]) + ", " + str(lines[-1 * time_range - 1][79:84]) + "\n to " + str(lines[-1][92:102]) + ", " + str(lines[-1][79:84])) plt.xlabel("Time (" + interval_print + ")") plt.ylabel("Temperature (K)") plt.grid(True) plt.legend() plt.show() plt.savefig('./Plot_Output/Temperature_History_' + str(lines[-1 * time_range][92:102]).replace("/", "_") + "__" + str(lines[-1 * time_range - 1][79:84]).replace(":", "_") + "__" + str(lines[-1][79:84]).replace(":", "_") + '.png') plt.figure(fig_nr + 1) plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0)) plt.plot(press_list) plt.title("Pressure history \n from " + str(lines[-1 * time_range - 1][92:102]) + ", " + str(lines[-1 * time_range - 1][79:84]) + "\n to " + str(lines[-1][92:102]) + ", " + str(lines[-1][79:84])) plt.xlabel("Time (" + interval_print + ")") plt.ylabel("Pressure (mbar)") plt.grid(True) plt.show() plt.savefig('./Plot_Output/Pressure_History_' + str(lines[-1 * time_range][92:102]).replace("/", "_") + "__" + str(lines[-1 * time_range - 1][79:84]).replace(":", "_") + "__" + str(lines[-1][79:84]).replace(":", "_") + '.png') print_file.close()
def length_plots(array, name, path, title=None, n50=None, color="#4CB391", figformat="png"): """Create histogram of normal and log transformed read lengths.""" logging.info("NanoPlot: Creating length plots for {}.".format(name)) maxvalx = np.amax(array) if n50: logging.info( "NanoPlot: Using {} reads with read length N50 of {}bp and maximum of {}bp." .format(array.size, n50, maxvalx)) else: logging.info("NanoPlot: Using {} reads maximum of {}bp.".format( array.size, maxvalx)) plots = [] HistType = namedtuple('HistType', 'weight name ylabel') for h_type in [ HistType(None, "", "Number of reads"), HistType(array, "Weighted ", "Number of bases") ]: histogram = Plot(path=path + h_type.name.replace(" ", "_") + "Histogram" + name.replace(' ', '') + "." + figformat, title=h_type.name + "Histogram of read lengths") ax = sns.distplot(a=array, kde=False, hist=True, bins=max(round(int(maxvalx) / 500), 10), color=color, hist_kws=dict(weights=h_type.weight, edgecolor=color, linewidth=0.2, alpha=0.8)) if n50: plt.axvline(n50) plt.annotate('N50', xy=(n50, np.amax([h.get_height() for h in ax.patches])), size=8) ax.set(xlabel='Read length', ylabel=h_type.ylabel, title=title or histogram.title) plt.ticklabel_format(style='plain', axis='y') histogram.fig = ax.get_figure() histogram.save(format=figformat) plt.close("all") log_histogram = Plot( path=path + h_type.name.replace(" ", "_") + "LogTransformed_Histogram" + name.replace(' ', '') + "." + figformat, title=h_type.name + "Histogram of read lengths after log transformation") ax = sns.distplot(a=np.log10(array), kde=False, hist=True, color=color, hist_kws=dict(weights=h_type.weight, edgecolor=color, linewidth=0.2, alpha=0.8)) ticks = [10**i for i in range(10) if not 10**i > 10 * maxvalx] ax.set(xticks=np.log10(ticks), xticklabels=ticks, xlabel='Read length', ylabel=h_type.ylabel, title=title or log_histogram.title) if n50: plt.axvline(np.log10(n50)) plt.annotate('N50', xy=(np.log10(n50), np.amax([h.get_height() for h in ax.patches])), size=8) plt.ticklabel_format(style='plain', axis='y') log_histogram.fig = ax.get_figure() log_histogram.save(format=figformat) plt.close("all") plots.extend([histogram, log_histogram]) plots.append( dynamic_histogram(array=array, name=name, path=path, title=title, color=color)) plots.append( yield_by_minimal_length_plot(array=array, name=name, path=path, title=title, color=color, figformat=figformat)) return plots
beta = -3.0 * alpha * lo2**2 data = [ini_x + i*(res_x - ini_x)/100 for i in range(100)] data = [(x, alpha * (x - ini_x - lo2)**3 + beta * (x - ini_x - lo2) + (ini + res) / 2.0) for x in data] return zip(*data) def moose(fn, i, j): f = open(fn) data = [line.strip().split(",") for line in f.readlines()[2:-1]] data = [(d[i], d[j]) for d in data] f.close() return zip(*data) plt.figure() expect3 = expected(1.0, 0.5, 0.0, 1.0E-5) expect13 = expected(0.9, 0.5, -1.0E-5, 0.0) m3 = moose("gold/small_deform_hard3.csv", 2, 4) m13 = moose("gold/small_deform_hard13.csv", 2, 6) plt.plot(expect3[0], expect3[1], 'k-', linewidth = 3.0, label = 'expected, tensile') plt.plot(m3[0], m3[1], 'k^', label = 'MOOSE, tensile') plt.plot(expect13[0], expect13[1], 'r-', linewidth = 3.0, label = 'expected, compressive') plt.plot(m13[0], [-float(y) for y in m13[1]], 'ro', label = 'MOOSE, compressive') plt.legend(loc = 'upper right') plt.xlabel("internal parameter") plt.ylabel("Strength") plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0)) plt.title("Tensile and compressive strengths with softening") plt.savefig("figures/small_deform_hard_3_13.eps") sys.exit(0)
Fs = int(38400 * 30) N = int(1024000 * 5) #configure device sdr.sample_rate = Fs sdr.center_freq = Fc sdr.gain = 'auto' #read samples samples = sdr.read_samples(N) #clean up sdr sdr.close() del (sdr) #conver to numpy array x1 = np.array(samples).astype("complex64") # mix down with fc fc1 = np.exp(-1.0j * 2.0 * np.pi * F_offset / Fs * np.arange(len(x1))) x2 = x1 * fc1 plt.specgram(x2, NFFT=2048, Fs=Fs) plt.xlabel("Time (s)") plt.ylabel("Frequency (Hz)") plt.ylim(-Fs / 2, Fs / 2) plt.xlim(0, len(x2) / Fs) plt.ticklabel_format(style='plain', axis='y') plt.show()
def FitData(p_guess, func): """ ChiSquared_Fit_to_Data Uses scipy.optimize.curve_fit to fit data from a file. The y-component of the data has uncertainties that are specified along with the x- and y-values of the data. See http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html for more information. To fit your own data, you need to: (1) Export your Logger Pro data to a text file. (2) Ensure your data file has the correct format: (a) any header lines should be commented out (# symbol on the left-hand side) (b) columns should be in the following order: x, y, sigma_y (3) The path and name of the datafile in the numpy.loadtxt command below must match the path and name of your datafile. (4) Ensure the function used in the fit, func(x,*p), is the function you are trying to fit. As written, this script assumes you are trying to perform a linear fit to your data. (5) The initial parameter values must be specified (this is your initial best guess at the fit parameters). The initial guess for the parameters does matter - if they are too far away from the true values, the fit may converge on a local minimum, not the global minimum, or it may not converge at all. (6) Edit the x- and y-axis labels for the plot to match your data. """ data_file = files.upload() # will prompt you to upload your file print(data_file.keys()) filename = next(iter(data_file)) # print("My name is "+filename) x_label = "x (m)" y_label = "y (m)" # print(data_file) df = pd.read_csv(io.BytesIO(data_file[filename])) # print(df) # Uncomment to check to make sure your data came in appropriately. data_list = df.values.tolist() x_data = [] y_data = [] y_sigma = [] for line in data_list: if (not math.isnan(line[0])): x_data.append(float(line[0])) y_data.append(float(line[1])) y_sigma.append(float(line[2])) ## Load data # x_data, y_data, y_sigma = numpy.loadtxt(data_file, unpack=True) # Fit the function to the data try: p, cov = scipy.optimize.curve_fit(func, x_data, y_data, p0=p_guess, sigma=y_sigma, maxfev=100 * (len(x_data) + 1)) # maxfev is the maximum number of func evaluations tried; increase this value if the fit fails # Catch fitting errors except: p, cov = p_guess, None # Calculate residuals y_fit = [] y_residual = [] for i in range(len(x_data)): y = func(x_data[i], *p) y_fit.append(y) y_residual.append(y_data[i] - y) # Degrees of freedom (number of data points - number of fit parameters) dof = len(x_data) - len(p) # Output plots and fit results print("*** Results from Chi Squared Fit ***") print("Fit Function: ", func.__name__) print("\nNumber of Data Points = {:7g}".format(len(x_data))) print("Number of Parameters = {:7g}".format(len(p))) print("Degrees of Freedom = {:7g}".format(len(x_data) - len(p))) try: # Calculate Chi-squared chisq = 0 for i in range(len(x_data)): chisq += ((y_data[i] - func(x_data[i], *p)) / y_sigma[i])**2 # Convert Scipy cov matrix to standard covariance matrix. cov = cov * dof / chisq print("\nEstimated parameters +/- uncertainties (initial guess)") for i in range(len(p)): print(" p[{:d}] = {:10.5f} +/- {:10.5f} ({:10.5f})".format( i, p[i], cov[i, i]**0.5 * max(1, numpy.sqrt(chisq / dof)), p_guess[i])) cdf = scipy.special.chdtrc(dof, chisq) print("\nChi-Squared = {:10.5f}".format(chisq)) print("Chi-Squared/dof = {:10.5f}".format(chisq / dof)) print("CDF = {:10.5f}".format(100. * cdf)) if cdf < 0.05: print( "\nNOTE: This does not appear to be a great fit, so the parameter uncertainties may be underestimated." ) elif cdf > 0.95: print( "\nNOTE: This fit seems better than expected, so the data uncertainties may have been overestimated." ) except TypeError: print( "Bad Fit: Try a different initial guess for the fit parameters or try increasing maxfev." ) chisq = None print("\n") # Plot of data and fit fig = pyplot.figure(facecolor="0.98") fit = fig.add_subplot(211) # Plot data as red circles, and fitted function as (default) line x_func = numpy.linspace(min(x_data), max(x_data), 150) fit.plot(x_data, y_data, 'ro', numpy.sort(x_func), func(numpy.sort(x_func), *p)) # Add error bars on data as red crosses. fit.errorbar(x_data, y_data, yerr=y_sigma, fmt='r+') fit.set_xticklabels(()) fit.grid() pyplot.title("Chisq Fit to Data and Residuals") #pyplot.xlabel(x_label) pyplot.ylabel(y_label) #pyplot.show(); # second plot to show residuals residuals = fig.add_subplot(212) residuals.errorbar(x_data, y_residual, yerr=y_sigma, fmt='r+', label="Residuals") # make sure residual plot has same x axis as fit plot residuals.set_xlim(fit.get_xlim()) residuals.axhline(y=0) # draw horizontal line at 0 on vertical axis residuals.grid() # Label axes #pyplot.title("Residuals") pyplot.xlabel(x_label) pyplot.ylabel(y_label) pyplot.ticklabel_format(style='plain', useOffset=False, axis='x') # Display the plot pyplot.show()
def calc_Darwin_curve(delta_theta=np.linspace(-0.00015, 0.00015, 5000), crystal='Si', energy=8, h=1, k=1, l=1, rel_angle=1, debye_temp_factor=1, use_correction=True, save_txt=True, save_fig=True, filename_to_save='Darwin_curve'): ''' Calculates the Darwin curve. It does not considers absortion. Valid for s-polarization only. Parameters: - delta_theta: array containing values of (Theta - Theta_Bragg) in rad. [array] - crystal: crystal material. [str] - energy: energy in keV. [float] - h, k, l: Miller indexes. [int] - rel_angle: relative angle [float] - debye_temp_factor: Debye Temperature Factor. [float] - use_correction: if True, considers the corrected Bragg angle due to refraction. [boolean] - save_txt: if True, saves the Darwin Curve in a .txt file. [boolean] - save_fig: if True, saves a figure with the Darwin Curve in .png. [boolean] - filename_to_save: name to save the figure and the .txt file. [string] Returns: - delta_theta: Array containing values of (Theta - Theta_Bragg) in rad. [array] - R: Intensity reflectivity array. [array] - zeta_total: Total Darwin width (delta_lambda/lambda). [float] - zeta_FWHM: Darwin width FWHM (delta_lambda/lambda). [float] - w_total: Total Angular Darwin width (delta_Theta) in rad. [float] - w_FWHM: Angular Darwin width FWHM (delta_Theta) in rad. [float] - w0: Angular shift of the Rocking Curve in rad. [float] References: Elements of modern X-ray physics / Jens Als-Nielsen, Des McMorrow – 2nd ed. Cap. 6. ''' # Functions: def calc_g(d, r0, Vc, F): return abs((2 * d * d * r0 / (Vc)) * F) def calc_xc(zeta, g, g0): return np.pi * zeta / g - g0 / g def calc_zeta_total(d, r0, Vc, F): return (4 / np.pi) * (d) * (d) * (r0 * abs(F) / Vc) def Darwin_curve(xc): R = [] for x in xc: if (x >= 1): r = (x - np.sqrt(x * x - 1)) * (x - np.sqrt(x * x - 1)) if (x <= 1): r = 1 if (x <= -1): r = (x + np.sqrt(x * x - 1)) * (x + np.sqrt(x * x - 1)) R.append(r) return np.array(R) # Calculating Darwin curve: cryst = xraylib.Crystal_GetCrystal(crystal) bragg = xraylib.Bragg_angle(cryst, energy, h, k, l) zeta = delta_theta / np.tan(bragg) r0 = physical_constants['classical electron radius'][0] FH = xraylib.Crystal_F_H_StructureFactor(cryst, energy, h, k, l, debye_temp_factor, rel_angle) F0 = xraylib.Crystal_F_H_StructureFactor(cryst, energy, 0, 0, 0, debye_temp_factor, rel_angle) d = 1e-10 * xraylib.Crystal_dSpacing(cryst, h, k, l) V = 1e-30 * cryst['volume'] g = calc_g(d, r0, V, FH) g0 = calc_g(d, r0, V, F0) xc = calc_xc(zeta, g, g0) R = Darwin_curve(xc) zeta_total = calc_zeta_total(d, r0, V, FH) zeta_FWHM = (3 / (2 * np.sqrt(2))) * zeta_total w_total = zeta_total * np.tan(bragg) w_FWHM = (3 / (2 * np.sqrt(2))) * w_total w0 = (g0 / (np.pi)) * np.tan(bragg) # Correcting curve offset (due to refraction): if (use_correction): delta_theta = delta_theta - w0 # Saving .txt file: if (save_txt): filename = filename_to_save + '.txt' with open(filename, 'w') as f: f.write('#Delta_Theta[rad] Intensity_Reflectivity \n') for i in range(len(R)): f.write('%.6E\t%.6E \n' % (delta_theta[i], R[i])) # Plotting Graph: plt.figure() plt.plot(delta_theta, R, linewidth=1.8, color='black') plt.fill_between(delta_theta, R, alpha=0.9, color='C0') plt.ylabel('Intensity reflectivity', fontsize=13) plt.xlabel('$\Delta$' + '$\Theta$' + ' [rad]', fontsize=13) plt.xscale('linear') plt.yscale('linear') plt.minorticks_on() plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0)) plt.tick_params(which='both', axis='both', direction='in', right=True, top=True, labelsize=12) plt.grid(which='both', alpha=0.2) plt.tight_layout() textstr = '\n'.join((r'$\zeta_{total}=$%.4E' % (zeta_total, ), r'$\zeta_{FWHM}=$%.4E' % (zeta_FWHM, ), r'$\omega_{total}=$%.4E rad' % (w_total, ), r'$\omega_{FWHM}=$%.4E rad' % (w_FWHM, ))) props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) # wheat # gray plt.text(0.05, 0.95, textstr, transform=plt.gca().transAxes, fontsize=10, verticalalignment='top', bbox=props) plt.show() if (save_fig): plt.savefig(filename_to_save + '.png', dpi=600) return delta_theta, R, zeta_total, zeta_FWHM, w_total, w_FWHM, w0
def comparison_plot(results_dict, smoothing_window=20, noshow=False): fig = plt.figure(figsize=(16, 8)) ax = plt.subplot() for label in (ax.get_xticklabels() + ax.get_yticklabels()): label.set_fontname('Arial') label.set_fontsize(28) plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0)) ax.xaxis.get_offset_text().set_fontsize(20) axis_font = {'fontname': 'Arial', 'size': '32'} rewards_smoothed = [] rewards_max = [] rewards_min = [] cum_rwd = [] colors = [ '#e6194b', '#3cb44b', '#ffe119', '#0082c8', '#f58231', '#911eb4', '#46f0f0', '#f032e6', '#d2f53c', '#fabebe', '#008080', '#e6beff', '#aa6e28', '#fffac8', '#800000', '#aaffc3', '#808000', '#ffd8b1', '#000080', '#808080', '#FFFFFF', '#000000' ] #colors = ['#e41a1c','#377eb8','#4daf4a','#984ea3','#ff7f00','#ffff33','#a65628','#f781bf','#999999', '#000000', ] index = 0 for k, key in enumerate(results_dict.keys()): #for i, data in enumerate(results_dict[key]['all']): # rewards_smoothed.append(pd.Series(data).rolling(smoothing_window, min_periods=smoothing_window).mean()) # cum_rwd_i, = ax.plot(range(len(rewards_smoothed[index])), rewards_smoothed[index], color = colors[k%len(colors)], linewidth=2.5, linestyle='solid', label=str(i)+": $\lambda$ = " + str(key)) # cum_rwd.append(cum_rwd_i) # index += 1 rewards_smoothed.append( pd.Series(results_dict[key]['mean']).rolling( smoothing_window, min_periods=smoothing_window).mean()) cum_rwd_i, = ax.plot(range(len(rewards_smoothed[k])), rewards_smoothed[k], color=colors[k % len(colors)], linewidth=2.5, linestyle='solid', label="$\lambda$ = " + str(key)) cum_rwd.append(cum_rwd_i) plt.fill_between(range(len(rewards_smoothed[k])), rewards_smoothed[k] + results_dict[key]['std'], rewards_smoothed[k] - results_dict[key]['std'], alpha=0.2, edgecolor=colors[k % len(colors)], facecolor=colors[k % len(colors)]) #rewards_min.append(pd.Series(results_dict[key]['min']).rolling(smoothing_window, min_periods=smoothing_window).mean()) #cum_rwd_i, = ax.plot(range(len(rewards_min[k])), rewards_min[k], color = colors[k%len(colors)], linewidth=2.5, linestyle='solid', label="Min:$\lambda$ = " + str(key)) #cum_rwd.append(cum_rwd_i) #rewards_max.append(pd.Series(results_dict[key]['max']).rolling(smoothing_window, min_periods=smoothing_window).mean()) #cum_rwd_i, = ax.plot(range(len(rewards_max[k])), rewards_max[k], color = colors[k%len(colors)], linewidth=2.5, linestyle='solid', label="Max:$\lambda$ = " + str(key)) #cum_rwd.append(cum_rwd_i) #plt.fill_between(range(len(rewards_max[k])), rewards_max[k], rewards_min[k], alpha=0.2, edgecolor=colors[k%len(colors)], facecolor=colors[k%len(colors)]) # Shrink current axis by 20% box = ax.get_position() ax.set_position([box.x0, box.y0, box.width * 0.8, box.height]) # Put a legend to the right of the current axis #ax.legend(loc='center left', bbox_to_anchor=(1, 0.5)) ax.legend(handles=cum_rwd, loc='center left', bbox_to_anchor=(1, 0.5), prop={'size': 26}) plt.xlabel("Episodes (1e6 timesteps)", **axis_font) plt.ylabel("Average Returns", **axis_font) plt.title("DDPG with Walker Environment - Actor and Critic Regularization", **axis_font) # plt.show() plt.savefig('./results_analysis/ddpg_walker_best_comparisons.png') return fig
def create_scatter(filename, result, x, y, a, stddev, i, units): xx = linspace( x.min(), x.max(), 50 ) #so this returns 50 evenly spaced values between the start and stop points yy = emfret( result.params, xx, a) #it uses each of these to calculate emfretmax (one per xx value) z = linspace(x.min(), x.max(), 50) #this plots all the values contained in Y points = ['b.', 'r.', 'g.', 'c.', 'm.'] #colors are: Blue, Red, Green, Cyan, Magenta. #Do not use yellow, too hard to see against white background stddev_points = ['b_', 'r_', 'g_', 'c_', 'm_'] #will plot colored horizontal lines for std dev line_style = ['b-', 'r-', 'g-', 'c-', 'm-' ] #uses dashes, but generally connects into a straight line #tracks the number of colors used in the lists above. Rotate through this list as necessary num_colors = len(points) #note that markersize is completely arbitrary #this plots the points of the given data, the calculated line is done below plot(x, y, points[i % num_colors], markersize=15) #plot the std dev ( point +/- std dev) #again, markersize/width are arbitrary. Markeredgewith increases the size of the dashes used by expanding the border. #the border is the same color as the interior of the marker, so it appears only the dashes got thicker plot(x, y - stddev, stddev_points[i % num_colors], markersize=7, markeredgewidth=3) plot(x, y + stddev, stddev_points[i % num_colors], markersize=7, markeredgewidth=3) plot([x, x], [y - stddev, y + stddev], line_style[i % num_colors], linewidth=1) #this plots a vertical line between stddev values unit_label = 'p' if (units == 'u'): #add micro symbol unit_label = u"\u00B5" unit_label = unit_label + 'M' elif (units == 'n'): #add nano symbol unit_label = 'nM' elif (units == 'p'): #pico unit_label = 'pM' #this plots the calcualted EMfret (xx,yy), and a black horizontal line through the origin (xx, z) for orientation of the axis line = plot(xx, yy, line_style[i % num_colors], linewidth=3, label='Donor [{}] = {}'.format(unit_label, str(a))) plot(xx, z, 'k-') gca().yaxis.set_major_formatter(ScalarFormatter(useMathText=True)) ticklabel_format(axis='y', style='sci', scilimits=( 0, 0)) #this forces labels on the y axis into scientific format # appropriately labels the x and y axis, fontsize is arbitary xlabel('Concentration of Acceptor [' + unit_label + ']') ylabel("Em$_{FRET}$ (RFU)", fontsize=14) legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) savefig(filename, bbox_inches='tight', dpi=200)
ax1.boxplot(recon_loss_plot,showfliers=show_outliers) ax1.set_xticklabels( x_tick_labels_eff) ax1.set_ylabel("Reconstruction loss") ax1.set_xlabel("Condition (%)") ax2.boxplot(epi_unc_plot,showfliers=show_outliers) ax2.set_xticklabels(x_tick_labels_eff) ax2.set_ylabel("Epistemic uncertainty") ax2.set_xlabel("Condition (%)") ax3.boxplot(alea_unc_plot,showfliers=show_outliers) ax3.set_xticklabels(x_tick_labels_eff) ax3.set_ylabel("Aleatoric uncertainty") ax3.set_xlabel("Condition (%)") plt.ticklabel_format(axis="y", style="sci", scilimits=(0,0)) plt.show() plt.tight_layout() #plot noise level np_unc_result_noise = np.array(unc_result_noise) np_unc_result_drift = np.array(unc_result_drift) #Plot single row for drifts #set plot sensor id here to show the sensitivity of metrics toward injected drifts figsize = (6,3) dpi = 250 fig, axes = plt.subplots(1,3,figsize=figsize,dpi=dpi) sensor_id = 10 # x_tick_labels_eff = ('0', '1', '2', '3', '4', '5')
def getPhiFit(keep_bins, realbins, phi_vals, phi_title, plot_dir, saveplot=False, sci_on=True, kopt=False): plt.rcParams["font.family"] = "Times New Roman" plt.rcParams["font.size"] = "20" xmin = 0 xmax = 360 #print("fitting {}".format(phi_title)) #data = phi_vals bins_x = np.linspace(xmin, xmax, 21) #data_entries, bins = np.histogram(data,bins=bins_x) ic(phi_vals) data_entries = phi_vals ic(data_entries) bins = bins_x data_errors = np.sqrt(data_entries) data_errors = [1 / err if err > 0 else err + 1 for err in data_errors] ic(data_entries) ic(data_errors) if 1 == 1: bins = realbins ic(bins) #binscenters = np.array([0.5 * (bins[i] + bins[i+1]) for i in range(len(bins)-1)]) binscenters = bins ic(binscenters) ic(data_entries) ic("TRYING TO RUN") acc_cut = 0.005 ind_to_drop = np.where(keep_bins > (1 / acc_cut)) ic("TRYING TO RUN2") ic(ind_to_drop) binscenters = np.delete(binscenters, ind_to_drop) data_entries = np.delete(data_entries, ind_to_drop) data_errors = np.delete(data_errors, ind_to_drop) ic(binscenters) ic(data_entries) ic(keep_bins) # 5.) Fit the function to the histogram data. popt, pcov = curve_fit(fit_function, xdata=binscenters, ydata=data_entries, p0=[2.0, 2, 0.3], sigma=data_errors, absolute_sigma=True) #print(popt) #popt contains the values for A, B, C a_err = np.sqrt(pcov[0][0]) b_err = np.sqrt(pcov[1][1]) c_err = np.sqrt(pcov[2][2]) a, b, c = popt[0], popt[1], popt[2] #ic(a_err,b_err,c_err) #ic.disable() # 6.) # Generate enough x values to make the curves look smooth. fit_y_data_1 = fit_function(binscenters, *popt) # chisq0 = stats.chisquare(f_obs=data_entries, f_exp=fit_y_data_1) # chisq = stats.chisquare(f_obs=np.array(data_entries, dtype=np.float64), f_exp=np.array(fit_y_data_1, dtype=np.float64)) # sums=[] # for ind,val in enumerate(fit_y_data_1): # diff2 = (data_entries[ind]-val)**2 # s1 = diff2/val # sums.append(s1) # manchisq = np.sum(sums) # ###ic.enable() # if chisq0[0]<0: # ic(manchisq) # ic(chisq0[0]) # if not (chisq0[0] == chisq[0]): # print("ERROR MISMATCH") # print(chisq0[0]) # print(chisq[0]) # print(manchisq) # ic.disable() # p = chisq[1] # chisq = chisq[0] # ic(chisq) # ic(p) xspace = np.linspace(binscenters.min() - 9, binscenters.max() + 9, 1000) fit_y_data = fit_function(xspace, *popt) if kopt: fit_y_data2 = fit_function(xspace, *kopt) ###ic.enable() # y_manual = [] # for ind, val in enumerate(xspace): # ic(val,a,b,c) # y_one = fit_function(val,a,b,c) # ic(y_one) # y_manual.append(y_one) #7 # Plot the histogram and the fitted function. fig, ax = plt.subplots(figsize=(12, 7)) ic(data_entries) ic(binscenters) bar1 = ax.bar(binscenters, data_entries, width=18, color='navy', label='CLAS12') fit1, = ax.plot(xspace, fit_y_data, color='darkorange', linewidth=2.5, label='CLAS12 Fit') if kopt: fit2, = ax.plot(xspace, fit_y_data2, color='black', linewidth=2.5, label='CLAS6 Fit') # Make the plot nicer. plt.xlim(xmin, xmax) #plt.ylim(0,300) plt.xlabel(r'phi') plt.ylabel('Corrected $N_{events}$/Lumi/Bin Vol') plot_title = plot_dir + phi_title + ".png" plt.title(phi_title + ", acc cutoff = {}".format(acc_cut)) #plt.legend(loc='best') chisq = 1 p = 1 fit_params = "A: {:2.6f} \n B:{:2.6f} \n C:{:2.6f}".format(a, b, c) extra = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0) #ax.legend([bar1, fit1, fit2, extra], ("Data","CLAS 12 A+Bcos(2Phi)+Ccos(Phi)",'CLAS6 fit',fit_params)) ax.legend([bar1, fit1, fit2], ("Data", "CLAS 12 fit", 'CLAS6 fit data')) if sci_on: plt.ticklabel_format(axis="y", style="sci", scilimits=(0, 0)) #plt.text(120, max(data_entries)/1.3, fit_params) if saveplot: new_plot_title = plot_title.replace("/", "").replace( " ", "_").replace("$", "").replace("^", "").replace("\\", "").replace( ".", "").replace("<", "").replace(">", "").replace(",", "_") plt.savefig(plot_dir + new_plot_title + ".png") plt.close() else: plt.show() plt.close() #print("plot saved to {}".format(plot_title)) return popt, pcov, chisq, p
def calc_Darwin_width_vs_E(crystal='Si', energy_array=np.linspace(2.8, 30, 1361), h=1, k=1, l=1, rel_angle=1, debye_temp_factor=1, save_txt=True, save_fig=True, filename_to_save_dw='Darwin_width', filename_to_save_resol='Intrinsic_resolution'): ''' Calculates the Darwin width and the intrinsic resolution for p and s polarizations as function of energy. It uses xraylib. Parameters: - crystal: crystal material. [str] - energy: energy in keV. [float] - h, k, l: Miller indexes. [int] - rel_angle: relative angle [float] - debye_temp_factor: Debye Temperature Factor. [float] - save_txt: if True, saves two .txt files with the Darwin width and the intrinsic resolution as function of energy. [boolean] - save_fig: if True, saves two figures with the Darwin width and the intrinsic resolution as function of energy. [boolean] - filename_to_save_dw: name to save the figure and the .txt file with the Darwin width as function of energy. [string] - filename_to_save_resol: name to save the figure and the .txt file with the intrinsic resolution as function of energy. [string] Returns: - darwin_width_s: Angular Darwin width for s polarization in rad as function of energy. [float] - darwin_width_p: Angular Darwin width for p polarization in rad as function of energy. [float] - resolution_s: Intrinsic resolution for s polarization as function of energy. [float] - resolution_p: Intrinsic resolution for p polarization as function of energy. [float] References: A simple formula to calculate the x-ray flux after a double-crystal monochromator - M. S. del Rio; O. MATHON. ''' # Calculating: resolution_s = [] darwin_width_s = [] resolution_p = [] darwin_width_p = [] for energy in energy_array: dw_s, dw_p, resol_s, resol_p = calc_Darwin_width(crystal, energy, h, k, l, rel_angle=1, debye_temp_factor=1) darwin_width_p.append(dw_p) resolution_p.append(resol_p) darwin_width_s.append(dw_s) resolution_s.append(resol_s) resolution_p = np.array(resolution_p) darwin_width_p = np.array(darwin_width_p) resolution_s = np.array(resolution_s) darwin_width_s = np.array(darwin_width_s) # Darwin Width: plt.figure() plt.plot(energy_array, 1.0E6 * darwin_width_s, label='s - pol', linewidth=2, markersize=9) plt.plot(energy_array, 1.0E6 * darwin_width_p, label='p - pol', linewidth=2, markersize=9) plt.ylabel('Darwin Width [$\mu$rad]', fontsize=15) plt.xlabel('Energy [keV]', fontsize=15) plt.xscale('linear') plt.yscale('linear') plt.xlim(energy_array[0], energy_array[-1]) plt.minorticks_on() plt.tick_params(which='both', axis='both', direction='in', right=True, top=True, labelsize=15) plt.grid(which='both', alpha=0.2) plt.legend(fontsize=12) plt.tight_layout() if (save_fig): plt.savefig(filename_to_save_dw + '.png', dpi=600) # Resolution: plt.figure() plt.plot(energy_array, resolution_s, label='s - pol', linewidth=2, markersize=9) plt.plot(energy_array, resolution_p, label='p - pol', linewidth=2, markersize=9) plt.ylabel('Resolution [$\Delta\Theta/tan(\Theta)$]', fontsize=15) # [$\dfrac{\Delta\Theta}{tan(\Theta)}$] plt.xlabel('Energy [keV]', fontsize=15) plt.xscale('linear') plt.yscale('linear') plt.xlim(energy_array[0], energy_array[-1]) plt.minorticks_on() plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0)) plt.tick_params(which='both', axis='both', direction='in', right=True, top=True, labelsize=15) plt.grid(which='both', alpha=0.2) plt.legend(fontsize=12, loc='best') plt.tight_layout() if (save_fig): plt.savefig(filename_to_save_resol + '.png', dpi=600) if (save_txt): # Writing .txt file: filename = filename_to_save_dw + '.txt' with open(filename, 'w') as f: f.write( '#Energy[keV]\tDarwin_Width_s[urad]\tDarwin_Width_p[urad] \n') for i in range(len(energy_array)): f.write('%.2f\t%.6E\t%.6E \n' % (energy_array[i], 1.0E6 * darwin_width_s[i], 1.0E6 * darwin_width_p[i])) # Writing .txt file: filename = filename_to_save_resol + '.txt' with open(filename, 'w') as f: f.write('#Energy[keV]\tResolution_s\tResolution_p \n') for i in range(len(energy_array)): f.write('%.2f\t%.6E\t%.6E \n' % (energy_array[i], resolution_s[i], resolution_p[i])) return darwin_width_s, darwin_width_p, resolution_s, resolution_p
'weight': 'bold', 'size': 15, } mycolor = np.array([[224, 32, 32], [255, 192, 0], [32, 160, 64], [48, 96, 192], [192, 48, 192]]) / 255.0 mymarker = ['1', '2', 's', '*', 'H', 'D', 'o', '>'] my_line_width = 3 my_marker_size = 10 # plot train G/D curve plt.figure(1) plt.style.use('ggplot') plt.gca().yaxis.set_major_formatter(ticker.FormatStrFormatter('%.2f')) plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0), useMathText=True) x_axix = range(len(LFI)) plt.plot(x_axix, LFI, color=mycolor[0], label='NANG', marker=mymarker[0], linewidth=my_line_width, markersize=my_marker_size) plt.plot(x_axix, criterion, color=mycolor[4], label='NeighAggre', linestyle='--', linewidth=my_line_width,
#Use below parameter in pandas to ignore columns #usecols=["date", "loc", "x"] #Accepts InputFile for processing inputFile = pd.read_csv(sys.argv[1], engine='python', header=None) for i in range(0, len(inputFile.columns)): plotMap.append(inputFile[i].dropna().tolist()) xheaderTicks.append(i + 1) #Prints Summary of InputFile print("\nInput File Summary: \n") print(inputFile.describe()) #Creates Figure Instance plt.ticklabel_format(useOffset=False) plt.ticklabel_format(style='plain') plt.grid(which='minor', alpha=0.5) plt.grid(which='major', alpha=0.5) fig = plt.figure(1, figsize=(9, 6)) #Create an Axes Instance ax = fig.add_subplot(111) # Create the boxplot bp = ax.violinplot(plotMap, showmedians=False, showmeans=False, showextrema=True) #bp['cmeans'].set_color('b') #bp['cmedians'].set_color('g')
def plot_events(fig, data_event, reward_value=False, clip=0.01): for i in range(len(data_event)): event = True if "_event" in data_event[i][0] else False x = [] movement = [] health = [] armor = [] shoot = [] ammo = [] weapon0 = [] weapon1 = [] weapon2 = [] weapon3 = [] weapon4 = [] weapon5 = [] weapon6 = [] weapon7 = [] weapon8 = [] weapon9 = [] weapon0kill = [] weapon1kill = [] weapon2kill = [] weapon3kill = [] weapon4kill = [] weapon5kill = [] weapon6kill = [] weapon7kill = [] weapon8kill = [] weapon9kill = [] kill = [] if reward_value: for d in data_event[i][1]: x.append(d[0]) movement.append(1 / max(clip, d[1])) health.append(1 / max(clip, d[2])) armor.append(1 / max(clip, d[3])) shoot.append(1 / max(clip, d[4])) ammo.append(1 / max(clip, d[5])) weapon0.append(1 / max(clip, d[6])) weapon1.append(1 / max(clip, d[7])) weapon2.append(1 / max(clip, d[8])) weapon3.append(1 / max(clip, d[9])) weapon4.append(1 / max(clip, d[10])) weapon5.append(1 / max(clip, d[11])) weapon6.append(1 / max(clip, d[12])) weapon7.append(1 / max(clip, d[13])) weapon8.append(1 / max(clip, d[14])) weapon9.append(1 / max(clip, d[15])) if len(d) > 17: weapon0kill.append(1 / max(clip, d[17])) weapon1kill.append(1 / max(clip, d[18])) weapon2kill.append(1 / max(clip, d[19])) weapon3kill.append(1 / max(clip, d[20])) weapon4kill.append(1 / max(clip, d[21])) weapon5kill.append(1 / max(clip, d[22])) weapon6kill.append(1 / max(clip, d[23])) weapon7kill.append(1 / max(clip, d[24])) weapon8kill.append(1 / max(clip, d[25])) weapon9kill.append(1 / max(clip, d[26])) kill.append(1 / max(clip, d[16])) else: for d in data_event[i][1]: x.append(d[0]) movement.append(d[1]) health.append(d[2]) armor.append(d[3]) shoot.append(d[4]) ammo.append(d[5]) weapon0.append(d[6]) weapon1.append(d[7]) weapon2.append(d[8]) weapon3.append(d[9]) weapon4.append(d[10]) weapon5.append(d[11]) weapon6.append(d[12]) weapon7.append(d[13]) weapon8.append(d[14]) weapon9.append(d[15]) if len(d) > 17: weapon0kill.append(d[17]) weapon1kill.append(d[18]) weapon2kill.append(d[19]) weapon3kill.append(d[20]) weapon4kill.append(d[21]) weapon5kill.append(d[22]) weapon6kill.append(d[23]) weapon7kill.append(d[24]) weapon8kill.append(d[25]) weapon9kill.append(d[26]) kill.append(d[16]) if event: title = data_event[i][0].split("vizdoom_")[1].split("_event")[0] else: title = data_event[i][0].split("vizdoom_")[1] title = title.replace("-2", "") x_max = np.max(x) if title == "health_gathering": idx = 1 y_max = 100 elif title == "health_gathering_supreme": idx = 2 y_max = 60 elif title == "deadly_corridor": idx = 3 y_max = 40 elif title == "my_way_home": idx = 4 y_max = 25 elif title == "deathmatch": idx = 5 if not single: y_max = 400 x_max = 75000000 else: continue if event: idx += 5 if single and single_title != title: continue if not single: ax = plt.subplot(2, 5, idx) if idx > 5: plt.xlabel('Time step') if idx % 5 == 1: if event: plt.ylabel(r"A2C+RoE" + "\n" + "Events / Episode", fontsize=fontsize) else: plt.ylabel(r"A2C" + "\n" + "Events / Episode", fontsize=fontsize) if title == "deathmatch": plt.xticks(np.arange(0, x_max + 1, 25000000)) else: plt.xticks(np.arange(0, x_max + x_max * 0.1, 2000000)) else: ax1 = plt.subplot(1, 1, 1) plt.xlim(0, x_max) plt.title("Common Events", fontsize=fontsize) ax2 = plt.subplot(2, 1, 1) plt.xlim(0, x_max) plt.title("Weapon Pickup Events", fontsize=fontsize) ax3 = plt.subplot(2, 1, 2) plt.xlim(0, x_max) plt.title("Kills", fontsize=fontsize) if single: ax = ax1 l0 = ax.plot(x, kill, label='Kills', linewidth=1) l0 = ax.plot(x, movement, label='Moves', linewidth=1) l1 = ax.plot(x, health, label='Medkit pickups', linewidth=1, color="green") l2 = ax.plot(x, armor, label='Armor pickups', linewidth=1, color="purple") l3 = ax.plot(x, shoot, label='Shots', linewidth=1, color="orange") #l4 = ax.plot(x, ammo, label='Ammo') if single: ax = ax2 l5 = ax.plot(x, weapon0, label='W. 0 pickup') l6 = ax.plot(x, weapon1, label='W. 1 pickup') l7 = ax.plot(x, weapon2, label='W. 2 pickup') l8 = ax.plot(x, weapon3, label='W. 3 pickup') l9 = ax.plot(x, weapon4, label='W. 4 pickup') l10 = ax.plot(x, weapon5, label='W. 5 pickup') l11 = ax.plot(x, weapon6, label='W. 6 pickup') l12 = ax.plot(x, weapon7, label='W. 7 pickup') l13 = ax.plot(x, weapon8, label='W. 8 pickup') l14 = ax.plot(x, weapon9, label='W. 9 pickup') if single: ax = ax3 if len(d) > 16 and single: l15 = ax.plot(x, weapon0kill, label='W. 0 kill') l16 = ax.plot(x, weapon1kill, label='W. 1 kill') l17 = ax.plot(x, weapon2kill, label='W. 2 kill') l18 = ax.plot(x, weapon3kill, label='W. 3 kill') l19 = ax.plot(x, weapon4kill, label='W. 4 kill') l20 = ax.plot(x, weapon5kill, label='W. 5 kill') l21 = ax.plot(x, weapon6kill, label='W. 6 kill') l22 = ax.plot(x, weapon7kill, label='W. 7 kill') l23 = ax.plot(x, weapon8kill, label='W. 8 kill') l24 = ax.plot(x, weapon9kill, label='W. 9 kill') if not single: plt.title(prettify(title), fontsize=fontsize) if title == "deadly_corridor" or single: if event: handles, labels = ax.get_legend_handles_labels() fig.legend(handles, labels, loc='upper center', ncol=5, fontsize=fontsize) plt.xlim(0, x_max) if not single: plt.ylim(0, y_max) plt.ticklabel_format(axis='x', style='sci', scilimits=(0, 4)) if reward_value: plt.savefig('event_rewards.pdf') else: if single: plt.savefig('events_single.pdf') else: plt.savefig('events.pdf')
def plotPhi_duo(phi_bins, bin_counts_0, bin_counts_1, phi_title, pics_dir, saveplot=False, legend=False, duo=False, fitting=False, sci_on=False): ic(phi_bins) plt.rcParams["font.family"] = "Times New Roman" plt.rcParams["font.size"] = "20" data_entries_0 = bin_counts_0 data_entries_1 = bin_counts_1 bins = phi_bins data_errors_0 = np.sqrt(data_entries_0) data_errors_0 = [1 / err if err > 0 else err + 1 for err in data_errors_0] data_errors_1 = np.sqrt(data_entries_1) data_errors_1 = [1 / err if err > 0 else err + 1 for err in data_errors_1] #print(data_entries) if 1 == 1: ic(bins) #binscenters = np.array([0.5 * (bins[i] + bins[i+1]) for i in range(len(bins)-1)]) binscenters = bins #binscenters = np.append(binscenters,np.array([351,]),axis=0) ic(binscenters) # 5.) Fit the function to the histogram data. #popt, pcov = curve_fit(fit_function, xdata=binscenters, ydata=data_entries, p0=[2.0, 2, 0.3], # sigma=data_errors, absolute_sigma=True) #print(popt) #popt contains the values for A, B, C ##a_err = np.sqrt(pcov[0][0]) ##b_err = np.sqrt(pcov[1][1]) #c_err = np.sqrt(pcov[2][2]) #a,b,c = popt[0],popt[1],popt[2] #ic(a_err,b_err,c_err) #ic.disable() # 6.) # Generate enough x values to make the curves look smooth. #fit_y_data_1 = fit_function(binscenters, *popt) #ic(fit_y_data_1) #chisq0 = stats.chisquare(f_obs=data_entries, f_exp=fit_y_data_1) #chisq = stats.chisquare(f_obs=np.array(data_entries, dtype=np.float64), f_exp=np.array(fit_y_data_1, dtype=np.float64)) #sums=[] #for ind,val in enumerate(fit_y_data_1): # diff2 = (data_entries[ind]-val)**2 # s1 = diff2/val # sums.append(s1) # manchisq = np.sum(sums) ###ic.enable() #if chisq0[0]<0: # ic(manchisq) # ic(chisq0[0]) #if not (chisq0[0] == chisq[0]): # print("ERROR MISMATCH") # print(chisq0[0]) # print(chisq[0]) # print(manchisq) # p = chisq[1] # chisq = chisq[0] ##ic(chisq) #ic(p) #xspace = np.linspace(0, xmax, 1000) #fit_y_data = fit_function(xspace, *popt) ##ic.enable() #ic(fit_y_data) #y_manual = [] #for ind, val in enumerate(xspace): # ic(val,a,b,c) # y_one = fit_function(val,a,b,c) # ic(y_one) # y_manual.append(y_one) #7 # Plot the histogram and the fitted function. fig, ax = plt.subplots(figsize=(12, 7)) highPower = data_entries_0 lowPower = data_entries_1 #plt.bar(binscenters, highPower, # color='b', label='LUND Events') #plt.bar(binscenters, lowPower, color='r', alpha=0.5, label='Sim Events') #ic.enable() #ic(binscenters) #ic(data_entries_0) #ic(data_entries_1) ic(binscenters) ic(bins) ic(data_entries_1) bar0 = ax.bar(binscenters, data_entries_1, width=18) #bar0 = ax.bar(binscenters, data_entries_1, width=bins[1] - bins[0], color='red', label='Raw') if duo: bar1 = ax.bar(binscenters, data_entries_0, width=bins[1] - bins[0], color='black', label='Corrected') # fit1, = ax.plot(xspace, fit_y_data, color='darkorange', linewidth=2.5, label='Fitted function') # Make the plot nicer. plt.xlim(0, 360) #plt.ylim(0,5) plt.xlabel(r'phi') plt.ylabel(r'Number of entries') plot_title = phi_title plt.title(phi_title) #plt.legend(loc='best') if legend: plt.legend() if sci_on: plt.ticklabel_format(axis="y", style="sci", scilimits=(0, 0)) #fit_params = "A: {:2.2f} +/- {:2.2f}\n B:{:2.2f} +/- {:2.2f}\n C:{:2.2f} +/- {:2.2f}\n Chi:{:2.2f} \n p:{:2.2f}".format(a,a_err,b,b_err,c,c_err,chisq,p) #plt.text(120, max(data_entries)/1.3, fit_params) if saveplot: new_plot_title = plot_title.replace("/", "").replace( " ", "_").replace("$", "").replace("^", "").replace("\\", "").replace( ".", "").replace("<", "").replace(">", "").replace(",", "_") plt.savefig(pics_dir + new_plot_title + ".png") plt.close() else: plt.show() plt.close()
nv.append(num_vertices) nc.append(num_cells) plt.subplot(1, 2, 1) h = plt.plot(nc, t, colors1[i], label=labels[i]) plt.subplot(1, 2, 2) plt.plot(nc, q, colors1[i]) plt.plot(nc, mq, colors2[i]) entries.append(h) plt.subplot(1, 2, 1) plt.title("# of cells vs. mesh generation time [s]") plt.legend() plt.xlabel("# of cells") plt.ticklabel_format(style="sci", axis="x", scilimits=(0, 0)) axes = plt.gca() axes.yaxis.grid() axes.set_frame_on(False) plt.subplot(1, 2, 2) plt.title("# of cells. vs cell quality") plt.xlabel("# of cells") plt.ticklabel_format(style="sci", axis="x", scilimits=(0, 0)) plt.ylim(ymax=1.1, ymin=0) axes = plt.gca() axes.yaxis.grid() axes.set_frame_on(False) plt.tight_layout(pad=3.0) plt.savefig("out.svg", transparent=True, bbox_inches="tight", pad_inches=0)
def plot_rewards(fig, data): for i in range(len(data)): x = [] y = [] yi = [] event = False title = data[i][0].split("vizdoom_")[1] title = title.replace("-2", "") if "_event" in title: event = True title = title.split("_event")[0] print(title) scale = 1 if event and title in ["my_way_home"]: scale = 100 # Scaling was fixed, so not needed in new experiments #if event and title in ["deadly_corridor"]: #scale = 0.1 for d in data[i][1]: x.append(d[1]) y.append(d[2] * 100 * scale) yi.append(d[4] * 100 * scale) # ignore first data point x = x[1:] y = y[1:] yi = yi[1:] # smoothen smooth = 25 x_max = np.max(x) if len(x) == 0: continue y_limits_set = False show_noise = True if title == "health_gathering": idx = 1 y_max = 2500 y_min = 0 y_limits_set = True elif title == "health_gathering_supreme": idx = 2 y_max = 1200 y_min = 0 y_limits_set = True elif title == "deadly_corridor": idx = 3 y_max = 70 y_min = -1 y_limits_set = True elif title == "my_way_home": idx = 4 y_max = 100 y_min = -15 y_limits_set = True elif title == "deathmatch": idx = 5 x_max = 75000000 y_max = 5000 y_min = 0 y_limits_set = True else: continue if single and single_title != title: continue xs = [] ys = [] yis = [] for i in np.arange(0, len(x)): mean_x = [] mean_y = [] mean_yi = [] if i == 0 or smooth == 1: mean_x.append(x[i]) mean_y.append(y[i]) mean_yi.append(yi[i]) for j in np.arange(max(0, i - round(smooth / 2)), min(i + round(smooth / 2), len(x))): mean_x.append(x[j]) mean_y.append(y[j]) mean_yi.append(yi[j]) xs.append(np.mean(mean_x)) ys.append(np.mean(mean_y)) yis.append(np.mean(mean_yi)) if not single: ax = plt.subplot(1, 5, idx) if idx > 5: plt.xlabel('Time step') if idx % 5 == 1: plt.ylabel('Reward / Episode', fontsize=fontsize) if title == "deathmatch": plt.xticks(np.arange(0, x_max + 1, 25000000)) else: plt.xticks(np.arange(0, x_max + x_max * 0.1, 2000000)) else: ax = plt.subplot(1, 1, 1) if event: if not y_limits_set: y_min = min(0, np.min(ys) - np.min(ys) * 0.1) y_max = np.max(ys) + np.max(ys) * 0.1 plt.xlim(0, x_max) plt.ylim(y_min, y_max) color = '#1f77b4' if event: color = '#d62728' plt.ticklabel_format(axis='x', style='sci', scilimits=(0, 4)) label = "A2C" if not event else "A2C+RoE" l = ax.plot(xs, ys, color=color, linewidth=1.0, label=label) if show_noise: ax.plot(x, y, linewidth=1, alpha=0.1, color=color) plt.title(prettify(title), fontsize=fontsize) if title == "deadly_corridor" or single: if event: handles, labels = ax.get_legend_handles_labels() fig.legend(handles, labels, loc='upper center', ncol=2, fontsize=fontsize) if single: plt.savefig('rewards_single.pdf') else: plt.savefig('rewards.pdf')