Пример #1
0
def runFit(evt, ip, vtrk, v, x, ktrkstr, kstr, param, img, hResoData, hResoMC):

    ROOT.gROOT.Reset()

    ROOT.gROOT.SetBatch()

    pstyle = style.SetPlotStyle(1, 'FIT')
    pstyle.SetOptFit(1111)

    figs = []

    if hResoData.GetEntries() < 10:
        #        print 'No stats in data: '+hResoData.GetName(), ktrkstr
        return figs, x, ktrkstr, kstr, -1, -1, -1, -1, -1, -1, -1, -1

    if hResoMC.GetEntries() < 10:
        #        print 'No stats in mc: '+hResoMC.GetName(), ktrkstr
        return figs, x, ktrkstr, kstr, -1, -1, -1, -1, -1, -1, -1, -1

    if param in ['pt', 'phi']:
        if options.selection == '':
            rResoData = fit.rebin(hResoData, 60, 30)
            rResoMC = fit.rebin(hResoMC, 60, 30)
        elif kstr == '_pt7p36to7p6':
            rResoData = fit.rebin(hResoData, 80, 30)
            rResoMC = fit.rebin(hResoMC, 80, 30)
        else:
            rResoData = fit.rebin(hResoData, 50, 30)
            rResoMC = fit.rebin(hResoMC, 50, 30)
        rmax = max(rResoData, rResoMC)
        hResoData = hResoData.Rebin(rmax)
        hResoMC = hResoMC.Rebin(rmax)
    else:
        if options.selection != '_pt3p0to10p0' and options.type == 'pv':
            rResoData = fit.rebin(hResoData, 1000, 30)
            rResoMC = fit.rebin(hResoMC, 1000, 30)
            rmax = max(rResoData, rResoMC)
            hResoData = hResoData.Rebin(rmax)
            hResoMC = hResoMC.Rebin(rmax)
        elif options.type == 'bs' and options.qcd:
            rResoData = fit.rebin(hResoData, 500, 30)
            rResoMC = fit.rebin(hResoMC, 500, 30)
            rmax = max(rResoData, rResoMC)
            hResoData = hResoData.Rebin(rmax)
            hResoMC = hResoMC.Rebin(rmax)
        elif options.type == 'bs' and options.selection == '_pt0p0to1p0':
            rResoData = fit.rebin(hResoData, 1000, 30)
            rResoMC = fit.rebin(hResoMC, 1000, 30)
            rmax = max(rResoData, rResoMC)
            hResoData = hResoData.Rebin(rmax)
            hResoMC = hResoMC.Rebin(rmax)
        else:
            rResoData = fit.rebin(hResoData, 500, 30)
            rResoMC = fit.rebin(hResoMC, 500, 30)
            rmax = max(rResoData, rResoMC)
            hResoData = hResoData.Rebin(rmax)
            hResoMC = hResoMC.Rebin(rmax)

    for h in [hResoData]:
        h.SetMarkerStyle(c.datamrk)
        h.SetMarkerSize(0.7)
        h.SetMarkerColor(1)
        h.SetLineColor(1)

    for h in [hResoMC]:
        h.SetMarkerSize(0)
        h.SetMarkerColor(c.mccol)
        h.SetLineColor(c.mccol)
        h.SetFillColor(c.mccol)
        h.SetLineStyle(1)

    intResoMC = hResoMC.Integral()
    intResoData = hResoData.Integral()

    hResoMC.Scale(intResoData / intResoMC)

    maxResoData = hResoData.GetMaximum()
    maxResoMC = hResoMC.GetMaximum()
    hResoMC.SetMaximum(1.2 * max(maxResoData, maxResoMC))
    hResoMC.SetMinimum(0.)

    selName = 'N_{trk}'
    units = ''
    if options.parampv == 'sumTrackPt':
        selName = '#sump_{T}'
        units = ' GeV'
    elif options.parampv == 'sumTrackPtSq':
        selName = '#sqrt{#sump^{2}_{T}}'
        units = ' GeV'

    # Resolution

    c1 = ROOT.TCanvas()

    hResoMC.Draw('hist')
    hResoData.Draw('e1 sames')

    fun.adjust(hResoMC, hResoData, nsig=2.0)

    if options.fit:

        if options.method == 'fwhm':
            nsig = 2.0
        else:
            ffit = '3g'
            nsig = 2.0

        if x == 'dz': ffit = '3g'

        resoChi2MC = 1e+10
        resResoMC, resoMC, resoErrMC, resoChi2MC = fit.doFit('mcfit',
                                                             hResoMC,
                                                             x,
                                                             kstr,
                                                             c.mcfit,
                                                             ffit,
                                                             nsig=nsig,
                                                             nTries=3)

        resoChi2Data = 1e+10
        resResoData, resoData, resoErrData, resoChi2Data = fit.doFit('datafit',
                                                                     hResoData,
                                                                     x,
                                                                     kstr,
                                                                     1,
                                                                     ffit,
                                                                     nsig=nsig,
                                                                     nTries=3)

        sysErrData, sysErrMC = hResoData.GetXaxis().GetBinWidth(
            2), hResoMC.GetXaxis().GetBinWidth(2)

        resResoMC.Draw("same")
        resResoData.Draw("same")

        if options.method == 'fwhm':
            # get resolution estimation from bins using the results of the maximum fit
            resoData, resoErrData, sysErrData = fit.fwhm(hResoData,
                                                         resResoData,
                                                         nmin=10000)
            resoMC, resoErrMC, sysErrMC = fit.fwhm(hResoMC,
                                                   resResoMC,
                                                   nmin=10000)

        resResoData.SetLineStyle(2)

        c1.Update()

        finfoData = hResoData.GetListOfFunctions().FindObject("stats")
        finfoData.__class__ = ROOT.TPaveStats
        finfoData.SetX1NDC(0.7)
        finfoData.SetX2NDC(0.95)
        finfoData.SetY1NDC(0.20)
        finfoData.SetY2NDC(0.40)
        lData = ROOT.TText(0.81, 0.41, "Data (fit)")
        lData.SetTextSize(0.035)
        lData.SetNDC()
        lData.Draw()

        finfoMC = hResoMC.GetListOfFunctions().FindObject("stats")
        finfoMC.__class__ = ROOT.TPaveStats
        finfoMC.SetX1NDC(0.7)
        finfoMC.SetX2NDC(0.95)
        finfoMC.SetY1NDC(0.45)
        finfoMC.SetY2NDC(0.65)
        lMC = ROOT.TText(0.81, 0.66, "Simulation (fit)")
        lMC.SetTextSize(0.035)
        lMC.SetNDC()
        lMC.Draw()

    else:

        resoData, resoErrData, sysErrData = fit.fwhm(hResoData, nmin=10000)
        resoMC, resoErrMC, sysErrMC = fit.fwhm(hResoMC, nmin=10000)

    if resoData * resoMC == 0.:
        resoData, resoErrData, sysErrData = 0., 0., 0.
        resoMC, resoErrMC, sysErrMC = 0., 0., 0.

    xLabel = x
    if x == 'd0': xLabel = 'd_{xy}'
    elif x == 'dz': xLabel = 'd_{z}'

    lDataReso = ROOT.TLatex(
        0.20, 0.61, "#sigma^{Data}_{" + xLabel + "} = %.1f #mum" % (resoData))
    lDataReso.SetNDC()
    lDataReso.SetTextFont(43)
    lDataReso.SetTextSize(20)
    lDataReso.Draw()

    lMCReso = ROOT.TLatex(
        0.20, 0.70, "#sigma^{Sim.}_{" + xLabel + "} = %.1f #mum" % (resoMC))
    lMCReso.SetNDC()
    lMCReso.SetTextFont(43)
    lMCReso.SetTextSize(20)
    lMCReso.Draw()

    lBin = ROOT.TLatex(0.43, 0.20, "Bin = %.1f #mum" % (sysErrData))
    lBin.SetNDC()
    lBin.SetTextFont(43)
    lBin.SetTextSize(14)
    lBin.Draw()

    if ip != 'bs':

        lSelPV = ROOT.TLatex(
            0.20, 0.85,
            str(vtrk['bins'][1]) + ' < ' + selName + ' < ' +
            str(vtrk['bins'][2]) + units)
        lSelPV.SetTextSize(0.035)
        lSelPV.SetNDC()
        lSelPV.Draw()

    else:

        lSelPVx = ROOT.TLatex(
            0.20, 0.87,
            'Beam width (x) = %.1f #mum' % (vtrk['beamwidthx'][int(ktrkstr)]))
        lSelPVy = ROOT.TLatex(
            0.20, 0.83,
            'Beam width (y) = %.1f #mum' % (vtrk['beamwidthy'][int(ktrkstr)]))
        lSelPVx.SetTextSize(0.032)
        lSelPVy.SetTextSize(0.032)
        lSelPVx.SetNDC()
        lSelPVy.SetNDC()
        lSelPVx.Draw()
        lSelPVy.Draw()

    pLabel = 'p_{T}'
    pUnits = 'GeV'
    pPrec = '%.2f'
    if param == 'eta':
        pLabel = '#eta'
        pUnits = ''
    elif param == 'phi':
        pLabel = '#phi'
        pUnits = ''
    elif param == 'npv':
        pLabel = 'N_{PV}'
        pUnits = ''
        pPrec = '%d'
    elif param == 'dr':
        pLabel = '#DeltaR'
        pUnits = ''

    lSel = ROOT.TLatex(
        0.20, 0.78, (pPrec + ' < ' + pLabel + ' < ' + pPrec + ' ' + pUnits) %
        (v['bins'][1], v['bins'][2]))
    lSel.SetTextSize(0.035)
    lSel.SetNDC()
    lSel.Draw()

    c1.Update()

    leg = ROOT.TLegend(0.82, 0.92, 0.990, 0.75)
    leg.SetFillColor(253)
    leg.SetBorderSize(0)
    leg.AddEntry(hResoData, "Data", "p")
    leg.AddEntry(hResoMC, "Simulation", "f")
    if options.fit:
        leg.AddEntry(resResoData, "Data (fit)", "l")
        leg.AddEntry(resResoMC, "Simulation (fit)", "l")
    leg.Draw()

    t1, t2, t3, t4 = style.cmslabel(1, c.year, evt)
    t1.Draw()
    t2.Draw()
    t3.Draw()
    t4.Draw()

    #    b = fun.isbadfit(resoChi2MC, resoChi2Data)
    #    b.Draw()

    foutput = 'ip' + ip + 'Reso_' + x + ktrkstr + kstr
    if ip == 'bs': foutput = 'ip' + ip + 'Reso_' + x + kstr + '_' + ktrkstr
    figs.append(foutput)
    c1.Print(options.output + '/' + foutput + '.' + img)
    c1.Clear()

    return figs, x, ktrkstr, kstr, resoData, resoErrData, intResoData, resoMC, resoErrMC, intResoMC, sysErrData, sysErrMC
Пример #2
0
                leg.AddEntry(h[p], "QCD", "f")
            elif p == 'TTGJets':
                leg.AddEntry(h[p], "t#bar{t}#gamma(#gamma)+jets", "f")
            elif p == 'TGJets':
                leg.AddEntry(h[p], "t/#bar{t}#gamma+jets", "f")
            elif p == 'VJets':
                leg.AddEntry(h[p], "V(#gamma)+jets", "f")
            elif p == 'Higgs':
                leg.AddEntry(h[p], "Higgs", "f")
            elif p == 'TT':
                leg.AddEntry(h[p], "t#bar{t}", "f")
            elif p == 'GJet':
                leg.AddEntry(h[p], "#gamma+jets", "f")
        leg.Draw()

        t1, t2, t3 = style.cmslabel(1)
        t1.Draw()
        t2.Draw()
        t3.Draw()
        t = style.channel(chan)
        t.Draw()

        hist_tqh_ratio.Divide(hSMbis)
        hSMbis_uncertainty = hSMbis.Clone()
        nbins = hSMbis.GetNbinsX()
        for i in range(nbins):
            mean = hSMbis_uncertainty.GetBinContent(i + 1)
            error = hSMbis_uncertainty.GetBinError(i + 1)
            upper_rel_error = 0. if mean == 0 else (mean + error) / mean
            lower_rel_error = 0 if mean == 0 else (mean - error) / mean
            error_mean = (upper_rel_error + lower_rel_error) / 2.
Пример #3
0
        hData.SetLineColor(1)

        hMC.SetMarkerSize(0)
        hMC.SetMarkerColor(c.mccol)
        hMC.SetLineColor(c.mccol)
        hMC.SetFillColor(c.mccol)
        hMC.SetLineStyle(1)

        leg = ROOT.TLegend(0.82, 0.92, 0.990, 0.75)
        leg.SetFillColor(253)
        leg.SetBorderSize(0)
        leg.AddEntry(hData, "Data", "p")
        leg.AddEntry(hMC, "Simulation", "f")
        leg.Draw()

        t1, t2, t3, t4 = style.cmslabel(1, c.year, evt)
        t1.Draw()
        t2.Draw()
        t3.Draw()
        t4.Draw()

        if h in ['ipPt', 'ipDrTrkJet']:
            hData.SetMinimum(10)
            hMC.SetMinimum(10)
            c1.SetLogy(1)
        else:
            c1.SetLogy(0)

        c1.Print(options.output + '/' + h + '.eps')
        c1.Clear()
Пример #4
0
        elif 'reso_x' in f:
            h0.GetYaxis().SetTitle('PV resolution in x [#mum]')
        elif 'reso_y' in f:
            h0.GetYaxis().SetTitle('PV resolution in y [#mum]')
        elif 'reso_z' in f:
            h0.GetYaxis().SetTitle('PV resolution in z [#mum]')
        elif 'pull_x' in f:
            h0.GetYaxis().SetTitle('PV pull in x')
        elif 'pull_y' in f:
            h0.GetYaxis().SetTitle('PV pull in y')
        elif 'pull_z' in f:
            h0.GetYaxis().SetTitle('PV pull in z')

    leg.Draw()

    t1, t2, t3, t4 = style.cmslabel(1, c.year, '', False)
    t1.Draw()
    t2.Draw()
    t3.Draw()
    t4.Draw()

    if 'eta' in options.param and 'dz' in files[0]: c1.SetLogy(1)
    if 'pt' in options.param:
        if options.log:
            h0.SetMinimum(5.)
            h0.SetMaximum(1000.)
            c1.SetLogy(1)

#    if options.selection:

    if options.param in ['phi', 'npv']:
Пример #5
0
def plot(c1, hData, hMC, mode, m, x, isDeconv=False):

    hData.SetMarkerStyle(20)
    hData.SetMarkerSize(1.0)
    hData.SetMarkerColor(1)
    hData.SetLineColor(1)

    hMC.SetMarkerStyle(22)
    hMC.SetMarkerSize(1.0)
    hMC.SetMarkerColor(c.mcfit)
    hMC.SetLineColor(c.mcfit)

    if mode == 'pv':
        if m == 'reso':
            if options.process == 'zb': h0 = c1.DrawFrame(0., 0., 20., 70.)
            else: h0 = c1.DrawFrame(0., 0., 400., 30.)
        else:
            if options.process == 'zb': h0 = c1.DrawFrame(0., 0., 20., 1.7)
            else: h0 = c1.DrawFrame(0., 0., 400., 1.7)

    if mode == 'pv':
        hMC.Draw('same')
        h0.GetXaxis().SetTitle(hMC.GetXaxis().GetTitle())
        h0.GetYaxis().SetTitle(hMC.GetYaxis().GetTitle())
    else:
        hMC.Draw('')
    hMC.Draw('pe1 same')
    hData.Draw('same')
    hData.Draw('pe1 same')

    if mode != 'pv':
        hMC.GetYaxis().SetRangeUser(0., 450.)
        if 'eta' in mode and x == 'dz': hMC.GetYaxis().SetRangeUser(0., 3000.)

    leg = ROOT.TLegend(0.62, 0.55, 0.86, 0.73)
    leg.SetFillColor(253)
    leg.SetBorderSize(0)
    leg.AddEntry(hData, "Data", "p")
    leg.AddEntry(hMC, "Simulation", "p")

    if mode == 'pv' and m == 'pull':
        leg = ROOT.TLegend(0.67, 0.25, 0.910, 0.43)
        leg.SetFillColor(253)
        leg.SetBorderSize(0)
        leg.AddEntry(hData, "Data", "p")
        leg.AddEntry(hMC, "Simulation", "p")

    leg.Draw()

    t1, t2, t3, t4 = style.cmslabel(2, c.year, evt, False)
    t1.Draw()
    t2.Draw()
    t3.Draw()
    t4.Draw()

    if isDeconv == False:
        for outdir in [options.output, 'pub']:
            if not options.pub and outdir == 'pub': continue
            c1.Print(outdir + '/' + mode + '_' + m + '_' + x + '_' +
                     options.process + '.pdf')
        if options.pub:
            c1.SaveAs('pub/' + mode + '_' + m + '_' + x + '_' +
                      options.process + '.root')
    else:
        for outdir in [options.output, 'pub']:
            if not options.pub and outdir == 'pub': continue
            c1.Print(outdir + '/' + mode + '_' + m + '_' + x + '_deconv_' +
                     options.process + '.pdf')
        if options.pub:
            c1.SaveAs('pub/' + mode + '_' + m + '_' + x + '_deconv_' +
                      options.process + '.root')
    c1.Clear()
Пример #6
0
def runFit(evt, v, x, kstr, img, hResoData, hResoMC, hPullData, hPullMC):

    ROOT.gROOT.Reset()

    ROOT.gROOT.SetBatch()

    pstyle = style.SetPlotStyle(1, 'FIT')
    pstyle.SetOptFit(1111)

    figs = []

    if hResoData.GetEntries() < 10:
        print 'No stats in data: ' + hResoData.GetName()
        sys.exit()
    if hResoMC.GetEntries() < 10:
        print 'No stats in mc: ' + hResoMC.GetName()
        sys.exit()

    for h in [hResoData, hPullData]:
        h.SetMarkerStyle(c.datamrk)
        h.SetMarkerSize(0.7)
        h.SetMarkerColor(1)
        h.SetLineColor(1)

    for h in [hResoMC, hPullMC]:
        h.SetMarkerSize(0)
        h.SetMarkerColor(c.mccol)
        h.SetLineColor(c.mccol)
        h.SetFillColor(c.mccol)
        h.SetLineStyle(1)

    intResoMC = hResoMC.Integral()
    intResoData = hResoData.Integral()
    hResoMC.Scale(intResoData / intResoMC)

    intPullMC = hPullMC.Integral()
    intPullData = hPullData.Integral()
    hPullMC.Scale(intPullData / intPullMC)

    # Rebin in case of fine-bin measurement
    #    hResoData = hResoData.Rebin(2)
    #    hResoMC = hResoMC.Rebin(2)
    #    hPullData = hPullData.Rebin(5)
    #    hPullMC = hPullMC.Rebin(5)

    maxResoData = hResoData.GetMaximum()
    maxResoMC = hResoMC.GetMaximum()
    hResoMC.SetMaximum(1.2 * max(maxResoData, maxResoMC))
    hResoMC.SetMinimum(0.)

    maxPullData = hPullData.GetMaximum()
    maxPullMC = hPullMC.GetMaximum()
    hPullMC.SetMaximum(1.2 * max(maxPullData, maxPullMC))
    hPullMC.SetMinimum(0.)

    selName = 'N_{trk}'
    units = ''
    if options.param == 'sumTrackPt':
        selName = '#sump_{T}'
        units = ' GeV'
    elif options.param == 'sumTrackPtSq':
        selName = '#sqrt{#sump^{2}_{T}}'
        units = ' GeV'

    # Resolution

    c1 = ROOT.TCanvas()

    fun.adjust(hResoMC, hResoData, nsig=5)

    hResoMC.Draw('hist')
    hResoData.Draw('e1 sames')

    resResoMC, resoMC, resoErrMC, resoChi2MC = fit.doFit('mcfit_reso',
                                                         hResoMC,
                                                         x,
                                                         kstr,
                                                         c.mcfit,
                                                         '2g',
                                                         nsig=3,
                                                         nTries=3)
    resResoMC.Draw("same")

    resResoData, resoData, resoErrData, resoChi2Data = fit.doFit(
        'datafit_reso', hResoData, x, kstr, 1, '2g', nsig=3, nTries=3)
    resResoData.Draw("same")
    resResoData.SetLineStyle(2)

    sysResoData = hResoData.GetXaxis().GetBinWidth(2)
    sysResoMC = hResoMC.GetXaxis().GetBinWidth(2)

    c1.Update()

    finfoData = hResoData.GetListOfFunctions().FindObject("stats")
    finfoData.__class__ = ROOT.TPaveStats
    finfoData.SetX1NDC(0.7)
    finfoData.SetX2NDC(0.95)
    finfoData.SetY1NDC(0.20)
    finfoData.SetY2NDC(0.40)
    lData = ROOT.TText(0.81, 0.41, "Data (fit)")
    lData.SetTextSize(0.035)
    lData.SetNDC()
    lData.Draw()

    finfoMC = hResoMC.GetListOfFunctions().FindObject("stats")
    finfoMC.__class__ = ROOT.TPaveStats
    finfoMC.SetX1NDC(0.7)
    finfoMC.SetX2NDC(0.95)
    finfoMC.SetY1NDC(0.45)
    finfoMC.SetY2NDC(0.65)
    lMC = ROOT.TText(0.81, 0.66, "Simulation (fit)")
    lMC.SetTextSize(0.035)
    lMC.SetNDC()
    lMC.Draw()

    lDataReso = ROOT.TLatex(
        0.20, 0.63, "#sigma^{Data}_{" + x + "} = %.1f #mum" % (resoData))
    lDataReso.SetNDC()
    lDataReso.SetTextFont(43)
    lDataReso.SetTextSize(20)
    lDataReso.Draw()

    lMCReso = ROOT.TLatex(0.20, 0.70,
                          "#sigma^{Sim.}_{" + x + "} = %.1f #mum" % (resoMC))
    lMCReso.SetNDC()
    lMCReso.SetTextFont(43)
    lMCReso.SetTextSize(20)
    lMCReso.Draw()

    lSel = ROOT.TLatex(
        0.20, 0.80,
        str(v['bins'][1]) + ' < ' + selName + ' < ' + str(v['bins'][2]) +
        units)
    lSel.SetTextSize(0.035)
    lSel.SetNDC()
    lSel.Draw()

    c1.Update()

    leg = ROOT.TLegend(0.82, 0.92, 0.990, 0.75)
    leg.SetFillColor(253)
    leg.SetBorderSize(0)
    leg.AddEntry(hResoData, "Data", "p")
    leg.AddEntry(hResoMC, "Simulation", "f")
    leg.AddEntry(resResoData, "Data (fit)", "l")
    leg.AddEntry(resResoMC, "Simulation (fit)", "l")
    leg.Draw()

    t1, t2, t3, t4 = style.cmslabel(1, c.year, evt)
    t1.Draw()
    t2.Draw()
    t3.Draw()
    t4.Draw()

    b = fun.isbadfit(resoChi2MC, resoChi2Data)
    b.Draw()

    foutput = 'pvReso_' + x + kstr
    figs.append(foutput)
    c1.Print(options.output + '/' + foutput + '.' + img)
    c1.Clear()

    # Pull

    fun.adjust(hPullMC, hPullData, nsig=5)

    hPullMC.Draw('hist')
    hPullData.Draw('e1 sames')

    resPullMC, pullMC, pullErrMC, pullChi2MC = fit.doFit('mcfit_pull',
                                                         hPullMC,
                                                         x,
                                                         kstr,
                                                         c.mcfit,
                                                         '1g',
                                                         nsig=2.5,
                                                         nTries=3)
    resPullMC.Draw("same")

    resPullData, pullData, pullErrData, pullChi2Data = fit.doFit(
        'datafit_pull', hPullData, x, kstr, 1, '1g', nsig=2.5, nTries=3)
    resPullData.Draw("same")
    resPullData.SetLineStyle(2)

    sysPullData = hPullData.GetXaxis().GetBinWidth(2)
    sysPullMC = hPullMC.GetXaxis().GetBinWidth(2)

    c1.Update()

    finfoData = hPullData.GetListOfFunctions().FindObject("stats")
    finfoData.__class__ = ROOT.TPaveStats
    finfoData.SetX1NDC(0.7)
    finfoData.SetX2NDC(0.95)
    finfoData.SetY1NDC(0.20)
    finfoData.SetY2NDC(0.40)
    lData = ROOT.TText(0.81, 0.41, "Data (fit)")
    lData.SetTextSize(0.035)
    lData.SetNDC()
    lData.Draw()

    finfoMC = hPullMC.GetListOfFunctions().FindObject("stats")
    finfoMC.__class__ = ROOT.TPaveStats
    finfoMC.SetX1NDC(0.7)
    finfoMC.SetX2NDC(0.95)
    finfoMC.SetY1NDC(0.45)
    finfoMC.SetY2NDC(0.65)
    lMC = ROOT.TText(0.81, 0.66, "Simulation (fit)")
    lMC.SetTextSize(0.035)
    lMC.SetNDC()
    lMC.Draw()

    lDataPull = ROOT.TLatex(0.20, 0.63,
                            "#sigma^{Data}_{" + x + "} = %.2f" % (pullData))
    lDataPull.SetNDC()
    lDataPull.SetTextFont(43)
    lDataPull.SetTextSize(20)
    lDataPull.Draw()

    lMCPull = ROOT.TLatex(0.20, 0.70,
                          "#sigma^{Sim.}_{" + x + "} = %.2f" % (pullMC))
    lMCPull.SetNDC()
    lMCPull.SetTextFont(43)
    lMCPull.SetTextSize(20)
    lMCPull.Draw()

    lSel = ROOT.TLatex(
        0.20, 0.80,
        str(v['bins'][1]) + ' < ' + selName + ' < ' + str(v['bins'][2]) +
        units)
    lSel.SetTextSize(0.035)
    lSel.SetNDC()
    lSel.Draw()

    c1.Update()

    leg = ROOT.TLegend(0.82, 0.92, 0.990, 0.75)
    leg.SetFillColor(253)
    leg.SetBorderSize(0)
    leg.AddEntry(hPullData, "Data", "p")
    leg.AddEntry(hPullMC, "Simulation", "f")
    leg.AddEntry(resPullData, "Data (fit)", "l")
    leg.AddEntry(resPullMC, "Simulation (fit)", "l")
    leg.Draw()

    t1, t2, t3, t4 = style.cmslabel(1, c.year, evt)
    t1.Draw()
    t2.Draw()
    t3.Draw()
    t4.Draw()

    b = fun.isbadfit(pullChi2MC, pullChi2Data)
    b.Draw()

    foutput = 'pvPull_' + x + kstr
    figs.append(foutput)
    c1.Print(options.output + '/' + foutput + '.' + img)
    c1.Clear()

    return figs, x, kstr, resoData, resoErrData, resoMC, resoErrMC, pullData, pullErrData, pullMC, pullErrMC, sysResoData, sysResoMC, sysPullData, sysPullMC
Пример #7
0
Файл: fit.py Проект: sowuy/tHGG
def makeModel(var, data_obs, sig, chan):

    # Derive background pdf

    dataPdf = {}
    dataPdfPar = {}

    ordMinBernstein = 1
    ordMaxBernstein = 10
    for ord in range(ordMinBernstein, ordMaxBernstein):
        dataPdfName = 'Bernstein' + str(ord)
        dataPdfPar[dataPdfName] = []
        dataPdf[dataPdfName] = [
            makePdf(var, 'Bernstein', ord, dataPdfPar[dataPdfName]), ord
        ]

    dataPdf = collections.OrderedDict(
        sorted(dataPdf.items(), key=lambda k: k[0]))
    dataPdfPar = collections.OrderedDict(
        sorted(dataPdfPar.items(), key=lambda k: k[0]))

    var.setRange('low', 100, 120)
    var.setRange('high', 130, 180)

    llh0 = 10E+10
    pval = 0.05
    ord0 = ordMinBernstein - 1
    bestBernstein = ''
    for name, pdf in dataPdf.items():
        res = dataPdf[name][0].fitTo(data_obs,\
        ROOT.RooFit.Minimizer("Minuit2","minimize"),\
        ROOT.RooFit.Minos(ROOT.kFALSE),ROOT.RooFit.Hesse(ROOT.kTRUE),\
        ROOT.RooFit.PrintLevel(-1000),\
        ROOT.RooFit.Save(),\
        ROOT.RooFit.Range("low,high"),\
        ROOT.RooFit.SumW2Error(ROOT.kTRUE))
        llh = res.minNll()
        chi2 = 2. * (llh0 - llh)
        ord = dataPdf[name][1]
        delta_dof = ord - ord0
        prob = ROOT.TMath.Prob(chi2, delta_dof)
        if prob > pval:
            bestBernstein = name
            break
        ord0 = ord
        llh0 = llh

    dataPdfBernstein = dataPdf[bestBernstein]

    if chan == 'leptonic':
        nBins = 32
    else:
        nBins = 64

    dataPlot = var.frame(ROOT.RooFit.Title("Fit"), ROOT.RooFit.Bins(nBins))

    dataPdfFinal = [dataPdfBernstein]

    for pdf in dataPdfFinal:

        data_obs.plotOn(dataPlot, ROOT.RooFit.DataError(ROOT.RooAbsData.SumW2),
                        ROOT.RooFit.MarkerStyle(20),
                        ROOT.RooFit.Name('data_obs'),
                        ROOT.RooFit.XErrorSize(0))
        pdf[0].plotOn(dataPlot, ROOT.RooFit.LineColor(ROOT.kBlue),
                      ROOT.RooFit.Name(pdf[0].GetName()))
        dataPlot.GetXaxis().SetTitle('Diphoton invariant mass [GeV]')

    bestDataPdf = dataPdfFinal[0]

    c1 = ROOT.TCanvas("c1", "c1", 650, 500)

    dataPlot.Draw()

    t1, t2, t3 = style.cmslabel(2)
    t1.Draw()
    t3.Draw()
    t = style.channel(chan)
    t.Draw()

    leg = ROOT.TLegend(0.65, 0.65, 0.88, 0.83)
    leg.SetFillColor(253)
    leg.SetBorderSize(0)
    leg.AddEntry(dataPlot.findObject('data_obs'), 'Data', 'p')
    leg.AddEntry(dataPlot.findObject(bestBernstein),
                 'Bernstein(' + str(dataPdfBernstein[1]) + ')', 'l')
    leg.Draw()

    #    param = bestDataPdf[0].getParameters(ROOT.RooArgSet())

    c1.Print('pics/bkgModel.eps')

    # Derive signal pdf

    sigPdf = {}
    sigPdfPar = {}
    sigPdfGaus = {}
    sigPdfDm = {}
    sigPdfMean = {}
    sigPdfSigma = {}

    mH = ROOT.RooRealVar("mH", "mH", 125., 115., 135.)
    mH.setConstant(True)

    ordMaxGaus = 4
    for ord in range(ordMaxGaus):
        sigPdfName = 'Gaus' + str(ord)
        sigPdfPar[sigPdfName] = []
        sigPdfGaus[sigPdfName] = []
        sigPdfDm[sigPdfName] = []
        sigPdfMean[sigPdfName] = []
        sigPdfSigma[sigPdfName] = []
        sigPdf[sigPdfName] = [makePdf(var,'Gaus',ord,sigPdfPar[sigPdfName],sigPdfGaus[sigPdfName],\
        sigPdfDm[sigPdfName],sigPdfMean[sigPdfName],sigPdfSigma[sigPdfName],mH),ord]

    sigPdf = collections.OrderedDict(sorted(sigPdf.items(),
                                            key=lambda k: k[0]))
    sigPdfPar = collections.OrderedDict(
        sorted(sigPdfPar.items(), key=lambda k: k[0]))
    sigPdfGaus = collections.OrderedDict(
        sorted(sigPdfGaus.items(), key=lambda k: k[0]))
    sigPdfDm = collections.OrderedDict(
        sorted(sigPdfDm.items(), key=lambda k: k[0]))
    sigPdfMean = collections.OrderedDict(
        sorted(sigPdfMean.items(), key=lambda k: k[0]))
    sigPdfSigma = collections.OrderedDict(
        sorted(sigPdfSigma.items(), key=lambda k: k[0]))

    llh0 = 0
    pval = 0.05
    ord0 = 0
    bestGaus = ''
    for name, pdf in sigPdf.items():

        print sigPdf[name][0]

        #        res = sigPdf[name][0].fitTo(sig,ROOT.RooFit.Minimizer("Minuit2","minimize"),\
        #        ROOT.RooFit.Minos(ROOT.kFALSE),ROOT.RooFit.Hesse(ROOT.kTRUE),\
        #        ROOT.RooFit.Warnings(ROOT.kTRUE),ROOT.RooFit.PrintLevel(-1000),\
        #        ROOT.RooFit.SumW2Error(True),\
        #        ROOT.RooFit.Save(),\
        #        ROOT.RooFit.Range(115.,135.))

        res = sigPdf[name][0].fitTo(sig,ROOT.RooFit.Minimizer("Minuit2","minimize"),\
        ROOT.RooFit.Minos(ROOT.kFALSE),ROOT.RooFit.Hesse(ROOT.kTRUE),\
        ROOT.RooFit.SumW2Error(True),\
        ROOT.RooFit.Save(),\
        ROOT.RooFit.Range(115.,135.))

        llh = res.minNll()
        chi2 = 2. * (llh0 - llh)
        ord = sigPdf[name][1]
        delta_dof = (2 * (ord + 1) + ord) - (2 * (ord0 + 1) + ord0)
        prob = ROOT.TMath.Prob(chi2, delta_dof)
        print prob
        if prob > pval:
            bestGaus = name
            break
        ord0 = ord
        llh0 = llh

    sigPdfGausResult = sigPdf[bestGaus]

    sigPlot = var.frame(ROOT.RooFit.Title("Fit"), ROOT.RooFit.Bins(64),
                        ROOT.RooFit.Range(110, 140))

    sigPdfFinal = [sigPdfGausResult]

    for pdf in sigPdfFinal:

        sig.plotOn(sigPlot, ROOT.RooFit.DataError(ROOT.RooAbsData.SumW2),
                   ROOT.RooFit.MarkerStyle(20), ROOT.RooFit.Name('sig'),
                   ROOT.RooFit.XErrorSize(0))
        pdf[0].getVariables().Print("v")
        pdf[0].plotOn(sigPlot, ROOT.RooFit.LineColor(ROOT.kBlue),
                      ROOT.RooFit.Name(pdf[0].GetName()))
        sigPlot.GetXaxis().SetTitle('Diphoton invariant mass [GeV]')

    bestSigPdf = sigPdfFinal[0]

    c1 = ROOT.TCanvas("c1", "c1", 650, 500)

    sigPlot.Draw()

    t1, t2, t3 = style.cmslabel(2)
    t1.Draw()
    t3.Draw()
    t = style.channel(chan)
    t.Draw()

    leg = ROOT.TLegend(0.65, 0.65, 0.88, 0.83)
    leg.SetFillColor(253)
    leg.SetBorderSize(0)
    leg.AddEntry(sigPlot.findObject('sig'), 'Data', 'p')
    leg.AddEntry(sigPlot.findObject(bestGaus),
                 'Gaus(' + str(sigPdfGausResult[1] + 1) + ')', 'l')
    leg.Draw()

    #    param = bestSigPdf[0].getParameters(ROOT.RooArgSet())

    #    iter = param.createIterator()
    #    while True:
    #        arg = iter.Next()
    #        if arg == None: break
    #        name = arg.GetName()
    #        print = param[name].getVal()

    c1.Print('pics/sigModel.eps')

    # Combine sig+bkg pdfs

    c1 = ROOT.TCanvas("c1", "c1", 650, 500)

    bkg = bestDataPdf[0]
    sig = bestSigPdf[0]

    fsig = ROOT.RooRealVar("fsig", "signal fraction", 0.001, 0., 1.)
    combPdf = ROOT.RooAddPdf("comb", "comb", ROOT.RooArgList(sig, bkg),
                             ROOT.RooArgList(fsig))

    param = combPdf.getParameters(ROOT.RooArgSet())

    iter = param.createIterator()
    while True:
        arg = iter.Next()
        if arg == None: break
        name = arg.GetName()
        if 'Gaus_dm' in name: param[name].setConstant(True)


#        print name, param[name].getVal()

    combPlot = var.frame(ROOT.RooFit.Title("Fit"), ROOT.RooFit.Bins(nBins))

    data_obs.plotOn(combPlot, ROOT.RooFit.DataError(ROOT.RooAbsData.SumW2),
                    ROOT.RooFit.MarkerStyle(20), ROOT.RooFit.Name('data_obs'),
                    ROOT.RooFit.XErrorSize(0))

    #    sig.plotOn(combPlot,ROOT.RooFit.Normalization(0.1),ROOT.RooFit.LineColor(2))
    sig.plotOn(combPlot, ROOT.RooFit.LineColor(2))

    res = combPdf.fitTo(data_obs,ROOT.RooFit.Minimizer("Minuit2","minimize"),\
    ROOT.RooFit.Minos(ROOT.kFALSE),ROOT.RooFit.Hesse(ROOT.kTRUE),\
    ROOT.RooFit.SumW2Error(True),\
    ROOT.RooFit.Save())

    bkgComponent = ROOT.RooArgSet(bkg)
    sigComponent = ROOT.RooArgSet(sig)

    combPdf.plotOn(combPlot, ROOT.RooFit.Components(bkgComponent),
                   ROOT.RooFit.LineStyle(2))
    combPdf.plotOn(combPlot, ROOT.RooFit.Components(sigComponent),
                   ROOT.RooFit.LineStyle(2), ROOT.RooFit.LineColor(2))
    combPdf.plotOn(combPlot)

    combPlot.GetXaxis().SetTitle('Diphoton invariant mass [GeV]')

    combPlot.Draw()

    t1, t2, t3 = style.cmslabel(2)
    t1.Draw()
    t3.Draw()
    t = style.channel(chan)
    t.Draw()

    combPlot.Print('v')

    leg = ROOT.TLegend(0.65, 0.65, 0.88, 0.83)
    leg.SetFillColor(253)
    leg.SetBorderSize(0)
    leg.AddEntry(combPlot.findObject('data_obs'), 'Data', 'p')
    leg.AddEntry(combPlot.findObject('comb_Norm[DiPhoMassFit]'),
                 'Combined fit', 'l')
    leg.AddEntry(
        combPlot.findObject('comb_Norm[DiPhoMassFit]_Comp[' + bestBernstein +
                            ']'), 'Background', 'l')
    leg.AddEntry(
        combPlot.findObject('comb_Norm[DiPhoMassFit]_Comp[' + bestGaus + ']'),
        'Signal', 'l')
    leg.AddEntry(
        combPlot.findObject(bestGaus + '_Norm[DiPhoMassFit]_Range[fit_nll_' +
                            bestGaus + '_sig]_NormRange[fit_nll_' + bestGaus +
                            '_sig]'), 'Signal fit', 'l')
    leg.Draw()

    c1.Print('pics/combModel.eps')