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.

1054 lines
40 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
8 months ago
10 months ago
8 months ago
8 months ago
8 months ago
10 months ago
10 months ago
10 months ago
10 months ago
10 months ago
8 months ago
10 months ago
10 months ago
10 months ago
8 months ago
10 months ago
10 months ago
8 months ago
10 months ago
10 months ago
8 months ago
10 months ago
10 months ago
8 months ago
8 months ago
8 months ago
10 months ago
8 months ago
10 months ago
10 months ago
8 months ago
10 months ago
8 months ago
8 months ago
10 months ago
8 months ago
10 months ago
8 months ago
10 months ago
8 months ago
10 months ago
10 months ago
8 months ago
10 months ago
8 months ago
10 months ago
8 months ago
10 months ago
10 months ago
8 months ago
10 months ago
8 months ago
8 months ago
10 months ago
8 months ago
10 months ago
8 months ago
10 months ago
8 months ago
10 months ago
10 months ago
8 months ago
8 months ago
8 months ago
8 months ago
10 months ago
10 months ago
10 months ago
8 months ago
10 months ago
9 months ago
10 months ago
9 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. import glob
  37. gROOT.SetBatch(True)
  38. from utils.components import unique_name_ext_re, findRootObjByName
  39. def getEfficiencyHistoNames():
  40. return ["p", "pt", "phi", "eta", "nPV"]
  41. def getTrackers(trackers):
  42. return trackers
  43. def getCompCuts(compare_cuts):
  44. return compare_cuts
  45. # data/resolutions_and_effs_Bd2KstEE_MDmaster.root:Track/...
  46. def getOriginFolders():
  47. basedict = {
  48. "Velo": {},
  49. "Upstream": {},
  50. "Forward": {},
  51. "Match": {},
  52. "MergedMatch": {},
  53. "DefaultMatch": {},
  54. "BestLong": {},
  55. "Seed": {},
  56. }
  57. # evtl anpassen wenn die folders anders heissen
  58. basedict["Velo"]["folder"] = "VeloTrackChecker/"
  59. basedict["Upstream"]["folder"] = "UpstreamTrackChecker/"
  60. basedict["Forward"]["folder"] = "ForwardTrackChecker" + unique_name_ext_re() + "/"
  61. basedict["Match"]["folder"] = "MatchTrackChecker" + unique_name_ext_re() + "/"
  62. basedict["MergedMatch"]["folder"] = (
  63. "MergedMatchTrackChecker" + unique_name_ext_re() + "/"
  64. )
  65. basedict["DefaultMatch"]["folder"] = (
  66. "DefaultMatchTrackChecker" + unique_name_ext_re() + "/"
  67. )
  68. basedict["BestLong"]["folder"] = "BestLongTrackChecker" + unique_name_ext_re() + "/"
  69. basedict["Seed"]["folder"] = "SeedTrackChecker" + unique_name_ext_re() + "/"
  70. # basedict["Forward"]["folder"] = "ForwardTrackChecker_7a0dbfa7/"
  71. # basedict["Match"]["folder"] = "MatchTrackChecker_29e3152a/"
  72. # basedict["BestLong"]["folder"] = "BestLongTrackChecker_4ddacce1/"
  73. # basedict["Seed"]["folder"] = "SeedTrackChecker_1b1d5575/"
  74. return basedict
  75. def getTrackNames():
  76. basedict = {
  77. "Velo": {},
  78. "Upstream": {},
  79. "Forward": {},
  80. "Match": {},
  81. "MergedMatch": {},
  82. "DefaultMatch": {},
  83. "BestLong": {},
  84. "Seed": {},
  85. }
  86. basedict["Velo"] = "Velo"
  87. basedict["Upstream"] = "VeloUT"
  88. basedict["Forward"] = "Forward"
  89. basedict["Match"] = "Match"
  90. basedict["MergedMatch"] = "MergedMatch"
  91. basedict["DefaultMatch"] = "DefaultMatch"
  92. basedict["BestLong"] = "BestLong"
  93. basedict["Seed"] = "Seed"
  94. return basedict
  95. def get_colors():
  96. return [kBlack, kAzure, kGreen + 2, kMagenta + 2, kRed, kCyan + 2, kGray + 1]
  97. def get_elec_colors():
  98. return [
  99. kGray + 2,
  100. kBlue - 3,
  101. kRed + 1,
  102. kGreen + 1,
  103. kViolet,
  104. kTeal - 1,
  105. kOrange + 8,
  106. kGray + 1,
  107. ]
  108. def get_markers():
  109. return [20, 21, 24, 25, 22, 23, 26, 32]
  110. def get_fillstyles():
  111. return [1003, 3001, 3002, 3325, 3144, 3244, 3444]
  112. def getGhostHistoNames():
  113. basedict = {
  114. # "Velo": {},
  115. # "Upstream": {},
  116. "Forward": {},
  117. "Match": {},
  118. "MergedMatch": {},
  119. "DefaultMatch": {},
  120. "BestLong": {},
  121. "Seed": {},
  122. }
  123. basedict["Velo"] = ["eta", "nPV"]
  124. basedict["Upstream"] = ["eta", "p", "pt", "nPV"]
  125. basedict["Forward"] = ["eta", "p", "pt", "nPV"]
  126. basedict["Match"] = ["eta", "p", "pt", "nPV"]
  127. basedict["MergedMatch"] = basedict["Match"]
  128. basedict["DefaultMatch"] = basedict["Match"]
  129. basedict["BestLong"] = ["eta", "p", "pt", "nPV"]
  130. basedict["Seed"] = ["eta", "p", "pt", "nPV"]
  131. return basedict
  132. def argument_parser():
  133. parser = argparse.ArgumentParser(description="location of the tuple file")
  134. parser.add_argument(
  135. "--filename",
  136. type=str,
  137. default=["data/resolutions_and_effs_B.root"],
  138. nargs="+",
  139. help="input files, including path",
  140. )
  141. parser.add_argument(
  142. "--outfile",
  143. type=str,
  144. default="data_results/compare_efficiency.root",
  145. help="output file",
  146. )
  147. parser.add_argument(
  148. "--trackers",
  149. type=str,
  150. nargs="+",
  151. default=["Match", "Seed"], # Forward
  152. help="Trackers to plot.",
  153. )
  154. parser.add_argument(
  155. "--label",
  156. nargs="+",
  157. default=["particle"],
  158. help="label for files",
  159. )
  160. parser.add_argument(
  161. "--savepdf",
  162. action="store_true",
  163. help="save plots in pdf format",
  164. )
  165. parser.add_argument(
  166. "--compare",
  167. default=True,
  168. action="store_true",
  169. help="compare efficiencies",
  170. )
  171. parser.add_argument(
  172. "--compare-cuts",
  173. type=str,
  174. nargs="+",
  175. default=["long", "long_fromB", "long_fromB_P>3GeV_Pt>0.5GeV"],
  176. help="which cuts get compared",
  177. )
  178. parser.add_argument(
  179. "--plot-electrons",
  180. default=True,
  181. action="store_true",
  182. help="plot electrons",
  183. )
  184. parser.add_argument(
  185. "--plot-electrons-only",
  186. action="store_true",
  187. help="plot only electrons",
  188. )
  189. parser.add_argument(
  190. "--plot-velo",
  191. action="store_true",
  192. default=True,
  193. help="plot using momentum at EndVelo",
  194. )
  195. parser.add_argument(
  196. "--plot-velo-only",
  197. action="store_true",
  198. default=True,
  199. help="plot using only momentum at EndVelo",
  200. )
  201. return parser
  202. def get_files(tf, filename, label):
  203. for i, f in enumerate(filename):
  204. tf[label[i]] = TFile(f, "read")
  205. return tf
  206. def get_nicer_var_string(var: str):
  207. nice_vars = dict(pt="p_{T}", eta="#eta", phi="#phi")
  208. try:
  209. return nice_vars[var]
  210. except KeyError:
  211. return var
  212. def get_eff(eff, hist, tf, histoName, label, var):
  213. eff = {}
  214. hist = {}
  215. var = get_nicer_var_string(var)
  216. for i, lab in enumerate(label):
  217. numeratorName = histoName + "_reconstructed"
  218. denominatorName = histoName + "_reconstructible"
  219. denominator = findRootObjByName(tf[lab], denominatorName)
  220. try:
  221. numerator = findRootObjByName(tf[lab], numeratorName)
  222. except:
  223. numerator = denominator
  224. if numerator.GetEntries() == 0 or denominator.GetEntries() == 0:
  225. continue
  226. teff = TEfficiency(numerator, denominator)
  227. teff.SetStatisticOption(7)
  228. eff[lab] = teff.CreateGraph()
  229. eff[lab].SetName(lab)
  230. eff[lab].SetTitle(lab)
  231. if histoName.find("Forward") != -1:
  232. if histoName.find("electron") != -1:
  233. eff[lab].SetTitle(lab + " Forward, e^{-}")
  234. else:
  235. eff[lab].SetTitle(lab + " Forward")
  236. if histoName.find("Merged") != -1:
  237. if histoName.find("electron") != -1:
  238. eff[lab].SetTitle(lab + " MergedMatch, e^{-}")
  239. else:
  240. eff[lab].SetTitle(lab + " MergedMatch")
  241. elif histoName.find("DefaultMatch") != -1:
  242. if histoName.find("electron") != -1:
  243. eff[lab].SetTitle(lab + " DefaultMatch, e^{-}")
  244. else:
  245. eff[lab].SetTitle(lab + " DefaultMatch")
  246. elif histoName.find("Match") != -1:
  247. if histoName.find("electron") != -1:
  248. eff[lab].SetTitle(lab + " Match, e^{-}")
  249. else:
  250. eff[lab].SetTitle(lab + " Match")
  251. if histoName.find("Seed") != -1:
  252. if histoName.find("electron") != -1:
  253. eff[lab].SetTitle(lab + " Seed, e^{-}")
  254. else:
  255. eff[lab].SetTitle(lab + " Seed")
  256. if histoName.find("BestLong") != -1:
  257. if histoName.find("electron") != -1:
  258. eff[lab].SetTitle(lab + " BestLong, e^{-}")
  259. else:
  260. eff[lab].SetTitle(lab + " BestLong")
  261. # if histoName.find("EndVelo") != -1:
  262. # eff[lab].SetTitle(eff[lab].GetTitle() + " EndVelo")
  263. hist[lab] = denominator.Clone()
  264. hist[lab].SetName("h_numerator_notElectrons")
  265. hist[lab].SetTitle(var + " distribution, not e^{-}")
  266. if histoName.find("strange") != -1:
  267. hist[lab].SetTitle(var + " distribution, stranges")
  268. if histoName.find("electron") != -1:
  269. hist[lab].SetTitle(var + " distribution, e^{-}")
  270. # if histoName.find("EndVelo") != -1:
  271. # hist[lab].SetTitle(hist[lab].GetTitle() + ", EndVelo")
  272. return eff, hist
  273. def get_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. return ghost
  288. def PrCheckerEfficiency(
  289. filename,
  290. outfile,
  291. label,
  292. trackers,
  293. savepdf,
  294. compare,
  295. compare_cuts,
  296. plot_electrons,
  297. plot_electrons_only,
  298. plot_velo,
  299. plot_velo_only,
  300. ):
  301. from utils.LHCbStyle import setLHCbStyle, set_style
  302. from utils.ConfigHistos import (
  303. efficiencyHistoDict,
  304. ghostHistoDict,
  305. categoriesDict,
  306. getCuts,
  307. )
  308. from utils.CompareConfigHistos import getCompare, getCompColors
  309. from utils.Legend import place_legend
  310. setLHCbStyle()
  311. markers = get_markers()
  312. colors = get_colors()
  313. elec_colors = get_elec_colors()
  314. styles = get_fillstyles()
  315. tf = {}
  316. tf = get_files(tf, filename, label)
  317. outputfile = TFile(outfile, "recreate")
  318. latex = TLatex()
  319. latex.SetNDC()
  320. latex.SetTextSize(0.05)
  321. efficiencyHistoDict = efficiencyHistoDict()
  322. efficiencyHistos = getEfficiencyHistoNames()
  323. ghostHistos = getGhostHistoNames()
  324. ghostHistoDict = ghostHistoDict()
  325. categories = categoriesDict()
  326. cuts = getCuts()
  327. compareDict = getCompare()
  328. compareCuts = getCompCuts(compare_cuts)
  329. compareColors = getCompColors()
  330. compareGhostHisto = ["eta", "p", "pt", "nPV"]
  331. trackers = getTrackers(trackers)
  332. folders = getOriginFolders()
  333. if savepdf:
  334. checks_files = glob.glob("checks/*")
  335. for f in checks_files:
  336. os.remove(f)
  337. for tracker in trackers:
  338. outputfile.cd()
  339. trackerDir = outputfile.mkdir(tracker)
  340. trackerDir.cd()
  341. for cut in cuts[tracker]:
  342. cutDir = trackerDir.mkdir(cut)
  343. cutDir.cd()
  344. folder = folders[tracker]["folder"]
  345. print("folder: " + folder.replace(unique_name_ext_re(), ""))
  346. histoBaseName = "Track/" + folder + tracker + "/" + cut + "_"
  347. # calculate efficiency
  348. for histo in efficiencyHistos:
  349. canvastitle = (
  350. "efficiency_" + histo + ", " + categories[tracker][cut]["title"]
  351. )
  352. # get efficiency for not electrons category
  353. histoName = histoBaseName + "" + efficiencyHistoDict[histo]["variable"]
  354. print("not electrons: " + histoName.replace(unique_name_ext_re(), ""))
  355. eff = {}
  356. hist_den = {}
  357. eff, hist_den = get_eff(eff, hist_den, tf, histoName, label, histo)
  358. if categories[tracker][cut]["plotElectrons"] and plot_electrons:
  359. histoNameElec = (
  360. "Track/"
  361. + folder
  362. + tracker
  363. + "/"
  364. + categories[tracker][cut]["Electrons"]
  365. )
  366. histoName_e = (
  367. histoNameElec + "_" + efficiencyHistoDict[histo]["variable"]
  368. )
  369. print("electrons: " + histoName_e.replace(unique_name_ext_re(), ""))
  370. eff_elec = {}
  371. hist_elec = {}
  372. eff_elec, hist_elec = get_eff(
  373. eff_elec,
  374. hist_elec,
  375. tf,
  376. histoName_e,
  377. label,
  378. histo,
  379. )
  380. if (
  381. categories[tracker][cut]["plotEndVelo"]
  382. and plot_velo
  383. and (histo == "p" or histo == "pt")
  384. ):
  385. histoNameEndVelo = (
  386. "Track/"
  387. + folder
  388. + tracker
  389. + "/"
  390. + categories[tracker][cut]["EndVelo"]
  391. )
  392. histoName_v = (
  393. histoNameEndVelo
  394. + "_"
  395. + efficiencyHistoDict[histo]["variable"]
  396. )
  397. print(
  398. "EndVelo: " + histoName_v.replace(unique_name_ext_re(), "")
  399. )
  400. eff_velo = {}
  401. hist_velo = {}
  402. eff_velo, hist_velo = get_eff(
  403. eff_velo,
  404. hist_velo,
  405. tf,
  406. histoName_v,
  407. label,
  408. histo,
  409. )
  410. name = "efficiency_" + histo
  411. canvas = TCanvas(name, canvastitle)
  412. canvas.SetRightMargin(0.1)
  413. mg = TMultiGraph()
  414. for i, lab in enumerate(label):
  415. if not plot_electrons_only: # and not plot_velo_only:
  416. mg.Add(eff[lab])
  417. set_style(eff[lab], colors[i], markers[i], styles[i])
  418. if categories[tracker][cut]["plotElectrons"] and plot_electrons:
  419. if not plot_velo_only or (
  420. histo == "phi" or histo == "eta" or histo == "nPV"
  421. ):
  422. mg.Add(eff_elec[lab])
  423. set_style(
  424. eff_elec[lab], elec_colors[i], markers[i], styles[i]
  425. )
  426. if (
  427. categories[tracker][cut]["plotEndVelo"]
  428. and plot_velo
  429. and (histo == "p" or histo == "pt")
  430. ):
  431. mg.Add(eff_velo[lab])
  432. set_style(
  433. eff_velo[lab], kMagenta + 1, markers[i], styles[i]
  434. )
  435. mg.Draw("AP")
  436. mg.GetYaxis().SetRangeUser(0, 1.05)
  437. xtitle = efficiencyHistoDict[histo]["xTitle"]
  438. unit_l = xtitle.split("[")
  439. if "]" in unit_l[-1]:
  440. unit = unit_l[-1].replace("]", "")
  441. else:
  442. unit = "a.u."
  443. print(unit)
  444. mg.GetXaxis().SetTitle(xtitle)
  445. mg.GetXaxis().SetTitleSize(0.06)
  446. mg.GetYaxis().SetTitle(
  447. "Efficiency of Long Tracks",
  448. ) # (" + str(round(hist_den[label[0]].GetBinWidth(1), 2)) + f"{unit})"+"^{-1}")
  449. mg.GetYaxis().SetTitleSize(0.06)
  450. mg.GetYaxis().SetTitleOffset(1.1)
  451. mg.GetXaxis().SetRangeUser(*efficiencyHistoDict[histo]["range"])
  452. mg.GetXaxis().SetNdivisions(10, 5, 0)
  453. mygray = 18
  454. myblue = kBlue - 10
  455. mypurple = kMagenta - 10
  456. for i, lab in enumerate(label):
  457. rightmax = 1.05 * hist_den[lab].GetMaximum()
  458. scale = gPad.GetUymax() / rightmax
  459. hist_den[lab].Scale(scale)
  460. if categories[tracker][cut]["plotElectrons"] and plot_electrons:
  461. rightmax = 1.05 * hist_elec[lab].GetMaximum()
  462. scale = gPad.GetUymax() / rightmax
  463. hist_elec[lab].Scale(scale)
  464. if (
  465. categories[tracker][cut]["plotEndVelo"]
  466. and plot_velo
  467. and (histo == "p" or histo == "pt")
  468. ):
  469. rightmax = 1.05 * hist_velo[lab].GetMaximum()
  470. scale = gPad.GetUymax() / rightmax
  471. hist_velo[lab].Scale(scale)
  472. if i == 0:
  473. if not plot_electrons_only: # and not plot_velo_only:
  474. set_style(hist_den[lab], mygray, markers[i], styles[i])
  475. gStyle.SetPalette(2, array("i", [mygray - 1, myblue + 1]))
  476. hist_den[lab].Draw("HIST PLC SAME")
  477. if categories[tracker][cut]["plotElectrons"] and plot_electrons:
  478. if not plot_velo_only or (
  479. histo == "phi" or histo == "eta" or histo == "nPV"
  480. ):
  481. set_style(hist_elec[lab], myblue, markers[i], styles[i])
  482. hist_elec[lab].SetFillColorAlpha(myblue, 0.5)
  483. hist_elec[lab].Draw("HIST PLC SAME")
  484. if (
  485. categories[tracker][cut]["plotEndVelo"]
  486. and plot_velo
  487. and (histo == "p" or histo == "pt")
  488. ):
  489. set_style(hist_velo[lab], myblue, markers[i], styles[i])
  490. hist_velo[lab].SetFillColorAlpha(myblue, 0.5)
  491. hist_velo[lab].Draw("HIST PLC SAME")
  492. # else:
  493. # print(
  494. # "No distribution plotted for other labels.",
  495. # "Can be added by uncommenting the code below this print statement.",
  496. # )
  497. # set_style(hist_den[lab], mygray, markers[i], styles[i])
  498. # gStyle.SetPalette(2, array("i", [mygray - 1, myblue + 1]))
  499. # hist_den[lab].Draw("HIST PLC SAME")
  500. if histo == "p":
  501. pos = [0.5, 0.3, 1.0, 0.5] # [0.53, 0.4, 1.01, 0.71]
  502. elif histo == "pt":
  503. pos = [0.5, 0.3, 0.99, 0.5] # [0.5, 0.4, 0.98, 0.71]
  504. elif histo == "phi":
  505. pos = [0.4, 0.3, 0.9, 0.5]
  506. elif histo == "eta":
  507. pos = [0.5, 0.25, 1.0, 0.45]
  508. else:
  509. pos = [0.35, 0.25, 0.85, 0.45]
  510. legend = place_legend(
  511. canvas, *pos, header="LHCb Simulation", option="LPE"
  512. )
  513. for le in legend.GetListOfPrimitives():
  514. if "distribution" in le.GetLabel():
  515. le.SetOption("LF")
  516. legend.SetTextFont(132)
  517. legend.SetTextSize(0.04)
  518. legend.Draw()
  519. for lab in label:
  520. if not plot_electrons_only: # and not plot_velo_only:
  521. eff[lab].Draw("P SAME")
  522. if categories[tracker][cut]["plotElectrons"] and plot_electrons:
  523. if not plot_velo_only or (
  524. histo == "phi" or histo == "eta" or histo == "nPV"
  525. ):
  526. eff_elec[lab].Draw("P SAME")
  527. if (
  528. categories[tracker][cut]["plotEndVelo"]
  529. and plot_velo
  530. and (histo == "p" or histo == "pt")
  531. ):
  532. eff_velo[lab].Draw("P SAME")
  533. cutName = categories[tracker][cut]["title"]
  534. latex.DrawLatex(legend.GetX1() + 0.01, legend.GetY1() - 0.05, cutName)
  535. low = 0
  536. high = 1.05
  537. gPad.Update()
  538. axis = TGaxis(
  539. gPad.GetUxmax(),
  540. gPad.GetUymin(),
  541. gPad.GetUxmax(),
  542. gPad.GetUymax(),
  543. low,
  544. high,
  545. 510,
  546. "+U",
  547. )
  548. axis.SetTitleFont(132)
  549. axis.SetTitleSize(0.06)
  550. axis.SetTitleOffset(0.55)
  551. axis.SetTitle(
  552. "# Tracks " + get_nicer_var_string(histo) + " distribution [a.u.]",
  553. )
  554. axis.SetLabelSize(0)
  555. axis.Draw()
  556. canvas.RedrawAxis()
  557. if savepdf and False:
  558. filestypes = ["pdf"] # , "png", "eps", "C", "ps", "tex"]
  559. for ftype in filestypes:
  560. if not plot_electrons_only:
  561. canvasName = tracker + "_" + cut + "_" + histo + "." + ftype
  562. else:
  563. canvasName = (
  564. tracker + "Electrons_" + cut + "_" + histo + "." + ftype
  565. )
  566. canvas.SaveAs("checks/" + canvasName)
  567. # canvas.SetRightMargin(0.05)
  568. canvas.Write()
  569. # calculate ghost rate
  570. print("\ncalculate ghost rate: ")
  571. histoBaseName = "Track/" + folder + tracker + "/"
  572. for histo in ghostHistos[tracker]:
  573. trackerDir.cd()
  574. title = "ghost_rate_vs_" + histo
  575. gPad.SetTicks()
  576. histoName = histoBaseName + ghostHistoDict[histo]["variable"]
  577. ghost = {}
  578. hist_den = {}
  579. ghost = get_ghost(ghost, hist_den, tf, histoName, label)
  580. canvas = TCanvas(title, title)
  581. mg = TMultiGraph()
  582. for i, lab in enumerate(label):
  583. mg.Add(ghost[lab])
  584. set_style(ghost[lab], colors[i], markers[2 * i], styles[i])
  585. xtitle = ghostHistoDict[histo]["xTitle"]
  586. mg.GetXaxis().SetTitle(xtitle)
  587. mg.GetYaxis().SetTitle("Fraction of fake tracks")
  588. mg.Draw("ap")
  589. mg.GetXaxis().SetTitleSize(0.06)
  590. mg.GetYaxis().SetTitleSize(0.06)
  591. mg.GetYaxis().SetTitleOffset(1.1)
  592. mg.GetXaxis().SetRangeUser(*efficiencyHistoDict[histo]["range"])
  593. mg.GetXaxis().SetNdivisions(10, 5, 0)
  594. # for lab in label:
  595. # ghost[lab].Draw("P SAME")
  596. if histo == "p":
  597. pos = [0.53, 0.4, 1.00, 0.71]
  598. elif histo == "pt":
  599. pos = [0.5, 0.4, 0.98, 0.71]
  600. elif histo == "eta":
  601. pos = [0.35, 0.6, 0.85, 0.9]
  602. elif histo == "phi":
  603. pos = [0.3, 0.3, 0.9, 0.6]
  604. else:
  605. pos = [0.4, 0.37, 0.80, 0.68]
  606. legend = place_legend(canvas, *pos, header="LHCb Simulation", option="LPE")
  607. legend.SetTextFont(132)
  608. legend.SetTextSize(0.04)
  609. legend.Draw()
  610. # if histo != "nPV":
  611. # latex.DrawLatex(0.7, 0.85, "LHCb simulation")
  612. # else:
  613. # latex.DrawLatex(0.2, 0.85, "LHCb simulation")
  614. # mg.GetYaxis().SetRangeUser(0, 0.4)
  615. if histo == "eta":
  616. mg.GetYaxis().SetRangeUser(0, 0.4)
  617. # track_name = names[tracker] + " tracks"
  618. # latex.DrawLatex(0.7, 0.75, track_name)
  619. # canvas.PlaceLegend()
  620. if savepdf:
  621. filestypes = ["pdf"] # , "png", "eps", "C", "ps", "tex"]
  622. for ftype in filestypes:
  623. canvas.SaveAs(
  624. "checks/" + tracker + "ghost_rate_" + histo + "." + ftype,
  625. )
  626. canvas.Write()
  627. #
  628. # Compare electron efficiencies of different trackers
  629. #
  630. plot_electrons_only = True
  631. if compare:
  632. print("\nCompare Efficiencies: ")
  633. outputfile.cd()
  634. for ncut, jcut in enumerate(
  635. compareCuts
  636. ): # [long, long_fromB, long_fromB_P>5GeV]
  637. compareDir = outputfile.mkdir("compare_" + jcut)
  638. compareDir.cd()
  639. for histo in efficiencyHistos: # [p, pt, phi, eta, nPV]
  640. canvastitle = "efficiency_" + histo + "_" + jcut
  641. name = "efficiency_" + histo + "_" + jcut
  642. canvas = TCanvas(name, canvastitle)
  643. canvas.SetRightMargin(0.1)
  644. mg = TMultiGraph()
  645. dist_eff = {}
  646. dist_hist_den = {}
  647. dist_eff_elec = {}
  648. dist_hist_elec = {}
  649. dist_eff_velo = {}
  650. dist_hist_velo = {}
  651. First = True
  652. First_Velo = True
  653. dist_tracker = ""
  654. dist_tracker_velo = ""
  655. for tracker in trackers: # [BestLong, Forward, Match, Seed]
  656. markeritr = 0
  657. cut = compareDict[jcut][tracker]
  658. folder = folders[tracker]["folder"]
  659. print("folder: " + folder.replace(unique_name_ext_re(), ""))
  660. jcolor = compareColors[tracker]
  661. histoName = (
  662. "Track/"
  663. + folder
  664. + tracker
  665. + "/"
  666. + cut
  667. + "_"
  668. + ""
  669. + efficiencyHistoDict[histo]["variable"]
  670. )
  671. print(
  672. "not electrons: " + histoName.replace(unique_name_ext_re(), "")
  673. )
  674. eff = {}
  675. hist_den = {}
  676. eff, hist_den = get_eff(eff, hist_den, tf, histoName, label, histo)
  677. if categories[tracker][cut]["plotElectrons"] and plot_electrons:
  678. histoNameElec = (
  679. "Track/"
  680. + folder
  681. + tracker
  682. + "/"
  683. + categories[tracker][cut]["Electrons"]
  684. )
  685. histoName_e = (
  686. histoNameElec + "_" + efficiencyHistoDict[histo]["variable"]
  687. )
  688. print(
  689. "electrons: "
  690. + histoName_e.replace(unique_name_ext_re(), "")
  691. )
  692. eff_elec = {}
  693. hist_elec = {}
  694. eff_elec, hist_elec = get_eff(
  695. eff_elec,
  696. hist_elec,
  697. tf,
  698. histoName_e,
  699. label,
  700. histo,
  701. )
  702. if First:
  703. dist_eff_elec = eff_elec
  704. dist_hist_elec = hist_elec
  705. if (
  706. categories[tracker][cut]["plotEndVelo"]
  707. and plot_velo
  708. and (histo == "p" or histo == "pt")
  709. ):
  710. histoNameEndVelo = (
  711. "Track/"
  712. + folder
  713. + tracker
  714. + "/"
  715. + categories[tracker][cut]["EndVelo"]
  716. )
  717. histoName_v = (
  718. histoNameEndVelo
  719. + "_"
  720. + efficiencyHistoDict[histo]["variable"]
  721. )
  722. print(
  723. "EndVelo: "
  724. + histoName_v.replace(unique_name_ext_re(), "")
  725. )
  726. eff_velo = {}
  727. hist_velo = {}
  728. eff_velo, hist_velo = get_eff(
  729. eff_velo,
  730. hist_velo,
  731. tf,
  732. histoName_v,
  733. label,
  734. histo,
  735. )
  736. if First:
  737. dist_eff_velo = eff_velo
  738. dist_hist_velo = hist_velo
  739. # dist_tracker_velo = tracker
  740. # First_Velo = False
  741. if First:
  742. dist_tracker = tracker
  743. dist_eff = eff
  744. dist_hist_den = hist_den
  745. First = False
  746. seeditr = 0
  747. for i, lab in enumerate(label):
  748. if categories[tracker][cut]["plotElectrons"] and plot_electrons:
  749. if not plot_velo_only or (
  750. histo == "phi" or histo == "eta" or histo == "nPV"
  751. ):
  752. if (tracker == "Seed") and (seeditr != 0):
  753. continue
  754. if tracker == "Seed":
  755. seeditr += 1
  756. mg.Add(eff_elec[lab])
  757. set_style(
  758. eff_elec[lab],
  759. colors[jcolor],
  760. markers[i + markeritr],
  761. styles[i],
  762. )
  763. else:
  764. mg.Add(eff_elec[lab])
  765. set_style(
  766. eff_elec[lab],
  767. elec_colors[jcolor + markeritr],
  768. markers[i + markeritr],
  769. styles[i],
  770. )
  771. if (
  772. categories[tracker][cut]["plotEndVelo"]
  773. and plot_velo
  774. and (histo == "p" or histo == "pt")
  775. ):
  776. if (tracker == "Seed") and (seeditr != 0):
  777. continue
  778. if tracker == "Seed":
  779. seeditr += 1
  780. mg.Add(eff_elec[lab])
  781. set_style(
  782. eff_elec[lab],
  783. colors[jcolor],
  784. markers[i + markeritr],
  785. styles[i],
  786. )
  787. else:
  788. mg.Add(eff_velo[lab])
  789. set_style(
  790. eff_velo[lab],
  791. elec_colors[jcolor + markeritr],
  792. markers[i + markeritr],
  793. styles[i],
  794. )
  795. markeritr = markeritr + 1
  796. mg.Draw("AP")
  797. mg.GetYaxis().SetRangeUser(0, 1.05)
  798. xtitle = efficiencyHistoDict[histo]["xTitle"]
  799. unit_l = xtitle.split("[")
  800. if "]" in unit_l[-1]:
  801. unit = unit_l[-1].replace("]", "")
  802. else:
  803. unit = "a.u."
  804. print(unit)
  805. mg.GetXaxis().SetTitle(xtitle)
  806. mg.GetXaxis().SetTitleSize(0.06)
  807. mg.GetYaxis().SetTitle(
  808. "Efficiency of Long Tracks",
  809. ) # (" + str(round(hist_den[label[0]].GetBinWidth(1), 2)) + f"{unit})"+"^{-1}")
  810. mg.GetYaxis().SetTitleSize(0.06)
  811. mg.GetYaxis().SetTitleOffset(1.1)
  812. mg.GetXaxis().SetRangeUser(*efficiencyHistoDict[histo]["range"])
  813. mg.GetXaxis().SetNdivisions(10, 5, 0)
  814. mygray = 18
  815. myblue = kBlue - 10
  816. mypurple = kMagenta - 7
  817. dist_cut = compareDict[jcut][dist_tracker]
  818. # dist_cut_velo = compareDict[jcut][dist_tracker_velo]
  819. for i, lab in enumerate(label):
  820. rightmax = 1.05 * dist_hist_den[lab].GetMaximum()
  821. scale = gPad.GetUymax() / rightmax
  822. dist_hist_den[lab].Scale(scale)
  823. if (
  824. categories[dist_tracker][dist_cut]["plotElectrons"]
  825. and plot_electrons
  826. ):
  827. rightmax = 1.05 * dist_hist_elec[lab].GetMaximum()
  828. scale = gPad.GetUymax() / rightmax
  829. dist_hist_elec[lab].Scale(scale)
  830. if (
  831. categories[dist_tracker][dist_cut]["plotEndVelo"]
  832. and plot_velo
  833. and (histo == "p" or histo == "pt")
  834. ):
  835. rightmax = 1.05 * dist_hist_velo[lab].GetMaximum()
  836. scale = gPad.GetUymax() / rightmax
  837. dist_hist_velo[lab].Scale(scale)
  838. if i == len(label) - 1:
  839. if not plot_electrons_only: # and not plot_velo_only:
  840. set_style(dist_hist_den[lab], mygray, markers[i], styles[i])
  841. # gStyle.SetPalette(2, array("i", [mygray - 1, myblue + 1]))
  842. dist_hist_den[lab].SetFillColorAlpha(mygray, 0.5)
  843. dist_hist_den[lab].Draw("HIST PLC SAME")
  844. if (
  845. categories[dist_tracker][dist_cut]["plotElectrons"]
  846. and plot_electrons
  847. ):
  848. if not plot_velo_only or (
  849. histo == "phi" or histo == "eta" or histo == "nPV"
  850. ):
  851. set_style(
  852. dist_hist_elec[lab], mygray, markers[i], styles[i]
  853. )
  854. # gStyle.SetPalette(2, array("i", [mygray - 1, myblue + 1]))
  855. # dist_hist_elec[lab].SetFillColor(myblue)
  856. dist_hist_elec[lab].SetFillColorAlpha(mygray, 0.5)
  857. dist_hist_elec[lab].Draw("HIST PLC SAME")
  858. if (
  859. categories[dist_tracker][dist_cut]["plotEndVelo"]
  860. and plot_velo
  861. and (histo == "p" or histo == "pt")
  862. ):
  863. set_style(
  864. dist_hist_velo[lab], mygray, markers[i], styles[i]
  865. )
  866. dist_hist_velo[lab].SetFillColorAlpha(mygray, 0.5)
  867. dist_hist_velo[lab].Draw("HIST PLC SAME")
  868. # else:
  869. # print(
  870. # "No distribution plotted for other labels.",
  871. # "Can be added by uncommenting the code below this print statement.",
  872. # )
  873. # set_style(dist_hist_den[lab], mygray, markers[i], styles[i])
  874. # gStyle.SetPalette(2, array("i", [mygray - 1, myblue + 1]))
  875. # dist_hist_den[lab].Draw("HIST PLC SAME")
  876. if histo == "p":
  877. pos = [0.5, 0.35, 1.0, 0.7] # [0.53, 0.4, 1.01, 0.71]
  878. elif histo == "pt":
  879. pos = [0.5, 0.3, 0.99, 0.5] # [0.5, 0.4, 0.98, 0.71]
  880. elif histo == "phi":
  881. pos = [0.4, 0.3, 0.9, 0.5]
  882. elif histo == "eta":
  883. pos = [0.5, 0.25, 1.0, 0.45]
  884. else:
  885. pos = [0.35, 0.25, 0.85, 0.45]
  886. legend = place_legend(
  887. canvas, *pos, header="LHCb Simulation", option="LPE"
  888. )
  889. for le in legend.GetListOfPrimitives():
  890. if "distribution" in le.GetLabel():
  891. le.SetOption("LF")
  892. legend.SetTextFont(132)
  893. legend.SetTextSize(0.04)
  894. legend.Draw()
  895. for lab in label:
  896. if not plot_electrons_only: # and not plot_velo_only:
  897. dist_eff[lab].Draw("P SAME")
  898. if categories[tracker][cut]["plotElectrons"] and plot_electrons:
  899. if not plot_velo_only or (
  900. histo == "phi" or histo == "eta" or histo == "nPV"
  901. ):
  902. dist_eff_elec[lab].Draw("P SAME")
  903. if (
  904. categories[tracker][cut]["plotEndVelo"]
  905. and plot_velo
  906. and (histo == "p" or histo == "pt")
  907. ):
  908. dist_eff_velo[lab].Draw("P SAME")
  909. cutName = categories[tracker][cut]["title"]
  910. latex.DrawLatex(legend.GetX1() + 0.01, legend.GetY1() - 0.05, cutName)
  911. low = 0
  912. high = 1.05
  913. gPad.Update()
  914. axis = TGaxis(
  915. gPad.GetUxmax(),
  916. gPad.GetUymin(),
  917. gPad.GetUxmax(),
  918. gPad.GetUymax(),
  919. low,
  920. high,
  921. 510,
  922. "+U",
  923. )
  924. axis.SetTitleFont(132)
  925. axis.SetTitleSize(0.06)
  926. axis.SetTitleOffset(0.55)
  927. axis.SetTitle(
  928. "# Tracks " + get_nicer_var_string(histo) + " distribution [a.u.]",
  929. )
  930. axis.SetLabelSize(0)
  931. axis.Draw()
  932. # canvas.Draw()
  933. canvas.RedrawAxis()
  934. # canvas.PlaceLegend()
  935. if savepdf:
  936. filestypes = ["pdf"] # , "png", "eps", "C", "ps", "tex"]
  937. for ftype in filestypes:
  938. if not plot_electrons_only:
  939. canvasName = (
  940. "Compare_"
  941. + str(ncut)
  942. + "_"
  943. + jcut
  944. + "_"
  945. + histo
  946. + "."
  947. + ftype
  948. )
  949. else:
  950. canvasName = (
  951. "Compare_Electrons_"
  952. + str(ncut)
  953. + "_"
  954. + jcut
  955. + "_"
  956. + histo
  957. + "."
  958. + ftype
  959. )
  960. canvas.SaveAs("checks/" + canvasName)
  961. # canvas.SetRightMargin(0.05)
  962. canvas.Write()
  963. outputfile.cd()
  964. outputfile.Write()
  965. outputfile.Close()
  966. if __name__ == "__main__":
  967. parser = argument_parser()
  968. args = parser.parse_args()
  969. PrCheckerEfficiency(**vars(args))