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()
Beispiel #2
0
    def getStatError_Minuit(db):
        """ FlErrHi, FlErrLo, AfbErrHi, AfbErrLo"""
        unboundFl = db[argAliasInDB.get("unboundFl", "unboundFl")]
        unboundAfb = db[argAliasInDB.get("unboundAfb", "unboundAfb")]

        fl = unboundFlToFl(unboundFl['getVal'])
        afb = unboundAfbToAfb(unboundAfb['getVal'], fl)

        yyFlErrHi = unboundFlToFl(unboundFl['getVal'] +
                                  unboundFl['getErrorHi']) - fl
        yyFlErrLo = fl - unboundFlToFl(unboundFl['getVal'] +
                                       unboundFl['getErrorLo'])
        yyAfbErrHi = unboundAfbToAfb(
            unboundAfb['getVal'] + unboundAfb['getErrorHi'], fl) - afb
        yyAfbErrLo = afb - unboundAfbToAfb(
            unboundAfb['getVal'] + unboundAfb['getErrorLo'], fl)

        # Sanity check, bound error to boundary when MINOS is FAILED.
        minimum_err = 1e-4  # 1e-3 is too wide for full signal MC
        if yyFlErrHi < minimum_err:
            yyFlErrHi = (1 - 4 * abs(afb) / 3) - fl
        if yyFlErrLo < minimum_err:
            yyFlErrLo = fl
        if yyAfbErrHi < minimum_err:
            yyAfbErrHi = 0.75 * (1 - fl) - afb
        if yyAfbErrLo < minimum_err:
            yyAfbErrLo = afb + 0.75 * (1 - fl)
        return yyFlErrHi, yyFlErrLo, yyAfbErrHi, yyAfbErrLo
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 #4
0
def plotSummaryAfbFl(self, pltName, dbSetup, drawSM=False, marks=None):
    """ Check carefully the keys in 'dbSetup' """
    if marks is None:
        marks = []
    binKeys = ['belowJpsi', 'betweenPeaks', 'abovePsi2s']

    xx = array('d', [sum(q2bins[binKey]['q2range']) / 2 for binKey in binKeys])
    xxErr = array(
        'd',
        map(lambda t: (t[1] - t[0]) / 2,
            [q2bins[binKey]['q2range'] for binKey in binKeys]))

    grFls = []
    grAfbs = []

    def quadSum(lst):
        return math.sqrt(sum(map(lambda i: i**2, lst)))

    def calcSystError(db):
        """ FlErrHi, FlErrLo, AfbErrHi, AfbErrLo"""
        flSystErrorHi = []
        flSystErrorLo = []
        afbSystErrorHi = []
        afbSystErrorLo = []
        systErrorSourceBlackList = ["^syst_altFitRange_.*$"]
        for key, val in db.items():
            if re.match("^syst_.*_afb$", key) and not any(
                [re.match(pat, key) for pat in systErrorSourceBlackList]):
                afbSystErrorHi.append(db[key]['getErrorHi'])
                afbSystErrorLo.append(db[key]['getErrorLo'])
            if re.match("^syst_.*_fl$", key) and not any(
                [re.match(pat, key) for pat in systErrorSourceBlackList]):
                flSystErrorHi.append(db[key]['getErrorHi'])
                flSystErrorLo.append(db[key]['getErrorLo'])
        return quadSum(flSystErrorHi), quadSum(flSystErrorLo), quadSum(
            afbSystErrorHi), quadSum(afbSystErrorLo)

    def getStatError_FeldmanCousins(db):
        """ FlErrHi, FlErrLo, AfbErrHi, AfbErrLo"""
        return db['stat_FC_fl'][
            'getErrorHi'], -db['stat_FC_fl']['getErrorLo'], db['stat_FC_afb'][
                'getErrorHi'], -db['stat_FC_afb']['getErrorLo']

    def getStatError_Minuit(db):
        """ FlErrHi, FlErrLo, AfbErrHi, AfbErrLo"""
        unboundFl = db[argAliasInDB.get("unboundFl", "unboundFl")]
        unboundAfb = db[argAliasInDB.get("unboundAfb", "unboundAfb")]

        fl = unboundFlToFl(unboundFl['getVal'])
        afb = unboundAfbToAfb(unboundAfb['getVal'], fl)

        yyFlErrHi = unboundFlToFl(unboundFl['getVal'] +
                                  unboundFl['getErrorHi']) - fl
        yyFlErrLo = fl - unboundFlToFl(unboundFl['getVal'] +
                                       unboundFl['getErrorLo'])
        yyAfbErrHi = unboundAfbToAfb(
            unboundAfb['getVal'] + unboundAfb['getErrorHi'], fl) - afb
        yyAfbErrLo = afb - unboundAfbToAfb(
            unboundAfb['getVal'] + unboundAfb['getErrorLo'], fl)

        # Sanity check, bound error to boundary when MINOS is FAILED.
        minimum_err = 1e-4  # 1e-3 is too wide for full signal MC
        if yyFlErrHi < minimum_err:
            yyFlErrHi = (1 - 4 * abs(afb) / 3) - fl
        if yyFlErrLo < minimum_err:
            yyFlErrLo = fl
        if yyAfbErrHi < minimum_err:
            yyAfbErrHi = 0.75 * (1 - fl) - afb
        if yyAfbErrLo < minimum_err:
            yyAfbErrLo = afb + 0.75 * (1 - fl)
        return yyFlErrHi, yyFlErrLo, yyAfbErrHi, yyAfbErrLo

    statErrorMethods = {
        'FeldmanCousins': getStatError_FeldmanCousins,
        'Minuit': getStatError_Minuit,
    }

    Plotter.legend.Clear()
    for dbsIdx, dbs in enumerate(dbSetup):
        title = dbs.get('title', None)
        dbPat = dbs.get(
            'dbPat',
            self.process.dbplayer.absInputDir + "/fitResults_{binLabel}.db")
        argAliasInDB = dbs.get('argAliasInDB', {})
        withSystError = dbs.get('withSystError', False)
        statErrorKey = dbs.get('statErrorKey', 'Minuit')
        drawOpt = dbs.get('drawOpt', ["PO"])
        fillColor = dbs.get('fillColor', 2)
        fillStyle = dbs.get('fillStyle', 3001)
        legendOpt = dbs.get('legendOpt', None)
        dbs.update({
            'drawOpt': drawOpt,
            'legendOpt': legendOpt,
        })

        yyFl = array('d', [0] * len(binKeys))
        yyFlStatErrHi = array('d', [0] * len(binKeys))
        yyFlStatErrLo = array('d', [0] * len(binKeys))
        yyFlSystErrHi = array('d', [0] * len(binKeys))
        yyFlSystErrLo = array('d', [0] * len(binKeys))
        yyFlErrHi = array('d', [0] * len(binKeys))
        yyFlErrLo = array('d', [0] * len(binKeys))

        yyAfb = array('d', [0] * len(binKeys))
        yyAfbStatErrHi = array('d', [0] * len(binKeys))
        yyAfbStatErrLo = array('d', [0] * len(binKeys))
        yyAfbSystErrHi = array('d', [0] * len(binKeys))
        yyAfbSystErrLo = array('d', [0] * len(binKeys))
        yyAfbErrHi = array('d', [0] * len(binKeys))
        yyAfbErrLo = array('d', [0] * len(binKeys))
        for binKeyIdx, binKey in enumerate(binKeys):
            if not os.path.exists(
                    dbPat.format(binLabel=q2bins[binKey]['label'])):
                self.logger.logERROR(
                    "Input db file {0} NOT found. Skip.".format(
                        dbPat.format(binLable=q2bins[binKey]['label'])))
                continue
            try:
                db = shelve.open(
                    dbPat.format(binLabel=q2bins[binKey]['label']))
                unboundFl = db[argAliasInDB.get("unboundFl", "unboundFl")]
                unboundAfb = db[argAliasInDB.get("unboundAfb", "unboundAfb")]

                fl = unboundFlToFl(unboundFl['getVal'])
                afb = unboundAfbToAfb(unboundAfb['getVal'], fl)

                yyFl[binKeyIdx] = fl
                yyAfb[binKeyIdx] = afb
                yyFlStatErrHi[binKeyIdx], yyFlStatErrLo[binKeyIdx],\
                    yyAfbStatErrHi[binKeyIdx], yyAfbStatErrLo[binKeyIdx] = statErrorMethods.get(statErrorKey, getStatError_Minuit)(db)
                if withSystError:
                    yyFlSystErrHi[binKeyIdx], yyFlSystErrLo[binKeyIdx],\
                        yyAfbSystErrHi[binKeyIdx], yyAfbSystErrLo[binKeyIdx] = calcSystError(db)
                else:
                    yyFlSystErrHi[binKeyIdx], yyFlSystErrLo[binKeyIdx],\
                        yyAfbSystErrHi[binKeyIdx], yyAfbSystErrLo[binKeyIdx] = 0, 0, 0, 0
                yyFlErrHi[binKeyIdx] = min(
                    quadSum(
                        [yyFlStatErrHi[binKeyIdx], yyFlSystErrHi[binKeyIdx]]),
                    1. - yyFl[binKeyIdx])
                yyFlErrLo[binKeyIdx] = min(
                    quadSum(
                        [yyFlStatErrLo[binKeyIdx], yyFlSystErrLo[binKeyIdx]]),
                    yyFl[binKeyIdx])
                yyAfbErrHi[binKeyIdx] = min(
                    quadSum(
                        [yyAfbStatErrHi[binKeyIdx],
                         yyAfbSystErrHi[binKeyIdx]]), 0.75 - yyAfb[binKeyIdx])
                yyAfbErrLo[binKeyIdx] = min(
                    quadSum(
                        [yyAfbStatErrLo[binKeyIdx],
                         yyAfbSystErrLo[binKeyIdx]]), 0.75 + yyAfb[binKeyIdx])
            finally:
                db.close()

        grAfb = ROOT.TGraphAsymmErrors(len(binKeys), xx, yyAfb, xxErr, xxErr,
                                       yyAfbErrLo, yyAfbErrHi)
        grAfb.SetMarkerColor(fillColor if fillColor else 2)
        grAfb.SetLineColor(fillColor if fillColor else 2)
        grAfb.SetFillColor(fillColor if fillColor else 2)
        grAfb.SetFillStyle(fillStyle if fillStyle else 3001)
        grAfbs.append(grAfb)

        grFl = ROOT.TGraphAsymmErrors(len(binKeys), xx, yyFl, xxErr, xxErr,
                                      yyFlErrLo, yyFlErrHi)
        grFl.SetMarkerColor(fillColor if fillColor else 2)
        grFl.SetLineColor(fillColor if fillColor else 2)
        grFl.SetFillColor(fillColor if fillColor else 2)
        grFl.SetFillStyle(fillStyle if fillStyle else 3001)
        grFls.append(grFl)

        if legendOpt:
            Plotter.legend.AddEntry(grAfb, title, legendOpt)

    if drawSM:
        dbSetup.insert(0, {
            'drawOpt': ["2", "P0Z"],
        })
        yyFl = array('d', [0] * len(binKeys))
        yyFlErrHi = array('d', [0] * len(binKeys))
        yyFlErrLo = array('d', [0] * len(binKeys))

        yyAfb = array('d', [0] * len(binKeys))
        yyAfbErrHi = array('d', [0] * len(binKeys))
        yyAfbErrLo = array('d', [0] * len(binKeys))

        for binKeyIdx, binKey in enumerate(
            ['belowJpsi', 'betweenPeaks', 'abovePsi2s']):
            if binKey != 'betweenPeaks':
                fl = q2bins[binKey]['sm']['fl']
                afb = q2bins[binKey]['sm']['afb']
                yyFl[binKeyIdx] = fl['getVal']
                yyAfb[binKeyIdx] = afb['getVal']
                yyFlErrHi[binKeyIdx] = fl['getError']
                yyFlErrLo[binKeyIdx] = fl['getError']
                yyAfbErrHi[binKeyIdx] = afb['getError']
                yyAfbErrLo[binKeyIdx] = afb['getError']
            else:
                yyFl[binKeyIdx] = -1
                yyAfb[binKeyIdx] = -1
                yyFlErrHi[binKeyIdx] = 0
                yyFlErrLo[binKeyIdx] = 0
                yyAfbErrHi[binKeyIdx] = 0
                yyAfbErrLo[binKeyIdx] = 0

        grAfb = ROOT.TGraphAsymmErrors(len(binKeys), xx, yyAfb, xxErr, xxErr,
                                       yyAfbErrLo, yyAfbErrHi)
        grAfb.SetMarkerColor(4)
        grAfb.SetLineColor(4)
        grAfb.SetFillColor(4)
        grAfb.SetFillStyle(3001)
        grAfbs.insert(0, grAfb)

        grFl = ROOT.TGraphAsymmErrors(len(binKeys), xx, yyFl, xxErr, xxErr,
                                      yyFlErrLo, yyFlErrHi)
        grFl.SetMarkerColor(4)
        grFl.SetLineColor(4)
        grFl.SetFillColor(4)
        grFl.SetFillStyle(3001)
        grFls.insert(0, grFl)
        Plotter.legend.AddEntry(grAfb, "SM", "LPF")

    for grIdx, gr in enumerate(grAfbs):
        gr.SetTitle("")
        gr.GetXaxis().SetTitle("q^{2} [GeV^{2}]")
        gr.GetYaxis().SetTitle("A_{FB}")
        gr.GetYaxis().SetRangeUser(-0.75, 1.5)
        gr.SetLineWidth(2)
        drawOpt = dbSetup[grIdx]['drawOpt'] if isinstance(
            dbSetup[grIdx]['drawOpt'], list) else [dbSetup[grIdx]['drawOpt']]
        for optIdx, opt in enumerate(drawOpt):
            if grIdx == 0:
                gr.Draw("A" + opt if optIdx == 0 else opt)
            else:
                gr.Draw(opt + " SAME")
    jpsiBox = ROOT.TBox(8.68, -0.75, 10.09, 1.5)
    psi2sBox = ROOT.TBox(12.86, -0.75, 14.18, 1.5)
    jpsiBox.SetFillColor(17)
    psi2sBox.SetFillColor(17)
    jpsiBox.Draw()
    psi2sBox.Draw()
    Plotter.legend.Draw()
    Plotter.latexDataMarks(marks)
    self.canvasPrint(pltName + '_afb', False)

    for grIdx, gr in enumerate(grFls):
        gr.SetTitle("")
        gr.GetXaxis().SetTitle("q^{2} [GeV^{2}]")
        gr.GetYaxis().SetTitle("F_{L}")
        gr.GetYaxis().SetRangeUser(0, 1.5)
        gr.SetLineWidth(2)
        drawOpt = dbSetup[grIdx]['drawOpt'] if isinstance(
            dbSetup[grIdx]['drawOpt'], list) else [dbSetup[grIdx]['drawOpt']]
        for optIdx, opt in enumerate(drawOpt):
            if grIdx == 0:
                gr.Draw("A" + opt if optIdx == 0 else opt)
            else:
                gr.Draw(opt + " SAME")
    jpsiBox.SetY1(0)
    psi2sBox.SetY1(0)
    jpsiBox.Draw()
    psi2sBox.Draw()
    Plotter.legend.Draw()
    Plotter.latexDataMarks(marks)
    self.canvasPrint(pltName + '_fl', False)
Beispiel #5
0
def plotPostfitBLK(self, pltName, dataReader, pdfPlots):
    """Specification of plotSimpleBLK for post-fit plots"""
    for pIdx, plt in enumerate(pdfPlots):
        pdfPlots[pIdx] = self.initPdfPlotCfg(plt)

    # Calculate normalization and then draw
    args = pdfPlots[0][0].getParameters(
        ROOT.RooArgSet(Bmass, CosThetaK, CosThetaL))
    nSigDB = args.find('nSig').getVal()
    nSigErrorDB = args.find('nSig').getError()
    nBkgCombDB = args.find('nBkgComb').getVal()
    nBkgCombErrorDB = args.find('nBkgComb').getError()
    flDB = unboundFlToFl(args.find('unboundFl').getVal())
    afbDB = unboundAfbToAfb(args.find('unboundAfb').getVal(), flDB)
    sigFrac = {}
    bkgCombFrac = {}
    for regionName in ["Fit", "SR", "LSB", "USB", "SB", "innerSB", "outerSB"]:
        dataPlots = [
            [
                "{0}.{1}".format(dataReader, regionName), plotterCfg_dataStyle,
                "Data"
            ],
        ]
        for pIdx, p in enumerate(dataPlots):
            dataPlots[pIdx] = self.initDataPlotCfg(p)

        # Bind the 'Bmass' defined in PDF with 'getObservables' to createIntegral
        obs = pdfPlots[1][0].getObservables(dataPlots[0][0])
        FitterCore.ArgLooper(
            obs, lambda p: p.setRange(regionName, *bMassRegions[regionName][
                'range']), ["Bmass"])
        sigFrac[regionName] = pdfPlots[1][0].createIntegral(
            obs, ROOT.RooFit.NormSet(obs),
            ROOT.RooFit.Range(regionName)).getVal()

        obs = pdfPlots[2][0].getObservables(dataPlots[0][0])
        FitterCore.ArgLooper(
            obs, lambda p: p.setRange(regionName, *bMassRegions[regionName][
                'range']), ["Bmass"])
        bkgCombFrac[regionName] = pdfPlots[2][0].createIntegral(
            obs, ROOT.RooFit.NormSet(obs),
            ROOT.RooFit.Range(regionName)).getVal()

        if regionName in ["SB", "innerSB"]:
            sigFrac[regionName] -= sigFrac['SR']
            bkgCombFrac[regionName] -= bkgCombFrac['SR']
        elif regionName == "outerSB":
            sigFrac[regionName] -= sigFrac['SR']
            sigFrac[regionName] -= sigFrac['innerSB']
            bkgCombFrac[regionName] -= bkgCombFrac['SR']
            bkgCombFrac[regionName] -= bkgCombFrac['innerSB']

        nTotal_local = nSigDB * sigFrac[regionName] + nBkgCombDB * bkgCombFrac[
            regionName]
        #  print(regionName, sigFrac[regionName], bkgCombFrac[regionName], nTotal_local)

        # Correct the shape of f_final
        args.find("nSig").setVal(nSigDB * sigFrac[regionName])
        args.find("nBkgComb").setVal(nBkgCombDB * bkgCombFrac[regionName])

        modified_pdfPlots = [
            [
                pdfPlots[0][0], pdfPlots[0][1] + (ROOT.RooFit.Normalization(
                    nTotal_local, ROOT.RooAbsReal.NumEvent), ), None,
                "Total fit"
            ],
            [
                pdfPlots[0][0], pdfPlots[1][1] +
                (ROOT.RooFit.Normalization(nTotal_local,
                                           ROOT.RooAbsReal.NumEvent),
                 ROOT.RooFit.Components(pdfPlots[1][0].GetName())), None,
                "Sigal"
            ],
            [
                pdfPlots[0][0], pdfPlots[2][1] +
                (ROOT.RooFit.Normalization(nTotal_local,
                                           ROOT.RooAbsReal.NumEvent),
                 ROOT.RooFit.Components(pdfPlots[2][0].GetName())), None,
                "Background"
            ],
        ]

        plotFuncs = {
            'B': {
                'func': Plotter.plotFrameB,
                'tag': ""
            },
            'L': {
                'func': Plotter.plotFrameL,
                'tag': "_cosl"
            },
            'K': {
                'func': Plotter.plotFrameK,
                'tag': "_cosK"
            },
        }

        drawLatexFitResults = False
        for frame in 'BLK':
            plotFuncs[frame]['func'](dataPlots=dataPlots,
                                     pdfPlots=modified_pdfPlots)
            if drawLatexFitResults:
                if frame == 'B':
                    Plotter.latex.DrawLatexNDC(.19, .77, "Y_{Signal}")
                    Plotter.latex.DrawLatexNDC(
                        .35, .77,
                        "= {0:.2f}".format(nSigDB * sigFrac[regionName]))
                    Plotter.latex.DrawLatexNDC(
                        .50, .77, "#pm {0:.2f}".format(nSigErrorDB *
                                                       sigFrac[regionName]))
                    Plotter.latex.DrawLatexNDC(.19, .70, "Y_{Background}")
                    Plotter.latex.DrawLatexNDC(
                        .35, .70, "= {0:.2f}".format(nBkgCombDB *
                                                     bkgCombFrac[regionName]))
                    Plotter.latex.DrawLatexNDC(
                        .50, .70, "#pm {0:.2f}".format(
                            nBkgCombErrorDB * bkgCombFrac[regionName]))
                elif frame == 'L':
                    Plotter.latex.DrawLatexNDC(
                        .19, .77, "A_{{FB}} = {0:.2f}".format(afbDB))
                elif frame == 'K':
                    Plotter.latex.DrawLatexNDC(
                        .19, .77, "F_{{L}} = {0:.2f}".format(flDB))
            Plotter.latexQ2(self.process.cfg['binKey'])
            self.canvasPrint(pltName + '_' + regionName +
                             plotFuncs[frame]['tag'])
def func_fitFCConfInterval(args):
    """Fit interval from FCConfInterval.root, make plots and save to database."""
    line = ROOT.TLine()
    line.SetLineColor(2)
    line.SetLineStyle(2)

    for binKey in targetBinKeys:
        def drawAfbPlot(grLo, grHi, measAfb):
            grLo.SetTitle("")
            grLo.GetXaxis().SetTitle("Measured A_{FB}")
            grLo.GetXaxis().SetLimits(-0.75, 0.75)
            grLo.GetYaxis().SetTitle("True A_{FB}")
            grLo.GetYaxis().SetRangeUser(-0.75, 0.75)
            grLo.SetMarkerStyle(7)
            grHi.SetMarkerStyle(7)
            grLo.SetMarkerSize(0.4)
            grHi.SetMarkerSize(0.4)
            grLo.SetMarkerColor(8)
            grHi.SetMarkerColor(9)
            grLo.Draw("AP")
            grHi.Draw("P SAME")
            line.DrawLine(measAfb, -0.75, measAfb, 0.75)
            Plotter.latexCMSMark()
            Plotter.latexCMSExtra()
            Plotter.latexLumi()

        def drawFlPlot(grLo, grHi, measFl):
            grLo.SetTitle("")
            grLo.GetXaxis().SetTitle("Measured F_{L}")
            grLo.GetXaxis().SetLimits(0, 1)
            grLo.GetYaxis().SetTitle("True F_{L}")
            grLo.GetYaxis().SetRangeUser(0, 1)
            grLo.SetMarkerStyle(7)
            grHi.SetMarkerStyle(7)
            grLo.SetMarkerSize(0.4)
            grHi.SetMarkerSize(0.4)
            grLo.SetMarkerColor(8)
            grHi.SetMarkerColor(9)
            grLo.Draw("AP")
            grHi.Draw("P SAME")
            line.DrawLine(measFl, 0, measFl, 1)
            Plotter.latexCMSMark()
            Plotter.latexCMSExtra()
            Plotter.latexLumi()

        db = shelve.open(args.dbDirPath + "/fitResults_{0}.db".format(q2bins[binKey]['label']),
                         writeback=True if args.saveToDB else False)
        fl = unboundFlToFl(db['unboundFl']['getVal'])
        afb = unboundAfbToAfb(db['unboundAfb']['getVal'], fl)
        fin = ROOT.TFile(args.batchDir + "/FCConfInterval_{0}.root".format(q2bins[binKey]['label']))
        gr_afbCILo = filterVeryBiasedPoint(fin.Get("gr_afbCILo"))
        gr_afbCIHi = filterVeryBiasedPoint(fin.Get("gr_afbCIHi"))
        gr_flCILo = filterVeryBiasedPoint(fin.Get("gr_flCILo"))
        gr_flCIHi = filterVeryBiasedPoint(fin.Get("gr_flCIHi"))

        bdWidth = 0.01
        intervalBias = 0.
        intervalRange = 0.1
        afb_fitRange = {
            'Lo': {
                'default': (max(-0.75 + bdWidth, afb + intervalBias - intervalRange),
                            min(0.75 - bdWidth, afb + intervalBias + intervalRange)),
                'belowJpsi': (-0.2, 0),
            },
            'Hi': {
                'default': (max(-0.75 + bdWidth, afb - intervalBias - intervalRange),
                            min(0.75 - bdWidth, afb - intervalBias + intervalRange)),
            }
        }

        f_local_afbCILo = ROOT.TF1("f_local_afbCILo", "[0]+[1]*x", -0.75 + bdWidth, 0.75 - bdWidth)
        f_local_afbCIHi = ROOT.TF1("f_local_afbCIHi", "[0]+[1]*x", -0.75 + bdWidth, 0.75 - bdWidth)
        r_local_afbCILo = gr_afbCILo.Fit(f_local_afbCILo, "SWM", "", *afb_fitRange['Lo'].get(binKey, afb_fitRange['Lo']['default']))
        r_local_afbCIHi = gr_afbCIHi.Fit(f_local_afbCIHi, "SWM", "", *afb_fitRange['Lo'].get(binKey, afb_fitRange['Lo']['default']))
        drawAfbPlot(gr_afbCILo, gr_afbCIHi, afb)
        stat_FC_afb_getErrorHi = f_local_afbCILo.Eval(afb) - afb
        stat_FC_afb_getErrorLo = f_local_afbCIHi.Eval(afb) - afb
        Plotter.latex.DrawLatexNDC(.19, .77, "A_{{FB}} = {0:.2f}^{{{1:+.2f}}}_{{{2:+.2f}}}".format(afb, stat_FC_afb_getErrorHi, stat_FC_afb_getErrorLo))
        Plotter.canvas.Print(args.batchDir + "/FCConfInterval_afb_local_{0}.pdf".format(q2bins[binKey]['label']))

        # For later coverage test
        intervalBias = 0.
        intervalRange = 0.1
        fl_fitRange = {
            'Lo': {
                'default': (max(0 + bdWidth, fl + intervalBias - intervalRange),
                            min(1 - bdWidth, fl + intervalBias + intervalRange)),
            },
            'Hi': {
                'default': (max(0 + bdWidth, fl - intervalBias - intervalRange),
                            min(1 - bdWidth, fl - intervalBias + intervalRange)),
            }
        }

        f_local_flCILo = ROOT.TF1("f_local_flCILo", "[0]+[1]*x", 0 + bdWidth, 1 - bdWidth)
        f_local_flCIHi = ROOT.TF1("f_local_flCIHi", "[0]+[1]*x", 0 + bdWidth, 1 - bdWidth)
        r_local_flCILo = gr_flCILo.Fit(f_local_flCILo, "SWM", "", *fl_fitRange['Lo'].get(binKey, fl_fitRange['Lo']['default']))
        r_local_flCIHi = gr_flCIHi.Fit(f_local_flCIHi, "SWM", "", *fl_fitRange['Hi'].get(binKey, fl_fitRange['Hi']['default']))
        drawFlPlot(gr_flCILo, gr_flCIHi, fl)
        stat_FC_fl_getErrorHi = f_local_flCILo.Eval(fl) - fl
        stat_FC_fl_getErrorLo = f_local_flCIHi.Eval(fl) - fl
        Plotter.latex.DrawLatexNDC(.19, .77, "F_{{L}} = {0:.2f}^{{{1:+.2f}}}_{{{2:+.2f}}}".format(fl, stat_FC_fl_getErrorHi, stat_FC_fl_getErrorLo))
        Plotter.canvas.Print(args.batchDir + "/FCConfInterval_fl_local_{0}.pdf".format(q2bins[binKey]['label']))

        # For later coverage test
        # Coverage test if bestFit dir exists
        stat_FC_afb_coverage = 0.
        stat_FC_fl_coverage = 0.
        if args.doCoverage and os.path.exists(args.batchDir + "/bestFit/setSummary_{0}.root".format(q2bins[binKey]['label'])):
            f_global_afbCILo = ROOT.TF1("f_global_afbCILo", "[0]+[1]*x+[2]*x**2", -0.75 + bdWidth, 0.75 - bdWidth)
            f_global_afbCIHi = ROOT.TF1("f_global_afbCIHi", "[0]+[1]*x+[2]*x**2", -0.75 + bdWidth, 0.75 - bdWidth)
            r_global_afbCILo = gr_afbCILo.Fit(f_global_afbCILo, "SWMR")
            r_global_afbCIHi = gr_afbCIHi.Fit(f_global_afbCIHi, "SWMR")

            f_global_flCILo = ROOT.TF1("f_global_flCILo", "[0]+[1]*x+[2]*x**2", 0 + bdWidth, 1 - bdWidth)
            f_global_flCIHi = ROOT.TF1("f_global_flCIHi", "[0]+[1]*x+[2]*x**2", 0 + bdWidth, 1 - bdWidth)
            r_global_flCILo = gr_flCILo.Fit(f_global_flCILo, "SWMR")
            r_global_flCIHi = gr_flCIHi.Fit(f_global_flCIHi, "SWMR")

            fin_bestFit = ROOT.TFile(args.batchDir + "/bestFit/setSummary_{0}.root".format(q2bins[binKey]['label']))
            tree_bestFit = fin_bestFit.Get("tree")
            for ev in tree_bestFit:
                if f_global_afbCILo.Eval(ev.afb) > afb > f_global_afbCIHi.Eval(ev.afb):
                    stat_FC_afb_coverage += 1.
                if f_global_flCILo.Eval(ev.fl) > fl > f_global_flCIHi.Eval(ev.fl):
                    stat_FC_fl_coverage += 1.
            stat_FC_afb_coverage /= tree_bestFit.GetEntries()
            stat_FC_fl_coverage /= tree_bestFit.GetEntries()
            fin.Close()

            drawAfbPlot(gr_afbCILo, gr_afbCIHi, afb)
            Plotter.latex.DrawLatexNDC(.19, .77, "A_{{FB}} = {0:.2f}^{{{1:+.2f}}}_{{{2:+.2f}}}".format(afb, stat_FC_afb_getErrorHi, stat_FC_afb_getErrorLo))
            Plotter.latex.DrawLatexNDC(.19, .70, "Coverage: {0:.1f}%".format(100*stat_FC_afb_coverage))
            Plotter.canvas.Print(args.batchDir + "/FCConfInterval_afb_global_{0}.pdf".format(q2bins[binKey]['label']))

            drawFlPlot(gr_flCILo, gr_flCIHi, fl)
            Plotter.latex.DrawLatexNDC(.19, .77, "F_{{L}} = {0:.2f}^{{{1:+.2f}}}_{{{2:+.2f}}}".format(fl, stat_FC_fl_getErrorHi, stat_FC_fl_getErrorLo))
            Plotter.latex.DrawLatexNDC(.19, .70, "Coverage: {0:.1f}%".format(100*stat_FC_fl_coverage))
            Plotter.canvas.Print(args.batchDir + "/FCConfInterval_fl_global_{0}.pdf".format(q2bins[binKey]['label']))

        if args.saveToDB:
            db['stat_FC_afb'] = {
                'getErrorHi': stat_FC_afb_getErrorHi,
                'getErrorLo': stat_FC_afb_getErrorLo,
            }
            db['stat_FC_fl'] = {
                'getErrorHi': stat_FC_fl_getErrorHi,
                'getErrorLo': stat_FC_fl_getErrorLo,
            }
            if stat_FC_afb_coverage != 0 and stat_FC_fl_coverage != 0:
                db['stat_FC_afb']['coverage'] = stat_FC_afb_coverage
                db['stat_FC_fl']['coverage'] = stat_FC_fl_coverage
            print(db['stat_FC_afb'])
            print(db['stat_FC_fl'])

        db.close()
        fin.Close()
Beispiel #7
0
def table_dataresAFBFL():
    baseIndentLevel = 2

    print("[table_dataresAFBFL] Printing table of final result")
    print("")
    print(indent * (baseIndentLevel + 0) + r"\begin{tabular}{|c|c|c|c|c|}")
    print(indent * (baseIndentLevel + 1) + r"\hline")
    print(
        indent * (baseIndentLevel + 1) +
        r"$q^2$ bin index & $q^2$ range (in $\GeV^2$) & Signal Yield & $A_{FB}$ & $F_{L}$ \\"
    )
    print(indent * (baseIndentLevel + 1) + r"\hline")
    print(indent * (baseIndentLevel + 1) + r"\hline")

    binKeyToLine = OrderedDict()
    binKeyToLine['belowJpsi'] = ["1", r"1.00 -- 8.68"]
    binKeyToLine['jpsi'] = [
        "2", r"8.68 -- 10.09",
        r"\multicolumn{3}{|c|} {$\JPsi$ resonance region}"
    ]
    binKeyToLine['betweenPeaks'] = ["3", r"10.09 -- 12.86"]
    binKeyToLine['psi2s'] = [
        "4", r"12.86 -- 14.18",
        r"\multicolumn{3}{|c|} {$\psi'$ resonance region}"
    ]
    binKeyToLine['abovePsi2s'] = ["5", r"14.18 -- 19.00"]
    binKeyToLine['summary'] = ["0", r"bin\#1 $+$ bin\#3 $+$ bin\#5"]

    syst_sources = [
        'syst_randEffi',
        'syst_altEffi',
        'syst_simMismodel',
        'syst_altSP',
        'syst_altBkgCombA',
        'syst_vetoJpsiX',
        #  'syst_altFitRange',
    ]
    for binKey, latexLine in binKeyToLine.items():
        if binKey not in ['jpsi', 'psi2s']:
            db = shelve.open(r"{0}/fitResults_{1}.db".format(
                db_dir, q2bins[binKey]['label']))
            latexLine.append(r"${0:.01f} \pm {1:.01f}$".format(
                db['nSig']['getVal'], db['nSig']['getError']))
            fl = unboundFlToFl(db['unboundFl']['getVal'])
            latexLine.append(
                "${0:.2f}^{{{1:+.2f}}}_{{{2:+.2f}}} \pm {3:.2f}$".format(
                    unboundAfbToAfb(db['unboundAfb']['getVal'],
                                    fl), db['stat_FC_afb']['getErrorHi'],
                    db['stat_FC_afb']['getErrorLo'],
                    math.sqrt(
                        sum([
                            pow(db[v + '_afb']['getError'], 2)
                            for v in syst_sources
                        ]))))
            latexLine.append(
                "${0:.2f}^{{{1:+.2f}}}_{{{2:+.2f}}} \pm {3:.2f}$".format(
                    fl, db['stat_FC_fl']['getErrorHi'],
                    db['stat_FC_fl']['getErrorLo'],
                    math.sqrt(
                        sum([
                            pow(db[v + '_fl']['getError'], 2)
                            for v in syst_sources
                        ]))))
            db.close()
        print(indent * (baseIndentLevel + 1) + " & ".join(latexLine) + r" \\")
        print(indent * (baseIndentLevel + 1) + r"\hline")

    print(indent * (baseIndentLevel + 0) + r"\end{tabular}")
    print("")