Beispiel #1
0
    def wrapped_f(self):
        self.pdf = self.process.sourcemanager.get(self.cfg['pdf'])
        self.argset = self.cfg['argset']
        self.params = self.pdf.getParameters(self.argset)
        FitDBPlayer.initFromDB(self.cfg['db'].format(binLabel=q2bins[self.process.cfg['binKey']]['label']), self.params, self.cfg.get('argAliasInDB', []))

        func(self)
Beispiel #2
0
    def _preFitSteps(self):
        """Prefit uncorrelated term"""
        args = self.pdf.getParameters(self.data)
        FitDBPlayer.initFromDB(self.process.dbplayer.odbfile, args)
        self.ToggleConstVar(args, isConst=True)

        # Disable xTerm correction and fit to 1-D
        args.find('hasXTerm').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+$"]),
            (h_accXrec_fine_ProjectionY, effi_cosK, CosThetaK, [r"^k\d+$"])
        ]:
            hdata = ROOT.RooDataHist("hdata", "", ROOT.RooArgList(var),
                                     ROOT.RooFit.Import(proj))
            self.ToggleConstVar(args, isConst=False, targetArgs=argPats)
            pdf.chi2FitTo(hdata, ROOT.RooLinkedList())
            self.ToggleConstVar(args, isConst=True, targetArgs=argPats)

        args.find('effi_norm').setConstant(False)
        self.pdf.chi2FitTo(self.data, ROOT.RooFit.Minos(True))
        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
        args.find('hasXTerm').setVal(1)
        self.ToggleConstVar(args, isConst=False, targetArgs=[r"^x\d+$"])
Beispiel #3
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)
Beispiel #4
0
        def wrapped_f(self):
            func(self)

            targetParams = ROOT.RooArgSet()
            def setParamsToFluc(arg):
                if arg.GetName() in parList:
                    targetParams.add(arg)
            FitterCore.ArgLooper(self.params, setParamsToFluc)
            FitDBPlayer.fluctuateFromDB(self.cfg['db'].format(binLabel=q2bins[self.process.cfg['binKey']]['label']), targetParams, self.cfg.get('argAliasInDB', []))
    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()
Beispiel #6
0
 def initPdfPlotCfg(self, p):
     """ [Name, plotOnOpt, argAliasInDB, LegendName] """
     pdfPlotTemplate = ["", plotterCfg_allStyle, None, None]
     p = p + pdfPlotTemplate[len(p):]
     if isinstance(p[0], str):
         self.logger.logDEBUG("Initialize pdfPlot {0}".format(p[0]))
         p[0] = self.process.sourcemanager.get(p[0])
         if p[0] == None:
             self.logger.logERROR("pdfPlot not found in source manager.")
             raise RuntimeError
     args = p[0].getParameters(
         ROOT.RooArgSet(Bmass, CosThetaK, CosThetaL, Mumumass, Kstarmass,
                        Kshortmass))
     FitDBPlayer.initFromDB(self.process.dbplayer.odbfile, args, p[2])
     return p
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()
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)
Beispiel #9
0
def plotEfficiency(self, data_name, pdf_name):
    pltName = "effi"
    data = self.process.sourcemanager.get(data_name)
    pdf = self.process.sourcemanager.get(pdf_name)
    if data == None or pdf == None:
        self.logger.logWARNING("Skip plotEfficiency. pdf or data not found")
        return
    args = pdf.getParameters(data)
    FitDBPlayer.initFromDB(self.process.dbplayer.odbfile, args)

    binningL = ROOT.RooBinning(
        len(dataCollection.accXEffThetaLBins) - 1,
        dataCollection.accXEffThetaLBins)
    binningK = ROOT.RooBinning(
        len(dataCollection.accXEffThetaKBins) - 1,
        dataCollection.accXEffThetaKBins)

    data_accXrec = self.process.sourcemanager.get("effiHistReader.h2_accXrec")
    data_accXrec.Scale(100)
    data_accXrec.SetMinimum(0)
    data_accXrec.SetMaximum(100 * 0.00015)  # Z axis in percentage
    data_accXrec.SetTitleOffset(1.6, "X")
    data_accXrec.SetTitleOffset(1.8, "Y")
    data_accXrec.SetTitleOffset(1.8, "Z")
    data_accXrec.SetZTitle("Efficiency [%]")
    data_accXrec.Draw("LEGO2")
    h2_effi_sigA_fine = pdf.createHistogram(
        "h2_effi_sigA_fine", CosThetaL, ROOT.RooFit.Binning(20),
        ROOT.RooFit.YVar(CosThetaK, ROOT.RooFit.Binning(20)))
    h2_effi_sigA_fine.Scale(100)
    h2_effi_sigA_fine.SetLineColor(2)
    h2_effi_sigA_fine.Draw("SURF SAME")
    Plotter.latexCMSSim(.08, .93)
    Plotter.latexCMSExtra(.08, .89)
    Plotter.latexQ2(self.process.cfg['binKey'], .40, .93)
    self.canvasPrint(pltName + "_2D")
    data_accXrec.Scale(0.01)

    cloned_frameL = Plotter.frameL.emptyClone("cloned_frameL")
    h_accXrec_fine_ProjectionX = self.process.sourcemanager.get(
        "effiHistReader.h_accXrec_fine_ProjectionX")
    data_accXrec_fine_ProjectionX = ROOT.RooDataHist(
        "data_accXrec_fine_ProjectionX", "", ROOT.RooArgList(CosThetaL),
        ROOT.RooFit.Import(h_accXrec_fine_ProjectionX))
    data_accXrec_fine_ProjectionX.plotOn(cloned_frameL,
                                         ROOT.RooFit.Rescale(100))
    pdfL = self.process.sourcemanager.get("effi_cosl")
    pdfL.plotOn(cloned_frameL,
                ROOT.RooFit.Normalization(100, ROOT.RooAbsReal.Relative),
                *plotterCfg_sigStyleNoFill)
    cloned_frameL.GetYaxis().SetTitle("Efficiency [%]")
    cloned_frameL.SetMaximum(1.5 * cloned_frameL.GetMaximum())
    cloned_frameL.Draw()
    Plotter.latexDataMarks(['sim'])
    Plotter.latexQ2(self.process.cfg['binKey'])
    #  Plotter.latex.DrawLatexNDC(.85, .89, "#chi^{{2}}={0:.2f}".format(cloned_frameL.chiSquare()))
    self.canvasPrint(pltName + "_cosl")

    cloned_frameK = Plotter.frameK.emptyClone("cloned_frameK")
    h_accXrec_fine_ProjectionY = self.process.sourcemanager.get(
        "effiHistReader.h_accXrec_fine_ProjectionY")
    data_accXrec_fine_ProjectionY = ROOT.RooDataHist(
        "data_accXrec_fine_ProjectionY", "", ROOT.RooArgList(CosThetaK),
        ROOT.RooFit.Import(h_accXrec_fine_ProjectionY))
    data_accXrec_fine_ProjectionY.plotOn(cloned_frameK,
                                         ROOT.RooFit.Rescale(100))
    pdfK = self.process.sourcemanager.get("effi_cosK")
    pdfK.plotOn(cloned_frameK,
                ROOT.RooFit.Normalization(100, ROOT.RooAbsReal.Relative),
                *plotterCfg_sigStyleNoFill)
    cloned_frameK.GetYaxis().SetTitle("Efficiency [%]")
    cloned_frameK.SetMaximum(1.5 * cloned_frameK.GetMaximum())
    cloned_frameK.Draw()
    Plotter.latexDataMarks(['sim'])
    Plotter.latexQ2(self.process.cfg['binKey'])
    #  Plotter.latex.DrawLatexNDC(.85, .89, "#chi^{{2}}={0:.2f}".format(cloned_frameK.chiSquare()))
    self.canvasPrint(pltName + "_cosK")
Beispiel #10
0
 def _preFitSteps_initFromDB(self):
     """Initialize from DB"""
     FitDBPlayer.initFromDB(self.process.dbplayer.odbfile, self.args, self.cfg['argAliasInDB'])
     self.ToggleConstVar(self.args, True)
     self.ToggleConstVar(self.args, False, self.cfg.get('argPattern'))
Beispiel #11
0
    ROOT.gStyle.cd()
    pass

# RooMsgService settings
# Suppress all message below error during minimization to keep short log file.
msgService = ROOT.RooMsgService.instance()
msgService.getStream(0).removeTopic(64)  # Eval
msgService.getStream(0).removeTopic(4)  # Plotting
msgService.getStream(0).removeTopic(2)  # Minimization
msgService.getStream(1).removeTopic(64)
msgService.getStream(1).removeTopic(4)
msgService.getStream(1).removeTopic(2)
msgService.addStream(4,
                     #  ROOT.RooFit.Topic(64),
                     ROOT.RooFit.Topic(4),
                     ROOT.RooFit.Topic(2))

# default configuration for Process
processCfg = {
    'isBatchJob': False,
    'binKey': 'summary',
}
p = Process("myProcess", "testProcess", processCfg)

dbplayer = FitDBPlayer(absInputDir=os.path.join(anaSetup.modulePath, "input", "selected"))
p.addService("dbplayer", dbplayer)

# Developers Area
if isDEBUG:
    p.logger.verbosityLevel = VerbosityLevels.DEBUG
Beispiel #12
0
 def _postFitSteps(self):
     """Post-processing"""
     args = self.pdf.getParameters(self.data)
     self.ToggleConstVar(args, True)
     FitDBPlayer.UpdateToDB(self.process.dbplayer.odbfile, args)
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()