You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

866 lines
32 KiB

8 months ago
  1. # flake8: noqa
  2. """
  3. Script for accessing histograms of reconstructible and
  4. reconstructed tracks for different tracking categories
  5. and trackers.
  6. The efficency is calculated usig TGraphAsymmErrors
  7. and Bayesian error bars
  8. author: Furkan Cetin
  9. date: 10/2023
  10. Takes data from Recent_get_resolution_and_eff_data.py and calculates efficiencies
  11. python scripts/CompareEfficiency.py
  12. --filename data/res_and_effs_B.root data/resolutions_and_effs_Bd2KstEE_MDmaster.root
  13. --trackers Match --label new old --outfile data/compare_effs.root
  14. python scripts/CompareEfficiency.py --filename data/resolutions_and_effs_D_default_weights.root data/resolutions_and_effs_D_with_electron_weights_as_residual.root --trackers BestLong Seed --label default new --outfile data_results/CompareEfficiencyDDefaultResidual.root
  15. recreate: defaultresidual, electronresidual, residual
  16. """
  17. import os, sys
  18. import argparse
  19. from ROOT import TMultiGraph, TLatex, TCanvas, TFile, TGaxis
  20. from ROOT import (
  21. kGreen,
  22. kBlue,
  23. kBlack,
  24. kAzure,
  25. kGray,
  26. kOrange,
  27. kMagenta,
  28. kCyan,
  29. kViolet,
  30. kTeal,
  31. kRed,
  32. )
  33. from ROOT import gROOT, gStyle, gPad
  34. from ROOT import TEfficiency
  35. from array import array
  36. gROOT.SetBatch(True)
  37. from utils.components import unique_name_ext_re, findRootObjByName
  38. def getEfficiencyHistoNames():
  39. return ["p", "pt", "phi", "eta", "nPV"]
  40. def getTrackers(trackers):
  41. return trackers
  42. def getCompCuts(compare_cuts):
  43. return compare_cuts
  44. # data/resolutions_and_effs_Bd2KstEE_MDmaster.root:Track/...
  45. def getOriginFolders():
  46. basedict = {
  47. "Velo": {},
  48. "Upstream": {},
  49. "Forward": {},
  50. "Match": {},
  51. "MergedMatch": {},
  52. "DefaultMatch": {},
  53. "BestLong": {},
  54. "Seed": {},
  55. }
  56. # evtl anpassen wenn die folders anders heissen
  57. basedict["Velo"]["folder"] = "VeloTrackChecker/"
  58. basedict["Upstream"]["folder"] = "UpstreamTrackChecker/"
  59. basedict["Forward"]["folder"] = "ForwardTrackChecker" + unique_name_ext_re() + "/"
  60. basedict["Match"]["folder"] = "MatchTrackChecker" + unique_name_ext_re() + "/"
  61. basedict["MergedMatch"]["folder"] = (
  62. "MergedMatchTrackChecker" + unique_name_ext_re() + "/"
  63. )
  64. basedict["DefaultMatch"]["folder"] = (
  65. "DefaultMatchTrackChecker" + unique_name_ext_re() + "/"
  66. )
  67. basedict["BestLong"]["folder"] = "BestLongTrackChecker" + unique_name_ext_re() + "/"
  68. basedict["Seed"]["folder"] = "SeedTrackChecker" + unique_name_ext_re() + "/"
  69. # basedict["Forward"]["folder"] = "ForwardTrackChecker_7a0dbfa7/"
  70. # basedict["Match"]["folder"] = "MatchTrackChecker_29e3152a/"
  71. # basedict["BestLong"]["folder"] = "BestLongTrackChecker_4ddacce1/"
  72. # basedict["Seed"]["folder"] = "SeedTrackChecker_1b1d5575/"
  73. return basedict
  74. def getTrackNames():
  75. basedict = {
  76. "Velo": {},
  77. "Upstream": {},
  78. "Forward": {},
  79. "Match": {},
  80. "MergedMatch": {},
  81. "DefaultMatch": {},
  82. "BestLong": {},
  83. "Seed": {},
  84. }
  85. basedict["Velo"] = "Velo"
  86. basedict["Upstream"] = "VeloUT"
  87. basedict["Forward"] = "Forward"
  88. basedict["Match"] = "Match"
  89. basedict["MergedMatch"] = "MergedMatch"
  90. basedict["DefaultMatch"] = "DefaultMatch"
  91. basedict["BestLong"] = "BestLong"
  92. basedict["Seed"] = "Seed"
  93. return basedict
  94. def get_colors():
  95. return [kBlack, kAzure, kGreen + 2, kMagenta + 2, kRed, kCyan + 2, kGray + 1]
  96. def get_elec_colors():
  97. return [
  98. kGray + 2,
  99. kBlue - 3,
  100. kRed + 1,
  101. kGreen + 1,
  102. kViolet,
  103. kTeal - 1,
  104. kOrange + 8,
  105. kGray + 1,
  106. ]
  107. def get_markers():
  108. return [20, 21, 24, 25, 22, 23, 26, 32]
  109. def get_fillstyles():
  110. return [1003, 3001, 3002, 3325, 3144, 3244, 3444]
  111. def getGhostHistoNames():
  112. basedict = {
  113. # "Velo": {},
  114. # "Upstream": {},
  115. "Forward": {},
  116. "Match": {},
  117. "MergedMatch": {},
  118. "DefaultMatch": {},
  119. "BestLong": {},
  120. "Seed": {},
  121. }
  122. basedict["Velo"] = ["eta", "nPV"]
  123. basedict["Upstream"] = ["eta", "p", "pt", "nPV"]
  124. basedict["Forward"] = ["eta", "p", "pt", "nPV"]
  125. basedict["Match"] = ["eta", "p", "pt", "nPV"]
  126. basedict["MergedMatch"] = basedict["Match"]
  127. basedict["DefaultMatch"] = basedict["Match"]
  128. basedict["BestLong"] = ["eta", "p", "pt", "nPV"]
  129. basedict["Seed"] = ["eta", "p", "pt", "nPV"]
  130. return basedict
  131. def argument_parser():
  132. parser = argparse.ArgumentParser(description="location of the tuple file")
  133. parser.add_argument(
  134. "--filename",
  135. type=str,
  136. default=["data/resolutions_and_effs_B.root"],
  137. nargs="+",
  138. help="input files, including path",
  139. )
  140. parser.add_argument(
  141. "--outfile",
  142. type=str,
  143. default="data_results/compare_efficiency.root",
  144. help="output file",
  145. )
  146. parser.add_argument(
  147. "--trackers",
  148. type=str,
  149. nargs="+",
  150. default=["Match", "BestLong", "Seed"], # Forward
  151. help="Trackers to plot.",
  152. )
  153. parser.add_argument(
  154. "--label",
  155. nargs="+",
  156. default=["Eff"],
  157. help="label for files",
  158. )
  159. parser.add_argument(
  160. "--savepdf",
  161. action="store_true",
  162. help="save plots in pdf format",
  163. )
  164. parser.add_argument(
  165. "--compare",
  166. default=True,
  167. action="store_true",
  168. help="compare efficiencies",
  169. )
  170. parser.add_argument(
  171. "--compare-cuts",
  172. type=str,
  173. nargs="+",
  174. default=["long", "long_fromB", "long_fromB_P>5GeV"],
  175. help="which cuts get compared",
  176. )
  177. parser.add_argument(
  178. "--plot-electrons",
  179. default=True,
  180. action="store_true",
  181. help="plot electrons",
  182. )
  183. parser.add_argument(
  184. "--plot-electrons-only",
  185. action="store_true",
  186. help="plot only electrons",
  187. )
  188. parser.add_argument(
  189. "--plot-velo",
  190. action="store_true",
  191. help="plot using momentum at EndVelo",
  192. )
  193. return parser
  194. def get_files(tf, filename, label):
  195. for i, f in enumerate(filename):
  196. tf[label[i]] = TFile(f, "read")
  197. return tf
  198. def get_nicer_var_string(var: str):
  199. nice_vars = dict(pt="p_{T}", eta="#eta", phi="#phi")
  200. try:
  201. return nice_vars[var]
  202. except KeyError:
  203. return var
  204. def get_eff(eff, hist, tf, histoName, label, var):
  205. eff = {}
  206. hist = {}
  207. var = get_nicer_var_string(var)
  208. for i, lab in enumerate(label):
  209. numeratorName = histoName + "_reconstructed"
  210. numerator = findRootObjByName(tf[lab], numeratorName)
  211. denominatorName = histoName + "_reconstructible"
  212. denominator = findRootObjByName(tf[lab], denominatorName)
  213. if numerator.GetEntries() == 0 or denominator.GetEntries() == 0:
  214. continue
  215. teff = TEfficiency(numerator, denominator)
  216. teff.SetStatisticOption(7)
  217. eff[lab] = teff.CreateGraph()
  218. eff[lab].SetName(lab)
  219. eff[lab].SetTitle(lab)
  220. if histoName.find("Forward") != -1:
  221. if histoName.find("electron") != -1:
  222. eff[lab].SetTitle(lab + " Forward, e^{-}")
  223. else:
  224. eff[lab].SetTitle(lab + " Forward")
  225. if histoName.find("Merged") != -1:
  226. if histoName.find("electron") != -1:
  227. eff[lab].SetTitle(lab + " MergedMatch, e^{-}")
  228. else:
  229. eff[lab].SetTitle(lab + " MergedMatch")
  230. elif histoName.find("DefaultMatch") != -1:
  231. if histoName.find("electron") != -1:
  232. eff[lab].SetTitle(lab + " DefaultMatch, e^{-}")
  233. else:
  234. eff[lab].SetTitle(lab + " DefaultMatch")
  235. elif histoName.find("Match") != -1:
  236. if histoName.find("electron") != -1:
  237. eff[lab].SetTitle(lab + " Match, e^{-}")
  238. else:
  239. eff[lab].SetTitle(lab + " Match")
  240. if histoName.find("Seed") != -1:
  241. if histoName.find("electron") != -1:
  242. eff[lab].SetTitle(lab + " Seed, e^{-}")
  243. else:
  244. eff[lab].SetTitle(lab + " Seed")
  245. if histoName.find("BestLong") != -1:
  246. if histoName.find("electron") != -1:
  247. eff[lab].SetTitle(lab + " BestLong, e^{-}")
  248. else:
  249. eff[lab].SetTitle(lab + " BestLong")
  250. if histoName.find("EndVelo") != -1:
  251. eff[lab].SetTitle(eff[lab].GetTitle() + " EndVelo")
  252. hist[lab] = denominator.Clone()
  253. hist[lab].SetName("h_numerator_notElectrons")
  254. hist[lab].SetTitle(var + " distribution, not e^{-}")
  255. if histoName.find("strange") != -1:
  256. hist[lab].SetTitle(var + " distribution, stranges")
  257. if histoName.find("electron") != -1:
  258. hist[lab].SetTitle(var + " distribution, e^{-}")
  259. if histoName.find("EndVelo") != -1:
  260. hist[lab].SetTitle(hist[lab].GetTitle() + ", EndVelo")
  261. return eff, hist
  262. def get_ghost(eff, hist, tf, histoName, label):
  263. ghost = {}
  264. for i, lab in enumerate(label):
  265. numeratorName = histoName + "_Ghosts"
  266. denominatorName = histoName + "_Total"
  267. numerator = findRootObjByName(tf[lab], numeratorName)
  268. denominator = findRootObjByName(tf[lab], denominatorName)
  269. print("Numerator = " + numeratorName.replace(unique_name_ext_re(), ""))
  270. print("Denominator = " + denominatorName.replace(unique_name_ext_re(), ""))
  271. teff = TEfficiency(numerator, denominator)
  272. teff.SetStatisticOption(7)
  273. ghost[lab] = teff.CreateGraph()
  274. print(lab)
  275. ghost[lab].SetName(lab)
  276. return ghost
  277. def PrCheckerEfficiency(
  278. filename,
  279. outfile,
  280. label,
  281. trackers,
  282. savepdf,
  283. compare,
  284. compare_cuts,
  285. plot_electrons,
  286. plot_electrons_only,
  287. plot_velo,
  288. ):
  289. from utils.LHCbStyle import setLHCbStyle, set_style
  290. from utils.ConfigHistos import (
  291. efficiencyHistoDict,
  292. ghostHistoDict,
  293. categoriesDict,
  294. getCuts,
  295. )
  296. from utils.CompareConfigHistos import getCompare, getCompColors
  297. from utils.Legend import place_legend
  298. setLHCbStyle()
  299. markers = get_markers()
  300. colors = get_colors()
  301. elec_colors = get_elec_colors()
  302. styles = get_fillstyles()
  303. tf = {}
  304. tf = get_files(tf, filename, label)
  305. outputfile = TFile(outfile, "recreate")
  306. latex = TLatex()
  307. latex.SetNDC()
  308. latex.SetTextSize(0.05)
  309. efficiencyHistoDict = efficiencyHistoDict()
  310. efficiencyHistos = getEfficiencyHistoNames()
  311. ghostHistos = getGhostHistoNames()
  312. ghostHistoDict = ghostHistoDict()
  313. categories = categoriesDict()
  314. cuts = getCuts()
  315. compareDict = getCompare()
  316. compareCuts = getCompCuts(compare_cuts)
  317. compareColors = getCompColors()
  318. compareGhostHisto = ["eta", "p", "pt", "nPV"]
  319. trackers = getTrackers(trackers)
  320. folders = getOriginFolders()
  321. for tracker in trackers:
  322. outputfile.cd()
  323. trackerDir = outputfile.mkdir(tracker)
  324. trackerDir.cd()
  325. for cut in cuts[tracker]:
  326. cutDir = trackerDir.mkdir(cut)
  327. cutDir.cd()
  328. folder = folders[tracker]["folder"]
  329. print("folder: " + folder.replace(unique_name_ext_re(), ""))
  330. histoBaseName = "Track/" + folder + tracker + "/" + cut + "_"
  331. # calculate efficiency
  332. for histo in efficiencyHistos:
  333. canvastitle = (
  334. "efficiency_" + histo + ", " + categories[tracker][cut]["title"]
  335. )
  336. # get efficiency for not electrons category
  337. histoName = histoBaseName + "" + efficiencyHistoDict[histo]["variable"]
  338. print("not electrons: " + histoName.replace(unique_name_ext_re(), ""))
  339. eff = {}
  340. hist_den = {}
  341. eff, hist_den = get_eff(eff, hist_den, tf, histoName, label, histo)
  342. if categories[tracker][cut]["plotElectrons"] and plot_electrons:
  343. histoNameElec = (
  344. "Track/"
  345. + folder
  346. + tracker
  347. + "/"
  348. + categories[tracker][cut]["Electrons"]
  349. )
  350. histoName_e = (
  351. histoNameElec + "_" + efficiencyHistoDict[histo]["variable"]
  352. )
  353. print("electrons: " + histoName_e.replace(unique_name_ext_re(), ""))
  354. eff_elec = {}
  355. hist_elec = {}
  356. eff_elec, hist_elec = get_eff(
  357. eff_elec,
  358. hist_elec,
  359. tf,
  360. histoName_e,
  361. label,
  362. histo,
  363. )
  364. name = "efficiency_" + histo
  365. canvas = TCanvas(name, canvastitle)
  366. canvas.SetRightMargin(0.1)
  367. mg = TMultiGraph()
  368. for i, lab in enumerate(label):
  369. if not plot_electrons_only:
  370. mg.Add(eff[lab])
  371. set_style(eff[lab], colors[i], markers[i], styles[i])
  372. if categories[tracker][cut]["plotElectrons"] and plot_electrons:
  373. mg.Add(eff_elec[lab])
  374. set_style(eff_elec[lab], elec_colors[i], markers[i], styles[i])
  375. mg.Draw("AP")
  376. mg.GetYaxis().SetRangeUser(0, 1.05)
  377. xtitle = efficiencyHistoDict[histo]["xTitle"]
  378. unit_l = xtitle.split("[")
  379. if "]" in unit_l[-1]:
  380. unit = unit_l[-1].replace("]", "")
  381. else:
  382. unit = "a.u."
  383. print(unit)
  384. mg.GetXaxis().SetTitle(xtitle)
  385. mg.GetXaxis().SetTitleSize(0.06)
  386. mg.GetYaxis().SetTitle(
  387. "Efficiency of Long Tracks",
  388. ) # (" + str(round(hist_den[label[0]].GetBinWidth(1), 2)) + f"{unit})"+"^{-1}")
  389. mg.GetYaxis().SetTitleSize(0.06)
  390. mg.GetYaxis().SetTitleOffset(1.1)
  391. mg.GetXaxis().SetRangeUser(*efficiencyHistoDict[histo]["range"])
  392. mg.GetXaxis().SetNdivisions(10, 5, 0)
  393. mygray = 18
  394. myblue = kBlue - 9
  395. for i, lab in enumerate(label):
  396. rightmax = 1.05 * hist_den[lab].GetMaximum()
  397. scale = gPad.GetUymax() / rightmax
  398. hist_den[lab].Scale(scale)
  399. if categories[tracker][cut]["plotElectrons"] and plot_electrons:
  400. rightmax = 1.05 * hist_elec[lab].GetMaximum()
  401. scale = gPad.GetUymax() / rightmax
  402. hist_elec[lab].Scale(scale)
  403. if i == 0:
  404. if not plot_electrons_only:
  405. set_style(hist_den[lab], mygray, markers[i], styles[i])
  406. gStyle.SetPalette(2, array("i", [mygray - 1, myblue + 1]))
  407. hist_den[lab].Draw("HIST PLC SAME")
  408. if categories[tracker][cut]["plotElectrons"] and plot_electrons:
  409. set_style(hist_elec[lab], myblue, markers[i], styles[i])
  410. hist_elec[lab].SetFillColorAlpha(myblue, 0.35)
  411. hist_elec[lab].Draw("HIST PLC SAME")
  412. # else:
  413. # print(
  414. # "No distribution plotted for other labels.",
  415. # "Can be added by uncommenting the code below this print statement.",
  416. # )
  417. # # set_style(hist_den[lab], mygray, markers[i], styles[i])
  418. # # gStyle.SetPalette(2, array("i", [mygray - 1, myblue + 1]))
  419. # # hist_den[lab].Draw("HIST PLC SAME")
  420. # if histo == "p":
  421. # pos = [0.5, 0.3, 1.0, 0.6]
  422. # elif histo == "pt":
  423. # pos = [0.5, 0.3, 0.99, 0.6]
  424. # elif histo == "phi":
  425. # pos = [0.3, 0.25, 0.8, 0.55]
  426. # else:
  427. # pos = [0.3, 0.25, 0.8, 0.55]
  428. if histo == "p":
  429. pos = [0.5, 0.3, 1.0, 0.5] # [0.53, 0.4, 1.01, 0.71]
  430. elif histo == "pt":
  431. pos = [0.5, 0.3, 0.99, 0.5] # [0.5, 0.4, 0.98, 0.71]
  432. elif histo == "phi":
  433. pos = [0.4, 0.3, 0.9, 0.5]
  434. elif histo == "eta":
  435. pos = [0.5, 0.25, 1.0, 0.45]
  436. else:
  437. pos = [0.35, 0.25, 0.85, 0.45]
  438. legend = place_legend(
  439. canvas, *pos, header="LHCb Simulation", option="LPE"
  440. )
  441. for le in legend.GetListOfPrimitives():
  442. if "distribution" in le.GetLabel():
  443. le.SetOption("LF")
  444. legend.SetTextFont(132)
  445. legend.SetTextSize(0.04)
  446. legend.Draw()
  447. for lab in label:
  448. if not plot_electrons_only:
  449. eff[lab].Draw("P SAME")
  450. if categories[tracker][cut]["plotElectrons"] and plot_electrons:
  451. eff_elec[lab].Draw("P SAME")
  452. cutName = categories[tracker][cut]["title"]
  453. latex.DrawLatex(legend.GetX1() + 0.01, legend.GetY1() - 0.05, cutName)
  454. low = 0
  455. high = 1.05
  456. gPad.Update()
  457. axis = TGaxis(
  458. gPad.GetUxmax(),
  459. gPad.GetUymin(),
  460. gPad.GetUxmax(),
  461. gPad.GetUymax(),
  462. low,
  463. high,
  464. 510,
  465. "+U",
  466. )
  467. axis.SetTitleFont(132)
  468. axis.SetTitleSize(0.06)
  469. axis.SetTitleOffset(0.55)
  470. axis.SetTitle(
  471. "# Tracks " + get_nicer_var_string(histo) + " distribution [a.u.]",
  472. )
  473. axis.SetLabelSize(0)
  474. axis.Draw()
  475. # canvas.RedrawAxis()
  476. if savepdf and (1 == 0):
  477. filestypes = ["pdf"] # , "pdf", "eps", "C", "ps", "tex"]
  478. for ftype in filestypes:
  479. if not plot_electrons_only:
  480. canvasName = tracker + "_" + cut + "_" + histo + "." + ftype
  481. else:
  482. canvasName = (
  483. tracker
  484. + "_Electrons_"
  485. + cut
  486. + "_"
  487. + histo
  488. + "."
  489. + ftype
  490. )
  491. canvas.SaveAs("checks/" + canvasName)
  492. # canvas.SetRightMargin(0.05)
  493. canvas.Write()
  494. # calculate ghost rate
  495. print("\ncalculate ghost rate: ")
  496. histoBaseName = "Track/" + folder + tracker + "/"
  497. for histo in ghostHistos[tracker]:
  498. trackerDir.cd()
  499. title = "ghost_rate_vs_" + histo
  500. gPad.SetTicks()
  501. histoName = histoBaseName + ghostHistoDict[histo]["variable"]
  502. ghost = {}
  503. hist_den = {}
  504. ghost = get_ghost(ghost, hist_den, tf, histoName, label)
  505. canvas = TCanvas(title, title)
  506. mg = TMultiGraph()
  507. for i, lab in enumerate(label):
  508. mg.Add(ghost[lab])
  509. set_style(ghost[lab], colors[i], markers[2 * i], styles[i])
  510. xtitle = ghostHistoDict[histo]["xTitle"]
  511. mg.GetXaxis().SetTitle(xtitle)
  512. mg.GetYaxis().SetTitle("Fraction of fake tracks")
  513. mg.Draw("ap")
  514. mg.GetXaxis().SetTitleSize(0.06)
  515. mg.GetYaxis().SetTitleSize(0.06)
  516. mg.GetYaxis().SetTitleOffset(1.1)
  517. mg.GetXaxis().SetRangeUser(*efficiencyHistoDict[histo]["range"])
  518. mg.GetXaxis().SetNdivisions(10, 5, 0)
  519. # for lab in label:
  520. # ghost[lab].Draw("P SAME")
  521. if histo == "p":
  522. pos = [0.53, 0.4, 1.00, 0.71]
  523. elif histo == "pt":
  524. pos = [0.5, 0.4, 0.98, 0.71]
  525. elif histo == "eta":
  526. pos = [0.35, 0.6, 0.85, 0.9]
  527. elif histo == "phi":
  528. pos = [0.3, 0.3, 0.9, 0.6]
  529. else:
  530. pos = [0.4, 0.37, 0.80, 0.68]
  531. legend = place_legend(canvas, *pos, header="LHCb Simulation", option="LPE")
  532. legend.SetTextFont(132)
  533. legend.SetTextSize(0.04)
  534. legend.Draw()
  535. # if histo != "nPV":
  536. # latex.DrawLatex(0.7, 0.85, "LHCb simulation")
  537. # else:
  538. # latex.DrawLatex(0.2, 0.85, "LHCb simulation")
  539. # mg.GetYaxis().SetRangeUser(0, 0.4)
  540. if histo == "eta":
  541. mg.GetYaxis().SetRangeUser(0, 0.4)
  542. # track_name = names[tracker] + " tracks"
  543. # latex.DrawLatex(0.7, 0.75, track_name)
  544. # canvas.PlaceLegend()
  545. if savepdf and (1 == 0):
  546. filestypes = ["pdf"] # , "pdf", "eps", "C", "ps", "tex"]
  547. for ftype in filestypes:
  548. canvas.SaveAs(
  549. "checks/" + tracker + "_ghost_rate_" + histo + "." + ftype,
  550. )
  551. canvas.Write()
  552. #
  553. # Compare electron efficiencies of different trackers
  554. #
  555. plot_electrons_only = True
  556. if compare:
  557. print("\nCompare Efficiencies: ")
  558. outputfile.cd()
  559. for jcut in compareCuts: # [long, long_fromB, long_fromB_P>5GeV]
  560. compareDir = outputfile.mkdir("compare_" + jcut)
  561. compareDir.cd()
  562. for histo in efficiencyHistos: # [p, pt, phi, eta, nPV]
  563. canvastitle = "efficiency_" + histo + "_" + jcut
  564. name = "efficiency_" + histo + "_" + jcut
  565. canvas = TCanvas(name, canvastitle)
  566. canvas.SetRightMargin(0.1)
  567. mg = TMultiGraph()
  568. dist_eff = {}
  569. dist_hist_den = {}
  570. dist_eff_elec = {}
  571. dist_hist_elec = {}
  572. First = True
  573. dist_tracker = ""
  574. markeritr = 0
  575. for tracker in trackers: # [BestLong, Forward, Match, Seed]
  576. cut = compareDict[jcut][tracker]
  577. folder = folders[tracker]["folder"]
  578. print("folder: " + folder.replace(unique_name_ext_re(), ""))
  579. jcolor = compareColors[tracker]
  580. histoName = (
  581. "Track/"
  582. + folder
  583. + tracker
  584. + "/"
  585. + cut
  586. + "_"
  587. + ""
  588. + efficiencyHistoDict[histo]["variable"]
  589. )
  590. print(
  591. "not electrons: " + histoName.replace(unique_name_ext_re(), "")
  592. )
  593. eff = {}
  594. hist_den = {}
  595. eff, hist_den = get_eff(eff, hist_den, tf, histoName, label, histo)
  596. if categories[tracker][cut]["plotElectrons"] and plot_electrons:
  597. histoNameElec = (
  598. "Track/"
  599. + folder
  600. + tracker
  601. + "/"
  602. + categories[tracker][cut]["Electrons"]
  603. )
  604. histoName_e = (
  605. histoNameElec + "_" + efficiencyHistoDict[histo]["variable"]
  606. )
  607. print(
  608. "electrons: "
  609. + histoName_e.replace(unique_name_ext_re(), "")
  610. )
  611. eff_elec = {}
  612. hist_elec = {}
  613. eff_elec, hist_elec = get_eff(
  614. eff_elec,
  615. hist_elec,
  616. tf,
  617. histoName_e,
  618. label,
  619. histo,
  620. )
  621. if First:
  622. dist_eff_elec = eff_elec
  623. dist_hist_elec = hist_elec
  624. if First:
  625. dist_tracker = tracker
  626. dist_eff = eff
  627. dist_hist_den = hist_den
  628. First = False
  629. seeditr = 0
  630. for i, lab in enumerate(label):
  631. if categories[tracker][cut]["plotElectrons"] and plot_electrons:
  632. if (tracker == "Seed") and (seeditr != 0):
  633. continue
  634. if tracker == "Seed":
  635. seeditr += 1
  636. mg.Add(eff_elec[lab])
  637. set_style(
  638. eff_elec[lab],
  639. colors[jcolor],
  640. markers[i + markeritr],
  641. styles[i],
  642. )
  643. else:
  644. mg.Add(eff_elec[lab])
  645. set_style(
  646. eff_elec[lab],
  647. elec_colors[jcolor + markeritr],
  648. markers[i + markeritr],
  649. styles[i],
  650. )
  651. markeritr = markeritr + 1
  652. # set_style(
  653. # eff_elec[lab], colors[jcolor], markers[i], styles[i]
  654. # )
  655. markeritr = 0
  656. mg.Draw("AP")
  657. mg.GetYaxis().SetRangeUser(0, 1.05)
  658. xtitle = efficiencyHistoDict[histo]["xTitle"]
  659. unit_l = xtitle.split("[")
  660. if "]" in unit_l[-1]:
  661. unit = unit_l[-1].replace("]", "")
  662. else:
  663. unit = "a.u."
  664. print(unit)
  665. mg.GetXaxis().SetTitle(xtitle)
  666. mg.GetXaxis().SetTitleSize(0.06)
  667. mg.GetYaxis().SetTitle(
  668. "Efficiency of Long Tracks",
  669. ) # (" + str(round(hist_den[label[0]].GetBinWidth(1), 2)) + f"{unit})"+"^{-1}")
  670. mg.GetYaxis().SetTitleSize(0.06)
  671. mg.GetYaxis().SetTitleOffset(1.1)
  672. mg.GetXaxis().SetRangeUser(*efficiencyHistoDict[histo]["range"])
  673. mg.GetXaxis().SetNdivisions(10, 5, 0)
  674. mygray = 16
  675. myblue = kBlue - 7
  676. dist_cut = compareDict[jcut][dist_tracker]
  677. for i, lab in enumerate(label):
  678. rightmax = 1.05 * dist_hist_den[lab].GetMaximum()
  679. scale = gPad.GetUymax() / rightmax
  680. dist_hist_den[lab].Scale(scale)
  681. if (
  682. categories[dist_tracker][dist_cut]["plotElectrons"]
  683. and plot_electrons
  684. ):
  685. rightmax = 1.05 * dist_hist_elec[lab].GetMaximum()
  686. scale = gPad.GetUymax() / rightmax
  687. dist_hist_elec[lab].Scale(scale)
  688. if i == len(label) - 1:
  689. if not plot_electrons_only:
  690. set_style(dist_hist_den[lab], mygray, markers[i], styles[i])
  691. # gStyle.SetPalette(2, array("i", [mygray - 1, myblue + 1]))
  692. dist_hist_den[lab].SetFillColorAlpha(mygray, 0.5)
  693. dist_hist_den[lab].Draw("HIST PLC SAME")
  694. if (
  695. categories[dist_tracker][dist_cut]["plotElectrons"]
  696. and plot_electrons
  697. ):
  698. set_style(
  699. dist_hist_elec[lab], mygray, markers[i], styles[i]
  700. )
  701. # gStyle.SetPalette(2, array("i", [mygray - 1, myblue + 1]))
  702. # dist_hist_elec[lab].SetFillColor(myblue)
  703. dist_hist_elec[lab].SetFillColorAlpha(myblue, 0.5)
  704. dist_hist_elec[lab].Draw("HIST PLC SAME")
  705. # else:
  706. # print(
  707. # "No distribution plotted for other labels.",
  708. # "Can be added by uncommenting the code below this print statement.",
  709. # )
  710. # set_style(dist_hist_den[lab], mygray, markers[i], styles[i])
  711. # gStyle.SetPalette(2, array("i", [mygray - 1, myblue + 1]))
  712. # dist_hist_den[lab].Draw("HIST PLC SAME")
  713. if histo == "p":
  714. pos = [0.5, 0.3, 1.0, 0.5] # [0.53, 0.4, 1.01, 0.71]
  715. elif histo == "pt":
  716. pos = [0.5, 0.3, 0.99, 0.5] # [0.5, 0.4, 0.98, 0.71]
  717. elif histo == "phi":
  718. pos = [0.4, 0.3, 0.9, 0.5]
  719. elif histo == "eta":
  720. pos = [0.5, 0.25, 1.0, 0.45]
  721. else:
  722. pos = [0.35, 0.25, 0.85, 0.45]
  723. legend = place_legend(
  724. canvas, *pos, header="LHCb Simulation", option="LPE"
  725. )
  726. for le in legend.GetListOfPrimitives():
  727. if "distribution" in le.GetLabel():
  728. le.SetOption("LF")
  729. legend.SetTextFont(132)
  730. legend.SetTextSize(0.04)
  731. legend.Draw()
  732. for lab in label:
  733. if not plot_electrons_only:
  734. dist_eff[lab].Draw("P SAME")
  735. if categories[tracker][cut]["plotElectrons"] and plot_electrons:
  736. dist_eff_elec[lab].Draw("P SAME")
  737. cutName = categories[tracker][cut]["title"]
  738. latex.DrawLatex(legend.GetX1() + 0.01, legend.GetY1() - 0.05, cutName)
  739. low = 0
  740. high = 1.05
  741. gPad.Update()
  742. axis = TGaxis(
  743. gPad.GetUxmax(),
  744. gPad.GetUymin(),
  745. gPad.GetUxmax(),
  746. gPad.GetUymax(),
  747. low,
  748. high,
  749. 510,
  750. "+U",
  751. )
  752. axis.SetTitleFont(132)
  753. axis.SetTitleSize(0.06)
  754. axis.SetTitleOffset(0.55)
  755. axis.SetTitle(
  756. "# Tracks " + get_nicer_var_string(histo) + " distribution [a.u.]",
  757. )
  758. axis.SetLabelSize(0)
  759. axis.Draw()
  760. # canvas.Draw()
  761. canvas.RedrawAxis()
  762. # canvas.PlaceLegend()
  763. if savepdf:
  764. filestypes = ["pdf"] # , "png", "eps", "C", "ps", "tex"]
  765. for ftype in filestypes:
  766. if not plot_electrons_only:
  767. canvasName = "Compare_" + jcut + "_" + histo + "." + ftype
  768. else:
  769. canvasName = (
  770. "Compare_Electrons_" + jcut + "_" + histo + "." + ftype
  771. )
  772. canvas.SaveAs("checks/" + canvasName)
  773. # canvas.SetRightMargin(0.05)
  774. canvas.Write()
  775. outputfile.cd()
  776. outputfile.Write()
  777. outputfile.Close()
  778. if __name__ == "__main__":
  779. parser = argument_parser()
  780. args = parser.parse_args()
  781. PrCheckerEfficiency(**vars(args))