Belle II Software  light-2212-foldex
test6_CPVFlavorTaggerEfficiency.py
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 
4 
11 
12 """
13 <header>
14  <input>CPVToolsOutput.root</input>
15  <output>test6_CPVFlavorTaggerEfficiency.root</output>
16  <contact>Yo Sato; yosato@post.kek.jp</contact>
17  <description>This file calculates the effective efficiency of the category based flavor tagger considering the two
18  standard combiners and the individual categories. Validation plots are also produced. </description>
19 </header>
20 """
21 
22 import ROOT
23 from array import array
24 
25 ROOT.gROOT.SetBatch(True)
26 
27 workingFiles = ["../CPVToolsOutput.root"]
28 treeName = str("B0tree")
29 
30 
31 workingDirectory = '.'
32 
33 #
34 # *******************************************
35 # DETERMINATION OF TOTAL EFFECTIVE EFFICIENCY
36 # *******************************************
37 #
38 
39 r_subsample = array('d', [
40  0.0,
41  0.1,
42  0.25,
43  0.5,
44  0.625,
45  0.75,
46  0.875,
47  1.0])
48 r_size = len(r_subsample)
49 average_eff = 0
50 
51 # All possible Categories
52 categories = [
53  'Electron',
54  'IntermediateElectron',
55  'Muon',
56  'IntermediateMuon',
57  'KinLepton',
58  'IntermediateKinLepton',
59  'Kaon',
60  'KaonPion',
61  'SlowPion',
62  'FSC',
63  'MaximumPstar',
64  'FastHadron',
65  'Lambda']
66 
67 
68 methods = []
69 
70 
71 class Quiet:
72  """Context handler class to quiet errors in a 'with' statement"""
73 
74  def __init__(self, level=ROOT.kInfo + 1):
75  """Class constructor"""
76 
77  self.levellevel = level
78 
79  def __enter__(self):
80  """Enter the context"""
81 
82  self.oldleveloldlevel = ROOT.gErrorIgnoreLevel
83  ROOT.gErrorIgnoreLevel = self.levellevel
84 
85  def __exit__(self, type, value, traceback):
86  """Exit the context"""
87  ROOT.gErrorIgnoreLevel = self.oldleveloldlevel
88 
89 
90 tree = ROOT.TChain(treeName)
91 
92 mcstatus = array('d', [-511.5, 0.0, 511.5])
93 ROOT.TH1.SetDefaultSumw2()
94 
95 for iFile in workingFiles:
96  tree.AddFile(iFile)
97 
98 totalBranches = []
99 for branch in tree.GetListOfBranches():
100  totalBranches.append(branch.GetName())
101 
102 if 'FBDT_qrCombined' in totalBranches:
103  methods.append("FBDT")
104 
105 usedCategories = []
106 for cat in categories:
107  catBranch = 'qp' + cat
108  if catBranch in totalBranches:
109  usedCategories.append(cat)
110 
111 categoriesNtupleList = str()
112 for category in usedCategories:
113  categoriesNtupleList = categoriesNtupleList + "Eff_%s:" % category
114 
115 
116 # Output Validation file
117 outputFile = ROOT.TFile("test6_CPVFlavorTaggerEfficiency.root", "RECREATE")
118 
119 # Values to be watched
120 outputNtuple = ROOT.TNtuple(
121  "FT_Efficiencies",
122  "Effective efficiencies of the flavor tagger combiners as well as of the individual tagging categories.",
123  "Eff_FBDT:DeltaEff_FBDT:" + categoriesNtupleList)
124 
125 outputNtuple.SetAlias('Description', "These are the effective efficiencies of the flavor tagger combiners as well as of " +
126  "the individual tagging efficiencies.")
127 outputNtuple.SetAlias(
128  'Check',
129  "These values should not change drastically. Since the nightly reconstruction validation runs" +
130  "on the same input file (which changes only from release to release), the values between builds should be the same.")
131 outputNtuple.SetAlias('Contact', "yosato@post.kek.jp")
132 
133 efficienciesForNtuple = []
134 
135 YmaxForQrPlot = 0
136 
137 for method in methods:
138  # histogram contains the average r in each of 7 bins -> calculation see below
139  histo_avr_r = ROOT.TH1F('Average_r', 'Average r in each of 7 bins (B0 and B0bar)', 7,
140  r_subsample)
141  histo_avr_rB0 = ROOT.TH1F('Average_rB0', 'Average r in each of 7 bins (B0)', 7,
142  r_subsample)
143  histo_avr_rB0bar = ROOT.TH1F('Average_rB0bar', 'Average r in each of 7 bins (B0bar)', 7,
144  r_subsample)
145  # histogram with number of entries in for each bin
146  histo_entries_per_bin = ROOT.TH1F(
147  'entries_per_bin',
148  'Events binned in r_subsample according to their r-value for B0 and B0bar prob',
149  7,
150  r_subsample)
151  histo_entries_per_binB0 = ROOT.TH1F('entries_per_binB0', 'Events binned in r_subsample according '
152  'to their r-value for B0 prob', 7, r_subsample)
153  histo_entries_per_binB0bar = ROOT.TH1F('entries_per_binB0bar',
154  'Events binned in r_subsample according to their r-value '
155  'for B0bar prob', 7, r_subsample)
156  # histogram network output (not qr and not r) for true B0 (signal) - not necessary
157  histo_Cnet_output_B0 = ROOT.TH1F('Comb_Net_Output_B0', 'Combiner network output [not equal to r] '
158  'for true B0 (binning 100)', 100, 0.0, 1.0)
159  # histogram network output (not qr and not r) for true B0bar (background) - not necessary
160  histo_Cnet_output_B0bar = ROOT.TH1F('Comb_Net_Output_B0bar', 'Combiner network output [not equal to r] '
161  'for true B0bar (binning 100)', 100, 0.0, 1.0)
162  # histogram containing the belle paper plot (qr-tagger output for true B0)
163  histo_belleplotB0 = ROOT.TH1F('qr_' + method + '_B0',
164  'BellePlot for true B0 (binning 50)', 50,
165  -1.0, 1.0)
166  # histogram containing the belle paper plot (qr-tagger output for true B0bar)
167  histo_belleplotB0bar = ROOT.TH1F('qr_' + method + '_B0Bar',
168  'BellePlot for true B0Bar (binning 50)',
169  50, -1.0, 1.0)
170 
171  # histogram containing the qr plot (qr-tagger output)
172  histo_belleplotBoth = ROOT.TH1F('qr_' + method + '_B0Both',
173  'qr-tagger output (binning 50)',
174  50, -1.0, 1.0)
175  # calibration plot for B0. If we get a linear line our MC is fine, than the assumption r ~ 1- 2w is reasonable
176  # expectation is, that for B0 calibration plot: qr=0 half B0 and half B0bar, qr = 1 only B0 and qr = -1
177  # no B0. Inverse for B0bar calibration plot
178  histo_calib_B0 = ROOT.TH1F('Calibration_' + method + '_B0', 'CalibrationPlot for true B0', 100, -1.0, 1.0)
179  # calibration plot for B0bar calibration plot
180  histo_calib_B0bar = ROOT.TH1F('Calibration_' + method + '_B0Bar',
181  'CalibrationPlot for true B0Bar', 100, -1.0,
182  1.0)
183  # belle plot with true B0 and B0bars
184  hallo12 = ROOT.TH1F('BellePlot_NoCut', 'BellePlot_NoCut (binning 100)',
185  100, -1.0, 1.0)
186 
187 
188  diag = ROOT.TF1('diag', 'pol1', -1, 1)
189 
190 
191  # histograms for the efficiency calculation in wrong way
192  histo_m0 = ROOT.TH1F('BellePlot_B0_m0',
193  'BellePlot_m for true B0 (binning 50)', 50, -1.0, 1.0)
194  histo_m1 = ROOT.TH1F('BellePlot_B0_m1',
195  'BellePlot_m for true B0 (binning 50)', 50, -1.0, 1.0)
196  histo_m2 = ROOT.TH1F('BellePlot_B0_m2',
197  'BellePlot_m for true B0Bar (binning 50)', 50, -1.0,
198  1.0)
199 
200  # filling the histograms
201 
202  tree.Draw(method + '_qrCombined>>qr_' + method + '_B0', 'qrMC == 1')
203  tree.Draw(method + '_qrCombined>>qr_' + method + '_B0Bar', 'qrMC == -1')
204  tree.Draw(method + '_qrCombined>>BellePlot_NoCut', 'abs(qrMC) == 1')
205  tree.Draw(method + '_qrCombined>>qr_' + method + '_B0Both', 'abs(qrMC) == 1')
206 
207  tree.Draw(method + '_qrCombined>>Calibration_' + method + '_B0', 'qrMC == 1')
208  tree.Draw(method + '_qrCombined>>Calibration_' + method + '_B0Bar', 'qrMC == -1')
209 
210  # filling histograms wrong efficiency calculation
211  tree.Draw(method + '_qrCombined>>BellePlot_B0_m0',
212  'qrMC == 1 && ' + method + '_qrCombined>0')
213  tree.Draw(method + '_qrCombined>>BellePlot_B0_m1',
214  'qrMC == 1 && ' + method + '_qrCombined<0')
215  tree.Draw(method + '_qrCombined>>BellePlot_B0_m2',
216  'qrMC == -1 && ' + method + '_qrCombined>0 ')
217 
218  # filling with abs(qr) in one of 7 bins with its weight
219  # separate calculation for B0 and B0bar
220 
221  tree.Project('Average_r', 'abs(' + method + '_qrCombined)',
222  'abs(' + method + '_qrCombined)')
223  tree.Project('Average_rB0', 'abs(' + method + '_qrCombined)', 'abs(' + method + '_qrCombined)*(qrMC==1)')
224  tree.Project('Average_rB0bar', 'abs(' + method + '_qrCombined)', 'abs(' + method + '_qrCombined)*(qrMC==-1)')
225 
226  # filling with abs(qr) in one of 7 bins
227  tree.Project('entries_per_bin', 'abs(' + method + '_qrCombined)', 'abs(qrMC) == 1')
228  tree.Project('entries_per_binB0', 'abs(' + method + '_qrCombined)', 'qrMC == 1')
229  tree.Project('entries_per_binB0bar', 'abs(' + method + '_qrCombined)', 'qrMC == -1')
230 
231  # producing the average r histograms
232  histo_avr_r.Divide(histo_entries_per_bin)
233  histo_avr_rB0.Divide(histo_entries_per_binB0)
234  histo_avr_rB0bar.Divide(histo_entries_per_binB0bar)
235 
236  # producing the calibration plots
237  # Errors ok
238  histo_calib_B0.Divide(hallo12)
239  histo_calib_B0bar.Divide(hallo12)
240 
241  # Fit for calibration plot
242  print(' ')
243  print('****************** CALIBRATION CHECK FOR COMBINER USING ' + method + ' ***************************************')
244  print(' ')
245  print('Fit polynomial of first order to the calibration plot. Expected value ~0.5')
246  print(' ')
247  histo_calib_B0.Fit(diag, 'TEST')
248  print(' ')
249  print('****************** MEASURED EFFECTIVE EFFICIENCY FOR COMBINER USING ' + method + ' ***************************')
250  print('* *')
251  # get total number of entries
252  total_entries = histo_entries_per_bin.GetEntries()
253  total_entries_B0 = histo_entries_per_binB0.GetEntries()
254  total_entries_B0bar = histo_entries_per_binB0bar.GetEntries()
255  tot_eff_effB0 = 0
256  tot_eff_effB0bar = 0
257  event_fractionB0 = array('f', [0] * r_size)
258  event_fractionB0bar = array('f', [0] * r_size)
259  event_fractionTotal = array('f', [0] * r_size)
260  event_fractionDiff = array('f', [0] * r_size)
261  rvalueB0 = array('f', [0] * r_size)
262  rvalueB0bar = array('f', [0] * r_size)
263  rvalueB0Average = array('f', [0] * r_size)
264  wvalue = array('f', [0] * r_size)
265  wvalueB0 = array('f', [0] * r_size)
266  wvalueB0bar = array('f', [0] * r_size)
267  wvalueDiff = array('f', [0] * r_size)
268  entries = array('f', [0] * r_size)
269  entriesB0 = array('f', [0] * r_size)
270  entriesB0bar = array('f', [0] * r_size)
271  iEffEfficiency = array('f', [0] * r_size)
272  iDeltaEffEfficiency = array('f', [0] * r_size)
273  # intervallEff = array('f', [0] * r_size)
274  performance = []
275  for i in range(1, r_size):
276  # get the average r-value
277  rvalueB0[i] = histo_avr_rB0.GetBinContent(i)
278  rvalueB0bar[i] = histo_avr_rB0bar.GetBinContent(i)
279  rvalueB0Average[i] = (rvalueB0[i] + rvalueB0bar[i]) / 2
280  # calculate the wrong tag fraction (only true if MC data good)
281  wvalue[i] = (1 - rvalueB0Average[i]) / 2
282  wvalueB0[i] = (1 - rvalueB0[i]) / 2
283  wvalueB0bar[i] = (1 - rvalueB0bar[i]) / 2
284  wvalueDiff[i] = wvalueB0[i] - wvalueB0bar[i]
285  entries[i] = histo_entries_per_bin.GetBinContent(i)
286  entriesB0[i] = histo_entries_per_binB0.GetBinContent(i)
287  entriesB0bar[i] = histo_entries_per_binB0bar.GetBinContent(i)
288  # fraction of events/all events
289  event_fractionTotal[i] = (entriesB0[i] + entriesB0bar[i]) / total_entries
290  event_fractionDiff[i] = (entriesB0[i] - entriesB0bar[i]) / total_entries
291  event_fractionB0[i] = entriesB0[i] / total_entries_B0
292  event_fractionB0bar[i] = entriesB0bar[i] / total_entries_B0bar
293  iEffEfficiency[i] = (event_fractionB0[i] * rvalueB0[i] * rvalueB0[i] +
294  event_fractionB0bar[i] * rvalueB0bar[i] * rvalueB0bar[i]) / 2
295  iDeltaEffEfficiency[i] = event_fractionB0[i] * rvalueB0[i] * \
296  rvalueB0[i] - event_fractionB0bar[i] * rvalueB0bar[i] * rvalueB0bar[i]
297  # finally calculating the total effective efficiency
298  tot_eff_effB0 = tot_eff_effB0 + event_fractionB0[i] * rvalueB0[i] * rvalueB0[i]
299  tot_eff_effB0bar = tot_eff_effB0bar + event_fractionB0bar[i] * rvalueB0bar[i] * rvalueB0bar[i]
300 
301  average_eff = (tot_eff_effB0 + tot_eff_effB0bar) / 2
302  diff_eff = tot_eff_effB0 - tot_eff_effB0bar
303  print('* ------------------------------------------------------------------------------------------------ *')
304  print('* *')
305  print('* __________________________________________________________________________________________ *')
306  print('* | | *')
307  print('* | TOTAL NUMBER OF TAGGED EVENTS = ' +
308  '{:<24}'.format("%.0f" % total_entries) + '{:>36}'.format('| *'))
309  print('* | | *')
310  print('* | TOTAL AVERAGE EFFECTIVE EFFICIENCY (q=+-1)= ' + '{:.2f}'.format(average_eff * 100) +
311  ' % | *')
312  print('* | | *')
313  print('* | B0-TAGGER TOTAL EFFECTIVE EFFICIENCIES: ' +
314  '{:.2f}'.format(tot_eff_effB0 * 100) + ' % (q=+1) ' +
315  '{:.2f}'.format(tot_eff_effB0bar * 100) + ' % (q=-1) EffDiff=' +
316  '{:^5.2f}'.format(diff_eff * 100) + ' % | *')
317  print('* | | *')
318  print('* | FLAVOR PERCENTAGE (MC): ' +
319  '{:.2f}'.format(total_entries_B0 / total_entries * 100) + ' % (q=+1) ' +
320  '{:.2f}'.format(total_entries_B0bar / total_entries * 100) + ' % (q=-1) Diff=' +
321  '{:^5.2f}'.format((total_entries_B0 - total_entries_B0bar) / total_entries * 100) + ' % | *')
322  print('* |__________________________________________________________________________________________| *')
323  print('* *')
324  print('****************************************************************************************************')
325  print('* *')
326 
327  efficienciesForNtuple.append(float(average_eff * 100))
328  efficienciesForNtuple.append(float(diff_eff * 100))
329 
330  maxB0 = histo_belleplotB0.GetBinContent(histo_belleplotB0.GetMaximumBin())
331  maxB0bar = histo_belleplotB0bar.GetBinContent(histo_belleplotB0bar.GetMaximumBin())
332  maxB0Both = histo_belleplotBoth.GetBinContent(histo_belleplotBoth.GetMaximumBin())
333 
334  Ymax = max(maxB0, maxB0bar, maxB0Both)
335  Ymax = Ymax + Ymax / 12
336 
337  if YmaxForQrPlot < Ymax:
338  YmaxForQrPlot = Ymax
339 
340  # produce a pdf
341  ROOT.gStyle.SetOptStat(0)
342  with Quiet(ROOT.kError):
343  Canvas1 = ROOT.TCanvas('Bla', 'Final Output', 1200, 800)
344  Canvas1.cd() # activate
345  Canvas1.SetLeftMargin(0.13)
346  Canvas1.SetRightMargin(0.04)
347  Canvas1.SetTopMargin(0.03)
348  Canvas1.SetBottomMargin(0.14)
349  histo_belleplotB0.SetFillColorAlpha(ROOT.kBlue, 0.2)
350  histo_belleplotB0.SetFillStyle(1001)
351  histo_belleplotB0.GetXaxis().SetLabelSize(0.04)
352  histo_belleplotB0.GetYaxis().SetLabelSize(0.04)
353  histo_belleplotB0.GetYaxis().SetTitleOffset(0.9)
354  histo_belleplotB0.GetXaxis().SetTitleSize(0.06)
355  histo_belleplotB0.GetYaxis().SetTitleSize(0.06)
356  histo_belleplotB0.GetYaxis().SetLimits(0, YmaxForQrPlot)
357  histo_belleplotB0.SetLineColor(ROOT.kBlue)
358  histo_belleplotB0bar.SetFillColorAlpha(ROOT.kRed, 1.0)
359  histo_belleplotB0bar.SetFillStyle(3005)
360  histo_belleplotB0bar.SetLineColor(ROOT.kRed)
361  # SetLabelSize etc SetTitle
362 
363  histo_belleplotB0.SetTitle('; #it{qr}_{' + method + '} ; Events (Total = ' + '{:<1}'.format("%.0f" % total_entries) + ')'
364  )
365  histo_belleplotB0.SetMinimum(0)
366  histo_belleplotB0.SetMaximum(YmaxForQrPlot)
367  histo_belleplotB0.Draw('hist')
368  histo_belleplotB0bar.Draw('hist same')
369 
370  leg = ROOT.TLegend(0.2, 0.7, 0.9, 0.95)
371  leg.AddEntry(
372  histo_belleplotB0,
373  'true B^{0} ' +
374  ' #varepsilon_{eff}(B^{0}) = ' +
375  '{:.2f}'.format(
376  tot_eff_effB0 *
377  100) +
378  '% #frac{n_{B^{0}}}{n} = ' +
379  '{:.2f}'.format(
380  total_entries_B0 /
381  total_entries *
382  100) +
383  '%')
384  leg.AddEntry(
385  histo_belleplotB0bar,
386  'true #bar{B}^{0} ' +
387  ' #varepsilon_{eff}(#bar{B}^{0}) = ' +
388  '{:.2f}'.format(
389  tot_eff_effB0bar *
390  100) +
391  '% #frac{n_{#bar{B}^{0}}}{n} = ' +
392  '{:.2f}'.format(
393  total_entries_B0bar /
394  total_entries *
395  100) +
396  '%')
397  leg.AddEntry("", "Avrg. #bf{ #varepsilon_{eff} = " + '{:.2f}'.format(average_eff * 100) +
398  '%} #Delta#varepsilon_{eff} = ' + '{:^5.2f}'.format(diff_eff * 100) + '%')
399  leg.SetTextSize(0.045)
400  leg.Draw()
401 
402  Canvas1.Update()
403 
404  with Quiet(ROOT.kError):
405  Canvas1.SaveAs(workingDirectory + '/' + 'test6_CPVFTqr' + method + '_both.pdf')
406 
407  # Validation Plot 1
408  histo_belleplotBoth.GetXaxis().SetLabelSize(0.04)
409  histo_belleplotBoth.GetYaxis().SetLabelSize(0.04)
410  histo_belleplotBoth.GetYaxis().SetTitleOffset(0.7)
411  histo_belleplotBoth.GetXaxis().SetTitleOffset(0.7)
412  histo_belleplotBoth.GetXaxis().SetTitleSize(0.06)
413  histo_belleplotBoth.GetYaxis().SetTitleSize(0.06)
414 
415  histo_belleplotBoth.GetListOfFunctions().Add(ROOT.TNamed('MetaOptions', 'nostats'))
416  histo_belleplotBoth.GetListOfFunctions().Add(ROOT.TNamed('Description', 'Output of the flavor tagger combiner ' + method))
417  histo_belleplotBoth.GetListOfFunctions().Add(
418  ROOT.TNamed(
419  'Check',
420  'Shape should not change drastically. E.g. Warning if the peak at 0 increases or if the peaks at +-1 decrease.'))
421  histo_belleplotBoth.GetListOfFunctions().Add(ROOT.TNamed('Contact', 'yosato@post.kek.jp'))
422 
423  histo_belleplotBoth.SetTitle(
424  'Flavor tagger output for combiner ' +
425  method +
426  '; #it{qr}_{' +
427  method +
428  '} ; Events (Total = ' +
429  '{:<1}'.format(
430  "%.0f" %
431  total_entries) +
432  ')')
433  histo_belleplotBoth.SetMinimum(0)
434  histo_belleplotBoth.SetMaximum(YmaxForQrPlot)
435  histo_belleplotBoth.SetStats(False)
436  histo_belleplotBoth.Write()
437 
438  # Validation Plot 2
439  histo_belleplotB0.GetYaxis().SetTitleOffset(0.7)
440  histo_belleplotB0.GetXaxis().SetTitleOffset(0.7)
441  histo_belleplotB0.SetLineColor(ROOT.kBlue + 2)
442  histo_belleplotB0.SetTitle(
443  'Flavor tagger output for combiner ' +
444  method +
445  ' for true B^{0}s; #it{qr}_{' +
446  method +
447  '} ; Events (Total = ' +
448  '{:<1}'.format(
449  "%.0f" %
450  histo_belleplotB0.GetEntries()) +
451  ')')
452  histo_belleplotB0.SetStats(False)
453 
454  histo_belleplotB0.GetListOfFunctions().Add(ROOT.TNamed('MetaOptions', 'nostats'))
455  histo_belleplotB0.GetListOfFunctions().Add(
456  ROOT.TNamed('Description', 'Output of the flavor tagger combiner ' + method + ' for true B0s'))
457  histo_belleplotB0.GetListOfFunctions().Add(
458  ROOT.TNamed(
459  'Check',
460  'Shape should not change drastically. E.g. Warning if the peak at 0 increases or if the peak at +1 decreases.'))
461  histo_belleplotB0.GetListOfFunctions().Add(ROOT.TNamed('Contact', 'yosato@post.kek.jp'))
462  histo_belleplotB0.Write()
463 
464  # Validation Plot 3
465  histo_belleplotB0bar.GetXaxis().SetLabelSize(0.04)
466  histo_belleplotB0bar.GetYaxis().SetLabelSize(0.04)
467  histo_belleplotB0bar.GetYaxis().SetTitleOffset(0.7)
468  histo_belleplotB0bar.GetXaxis().SetTitleOffset(0.7)
469  histo_belleplotB0bar.GetXaxis().SetTitleSize(0.06)
470  histo_belleplotB0bar.GetYaxis().SetTitleSize(0.06)
471  histo_belleplotB0bar.SetLineColor(ROOT.kBlue + 2)
472  histo_belleplotB0bar.SetTitle(
473  'Flavor tagger output for combiner ' +
474  method +
475  ' for true #bar{B}^{0}s; #it{qr}_{' +
476  method +
477  '} ; Events (Total = ' +
478  '{:<1}'.format(
479  "%.0f" %
480  histo_belleplotB0bar.GetEntries()) +
481  ')')
482  histo_belleplotB0bar.SetMinimum(0)
483  histo_belleplotB0bar.SetMaximum(YmaxForQrPlot)
484  histo_belleplotB0bar.SetStats(False)
485 
486  histo_belleplotB0bar.GetListOfFunctions().Add(ROOT.TNamed('MetaOptions', 'nostats'))
487  histo_belleplotB0bar.GetListOfFunctions().Add(
488  ROOT.TNamed(
489  'Description',
490  'Output of the flavor tagger combiner ' +
491  method +
492  ' for true B0bars'))
493  histo_belleplotB0bar.GetListOfFunctions().Add(ROOT.TNamed(
494  'Check', 'Shape should not change drastically. E.g. Warning if the peak at 0 increases or if the peak at -1 decreases.'))
495  histo_belleplotB0bar.GetListOfFunctions().Add(ROOT.TNamed('Contact', 'yosato@post.kek.jp'))
496  histo_belleplotB0bar.Write()
497 
498  # IPython.embed()
499 
500  # produce the nice calibration plot
501  with Quiet(ROOT.kError):
502  Canvas2 = ROOT.TCanvas('Bla2', 'Calibration plot for true B0', 1200, 800)
503  Canvas2.cd() # activate
504  Canvas2.SetLeftMargin(0.13)
505  Canvas2.SetRightMargin(0.04)
506  Canvas2.SetTopMargin(0.03)
507  Canvas2.SetBottomMargin(0.14)
508  histo_calib_B0.GetXaxis().SetLabelSize(0.04)
509  histo_calib_B0.GetYaxis().SetLabelSize(0.04)
510  histo_calib_B0.GetYaxis().SetTitleOffset(0.9)
511  histo_calib_B0.GetXaxis().SetTitleSize(0.06)
512  histo_calib_B0.GetYaxis().SetTitleSize(0.06)
513  histo_calib_B0.SetFillColorAlpha(ROOT.kBlue, 0.2)
514  histo_calib_B0.SetFillStyle(1001)
515  histo_calib_B0.GetYaxis().SetTitleOffset(0.9)
516  histo_calib_B0.SetLineColor(ROOT.kBlue)
517 
518  histo_calib_B0.SetTitle('; #it{qr}_{' + method + '} ; Calibration '
519  )
520  histo_calib_B0.Draw('hist')
521  diag.Draw('SAME')
522 
523  leg2 = ROOT.TLegend(0.2, 0.75, 0.63, 0.93)
524  leg2.SetHeader(" y = #it{m}#it{x} + #it{c}", "")
525  leg2.GetListOfPrimitives().First().SetTextAlign(22)
526  leg2.AddEntry(
527  diag,
528  "#it{m} = " +
529  '{:.2f}'.format(
530  diag.GetParameter("p1")) +
531  " #it{c} = " +
532  '{:.2f}'.format(
533  diag.GetParameter("p0")))
534  leg2.SetTextSize(0.05)
535  leg2.Draw()
536 
537  Canvas2.Update()
538  with Quiet(ROOT.kError):
539  Canvas2.SaveAs(workingDirectory + '/' + 'test6_CPVFTCalibration_' + method + '_B0.pdf')
540 
541  # Validation Plot 4
542 
543  histo_calib_B0.GetYaxis().SetTitleOffset(0.7)
544  histo_calib_B0.GetXaxis().SetTitleOffset(0.7)
545  histo_calib_B0.SetLineColor(ROOT.kBlue + 2)
546  histo_calib_B0.SetTitle('Calibration plot for the flavor tagger combiner ' +
547  method + ' ; #it{qr}_{' + method + '} ; Calibration')
548  histo_calib_B0.SetMinimum(-0.2)
549  histo_calib_B0.SetMaximum(+1.2)
550  histo_calib_B0.SetStats(False)
551 
552  histo_calib_B0.GetListOfFunctions().Add(ROOT.TNamed('MetaOptions', 'nostats'))
553  histo_calib_B0.GetListOfFunctions().Add(
554  ROOT.TNamed(
555  'Description',
556  'Calibration plot for the flavor tagger combiner ' +
557  method +
558  ' for true B0s'))
559  histo_calib_B0.GetListOfFunctions().Add(
560  ROOT.TNamed('Check', 'Shape should not change drastically. E.g. warning if the shape stops being linear.'))
561  histo_calib_B0.GetListOfFunctions().Add(ROOT.TNamed('Contact', 'yosato@post.kek.jp'))
562  histo_calib_B0.Write()
563 
564  histo_belleplotBoth.Delete()
565  histo_avr_r.Delete()
566  histo_avr_rB0.Delete()
567  histo_avr_rB0bar.Delete()
568  histo_entries_per_bin.Delete()
569  histo_entries_per_binB0.Delete()
570  histo_entries_per_binB0bar.Delete()
571  histo_Cnet_output_B0.Delete()
572  histo_Cnet_output_B0bar.Delete()
573  histo_belleplotB0.Delete()
574  histo_belleplotB0bar.Delete()
575  histo_calib_B0.Delete()
576  histo_calib_B0bar.Delete()
577  hallo12.Delete()
578  histo_m0.Delete()
579  histo_m1.Delete()
580  histo_m2.Delete()
581  Canvas1.Clear()
582  Canvas2.Clear()
583 
584 
585 # **********************************************
586 # DETERMINATION OF INDIVIDUAL EFFECTIVE EFFICIENCY
587 # **********************************************
588 
589 print('************************* MEASURED EFFECTIVE EFFICIENCY FOR INDIVIDUAL CATEGORIES *********************************')
590 print('* *')
591 # input: Classifier input from event-level. Output of event-level is recalculated for input on combiner-level.
592 # but is re-evaluated under combiner target. Signal is B0, background is B0Bar.
593 
594 for category in usedCategories:
595  # histogram of input variable (only signal) - not yet a probability! It's a classifier plot!
596  hist_signal = ROOT.TH1F('Signal_' + category, 'Input Signal (B0)' +
597  category + ' (binning 50)', 50, -1.0, 1.0)
598  # histogram of input variable (only background) - not yet a probability! It's a classifier plot!
599  hist_background = ROOT.TH1F('Background_' + category, 'Input Background (B0bar)' +
600  category + ' (binning 50)', 50, -1.0, 1.0)
601  hist_both = ROOT.TH1F('qp_' + category, 'Input Background (B0bar)' +
602  category + ' (binning 50)', 100, -1, 1)
603 
604  # per definition that input is not comparable to the network output, this has to be transformed.
605  # probability output from 0 to 1 (corresponds to net output probability) -> calculation below
606  hist_probB0 = ROOT.TH1F('ProbabilityB0_' + category,
607  'Transformed to probability (B0) (' + category + ')',
608  50, 0.0, 1.0)
609  hist_probB0bar = ROOT.TH1F('ProbabilityB0bar_' + category,
610  'Transformed to probability (B0bar) (' + category + ')',
611  50, 0.0, 1.0)
612  # qp output from -1 to 1 -> transformation below
613  hist_qpB0 = ROOT.TH1F('QRB0_' + category, 'Transformed to qp (B0)(' +
614  category + ')', 50, -1.0, 1.0)
615  hist_qpB0bar = ROOT.TH1F('QRB0bar_' + category, 'Transformed to qp (B0bar) (' +
616  category + ')', 50, -1.0, 1.0)
617  # histogram for abs(qp), i.e. this histogram contains the r-values -> transformation below
618  # also used to get the number of entries, sorted into 7 bins
619  hist_absqpB0 = ROOT.TH1F('AbsQRB0_' + category, 'Abs(qp)(B0) (' + category + ')', 7, r_subsample)
620  hist_absqpB0bar = ROOT.TH1F('AbsQRB0bar_' + category, 'Abs(qp) (B0bar) (' + category + ')', 7, r_subsample)
621  # histogram contains at the end the average r values -> calculation below
622  # sorted into 7 bins
623  hist_aver_rB0 = ROOT.TH1F('AverageRB0_' + category, 'A good one (B0)' +
624  category, 7, r_subsample)
625  hist_aver_rB0bar = ROOT.TH1F('AverageRB0bar_' + category, 'A good one (B0bar)' +
626  category, 7, r_subsample)
627  # ****** TEST OF CALIBRATION ******
628  # for calibration plot we want to have
629  hist_all = ROOT.TH1F('All_' + category, 'Input Signal (B0) and Background (B0Bar)' +
630  category + ' (binning 50)', 50, 0.0, 1.0)
631  tree.Draw('qp' + category + '>>All_' + category, 'qrMC!=0')
632  hist_calib_B0 = ROOT.TH1F('Calib_B0_' + category, 'Calibration Plot for true B0' +
633  category + ' (binning 50)', 50, 0.0, 1.0)
634  tree.Draw('qp' + category + '>>Calib_B0_' + category, 'qrMC == 1.0')
635  hist_calib_B0.Divide(hist_all)
636 
637  # fill signal
638  tree.Draw('qp' + category + '>>Signal_' + category, 'qrMC == 1.0')
639  # fill background
640  tree.Draw('qp' + category + '>>Background_' + category, 'qrMC == -1.0'
641  )
642  # fill both
643  tree.Draw('qp' + category + '>>qp_' + category, 'abs(qrMC) == 1.0'
644  )
645 
646  # ***** TEST OF CALIBRATION ******
647 
648  # initialize some arrays
649  purityB0 = array('d', [0] * 51)
650  dilutionB02 = array('d', [0] * 51)
651  purityB0bar = array('d', [0] * 51)
652  dilutionB0bar2 = array('d', [0] * 51)
653  signal = array('d', [0] * 51)
654  back = array('d', [0] * 51)
655  weight = array('d', [0] * 51)
656 
657  for i in range(1, 51):
658  # doing the transformation to probabilities
659  signal[i] = hist_signal.GetBinContent(i)
660  back[i] = hist_background.GetBinContent(i)
661 
662  weight[i] = signal[i] + back[i]
663 
664  # avoid dividing by zero
665  if signal[i] + back[i] == 0:
666  purityB0[i] = 0
667  dilutionB02[i] = 0
668  purityB0bar[i] = 0
669  dilutionB0bar2[i] = 0
670  else:
671  purityB0[i] = signal[i] / (signal[i] + back[i])
672  dilutionB02[i] = -1 + 2 * signal[i] / (signal[i] + back[i])
673 
674  purityB0bar[i] = back[i] / (signal[i] + back[i])
675  dilutionB0bar2[i] = -1 + 2 * back[i] / (signal[i] + back[i])
676 
677  # filling histogram with probability from 0 to 1
678  hist_probB0.Fill(purityB0[i], signal[i])
679  hist_probB0bar.Fill(purityB0bar[i], back[i])
680 
681  # filling histogram with qp from -1 to 1
682  hist_qpB0.Fill(dilutionB02[i], signal[i])
683  hist_qpB0bar.Fill(dilutionB0bar2[i], back[i])
684 
685  # filling histogram with abs(qp), i.e. this histogram contains the r-values (not qp)
686  hist_absqpB0.Fill(abs(dilutionB02[i]), signal[i])
687  hist_absqpB0bar.Fill(abs(dilutionB0bar2[i]), back[i])
688  # filling histogram with abs(qp) special weighted - needed for average r calculation
689  hist_aver_rB0.Fill(abs(dilutionB02[i]), abs(dilutionB02[i]) * signal[i])
690  hist_aver_rB0bar.Fill(abs(dilutionB0bar2[i]), abs(dilutionB0bar2[i]) * back[i])
691 
692  # hist_aver_rB0bar contains now the average r-value
693  hist_aver_rB0.Divide(hist_absqpB0)
694  hist_aver_rB0bar.Divide(hist_absqpB0bar)
695  # now calculating the efficiency
696 
697  # calculating number of events
698  tot_entriesB0 = 0
699  tot_entriesB0bar = 0
700  for i in range(1, r_size):
701  tot_entriesB0 = tot_entriesB0 + hist_absqpB0.GetBinContent(i)
702  tot_entriesB0bar = tot_entriesB0bar + hist_absqpB0bar.GetBinContent(i)
703  # initializing some arrays
704  tot_eff_effB0 = 0
705  tot_eff_effB0bar = 0
706  event_fractionB0 = array('f', [0] * r_size)
707  event_fractionB0bar = array('f', [0] * r_size)
708  rvalueB0 = array('f', [0] * r_size)
709  rvalueB0bar = array('f', [0] * r_size)
710  # wvalue = array('f', [0] * r_size)
711  entriesB0 = array('f', [0] * r_size)
712  entriesB0bar = array('f', [0] * r_size)
713 
714  for i in range(1, r_size):
715  rvalueB0[i] = hist_aver_rB0.GetBinContent(i)
716  rvalueB0bar[i] = hist_aver_rB0bar.GetBinContent(i)
717  # wvalue[i] = (1 - rvalueB0[i]) / 2
718  entriesB0[i] = hist_absqpB0.GetBinContent(i)
719  entriesB0bar[i] = hist_absqpB0bar.GetBinContent(i)
720  event_fractionB0[i] = entriesB0[i] / tot_entriesB0
721  event_fractionB0bar[i] = entriesB0bar[i] / tot_entriesB0bar
722  # print '* Bin ' + str(i) + ' r-value: ' + str(rvalueB0[i]), 'entriesB0: ' +
723  # str(event_fractionB0[i] * 100) + ' % (' + str(entriesB0[i]) + '/' +
724  # str(tot_entriesB0) + ')'
725  tot_eff_effB0 = tot_eff_effB0 + event_fractionB0[i] * rvalueB0[i] \
726  * rvalueB0[i]
727  tot_eff_effB0bar = tot_eff_effB0bar + event_fractionB0bar[i] * rvalueB0bar[i] \
728  * rvalueB0bar[i]
729  effDiff = tot_eff_effB0 - tot_eff_effB0bar
730  effAverage = (tot_eff_effB0 + tot_eff_effB0bar) / 2
731 
732  print(
733  '{:<25}'.format("* " +
734  category) +
735  ' B0-Eff=' +
736  '{: 8.2f}'.format(
737  tot_eff_effB0 *
738  100) +
739  ' %' +
740  ' B0bar-Eff=' +
741  '{: 8.2f}'.format(
742  tot_eff_effB0bar *
743  100) +
744  ' %' +
745  ' EffAverage=' +
746  '{: 8.2f}'.format(effAverage * 100) + ' %' +
747  ' EffDiff=' +
748  '{: 8.2f}'.format(effDiff * 100) + ' % *')
749 
750  # ****** produce the input plots from combiner level ******
751 
752  efficienciesForNtuple.append(float(effAverage * 100))
753 
754  maxSignal = hist_signal.GetBinContent(hist_signal.GetMaximumBin())
755  maxBackground = hist_background.GetBinContent(hist_background.GetMaximumBin())
756 
757  Ymax = max(maxSignal, maxBackground)
758  Ymax = Ymax + Ymax / 12
759 
760  ROOT.gStyle.SetOptStat(0)
761  with Quiet(ROOT.kError):
762  Canvas = ROOT.TCanvas('Bla', 'TITEL BLA', 1200, 800)
763  Canvas.cd() # activate
764  Canvas.SetLogy()
765  Canvas.SetLeftMargin(0.13)
766  Canvas.SetRightMargin(0.04)
767  Canvas.SetTopMargin(0.03)
768  Canvas.SetBottomMargin(0.14)
769  hist_signal.SetFillColorAlpha(ROOT.kBlue, 0.2)
770  hist_signal.SetFillStyle(1001)
771  hist_signal.SetTitleSize(0.1)
772  hist_signal.GetXaxis().SetLabelSize(0.04)
773  hist_signal.GetYaxis().SetLabelSize(0.04)
774  hist_signal.GetXaxis().SetTitleSize(0.06)
775  hist_signal.GetYaxis().SetTitleSize(0.06)
776  hist_signal.GetXaxis().SetLabelSize(0.04)
777  hist_signal.GetYaxis().SetLabelSize(0.04)
778  hist_signal.GetXaxis().SetTitleSize(0.05)
779  hist_signal.GetYaxis().SetTitleSize(0.05)
780  hist_signal.GetXaxis().SetTitleOffset(0.95)
781  hist_signal.GetYaxis().SetTitleOffset(1.1)
782  hist_signal.GetXaxis().SetTitleOffset(1.15)
783  hist_signal.GetYaxis().SetLimits(0, Ymax)
784  hist_signal.SetLineColor(ROOT.kBlue)
785  hist_background.SetFillColorAlpha(ROOT.kRed, 1.0)
786  hist_background.SetFillStyle(3005)
787  hist_background.GetYaxis().SetLimits(0, Ymax)
788  hist_background.SetLineColor(ROOT.kRed)
789 
790  catName = category
791  if category == 'MaximumPstar':
792  catName = 'MaximumP*'
793 
794  hist_signal.SetTitle('; (#it{qp})^{' + catName + '} ; Events')
795  # hist_signal.SetMinimum(0)
796  hist_signal.SetMaximum(Ymax)
797  # hist_background.SetMinimum(0)
798  hist_background.SetMaximum(Ymax)
799 
800  hist_signal.Draw('hist')
801  hist_background.Draw('hist same')
802 
803  l0 = ROOT.TLegend(0.13, 0.65, 0.33, 0.97)
804  l0.SetFillColorAlpha(ROOT.kWhite, 0)
805  l0.AddEntry(hist_signal, ' #varepsilon_{eff}(B^{0}) = ' + '{:.2f}'.format(tot_eff_effB0 * 100) + "%")
806  l0.AddEntry(hist_background, ' #varepsilon_{eff}(#bar{B}^{0}) = ' + '{:.2f}'.format(tot_eff_effB0bar * 100) + "%")
807  l0.AddEntry("", "#bf{#varepsilon_{eff} = " + '{:.2f}'.format(effAverage * 100) + '%}')
808  l0.AddEntry("", '#Delta#varepsilon_{eff} = ' + '{:^5.2f}'.format(effDiff * 100) + '%')
809  l0.SetBorderSize(0)
810  l0.SetTextSize(0.045)
811  l0.Draw()
812 
813  l1 = ROOT.TLegend(0.85, 0.7, 0.96, 0.97)
814  l1.SetFillColorAlpha(ROOT.kWhite, 0.35)
815  l1.AddEntry(hist_signal, 'B^{0}_{MC}')
816  l1.AddEntry(hist_background, '#bar{B}^{0}_{MC}')
817  l1.SetTextSize(0.045)
818  l1.Draw()
819 
820  Canvas.Update()
821  with Quiet(ROOT.kError):
822  Canvas.SaveAs(workingDirectory + '/' + 'test6_CPVFTqp_' + category + '_both.pdf')
823 
824  # Validation Plot 4
825  hist_both.GetXaxis().SetLabelSize(0.04)
826  hist_both.GetYaxis().SetLabelSize(0.04)
827  hist_both.GetYaxis().SetTitleOffset(0.7)
828  hist_both.GetXaxis().SetTitleOffset(0.7)
829  hist_both.GetXaxis().SetTitleSize(0.06)
830  hist_both.GetYaxis().SetTitleSize(0.06)
831 
832  hist_both.GetListOfFunctions().Add(ROOT.TNamed('MetaOptions', 'nostats, logy'))
833  hist_both.GetListOfFunctions().Add(ROOT.TNamed('Description', 'Output of the flavor tagger category ' + catName))
834  hist_both.GetListOfFunctions().Add(
835  ROOT.TNamed('Check', 'Shape should not change drastically. E.g. Warning if there is only a peak at 0.'))
836  hist_both.GetListOfFunctions().Add(ROOT.TNamed('Contact', 'yosato@post.kek.jp'))
837 
838  hist_both.SetTitle(
839  'Flavor tagger output of the category ' +
840  catName +
841  '; #it{qp}_{' +
842  catName +
843  '} ; Events (Total = ' +
844  '{:<1}'.format(
845  "%.0f" %
846  hist_both.GetEntries()) +
847  ')')
848  # hist_both.SetStats(False)
849  hist_both.Write()
850 
851  Canvas.Clear()
852 
853 outputNtuple.Fill(array('f', efficienciesForNtuple))
854 outputNtuple.Write()
855 outputFile.Close()
856 
857 print('* *')
858 print('*******************************************************************************************************************')
oldlevel
the previously set level to be ignored