graph1.GetYaxis().SetRangeUser(52., 62.) graph1.GetYaxis().SetTitle("Mean value") graph1.GetXaxis().SetTitle("Top M(GeV)") graph1.Draw("AP") graph1.SetTitle("Mean value of the histogram vs top mass") graph2.SetLineColor(2) graph2.SetMarkerColor(2) graph2.Draw("P") # fit graph1.Fit("pol1") graph2.Fit("pol1") pol1 = TF1() pol1 = graph1.GetFunction("pol1") pol2 = TF1() pol2 = graph2.GetFunction("pol1") a0 = str(round(pol1.GetParameter(0), 2)) a1 = str(round(pol1.GetParameter(1), 2)) b0 = str(round(pol2.GetParameter(0), 2)) b1 = str(round(pol2.GetParameter(1), 2)) pol1.SetLineColor(1) pol2.SetLineColor(2) leg2 = TLegend(0.7, 0.15, 1, 0.25) leg2.SetHeader("Fits:") ##NEEDS TO BE CHANGED leg2.AddEntry(pol1, "deltar: y = " + a0 + " + " + a1 + "x", "ll") leg2.AddEntry(pol2, "minmass: y = " + b0 + " + " + b1 + "x", "ll")
def pp_pPB_Avg_Ratio(Comb_Dict,pT_Start): pPb_Combined = Comb_Dict["p-Pb_Combined_FF"] pPb_Combined_Errors = Comb_Dict["p-Pb_Combined_FF_Errors"] pPb_purity_Uncertainty = Comb_Dict["p-Pb_purity_Uncertainty"] pp_Combined = Comb_Dict["pp_Combined_FF"] pp_Combined_Errors = Comb_Dict["pp_Combined_FF_Errors"] pp_purity_Uncertainty = Comb_Dict["pp_purity_Uncertainty"] #Ratio Ratio = pPb_Combined/pp_Combined #Stat. Error in ratio Ratio_Error = np.sqrt((pPb_Combined_Errors/pPb_Combined)**2 + (pp_Combined_Errors/pp_Combined)**2)*Ratio #Save np.save("npy_files/%s_Averaged_FF_Ratio_%s.npy"%(Shower,description_string),Ratio) np.save("npy_files/%s_Averaged_FF_Ratio_Errors_%s.npy"%(Shower,description_string),Ratio_Error) #Sys. Error in ratio Purity_Uncertainty = np.sqrt((pp_purity_Uncertainty/pPb_Combined)**2 + (pPb_purity_Uncertainty/pPb_Combined)**2)*Ratio Efficiency_Uncertainty = np.ones(len(pPb_Combined))*0.056*math.sqrt(2)*Ratio if (CorrectedP): Ratio_Systematic = np.sqrt(Purity_Uncertainty**2 + Efficiency_Uncertainty**2) plt.figure(figsize=(10,7)) plt.tick_params(which='both',direction='in',right=True,bottom=True,top=True,length=10) #Sys_Plot = plt.bar(zT_centers[:NzT-ZT_OFF_PLOT], Ratio_Systematic[:NzT-ZT_OFF_PLOT]+Ratio_Systematic[:NzT-ZT_OFF_PLOT], # bottom=Ratio[:NzT-ZT_OFF_PLOT]-Ratio_Systematic[:NzT-ZT_OFF_PLOT], width=zt_box[:NzT-ZT_OFF_PLOT], align='center',edgecolor="k",color='w') #bottom=Ratio[:NzT-ZT_OFF_PLOT]-Ratio_Systematic[:NzT-ZT_OFF_PLOT], width=zt_box[:NzT-ZT_OFF_PLOT], align='center',color='black',alpha=0.2) Sys_Plot = plt.bar(zT_centers[:NzT-ZT_OFF_PLOT], 2*Ratio_Systematic[:NzT-ZT_OFF_PLOT], bottom=1.0-Ratio_Systematic[:NzT-ZT_OFF_PLOT], width=2*zT_widths[:NzT-ZT_OFF_PLOT], align='center',color='black',alpha = 0.2) empt4, = plt.plot([], [],' ') Ratio_Plot = plt.errorbar(zT_centers[:NzT-ZT_OFF_PLOT], Ratio[:NzT-ZT_OFF_PLOT], yerr=Ratio_Error[:NzT-ZT_OFF_PLOT],xerr=zT_widths[:NzT-ZT_OFF_PLOT], fmt='ko',capsize=3, ms=6,lw=1) plt.xlabel("${z_\mathrm{T}} = p_\mathrm{T}^{\mathrm{h}}/p_\mathrm{T}^\gamma$",fontsize=20) plt.ylabel(r"$\frac{\mathrm{p-Pb}}{\mathrm{pp}}$",fontsize=20) plt.ylim((-0.49, 2.9)) #plt.yticks(np.arange(-0, 2, step=0.2)) if(NzT == 6): plt.xlim(xmin = 0.0,xmax=0.7) elif(NzT==7): plt.xlim(xmin = 0.0,xmax=1.0) #plt.xlim(xmin = 0.0,xmax=zTbins[NzT-ZT_OFF_PLOT]) plt.xlim(xmin = 0.0,xmax=0.67) plt.axhline(y=1, color='k', linestyle='--') ### ROOT LINEAR and CONSTANT FITS ### Ratio_TGraph = TGraphErrors() for izt in range (len(Ratio)-ZT_OFF_PLOT): Ratio_TGraph.SetPoint(izt,zT_centers[izt],Ratio[izt]) Ratio_TGraph.SetPointError(izt,0,Ratio_Error[izt]) Ratio_TGraph.Fit("pol0","S") f = Ratio_TGraph.GetFunction("pol0") chi2_red = f.GetChisquare()/f.GetNDF() pval = f.GetProb() p0 = f.GetParameter(0) p0e = f.GetParError(0) p0col = "blue" if (Show_Fits): plt.annotate("Constant Fit", xy=(0.05, 0.99), xycoords='axes fraction', ha='left', va='top', color=p0col,fontsize=20,alpha=.7) plt.annotate(r"$p0 = {0:.2f} \pm {1:.2f}$".format(p0,p0e), xy=(0.05, 0.94), xycoords='axes fraction', ha='left', va='top', color=p0col,fontsize=18,alpha=.7) plt.annotate(r"$\chi^2_{red} = %1.2f$"%(chi2_red), xy=(0.05, 0.89), xycoords='axes fraction', ha='left', va='top', color=p0col,fontsize=18,alpha=.7) plt.annotate(r"$p_{val} = %1.2f$"%(pval), xy=(0.05, 0.84), xycoords='axes fraction', ha='left', va='top', color=p0col,fontsize=18,alpha=.7) plt.fill_between(np.arange(0,1.1,0.1), p0+p0e, p0-p0e,color=p0col,alpha=.2) Ratio_TGraph.Fit("pol1","S") #zT_Points = np.linspace(0.05,zTbins[NzT-1],20) zT_Points = np.linspace(0.0,1,20) Fit_Band = ROOT.TGraphErrors(len(zT_Points)); for i in range(len(zT_Points)-ZT_OFF_PLOT): Fit_Band.SetPoint(i, zT_Points[i], 0) (ROOT.TVirtualFitter.GetFitter()).GetConfidenceIntervals(Fit_Band,0.68) band_errors = np.zeros(len(zT_Points)) for i in range (len(zT_Points)): band_errors[i] = Fit_Band.GetErrorY(i) print(band_errors) f2 = Ratio_TGraph.GetFunction("pol1") chi2_red = f2.GetChisquare()/f2.GetNDF() pval = f2.GetProb() p0 = f2.GetParameter(0) p0e = f2.GetParError(0) p1 = f2.GetParameter(1) p1e = f2.GetParError(1) print(p1e) p1col = "Green" if (Show_Fits): plt.annotate("Linear Fit", xy=(0.4, 0.99), xycoords='axes fraction', ha='left', va='top', color=p1col,fontsize=20,alpha=.7) plt.annotate(r"$p0 = %1.2f \pm %1.2f$"%(p0,p0e), xy=(0.4, 0.94), xycoords='axes fraction', ha='left', va='top', color=p1col,fontsize=18,alpha=.7) plt.annotate(r"$p1 = %1.2f \pm %1.2f$"%(p1,p1e), xy=(0.4, 0.89), xycoords='axes fraction', ha='left', va='top', color=p1col,fontsize=18,alpha=.7) plt.annotate(r"$\chi^2_{red} = %1.2f$"%(chi2_red), xy=(0.4, 0.84), xycoords='axes fraction', ha='left', va='top', color=p1col,fontsize=18,alpha=.7) plt.annotate(r"$p_{val} = %1.2f$"%(pval), xy=(0.4, 0.79), xycoords='axes fraction', ha='left', va='top', color=p1col,fontsize=18,alpha=.7) axes = plt.gca() x_vals = np.array(zT_Points) y_vals = p0 + p1 * zT_Points plt.plot(zT_Points, y_vals, '--',color=p1col,linewidth=2,alpha=0.5) plt.fill_between(zT_Points,y_vals+band_errors,y_vals-band_errors,color=p1col,alpha=0.2) ### ROOT DONE ### leg = plt.legend([Ratio_Plot,empt4],["Statistical Error",r'%1.0f < $p_\mathrm{T}^{\mathrm{trig}}$ < %1.0f GeV/$c$'%(pTbins[pT_Start],pTbins[N_pT_Bins])],frameon=False,numpoints=1,loc="lower left",title=' ',prop={'size':18}) leg.set_title("ALICE Work in Progress\n $\sqrt{s_{\mathrm{_{NN}}}} = $ 5 TeV") plt.setp(leg.get_title(),fontsize=20) plt.gcf() plt.savefig("pics/%s/%s/Ratio_Fits.pdf"%(Shower,description_string), bbox='tight') plt.show() print(" Central Values:") print(Ratio[:NzT-ZT_OFF_PLOT]) print("\n Satistical Uncertainty Absolute:") print(Ratio_Error[:NzT-ZT_OFF_PLOT]) print("\n Relative Satistical Uncertainty:") print(Ratio_Error[:NzT-ZT_OFF_PLOT]/Ratio[:NzT-ZT_OFF_PLOT]) print("\n Ratio Uncertainty from Purity:") print(Purity_Uncertainty[:NzT-ZT_OFF_PLOT]) print("\n Ratio Uncertainty from Single Track Efficiency:") print(Efficiency_Uncertainty[:NzT-ZT_OFF_PLOT]) print("\n Full Systematic Uncertainty:") print(Ratio_Systematic[:NzT-ZT_OFF_PLOT]) print("\n Relative Full Systematic:") print(Ratio_Systematic[:NzT-ZT_OFF_PLOT]/Ratio[:NzT-ZT_OFF_PLOT]) print("\n LaTeX Table:") print("$\zt$ range & pp & p--Pb & p--Pb/pp \\\\") for izt in range (NzT): print("%1.2f - %1.2f & %1.3f $\pm$ %1.3f & %1.3f $\pm$ %1.3f & %1.3f $\pm$ %1.3f \\\\" %(zTbins[izt], zTbins[izt+1], pp_Combined[izt], pp_Combined_Errors[izt], pPb_Combined[izt], pPb_Combined_Errors[izt], Ratio[izt], Ratio_Error[izt]))
def Plot_pp_pPb_Avg_FF_and_Ratio(Comb_Dict): label_size=22 axis_size=34 plot_power = False Colors = ["red","blue"] Markers = ["s","o"] fig = plt.figure(figsize=(8,8)) pp_sys_Error = 0 p_Pb_sys_Error = 0 fig.add_axes((0.1,0.3,0.88,0.6)) for SYS,sys_col,marker in zip(reversed(Systems),reversed(Colors),reversed(Markers)): #Systematics Efficiency_Uncertainty = 0.056*Comb_Dict["%s_Combined_FF"%(SYS)] Eta_Cor = Eta_Correction #see default_value.py for value Eta_Cor_Uncertainty = Eta_Correction_Uncertainty*Comb_Dict["%s_Combined_FF"%(SYS)] if not(Apply_Eta_Correction and SYS=="p-Pb"): Eta_Cor_Uncertainty = 0 #2% otherwise FF_Central = Comb_Dict["%s_Combined_FF"%(SYS)] #Eta Correction is applied when creating Dictionary! Sys_Uncertainty = np.sqrt(Efficiency_Uncertainty**2 + Comb_Dict["%s_purity_Uncertainty"%(SYS)]**2 + Eta_Cor_Uncertainty**2) if (SYS=="pp"): pp_sys_Error = Sys_Uncertainty elif (SYS=="p-Pb"): p_Pb_sys_Error=Sys_Uncertainty #Plots if (SYS=="pp"): leg_string = SYS if (SYS=="p-Pb"): leg_string = "p$-$Pb" plt.errorbar(zT_centers[:NzT-ZT_OFF_PLOT], Comb_Dict["%s_Combined_FF"%(SYS)][:NzT-ZT_OFF_PLOT],xerr=zT_widths[:NzT-ZT_OFF_PLOT]*0, yerr=Comb_Dict["%s_Combined_FF_Errors"%(SYS)][:NzT-ZT_OFF_PLOT],linewidth=1, fmt=marker,color=sys_col,capsize=0)#for lines plt.plot(zT_centers[:NzT-ZT_OFF_PLOT], Comb_Dict["%s_Combined_FF"%(SYS)][:NzT-ZT_OFF_PLOT],marker,linewidth=0,color=sys_col, label=leg_string)#for legend without lines if (SYS == "pp"): Sys_Plot_pp = plt.bar(zT_centers[:NzT-ZT_OFF_PLOT], Sys_Uncertainty[:NzT-ZT_OFF_PLOT]+Sys_Uncertainty[:NzT-ZT_OFF_PLOT], bottom=Comb_Dict["%s_Combined_FF"%(SYS)][:NzT-ZT_OFF_PLOT]-Sys_Uncertainty[:NzT-ZT_OFF_PLOT],width=zT_widths[:NzT-ZT_OFF_PLOT]*2, align='center',color=sys_col,alpha=0.3,edgecolor=sys_col) else: Sys_Plot_pp = plt.bar(zT_centers[:NzT-ZT_OFF_PLOT], Sys_Uncertainty[:NzT-ZT_OFF_PLOT]+Sys_Uncertainty[:NzT-ZT_OFF_PLOT], bottom=Comb_Dict["%s_Combined_FF"%(SYS)][:NzT-ZT_OFF_PLOT]-Sys_Uncertainty[:NzT-ZT_OFF_PLOT],width=zT_widths[:NzT-ZT_OFF_PLOT]*2,align='center',color=sys_col,fill=False,edgecolor="blue") if (plot_power): model,p,chi2dof = Fit_FF_PowerLaw(Comb_Dict,SYS) plt.plot(zT_centers[:NzT-ZT_OFF_PLOT], model, sys_col,label=r"%s $\alpha = %1.2f\pm 0.1 \chi^2 = %1.2f$"%(SYS,p,chi2dof)) if (Use_MC): plt.plot(zT_centers[:NzT-ZT_OFF_PLOT],pythia_FF,'--',color="forestgreen",label="PYTHIA 8.2 Monash") plt.errorbar(zT_centers[:NzT-ZT_OFF_PLOT],pythia_FF,yerr=pythia_FF_Errors,fmt='--',color="forestgreen",capsize=0) plt.yscale('log') plt.ylabel(r"$\frac{1}{N_{\mathrm{\gamma}}}\frac{\mathrm{d}^3N}{\mathrm{d}z_{\mathrm{T}}\mathrm{d}|\Delta\varphi|\mathrm{d}\Delta\eta}$",fontsize=axis_size,y=0.76) plt.ylim(0.037,15) plt.yticks(fontsize=20) plt.xticks(fontsize=0) plt.xlim(0,0.65) plt.tick_params(which='both',direction='in',right=True,top=True,bottom=False,length=10) plt.tick_params(which='minor',length=5) #pp_sys_Error = (Comb_Dict["pp_Combined_FF"][:NzT-ZT_OFF_PLOT])*math.sqrt(Rel_pUncert["pp"]**2+0.056**2) #p_Pb_sys_Error = (Comb_Dict["p-Pb_Combined_FF"][:NzT-ZT_OFF_PLOT])*math.sqrt(Rel_pUncert["p-Pb"]**2+0.056**2+Eta_Cor**2) Chi2,NDF,Pval = Get_pp_pPb_List_Chi2(Comb_Dict["pp_Combined_FF"][:NzT-ZT_OFF_PLOT], Comb_Dict["pp_Combined_FF_Errors"][:NzT-ZT_OFF_PLOT], pp_sys_Error, Comb_Dict["p-Pb_Combined_FF"][:NzT-ZT_OFF_PLOT], Comb_Dict["p-Pb_Combined_FF_Errors"][:NzT-ZT_OFF_PLOT], p_Pb_sys_Error) leg = plt.legend(numpoints=1,frameon=True,edgecolor='white', framealpha=0.0, fontsize=label_size,handlelength=1,labelspacing=0.2,loc='lower left',bbox_to_anchor=(0.001, 0.05)) plt.annotate(r"ALICE, $\sqrt{s_{\mathrm{_{NN}}}}=5.02$ TeV",xy=(0.115,0.008),xycoords='axes fraction', ha='left',va='bottom',fontsize=label_size) plt.annotate(r"%1.0f < $p_\mathrm{T}^{\gamma}$ < %1.0f GeV/$c$"%(pTbins[0],pTbins[N_pT_Bins]),xy=(0.97, 0.81), xycoords='axes fraction', ha='right', va='top', fontsize=label_size) plt.annotate(r"%1.1f < $p_\mathrm{T}^\mathrm{h}$ < %1.1f GeV/$c$"%(Min_Hadron_pT,Max_Hadron_pT),xy=(0.97, 0.89), xycoords='axes fraction', ha='right', va='top', fontsize=label_size) plt.annotate("$\chi^2/\mathrm{ndf}$ = %1.1f/%i, $p$ = %1.2f"%(Chi2*NDF,NDF,Pval), xy=(0.97, 0.97), xycoords='axes fraction', ha='right', va='top', fontsize=label_size) #HEP FF Fig5 = Table("Figure 5 Top Panel") Fig5.description = "$\gamma^\mathrm{iso}$-tagged fragmentation function for pp (red) and p$-$Pb data (blue) at $\sqrt{s_\mathrm{NN}}$ = 5.02 TeV as measured by the ALICE detector. The boxes represent the systematic uncertainties while the vertical bars indicate the statistical uncertainties. The dashed green line corresponds to PYTHIA 8.2 Monash Tune. The $\chi^2$ test for the comparison of pp and p$-$Pb data incorporates correlations among different $z_\mathrm{T}$ intervals. A constant that was fit to the ratio is shown as grey band, with the width indicating the uncertainty on the fit." Fig5.location = "Data from Figure 5 Top Panel, Page 15" Fig5.keywords["observables"] = ["$\frac{1}{N_{\mathrm{\gamma}}}\frac{\mathrm{d}^3N}{\mathrm{d}z_{\mathrm{T}}\mathrm{d}\Delta\varphi\mathrm{d}\Delta\eta}$"] Fig5.add_image("./pics/LO/zT_Rebin_8_006zT06zT13fnew/Final_FFunction_and_Ratio.pdf") # x-axis: zT zt = Variable(r"$z_\mathrm{T}$", is_independent=True, is_binned=True, units="") zt.values = zT_edges Fig5.add_variable(zt) # y-axis: p-Pb Yields pPb_data = Variable("p$-$Pb conditional yield of associated hadrons", is_independent=False, is_binned=False, units="") pPb_data.values = Comb_Dict["p-Pb_Combined_FF"] pPb_sys = Uncertainty("p-Pb Systematic", is_symmetric=True) pPb_sys.values = p_Pb_sys_Error pPb_stat = Uncertainty("p-Pb Statistical", is_symmetric=True) pPb_stat.values = Comb_Dict["p-Pb_Combined_FF_Errors"] pPb_data.add_uncertainty(pPb_sys) pPb_data.add_uncertainty(pPb_stat) # y-axis: pp Yields pp_data = Variable("pp conditional yield of associated hadrons", is_independent=False, is_binned=False, units="") pp_data.values = Comb_Dict["pp_Combined_FF"] pp_sys = Uncertainty("pp Systematic", is_symmetric=True) pp_sys.values = pp_sys_Error pp_stat = Uncertainty("pp Statistical", is_symmetric=True) pp_stat.values = Comb_Dict["pp_Combined_FF_Errors"] pp_data.add_uncertainty(pp_sys) pp_data.add_uncertainty(pp_stat) # y-axis: PYTHIA Yields pythia_data = Variable("PYTHIA conditional yield of associated hadrons", is_independent=False, is_binned=False, units="") pythia_data.values = pythia_FF pythia_stat = Uncertainty("PYTHIA Statistical", is_symmetric=True) pythia_stat.values = pythia_FF_Errors pythia_data.add_uncertainty(pythia_stat) #Add everything to the HEP Table Fig5.add_variable(pPb_data) Fig5.add_variable(pp_data) Fig5.add_variable(pythia_data) submission.add_table(Fig5) #RATIO SECOND Y_AXIS fig.add_axes((0.1,0.1,0.88,0.2)) pPb_Combined = Comb_Dict["p-Pb_Combined_FF"] pPb_Combined_Errors = Comb_Dict["p-Pb_Combined_FF_Errors"] pPb_purity_Uncertainty = Comb_Dict["p-Pb_purity_Uncertainty"] pp_Combined = Comb_Dict["pp_Combined_FF"] pp_Combined_Errors = Comb_Dict["pp_Combined_FF_Errors"] pp_purity_Uncertainty = Comb_Dict["pp_purity_Uncertainty"] Ratio = pPb_Combined/pp_Combined Ratio_Error = np.sqrt((pPb_Combined_Errors/pPb_Combined)**2 + (pp_Combined_Errors/pp_Combined)**2)*Ratio Ratio_Plot = plt.errorbar(zT_centers[:NzT-ZT_OFF_PLOT], Ratio[:NzT-ZT_OFF_PLOT], yerr=Ratio_Error[:NzT-ZT_OFF_PLOT],xerr=zT_widths[:NzT-ZT_OFF_PLOT]*0, fmt='ko',capsize=0, ms=6,lw=1) #Save np.save("npy_files/%s_Averaged_FF_Ratio_%s.npy"%(Shower,description_string),Ratio) np.save("npy_files/%s_Averaged_FF_Ratio_Errors_%s.npy"%(Shower,description_string),Ratio_Error) Purity_Uncertainty = np.sqrt((pp_purity_Uncertainty/pp_Combined)**2 + (pPb_purity_Uncertainty/pPb_Combined)**2)*Ratio Efficiency_Uncertainty = np.ones(len(pPb_Combined))*0.056*math.sqrt(2)*Ratio Eta_Cor_Uncertainty = Eta_Correction_Uncertainty/Comb_Dict["p-Pb_Combined_FF"]*Ratio if (CorrectedP): Ratio_Systematic = np.sqrt(Purity_Uncertainty**2 + Efficiency_Uncertainty**2 + Eta_Cor_Uncertainty**2) Sys_Plot = plt.bar(zT_centers[:NzT-ZT_OFF_PLOT], Ratio_Systematic[:NzT-ZT_OFF_PLOT]+Ratio_Systematic[:NzT-ZT_OFF_PLOT], bottom=Ratio[:NzT-ZT_OFF_PLOT]-Ratio_Systematic[:NzT-ZT_OFF_PLOT], width=zT_widths[:NzT-ZT_OFF_PLOT]*2, align='center',color='black',alpha=0.25) ### ROOT LINEAR and CONSTANT FITS ### Ratio_TGraph = TGraphErrors() for izt in range (len(Ratio)-ZT_OFF_PLOT): Ratio_TGraph.SetPoint(izt,zT_centers[izt],Ratio[izt]) Ratio_TGraph.SetPointError(izt,0,Ratio_Error[izt]) Ratio_TGraph.Fit("pol0","S") f = Ratio_TGraph.GetFunction("pol0") chi2_red = f.GetChisquare()/f.GetNDF() pval = f.GetProb() p0 = f.GetParameter(0) p0e = f.GetParError(0) p0col = "grey" Show_Fits = True if (Show_Fits): sys_const = 0.19 #23% relative from purity + tracking #sys_const = 0.504245 #IRC plt.annotate("$c = {0:.2f} \pm {1:.2f} \pm {2:.2f}$".format(p0,p0e,sys_const), xy=(0.98, 0.9), xycoords='axes fraction', ha='right', va='top', color="black",fontsize=label_size,alpha=.9) plt.annotate(r"$p = %1.2f$"%(pval), xy=(0.98, 0.75), xycoords='axes fraction', ha='right', va='top', color="black",fontsize=label_size,alpha=.9) c_error = math.sqrt(p0e**2 + sys_const**2) plt.fill_between(np.arange(0,1.1,0.1), p0+c_error, p0-c_error,color=p0col,alpha=.3) ###LABELS/AXES### plt.axhline(y=1, color='k', linestyle='--') plt.xlabel("${z_\mathrm{T}} = p_\mathrm{T}^{\mathrm{h}}/p_\mathrm{T}^\gamma$",fontsize=axis_size-8,x=0.9) plt.ylabel(r"$\frac{\mathrm{p-Pb}}{\mathrm{pp}}$",fontsize=axis_size,y=0.5) plt.ylim((-0.0, 2.8)) plt.xticks(fontsize=20) plt.yticks([0.5,1.0,1.5,2.0,2.5],fontsize=20) plt.xlim(0,0.65) plt.tick_params(which='both',direction='in',right=True,bottom=True,top=True,length=10) plt.tick_params(which='both',direction='in',top=True,length=5) plt.savefig("pics/%s/%s/Final_FFunction_and_Ratio.pdf"%(Shower,description_string), bbox_inches = "tight") plt.show() #RATIO HEP FigRatio = Table("Figure 5 Bottom Panel") FigRatio.description = r"$\gamma^\mathrm{iso}$-tagged fragmentation function for pp (red) and p$-$Pb data (blue) at $\sqrt{s_\mathrm{NN}}$ = 5.02 TeV as measured by the ALICE detector. The boxes represent the systematic uncertainties while the vertical bars indicate the statistical uncertainties. The dashed green line corresponds to PYTHIA 8.2 Monash Tune. The $\chi^2$ test for the comparison of pp and p$-$Pb data incorporates correlations among different $z_\mathrm{T}$ intervals. A constant that was fit to the ratio is shown as grey band, with the width indicating the uncertainty on the fit." FigRatio.location = "Data from Figure 5, Bottom Panel, Page 15" FigRatio.keywords["observables"] = [r"$\frac{1}{N_{\mathrm{\gamma}}}\frac{\mathrm{d}^3N}{\mathrm{d}z_{\mathrm{T}}\mathrm{d}\Delta\varphi\mathrm{d}\Delta\eta}$"] FigRatio.add_image("./pics/LO/zT_Rebin_8_006zT06zT13fnew/Final_FFunction_and_Ratio.pdf") # x-axis: zT zt_ratio = Variable(r"$z_\mathrm{T}$", is_independent=True, is_binned=True, units="") zt_ratio.values = zT_edges FigRatio.add_variable(zt_ratio) # y-axis: p-Pb Yields Ratio_HEP = Variable("Ratio conditional yield of associated hadrons in pp and p$-$Pb", is_independent=False, is_binned=False, units="") Ratio_HEP.values = Ratio Ratio_sys = Uncertainty("Ratio Systematic", is_symmetric=True) Ratio_sys.values = Ratio_Systematic Ratio_stat = Uncertainty("Ratio Statistical", is_symmetric=True) Ratio_stat.values = Ratio_Error Ratio_HEP.add_uncertainty(Ratio_stat) Ratio_HEP.add_uncertainty(Ratio_sys) FigRatio.add_variable(Ratio_HEP) submission.add_table(FigRatio)
def Model_Comparisons(Comb_Dict): label_size=22 axis_size=34 plot_power = False Colors = ["red","blue"] Markers = ["s","o"] fig = plt.figure(figsize=(8,8)) fig.add_axes((0.1,0.3,0.88,0.6)) for SYS,sys_col,marker in zip(reversed(Systems),reversed(Colors),reversed(Markers)): #Systematics Efficiency_Uncertainty = 0.056*Comb_Dict["%s_Combined_FF"%(SYS)] Eta_Cor = Eta_Correction #see default_value.py for value Eta_Cor_Uncertainty = Eta_Correction_Uncertainty*Comb_Dict["%s_Combined_FF"%(SYS)] if not(Apply_Eta_Correction and SYS=="p-Pb"): Eta_Cor_Uncertainty = 0 #2% otherwise FF_Central = Comb_Dict["%s_Combined_FF"%(SYS)] #Eta Correction is applied when creating Dictionary! Sys_Uncertainty = np.sqrt(Efficiency_Uncertainty**2 + Comb_Dict["%s_purity_Uncertainty"%(SYS)]**2 + Eta_Cor_Uncertainty**2) if (SYS=="pp"): pp_sys_Error = Sys_Uncertainty elif (SYS=="p-Pb"): p_Pb_sys_Error=Sys_Uncertainty #Plots if (SYS=="pp"): leg_string = SYS if (SYS=="p-Pb"): leg_string = "p$-$Pb" plt.errorbar(zT_centers[:NzT-ZT_OFF_PLOT], Comb_Dict["%s_Combined_FF"%(SYS)][:NzT-ZT_OFF_PLOT],xerr=zT_widths[:NzT-ZT_OFF_PLOT]*0, yerr=Comb_Dict["%s_Combined_FF_Errors"%(SYS)][:NzT-ZT_OFF_PLOT],linewidth=1, fmt=marker,color=sys_col,capsize=0)#for lines plt.plot(zT_centers[:NzT-ZT_OFF_PLOT], Comb_Dict["%s_Combined_FF"%(SYS)][:NzT-ZT_OFF_PLOT],marker,linewidth=0,color=sys_col, label=leg_string)#for legend without lines if (SYS == "pp"): Sys_Plot_pp = plt.bar(zT_centers[:NzT-ZT_OFF_PLOT], Sys_Uncertainty[:NzT-ZT_OFF_PLOT]+Sys_Uncertainty[:NzT-ZT_OFF_PLOT], bottom=Comb_Dict["%s_Combined_FF"%(SYS)][:NzT-ZT_OFF_PLOT]-Sys_Uncertainty[:NzT-ZT_OFF_PLOT],width=zT_widths[:NzT-ZT_OFF_PLOT]*2, align='center',color=sys_col,alpha=0.3,edgecolor=sys_col) else: Sys_Plot_pp = plt.bar(zT_centers[:NzT-ZT_OFF_PLOT], Sys_Uncertainty[:NzT-ZT_OFF_PLOT]+Sys_Uncertainty[:NzT-ZT_OFF_PLOT], bottom=Comb_Dict["%s_Combined_FF"%(SYS)][:NzT-ZT_OFF_PLOT]-Sys_Uncertainty[:NzT-ZT_OFF_PLOT],width=zT_widths[:NzT-ZT_OFF_PLOT]*2,align='center',color=sys_col,fill=False,edgecolor="blue") if (plot_power): model,p,chi2dof = Fit_FF_PowerLaw(Comb_Dict,SYS) plt.plot(zT_centers[:NzT-ZT_OFF_PLOT], model, sys_col,label=r"%s $\alpha = %1.2f\pm 0.1 \chi^2 = %1.2f$"%(SYS,p,chi2dof)) if (Use_MC): plt.plot(zT_centers[:NzT-ZT_OFF_PLOT],pythia_FF,'--',color="forestgreen",label="PYTHIA 8.2 Monash") plt.errorbar(zT_centers[:NzT-ZT_OFF_PLOT],pythia_FF,yerr=pythia_FF_Errors,fmt='--',color="forestgreen",capsize=0) plt.yscale('log') plt.ylabel(r"$\frac{1}{N_{\mathrm{\gamma}}}\frac{\mathrm{d}^3N}{\mathrm{d}z_{\mathrm{T}}\mathrm{d}|\Delta\varphi|\mathrm{d}\Delta\eta}$",fontsize=axis_size,y=0.76) plt.ylim(0.037,15) plt.yticks(fontsize=20) plt.xticks(fontsize=0) plt.xlim(0,0.65) plt.tick_params(which='both',direction='in',right=True,top=True,bottom=False,length=10) plt.tick_params(which='minor',length=5) #pp_sys_Error = (Comb_Dict["pp_Combined_FF"][:NzT-ZT_OFF_PLOT])*math.sqrt(Rel_pUncert["pp"]**2+0.056**2) #p_Pb_sys_Error = (Comb_Dict["p-Pb_Combined_FF"][:NzT-ZT_OFF_PLOT])*math.sqrt(Rel_pUncert["p-Pb"]**2+0.056**2+Eta_Cor**2) Chi2,NDF,Pval = Get_pp_pPb_List_Chi2(Comb_Dict["pp_Combined_FF"][:NzT-ZT_OFF_PLOT], Comb_Dict["pp_Combined_FF_Errors"][:NzT-ZT_OFF_PLOT], pp_sys_Error, Comb_Dict["p-Pb_Combined_FF"][:NzT-ZT_OFF_PLOT], Comb_Dict["p-Pb_Combined_FF_Errors"][:NzT-ZT_OFF_PLOT], p_Pb_sys_Error) leg = plt.legend(numpoints=1,frameon=True,edgecolor='white', framealpha=0.0, fontsize=label_size,handlelength=1,labelspacing=0.2,loc='lower left',bbox_to_anchor=(0.001, 0.05)) plt.annotate(r"ALICE, $\sqrt{s_{\mathrm{_{NN}}}}=5.02$ TeV",xy=(0.115,0.008),xycoords='axes fraction', ha='left',va='bottom',fontsize=label_size) plt.annotate(r"%1.0f < $p_\mathrm{T}^{\gamma}$ < %1.0f GeV/$c$"%(pTbins[0],pTbins[N_pT_Bins]),xy=(0.97, 0.81), xycoords='axes fraction', ha='right', va='top', fontsize=label_size) plt.annotate(r"%1.1f < $p_\mathrm{T}^\mathrm{h}$ < %1.1f GeV/$c$"%(Min_Hadron_pT,Max_Hadron_pT),xy=(0.97, 0.89), xycoords='axes fraction', ha='right', va='top', fontsize=label_size) plt.annotate("$\chi^2/\mathrm{ndf}$ = %1.1f/%i, $p$ = %1.2f"%(Chi2*NDF,NDF,Pval), xy=(0.97, 0.97), xycoords='axes fraction', ha='right', va='top', fontsize=label_size) #RATIO SECOND Y_AXIS fig.add_axes((0.1,0.1,0.88,0.2)) pPb_Combined = Comb_Dict["p-Pb_Combined_FF"] pPb_Combined_Errors = Comb_Dict["p-Pb_Combined_FF_Errors"] pPb_purity_Uncertainty = Comb_Dict["p-Pb_purity_Uncertainty"] pp_Combined = Comb_Dict["pp_Combined_FF"] pp_Combined_Errors = Comb_Dict["pp_Combined_FF_Errors"] pp_purity_Uncertainty = Comb_Dict["pp_purity_Uncertainty"] Ratio = pPb_Combined/pp_Combined Ratio_Error = np.sqrt((pPb_Combined_Errors/pPb_Combined)**2 + (pp_Combined_Errors/pp_Combined)**2)*Ratio Ratio_Plot = plt.errorbar(zT_centers[:NzT-ZT_OFF_PLOT], Ratio[:NzT-ZT_OFF_PLOT], yerr=Ratio_Error[:NzT-ZT_OFF_PLOT],xerr=zT_widths[:NzT-ZT_OFF_PLOT]*0, fmt='ko',capsize=0, ms=6,lw=1) Purity_Uncertainty = np.sqrt((pp_purity_Uncertainty/pp_Combined)**2 + (pPb_purity_Uncertainty/pPb_Combined)**2)*Ratio Efficiency_Uncertainty = np.ones(len(pPb_Combined))*0.056*math.sqrt(2)*Ratio Eta_Cor_Uncertainty = Eta_Correction_Uncertainty/Comb_Dict["p-Pb_Combined_FF"]*Ratio if (CorrectedP): Ratio_Systematic = np.sqrt(Purity_Uncertainty**2 + Efficiency_Uncertainty**2 + Eta_Cor_Uncertainty**2) Sys_Plot = plt.bar(zT_centers[:NzT-ZT_OFF_PLOT], Ratio_Systematic[:NzT-ZT_OFF_PLOT]+Ratio_Systematic[:NzT-ZT_OFF_PLOT], bottom=Ratio[:NzT-ZT_OFF_PLOT]-Ratio_Systematic[:NzT-ZT_OFF_PLOT], width=zT_widths[:NzT-ZT_OFF_PLOT]*2, align='center',color='black',alpha=0.25) ### ROOT LINEAR and CONSTANT FITS ### Ratio_TGraph = TGraphErrors() for izt in range (len(Ratio)-ZT_OFF_PLOT): Ratio_TGraph.SetPoint(izt,zT_centers[izt],Ratio[izt]) Ratio_TGraph.SetPointError(izt,0,Ratio_Error[izt]) Ratio_TGraph.Fit("pol0","S") f = Ratio_TGraph.GetFunction("pol0") chi2_red = f.GetChisquare()/f.GetNDF() pval = f.GetProb() p0 = f.GetParameter(0) p0e = f.GetParError(0) p0col = "grey" Show_Fits = True if (Show_Fits): sys_const = 0.19 #23% relative from purity + tracking plt.annotate("$c = {0:.2f} \pm {1:.2f} \pm {2:.2f}$".format(p0,p0e,sys_const), xy=(0.98, 0.9), xycoords='axes fraction', ha='right', va='top', color="black",fontsize=label_size,alpha=.9) plt.annotate(r"$p = %1.2f$"%(pval), xy=(0.98, 0.75), xycoords='axes fraction', ha='right', va='top', color="black",fontsize=label_size,alpha=.9) c_error = math.sqrt(p0e**2 + sys_const**2) plt.fill_between(np.arange(0,1.1,0.1), p0+c_error, p0-c_error,color=p0col,alpha=.3) ###LABELS/AXES### plt.axhline(y=1, color='k', linestyle='--') #plt.xlabel("${z_\mathrm{T}} = p_\mathrm{T}^{\mathrm{h}}/p_\mathrm{T}^\gamma$",fontsize=axis_size-8,x=0.9) plt.xlabel(r"varphi = $\varphi$, phi = $\phi$",fontsize = 30) plt.ylabel(r"$\frac{\mathrm{p-Pb}}{\mathrm{pp}}$",fontsize=axis_size,y=0.5) plt.ylim((-0.0, 2.8)) plt.xticks(fontsize=20) plt.yticks([0.5,1.0,1.5,2.0,2.5],fontsize=20) plt.xlim(0,0.65) plt.tick_params(which='both',direction='in',right=True,bottom=True,top=True,length=10) plt.tick_params(which='both',direction='in',top=True,length=5) plt.fill_between(QGP_zt,QGP_IpPb_LowAll,QGP_IpPb_HighAll,label="QGP Droplet",color='orange') plt.plot(CNM_zt,CNM_IpPb,color='red',label="CNM Model") plt.legend(loc='upper left') plt.savefig("pics/%s/%s/Model_Comparisons.pdf"%(Shower,description_string), bbox_inches = "tight") plt.show()
def Model_Ratio_Comparisons(Comb_Dict): label_size=24 axis_size=34 plot_power = False Colors = ["red","blue"] Markers = ["s","o"] fig = plt.figure(figsize=(8,8)) fig.add_axes((0.1,0.3,0.88,0.6)) # fig.add_axes((0.1,0.1,0.88,0.2)) pPb_Combined = Comb_Dict["p-Pb_Combined_FF"] pPb_Combined_Errors = Comb_Dict["p-Pb_Combined_FF_Errors"] pPb_purity_Uncertainty = Comb_Dict["p-Pb_purity_Uncertainty"] pp_Combined = Comb_Dict["pp_Combined_FF"] pp_Combined_Errors = Comb_Dict["pp_Combined_FF_Errors"] pp_purity_Uncertainty = Comb_Dict["pp_purity_Uncertainty"] Ratio = pPb_Combined/pp_Combined Ratio_Error = np.sqrt((pPb_Combined_Errors/pPb_Combined)**2 + (pp_Combined_Errors/pp_Combined)**2)*Ratio Ratio_Plot = plt.errorbar(zT_centers[:NzT-ZT_OFF_PLOT], Ratio[:NzT-ZT_OFF_PLOT], yerr=Ratio_Error[:NzT-ZT_OFF_PLOT],xerr=zT_widths[:NzT-ZT_OFF_PLOT]*0, fmt='ko',capsize=0, ms=6,lw=1) Ratio_for_Legend = plt.plot(zT_centers[:NzT-ZT_OFF_PLOT], Ratio[:NzT-ZT_OFF_PLOT],'ko',label='Data') Purity_Uncertainty = np.sqrt((pp_purity_Uncertainty/pp_Combined)**2 + (pPb_purity_Uncertainty/pPb_Combined)**2)*Ratio Efficiency_Uncertainty = np.ones(len(pPb_Combined))*0.056*math.sqrt(2)*Ratio Eta_Cor_Uncertainty = Eta_Correction_Uncertainty/Comb_Dict["p-Pb_Combined_FF"]*Ratio if (CorrectedP): Ratio_Systematic = np.sqrt(Purity_Uncertainty**2 + Efficiency_Uncertainty**2 + Eta_Cor_Uncertainty**2) Sys_Plot = plt.bar(zT_centers[:NzT-ZT_OFF_PLOT], Ratio_Systematic[:NzT-ZT_OFF_PLOT]+Ratio_Systematic[:NzT-ZT_OFF_PLOT], bottom=Ratio[:NzT-ZT_OFF_PLOT]-Ratio_Systematic[:NzT-ZT_OFF_PLOT], width=zT_widths[:NzT-ZT_OFF_PLOT]*2, align='center',color='black',alpha=0.25) ### ROOT LINEAR and CONSTANT FITS ### Ratio_TGraph = TGraphErrors() for izt in range (len(Ratio)-ZT_OFF_PLOT): Ratio_TGraph.SetPoint(izt,zT_centers[izt],Ratio[izt]) Ratio_TGraph.SetPointError(izt,0,Ratio_Error[izt]) Ratio_TGraph.Fit("pol0","S") f = Ratio_TGraph.GetFunction("pol0") chi2_red = f.GetChisquare()/f.GetNDF() pval = f.GetProb() p0 = f.GetParameter(0) p0e = f.GetParError(0) p0col = "grey" Show_Fits = True if (Show_Fits): sys_const = 0.19 #23% relative from purity + tracking plt.annotate("$c = {0:.2f} \pm {1:.2f} \pm {2:.2f}$".format(p0,p0e,sys_const), xy=(0.02, 0.15), xycoords='axes fraction', ha='left', va='top', color="black",fontsize=label_size,alpha=.9) plt.annotate(r"$p = %1.2f$"%(pval), xy=(0.02, 0.09), xycoords='axes fraction', ha='left', va='top', color="black",fontsize=label_size,alpha=.9) c_error = math.sqrt(p0e**2 + sys_const**2) plt.fill_between(np.arange(0,1.1,0.1), p0+c_error, p0-c_error,color=p0col,alpha=.3) ###LABELS/AXES### plt.axhline(y=1, color='k', linestyle='--') plt.xlabel("${z_\mathrm{T}} = p_\mathrm{T}^{\mathrm{h}}/p_\mathrm{T}^\gamma$",fontsize=axis_size-8,x=0.9) #plt.xlabel(r"varphi = $\varphi$, phi = $\phi$",fontsize = 30) plt.ylabel(r"$\frac{\mathrm{p-Pb}}{\mathrm{pp}}$",fontsize=axis_size,y=0.88) plt.ylim((-0.0, 2.8)) plt.xticks(fontsize=20) plt.yticks([0.5,1.0,1.5,2.0,2.5],fontsize=20) plt.yticks(np.arange(0,3,0.25),["","","0.5","","1.0","","1.5","","2.0","","2.5"]) #Ratio_Plot.yaxis.set_minor_locator(AutoMinorLocator(1)) plt.xlim(0,0.65) plt.tick_params(which='both',direction='in',right=True,bottom=True,top=True,length=10) plt.tick_params(which='both',direction='in',top=True,length=5) plt.fill_between(QGP_zt,QGP_IpPb_LowAll,QGP_IpPb_HighAll,label="QGP Droplet",color='orange') plt.plot(CNM_zt,CNM_IpPb,color='red',label="CNM Model",linewidth=2) leg = plt.legend(loc='upper right',fontsize=20,frameon=False) leg.set_title("ALICE, $\sqrt{s_{\mathrm{_{NN}}}} = $ 5.02 TeV") plt.setp(leg.get_title(),fontsize=24) plt.savefig("pics/%s/%s/Model_Comparisons_Ratio.pdf"%(Shower,description_string), bbox_inches = "tight") plt.show()
def showENC(self): tree1 = TTree() header = 'idX/i:vL/F:vH:A:D/i:R:W' first = True for f in self.dataFiles: if first: tree1.ReadFile(f, header) else: tree1.ReadFile(f) p1 = TProfile('p1', 'p1;#DeltaU [V];Prob', self.bins[0], tree1.GetMinimum('vH-vL') * 0.8, tree1.GetMaximum('vH-vL') * 1.2) tree1.Draw("D:(vH-vL)>>p1", "", "profE") ### change it to tgraph g1 = TGraphErrors() for i in range(p1.GetNbinsX() + 2): N = p1.GetBinEntries(i) if N > 0: print i, N, p1.GetXaxis().GetBinCenter(i), p1.GetBinContent( i), p1.GetBinError(i) n = g1.GetN() g1.SetPoint(n, p1.GetXaxis().GetBinCenter(i), p1.GetBinContent(i)) g1.SetPointError(n, 0, p1.GetBinError(i)) p1.Draw("axis") g1.Draw('Psame') fun1 = TF1('fun1', '0.5*(1+TMath::Erf((x-[0])/(TMath::Sqrt(2)*[1])))', 0.05, 0.3) fun1.SetParameter(0, 0.155) fun1.SetParameter(1, 0.005) g1.Fit(fun1) fun1a = g1.GetFunction('fun1') fun1a.SetLineColor(2) v0 = fun1a.GetParameter(0) e0 = fun1a.GetParError(0) v1 = fun1a.GetParameter(1) e1 = fun1a.GetParError(1) print v0, v1 fUnit = 1000. self.lt.DrawLatexNDC( 0.185, 0.89, '#mu = {0:.1f} #pm {1:.1f} mV'.format(v0 * fUnit, e0 * fUnit)) self.lt.DrawLatexNDC( 0.185, 0.84, '#sigma = {0:.1f} #pm {1:.1f} mV'.format(v1 * fUnit, e1 * fUnit)) if self.Info: self.lt.DrawLatexNDC(0.185, 0.6, self.Info) print 'TMath::Gaus(x,{0:.5f},{1:.5f})'.format(v0, v1) fun2 = TF1('gaus1', 'TMath::Gaus(x,{0:.5f},{1:.5f})'.format(v0, v1)) fun2.SetLineColor(4) fun2.SetLineStyle(2) fun2.Draw('same') lg = TLegend(0.7, 0.4, 0.95, 0.5) lg.SetFillStyle(0) lg.AddEntry(p1, 'Measurement', 'p') lg.AddEntry(fun1a, 'Fit', 'l') lg.AddEntry(fun2, 'Gaus', 'l') lg.Draw() waitRootCmdX()
def showENC(): fname1 = '/data/repos/Mic4Test_KC705/Software/Analysis/data/ENC/ENC_Chip5Col12_scan1.dat' tree1 = TTree() tree1.ReadFile( '/data/repos/Mic4Test_KC705/Software/Analysis/data/ENC/ENC_Chip5Col12_scan1.dat', 'idX/i:vL/F:vH:A:D/i:R:W') tree1.ReadFile( '/data/repos/Mic4Test_KC705/Software/Analysis/data/ENC/ENC_Chip5Col12_scan2_mod.dat' ) tree1.Show(500) p1 = TProfile('p1', 'p1;#DeltaU [V];Prob', 50, 0.12, 0.2) tree1.Draw("D:(vH-vL)>>p1", "", "profE") ### change it to tgraph g1 = TGraphErrors() for i in range(p1.GetNbinsX() + 2): N = p1.GetBinEntries(i) if N > 0: print i, N, p1.GetXaxis().GetBinCenter(i), p1.GetBinContent( i), p1.GetBinError(i) n = g1.GetN() g1.SetPoint(n, p1.GetXaxis().GetBinCenter(i), p1.GetBinContent(i)) g1.SetPointError(n, 0, p1.GetBinError(i)) # g1.SetMarkerColor(3) # g1.SetLineColor(3) p1.Draw("axis") g1.Draw('Psame') fun1 = TF1('fun1', '0.5*(1+TMath::Erf((x-[0])/(TMath::Sqrt(2)*[1])))', 0.05, 0.3) fun1.SetParameter(0, 0.155) fun1.SetParameter(1, 0.005) g1.Fit(fun1) fun1a = g1.GetFunction('fun1') # p1.Fit(fun1) # fun1a = p1.GetFunction('fun1') fun1a.SetLineColor(2) # p1.Draw("Esame") v0 = fun1a.GetParameter(0) e0 = fun1a.GetParError(0) v1 = fun1a.GetParameter(1) e1 = fun1a.GetParError(1) print v0, v1 fUnit = 1000. lt = TLatex() lt.DrawLatexNDC( 0.185, 0.89, '#mu = {0:.1f} #pm {1:.1f} mV'.format(v0 * fUnit, e0 * fUnit)) lt.DrawLatexNDC( 0.185, 0.84, '#sigma = {0:.1f} #pm {1:.1f} mV'.format(v1 * fUnit, e1 * fUnit)) print 'TMath::Gaus(x,{0:.5f},{1:.5f})'.format(v0, v1) fun2 = TF1('gaus1', 'TMath::Gaus(x,{0:.5f},{1:.5f})'.format(v0, v1)) fun2.SetLineColor(4) fun2.SetLineStyle(2) fun2.Draw('same') lg = TLegend(0.7, 0.4, 0.95, 0.5) lg.SetFillStyle(0) lg.AddEntry(p1, 'Measurement', 'p') lg.AddEntry(fun1a, 'Fit', 'l') lg.AddEntry(fun2, 'Gaus', 'l') lg.Draw() waitRootCmdX()
graph1_4ntr.GetYaxis().SetRangeUser(59., 69.) graph1_4ntr.GetYaxis().SetTitle("Mean value") graph1_4ntr.GetXaxis().SetTitle("Top M(GeV)") graph1_4ntr.Draw("AP") graph1_4ntr.SetTitle("Mean value of the inv.mass vs top mass") graph2_4ntr.SetLineColor(2) graph2_4ntr.SetMarkerColor(2) graph2_4ntr.Draw("P") # fit graph1.Fit("pol1") graph2.Fit("pol1") pol1 = TF1() pol1 = graph1.GetFunction("pol1") pol2 = TF1() pol2 = graph2.GetFunction("pol1") a0 = str(round(pol1.GetParameter(0), 2)) a1 = str(round(pol1.GetParameter(1), 2)) b0 = str(round(pol2.GetParameter(0), 2)) b1 = str(round(pol2.GetParameter(1), 2)) c2.cd() leg2 = TLegend(0.7, 0.15, 1, 0.25) leg2.SetHeader("Fits:") ##NEEDS TO BE CHANGED leg2.AddEntry(pol1, "deltar: y = " + a0 + " + " + a1 + "x", "ll") leg2.AddEntry(pol2, "minmass: y = " + b0 + " + " + b1 + "x", "ll") leg2.Draw()
def collectPerDirectionBx(options): """Fit data in both directions of a scan""" nSteps = len(O['nominalPos'][options['scan']]) for i in range(nSteps - 1): if O['nominalPos'][options['scan']][i+1] == \ O['nominalPos'][options['scan']][i]: break else: for i in range(nSteps - 1): if abs(O['nominalPos'][options['scan']][i+1] - \ O['nominalPos'][options['scan']][i]) < 10.0: break else: raise RuntimeError('Could not find change of direction.') if 'nominalPos' in options: nominalPos = options['nominalPos'] else: nominalPos = O['nominalPos'][options['scan']] oldname = options['scan'] + '_' + options['name'] + options['fitted'] if options.get('newname', False): newname = options['scan'] + '_' + options['newname'] + \ options['fitted'] else: newname = oldname if options.get('method', False): oldname += '_' + options['method'] newname += '_' + options['method'] newname += '_collected' f = openRootFileR(oldname) g = openRootFileW(newname) for bx in options['crossings']: average = [0 for j in range(nSteps)] averror = [0 for j in range(nSteps)] for step in range(nSteps): print '<<< Access data from:', options['scan'], bx, 'step', step histname = plotName(oldname+'_bx'+str(bx)+'_step'+str(step), \ timestamp=False) hist = f.Get(histname) if options['custom']: average[step], averror[step] = options['custom'](hist, step) else: average[step] = hist.GetMean() averror[step] = hist.GetMeanError() plotname = plotName(newname + '_bx' + str(bx), timestamp=False) plottitl = plotTitle(options['scan'] + ' BX ' + str(bx)) print '<<< Create plot:', plotname graphs = TMultiGraph(plotname, plottitl) residuals = TMultiGraph(plotname + '_residuals', '') for n, rnge in zip([i+1, nSteps-i-1], [lambda l: l[:i+1], \ lambda l: l[i+1:]]): graph = TGraphErrors(n, \ array('d', [options['x'](a) for a in rnge(nominalPos)]), \ array('d', [options['y'](a) for a in rnge(average)]), \ array('d', [0]*n), \ array('d', [options['e'](a) for a in rnge(averror)])) graph.Fit(options['fit']) residual = TGraphErrors(n, \ array('d', [options['x'](a) for a in rnge(nominalPos)]), \ array('d', [options['y'](a) - graph.GetFunction( \ options['fit']).Eval(options['x'](b)) for a, b \ in zip(rnge(average), rnge(nominalPos))]), array('d', [0]*n), \ array('d', [options['e'](a) for a in rnge(averror)])) graphs.Add(graph) residuals.Add(residual) graphs.Write('', TObject.kOverwrite) residuals.Write('', TObject.kOverwrite) closeRootFile(g, newname) closeRootFile(f, oldname)
def create_fastgrapherror(Fastscinenergy, Fastcherenergy, rmsScin, rmsCher, fem, rmsfem, PrimaryParticleEnergy): """Function to perform ROOT graphs and compute he values""" #How many graph points n = len(Fastscinenergy) TGraphfasthescin = TGraphErrors(n, fem, Fastscinenergy, rmsfem, rmsScin) TGraphfasthecher = TGraphErrors(n, fem, Fastcherenergy, rmsfem, rmsCher) #Draw + DrawOptions, Fit + parameter estimation Style = gStyle Style.SetOptFit(1) Style.SetOptStat(0) #Do not show statistics XAxis = TGraphfasthescin.GetXaxis() #TGraphfasthescin TGraphfasthescin.SetMarkerColor(4) TGraphfasthescin.SetMarkerStyle(1) TGraphfasthescin.SetMarkerSize(1) XAxis.SetTitle("fem") XAxis.SetLimits(0.0,1.0) YAxis = TGraphfasthescin.GetYaxis() YAxis.SetTitle("Energy scin (MeV)") YAxis.SetRange(int(0.0),int(float(PrimaryParticleEnergy)+10000.0)) TGraphfasthescin.Fit("pol1") myfit = TGraphfasthescin.GetFunction("pol1") Fasthescin = myfit.GetParameter(0)/PrimaryParticleEnergy Fasthescinerror = myfit.GetParError(0)/PrimaryParticleEnergy Fasthescin2 = (PrimaryParticleEnergy - myfit.GetParameter(1))/PrimaryParticleEnergy TGraphfasthescin.SetTitle("") TGraphfasthescin.Draw("AP") gPad.SaveAs("Fasthescin-pol1fit.pdf") gPad.Close() combinedfit = TF1("combinedfit", '(x)*([1]-[0]*[1])+[0]*[1]', 0, max(fem)) combinedfit.FixParameter(1, PrimaryParticleEnergy) TGraphfasthescin.Fit("combinedfit") hes = combinedfit.GetParameter(0) heserror = combinedfit.GetParError(0) TGraphfasthescin.Draw("AP") gPad.SaveAs("Fasthescin.pdf") gPad.Close() XAxis = TGraphfasthecher.GetXaxis() #TGraphfasthecher TGraphfasthecher.SetMarkerColor(4) TGraphfasthecher.SetMarkerStyle(1) TGraphfasthecher.SetMarkerSize(1) XAxis.SetTitle("fem") XAxis.SetLimits(0.0,1.0) YAxis = TGraphfasthecher.GetYaxis() YAxis.SetTitle("Energy Cher (MeV)") YAxis.SetRange(int(0.0),int(float(PrimaryParticleEnergy)+10000.0)) TGraphfasthecher.Fit("pol1") myfit = TGraphfasthecher.GetFunction("pol1") Fasthecher = myfit.GetParameter(0)/PrimaryParticleEnergy Fasthechererror = myfit.GetParError(0)/PrimaryParticleEnergy Fasthecher2 = (PrimaryParticleEnergy - myfit.GetParameter(1))/PrimaryParticleEnergy TGraphfasthecher.SetTitle("") TGraphfasthecher.Draw("AP") gPad.SaveAs("Fasthecher-pol1fit.pdf") gPad.Close() TGraphfasthecher.Fit("combinedfit") hec = combinedfit.GetParameter(0) hecerror = combinedfit.GetParError(0) TGraphfasthecher.Draw("AP") gPad.SaveAs("Fasthecher.pdf") gPad.Close() return Fasthescin, Fasthecher, Fasthescinerror, Fasthechererror, Fasthescin2, Fasthecher2, hes, hec, heserror, hecerror
c2.Divide(2,1,0.01,0.01) # fit graph1.Fit("pol1") graph2.Fit("pol1") graph1_t.Fit("pol1") graph2_t.Fit("pol1") graph1_tup.Fit("pol1") graph2_tup.Fit("pol1") line1.SetLineStyle(7) line2.SetLineStyle(7) pol1=graph1.GetFunction("pol1") pol2=graph2.GetFunction("pol1") pol1.SetLineColor(4) pol2.SetLineColor(4) pol1.SetLineStyle(2) pol2.SetLineStyle(2) graph1_scaledown.SetLineColor(6) graph2_scaledown.SetLineColor(6) graph1_scaledown.SetMarkerColor(6) graph2_scaledown.SetMarkerColor(6) graph1_scaledown.SetMarkerStyle(21) graph2_scaledown.SetMarkerStyle(21) graph1_scaledown.SetMarkerSize(1.0) graph2_scaledown.SetMarkerSize(1.0) graph1_scaleup.SetLineColor(2)
yerr[i] = ts_correct[i].GetMeanError() graph1.SetPoint(i, x[i], y[i]) graph1.SetPointError(i, 0, yerr[i]) c2.cd() graph1.Draw("AP") graph1.GetYaxis().SetTitle("Mean value") graph1.GetXaxis().SetTitle("Top M(GeV)") graph1.Draw("AP") graph1.Fit("pol1") pol1=TF1() pol1=graph1.GetFunction("pol1") a0=str(round(pol1.GetParameter(0),2)) a1=str(round(pol1.GetParameter(1),2)) pol1.SetLineColor(1) graph1.SetMarkerColor(1) graph1.SetLineColor(1) leg2 = TLegend(0.7,0.15,1,0.25) leg2.SetHeader("Fits:") ##NEEDS TO BE CHANGED leg2.AddEntry(pol1, "deltar: y = " + a0 + " + " + a1 + "x", "ll") leg2.Draw() # part for relative ratios # part for relative ratios # part for relative ratios