Пример #1
0
def makeBinnedResPlot(MUON, fs, sp, quantity, q2):
    h = HistogramGetter.getHistogram(f, (fs, sp), '{M}_{Q}ResVS{Q2}'.format(M=MUON, Q=quantity, Q2=q2)).Clone()

    fname = 'pdfs/SRR_{}_{}_{}-Binned_{}HTo2XTo{}_{}.pdf'.format(MUON, quantity+'Res', q2, 'Trig-' if TRIGGER else '', fs, SPStr(sp))

    pretty, binranges, values, colors, colors2, legName = getBinningValues(q2)

    projections = {key:h.ProjectionY('_'+str(i), key[0], key[1]) for i,key in enumerate(binranges)}
    plots       = {key:Plotter.Plot(projections[key], legName.format(Q2=pretty, V1=values[key][0], V2=values[key][1]), 'l', 'hist') for key in binranges}

    canvas = Plotter.Canvas(lumi=SPLumiStr(fs, *sp))
    for key in binranges:
        RT.addFlows(plots[key])
        plots[key].Rebin(10)
        if plots[key].Integral() != 0:
            plots[key].Scale(1./plots[key].Integral())
        canvas.addMainPlot(plots[key])

    canvas.makeLegend(lWidth=.25, pos='tr')
    canvas.legend.moveLegend(X=-.08)
    canvas.legend.resizeHeight()
    canvas.setMaximum(recompute=True)

    for i, key in enumerate(binranges):
        plots[key].SetLineColor(colors[key])
        plots[key].setTitles(X=plots[key].GetXaxis().GetTitle(), Y='Normalized Counts')
        canvas.drawText('#color[{}]{{'.format(colors2[key]) + 'RMS = {:.4f}'.format(plots[key].GetStdDev()) + '}',
                        (canvas.legend.GetX1NDC()+.01, canvas.legend.GetY1NDC()-(i*0.04)-.04)
        )

    RT.addBinWidth(canvas.firstPlot)
    canvas.cleanup(fname)
Пример #2
0
def fillPlots(fs, sp, HList, FNAME):
    # get file and tree
    f = R.TFile.Open(FNAME.format('HTo2XTo' + fs + '_' + SPStr(sp)))
    t = f.Get('SimpleNTupler/DDTree')

    # set basic particle aliases
    RT.setGenAliases(t, fs)

    # set additional aliases from HAliases
    for alias, expr in HAliases.iteritems():
        t.SetAlias(alias, expr)

    # define histogram configurations for this signal point
    HConfig = HistogramConfigurations(fs, sp)

    # declare histograms
    # make sure histograms don't get deleted when file is closed
    # fill histograms using TTree::Draw
    for key in HList:
        if key not in HConfig.data:
            raise Exception('At least one histogram key: ' + key +
                            ' not known')
        nAxes = str(HConfig.data[key]['nAxes'])
        HISTS[(fs, sp)][key] = getattr(R, 'TH' + nAxes + 'F')(*HConfig[key])
        Draw(t, HConfig, key, HExpressions[key])
        HISTS[(fs, sp)][key].SetDirectory(0)

    # cleanup
    del t
    f.Close()
    del f
def makeOverlaidPlot():
    REFLIST = (('2Mu2J', (1000, 20, 2)), ('2Mu2J', (200, 50, 200)))
    key = 'Dim_deltaPhi_Matched'

    h = {
        REFLIST[0]: HISTS[REFLIST[0]][key].Clone(),
        REFLIST[1]: HISTS[REFLIST[1]][key].Clone(),
    }

    p = {}
    for ref in h:
        RT.addFlows(h[ref])
        if h[ref].GetNbinsX() > 100: h[ref].Rebin(10)
        p[ref] = Plotter.Plot(h[ref], '2#mu2j ({}, {}, {})'.format(*ref[1]),
                              'l', 'hist')

    fname = 'pdfs/{}{}_Overlaid.pdf'.format(key, CUTSTRING)

    canvas = Plotter.Canvas()
    canvas.addMainPlot(p[REFLIST[1]])
    canvas.addMainPlot(p[REFLIST[0]])
    canvas.makeLegend(lWidth=.25, pos='tl')
    #canvas.legend.moveLegend(Y=-.3)
    canvas.legend.resizeHeight()
    p[REFLIST[1]].SetLineColor(R.kBlue)
    p[REFLIST[0]].SetLineColor(R.kRed)
    RT.addBinWidth(canvas.firstPlot)

    pave1 = canvas.makeStatsBox(p[REFLIST[1]], color=R.kBlue)
    pave2 = canvas.makeStatsBox(p[REFLIST[0]], color=R.kRed)
    Plotter.MOVE_OBJECT(pave2, Y=-.22, NDC=False)
    canvas.cleanup(fname)
Пример #4
0
def makeRepEffectPlots(hkey):
    HISTS, PConfig = HG.getBackgroundHistograms(FILES['MC'], hkey)
    HISTS = HISTS[hkey]
    PConfig = PConfig[hkey]

    PLOTS = {}
    for key in HG.BGORDER + ('stack', ):
        PLOTS[key] = Plotter.Plot(HISTS[key], *PConfig[key])

    canvas = Plotter.Canvas(lumi='MC, {} replacement'.format(
        hkey.replace('LxySig-', '').replace('Lxy-', '')),
                            logy=True)

    for key in HG.BGORDER:
        PLOTS[key].setColor(HG.PLOTCONFIG[key]['COLOR'], which='LF')

    canvas.addMainPlot(PLOTS['stack'])

    canvas.firstPlot.setTitles(X='', copy=PLOTS[HG.BGORDER[0]])
    canvas.firstPlot.setTitles(Y='Normalized Counts')
    canvas.makeLegend(lWidth=.27, pos='tr', autoOrder=False, fontscale=0.8)
    for ref in reversed(HG.BGORDER):
        canvas.addLegendEntry(PLOTS[ref])
    canvas.legend.resizeHeight()
    RT.addBinWidth(canvas.firstPlot)

    canvas.firstPlot.SetMaximum(10.**7.)
    canvas.firstPlot.SetMinimum(10.**0.)
    canvas.cleanup('RepEffect_MC_{}.pdf'.format(hkey))
Пример #5
0
def makeSignalPlot(hkey):
    HISTS = HG.getAddedSignalHistograms(FILES['2Mu2J'], '2Mu2J', hkey)
    h = HISTS[hkey]
    p = Plotter.Plot(h, '', '', 'hist')
    canvas = Plotter.Canvas(lumi='Signal: H#rightarrow2X#rightarrow2#mu + *',
                            logy=True if hkey != 'nDTHits' else False)
    canvas.addMainPlot(p)
    p.SetLineColor(R.kBlue)
    canvas.firstPlot.SetMinimum(0.9)
    pave = canvas.makeStatsBox(p, color=R.kBlue)
    if hkey in ('nHits', 'LxySig'):
        Plotter.MOVE_OBJECT(pave, Y=-.3)
    canvas.mainPad.Update()
    if canvas.logy:
        line = R.TLine(
            CONFIG[hkey]['val'], canvas.firstPlot.GetMinimum(),
            CONFIG[hkey]['val'],
            10.**(R.TMath.Log10(canvas.firstPlot.GetMaximum()) * 1.06))
    else:
        line = R.TLine(CONFIG[hkey]['val'], canvas.firstPlot.GetMinimum(),
                       CONFIG[hkey]['val'],
                       canvas.firstPlot.GetMaximum() * 1.05)
    line.Draw()
    line.SetLineStyle(2)
    print '\033[31m{:6s} {:8s} {:5.0f} {:5.0f} {:7.2%}\033[m'.format(
        'Signal', hkey, *fractionCut(hkey, canvas.firstPlot.plot))
    RT.addBinWidth(canvas.firstPlot)
    canvas.cleanup('pdfs/NM1D_{}_2Mu2J.pdf'.format(hkey))
def importHistogram(allhists,
                    resolution_variable,
                    includes=None,
                    excludes=None):
    imported_hists = []
    imported_d0hists = []
    for dat in allhists:
        resolution_hists = getHistNames(allhists,
                                        dat,
                                        *includes,
                                        exclude=excludes)

        for key in resolution_hists:
            if not all([d0str in key for d0str in ["__d0GT", "__d0LT"]]):
                continue

            h = allhists[dat][key].Clone()
            RT.addFlows(h)
            imported_hists.append(h)

            d0_histname = key.replace("__{}".format(resolution_variable),
                                      "__d0VAR")
            if d0_histname == key:
                raise Exception("Error parsing the name of the d0 histogram")

            d0_h = allhists[dat][d0_histname].Clone()
            RT.addFlows(d0_h)
            imported_d0hists.append(d0_h)

    return imported_hists, imported_d0hists
Пример #7
0
def makeTestPlot():
    hkey = 'DSA-deltaPhi'
    HISTS = HG.getAddedSignalHistograms(FILES['2Mu2J'], '2Mu2J',
                                        ('deltaPhi', ))
    DATAHISTS, DataPConfig = HG.getDataHistograms(FILES['Data'], hkey)

    HISTS[hkey] = HISTS['deltaPhi']

    pS = Plotter.Plot(HISTS[hkey], 'H#rightarrow2X#rightarrow2#mu signal', 'l',
                      'hist')
    pD = Plotter.Plot(DATAHISTS[hkey]['data'], *DataPConfig[hkey]['data'])

    canvas = Plotter.Canvas(lumi='2#mu signal + 10% of 2016 data', logy=True)

    canvas.addMainPlot(pS)
    canvas.addMainPlot(pD)

    pS.setColor(R.kBlue, which='L')

    canvas.makeLegend(lWidth=.25)
    canvas.legend.resizeHeight()
    canvas.legend.moveLegend(X=-.1)

    canvas.firstPlot.SetMinimum(0.5)
    canvas.firstPlot.SetMaximum(50000.)
    canvas.firstPlot.setTitles(Y='Long-Lived Candidates')

    line = R.TLine(R.TMath.Pi() / 2., 0.5, R.TMath.Pi() / 2., 50000.)
    line.Draw()
    line.SetLineStyle(2)

    RT.addBinWidth(canvas.firstPlot)
    canvas.cleanup('deltaPhi.pdf')
Пример #8
0
def makeMCPlots():
    f = R.TFile.Open('roots/PATMuonStudyPlots_Combined_BS8_MC.root')
    #f = R.TFile.Open('roots/PATMuonStudyPlots_Combined_BS8_MC_OldPATMatch.root')
    BGORDER = ('WJets', 'WW', 'WZ', 'ZZ', 'tW', 'tbarW', 'ttbar', 'QCD20toInf-ME', 'DY10to50', 'DY50toInf')
    PC = HG.PLOTCONFIG
    for hkey in ('PAT-LxySig', 'DSA-LxySig', 'PAT-vtxChi2', 'DSA-vtxChi2'):
        HISTS = {}
        HISTS['stack'] = R.THStack('hStack', '')
        PConfig = {'stack':('', '', 'hist')}
        for ref in BGORDER:
           HISTS[ref] = HG.getHistogram(f, ref, hkey).Clone()
           #RT.addFlows(HISTS[ref])
           HISTS[ref].Scale(PC[ref]['WEIGHT'])
           HISTS[ref].Rebin(10)
           HISTS['stack'].Add(HISTS[ref])
           PConfig[ref] = (PC[ref]['LATEX'], 'f', 'hist')

        PLOTS = {}
        for key in BGORDER + ('stack',):
            PLOTS[key] = Plotter.Plot(HISTS[key], *PConfig[key])
        canvas = Plotter.Canvas(logy=True)
        for key in BGORDER:
            PLOTS[key].setColor(PC[key]['COLOR'], which='LF')
        canvas.addMainPlot(PLOTS['stack'])
        # this has to be here because it has to be drawn first
        if 'LxySig' in hkey:
            canvas.firstPlot.GetXaxis().SetRangeUser(0., 1000.)
            pass
        if 'vtxChi2' in hkey:
            #canvas.firstPlot.GetXaxis().SetRangeUser(0., 200.)
            pass
        canvas.firstPlot.setTitles(X='', copy=PLOTS[BGORDER[0]])
        canvas.firstPlot.setTitles(Y='Normalized Counts')
        canvas.makeLegend(lWidth=.27, pos='tr', autoOrder=False, fontscale=0.8)
        for ref in reversed(BGORDER):
            canvas.addLegendEntry(PLOTS[ref])
        canvas.legend.resizeHeight()
        RT.addBinWidth(canvas.firstPlot)

        HISTS['sum'] = HISTS['stack'].GetStack().Last()
        nBins = HISTS['sum'].GetNbinsX()

        if 'LxySig' in hkey:
            val = 100.
        if 'vtxChi2' in hkey:
            val = 50.
        print '{} Mean         : {}'.format(hkey,      HISTS['sum'].GetMean())
        print '{} Overflow   % : {}'.format(hkey,      HISTS['sum'].GetBinContent(                           nBins+1)/HISTS['sum'].Integral(0, nBins+1)*100.)
        print '{} > {:<8.0f} % : {}'.format(hkey, val, HISTS['sum'].Integral     (HISTS['sum'].FindBin(val), nBins+1)/HISTS['sum'].Integral(0, nBins+1)*100.)

        if hkey == 'PAT-LxySig':
            h = HG.getHistogram(f, 'DY50toInf', hkey).Clone()
            print '{} DY50toInf    : {}'.format(hkey, h.Integral(h.FindBin(100.), h.GetNbinsX()+1))

        canvas.firstPlot.SetMaximum(HISTS['sum'].GetMaximum()*1.05)
        canvas.firstPlot.SetMinimum(1.)
        canvas.cleanup('pdfs/MC_'+hkey+'.pdf')
def makeLessMorePlot(fs, sp, quantity):
    h = {
        'Less':
        HG.getHistogram(FILES[fs], (fs, sp),
                        '{}-Less'.format(quantity)).Clone(),
        'More':
        HG.getHistogram(FILES[fs], (fs, sp),
                        '{}-More'.format(quantity)).Clone(),
    }

    for key in h:
        try:
            h[key].Scale(1. / h[key].Integral())
        except:
            return

    pretty = {
        'Less': {
            'leg': 'L_{xy} < 320 cm',
            'col': R.kBlue
        },
        'More': {
            'leg': 'L_{xy} > 320 cm',
            'col': R.kRed
        },
    }

    p = {
        key: Plotter.Plot(h[key], pretty[key]['leg'], 'l', 'hist')
        for key in h
    }

    prettyFS = '2#mu' if '2Mu' in fs else '4#mu'
    c = Plotter.Canvas(
        lumi='H#rightarrow2X#rightarrow{} ({} GeV, {} GeV, {} mm)'.format(
            prettyFS, *sp),
        cWidth=600 if ARGS.SQUARE else 800)

    for key in p:
        c.addMainPlot(p[key])
        p[key].setColor(pretty[key]['col'], which='LM')

    RT.addBinWidth(c.firstPlot)
    c.makeLegend(lWidth=0.125, pos='tr')
    c.legend.resizeHeight()
    c.legend.moveLegend(X=-.4)
    c.setMaximum()

    if ARGS.SQUARE:
        c.firstPlot.scaleTitleOffsets(1.1, 'X')
    c.cleanup('pdfs/LESSMORE_{}_{}_{}_{}_{}.pdf'.format(quantity, fs, *sp),
              mode='LUMI')
Пример #10
0
def makePerSignalPlots(fs):
    for sp in SIGNALPOINTS:
        for key in HISTS[(fs, sp)]:
            h = HISTS[(fs, sp)][key]
            RT.addFlows(h)
            p = Plotter.Plot(h, '', 'p', 'hist')
            canvas = Plotter.Canvas(lumi=SPLumiStr(fs, *sp))
            canvas.addMainPlot(p)
            p.SetLineColor(R.kBlue)
            RT.addBinWidth(p)
            pave = canvas.makeStatsBox(p, color=R.kBlue)
            canvas.cleanup('pdfs/Gen_{}_{}HTo2XTo{}_{}.pdf'.format(
                key, 'Trig-' if TRIGGER else '', fs, SPStr(sp)))
def makePerSamplePlots():
    for ref in HISTS:
        for key in HISTS[ref]:
            if 'DenVS' in key: continue

            matches = re.match(r'(.*)EffVS(.*)', key)

            cut = matches.group(1)
            val = matches.group(2)

            if cut in Selections.CutLists['MuonCutList'] and val == 'Lxy':
                continue
            if cut in Selections.CutLists['DimuonCutList'] and val in ('pT',
                                                                       'eta',
                                                                       'd0'):
                continue

            if type(ref) == tuple:
                if ref[0] == '4Mu': name = 'HTo2XTo4Mu_'
                elif ref[0] == '2Mu2J': name = 'HTo2XTo2Mu2J_'
                name += SPStr(ref[1])
                if TRIGGER:
                    name = 'Trig-' + name
                lumi = SPLumiStr(ref[0], *ref[1])
                legName = HistogramGetter.PLOTCONFIG['HTo2XTo' +
                                                     ref[0]]['LATEX']
            else:
                name = ref
                lumi = HistogramGetter.PLOTCONFIG[ref]['LATEX']
                legName = HistogramGetter.PLOTCONFIG[ref]['LATEX']

            h = HISTS[ref][key].Clone()
            RT.addFlows(h)
            d = HISTS[ref][key.replace('Eff', 'Den')].Clone()
            RT.addFlows(d)
            g = R.TGraphAsymmErrors(h, d, 'cp')
            g.SetNameTitle(
                'g_' + key,
                ';' + h.GetXaxis().GetTitle() + ';' + h.GetYaxis().GetTitle())
            p = Plotter.Plot(g, '', 'pe', 'pe')

            canvas = Plotter.Canvas(lumi=lumi)
            canvas.addMainPlot(p)
            p.setColor(R.kBlue)
            canvas.firstPlot.SetMinimum(0.)
            canvas.firstPlot.SetMaximum(1.)

            fname = 'pdfs/NM1E_{}_{}.pdf'.format(key, name)
            canvas.cleanup(fname)
def makeGenRecoPlots():
    for ref in HISTS:
        if not type(ref) == tuple: continue
        if ref[0] == '4Mu':
            name = 'HTo2XTo4Mu_'
            latexFS = '4#mu'
        elif ref[0] == '2Mu2J':
            name = 'HTo2XTo2Mu2J_'
            latexFS = '2#mu2j'
        if TRIGGER:
            name = 'Trig-' + name
        name += SPStr(ref[1])
        lumi = SPLumiStr(ref[0], *ref[1])

        colors = {'Matched': R.kRed, 'Closest': R.kBlue}
        KEYS = ('Matched', 'Closest')

        for MUON in ('DSA', 'REF'):
            h, p = {}, {}
            for key in KEYS:
                h[key] = HISTS[ref]['{}_{}_{}'.format(MUON, 'deltaRGR',
                                                      key)].Clone()
                RT.addFlows(h[key])
                if h[key].GetNbinsX() > 100: h.Rebin(10)
                p[key] = Plotter.Plot(h[key], key, 'l', 'hist')
            fname = 'pdfs/{}{}_{}_{}_{}.pdf'.format(MUON, CUTSTRING,
                                                    'deltaRGR', 'Matched',
                                                    name)

            canvas = Plotter.Canvas(lumi=lumi)
            for key in KEYS:
                canvas.addMainPlot(p[key])
                p[key].SetLineColor(colors[key])

            canvas.makeLegend(lWidth=.25, pos='tr')
            canvas.legend.resizeHeight()
            canvas.setMaximum()
            RT.addBinWidth(canvas.firstPlot)

            LPOS = (canvas.legend.GetX1NDC() + .01,
                    canvas.legend.GetY1NDC() - .04)

            for i, key in enumerate(KEYS):
                canvas.drawText(text='#color[{}]{{n = {:d}}}'.format(
                    colors[key], int(p[key].GetEntries())),
                                pos=(LPOS[0], LPOS[1] - i * 0.04))

            canvas.cleanup(fname)
Пример #13
0
def makeEffPlots(quantity, fs, SP=None):
    HKeys = {
        'Eff': '{}Eff',
        'Den': '{}Den',
    }
    for key in HKeys:
        HKeys[key] = HKeys[key].format(quantity)

    h = {}
    p = {}
    g = {}

    if SP is None:
        for i, sp in enumerate(SIGNALPOINTS):
            if i == 0:
                for key in HKeys:
                    h[key] = HISTS[(fs, sp)][HKeys[key]].Clone()
                    h[key].SetDirectory(0)
            else:
                for key in HKeys:
                    h[key].Add(HISTS[(fs, sp)][HKeys[key]])
    else:
        sp = SP
        for key in HKeys:
            h[key] = HISTS[(fs, sp)][HKeys[key]].Clone()
            h[key].SetDirectory(0)

    for key in HKeys:
        RT.addFlows(h[key])
        h[key].Rebin(10)

    g['Eff'] = R.TGraphAsymmErrors(h['Eff'], h['Den'], 'cp')
    g['Eff'].SetNameTitle(
        'g_Eff',
        ';' + h['Eff'].GetXaxis().GetTitle() + ';Vertex Fit Efficiency')
    p['Eff'] = Plotter.Plot(g['Eff'], '', 'elp', 'pe')

    canvas = Plotter.Canvas(lumi=fs if SP is None else SPLumiStr(fs, *SP))
    canvas.addMainPlot(p['Eff'])
    p['Eff'].setColor(R.kBlue)
    RT.addBinWidth(canvas.firstPlot)
    canvas.firstPlot.SetMinimum(0.)
    canvas.firstPlot.SetMaximum(1.)
    canvas.cleanup('pdfs/SVFE_{}Eff{}_{}HTo2XTo{}_{}.pdf'.format(
        quantity, CUTSTRING, 'Trig-' if TRIGGER else '', fs,
        'Global' if SP is None else SPStr(SP)))
def makeResPlot(fs, sp):
    if sp is None:
        h = HG.getAddedSignalHistograms(FILES[fs], fs,
                                        ['pTRes-' + MUON for MUON in MUONS])
        prettyFS = '2#mu' if '2Mu' in fs else '4#mu'
        lumi = 'H#rightarrow2X#rightarrow{}, all samples combined{}'.format(
            prettyFS, ' + trigger' if ARGS.TRIGGER else '')
    else:
        h = {}
        for MUON in MUONS:
            h['pTRes-' + MUON] = HG.getHistogram(FILES[fs], (fs, sp),
                                                 'pTRes-' + MUON).Clone()
        prettyFS = '2#mu' if '2Mu' in fs else '4#mu'
        lumi = 'H#rightarrow2X#rightarrow{} ({} GeV, {} GeV, {} mm){}'.format(
            prettyFS, sp[0], sp[1], sp[2],
            ' + trigger' if ARGS.TRIGGER else '')

    c = Plotter.Canvas(lumi=lumi, cWidth=600 if ARGS.SQUARE else 800)
    pretty = {'DSA': {'col': R.kBlue}, 'RSA': {'col': R.kRed}}
    p = {}
    for MUON in MUONS:
        h['pTRes-' + MUON].Scale(
            1. /
            h['pTRes-' + MUON].Integral(0, h['pTRes-' + MUON].GetNbinsX() + 1))
        #h['pTRes-'+MUON].Rebin(10)
        p[MUON] = Plotter.Plot(h['pTRes-' + MUON], MUON, 'l', 'hist')
        c.addMainPlot(p[MUON])
        p[MUON].setColor(pretty[MUON]['col'], which='LM')

    c.makeLegend(lWidth=0.125, pos='tr')
    c.legend.resizeHeight()

    c.setMaximum()
    c.firstPlot.setTitles(X='', Y='', copy=h['pTRes-DSA'])
    RT.addBinWidth(c.firstPlot)
    if ARGS.SQUARE:
        c.firstPlot.scaleTitleOffsets(1.1, 'X')
        c.firstPlot.scaleTitleOffsets(1.3, 'Y')

    c.cleanup('pdfs/PTRES{}_{}_{}.pdf'.format(
        '_Trig' if ARGS.TRIGGER else '', fs,
        'Global' if sp is None else SPStr(sp)),
              mode='LUMI')
Пример #15
0
def getBackgroundHistograms(FILE, keylist, stack=True, addFlows=True, rebin=None, rebinVeto=None, extraScale=None):
    # allow passing a string or a list
    if type(keylist) == str:
        keylist = [keylist]

    # loop through the keys
    # if stack, make a THStack; otherwise, get started by using the first histogram
    # loop through the bg keys, addFlows if desired, scale, rebin if desired
    # if stack, Add
    # if not stack and this isn't the first, also Add
    # if not stack and this is the first, clone ("get started")
    # return dictionary of dictionary of histograms, and plot configs
    HISTS = {}
    PConfig = {}
    for key in keylist:
        HISTS[key] = {}
        PConfig[key] = {'stack':('', '', 'hist')}
        if stack:
            HISTS[key]['stack'] = R.THStack('hStack', '')
        for ref in BGORDER:
            HISTS[key][ref] = getHistogram(FILE, ref, key).Clone()
            if addFlows:
                RT.addFlows(HISTS[key][ref])
            HISTS[key][ref].Scale(PLOTCONFIG[ref]['WEIGHT'])
            if extraScale is not None:
                HISTS[key][ref].Scale(extraScale)
            if rebin is not None and (rebinVeto is None or (rebinVeto is not None and not rebinVeto(key))):
                is2D = 'TH2' in str(HISTS[key][ref].__class__)
                if is2D:
                    if not hasattr(rebin, '__iter__'):
                        print '[HISTOGRAMGETTER ERROR]: For 2D plots, "rebin" must be a list of 2 rebin values'
                        exit()
                    HISTS[key][ref].Rebin2D(*rebin)
                else:
                    HISTS[key][ref].Rebin(rebin)
            PConfig[key][ref] = (PLOTCONFIG[ref]['LATEX'], 'f', 'hist')
            if not stack and ref == BGORDER[0]:
                HISTS[key]['stack'] = HISTS[key][ref].Clone()
                continue
            HISTS[key]['stack'].Add(HISTS[key][ref])

    return HISTS, PConfig
def makePerSamplePlots():
    for ref in HISTS:
        if not type(ref) == tuple: continue
        for key in HISTS[ref]:
            if 'deltaRGR' in key: continue
            if 'VS' in key: continue
            if type(ref) == tuple:
                if ref[0] == '4Mu':
                    name = 'HTo2XTo4Mu_'
                    latexFS = '4#mu'
                elif ref[0] == '2Mu2J':
                    name = 'HTo2XTo2Mu2J_'
                    latexFS = '2#mu2j'
                if TRIGGER:
                    name = 'Trig-' + name
                name += SPStr(ref[1])
                lumi = SPLumiStr(ref[0], *ref[1])
                legName = HistogramGetter.PLOTCONFIG['HTo2XTo' +
                                                     ref[0]]['LATEX']
            else:
                if '_Matched' in key: continue
                name = ref
                lumi = HistogramGetter.PLOTCONFIG[ref]['LATEX']
                legName = HistogramGetter.PLOTCONFIG[ref]['LATEX']

            h = HISTS[ref][key].Clone()
            RT.addFlows(h)
            if h.GetNbinsX() > 100: h.Rebin(10)
            p = Plotter.Plot(h, legName, 'l', 'hist')
            fname = 'pdfs/{}{}_{}.pdf'.format(key, CUTSTRING, name)

            canvas = Plotter.Canvas(lumi=lumi)
            canvas.addMainPlot(p)
            canvas.makeLegend(lWidth=.25, pos='tr')
            canvas.legend.moveLegend(Y=-.3)
            canvas.legend.resizeHeight()
            p.SetLineColor(R.kBlue)
            RT.addBinWidth(p)

            pave = canvas.makeStatsBox(p, color=R.kBlue)
            canvas.cleanup(fname)
Пример #17
0
def makeBinnedResPlotBinwise(MUONS, outputTag, quantity, q2, fs, sp):
    defaultColorOrder = (R.kRed, R.kBlue, R.kGreen, R.kMagenta)
    h = {}
    for MUON in MUONS:
        h[MUON] = HistogramGetter.getHistogram(f, (fs, sp), '{M}_{Q}ResVS{Q2}'.format(M=MUON, Q=quantity, Q2=q2)).Clone()

    # leaving space for the bin number
    fname = 'pdfs/SRR_{}_{}_{}-Binned-Bin-{{}}_{}HTo2XTo{}_{}.pdf'.format(outputTag, quantity+'Res', q2, 'Trig-' if TRIGGER else '', fs, SPStr(sp))

    pretty, binranges, values, colors, colors2, legName = getBinningValues(q2)

    for i, key in enumerate(binranges):
        canvas = Plotter.Canvas(lumi=SPLumiStr(fs, *sp))
        projections, plots = {}, {}
        for j, MUON in enumerate(MUONS):
            projections[MUON] = h[MUON].ProjectionY('_'+str(i)+'_'+str(j), key[0], key[1])
            plots[MUON]       = Plotter.Plot(projections[MUON], MUON, 'l', 'hist')
            RT.addFlows(plots[MUON])
            plots[MUON].Rebin(10)
            if plots[MUON].Integral() != 0:
                plots[MUON].Scale(1./plots[MUON].Integral())
            plots[MUON].SetLineColor(defaultColorOrder[j])

            canvas.addMainPlot(plots[MUON])

        canvas.makeLegend(lWidth=.25, pos='tr')
        canvas.legend.resizeHeight()
        canvas.setMaximum(recompute=True)

        canvas.drawText(legName.format(Q2=pretty, V1=values[key][0], V2=values[key][1]), (canvas.legend.GetX1NDC()+.01, canvas.legend.GetY1NDC()-.04))

        for j, MUON in enumerate(MUONS):
            plots[MUON].SetLineColor(defaultColorOrder[j])
            plots[MUON].setTitles(X=plots[MUON].GetXaxis().GetTitle(), Y='Normalized Counts')
            canvas.drawText('#color[{}]{{'.format(defaultColorOrder[j]) + 'RMS = {:.4f}'.format(plots[MUON].GetStdDev()) + '}',
                (canvas.legend.GetX1NDC()+.01, canvas.legend.GetY1NDC()-(j*0.04)-.08)
            )

        RT.addBinWidth(canvas.firstPlot)
        canvas.cleanup(fname.format(i+1))
def makePerSamplePlots():
    for ref in HISTS:
        for key in HISTS[ref]:
            if type(ref) == tuple:
                if ref[0] == '4Mu': name = 'HTo2XTo4Mu_'
                elif ref[0] == '2Mu2J': name = 'HTo2XTo2Mu2J_'
                name += SPStr(ref[1])
                if TRIGGER:
                    name = 'Trig-' + name
                lumi = SPLumiStr(ref[0], *ref[1])
                legName = HistogramGetter.PLOTCONFIG['HTo2XTo' +
                                                     ref[0]]['LATEX']
            else:
                name = ref
                lumi = HistogramGetter.PLOTCONFIG[ref]['LATEX']
                legName = HistogramGetter.PLOTCONFIG[ref]['LATEX']

            h = HISTS[ref][key].Clone()
            RT.addFlows(h)
            p = Plotter.Plot(h, legName, 'l', 'hist')
            fname = 'pdfs/NM1_{}_{}.pdf'.format(key, name)
            canvas = Plotter.Canvas(lumi=lumi)
            canvas.lumi += ' : |#Delta#Phi| ' + ('<' if '_Less' in key else
                                                 '>') + ' #pi/2'
            canvas.addMainPlot(p)
            canvas.makeLegend(lWidth=.25, pos='tr')
            canvas.legend.moveLegend(Y=-.3)
            canvas.legend.resizeHeight()
            p.SetLineColor(R.kBlue)
            RT.addBinWidth(p)

            cutKey = key.replace('_Less', '').replace('_More', '')
            cutVal = Selections.CUTS[cutKey].val

            l = R.TLine(cutVal, p.GetMinimum(), cutVal, p.GetMaximum() * 1.05)
            l.SetLineStyle(2)
            l.SetLineWidth(2)
            l.Draw()

            canvas.cleanup(fname)
def makeRatioPlots(quantity, LxyRange):
    legDict = {'Less': '<  #pi/4', 'More': '> 3#pi/4'}
    hkeys = {
        key: 'h{}{}{}'.format(key, quantity, LxyRange)
        for key in ('Less', 'More')
    }

    a = HISTS[hkeys['Less']]['stack'].GetStack().Last().Clone()
    den = HISTS[hkeys['More']]['stack'].GetStack().Last().Clone()
    a.Rebin(2), den.Rebin(2)
    a.Divide(den)
    d = DHists[hkeys['Less']].Clone()
    den = DHists[hkeys['More']].Clone()
    d.Rebin(2), den.Rebin(2)
    d.Divide(den)

    PLOTS = {'': Plotter.Plot(a, '  MC SR/CR', 'lp', 'hist p')}
    DPLOTS = {'': Plotter.Plot(d, 'Data SR/CR', 'lp', 'hist p')}

    canvas = Plotter.Canvas(lumi='36.3 fb^{-1} (13 TeV)', logy=False)

    colors = {'': R.kBlue}
    canvas.addMainPlot(PLOTS[''])
    canvas.addMainPlot(DPLOTS[''])

    PLOTS[''].setColor(R.kBlue)
    DPLOTS[''].setColor(R.kBlack)

    canvas.firstPlot.setTitles(X='', copy=DHists[hkeys['Less']])
    canvas.firstPlot.setTitles(Y='Event Yield')
    canvas.makeLegend(lWidth=.3, pos='tr')
    canvas.legend.resizeHeight()
    RT.addBinWidth(canvas.firstPlot)

    canvas.firstPlot.SetMaximum(2.)
    canvas.firstPlot.SetMinimum(-1.)

    canvas.cleanup('pdfs/Ratio_{}_{}.pdf'.format(
        keyList[hkeys['Less']], 'Lin' if not canvas.logy else 'Log'))
Пример #20
0
def getDataHistograms(FILE, keylist, addFlows=True, rebin=None, rebinVeto=None):
    # allow passing a string or a list
    if type(keylist) == str:
        keylist = [keylist]

    DataKeys = ['DoubleMuonRun2016{}-07Aug17{}'.format(era, '' if era != 'B' else '-v2') for era in ('B', 'C', 'D', 'E', 'F', 'G', 'H')]

    # loop through the keys
    # if stack, make a THStack; otherwise, get started by using the first histogram
    # loop through the bg keys, addFlows if desired, scale, rebin if desired
    # if stack, Add
    # if not stack and this isn't the first, also Add
    # if not stack and this is the first, clone ("get started")
    # return dictionary of dictionary of histograms, and plot configs
    HISTS = {}
    PConfig = {}
    for key in keylist:
        HISTS[key] = {}
        PConfig[key] = {'data':('DoubleMuon2016', 'pe', 'pe')}
        for ref in DataKeys:
            HISTS[key][ref] = getHistogram(FILE, ref, key).Clone()
            if addFlows:
                RT.addFlows(HISTS[key][ref])
            if rebin is not None and (rebinVeto is None or (rebinVeto is not None and not rebinVeto(key))):
                is2D = 'TH2' in str(HISTS[key][ref].__class__)
                if is2D:
                    if not hasattr(rebin, '__iter__'):
                        print '[HISTOGRAMGETTER ERROR]: For 2D plots, "rebin" must be a list of 2 rebin values'
                        exit()
                    HISTS[key][ref].Rebin2D(*rebin)
                else:
                    HISTS[key][ref].Rebin(rebin)
            if ref == DataKeys[0]:
                HISTS[key]['data'] = HISTS[key][ref].Clone()
                continue
            HISTS[key]['data'].Add(HISTS[key][ref])

    return HISTS, PConfig
def makeRepEffectPlots(hkey):
    HISTS, PConfig = HG.getBackgroundHistograms(FILES['MC'], hkey)
    HISTS = HISTS[hkey]
    PConfig = PConfig[hkey]

    PLOTS = {}
    for key in HG.BGORDER + ('stack', ):
        PLOTS[key] = Plotter.Plot(HISTS[key], *PConfig[key])

    canvas = Plotter.Canvas(
        lumi='MC Background, {} PAT association (36.3 fb^{{-1}})'.format(
            hkey.replace('LxySig-', '').replace('Lxy-', '')),
        logy=True,
        cWidth=600 if ARGS.SQUARE else 800)

    for key in HG.BGORDER:
        PLOTS[key].setColor(HG.PLOTCONFIG[key]['COLOR'], which='LF')

    canvas.addMainPlot(PLOTS['stack'])

    canvas.firstPlot.setTitles(X='', copy=PLOTS[HG.BGORDER[0]])
    canvas.firstPlot.setTitles(Y='Event Yield')
    canvas.makeLegend(lWidth=.3, pos='tr', autoOrder=False, fontscale=0.8)
    for ref in reversed(HG.BGORDER):
        canvas.addLegendEntry(PLOTS[ref])
    canvas.legend.resizeHeight()
    RT.addBinWidth(canvas.firstPlot)

    canvas.firstPlot.SetMaximum(10.**7.)
    canvas.firstPlot.SetMinimum(10.**0.)

    if ARGS.SQUARE:
        canvas.firstPlot.scaleTitleOffsets(1.1, 'X')

    z = PLOTS['stack'].plot.GetStack().Last()
    print 'MC', hkey, z.Integral(0, z.GetNbinsX() + 1)
    canvas.cleanup('pdfs/REPEFF_MC_{}.pdf'.format(hkey), mode='LUMI')
Пример #22
0
    def makeSimplePlots(quantity, fs, SP=None, normalize=False):
        range_limits = {
                'pT': [0., 300.],
                'eta': None,
                'phi': None,
                'd0': None,
                'Lxy': [0., (500. if SP is None else \
                        SAMPLE_SPECS[fs]['{}_{}_{}'.format(*SP)]['xmax'])],
                'deltaR': None,
                'mass': None,
                'cosAlpha': None,
                'dimuonPTOverM': [0, 10],
                'XBeta': None,
        }

        HKeys = {
            'GEN_Den' : 'GEN_{}Den',
            'DSA_Den' : 'DSA_{}Den',
            'RSA_Den' : 'RSA_{}Den',
        }
        for key in HKeys:
            HKeys[key] = HKeys[key].format(quantity, 'HTo2XTo'+fs)

        h = {}
        p = {}

        if SP is None:
            for i, sp in enumerate(SIGNALPOINTS):
                if i == 0:
                    for key in HKeys:
                        h[key] = HISTS[(fs, sp)][HKeys[key]].Clone()
                        h[key].Sumw2()
                        h[key].SetDirectory(0)
                else:
                    for key in HKeys:
                        h[key].Sumw2()
                        h[key].Add(HISTS[(fs, sp)][HKeys[key]])

        else:
            for key in HKeys:
                h[key] = HISTS[(fs, SP)][HKeys[key]].Clone()
                h[key].Sumw2()
                if normalize is True and h[key].Integral() != 0:
                    h[key].Scale(1/h[key].Integral())
                h[key].SetDirectory(0)

        for key in HKeys:
            RT.addFlows(h[key])
            nConcatBins = 20 if SP is None else \
                    SAMPLE_SPECS[fs]['{}_{}_{}'.format(*SP)]['rebin']
            h[key].Rebin(nConcatBins)
        
        if quantity == 'deltaR':
            ratio_cut = 0.5
            hist_ratios = {}
            for key in HKeys:
                num_before_cut = 0
                num_after_cut = 0
                for i in range(h[key].GetNbinsX()+1):
                    if h[key].GetXaxis().GetBinCenter(i) < ratio_cut:
                        num_before_cut += h[key].GetBinContent(i)
                    else:
                        num_after_cut += h[key].GetBinContent(i)

                if num_before_cut+num_after_cut != 0:
                    hist_ratios[key] = 1.0*num_before_cut/(num_before_cut+num_after_cut)
                else:
                    hist_ratios[key] = -1

        HistSpecs = (
            ('GEN_Den', 'GEN', R.kGreen, 'Yield [a.u.]'),
            ('DSA_Den', 'DSA', R.kBlue, 'Yield [a.u.]'),
            ('RSA_Den', 'RSA', R.kRed, 'Yield [a.u.]'),
        )

        for key, leg, col, yTitle in HistSpecs:
            if range_limits[quantity] is not None:
                h[key].GetXaxis().SetRangeUser(
                        range_limits[quantity][0],
                        range_limits[quantity][1])
            
            h[key].SetNameTitle('h_'+key,
                    ';'+h[key].GetXaxis().GetTitle() + '; ' + \
                    ('Normalized ' if normalize is True else '') + yTitle)
            # leg += (': yield(#Delta R<0.5) #times 100 / (total yield) = {}'.format(
            #     round(hist_ratios[key]*100,2)) if quantity == 'deltaR' else '')
            p[key] = Plotter.Plot(h[key], leg, '', 'hist e1 x0')
            
        FIRST = (0, 3)
        CHARGE = ''
        for SECTION in (FIRST,):
            fraction_str = '' if SP is None else '[{}%, {}%]'.format(
                    round(SAMPLE_SPECS[fs]['{}_{}_{}'.format(*SP)]['fractions'][0], 1),
                    round(SAMPLE_SPECS[fs]['{}_{}_{}'.format(*SP)]['fractions'][1], 1))

            canvas = Plotter.Canvas(lumi = fs if SP is None else \
                    '{} ({} GeV, {} GeV, {} mm) ' \
                    '#scale[0.7]{{{fraction_str}}}'.format(
                        fs, *SP, fraction_str=fraction_str))

            for i in range(SECTION[0], SECTION[1]):
                key = HistSpecs[i][0]
                col = HistSpecs[i][2]
                yTitle = HistSpecs[i][3]
                canvas.addMainPlot(p[key])
                p[key].SetMarkerColor(col)
                p[key].SetLineColor(col)
                # p[key].firstPlot.SetYTitle(yTitle)

            canvas.makeLegend(pos='tl')
            canvas.legend.moveLegend(X=0.15)
            canvas.legend.resizeHeight()
            RT.addBinWidth(canvas.firstPlot)

            canvas.cleanup(OUTPUT_PATH + FILENAME_OUT.format('STD', LXYMIN, LXYMAX, quantity, fs, 'Global' if SP is None else SPStr(SP)))
def makeResPlots(metric, quantity, sp=None):
    PRETTY = {
        'pTRes_hits_less': {
            'mnice': 'p_{T} res.',
            'qnice': 'N(hits)',
            'leg': 'N(hits) #leq 12',
            'col': R.kRed
        },
        'pTRes_hits_more': {
            'mnice': 'p_{T} res.',
            'qnice': 'N(hits)',
            'leg': 'N(hits) > 12',
            'col': R.kBlue
        },
        'pTRes_fpte_less': {
            'mnice': 'p_{T} res.',
            'qnice': '#sigma_{p_{T}}/p_{T}',
            'leg': '#sigma_{p_{T}}/p_{T} < 1',
            'col': R.kBlue
        },
        'pTRes_fpte_more': {
            'mnice': 'p_{T} res.',
            'qnice': '#sigma_{p_{T}}/p_{T}',
            'leg': '#sigma_{p_{T}}/p_{T} #geq 1',
            'col': R.kRed
        },
        'qdiff_hits_less': {
            'mnice': 'charge diff.',
            'qnice': 'N(hits)',
            'leg': 'N(hits) #leq 12',
            'col': R.kRed
        },
        'qdiff_hits_more': {
            'mnice': 'charge diff.',
            'qnice': 'N(hits)',
            'leg': 'N(hits) > 12',
            'col': R.kBlue
        },
        'qdiff_fpte_less': {
            'mnice': 'charge diff.',
            'qnice': '#sigma_{p_{T}}/p_{T}',
            'leg': '#sigma_{p_{T}}/p_{T} < 1',
            'col': R.kBlue
        },
        'qdiff_fpte_more': {
            'mnice': 'charge diff.',
            'qnice': '#sigma_{p_{T}}/p_{T}',
            'leg': '#sigma_{p_{T}}/p_{T} #geq 1',
            'col': R.kRed
        },
    }
    witches = ('less', 'more') if quantity == 'fpte' else ('more', 'less')
    hkeys = ['{}_{}_{}'.format(metric, quantity, which) for which in witches]

    if sp is None:
        HISTS = HG.getAddedSignalHistograms(FILES['Signal'], '2Mu2J', hkeys)
    else:
        HISTS = {}
        for key in hkeys:
            HISTS[key] = HG.getHistogram(FILES['Signal'], ('2Mu2J', sp),
                                         key).Clone()

    PLOTS = {}
    for key in hkeys:
        HISTS[key].Scale(1. /
                         HISTS[key].Integral(0, HISTS[key].GetNbinsX() + 1))
        #RT.addFlows(HISTS[key])
        PLOTS[key] = Plotter.Plot(HISTS[key], PRETTY[key]['leg'], 'l', 'hist')

    #canvas = Plotter.Canvas(lumi='{} by {}'.format(PRETTY[hkeys[0]]['mnice'], PRETTY[hkeys[0]]['qnice']))
    lumi = 'H#rightarrow2X#rightarrow2#mu'
    if sp is None:
        lumi += ', all samples combined'
    else:
        lumi += ' ({} GeV, {} GeV, {} mm)'.format(*sp)
    canvas = Plotter.Canvas(lumi=lumi, cWidth=600 if ARGS.SQUARE else 800)

    for key in hkeys:
        canvas.addMainPlot(PLOTS[key])
        PLOTS[key].setColor(PRETTY[key]['col'], which='L')

    canvas.firstPlot.SetMinimum(0.)
    canvas.setMaximum()
    if metric == 'qdiff':
        canvas.firstPlot.SetMaximum(1.)

    canvas.firstPlot.setTitles(Y='Density')
    if 'qdiff' in hkeys[0]:
        canvas.firstPlot.SetNdivisions(3)

    canvas.makeLegend(lWidth=0.27, pos='tr')
    canvas.legend.resizeHeight()

    RT.addBinWidth(canvas.firstPlot)

    if ARGS.SQUARE:
        canvas.firstPlot.scaleTitleOffsets(1.1, 'X')
        if metric == 'pTRes':
            canvas.firstPlot.scaleTitleOffsets(1.3, 'Y')
    canvas.cleanup('pdfs/QCUTRES_Sig_{}_{}_{}.pdf'.format(
        metric, quantity, 'Global' if sp is None else SPStr(sp)),
                   mode='LUMI')
def makeStackPlots(DataMC=False, logy=False):
    BGORDER = ('WJets', 'WW', 'WZ', 'ZZ', 'tW', 'tbarW', 'ttbar',
               'QCD20toInf-ME', 'DY10to50', 'DY50toInf')
    for hkey in HISTS['DY50toInf']:
        if 'Matched' in hkey: continue
        if 'VS' in hkey: continue

        h = {}
        if not MCONLY:
            h['Data'] = HISTS['DoubleMuonRun2016B-07Aug17-v2'][hkey].Clone()
        if True:
            #           h      ['Signal'] = HISTS[('4Mu', (125, 20, 13))         ][hkey].Clone()
            h['BG'] = R.THStack('hBG', '')

        PConfig = {}
        if not MCONLY:
            PConfig['Data'] = ('DoubleMuon2016', 'pe', 'pe')
        if True:
            #           PConfig['Signal'] = ('H#rightarrow2X#rightarrow4#mu', 'l' , 'hist')
            PConfig['BG'] = ('', '', 'hist')

        PC = HistogramGetter.PLOTCONFIG

        for key in BGORDER:
            h[key] = HISTS[key][hkey].Clone()
            RT.addFlows(h[key])
            if h[key].GetNbinsX() > 100: h[key].Rebin(10)
            h[key].Scale(PC[key]['WEIGHT'])
            PConfig[key] = (PC[key]['LATEX'], 'f', 'hist')
            h['BG'].Add(h[key])

        if not MCONLY:
            for era in ('C', 'D', 'E', 'F', 'G', 'H'):
                h['Data'].Add(
                    HISTS['DoubleMuonRun2016{}-07Aug17'.format(era)][hkey])
            RT.addFlows(h['Data'])
            if h['Data'].GetNbinsX() > 100: h['Data'].Rebin(10)

        p = {}
        for key in h:
            p[key] = Plotter.Plot(h[key], *PConfig[key])

        fname = 'pdfs/{}{}_Stack{}{}{}.pdf'.format(hkey, CUTSTRING,
                                                   'MC' if MCONLY else '',
                                                   '-Log' if logy else '',
                                                   '-Rat' if DataMC else '')

        for key in BGORDER:
            p[key].setColor(PC[key]['COLOR'], which='LF')

        canvas = Plotter.Canvas(ratioFactor=0. if not DataMC else 1. / 3.,
                                logy=logy,
                                fontscale=1. if not DataMC else 1. + 1. / 3.)
        if True:
            canvas.addMainPlot(p['BG'])
        if not MCONLY:
            canvas.addMainPlot(p['Data'])
#       canvas.addMainPlot(p['Signal'])

        canvas.makeLegend(lWidth=.27,
                          pos='tr',
                          autoOrder=False,
                          fontscale=0.8 if not DataMC else 1.)
        if not MCONLY:
            canvas.addLegendEntry(p['Data'])
        for key in reversed(BGORDER):
            canvas.addLegendEntry(p[key])
#       canvas.addLegendEntry(p['Signal'])
        canvas.legend.resizeHeight()

        p['BG'].setTitles(X=p['WJets'].GetXaxis().GetTitle(),
                          Y='Normalized Counts')
        RT.addBinWidth(p['BG'])

        canvas.firstPlot.SetMaximum(h['BG'].GetStack().Last().GetMaximum() *
                                    1.05)
        #canvas.firstPlot.SetMaximum(1.e-4)
        if logy:
            canvas.firstPlot.SetMinimum(1.)

        if DataMC:
            canvas.makeRatioPlot(p['Data'].plot,
                                 p['BG'].plot.GetStack().Last())
            canvas.firstPlot.scaleTitleOffsets(0.8, axes='Y')
            canvas.rat.scaleTitleOffsets(0.8, axes='Y')

#       p['Signal'    ].SetLineStyle(2)
#       p['Signal'    ].SetLineColor(R.kRed)

        canvas.finishCanvas(extrascale=1. if not DataMC else 1. + 1. / 3.)
        canvas.save(fname)
        canvas.deleteCanvas()
Пример #25
0
def makeOverlaidResPlot(MUONS, fs, sp, quantity, outputTag=None):
    # whether the plot is dif or res makes a difference wrt binning, fit range, and stats box positions
    # only pT is a res type; the others are all dif types
    ISDIF = quantity != 'pT'

    # what to name the plot. if MUONS is length 1, no sense to pass it twice, so get it automatically
    if outputTag is None:
        outputTag = MUONS[0]

    # colors, in order of MUONS, and also hashed
    defaultColorOrder = (R.kBlue, R.kRed, R.kGreen)
    colorDict = dict(zip(MUONS, defaultColorOrder))

    # get histograms and define plots
    h = {}
    for MUON in MUONS:
        h[MUON] = HistogramGetter.getHistogram(f, (fs, sp), MUON+'_'+quantity+'Res').Clone()
    p = {}
    for MUON in MUONS:
        RT.addFlows(h[MUON])
        if not ISDIF:
            h[MUON].Rebin(5)
        else:
            h[MUON].Rebin(10)
        p[MUON] = Plotter.Plot(h[MUON], 'Signal MC ({})'.format(MUON[:3]), 'l', 'hist')

    # define and fit gaussians to everything. Set FITRANGE to be something useful.
    funcs = {}
    fplots = {}
    for MUON in MUONS:
        if quantity == 'pT':
            FITRANGE = (-0.4, 0.3)
        elif quantity == 'eta':
            FITRANGE = (-0.1, 0.1)
        else:
            FITRANGE = (-20., 20.)
        funcs[MUON] = R.TF1('f'+MUON, 'gaus', *FITRANGE)
        h[MUON].Fit('f'+MUON, 'R')
        fplots[MUON] = Plotter.Plot(funcs[MUON], 'Gaussian fit ({})'.format(MUON[:3]), 'l', '')

    # define canvas, add plots. addS is so that statsbox will be drawn later.
    # these all should be pretty obvious until...
    canvas = Plotter.Canvas(lumi=SPLumiStr(fs, *sp))
    for i, MUON in enumerate(MUONS):
        canvas.addMainPlot(p[MUON], addS=True if i!=0 else False)
        canvas.addMainPlot(fplots[MUON])

    if len(MUONS) > 1:
        canvas.firstPlot.setTitles(X=canvas.firstPlot.GetXaxis().GetTitle().replace(MUONS[0],'Reco'))

    canvas.makeLegend(lWidth=.25, pos='tl')
    canvas.legend.resizeHeight()

    for MUON in MUONS:
        p     [MUON].SetLineColor(colorDict[MUON]  )
        fplots[MUON].SetLineColor(colorDict[MUON]+1)

    RT.addBinWidth(canvas.firstPlot)

    # dif type: fit boxes go down the left side
    # res type: fit boxes go down the middle
    # stats boxes are on the right
    paves = []
    for i, MUON in enumerate(MUONS):
        paves.append(canvas.makeStatsBox(p[MUON], color=colorDict[MUON]))
        Plotter.MOVE_OBJECT(paves[-1], Y=-.2*i)

        if not ISDIF:
            canvas.setFitBoxStyle(h[MUON], lWidth=0.275, pos='tr')
        else:
            canvas.setFitBoxStyle(h[MUON], lWidth=0.275, pos='tl')

        sbox = p[MUON].FindObject('stats')
        sbox.SetTextColor(colorDict[MUON]+1)

        if not ISDIF:
            Plotter.MOVE_OBJECT(sbox, Y=-.15*i, X=-.18, NDC=True)
        else:
            Plotter.MOVE_OBJECT(sbox, Y=-.15*i-0.04*4.1, NDC=True)

    fname = 'pdfs/SRR_{}_{}_{}HTo2XTo{}_{}.pdf'.format(outputTag, quantity+'Res', 'Trig-' if TRIGGER else '', fs, SPStr(sp))
    canvas.cleanup(fname)
Пример #26
0
def importHistograms(DISTRIBUTION_SPECS):
    """
    Read and add specified histograms from one or many files.

    Extracts histograms from one or many ROOT files (defined via the argument
    'DISTRIBUTION_SPECS') and adds them to the given HistSpecs objects.

    Parameters
    ----------
    DISTRIBUTION_SPECS : HistSpecs object
        An instance of the HistSpecs class, which defines all the relevant histogram
        properties

    """

    # perform some basic sanity checks
    for el in DISTRIBUTION_SPECS:
        filepath = el.getAttribute("filepath")
        histname_identifier = el.getAttribute("histname_identifier")
        histname_exclude = el.getAttribute("histname_exclude")

        types = ((filepath, str), (histname_identifier, str),
                 (histname_exclude, list))
        for o, t in types:
            if not isinstance(o, t):
                raise Exception(
                    "Invalid type of {}: should be {}, but is {}".format(
                        o, t, type(o)))

        if not os.path.exists(filepath):
            raise Exception("No such file: {}".format(filepath))

    # dictionary structure for collecting the relevant distributions
    hists = {}

    cnt_files = 1
    for el in DISTRIBUTION_SPECS:
        filepath = el.getAttribute("filepath")
        histname_identifier = el.getAttribute("histname_identifier")
        histname_exclude = el.getAttribute("histname_exclude")

        print("[{}/{}] Reading file {}...".format(cnt_files,
                                                  len(DISTRIBUTION_SPECS),
                                                  filepath))

        f_allhists = HistogramGetter.getHistograms(filepath)

        histogram = None

        for dataset in f_allhists:
            selected_hists_names = getHistNames(f_allhists,
                                                dataset,
                                                histname_identifier,
                                                exclude=histname_exclude)
            print("hist names: {}".format(selected_hists_names))

            if len(selected_hists_names) > 1:
                raise Exception(
                    "Ambiguous histogram identifier: {} would select the following {} histograms: {}"
                    .format(histname_identifier, len(selected_hists_names),
                            '\n'.join(selected_hists_names)))

            for key in selected_hists_names:
                if histogram is None:
                    histogram = f_allhists[dataset][key].Clone()
                else:
                    histogram.Add(f_allhists[dataset][key])

        if histogram:
            print("\tImported histogram {}".format(histogram.GetName()))
        else:
            print("\tNo histograms found.")

        # prepare the histogram
        RT.addFlows(histogram)

        if el.getAttribute("histogram") is not None:
            print(
                "Warning: Histogram already exists in the HistSpecs object and will be overwritten"
            )

        # add the actual histrogram to the corresponding HistSpecs object
        el.setAttribute("histogram", histogram)

        cnt_files += 1
        del f_allhists
Пример #27
0
def makeSimplePlots(PLOT_SPECS,
                    DISTRIBUTION_SPECS,
                    output_filename,
                    output_folder="pdfs/",
                    logy=False,
                    normalize=False,
                    make_legend=True):
    importHistograms(DISTRIBUTION_SPECS)

    canvas = Plotter.Canvas(logy=logy, lumi=PLOT_SPECS["lumi_str"])

    Xrange_min = None
    Xrange_max = None
    Yrange_min = None
    Yrange_max = None

    for el in DISTRIBUTION_SPECS:
        hist = el.getAttribute("histogram")
        leg = el.getAttribute("legend")
        if leg is None: leg = ''
        if normalize: leg += ' (normalized)'
        linecolor = el.getAttribute("linecolor")
        linestyle = el.getAttribute("linestyle")
        markercolor = el.getAttribute("markercolor")
        markerstyle = el.getAttribute("markerstyle")
        Xrange = el.getAttribute("Xrange")
        Yrange = el.getAttribute("Yrange")
        rebin = el.getAttribute("rebin")

        if Xrange is not None:
            # find the most inclusive x-axis ranges
            if Xrange_min is not None:
                Xrange_min = Xrange[0] if Xrange[0] < Xrange_min else Xrange_min
            else:
                Xrange_min = Xrange[0]

            if Xrange_max is not None:
                Xrange_max = Xrange[1] if Xrange[1] > Xrange_max else Xrange_max
            else:
                Xrange_max = Xrange[1]

        if Yrange is not None:
            # find the most inclusive y-axis ranges
            if Yrange_min is not None:
                Yrange_min = Yrange[0] if Yrange[0] < Yrange_min else Yrange_min
            else:
                Yrange_min = Yrange[0]

            if Yrange_max is not None:
                Yrange_max = Yrange[1] if Yrange[1] > Yrange_max else Yrange_max
            else:
                Yrange_max = Yrange[1]

        # rebin histograms, if applicable
        if rebin: hist.Rebin(rebin)

        # normalize histograms, if applicable
        if normalize and hist.Integral() != 0:
            hist.Scale(1. / hist.Integral())

        plot = Plotter.Plot(hist, leg, "l", "hist")
        canvas.addMainPlot(plot)

        if linecolor: plot.SetLineColor(linecolor)
        if linestyle: plot.SetLineStyle(linestyle)
        if markercolor: plot.SetMarkerColor(markercolor)
        if markerstyle: plot.SetMarkerStyle(markerstyle)
        RT.addBinWidth(plot)

    # set custom axis ranges if specified in DISTRIBUTION_SPECS
    if logy and Yrange_min <= 0.0: Yrange_min = 1e-3
    if Xrange:
        print('setting x ranges: {}, {}'.format(Xrange_min, Xrange_max))
        canvas.firstPlot.GetXaxis().SetRangeUser(Xrange_min, Xrange_max)
    if Yrange: canvas.firstPlot.GetYaxis().SetRangeUser(Yrange_min, Yrange_max)

    if make_legend:
        canvas.makeLegend(pos="tl", fontscale=0.77)
        canvas.legend.resizeHeight()

    fname = output_folder + "/" + output_filename
    if logy: fname += "_logy"
    if normalize: fname += "_norm"

    canvas.finishCanvas()
    canvas.save(fname, extList=[".pdf", ".root"])
    canvas.deleteCanvas()
Пример #28
0
    def makeEffPlots(quantity, fs, SP=None):
        range_limits = {
                'pT': [0., 300.],
                'eta': None,
                'phi': None,
                'd0': None,
                'Lxy': [0., (500. if SP is None else \
                        SAMPLE_SPECS[fs]['{}_{}_{}'.format(*SP)]['xmax'])],
                'deltaR': None,
                'mass': None,
                'cosAlpha': None,
                'dimuonPTOverM': [0, 10],
                'XBeta': None,
        }

        HKeys = {
            'GEN_Eff'       : 'GEN_{}Num'      ,
            'GEN_Den'       : 'GEN_{}Den'      ,
            'DSA_Eff'       : 'DSA_{}Num'      ,
            'DSA_Den'       : 'DSA_{}Den'      ,
            'RSA_Eff'       : 'RSA_{}Num'      ,
            'RSA_Den'       : 'RSA_{}Den'      ,
        }
        for key in HKeys:
            HKeys[key] = HKeys[key].format(quantity, 'HTo2XTo'+fs)

        h = {}
        p = {}
        g = {}
        hm = {}

        if SP is None:
            for i, sp in enumerate(SIGNALPOINTS):
                if i == 0:
                    for key in HKeys:
                        h[key] = HISTS[(fs, sp)][HKeys[key]].Clone()
                        h[key].SetDirectory(0)
                else:
                    for key in HKeys:
                        h[key].Add(HISTS[(fs, sp)][HKeys[key]])

        else:
            sp = SP
            for key in HKeys:
                h[key] = HISTS[(fs, sp)][HKeys[key]].Clone()
                h[key].SetDirectory(0)

        for key in HKeys:
            RT.addFlows(h[key])
            nConcatBins = 20 if SP is None else \
                    SAMPLE_SPECS[fs]['{}_{}_{}'.format(*SP)]['rebin']
            h[key].Rebin(nConcatBins)
            # h[key].Rebin(30)

        NumDens = (
            ('GEN_Eff'      , 'GEN_Den'          , 'GEN'       , R.kGreen   ),
            ('DSA_Eff'      , 'DSA_Den'          , 'DSA'       , R.kBlue    ),
            ('RSA_Eff'      , 'RSA_Den'          , 'RSA'       , R.kRed     ),
        )

        for num, den, leg, col in NumDens:
            g[num] = R.TGraphAsymmErrors(h[num], h[den], 'cp')
            g[num].SetNameTitle('g_'+num, ';'+h[num].GetXaxis().GetTitle()+'; Trigger Efficiency')
            # g[num].GetXaxis().SetRangeUser(0., 30.)
            if range_limits[quantity] is not None:
                g[num].GetXaxis().SetLimits(
                        range_limits[quantity][0],
                        range_limits[quantity][1])

            p[num] = Plotter.Plot(g[num], leg, 'elp', 'pe')

            h[num].Sumw2()
            h[den].Sumw2()

            ratio_hist = R.TEfficiency(h[num], h[den])
            eff_sum_num = 0
            eff_sum_den = 0
            for binx in range(1,h[num].GetXaxis().GetNbins()+2):
                # if h[num].GetBinLowEdge(binx) > 250: continue
                glob_bin = ratio_hist.GetGlobalBin(binx)
                efferror = max(ratio_hist.GetEfficiencyErrorLow(glob_bin),
                        ratio_hist.GetEfficiencyErrorUp(glob_bin))
                if efferror != 0:
                    eff_sum_num += ratio_hist.GetEfficiency(glob_bin) / \
                            (efferror*efferror)
                    if ratio_hist.GetEfficiency(glob_bin) != 0:
                        eff_sum_den += 1/(efferror*efferror)
            if eff_sum_den != 0:
                hm[num] = eff_sum_num / eff_sum_den


        FIRST  = (0, 3)
        # SECOND = (3, 5)
        CHARGE = ''
        for SECTION in (FIRST,):
            fraction_str = '' if SP is None else '[{}%, {}%]'.format(
                    round(SAMPLE_SPECS[fs]['{}_{}_{}'.format(*SP)]['fractions'][0], 1),
                    round(SAMPLE_SPECS[fs]['{}_{}_{}'.format(*SP)]['fractions'][1], 1))
            canvas = Plotter.Canvas(lumi = fs if SP is None else \
                    '{} ({} GeV, {} GeV, {} mm) ' \
                    '#scale[0.7]{{{fraction_str}}}'.format(
                        fs, *SP, fraction_str=fraction_str))
            for i in range(SECTION[0], SECTION[1]):
                key = NumDens[i][0]
                col = NumDens[i][3]
                canvas.addMainPlot(p[key])
                p[key].SetMarkerColor(col)
                p[key].SetLineColor(col)

                # if quantity in ['Lxy','pT']:
                #     axis_min = p[key].GetXaxis().GetBinLowEdge(1)
                #     axis_max = p[key].GetXaxis().GetBinLowEdge(p[key].GetXaxis().GetNbins()+1)
                #     hline = R.TLine(axis_min, hm[key], range_limits[quantity][1], hm[key])
                #     R.SetOwnership(hline, 0)
                #     hline.SetLineColor(col)
                #     hline.Draw()
                

            canvas.makeLegend(pos='tr')
            canvas.legend.moveLegend(X=-0.18)
            canvas.legend.resizeHeight()
            canvas.firstPlot.SetMinimum(0.)
            canvas.firstPlot.SetMaximum(1.)
            RT.addBinWidth(canvas.firstPlot)
            if quantity == 'pT':
                vline = R.TLine(28.,0.,28.,1.)  # draw vertical line at 28 GeV
                R.SetOwnership(vline, 0)
                vline.SetLineColor(15)
                vline.Draw()

            canvas.cleanup(OUTPUT_PATH + FILENAME_OUT.format('STE', LXYMIN, LXYMAX, quantity, fs, 'Global' if SP is None else SPStr(SP)))
def makeStackPlots(DataMC=False, logy=False):
    BGORDER = ('WJets', 'WW', 'WZ', 'ZZ', 'tW', 'tbarW', 'ttbar', 'DY10to50',
               'DY50toInf')
    for hkey in HISTS['DY50toInf']:

        h = {
            #           'Data'       : HISTS['DoubleMuonRun2016D-07Aug17'][hkey].Clone(),
            #           'Signal'     : HISTS[('4Mu', (125, 20, 13))      ][hkey].Clone(),
            'BG': R.THStack('hBG', '')
        }

        PConfig = {
            #           'Data'       : ('DoubleMuon2016D'              , 'pe', 'pe'  ),
            #           'Signal'     : ('H#rightarrow2X#rightarrow4#mu', 'l' , 'hist'),
            'BG': ('', '', 'hist'),
        }

        PC = HistogramGetter.PLOTCONFIG

        for key in BGORDER:
            h[key] = HISTS[key][hkey].Clone()
            RT.addFlows(h[key])
            if h[key].GetNbinsX() > 100: h[key].Rebin(10)
            h[key].Scale(PC[key]['WEIGHT'])
            PConfig[key] = (PC[key]['LATEX'], 'f', 'hist')
            h['BG'].Add(h[key])

        p = {}
        for key in h:
            p[key] = Plotter.Plot(h[key], *PConfig[key])

        fname = 'pdfs/NM1_{}_Stack{}.pdf'.format(hkey, '-Log' if logy else '')

        for key in BGORDER:
            p[key].setColor(PC[key]['COLOR'], which='LF')

        canvas = Plotter.Canvas(ratioFactor=0. if not DataMC else 1. / 3.,
                                cHeight=600 if not DataMC else 800,
                                logy=logy)
        canvas.addMainPlot(p['BG'])
        #       canvas.addMainPlot(p['Data'])
        #       canvas.addMainPlot(p['Signal'])

        canvas.lumi += ' : |#Delta#Phi| ' + ('<' if '_Less' in key else
                                             '>') + ' #pi/2'

        canvas.makeLegend(lWidth=.27, pos='tr', autoOrder=False, fontscale=0.8)
        #       canvas.addLegendEntry(p['Data'     ])
        for key in reversed(BGORDER):
            canvas.addLegendEntry(p[key])


#       canvas.addLegendEntry(p['Signal'])
        canvas.legend.resizeHeight()

        p['BG'].setTitles(X=p['WJets'].GetXaxis().GetTitle(),
                          Y='Normalized Counts')
        RT.addBinWidth(p['BG'])

        canvas.firstPlot.SetMaximum(h['BG'].GetStack().Last().GetMaximum() *
                                    1.05)
        #canvas.firstPlot.SetMaximum(1.e-4)

        #       if DataMC:
        #           canvas.makeRatioPlot(p['Data'].plot, p['BG'].plot.GetStack().Last())

        #       p['Signal'    ].SetLineStyle(2)
        #       p['Signal'    ].SetLineColor(R.kRed)

        canvas.cleanup(fname)
Пример #30
0
def compareFOMPlot(quantity, sp, sigmaBMode='GLOBAL'):
    keys = FACTORS
    for FACTOR in FACTORS:
        s = HG.getHistogram(FILES['Signal'], (fs, sp),
                            '{}_{}'.format(quantity, FACTOR)).Clone()

        if sigmaBMode == 'GLOBAL':
            s.Scale(ScaleFactor(sp, 1, 1.e-2))
            extra = 'GLOBAL'

        DHists, DPConfig = HG.getDataHistograms(FILES['Data'],
                                                '{}_1'.format(quantity),
                                                addFlows=False)
        b = DHists['{}_1'.format(quantity)]['data']

        # get cumulatives
        bCum = b.GetCumulative(CONFIG[quantity]['forward'])
        sCum = s.GetCumulative(CONFIG[quantity]['forward'])
        fom = {z: sCum.Clone() for z in ('ZBi', 'ZPL')}

        nBins = sCum.GetNbinsX()
        xAxis = sCum.GetXaxis()

        # dictionaries instead of numbers because we have 2 sets of ZBi curves
        fom_max = {z: 0. for z in ('ZBi', 'ZPL')}
        opt_cut = {z: 0. for z in ('ZBi', 'ZPL')}
        opt_s = {z: 0. for z in ('ZBi', 'ZPL')}
        opt_b = {z: 0. for z in ('ZBi', 'ZPL')}

        for ibin in range(1, nBins + 1):
            S, B, cutVal, FOMs = calculateFOM(s, b, sCum, bCum, nBins, ibin,
                                              xAxis,
                                              CONFIG[quantity]['forward'])
            for z in ('ZBi', 'ZPL'):
                if FOMs[z] > fom_max[z]:
                    fom_max[z] = FOMs[z]
                    opt_cut[z] = cutVal
                    opt_s[z] = S
                    opt_b[z] = B

                fom[z].SetBinContent(ibin, FOMs[z])

        p = {
            z: Plotter.Plot(fom[z], PRETTY_LEG[z], 'l', 'hist p')
            for z in fom
        }

        colors = {'ZBi': R.kRed, 'ZPL': R.kBlue}

        c = Plotter.Canvas(lumi='({} GeV, {} GeV, {} mm){}'.format(
            sp[0], sp[1], sp[2], '' if FACTOR ==
            1 else ' #rightarrow {} mm'.format(sp[2] / FACTOR)))
        for z in fom:
            c.addMainPlot(p[z])
            p[z].setColor(colors[z], which='LM')

        c.makeLegend(lWidth=0.1, pos='tr')
        #c.legend.SetMargin(0.1)
        c.legend.resizeHeight()

        lines = {
            z: R.TLine(opt_cut[z], 0., opt_cut[z],
                       max(fom_max.values()) * 1.1)
            for z in fom
        }
        for z in fom:
            lines[z].SetLineStyle(2)
            lines[z].SetLineColor(colors[z])
            lines[z].Draw()

        for i, z in enumerate(fom.keys()):
            c.drawText(text='#color[{:d}]{{opt = {:.1f}}}'.format(
                colors[z], opt_cut[z]),
                       pos=(c.legend.GetX2(),
                            c.legend.GetY1() - .04 - i * .04),
                       align='br')

        c.firstPlot.SetMinimum(0.)
        c.firstPlot.SetMaximum(max(fom_max.values()) * 1.1)
        c.firstPlot.setTitles(Y='Figure of Merit')
        RT.addBinWidth(c.firstPlot)

        c.cleanup('pdfs/COMPARE_FOM-{}_{}_{}_{}_{}_{}.pdf'.format(
            extra, quantity, sp[0], sp[1], sp[2], FACTOR))