Exemplo n.º 1
0
 def _postFitSteps(self):
     """Post-processing"""
     #  FitterCore.ArgLooper(self.args, lambda arg: arg.Print())
     self.ToggleConstVar(self.args, True)
     if self.cfg['saveToDB']:
         FitDBPlayer.UpdateToDB(
             self.process.dbplayer.odbfile, self.args,
             self.cfg['argAliasInDB']
             if self.cfg['argAliasSaveToDB'] else None)
         FitDBPlayer.UpdateToDB(self.process.dbplayer.odbfile,
                                self.fitResult)
Exemplo n.º 2
0
def func_simMismodel(args):
    p.setSequence([])
    try:
        p.beginSeq()
        db = shelve.open(p.dbplayer.odbfile)
        fl_GEN = unboundFlToFl(db['unboundFl_GEN']['getVal'])
        fl_RECO = unboundFlToFl(db['unboundFl_RECO']['getVal'])
        afb_GEN = unboundAfbToAfb(db['unboundAfb_GEN']['getVal'], fl_GEN)
        afb_RECO = unboundAfbToAfb(db['unboundAfb_RECO']['getVal'], fl_RECO)
        db.close()
        syst_simMismodel = {
            'syst_simMismodel_fl': {
                'getError': math.fabs(fl_GEN - fl_RECO),
                'getErrorHi': math.fabs(fl_GEN - fl_RECO),
                'getErrorLo': -math.fabs(fl_GEN - fl_RECO),
            },
            'syst_simMismodel_afb': {
                'getError': math.fabs(afb_GEN - afb_RECO),
                'getErrorHi': math.fabs(afb_GEN - afb_RECO),
                'getErrorLo': -math.fabs(afb_GEN - afb_RECO),
            }
        }
        print(syst_simMismodel)

        if args.updateDB:
            FitDBPlayer.UpdateToDB(p.dbplayer.odbfile, syst_simMismodel)
    finally:
        p.endSeq()
Exemplo n.º 3
0
def updateToDB_altShape(args, tag):
    """ Template db entry maker for syst """
    db = shelve.open(p.dbplayer.odbfile)
    nominal_fl = unboundFlToFl(db['unboundFl']['getVal'])
    nominal_afb = unboundAfbToAfb(db['unboundAfb']['getVal'], nominal_fl)
    db.close()
    afb = p.sourcemanager.get('afb').getVal()
    fl = p.sourcemanager.get('fl').getVal()
    syst_altShape = {}
    syst_altShape['syst_{0}_afb'.format(tag)] = {
        'getError': math.fabs(afb - nominal_afb),
        'getErrorHi': math.fabs(afb - nominal_afb),
        'getErrorLo': -1 * math.fabs(afb - nominal_afb),
    }
    syst_altShape['syst_{0}_fl'.format(tag)] = {
        'getError': math.fabs(fl - nominal_fl),
        'getErrorHi': math.fabs(fl - nominal_fl),
        'getErrorLo': -1 * math.fabs(fl - nominal_fl),
    }
    print(syst_altShape)

    if args.updateDB:
        FitDBPlayer.UpdateToDB(p.dbplayer.odbfile, syst_altShape)
    def _preFitSteps(self):
        """Prefit uncorrelated term"""
        args = self.pdf.getParameters(self.data)
        if not self.process.cfg['args'].NoImport:
            FitDBPlayer.initFromDB(self.process.dbplayer.odbfile, args)
        self.ToggleConstVar(args, isConst=True)

        # Disable xTerm correction and fit to 1-D
        args.find('hasXTerm{}'.format(self.cfg['label'])).setVal(0)

        h_accXrec_fine_ProjectionX = self.process.sourcemanager.get(
            self.cfg['dataX'])
        h_accXrec_fine_ProjectionY = self.process.sourcemanager.get(
            self.cfg['dataY'])
        effi_cosl = self.process.sourcemanager.get(self.cfg['pdfX'])
        effi_cosK = self.process.sourcemanager.get(self.cfg['pdfY'])
        for proj, pdf, var, argPats in [
            (h_accXrec_fine_ProjectionX, effi_cosl, CosThetaL, [r"^l\d+\w*"]),
            (h_accXrec_fine_ProjectionY, effi_cosK, CosThetaK, [r"^k\d+\w*"])
        ]:
            hdata = ROOT.RooDataHist("hdata", "", ROOT.RooArgList(var),
                                     ROOT.RooFit.Import(proj))
            self.ToggleConstVar(args, isConst=False, targetArgs=argPats)

            theList = ROOT.RooLinkedList()
            Err = ROOT.RooFit.Minos(True)
            theSave = ROOT.RooFit.Save()  #Python discards temporary objects
            Verbose = ROOT.RooFit.Verbose(0)
            Strategy = ROOT.RooFit.Strategy(2)
            PrintLevel = ROOT.RooFit.PrintLevel(-1)
            theList.Add(theSave)
            theList.Add(Verbose)
            theList.Add(PrintLevel)
            theList.Add(Err)
            theList.Add(Strategy)
            Res = pdf.chi2FitTo(hdata, theList)
            Res = pdf.chi2FitTo(hdata, theList)
            Res.Print("v")
            FitDBPlayer.UpdateToDB(
                self.process.dbplayer.odbfile,
                FitterCore.GetFitResult(self.name, var.GetName(), Res))

            ################## AlTernatively #######################
            #chi2 = pdf.createChi2(hdata, ROOT.RooFit.Save(1))
            #m=ROOT.RooMinuit(chi2)
            #m.setPrintLevel(3)
            #m.migrad()
            #m.hesse()
            #m.minos()
            #RooRes=m.save()

            self.ToggleConstVar(args, isConst=True, targetArgs=argPats)

        effi_norm = 'effi_norm{}'.format(self.cfg['label'])
        args.find('hasXTerm{}'.format(self.cfg['label'])).setVal(1)
        args.find(effi_norm).setConstant(False)
        Res2D = self.pdf.chi2FitTo(self.data, ROOT.RooFit.Minos(True),
                                   ROOT.RooFit.Save(), ROOT.RooFit.Strategy(2),
                                   ROOT.RooFit.PrintLevel(-1))
        Res2D.Print()
        #args.find(effi_norm).setVal(args.find(effi_norm).getVal() / 4.)
        args.find(effi_norm).setConstant(True)

        # Fix uncorrelated term and for later update with xTerms in main fit step
        self.ToggleConstVar(args, isConst=False, targetArgs=[r"^x\d+\w*"])
    def _runFitSteps(self):
        h2_accXrec = self.process.sourcemanager.get(self.cfg['datahist'])
        args = self.pdf.getParameters(self.data)
        nPar = 0
        floaters = {}  #Saving indices for cross terms

        def GetTFunction():
            nonlocal nPar
            args_it = args.createIterator()
            arg = args_it.Next()
            effi_sigA_formula = self.pdf.formula().formulaString()
            paramDict = {}
            for p in range(self.pdf.formula().actualDependents().getSize()):
                paramDict[self.pdf.formula().getParameter(p).GetName()] = p
            effi_sigA_formula = effi_sigA_formula.replace(
                "x[{0}]".format(paramDict['CosThetaL']), "x")
            effi_sigA_formula = effi_sigA_formula.replace(
                "x[{0}]".format(paramDict['CosThetaK']), "y")
            while arg:
                if any(
                        re.match(pat, arg.GetName()) for pat in
                    ["effi_norm", "hasXTerm", r"^l\d+\w*", r"^k\d+\w*"]):
                    effi_sigA_formula = effi_sigA_formula.replace(
                        'x[{0}]'.format(paramDict[arg.GetName()]),
                        "({0})".format(arg.getVal()))
                elif re.match(r"^x\d+\w*$", arg.GetName()):
                    effi_sigA_formula = effi_sigA_formula.replace(
                        'x[{0}]'.format(paramDict[arg.GetName()]),
                        "[{0}]".format(nPar))
                    floaters[nPar] = arg.GetName()
                    nPar = nPar + 1
                arg = args_it.Next()
            f2_effi_sigA = ROOT.TF2("f2_effi_sigA", effi_sigA_formula, -1, 1,
                                    -1, 1)
            return f2_effi_sigA

        if True:  #Using RooMinuit
            if False:  #Using {} optimization
                fitter = ROOT.StdFitter()
                minuit = fitter.Init(self.pdf, self.data)
                minuit.setStrategy(2)
                minuit.optimizeConst(1)
                minuit.setPrintLevel(0)
                self._nll = fitter.GetNLL()
                self.fitter = fitter.FitMigrad()
                self.fitter = fitter.FitHesse()
                self.fitter = fitter.FitMinos(
                    self.pdf.getParameters(self.data).selectByAttrib(
                        "Constant", 0))
            else:  #Using chi2 optimization
                self.fitter = self.pdf.chi2FitTo(self.data,
                                                 ROOT.RooFit.Minos(1),
                                                 ROOT.RooFit.Strategy(2),
                                                 ROOT.RooFit.Save(1),
                                                 ROOT.RooFit.PrintLevel(-1))
                self.fitter = self.pdf.chi2FitTo(self.data,
                                                 ROOT.RooFit.Minos(1),
                                                 ROOT.RooFit.Strategy(2),
                                                 ROOT.RooFit.Save(1),
                                                 ROOT.RooFit.PrintLevel(-1))
            self.fitter.Print("v")
            FitDBPlayer.UpdateToDB(
                self.process.dbplayer.odbfile,
                FitterCore.GetFitResult(self.name, "XTerm", self.fitter))

            setStyle()
            canvas = ROOT.TCanvas()
            latex = ROOT.TLatex()
            h2_effi_2D_comp = h2_accXrec.Clone("h2_effi_2D_comp")
            h2_effi_2D_comp.Reset("ICESM")
            pdfhist = h2_accXrec.Clone("pdfhist")
            pdfhist.Reset("ICESM")
            self.pdf.fillHistogram(pdfhist,
                                   ROOT.RooArgList(CosThetaL, CosThetaK))

            #Text plot comparison
            canvas2 = ROOT.TCanvas()
            for lBin, KBin in itertools.product(
                    list(range(1,
                               h2_effi_2D_comp.GetNbinsX() + 1)),
                    list(range(1,
                               h2_effi_2D_comp.GetNbinsY() + 1))):
                if h2_accXrec.GetBinContent(lBin, KBin) == 0:
                    h2_effi_2D_comp.SetBinContent(lBin, KBin, 0)
                    print(">> ** Warning ** Empty bins: (l, k)", lBin, KBin)
                else:
                    h2_effi_2D_comp.SetBinContent(
                        lBin, KBin,
                        pdfhist.GetBinContent(lBin, KBin) /
                        h2_accXrec.GetBinContent(lBin, KBin))

            ROOT.gStyle.SetPalette(
                ROOT.kLightTemperature)  #kColorPrintableOnGrey)
            h2_effi_2D_text = h2_effi_2D_comp.Clone(
                "h2_effi_2D_text")  #; h2_effi_2D_text.Reset("ICESM")
            h2_effi_2D_text.Draw("COLZ")
            h2_effi_2D_text.GetYaxis().SetTitleOffset(1)
            ROOT.gStyle.SetPaintTextFormat("6.4g")
            pdfhist.SetBarOffset(0.25)
            pdfhist.Draw("TEXT SAME")
            canvas2.SetRightMargin(0.115)
            canvas2.SetLeftMargin(0.1)
            h2_accXrec.SetBarOffset(0.)
            h2_accXrec.Draw("TEXT SAME")
            h2_effi_2D_comp.SetBarOffset(-0.25)
            h2_effi_2D_comp.Draw("TEXT SAME")
            ROOT.TLatex().DrawLatexNDC(
                0.12, 0.96,
                r"#scale[0.8]{{{latexLabel}}}".format(latexLabel=q2bins[
                    self.process.cfg['binKey']]['latexLabel']))

            canvas.cd()
            h2_effi_2D_comp.SetMinimum(0)
            h2_effi_2D_comp.SetMaximum(1.5)
            h2_effi_2D_comp.SetTitleOffset(1.6, "X")
            h2_effi_2D_comp.SetTitleOffset(1.8, "Y")
            h2_effi_2D_comp.SetTitleOffset(1.5, "Z")
            h2_effi_2D_comp.SetZTitle(
                "#varepsilon_{fit}/#varepsilon_{measured}")
            h2_effi_2D_comp.Draw("LEGO2")
            latex.DrawLatexNDC(
                .08, .93, "#font[61]{CMS} #font[52]{#scale[0.8]{Simulation}}")
            chi2ndf = self.fitter.minNll() / (
                h2_effi_2D_comp.GetNbinsX() * h2_effi_2D_comp.GetNbinsY() -
                self.pdf.getParameters(self.data).selectByAttrib(
                    "Constant", 0).getSize())
            latex.DrawLatexNDC(.08, .89,
                               "#chi^{{2}}/ndf={0:.2f}".format(chi2ndf))
            print("2D Efficiency Chi^2/ndf: ", chi2ndf)

        else:  #Using TMinuit (This section can be used only if pdf is defined in terms of expression (e.g. RooFormulaVar). Does not work for RooProdPdf or RooProduct)
            f2_effi_sigA = GetTFunction()
            fitter = ROOT.EfficiencyFitter()
            self.minimizer = fitter.Init(nPar, h2_accXrec, f2_effi_sigA)
            self.minimizer.SetPrintLevel(0)  #Pritam
            self.minimizer.mnexcm("SET STR", ctypes.c_double(2.), 1,
                                  ctypes.c_int(0))
            for xIdx in range(nPar):
                self.minimizer.DefineParameter(xIdx, floaters[xIdx], 0., 1E-4,
                                               -1E+2, 1E+2)
            MigStatus = self.minimizer.Migrad()
            MigStatus = self.minimizer.Migrad()
            MinosStatus = self.minimizer.Command("MINOS")

            # Check if efficiency is positive definite
            f2_max_x, f2_max_y = ctypes.c_double(0.), ctypes.c_double(.0)
            f2_min_x, f2_min_y = ctypes.c_double(0.), ctypes.c_double(.0)
            f2_effi_sigA.GetMaximumXY(f2_max_x, f2_max_y)
            f2_effi_sigA.GetMinimumXY(f2_min_x, f2_min_y)
            print("Sanitary check: Efficiency ranges from {0:.2e} to {1:.2e}".
                  format(f2_effi_sigA.Eval(f2_min_x, f2_min_y),
                         f2_effi_sigA.Eval(f2_max_x, f2_max_y)))
            EfficiencyFitter.isPosiDef(f2_effi_sigA)

            #Update parameter values
            parVal, parErr = ctypes.c_double(.0), ctypes.c_double(.0)
            eplus, eminus, eparab, gcc = ctypes.c_double(0.), ctypes.c_double(
                0.), ctypes.c_double(.0), ctypes.c_double(0.)
            for xIdx in range(nPar):
                self.minimizer.GetParameter(xIdx, parVal, parErr)
                self.minimizer.mnerrs(xIdx, eplus, eminus, eparab, gcc)
                arg = args.find(floaters[xIdx])
                arg.setVal(parVal.value)
                arg.setError(parErr.value)
                arg.setAsymError(eplus.value, eminus.value)

            # Plot comparison between fitting result to data
            setStyle()
            canvas = ROOT.TCanvas()
            latex = ROOT.TLatex()
            h2_effi_2D_comp = h2_accXrec.Clone("h2_effi_2D_comp")
            h2_effi_2D_comp.Reset("ICESM")
            pdfhist = h2_accXrec.Clone("pdfhist")
            pdfhist.Reset("ICESM")
            self.pdf.fillHistogram(pdfhist,
                                   ROOT.RooArgList(CosThetaL, CosThetaK))
            print(
                "2D Efficiency Chi^2/ndf: ",
                fitter.GetChi2() /
                (h2_effi_2D_comp.GetNbinsX() * h2_effi_2D_comp.GetNbinsY() -
                 nPar))
            print("TMinuit Status: ", self.minimizer.GetStatus(), MigStatus,
                  MinosStatus)

            #Text plot comparison
            canvas2 = ROOT.TCanvas()
            for lBin, KBin in itertools.product(
                    list(range(1,
                               h2_effi_2D_comp.GetNbinsX() + 1)),
                    list(range(1,
                               h2_effi_2D_comp.GetNbinsY() + 1))):
                if h2_accXrec.GetBinContent(lBin, KBin) == 0:
                    h2_effi_2D_comp.SetBinContent(lBin, KBin, 0)
                    print(">> ** Warning ** Empty bins: (l, k)", lBin, KBin)
                else:
                    h2_effi_2D_comp.SetBinContent(
                        lBin, KBin,
                        f2_effi_sigA.Eval(
                            h2_accXrec.GetXaxis().GetBinCenter(lBin),
                            h2_accXrec.GetYaxis().GetBinCenter(KBin)) /
                        h2_accXrec.GetBinContent(lBin, KBin))

            ROOT.gStyle.SetPalette(
                ROOT.kLightTemperature)  #kColorPrintableOnGrey)
            h2_effi_2D_text = h2_effi_2D_comp.Clone(
                "h2_effi_2D_text")  #; h2_effi_2D_text.Reset("ICESM")
            h2_effi_2D_text.Draw("COLZ")
            h2_effi_2D_text.GetYaxis().SetTitleOffset(1)
            ROOT.gStyle.SetPaintTextFormat("6.4g")
            pdfhist.SetBarOffset(0.25)
            pdfhist.Draw("TEXT SAME")
            canvas2.SetRightMargin(0.115)
            canvas2.SetLeftMargin(0.1)
            h2_accXrec.SetBarOffset(0.)
            h2_accXrec.Draw("TEXT SAME")
            h2_effi_2D_comp.SetBarOffset(-0.25)
            h2_effi_2D_comp.Draw("TEXT SAME")
            ROOT.TLatex().DrawLatexNDC(
                0.12, 0.96,
                r"#scale[0.8]{{{latexLabel}}}".format(latexLabel=q2bins[
                    self.process.cfg['binKey']]['latexLabel']))

            canvas.cd()
            h2_effi_2D_comp.SetMinimum(0)
            h2_effi_2D_comp.SetMaximum(1.5)
            h2_effi_2D_comp.SetTitleOffset(1.6, "X")
            h2_effi_2D_comp.SetTitleOffset(1.8, "Y")
            h2_effi_2D_comp.SetTitleOffset(1.5, "Z")
            h2_effi_2D_comp.SetZTitle(
                "#varepsilon_{fit}/#varepsilon_{measured}")
            h2_effi_2D_comp.Draw("LEGO2")
            latex.DrawLatexNDC(
                .08, .93, "#font[61]{CMS} #font[52]{#scale[0.8]{Simulation}}")
            latex.DrawLatexNDC(
                .08, .89, "#chi^{{2}}/ndf={0:.2f}".format(
                    fitter.GetChi2() / (h2_effi_2D_comp.GetNbinsX() *
                                        h2_effi_2D_comp.GetNbinsY() - nPar)))
            FitterCore.ArgLooper(args, lambda p: p.Print())

        ####################################
        path = os.path.join(modulePath, self.process.work_dir, "Efficiency")
        if not os.path.exists(path):
            os.mkdir(path)
        os.chdir(path)
        ####################################
        canvas.Print("effi_2D_comp{}_{}.pdf".format(
            self.cfg['label'], q2bins[self.process.cfg['binKey']]['label']))
        canvas2.cd()
        canvas2.Print("effi_2D_TEXT{}_{}.pdf".format(
            self.cfg['label'], q2bins[self.process.cfg['binKey']]['label']))
        os.chdir(os.path.join(modulePath, self.process.work_dir))
 def _postFitSteps(self):
     """Post-processing"""
     args = self.pdf.getParameters(self.data)
     self.ToggleConstVar(args, True)
     FitDBPlayer.UpdateToDB(self.process.dbplayer.odbfile, args)
Exemplo n.º 7
0
def func_randEffi(args):
    """ Typically less than 5% """
    setupFinalRandEffiFitter = deepcopy(fitCollection.setupFinalFitter)
    setupFinalRandEffiFitter.update({
        'FitMinos': [False, ()],
        'argAliasInDB': {'afb': 'afb_randEffi', 'fl': 'fl_randEffi', 'fs': 'fs_randEffi', 'as': 'as_randEffi'},
        'saveToDB': False,
    })
    finalRandEffiFitter = StdFitter(setupFinalRandEffiFitter)

    def preFitSteps_randEffi(self):
        self.args = self.pdf.getParameters(self.data)
        self._preFitSteps_initFromDB()

        # Fluctuate cross-term correction
        effiArgs = ROOT.RooArgSet()
        FitterCore.ArgLooper(self.args, lambda iArg: effiArgs.add(iArg), targetArgs=[r"x\d{1,2}"])
        FitDBPlayer.fluctuateFromDB(self.process.dbplayer.odbfile, effiArgs, self.cfg['argAliasInDB'])

        self._preFitSteps_vetoSmallFs()
        self._preFitSteps_preFit()

    finalRandEffiFitter._preFitSteps = types.MethodType(preFitSteps_randEffi, finalRandEffiFitter)

    foutName = "syst_randEffi_{0}.root".format(q2bins[args.binKey]['label'])
    class effiStudier(AbsToyStudier):
        def _preSetsLoop(self):
            self.hist_afb = ROOT.TH1F("hist_afb", "", 300, -0.75, 0.75)
            self.hist_afb.GetXaxis().SetTitle("A_{{FB}}")
            self.hist_fl = ROOT.TH1F("hist_fl", "", 200, 0., 1.)
            self.hist_fl.GetXaxis().SetTitle("F_{{L}}")

        def _preRunFitSteps(self, setIndex):
            pass

        def _postRunFitSteps(self, setIndex):
            if self.fitter.fitResult["{0}.migrad".format(self.fitter.name)]['status'] == 0:
                afb = self.process.sourcemanager.get('afb')
                fl = self.process.sourcemanager.get('fl')
                self.hist_afb.Fill(afb.getVal())
                self.hist_fl.Fill(fl.getVal())

        def _postSetsLoop(self):
            fout = ROOT.TFile(foutName, "RECREATE")
            fout.cd()
            self.hist_afb.Write()
            self.hist_fl.Write()
            fout.Close()

        def getSubDataEntries(self, setIndex):
            return 1

        def getSubData(self):
            while True:
                yield self.data

    setupStudier = deepcopy(effiStudier.templateConfig())
    setupStudier.update({
        'name': "effiStudier",
        'data': "dataReader.Fit",
        'fitter': finalRandEffiFitter,
        'nSetOfToys': 200,
    })
    studier = effiStudier(setupStudier)

    p.setSequence([
        pdfCollection.stdWspaceReader,
        dataCollection.dataReader,
        studier,
    ])

    try:
        p.beginSeq()
        if os.path.exists("{0}".format(foutName)):
            print("{0} exists, skip fitting procedure".format(foutName))
        else:
            p.runSeq()

        fin = ROOT.TFile("{0}".format(foutName))

        hist_fl = fin.Get("hist_fl")
        gaus_fl = ROOT.TF1("gaus_fl", "gaus(0)", 0, 1)
        hist_fl.Fit(gaus_fl, "WI")

        hist_afb = fin.Get("hist_afb")
        gaus_afb = ROOT.TF1("gaus_afb", "gaus(0)", -0.75, 0.75)
        hist_afb.Fit(gaus_afb, "WI")

        syst_randEffi = {
            'syst_randEffi_fl': {
                'getError': gaus_fl.GetParameter(2),
                'getErrorHi': gaus_fl.GetParameter(2),
                'getErrorLo': -gaus_fl.GetParameter(2),
            },
            'syst_randEffi_afb': {
                'getError': gaus_afb.GetParameter(2),
                'getErrorHi': gaus_afb.GetParameter(2),
                'getErrorLo': -gaus_afb.GetParameter(2),
            }
        }
        print(syst_randEffi)

        if args.updatePlot:
            canvas = Plotter.canvas.cd()
            hist_afb.Draw("HIST")
            Plotter.latexCMSMark()
            Plotter.latexCMSExtra()
            Plotter.latexCMSSim()
            canvas.Print("syst_randEffi_afb_{0}.pdf".format(q2bins[args.binKey]['label']))

            hist_fl.GetXaxis().SetTitle("F_{{L}}")
            hist_fl.Draw("HIST")
            Plotter.latexCMSMark()
            Plotter.latexCMSExtra()
            Plotter.latexCMSSim()
            canvas.Print("syst_randEffi_fl_{0}.pdf".format(q2bins[args.binKey]['label']))

        if args.updateDB:
            FitDBPlayer.UpdateToDB(p.dbplayer.odbfile, syst_randEffi)
    finally:
        p.endSeq()
Exemplo n.º 8
0
    def _postFitSteps(self):
        """ Abstract: Do something after main fit loop"""

        for pdf, data in zip(self.pdf, self.data):
            self.ToggleConstVar(pdf.getParameters(data), True)

        cwd = os.getcwd()
        if self.process.cfg['args'].seqKey == 'fitBkgCombA':
            os.chdir(
                os.path.join(self.process.cwd, "plots_{0}".format(
                    self.process.cfg['args'].Year)))
        if self.cfg['saveToDB']:  #Update parameters to db file
            FitDBPlayer.UpdateToDB(
                self.process.dbplayer.odbfile,
                self.minimizer.getParameters(self.dataWithCategories),
                self.cfg['argAliasInDB']
                if self.cfg['argAliasSaveToDB'] else None)
        for pdf, data in zip(self.pdf,
                             self.data):  #Get parameter values from db file
            FitDBPlayer.initFromDB(self.process.dbplayer.odbfile,
                                   pdf.getParameters(data),
                                   aliasDict=self.cfg['argAliasInDB']
                                   if self.cfg['argAliasSaveToDB'] else None,
                                   exclude=None)
        os.chdir(cwd)
        """ofile = ROOT.TFile("../input/Simultaneous_{0}.root".format(q2bins[self.process.cfg['binKey']]['label']), "RECREATE")
        self.minimizer.Write()
        self.dataWithCategories.Write()
        self.category.Write()
        ofile.Close()"""

        self.cfg['source']["{0}.dataWithCategories".format(
            self.name)] = self.dataWithCategories
        self.cfg['source'][self.name] = self.minimizer
        self.cfg['source']["{0}.category".format(self.name)] = self.category
        sampleSet = ROOT.RooArgSet(self.category)
        self.cfg['source']['ProjWData'] = ROOT.RooFit.ProjWData(
            sampleSet, self.dataWithCategories)

        #Attach ProjWData Argument to plotter for getting combined fit
        #self.process._sequence[1].cfg['plots'][self.process._sequence[1].cfg['switchPlots'][0]]['kwargs']['pdfPlots'][0][1]=(ROOT.RooFit.ProjWData(sampleSet, self.dataWithCategories), ROOT.RooFit.LineColor(2), ROOT.RooFit.LineStyle(9))

        frameL = CosThetaL.frame(ROOT.RooFit.Bins(20))
        frameK = CosThetaK.frame(ROOT.RooFit.Bins(20))
        legendInstance = Plotter.legend
        c1 = ROOT.TCanvas()
        binKey = q2bins[self.process.cfg['binKey']]['label']
        if self.process.cfg['args'].seqKey in [
                'fitBkgCombA', 'fitFinal3D_WithKStar'
        ]:
            marks = None
        else:
            marks = ['sim']
        for ID, Category, Year in zip(range(len(self.Years)),
                                      self.cfg['category'], self.Years):
            CopyFrameL = frameL.Clone()
            self.category.setIndex(ID)
            sampleSet = ROOT.RooArgSet(self.category)
            self.dataWithCategories.plotOn(
                CopyFrameL,
                ROOT.RooFit.Cut("({0}==({0}::{1}))".format(
                    self.category.GetName(), Category)))
            self.minimizer.plotOn(
                CopyFrameL, ROOT.RooFit.Slice(self.category, Category),
                ROOT.RooFit.Components(self.pdf[ID].GetName()),
                ROOT.RooFit.ProjWData(sampleSet, self.dataWithCategories),
                ROOT.RooFit.LineStyle(ROOT.kSolid),
                ROOT.RooFit.LineColor(2 if self.process.cfg['args'].seqKey ==
                                      'fitBkgCombA' else 4)
            )  # ROOT.RooFit.Components( self.pdf[ID].GetName())
            CopyFrameL.SetMaximum(1.5 * CopyFrameL.GetMaximum())
            c1.Clear()
            CopyFrameL.Draw(
            ) if self.process.cfg['args'].NoPull else Plotter.DrawWithResidue(
                CopyFrameL)
            Plotter.latexQ2(self.process.cfg['binKey'])
            Plotter.latex.DrawLatexNDC(
                .45, .84, r"#scale[0.8]{{Events = {0:.2f}}}".format(
                    self.dataWithCategories.sumEntries("{0}=={0}::{1}".format(
                        self.category.GetName(), Category))))
            Plotter.latexDataMarks(marks=marks)
            legendInstance.Clear()
            legendInstance.AddEntry(
                CopyFrameL.getObject(0).GetName(), self.cfg['LegName'], "LPFE")
            legendInstance.Draw()
            c1.SaveAs("Simultaneous_Cosl_{0}_{1}_{2}.pdf".format(
                Category, self.process.cfg['args'].seqKey, binKey))

            CopyFrameK = frameK.Clone()
            self.dataWithCategories.plotOn(
                CopyFrameK,
                ROOT.RooFit.Cut("{0}=={0}::{1}".format(self.category.GetName(),
                                                       Category)))
            self.minimizer.plotOn(
                CopyFrameK, ROOT.RooFit.Slice(self.category, Category),
                ROOT.RooFit.Components(self.pdf[ID].GetName()),
                ROOT.RooFit.ProjWData(sampleSet, self.dataWithCategories),
                ROOT.RooFit.LineStyle(ROOT.kSolid),
                ROOT.RooFit.LineColor(2 if self.process.cfg['args'].seqKey ==
                                      'fitBkgCombA' else 4)
            )  #, ROOT.RooFit.Components(self.pdf[ID].GetName())
            CopyFrameK.SetMaximum(1.5 * CopyFrameK.GetMaximum())
            c1.Clear()
            CopyFrameK.Draw(
            ) if self.process.cfg['args'].NoPull else Plotter.DrawWithResidue(
                CopyFrameK)
            Plotter.latexQ2(self.process.cfg['binKey'])
            Plotter.latex.DrawLatexNDC(
                .45, .84, r"#scale[0.8]{{Events = {0:.2f}}}".format(
                    self.dataWithCategories.sumEntries("{0}=={0}::{1}".format(
                        self.category.GetName(), Category))))
            Plotter.latexDataMarks(marks=marks)
            legendInstance.Clear()
            legendInstance.AddEntry(
                CopyFrameK.getObject(0).GetName(), self.cfg['LegName'], "LPFE")
            legendInstance.Draw()
            c1.SaveAs("Simultaneous_CosK_{0}_{1}_{2}.pdf".format(
                Category, self.process.cfg['args'].seqKey, binKey))