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.

1063 lines
41 KiB

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