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.

970 lines
36 KiB

10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 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 - 4,
  100. kRed + 1,
  101. kGreen + 1,
  102. kViolet,
  103. kOrange - 8,
  104. kTeal - 1,
  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. return parser
  189. def get_files(tf, filename, label):
  190. for i, f in enumerate(filename):
  191. tf[label[i]] = TFile(f, "read")
  192. return tf
  193. def get_nicer_var_string(var: str):
  194. nice_vars = dict(pt="p_{T}", eta="#eta", phi="#phi")
  195. try:
  196. return nice_vars[var]
  197. except KeyError:
  198. return var
  199. def get_eff(eff, hist, tf, histoName, label, var):
  200. eff = {}
  201. hist = {}
  202. var = get_nicer_var_string(var)
  203. for i, lab in enumerate(label):
  204. numeratorName = histoName + "_reconstructed"
  205. numerator = findRootObjByName(tf[lab], numeratorName)
  206. denominatorName = histoName + "_reconstructible"
  207. denominator = findRootObjByName(tf[lab], denominatorName)
  208. if numerator.GetEntries() == 0 or denominator.GetEntries() == 0:
  209. continue
  210. teff = TEfficiency(numerator, denominator)
  211. teff.SetStatisticOption(7)
  212. eff[lab] = teff.CreateGraph()
  213. eff[lab].SetName(lab)
  214. eff[lab].SetTitle(lab)
  215. if histoName.find("Forward") != -1:
  216. if histoName.find("electron") != -1:
  217. eff[lab].SetTitle(lab + " Forward, e^{-}")
  218. else:
  219. eff[lab].SetTitle(lab + " Forward")
  220. if histoName.find("Merged") != -1:
  221. if histoName.find("electron") != -1:
  222. eff[lab].SetTitle(lab + " MergedMatch, e^{-}")
  223. else:
  224. eff[lab].SetTitle(lab + " MergedMatch")
  225. elif histoName.find("DefaultMatch") != -1:
  226. if histoName.find("electron") != -1:
  227. eff[lab].SetTitle(lab + " DefaultMatch, e^{-}")
  228. else:
  229. eff[lab].SetTitle(lab + " DefaultMatch")
  230. elif histoName.find("Match") != -1:
  231. if histoName.find("electron") != -1:
  232. eff[lab].SetTitle(lab + " Match, e^{-}")
  233. else:
  234. eff[lab].SetTitle(lab + " Match")
  235. if histoName.find("Seed") != -1:
  236. if histoName.find("electron") != -1:
  237. eff[lab].SetTitle(lab + " Seed, e^{-}")
  238. else:
  239. eff[lab].SetTitle(lab + " Seed")
  240. if histoName.find("BestLong") != -1:
  241. if histoName.find("electron") != -1:
  242. eff[lab].SetTitle(lab + " BestLong, e^{-}")
  243. else:
  244. eff[lab].SetTitle(lab + " BestLong")
  245. # eff[lab].SetTitle(lab + " not e^{-}")
  246. # if histoName.find("strange") != -1:
  247. # eff[lab].SetTitle(lab + " from stranges")
  248. # if histoName.find("electron") != -1:
  249. # eff[lab].SetTitle(lab + " e^{-}")
  250. hist[lab] = denominator.Clone()
  251. hist[lab].SetName("h_numerator_notElectrons")
  252. hist[lab].SetTitle(var + " distribution, not e^{-}")
  253. if histoName.find("strange") != -1:
  254. hist[lab].SetTitle(var + " distribution, stranges")
  255. if histoName.find("electron") != -1:
  256. hist[lab].SetTitle(var + " distribution, e^{-}")
  257. return eff, hist
  258. def get_ghost(eff, hist, tf, histoName, label):
  259. ghost = {}
  260. for i, lab in enumerate(label):
  261. numeratorName = histoName + "_Ghosts"
  262. denominatorName = histoName + "_Total"
  263. numerator = findRootObjByName(tf[lab], numeratorName)
  264. denominator = findRootObjByName(tf[lab], denominatorName)
  265. print("Numerator = " + numeratorName.replace(unique_name_ext_re(), ""))
  266. print("Denominator = " + denominatorName.replace(unique_name_ext_re(), ""))
  267. teff = TEfficiency(numerator, denominator)
  268. teff.SetStatisticOption(7)
  269. ghost[lab] = teff.CreateGraph()
  270. print(lab)
  271. ghost[lab].SetName(lab)
  272. return ghost
  273. def get_compare_ghost(eff, hist, tf, histoName, label):
  274. ghost = {}
  275. for i, lab in enumerate(label):
  276. numeratorName = histoName + "_Ghosts"
  277. denominatorName = histoName + "_Total"
  278. numerator = findRootObjByName(tf[lab], numeratorName)
  279. denominator = findRootObjByName(tf[lab], denominatorName)
  280. print("Numerator = " + numeratorName.replace(unique_name_ext_re(), ""))
  281. print("Denominator = " + denominatorName.replace(unique_name_ext_re(), ""))
  282. teff = TEfficiency(numerator, denominator)
  283. teff.SetStatisticOption(7)
  284. ghost[lab] = teff.CreateGraph()
  285. print(lab)
  286. ghost[lab].SetName(lab)
  287. if histoName.find("Forward") != -1:
  288. ghost[lab].SetName(lab + " Ghosts, Forward")
  289. if histoName.find("Merged") != -1:
  290. ghost[lab].SetName(lab + " Ghosts, MergedMatch")
  291. elif histoName.find("DefaultMatch") != -1:
  292. ghost[lab].SetName(lab + " Ghosts, DefaultMatch")
  293. elif histoName.find("Match") != -1:
  294. ghost[lab].SetName(lab + " Ghosts, Match")
  295. if histoName.find("Seed") != -1:
  296. ghost[lab].SetName(lab + " Ghosts, Seed")
  297. if histoName.find("BestLong") != -1:
  298. ghost[lab].SetName(lab + " Ghosts, BestLong")
  299. return ghost
  300. def PrCheckerEfficiency(
  301. filename,
  302. outfile,
  303. label,
  304. trackers,
  305. savepdf,
  306. compare,
  307. compare_cuts,
  308. plot_electrons,
  309. plot_electrons_only,
  310. ):
  311. from utils.LHCbStyle import setLHCbStyle, set_style
  312. from utils.ConfigHistos import (
  313. efficiencyHistoDict,
  314. ghostHistoDict,
  315. categoriesDict,
  316. getCuts,
  317. )
  318. from utils.CompareConfigHistos import getCompare, getCompColors
  319. from utils.Legend import place_legend
  320. setLHCbStyle()
  321. markers = get_markers()
  322. colors = get_colors()
  323. elec_colors = get_elec_colors()
  324. styles = get_fillstyles()
  325. tf = {}
  326. tf = get_files(tf, filename, label)
  327. outputfile = TFile(outfile, "recreate")
  328. latex = TLatex()
  329. latex.SetNDC()
  330. latex.SetTextSize(0.05)
  331. efficiencyHistoDict = efficiencyHistoDict()
  332. efficiencyHistos = getEfficiencyHistoNames()
  333. ghostHistos = getGhostHistoNames()
  334. ghostHistoDict = ghostHistoDict()
  335. categories = categoriesDict()
  336. cuts = getCuts()
  337. compareDict = getCompare()
  338. compareCuts = getCompCuts(compare_cuts)
  339. compareColors = getCompColors()
  340. compareGhostHisto = ["eta", "p", "pt", "nPV"]
  341. trackers = getTrackers(trackers)
  342. folders = getOriginFolders()
  343. for tracker in trackers:
  344. outputfile.cd()
  345. trackerDir = outputfile.mkdir(tracker)
  346. trackerDir.cd()
  347. for cut in cuts[tracker]:
  348. cutDir = trackerDir.mkdir(cut)
  349. cutDir.cd()
  350. folder = folders[tracker]["folder"]
  351. print("folder: " + folder.replace(unique_name_ext_re(), ""))
  352. histoBaseName = "Track/" + folder + tracker + "/" + cut + "_"
  353. # calculate efficiency
  354. for histo in efficiencyHistos:
  355. canvastitle = (
  356. "efficiency_" + histo + ", " + categories[tracker][cut]["title"]
  357. )
  358. # get efficiency for not electrons category
  359. histoName = histoBaseName + "" + efficiencyHistoDict[histo]["variable"]
  360. print("not electrons: " + histoName.replace(unique_name_ext_re(), ""))
  361. eff = {}
  362. hist_den = {}
  363. eff, hist_den = get_eff(eff, hist_den, tf, histoName, label, histo)
  364. if categories[tracker][cut]["plotElectrons"] and plot_electrons:
  365. histoNameElec = (
  366. "Track/"
  367. + folder
  368. + tracker
  369. + "/"
  370. + categories[tracker][cut]["Electrons"]
  371. )
  372. histoName_e = (
  373. histoNameElec + "_" + efficiencyHistoDict[histo]["variable"]
  374. )
  375. print("electrons: " + histoName_e.replace(unique_name_ext_re(), ""))
  376. eff_elec = {}
  377. hist_elec = {}
  378. eff_elec, hist_elec = get_eff(
  379. eff_elec,
  380. hist_elec,
  381. tf,
  382. histoName_e,
  383. label,
  384. histo,
  385. )
  386. name = "efficiency_" + histo
  387. canvas = TCanvas(name, canvastitle)
  388. canvas.SetRightMargin(0.1)
  389. mg = TMultiGraph()
  390. for i, lab in enumerate(label):
  391. if not plot_electrons_only:
  392. mg.Add(eff[lab])
  393. set_style(eff[lab], colors[i], markers[i], styles[i])
  394. if categories[tracker][cut]["plotElectrons"] and plot_electrons:
  395. mg.Add(eff_elec[lab])
  396. set_style(eff_elec[lab], elec_colors[i], markers[i], styles[i])
  397. mg.Draw("AP")
  398. mg.GetYaxis().SetRangeUser(0, 1.05)
  399. xtitle = efficiencyHistoDict[histo]["xTitle"]
  400. unit_l = xtitle.split("[")
  401. if "]" in unit_l[-1]:
  402. unit = unit_l[-1].replace("]", "")
  403. else:
  404. unit = "a.u."
  405. print(unit)
  406. mg.GetXaxis().SetTitle(xtitle)
  407. mg.GetXaxis().SetTitleSize(0.06)
  408. mg.GetYaxis().SetTitle(
  409. "Efficiency of Long Tracks",
  410. ) # (" + str(round(hist_den[label[0]].GetBinWidth(1), 2)) + f"{unit})"+"^{-1}")
  411. mg.GetYaxis().SetTitleSize(0.06)
  412. mg.GetYaxis().SetTitleOffset(1.1)
  413. mg.GetXaxis().SetRangeUser(*efficiencyHistoDict[histo]["range"])
  414. mg.GetXaxis().SetNdivisions(10, 5, 0)
  415. mygray = 18
  416. myblue = kBlue - 9
  417. for i, lab in enumerate(label):
  418. rightmax = 1.05 * hist_den[lab].GetMaximum()
  419. scale = gPad.GetUymax() / rightmax
  420. hist_den[lab].Scale(scale)
  421. if categories[tracker][cut]["plotElectrons"] and plot_electrons:
  422. rightmax = 1.05 * hist_elec[lab].GetMaximum()
  423. scale = gPad.GetUymax() / rightmax
  424. hist_elec[lab].Scale(scale)
  425. if i == 0:
  426. if not plot_electrons_only:
  427. set_style(hist_den[lab], mygray, markers[i], styles[i])
  428. gStyle.SetPalette(2, array("i", [mygray - 1, myblue + 1]))
  429. hist_den[lab].Draw("HIST PLC SAME")
  430. if categories[tracker][cut]["plotElectrons"] and plot_electrons:
  431. set_style(hist_elec[lab], myblue, markers[i], styles[i])
  432. hist_elec[lab].SetFillColorAlpha(myblue, 0.35)
  433. hist_elec[lab].Draw("HIST PLC SAME")
  434. # else:
  435. # print(
  436. # "No distribution plotted for other labels.",
  437. # "Can be added by uncommenting the code below this print statement.",
  438. # )
  439. # # set_style(hist_den[lab], mygray, markers[i], styles[i])
  440. # # gStyle.SetPalette(2, array("i", [mygray - 1, myblue + 1]))
  441. # # hist_den[lab].Draw("HIST PLC SAME")
  442. # if histo == "p":
  443. # pos = [0.5, 0.3, 1.0, 0.6]
  444. # elif histo == "pt":
  445. # pos = [0.5, 0.3, 0.99, 0.6]
  446. # elif histo == "phi":
  447. # pos = [0.3, 0.25, 0.8, 0.55]
  448. # else:
  449. # pos = [0.3, 0.25, 0.8, 0.55]
  450. if histo == "p":
  451. pos = [0.5, 0.3, 1.0, 0.5] # [0.53, 0.4, 1.01, 0.71]
  452. elif histo == "pt":
  453. pos = [0.5, 0.3, 0.99, 0.5] # [0.5, 0.4, 0.98, 0.71]
  454. elif histo == "phi":
  455. pos = [0.4, 0.3, 0.9, 0.5]
  456. elif histo == "eta":
  457. pos = [0.5, 0.25, 1.0, 0.45]
  458. else:
  459. pos = [0.35, 0.25, 0.85, 0.45]
  460. legend = place_legend(
  461. canvas, *pos, header="LHCb Simulation", option="LPE"
  462. )
  463. for le in legend.GetListOfPrimitives():
  464. if "distribution" in le.GetLabel():
  465. le.SetOption("LF")
  466. legend.SetTextFont(132)
  467. legend.SetTextSize(0.04)
  468. legend.Draw()
  469. for lab in label:
  470. if not plot_electrons_only:
  471. eff[lab].Draw("P SAME")
  472. if categories[tracker][cut]["plotElectrons"] and plot_electrons:
  473. eff_elec[lab].Draw("P SAME")
  474. cutName = categories[tracker][cut]["title"]
  475. latex.DrawLatex(legend.GetX1() + 0.01, legend.GetY1() - 0.05, cutName)
  476. low = 0
  477. high = 1.05
  478. gPad.Update()
  479. axis = TGaxis(
  480. gPad.GetUxmax(),
  481. gPad.GetUymin(),
  482. gPad.GetUxmax(),
  483. gPad.GetUymax(),
  484. low,
  485. high,
  486. 510,
  487. "+U",
  488. )
  489. axis.SetTitleFont(132)
  490. axis.SetTitleSize(0.06)
  491. axis.SetTitleOffset(0.55)
  492. axis.SetTitle(
  493. "# Tracks " + get_nicer_var_string(histo) + " distribution [a.u.]",
  494. )
  495. axis.SetLabelSize(0)
  496. axis.Draw()
  497. canvas.RedrawAxis()
  498. if savepdf:
  499. filestypes = ["pdf"] # , "png", "eps", "C", "ps", "tex"]
  500. for ftype in filestypes:
  501. if not plot_electrons_only:
  502. canvasName = tracker + "_" + cut + "_" + histo + "." + ftype
  503. else:
  504. canvasName = (
  505. tracker
  506. + "_Electrons_"
  507. + cut
  508. + "_"
  509. + histo
  510. + "."
  511. + ftype
  512. )
  513. canvas.SaveAs("checks/" + canvasName)
  514. # canvas.SetRightMargin(0.05)
  515. canvas.Write()
  516. # calculate ghost rate
  517. print("\ncalculate ghost rate: ")
  518. histoBaseName = "Track/" + folder + tracker + "/"
  519. for histo in ghostHistos[tracker]:
  520. trackerDir.cd()
  521. title = "ghost_rate_vs_" + histo
  522. gPad.SetTicks()
  523. histoName = histoBaseName + ghostHistoDict[histo]["variable"]
  524. ghost = {}
  525. hist_den = {}
  526. ghost = get_ghost(ghost, hist_den, tf, histoName, label)
  527. canvas = TCanvas(title, title)
  528. mg = TMultiGraph()
  529. for i, lab in enumerate(label):
  530. mg.Add(ghost[lab])
  531. set_style(ghost[lab], colors[i], markers[2 * i], styles[i])
  532. xtitle = ghostHistoDict[histo]["xTitle"]
  533. mg.GetXaxis().SetTitle(xtitle)
  534. mg.GetYaxis().SetTitle("Fraction of fake tracks")
  535. mg.Draw("ap")
  536. mg.GetXaxis().SetTitleSize(0.06)
  537. mg.GetYaxis().SetTitleSize(0.06)
  538. mg.GetYaxis().SetTitleOffset(1.1)
  539. mg.GetXaxis().SetRangeUser(*efficiencyHistoDict[histo]["range"])
  540. mg.GetXaxis().SetNdivisions(10, 5, 0)
  541. # for lab in label:
  542. # ghost[lab].Draw("P SAME")
  543. if histo == "p":
  544. pos = [0.53, 0.4, 1.00, 0.71]
  545. elif histo == "pt":
  546. pos = [0.5, 0.4, 0.98, 0.71]
  547. elif histo == "eta":
  548. pos = [0.35, 0.6, 0.85, 0.9]
  549. elif histo == "phi":
  550. pos = [0.3, 0.3, 0.9, 0.6]
  551. else:
  552. pos = [0.4, 0.37, 0.80, 0.68]
  553. legend = place_legend(canvas, *pos, header="LHCb Simulation", option="LPE")
  554. legend.SetTextFont(132)
  555. legend.SetTextSize(0.04)
  556. legend.Draw()
  557. # if histo != "nPV":
  558. # latex.DrawLatex(0.7, 0.85, "LHCb simulation")
  559. # else:
  560. # latex.DrawLatex(0.2, 0.85, "LHCb simulation")
  561. # mg.GetYaxis().SetRangeUser(0, 0.4)
  562. if histo == "eta":
  563. mg.GetYaxis().SetRangeUser(0, 0.4)
  564. # track_name = names[tracker] + " tracks"
  565. # latex.DrawLatex(0.7, 0.75, track_name)
  566. # canvas.PlaceLegend()
  567. if savepdf:
  568. filestypes = ["pdf"] # , "png", "eps", "C", "ps", "tex"]
  569. for ftype in filestypes:
  570. canvas.SaveAs(
  571. "checks/" + tracker + "_ghost_rate_" + histo + "." + ftype,
  572. )
  573. canvas.Write()
  574. #
  575. # Compare electron efficiencies of different trackers
  576. #
  577. plot_electrons_only = True
  578. if compare:
  579. print("\nCompare Efficiencies: ")
  580. outputfile.cd()
  581. for jcut in compareCuts: # [long, long_fromB, long_fromB_P>5GeV]
  582. compareDir = outputfile.mkdir("compare_" + jcut)
  583. compareDir.cd()
  584. for histo in efficiencyHistos: # [p, pt, phi, eta, nPV]
  585. canvastitle = "efficiency_" + histo + "_" + jcut
  586. name = "efficiency_" + histo + "_" + jcut
  587. canvas = TCanvas(name, canvastitle)
  588. canvas.SetRightMargin(0.1)
  589. mg = TMultiGraph()
  590. dist_eff = {}
  591. dist_hist_den = {}
  592. dist_eff_elec = {}
  593. dist_hist_elec = {}
  594. First = True
  595. dist_tracker = ""
  596. markeritr = 0
  597. for tracker in trackers: # [BestLong, Forward, Match, Seed]
  598. cut = compareDict[jcut][tracker]
  599. folder = folders[tracker]["folder"]
  600. print("folder: " + folder.replace(unique_name_ext_re(), ""))
  601. jcolor = compareColors[tracker]
  602. histoName = (
  603. "Track/"
  604. + folder
  605. + tracker
  606. + "/"
  607. + cut
  608. + "_"
  609. + ""
  610. + efficiencyHistoDict[histo]["variable"]
  611. )
  612. print(
  613. "not electrons: " + histoName.replace(unique_name_ext_re(), "")
  614. )
  615. eff = {}
  616. hist_den = {}
  617. eff, hist_den = get_eff(eff, hist_den, tf, histoName, label, histo)
  618. if categories[tracker][cut]["plotElectrons"] and plot_electrons:
  619. histoNameElec = (
  620. "Track/"
  621. + folder
  622. + tracker
  623. + "/"
  624. + categories[tracker][cut]["Electrons"]
  625. )
  626. histoName_e = (
  627. histoNameElec + "_" + efficiencyHistoDict[histo]["variable"]
  628. )
  629. print(
  630. "electrons: "
  631. + histoName_e.replace(unique_name_ext_re(), "")
  632. )
  633. eff_elec = {}
  634. hist_elec = {}
  635. eff_elec, hist_elec = get_eff(
  636. eff_elec,
  637. hist_elec,
  638. tf,
  639. histoName_e,
  640. label,
  641. histo,
  642. )
  643. if First:
  644. dist_eff_elec = eff_elec
  645. dist_hist_elec = hist_elec
  646. if First:
  647. dist_tracker = tracker
  648. dist_eff = eff
  649. dist_hist_den = hist_den
  650. First = False
  651. seeditr = 0
  652. for i, lab in enumerate(label):
  653. if categories[tracker][cut]["plotElectrons"] and plot_electrons:
  654. if (tracker == "Seed") and (seeditr != 0):
  655. continue
  656. if tracker == "Seed":
  657. seeditr += 1
  658. mg.Add(eff_elec[lab])
  659. set_style(
  660. eff_elec[lab],
  661. colors[jcolor],
  662. markers[i + markeritr],
  663. styles[i],
  664. )
  665. else:
  666. mg.Add(eff_elec[lab])
  667. set_style(
  668. eff_elec[lab],
  669. elec_colors[jcolor + markeritr],
  670. markers[i + markeritr],
  671. styles[i],
  672. )
  673. markeritr = markeritr + 1
  674. # set_style(
  675. # eff_elec[lab], colors[jcolor], markers[i], styles[i]
  676. # )
  677. markeritr = 0
  678. mg.Draw("AP")
  679. mg.GetYaxis().SetRangeUser(0, 1.05)
  680. xtitle = efficiencyHistoDict[histo]["xTitle"]
  681. unit_l = xtitle.split("[")
  682. if "]" in unit_l[-1]:
  683. unit = unit_l[-1].replace("]", "")
  684. else:
  685. unit = "a.u."
  686. print(unit)
  687. mg.GetXaxis().SetTitle(xtitle)
  688. mg.GetXaxis().SetTitleSize(0.06)
  689. mg.GetYaxis().SetTitle(
  690. "Efficiency of Long Tracks",
  691. ) # (" + str(round(hist_den[label[0]].GetBinWidth(1), 2)) + f"{unit})"+"^{-1}")
  692. mg.GetYaxis().SetTitleSize(0.06)
  693. mg.GetYaxis().SetTitleOffset(1.1)
  694. mg.GetXaxis().SetRangeUser(*efficiencyHistoDict[histo]["range"])
  695. mg.GetXaxis().SetNdivisions(10, 5, 0)
  696. mygray = 16
  697. myblue = kBlue - 7
  698. dist_cut = compareDict[jcut][dist_tracker]
  699. for i, lab in enumerate(label):
  700. rightmax = 1.05 * dist_hist_den[lab].GetMaximum()
  701. scale = gPad.GetUymax() / rightmax
  702. dist_hist_den[lab].Scale(scale)
  703. if (
  704. categories[dist_tracker][dist_cut]["plotElectrons"]
  705. and plot_electrons
  706. ):
  707. rightmax = 1.05 * dist_hist_elec[lab].GetMaximum()
  708. scale = gPad.GetUymax() / rightmax
  709. dist_hist_elec[lab].Scale(scale)
  710. if i == len(label) - 1:
  711. if not plot_electrons_only:
  712. set_style(dist_hist_den[lab], mygray, markers[i], styles[i])
  713. # gStyle.SetPalette(2, array("i", [mygray - 1, myblue + 1]))
  714. dist_hist_den[lab].SetFillColorAlpha(mygray, 0.5)
  715. dist_hist_den[lab].Draw("HIST PLC SAME")
  716. if (
  717. categories[dist_tracker][dist_cut]["plotElectrons"]
  718. and plot_electrons
  719. ):
  720. set_style(
  721. dist_hist_elec[lab], mygray, markers[i], styles[i]
  722. )
  723. # gStyle.SetPalette(2, array("i", [mygray - 1, myblue + 1]))
  724. # dist_hist_elec[lab].SetFillColor(myblue)
  725. dist_hist_elec[lab].SetFillColorAlpha(myblue, 0.5)
  726. dist_hist_elec[lab].Draw("HIST PLC SAME")
  727. # else:
  728. # print(
  729. # "No distribution plotted for other labels.",
  730. # "Can be added by uncommenting the code below this print statement.",
  731. # )
  732. # set_style(dist_hist_den[lab], mygray, markers[i], styles[i])
  733. # gStyle.SetPalette(2, array("i", [mygray - 1, myblue + 1]))
  734. # dist_hist_den[lab].Draw("HIST PLC SAME")
  735. if histo == "p":
  736. pos = [0.5, 0.3, 1.0, 0.5] # [0.53, 0.4, 1.01, 0.71]
  737. elif histo == "pt":
  738. pos = [0.5, 0.3, 0.99, 0.5] # [0.5, 0.4, 0.98, 0.71]
  739. elif histo == "phi":
  740. pos = [0.4, 0.3, 0.9, 0.5]
  741. elif histo == "eta":
  742. pos = [0.5, 0.25, 1.0, 0.45]
  743. else:
  744. pos = [0.35, 0.25, 0.85, 0.45]
  745. legend = place_legend(
  746. canvas, *pos, header="LHCb Simulation", option="LPE"
  747. )
  748. for le in legend.GetListOfPrimitives():
  749. if "distribution" in le.GetLabel():
  750. le.SetOption("LF")
  751. legend.SetTextFont(132)
  752. legend.SetTextSize(0.04)
  753. legend.Draw()
  754. for lab in label:
  755. if not plot_electrons_only:
  756. dist_eff[lab].Draw("P SAME")
  757. if categories[tracker][cut]["plotElectrons"] and plot_electrons:
  758. dist_eff_elec[lab].Draw("P SAME")
  759. cutName = categories[tracker][cut]["title"]
  760. latex.DrawLatex(legend.GetX1() + 0.01, legend.GetY1() - 0.05, cutName)
  761. low = 0
  762. high = 1.05
  763. gPad.Update()
  764. axis = TGaxis(
  765. gPad.GetUxmax(),
  766. gPad.GetUymin(),
  767. gPad.GetUxmax(),
  768. gPad.GetUymax(),
  769. low,
  770. high,
  771. 510,
  772. "+U",
  773. )
  774. axis.SetTitleFont(132)
  775. axis.SetTitleSize(0.06)
  776. axis.SetTitleOffset(0.55)
  777. axis.SetTitle(
  778. "# Tracks " + get_nicer_var_string(histo) + " distribution [a.u.]",
  779. )
  780. axis.SetLabelSize(0)
  781. axis.Draw()
  782. canvas.RedrawAxis()
  783. if savepdf:
  784. filestypes = ["pdf"] # , "png", "eps", "C", "ps", "tex"]
  785. for ftype in filestypes:
  786. if not plot_electrons_only:
  787. canvasName = "Compare_" + cut + "_" + histo + "." + ftype
  788. else:
  789. canvasName = (
  790. "Compare_Electrons_" + cut + "_" + histo + "." + ftype
  791. )
  792. canvas.SaveAs("checks/" + canvasName)
  793. # canvas.SetRightMargin(0.05)
  794. canvas.Write()
  795. # calculate ghost rate
  796. print("\ncalculate ghost rate: ")
  797. for histo in compareGhostHisto: # [Match, Seed, ...]
  798. cut = compareDict[jcut][tracker]
  799. canvastitle = "ghost_rate_vs_" + histo + "_" + jcut
  800. name = "ghost_rate_vs_" + histo + "_" + jcut
  801. canvas = TCanvas(name, canvastitle)
  802. canvas.SetRightMargin(0.1)
  803. mg = TMultiGraph()
  804. jitr = 0
  805. for tracker in trackers:
  806. if tracker == "Seed":
  807. continue
  808. folder = folders[tracker]["folder"]
  809. jcolor = compareColors[tracker]
  810. gPad.SetTicks()
  811. histoName = (
  812. "Track/"
  813. + folder
  814. + tracker
  815. + "/"
  816. + ghostHistoDict[histo]["variable"]
  817. )
  818. ghost = {}
  819. hist_den = {}
  820. ghost = get_compare_ghost(ghost, hist_den, tf, histoName, label)
  821. for i, lab in enumerate(label):
  822. mg.Add(ghost[lab])
  823. set_style(
  824. ghost[lab], colors[jcolor + jitr], markers[2 * i], styles[i]
  825. )
  826. jitr += 1
  827. xtitle = ghostHistoDict[histo]["xTitle"]
  828. mg.GetXaxis().SetTitle(xtitle)
  829. mg.GetYaxis().SetTitle("Fraction of fake tracks")
  830. mg.Draw("ap")
  831. mg.GetXaxis().SetTitleSize(0.06)
  832. mg.GetYaxis().SetTitleSize(0.06)
  833. mg.GetYaxis().SetTitleOffset(1.1)
  834. mg.GetXaxis().SetRangeUser(*efficiencyHistoDict[histo]["range"])
  835. mg.GetXaxis().SetNdivisions(10, 5, 0)
  836. # for lab in label:
  837. # ghost[lab].Draw("P SAME")
  838. if histo == "p":
  839. pos = [0.53, 0.4, 1.00, 0.71]
  840. elif histo == "pt":
  841. pos = [0.5, 0.4, 0.98, 0.71]
  842. elif histo == "eta":
  843. pos = [0.35, 0.6, 0.85, 0.9]
  844. elif histo == "phi":
  845. pos = [0.3, 0.3, 0.9, 0.6]
  846. else:
  847. pos = [0.4, 0.37, 0.80, 0.68]
  848. legend = place_legend(
  849. canvas, *pos, header="LHCb Simulation", option="LPE"
  850. )
  851. legend.SetTextFont(132)
  852. legend.SetTextSize(0.04)
  853. legend.Draw()
  854. # if histo != "nPV":
  855. # latex.DrawLatex(0.7, 0.85, "LHCb simulation")
  856. # else:
  857. # latex.DrawLatex(0.2, 0.85, "LHCb simulation")
  858. # mg.GetYaxis().SetRangeUser(0, 0.4)
  859. if histo == "eta":
  860. mg.GetYaxis().SetRangeUser(0, 0.4)
  861. # track_name = names[tracker] + " tracks"
  862. # latex.DrawLatex(0.7, 0.75, track_name)
  863. # canvas.PlaceLegend()
  864. if savepdf:
  865. filestypes = ["pdf"] # , "png", "eps", "C", "ps", "tex"]
  866. for ftype in filestypes:
  867. canvas.SaveAs(
  868. "checks/" + tracker + "_ghost_rate_" + histo + "." + ftype,
  869. )
  870. canvas.Write()
  871. outputfile.cd()
  872. outputfile.Write()
  873. outputfile.Close()
  874. if __name__ == "__main__":
  875. parser = argument_parser()
  876. args = parser.parse_args()
  877. PrCheckerEfficiency(**vars(args))