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