Back to home page

sPhenix code displayed by LXR

 
 

    


File indexing completed on 2025-12-16 09:18:05

0001 import ROOT
0002 
0003 # 打开文件
0004 infile = ROOT.TFile.Open("outputFile/pt_relative_error_combined.root")
0005 if not infile or infile.IsZombie():
0006     print("❌ Cannot open ROOT file!")
0007     exit(1)
0008 
0009 # 读取 TH1D
0010 hist1d = infile.Get("h_relerr_combined")
0011 if not hist1d:
0012     print("❌ Cannot find h_relerr_combined!")
0013     infile.Close()
0014     exit(1)
0015 
0016 # 创建画布
0017 c1 = ROOT.TCanvas("c1", "RelErr Combined", 1000, 1000)
0018 
0019 # 高斯拟合
0020 fit_result = hist1d.Fit("gaus", "S", "", -0.1, 0.1)  # "S" 静默拟合
0021 gaus_func = hist1d.GetFunction("gaus")
0022 mean = gaus_func.GetParameter(1)
0023 sigma = gaus_func.GetParameter(2)
0024 
0025 # chi2 / ndf
0026 chi2 = gaus_func.GetChisquare()
0027 ndf = gaus_func.GetNDF()
0028 chi2_ndf = chi2 / ndf if ndf != 0 else 0
0029 
0030 # 打印
0031 print(f"Gaussian fit result:")
0032 print(f"  mean   = {mean:.4f}")
0033 print(f"  sigma  = {sigma:.4f}")
0034 print(f"  chi2/ndf = {chi2:.2f} / {ndf} = {chi2_ndf:.4f}")
0035 
0036 # 画图
0037 hist1d.Draw()
0038 gaus_func.SetLineColor(ROOT.kRed)
0039 gaus_func.SetLineWidth(2)
0040 gaus_func.Draw("same")
0041 
0042 # 加标注
0043 latex = ROOT.TLatex()
0044 latex.SetNDC()
0045 latex.SetTextSize(0.04)
0046 x_pos = 0.6
0047 y_pos = 0.75
0048 latex.DrawLatex(x_pos, y_pos,     f"#mu = {mean:.4f}")
0049 latex.DrawLatex(x_pos, y_pos-0.05, f"#sigma = {sigma:.4f}")
0050 latex.DrawLatex(x_pos, y_pos-0.10, f"#chi^{{2}}/ndf = {chi2_ndf:.4f}")
0051 
0052 # 保存
0053 c1.SaveAs("outputFile/h_relerr_combined_fit_new.png")
0054 
0055 # 关闭文件
0056 infile.Close()
0057 
0058 print("✅ Fit plot saved to outputFile/h_relerr_combined_fit_new.png")