def set_xspec(obsid, model = None, rmffile='/Users/corcoran/Dropbox/nicer_cal/nicer_v0.06.rmf', arffile='/Users/corcoran/Dropbox/nicer_cal/ni_xrcall_onaxis_v0.06.arf', workdir='/Users/corcoran/research/WR140/NICER/work/', ignore='0.0-0.45, 5.-**', showplot=False, showmodel=False ): """ sets the pha and model instances for a given obsid :param obsid: NICER observation id (integer) :param rmffile: NICER response file :param arffile: NICER effective area file :param workdir: NICER dataset working directory :param ignore: energy range in keV to ignore when fitting :param showplot: if True plot the model and spectrum vs. energy :param showmodel: if True print the model parameters :return: """ import xspec import matplotlib as plt obs = str(obsid) xspec.AllData.clear() xspec.AllModels.clear() xspecdir = os.path.join(workdir, obs) phaname = os.path.join(xspecdir, 'ni{obs}_0mpu7_cl.pha'.format(obs=obsid)) print "phaname = {phaname}".format(phaname=phaname) try: pha = xspec.Spectrum(phaname) except: print "Can't find {phaname}; returning".format(phaname=phaname) return 0, 0 pha.response = rmffile pha.response.arf = arffile pha.ignore(ignore) # # Define a model # if not model: model = set_model() if showmodel: with sys_pipes(): model.show() if showplot: xspec.Plot.setRebin(minSig=3, maxBins=30) xspec.Plot.device = "/null" xspec.Plot.xAxis = "keV" xspec.Plot.yLog = "True" xspec.Plot("data") plt.figure(figsize=[10, 6]) plt.yscale('log') plt.xscale('log') plt.xlabel('Energy (keV)', fontsize=16) plt.step(xspec.Plot.x(), xspec.Plot.y()) plt.step(xspec.Plot.x(), xspec.Plot.model()) return pha, model
def animate_plotting(subdir_path,): average_filename = 'averaged_out.txt' if os.path.exists( os.path.join(subdir_path,average_filename) ): print(subdir_path+average_filename+' already exists please use hotPlot.py') #import existing data for average at the end # data_out = numpy.genfromtxt(os.path.join(subdir_path,average_filename)) # averaged_data = numpy.array(data_out[:,1]) # angles = data_out[:,0] #os.remove( os.path.join(subdir_path,average_filename)) else: files = os.listdir(subdir_path) #files = [d for d in os.listdir(subdir_path) if os.path.isdir(os.path.join(subdir_path, d))] onlyfiles_path = [os.path.join(subdir_path,f) for f in files if os.path.isfile(os.path.join(subdir_path,f))] onlyfiles_path = natsort.natsorted(onlyfiles_path) averaged_data = [] angles = [] for f in onlyfiles_path: data = numpy.genfromtxt(f,delimiter = ',') #data = pandas.read_csv(f) averaged_data.append(numpy.mean(data)) angle = os.path.basename(f).split('_')[0] angles.append(float(angle)) fig = plt.plot(angles, averaged_data,'o') plt.yscale('log') plt.xscale('log') plt.legend(loc='upper right') plt.title(base_path) plt.grid(True) plt.xlabel(r'$\theta$ $[deg.]}$') #plt.xlabel(r'$\mathrm{xlabel\;with\;\LaTeX\;font}$') plt.ylabel(r'I($\theta$) $[a.u.]$')
def __save(self,n,plot,sfile): p.figure(figsize=sfile) p.xlabel(plot.xlabel) p.ylabel(plot.ylabel) p.xscale(plot.xscale) p.yscale(plot.yscale) p.grid() for curve in plot.curves: if curve[1] == None: p.plot(curve[0],curve[2], label=curve[3]) else: p.plot(curve[0], curve[1], curve[2], label=curve[3]) p.rc('legend', fontsize='small') p.legend(shadow=0, loc='best') p.axes().set_aspect(plot.aspect) if not plot.dir: plot.dir = './plots/' if not plot.name: plot.name = self.__global_name+'_%0*i'%(2,n) if not os.path.isdir(plot.dir): os.mkdir(plot.dir) if plot.pgf: p.savefig(plot.dir+plot.name+'.pgf') else: p.savefig(plot.dir+plot.name+'.pdf', bbox_inches='tight') p.close()
def fit_spectrum(obsid, pha, model, writexcm=True, workdir='/Users/corcoran/research/WR140/NICER/work/', statMethod='cstat' ): import xspec from wurlitzer import sys_pipes import pylab as plt from heasarc.utils import xspec_utils as xu if type(pha) != int: # # do fit # xspec.Fit.statMethod = statMethod xspec.Fit.perform() print("Best Fit Model is\n") with sys_pipes(): model.show() pha.notice("0.4-10.0") xspec.Plot.setRebin(minSig=3, maxBins=30) xspec.Plot.device = "/null" xspec.Plot.xAxis = "keV" xspec.Plot.yLog = "True" xspec.Plot("data") plt.figure(figsize=[10, 6]) plt.yscale('log') plt.xscale('log') plt.xlabel('Energy (keV)', fontsize=16) plt.title("{obs}".format(obs=obsid), fontsize=16) plt.errorbar(xspec.Plot.x(), xspec.Plot.y(), xerr=xspec.Plot.xErr(), yerr=xspec.Plot.yErr(), fmt='.') plt.step(xspec.Plot.x(), xspec.Plot.model(), where="mid") band = "0.5-10 keV" xspec.AllModels.calcFlux(band.replace(' keV', '').replace('-',' ')) print "Flux is {0:.3e} in the {1} band".format(pha.flux[0], band) if writexcm: xcmfile = os.path.join(workdir, str(obsid), 'ni{obsid}_0mpu7_cl'.format(obsid=obsid)) xu.write_xcm(xcmfile, pha, model=model) else: print "Can't fit OBSID {obs}".format(obs=obsid) return pha, model
def animate_plotting(subdir_path, ): average_filename = 'averaged_out.txt' if os.path.exists(os.path.join(subdir_path, average_filename)): print(subdir_path + average_filename + ' already exists please use hotPlot.py') #import existing data for average at the end # data_out = numpy.genfromtxt(os.path.join(subdir_path,average_filename)) # averaged_data = numpy.array(data_out[:,1]) # angles = data_out[:,0] #os.remove( os.path.join(subdir_path,average_filename)) else: files = os.listdir(subdir_path) #files = [d for d in os.listdir(subdir_path) if os.path.isdir(os.path.join(subdir_path, d))] onlyfiles_path = [ os.path.join(subdir_path, f) for f in files if os.path.isfile(os.path.join(subdir_path, f)) ] onlyfiles_path = natsort.natsorted(onlyfiles_path) averaged_data = [] angles = [] for f in onlyfiles_path: data = numpy.genfromtxt(f, delimiter=',') #data = pandas.read_csv(f) averaged_data.append(numpy.mean(data)) angle = os.path.basename(f).split('_')[0] angles.append(float(angle)) fig = plt.plot(angles, averaged_data, 'o') plt.yscale('log') plt.xscale('log') plt.legend(loc='upper right') plt.title(base_path) plt.grid(True) plt.xlabel(r'$\theta$ $[deg.]}$') #plt.xlabel(r'$\mathrm{xlabel\;with\;\LaTeX\;font}$') plt.ylabel(r'I($\theta$) $[a.u.]$')
# Import numpy as np import numpy as np import matplotlib as plt pop = [1, 2, 5, 20, 50, 60, 5, 84, 32] # Store pop as a numpy array: np_pop np_pop = np.array(pop) # Double np_pop np_pop.value = np_pop * 2 # Update: set s argument to np_pop plt.scatter(gdp_cap, life_exp, s=np_pop) # Previous customizations plt.xscale('log') plt.xlabel('GDP per Capita [in USD]') plt.ylabel('Life Expectancy [in years]') plt.title('World Development in 2007') plt.xticks([1000, 10000, 100000], ['1k', '10k', '100k']) # Display the plot plt.show()
print(life_exp[-1]) # Make a line plot, gdp_cap on the x-axis, life_exp on the y-axis plt.plot(gdp_cap, life_exp) # Display the plot plt.show() plt.clf() # Scatter plot (1) # Change the line plot below to a scatter plot # plt.plot(gdp_cap, life_exp) plt.scatter(gdp_cap, life_exp) # Put the x-axis on a logarithmic scale plt.xscale("log") # Show plot plt.show() # Scatter plot (2) # Build Scatter plot plt.scatter(pop, life_exp) # Show plot plt.show() plt.clf() ###################################################################### # Histogram ------------------------------------------- # Build a histogram (1)
#compute corr coef line. lin_fit = numpy.polyfit(numpy.array(fc),numpy.array(fc2),1) # this returns the coef of the polynomial fit corr_coef = numpy.corrcoef(numpy.array(fc),numpy.array(fc2))[0][1] # this is R line_x = numpy.linspace(numpy.array(fc).min(),numpy.array(fc).max()) # this is to have some points to actually draw the line. plots=[] for i,classe in enumerate(all_classes): a=plt.plot(numpy.array(fc)[all_classes[classe]],numpy.array(fc2)[all_classes[classe]],'o',alpha=.5, color=colors[i], marker=markers[i], label=classe) plots.append(a) plots.append( plt.plot(line_x, line_x*lin_fit[0] + lin_fit[1] , '--b', label='$R^2$ = %.2f'%(corr_coef*corr_coef) )) #we append the plot of the line here kwarg={'size':6 } plt.legend(loc='upper right', prop=kwarg) if log2gene1: plt.xscale('log', basex=2) plt.xlabel('log2 expression of %s'%in_gene) plt.xlim(xmax=plt.xlim()[1]+2^10) #make room for the legend else: plt.xlabel('%s'%in_gene) plt.xlim(xmax=plt.xlim()[1]+1000) #make room for the legend if log2gene2: plt.yscale('log', basey=2) plt.ylabel('log2 expression of %s'%in_gene2) plt.xlim(xmax=plt.xlim()[1]+2^10) #make room for the legend else: plt.xlabel('%s'%in_gene) plt.xlim(xmax=plt.xlim()[1]+1000) #make room for the legend