def customizeOne(self, targetBMassRegion=None, extraCuts=None):
    """Define datasets with arguments."""
    if targetBMassRegion is None:
        targetBMassRegion = []
    if not self.process.cfg['binKey'] in q2bins.keys():
        self.logger.logERROR("Bin {0} is not defined.\n".format(self.process.cfg['binKey']))
        raise ValueError

    # With shallow copied CFG, have to bind cfg['dataset'] to a new object.
    self.cfg['dataset'] = []
    for key, val in bMassRegions.items():
        if any([re.match(pat, key) for pat in targetBMassRegion]):
            self.cfg['dataset'].append(
                (
                    "{0}.{1}".format(self.cfg['name'], key),
                    "({0}) && ({1}) && ({2}) && ({3})".format(
                        val['cutString'],
                        q2bins[self.process.cfg['binKey']]['cutString'],
                        cuts[-1] if self.process.cfg['binKey'] not in ['jpsi', 'psi2s'] else cuts_noResVeto,
                        "1" if not extraCuts else extraCuts,
                    )
                )
            )

    # Customize preload TFile
    if self.cfg['preloadFile']:
        self.cfg['preloadFile'] = self.cfg['preloadFile'].format(binLabel=q2bins[self.process.cfg['binKey']]['label'])
def table_yields():
    baseIndentLevel = 2
    print("[table_yields] Printing table of yields")
    print("")
    print(indent * (baseIndentLevel + 0) + r"\begin{tabular}{|c|c|c|}")
    print(indent * (baseIndentLevel + 1) + r"\hline")
    print(indent * (baseIndentLevel + 1) + r"$q^2$ bin & $Y_S$ & $Y^C_B$ \\")
    print(indent * (baseIndentLevel + 1) + r"\hline")
    print(indent * (baseIndentLevel + 1) + r"\hline")

    binKeyToLine = OrderedDict()
    for binKey in q2bins.keys():
        if binKey in ['jpsi', 'psi2s', 'peaks', 'abovePsi2sA', 'abovePsi2sB']:
            continue
        binKeyToLine[binKey] = [q2bins[binKey]['label'].strip('bin')]
        #binKeyToLine['betweenPeaks'] = ["3"]
        #binKeyToLine['abovePsi2s'] = ["5"]
        #binKeyToLine['summary'] = ["0"]
    for binKey, latexLine in binKeyToLine.items():
        db = shelve.open("{0}/fitResults_{1}.db".format(db_dir, q2bins[binKey]['label']))
        latexLine.append("${0:.01f} \pm {1:.01f}$".format(db['nSig']['getVal'], db['nSig']['getError']))
        latexLine.append("${0:.01f} \pm {1:.01f}$".format(db['nBkgComb']['getVal'], db['nBkgComb']['getError']))
        db.close()
        print(indent * (baseIndentLevel + 1) + " & ".join(latexLine) + r" \\")

    print(indent * (baseIndentLevel + 1) + r"\hline")
    print(indent * (baseIndentLevel + 0) + r"\end{tabular}")
    print("")
def table_FitResults():
    baseIndentLevel = 2                                                                                                                        
    print("[table_FitResults] Printing table of Fit-Results")
    print("")
    print(indent * (baseIndentLevel + 0) + r"\begin{tabular}{|c|l|l|l|l|l|}")
    print(indent * (baseIndentLevel + 1) + r"\hline")
    print(indent * (baseIndentLevel + 1) + r"$q^2$ bin & SigGEN & Sig2D & SigM & SigMDCB & BkgCombA & Final \\")
    print(indent * (baseIndentLevel + 1) + r"\hline")
    print(indent * (baseIndentLevel + 1) + r"\hline")
 
    binKeyToLine = OrderedDict()
    for binKey in q2bins.keys():
        if binKey in ['jpsi', 'psi2s', 'peaks']:
            continue
        binKeyToLine[binKey] = [q2bins[binKey]['label'].strip('bin')]
    for binKey, latexLine in binKeyToLine.items():
        db = shelve.open("{0}/fitResults_{1}.db".format(db_dir, q2bins[binKey]['label']))
        latexLine.append("${0}$ nll:${1:10.1f}$ ".format(db['sigAFitter.migrad']['status'], db['sigAFitter.migrad']['nll']))
        latexLine.append("${0}$ nll:${1:10.1f}$ ".format(db['sig2DFitter.migrad']['status'], db['sig2DFitter.migrad']['nll']))
        latexLine.append("${0}$ nll:${1:10.1f}$ ".format(db['sigMFitter.migrad']['status'], db['sigMFitter.migrad']['nll']))
        latexLine.append("${0}$ nll:${1:10.1f}$ ".format(db['sigMDCBFitter.migrad']['status'] if 'sigMDCBFitter.migrad' in db.keys() else 8, db['sigMDCBFitter.migrad']['nll'] if 'sigMDCBFitter.migrad' in db.keys() else 8))
        latexLine.append("${0}$ nll:${1:10.1f}$ ".format(db['bkgCombAFitter.migrad']['status'], db['bkgCombAFitter.migrad']['nll']))
        latexLine.append("${0}$ nll:${1:10.1f}$ ".format(db['finalFitter.migrad']['status'], db['finalFitter.migrad']['nll']))
        db.close()
        print(indent * (baseIndentLevel + 1) + " & ".join(latexLine) + r" \\")
             
    print(indent * (baseIndentLevel + 1) + r"\hline")
    print(indent * (baseIndentLevel + 0) + r"\end{tabular}")
    print("")
def customizeOne(self, targetBMassRegion=None, extraCuts=None):
    """Define datasets with arguments."""
    if targetBMassRegion is None:
        targetBMassRegion = []
    if not self.process.cfg['binKey'] in q2bins.keys():
        self.logger.logERROR("Bin {0} is not defined.\n".format(self.process.cfg['binKey']))
        raise ValueError

    # With shallow copied CFG, have to bind cfg['dataset'] to a new object.
    self.cfg['dataset'] = []
    for key, val in bMassRegions.items():
        finalcut = self.process.cfg['cuts'][-1] if not key in ['USB', 'LSB'] else self.process.cfg['cuts'][-1].replace(re.search("Bdt \>(.*?)\)\&\&", self.process.cfg['cuts'][-1]).group(0).strip(), 'Bdt > 0.40)&&')
        if any([re.match(pat, key) for pat in targetBMassRegion]):
            self.cfg['dataset'].append(
                (
                    "{0}.{1}".format(self.cfg['name'], key),
                    "({0}) && ({1}) && ({2}) && ({3})".format(
                        val['cutString'],
                        q2bins[self.process.cfg['binKey']]['cutString'],
                        finalcut, #self.process.cfg['cuts'][-1],
                        "1" if not extraCuts else extraCuts,
                    )
                )
            )
    if "ResVeto" in targetBMassRegion and self.process.cfg['binKey']=='full':
        self.cfg['dataset'].append(
            (
                "{0}.Fit_ResVeto".format(self.cfg['name'], key),
                "({0}) && ({1}) && ({2}) && ({3})".format(
                    bMassRegions['Fit']['cutString'],
                    q2bins[self.process.cfg['binKey']]['cutString'],
                    self.process.cfg['cuts_Signal'],
                    extraCuts,
                )
            )
        )
    if "antiResVeto" in targetBMassRegion and self.process.cfg['binKey'] in ['jpsi', 'psi2s']:
        self.cfg['dataset'].append(
            (
                "{0}.Fit_antiResVeto".format(self.cfg['name'], key),
                "({0}) && ({1}) && ({2}) && ({3})".format(
                    bMassRegions['SR']['cutString'],
                    q2bins[self.process.cfg['binKey']]['cutString'],
                    self.process.cfg['cuts_antiResVeto'],
                    extraCuts,
                )
            )
        )    
    # Customize preload TFile
    self.cfg['preloadFile'] = modulePath + "/data/preload_{datasetName}_{Year}_{binLabel}.root".format(datasetName=self.cfg['name'].split('.')[0], Year=self.process.cfg['args'].Year,  binLabel=q2bins[self.process.cfg['binKey']]['label'])
def customizeGEN(self):
    """Define datasets with arguments."""
    if not self.process.cfg['binKey'] in q2bins.keys():
        print("ERROR\t: Bin {0} is not defined.\n".format(self.process.cfg['binKey']))
        raise AttributeError

    # With shallow copied CFG, have to bind cfg['dataset'] to a new object.
    self.cfg['dataset'] = []
    self.cfg['dataset'].append(
        (
            "{0}.Fit".format(self.cfg['name']),
            re.sub("Q2", "genQ2", q2bins[self.process.cfg['binKey']]['cutString']) + " && genKpPt>0 && genKmPt>0"
        )
    )
    # Customize preload TFile
    self.cfg['preloadFile'] = modulePath + "/data/preload_{datasetName}_{Year}_{binLabel}.root".format(datasetName=self.cfg['name'].split('.')[0], Year=self.process.cfg['args'].Year, binLabel=q2bins[self.process.cfg['binKey']]['label'])
def customizeGEN(self):
    """Define datasets with arguments."""
    if not self.process.cfg['binKey'] in q2bins.keys():
        print("ERROR\t: Bin {0} is not defined.\n".format(self.process.cfg['binKey']))
        raise AttributeError

    # With shallow copied CFG, have to bind cfg['dataset'] to a new object.
    self.cfg['dataset'] = []
    self.cfg['dataset'].append(
        (
            "{0}.Fit".format(self.cfg['name']),
            re.sub("Mumumass", "sqrt(genQ2)", q2bins[self.process.cfg['binKey']]['cutString'])
        )
    )

    # Customize preload TFile
    if self.cfg['preloadFile']:
        self.cfg['preloadFile'] = self.cfg['preloadFile'].format(binLabel=q2bins[self.process.cfg['binKey']]['label'])
def PeakFracTable(self):
    import json
    parentkey = self.process.cfg['args'].SimFitPlots
    baseIndentLevel = 2                                                                                                                        
    print("[table_FitResults] Printing table of fractions of peaking yield wrt to signal yield")
    print("")
    if parentkey:
        print(indent * (baseIndentLevel + 0) + r"\begin{tabular}{|c|c|c|c|}")
    else:
        print(indent * (baseIndentLevel + 0) + r"\begin{tabular}{|c|c|}")
    print(indent * (baseIndentLevel + 1) + r"\hline")
    print(indent * (baseIndentLevel + 1) + r"$q^2$ bin & Fraction \\" if not parentkey else r"$q^2$ bin & 2016 Fraction & 2017 Fraction & 2018 Fraction\\")
    print(indent * (baseIndentLevel + 1) + r"\hline")
    print(indent * (baseIndentLevel + 1) + r"\hline")
    binKeyToLine = OrderedDict()
    for binKey in q2bins.keys():
        if binKey in ['jpsi', 'psi2s', 'peaks', 'abovePsi2s', 'abovePsi2sA', 'abovePsi2sB', 'summary', 'summaryA', 'full', 'Test1', 'Test2']:
            continue
        binKeyToLine[binKey] = [q2bins[binKey]['label'].strip('bin')]
    filename="TotalEffValues.json"
    def GetDict():
        File = open(filename, 'r')
        if os.path.exists(filename):
            EFile = json.load(File) 
            return EFile
        else:
            print("Error:: File {} does not exists, please produce it first.".format(filename))
            sys.exit(0)
    for binKey, latexLine in binKeyToLine.items():
        for year in [2016, 2017, 2018] if parentkey else [self.process.cfg['args'].Year]:
            os.chdir("../plots_{}".format(year))
            EFile = GetDict()
            frac = EFile[binKey]['ratio']['getVal']*3.90625*(9.4E-7/(8.2E-7*0.492))
            latexLine.append("${:.4%}$".format(frac).replace("%","\%"))
        print(indent * (baseIndentLevel + 1) + " & ".join(latexLine) + r" \\")     
    print(indent * (baseIndentLevel + 1) + r"\hline")
    print(indent * (baseIndentLevel + 0) + r"\end{tabular}")
    print("")
def EffiTable(self):
    baseIndentLevel = 2                                                                                                                        
    print("[table_FitResults] Printing table of Efficiency Numbers")
    print("")
    print(indent * (baseIndentLevel + 0) + r"\begin{tabular}{|c|c|l|l|l|l|l|}")
    print(indent * (baseIndentLevel + 1) + r"\hline")
    print(indent * (baseIndentLevel + 1) + r"$q^2$ bin & Range & Reco-eff N & Reco-eff D & Acc-Eff N & Acc-Eff D & Efficiency \\")
    print(indent * (baseIndentLevel + 1) + r"\hline")
    print(indent * (baseIndentLevel + 1) + r"\hline")
    binKeyToLine = OrderedDict()
    for binKey in q2bins.keys():
        if binKey in ['jpsi', 'psi2s', 'peaks', 'abovePsi2sA', 'abovePsi2sB', 'Test1', 'Test2']:
            continue
        binKeyToLine[binKey] = [q2bins[binKey]['label'].strip('bin')]
    for binKey, latexLine in binKeyToLine.items():
        filename="../data/accXrecEffHists_{0}_{1}.root".format(self.process.cfg['args'].Year, q2bins[binKey]['label'])
        if os.path.exists(filename):
            EFile = ROOT.TFile.Open(filename, "READ")
        else:
            print("Error:: File {} does not exists, please produce it first.".format(filename))
            sys.exit(0)
        receffi = EFile.Get('h2_rec_{}'.format(binKey))
        acceffi = EFile.Get('h2_acc_{}'.format(binKey))
        if not receffi or not acceffi:
            print("Error: Attempt to access non existant object from file. Please content of a file for {} bin.".format(binKey))
            sys.exit(0)
        latexLine.append("${}$".format(q2bins[binKey]['latexLabel']))
        latexLine.append("${:.0f}$".format(receffi.GetPassedHistogram().GetEntries()))
        latexLine.append("${:.0f}$".format(receffi.GetTotalHistogram().GetEntries()))
        latexLine.append("${:.0f}$".format(acceffi.GetPassedHistogram().GetEntries()))
        latexLine.append("${:.0f}$".format(acceffi.GetTotalHistogram().GetEntries()))
        effi = (receffi.GetPassedHistogram().GetEntries()/receffi.GetTotalHistogram().GetEntries())*(acceffi.GetPassedHistogram().GetEntries()/acceffi.GetTotalHistogram().GetEntries())
        latexLine.append(("${:.3%}$".format(effi)).replace("%","\%"))
        EFile.Close()
        print(indent * (baseIndentLevel + 1) + " & ".join(latexLine) + r" \\")     
    print(indent * (baseIndentLevel + 1) + r"\hline")
    print(indent * (baseIndentLevel + 0) + r"\end{tabular}")
    print("")
    odbfile = 'fitResults_{}.db'.format(binkey)

    for key in pdf.keys():
        arguments = pdf[key].getParameters(ROOT.RooArgSet(
            CosThetaL, CosThetaK))
        FitDBPlayer.initFromDB(odbfile, arguments)
    os.chdir(cwd)
    return pdf


for i in List:  # 2 Step list
    obj = f.Get(i.GetName())
    if obj.InheritsFrom(ROOT.TH1D.Class()):
        for j in List2:  # One Step list
            obj2 = f2.Get(j.GetName())
            key = [k for k in q2bins.keys() if k in obj.GetName()]
            if j.GetName() == i.GetName():
                pdf = GetPDFlist(q2bins[key[0]]['label'])
                print(pdf)
                h1Canvas = ROOT.TCanvas()
                h1Canvas.cd()
                res = ROOT.NewResPlot('TH1D')(obj, obj2)
                scale = 1. / obj.Integral()
                scale2 = 1. / obj2.Integral()
                obj.Scale(scale)
                obj2.Scale(scale2)

                res.fUpperPad.Draw()
                res.fLowerPad.Draw()
                res.fUpperPad.cd()
                obj.Draw("E1 HIST")
    return sequence


if __name__ == '__main__':
    from BsToPhiMuMuFitter.StdProcess import p
    from BsToPhiMuMuFitter.anaSetup import q2bins
    from BsToPhiMuMuFitter.python.datainput import GetInputFiles
    from copy import deepcopy

    if args.OneStep is False: args.TwoStep = True
    p.work_dir = "plots_{}".format(args.Year)
    p.cfg['args'] = deepcopy(args)
    p.cfg['sysargs'] = sys.argv
    GetInputFiles(p)
    p.cfg['bins'] = p.cfg['allBins'] if args.binKey == "all" else [
        key for key in q2bins.keys() if q2bins[key]['label'] == args.binKey
    ]

    if (not args.SimFit) and (type(predefined_sequence[args.seqKey]) is tuple):
        predefined_sequence[args.seqKey] = predefined_sequence[
            args.seqKey][0] + predefined_sequence[args.seqKey][1]
    if args.SimFit or args.SimFitPlots:
        p.name = "SimultaneousFitProcess"
        p.work_dir = "plots_simultaneous"
    if args.seqKey == 'sigMCValidation': p.name = 'sigMCValidationProcess'

    for b in p.cfg['bins']:
        Stime = datetime.datetime.now()
        p.cfg['binKey'] = b
        try:
Beispiel #11
0
from BsToPhiMuMuFitter.python.ArgParser import SetParser, GetBatchTaskParser
parser = GetBatchTaskParser()
args = parser.parse_known_args()[0]
from BsToPhiMuMuFitter.StdProcess import p
p.work_dir = "plots_{}".format(args.Year)
p.cfg['args'] = args

from BsToPhiMuMuFitter.plotCollection import GetPlotterObject
import BsToPhiMuMuFitter.seqCollection as seqCollection
from BsToPhiMuMuFitter.anaSetup import q2bins, modulePath
import os, re

seqKey = list(seqCollection.predefined_sequence.keys())
binKeys = [q2bins[k]['label'] for k in q2bins.keys()]
plotList = list(GetPlotterObject(p).cfg['plots'].keys())

dirlist = re.findall(r"\w*.py\b", " ".join(os.listdir(modulePath)))

print(dirlist)
print(binKeys)
print(seqKey)
print(plotList)
List = " ".join(binKeys + seqKey + plotList)
os.system("""complete -W \"{0}\" seqCollection.py """.format(List))
def buildAccXRecEffiHist(self):
    """Build efficiency histogram for later fitting/plotting"""
    print("Now I am Here in buildAccXRecEffiHist")
    fin = self.process.filemanager.open("buildAccXRecEffiHist", modulePath + "/data/accXrecEffHists_Run2016.root", "UPDATE")

    # Build acceptance, reco efficiency, and accXrec
    forceRebuild = False
    for binKey in q2bins.keys():
        print("Q2Bins: ", q2bins.keys())#Pritam
        if binKey in ['jpsi', 'psi2s', 'peaks']:
            continue
        h2_accXrec = fin.Get("h2_accXrec_{0}".format(binKey))
        if h2_accXrec == None or forceRebuild:
            h2_acc = fin.Get("h2_acc_{0}".format(binKey))
            h2_rec = fin.Get("h2_rec_{0}".format(binKey))

            # Fill histograms
            setupEfficiencyBuildProcedure = {}
            setupEfficiencyBuildProcedure['acc'] = {
                #'ifiles': ["/eos/cms/store/user/pchen/BToKstarMuMu/dat/sel/v3p5/unfilteredSIG_genonly/*.root", ],
                'ifiles': ["/afs/cern.ch/work/p/pkalbhor/BFitter/BPhysicsData/data/Modified_sel_BsToPhiMuMu_NofilterMC_signal_2016_mc.lite_cut0_s.root", ],
                'baseString': re.sub("Mumumass", "sqrt(genQ2)", q2bins[binKey]['cutString']),
                'cutString': "fabs(genMupEta)<2.5 && fabs(genMumEta)<2.5 && genMupPt>2.5 && genMumPt>2.5",
                'fillXY': "genCosThetaK:genCosThetaL"  # Y:X
            }
            setupEfficiencyBuildProcedure['rec'] = {
                'ifiles': sigMCReader.cfg['ifile'],
                'baseString': "{0}".format(setupEfficiencyBuildProcedure['acc']['baseString']),
                'cutString': "Bmass > 0.5 && ({0})".format(cuts[-1]),
                'fillXY': "genCosThetaK:genCosThetaL"  # Y:X
            }
            i=0 #testing events
            # print(setupEfficiencyBuildProcedure['rec'])
            for h2, label in (h2_acc, 'acc'), (h2_rec, 'rec'):
                if h2 == None or forceRebuild:
                    print("h2: ", h2, label)
                    treein = TChain("events")
                    for f in setupEfficiencyBuildProcedure[label]['ifiles']:
                        treein.Add(f)
                        print(setupEfficiencyBuildProcedure[label]['ifiles'])

                    treein.Draw(">>totEvtList", setupEfficiencyBuildProcedure[label]['baseString'])
                    totEvtList = ROOT.gDirectory.Get("totEvtList")
                    # print("MyEventList:")
                    # totEvtList.Print() #Pritam
                    treein.SetEventList(totEvtList)
                    treein.Draw(">>accEvtList", setupEfficiencyBuildProcedure[label]['cutString'])
                    # totEvtList.Print() #Pritam
                    accEvtList = ROOT.gDirectory.Get("accEvtList")
                    accEvtList.Print()

                    h2_total = TH2D("h2_{0}_{1}_total".format(label, binKey), "", len(accXEffThetaLBins) - 1, accXEffThetaLBins, len(accXEffThetaKBins) - 1, accXEffThetaKBins)
                    h2_passed = h2_total.Clone("h2_{0}_{1}_passed".format(label, binKey))

                    h2_fine_total = TH2D("h2_{0}_fine_{1}_total".format(label, binKey), "", 20, -1, 1, 20, -1, 1)
                    h2_fine_passed = h2_fine_total.Clone("h2_{0}_fine_{1}_passed".format(label, binKey))

                    treein.SetEventList(totEvtList)
                    for hist in h2_total, h2_fine_total:
                        treein.Draw("{0}>>{1}".format(setupEfficiencyBuildProcedure[label]['fillXY'], hist.GetName()), "", "goff")

                    treein.SetEventList(accEvtList)
                    for hist in h2_passed, h2_fine_passed:
                        treein.Draw("{0}>>{1}".format(setupEfficiencyBuildProcedure[label]['fillXY'], hist.GetName()), "", "goff")

                    h2_eff = TEfficiency(h2_passed, h2_total)
                    h2_eff_fine = TEfficiency(h2_fine_passed, h2_fine_total)

                    fin.cd()
                    for proj, var in [("ProjectionX", CosThetaL), ("ProjectionY", CosThetaK)]:
                        proj_fine_total = getattr(h2_fine_total, proj)("{0}_{1}".format(h2_fine_total.GetName(), proj), 0, -1, "e")
                        proj_fine_passed = getattr(h2_fine_passed, proj)("{0}_{1}".format(h2_fine_passed.GetName(), proj), 0, -1, "e")
                        h_eff = TEfficiency(proj_fine_passed, proj_fine_total)
                        h_eff.Write("h_{0}_fine_{1}_{2}".format(label, binKey, proj), ROOT.TObject.kOverwrite)

                    h2_eff.Write("h2_{0}_{1}".format(label, binKey), ROOT.TObject.kOverwrite)
                    h2_eff_fine.Write("h2_{0}_fine_{1}".format(label, binKey), ROOT.TObject.kOverwrite)

            # Merge acc and rec to accXrec
            fin.cd()
            for proj in ["ProjectionX", "ProjectionY"]:
                h_acc_fine = fin.Get("h_acc_fine_{0}_{1}".format(binKey, proj))
                h_rec_fine = fin.Get("h_rec_fine_{0}_{1}".format(binKey, proj))
                h_accXrec_fine = h_acc_fine.GetPassedHistogram().Clone("h_accXrec_fine_{0}_{1}".format(binKey, proj))
                h_accXrec_fine.Reset("ICESM")
                for b in range(1, h_accXrec_fine.GetNbinsX() + 1):
                    h_accXrec_fine.SetBinContent(b, h_acc_fine.GetEfficiency(b) * h_rec_fine.GetEfficiency(b))
                    h_accXrec_fine.SetBinError(b, h_accXrec_fine.GetBinContent(b) * math.sqrt(1 / h_acc_fine.GetTotalHistogram().GetBinContent(b) + 1 / h_acc_fine.GetPassedHistogram().GetBinContent(b) + 1 / h_rec_fine.GetTotalHistogram().GetBinContent(b) + 1 / h_rec_fine.GetPassedHistogram().GetBinContent(b)))
                h_accXrec_fine.Write("h_accXrec_{0}_{1}".format(binKey, proj), ROOT.TObject.kOverwrite)

            h2_acc = fin.Get("h2_acc_{0}".format(binKey))
            h2_rec = fin.Get("h2_rec_{0}".format(binKey))
            h2_accXrec = h2_acc.GetPassedHistogram().Clone("h2_accXrec_{0}".format(binKey))
            h2_accXrec.Reset("ICESM")
            for iL, iK in itertools.product(range(1, len(accXEffThetaLBins)), range(1, len(accXEffThetaKBins))):
                if h2_rec.GetTotalHistogram().GetBinContent(iL, iK) == 0 or h2_rec.GetPassedHistogram().GetBinContent(iL, iK) == 0:
                    h2_accXrec.SetBinContent(iL, iK, 0)
                    h2_accXrec.SetBinError(iL, iK, 1)
                else:
                    iLK = h2_acc.GetGlobalBin(iL, iK)
                    h2_accXrec.SetBinContent(iL, iK, h2_acc.GetEfficiency(iLK) * h2_rec.GetEfficiency(iLK))
                    h2_accXrec.SetBinError(iL, iK, h2_accXrec.GetBinContent(iL, iK) * math.sqrt(1 / h2_acc.GetTotalHistogram().GetBinContent(iLK) + 1 / h2_acc.GetPassedHistogram().GetBinContent(iLK) + 1 / h2_rec.GetTotalHistogram().GetBinContent(iLK) + 1 / h2_rec.GetPassedHistogram().GetBinContent(iLK)))
            h2_accXrec.SetXTitle("cos#theta_{l}")
            h2_accXrec.SetYTitle("cos#theta_{K}")
            h2_accXrec.SetZTitle("Overall efficiency")

            h2_accXrec.Write("h2_accXrec_{0}".format(binKey), ROOT.TObject.kOverwrite)
            self.logger.logINFO("Overall efficiency is built.")

    # Register the chosen one to sourcemanager
    h2_accXrec = fin.Get("h2_accXrec_{0}".format(self.process.cfg['binKey']))
    self.cfg['source']['effiHistReader.h2_accXrec'] = h2_accXrec
    self.cfg['source']['effiHistReader.accXrec'] = RooDataHist("accXrec", "", RooArgList(CosThetaL, CosThetaK), ROOT.RooFit.Import(h2_accXrec))
    self.cfg['source']['effiHistReader.h_accXrec_fine_ProjectionX'] = fin.Get("h_accXrec_{0}_ProjectionX".format(self.process.cfg['binKey']))
    self.cfg['source']['effiHistReader.h_accXrec_fine_ProjectionY'] = fin.Get("h_accXrec_{0}_ProjectionY".format(self.process.cfg['binKey']))