Beispiel #1
0
def makeColorPlot(MUON, fs, quantity, sp=None, q2=None):
    if q2 is None:
        fstring = '{M}_{Q}VS{Q}'.format(M=MUON, Q=quantity)
    else:
        fstring = '{M}_{Q}ResVS{Q2}'.format(M=MUON, Q=quantity, Q2=q2)

    if sp is None:
        for i, SP in enumerate(SIGNALPOINTS):
            if i == 0:
                h = HistogramGetter.getHistogram(f, (fs, SP), fstring).Clone()
            else:
                h.Add(HistogramGetter.getHistogram(f, (fs, SP), fstring).Clone())
        fname = 'pdfs/SRR_{}_{}HTo2XTo{}_Global.pdf'.format(fstring, 'Trig-' if TRIGGER else '', fs)
    else:
        h = HistogramGetter.getHistogram(f, (fs, sp), fstring).Clone()
        fname = 'pdfs/SRR_{}_{}HTo2XTo{}_{}.pdf'.format(fstring, 'Trig-' if TRIGGER else '', fs, SPStr(sp))

    h.Rebin2D(10, 10)
    p = Plotter.Plot(h, '', '', 'colz')
    canvas = Plotter.Canvas(lumi=SPLumiStr(fs, *sp) if sp is not None else fs)
    canvas.mainPad.SetLogz(True)
    canvas.addMainPlot(p)
    canvas.scaleMargins(1.75, edges='R')
    canvas.scaleMargins(0.8, edges='L')
    canvas.cleanup(fname)
def makeIndividualPlots(obj, dtype, key):
    if type(key) == tuple:
        fs, sp = key
        lumi = SPLumiStr(fs, *sp)
        fname = 'pdfs/CutTable_{}-{}_{}HTo2XTo{}_{}.pdf'.format(obj, dtype, 'Trig-' if TRIGGER else '', fs, SPStr(sp))
    else:
        sample = key
        lumi = sample
        fname = 'pdfs/CutTable_{}-{}_{}.pdf'.format(obj, dtype, sample)

    p = Plotter.Plot(HISTS[obj][dtype][key], '', '', 'hist')
    canvas = Plotter.Canvas(lumi=lumi)
    canvas.addMainPlot(p)
    canvas.firstPlot.SetMaximum(1.)
    canvas.firstPlot.SetMinimum(0.)

    #canvas.firstPlot.SetMarkerColor(R.kBlue)
    #canvas.firstPlot.SetLineColor(R.kBlue)

    canvas.firstPlot.SetLineColor(4000)
    canvas.firstPlot.SetFillColor(R.kOrange)

    for ibin in xrange(1, p.GetNbinsX()+1):
        canvas.drawText(text='{:.2f}'.format(p.GetBinContent(ibin)), pos=(ibin-0.5, 0.1), align='cc', NDC=False)
    canvas.cleanup(fname)
Beispiel #3
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)
def makeColorPlots(key):
    for ref in HISTS:
        if not type(ref) == tuple: 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])
        else:
            name = ref
            lumi = HistogramGetter.PLOTCONFIG[ref]['LATEX']
            if '_Matched' in key: continue

        h = HISTS[ref][key].Clone()
        h.Rebin2D(10, 10)
        p = Plotter.Plot(h, '', '', 'colz')
        canvas = Plotter.Canvas(lumi=lumi)
        #canvas.mainPad.SetLogz(True)
        canvas.addMainPlot(p)
        canvas.scaleMargins(1.75, edges='R')
        canvas.scaleMargins(0.8, edges='L')

        fname = 'pdfs/{}{}_{}.pdf'.format(key, CUTSTRING, name)
        canvas.cleanup(fname)
def makeDSASignal2DPlots():
    for quantity in ('pT', 'eta', 'trkChi2'):

        hkey = 'DSA-12-' + quantity
        HISTS = HG.getAddedSignalHistograms(FILES[fs], fs, (hkey, ))
        if 'trkChi2' not in hkey: HISTS[hkey].Rebin2D(10, 10)
        for sp in SIGNALPOINTS:
            HISTS[sp] = HG.getHistogram(FILES[fs], (fs, sp), hkey).Clone()
            if 'trkChi2' not in hkey: HISTS[sp].Rebin2D(10, 10)

        opt = 'colz'
        #opt = 'scat=0.2'
        PLOTS = {hkey: Plotter.Plot(HISTS[hkey], '', '', opt)}
        for sp in SIGNALPOINTS:
            PLOTS[sp] = Plotter.Plot(HISTS[sp], '', '', opt)

        for sp in [
                hkey,
        ] + SIGNALPOINTS:
            canvas = Plotter.Canvas(lumi=fs + lumiExtra.get(CUTSTRING) if
                                    type(sp) != tuple else SPLumiStr(fs, *sp))
            canvas.addMainPlot(PLOTS[sp])
            canvas.mainPad.SetLogz()

            if quantity == 'trkChi2':
                canvas.firstPlot.GetXaxis().SetRangeUser(0., 10.)
                canvas.firstPlot.GetYaxis().SetRangeUser(0., 10.)

            canvas.scaleMargins(1.75, edges='R')
            canvas.scaleMargins(0.8, edges='L')
            canvas.cleanup('pdfs/ZEP_2D_{}_{}_{}_{}.pdf'.format(
                quantity, CUTSTRING, fs,
                'Global' if type(sp) != tuple else SPStr(sp)))
Beispiel #6
0
def makeLxyEffPlot(key, colorAxis, fs, sp, pTCut=''):

    config = {
        'Correct': ('Correct', 'Matches'),
    }
    if colorAxis == 'nMuons':
        num, den = config[key]

        nums = ['Lxy' + pTCut + '_n' + num + '_' + m for m in mnames]
        dens = ['Lxy' + pTCut + '_n' + den + '_' + m for m in mnames]
        tags = list(set(nums + dens))
        legs = {
            num: m if 'All' in m else m + ' #mu'
            for num, m in zip(nums, mnames)
        }
        cols = {num: c for num, c in zip(nums, colors)}

    if sp is None:
        h = {}
        for tag in tags:
            h[tag] = HistogramGetter.getHistogram(f, (fs, SIGNALPOINTS[0]),
                                                  tag).Clone()
        for SP in SIGNALPOINTS[1:]:
            for tag in tags:
                h[tag].Add(HistogramGetter.getHistogram(f, (fs, SP), tag))
    else:
        h = {}
        for tag in tags:
            h[tag] = HistogramGetter.getHistogram(f, (fs, sp), tag).Clone()

    for z in h:
        h[z].Rebin(10)

    p = {}
    graphs = {}
    for num, den in zip(nums, dens):
        realDen = h[den].Clone()
        graphs[num] = R.TGraphAsymmErrors(h[num], realDen, 'cp')
        p[num] = Plotter.Plot(graphs[num], legs[num], 'l', 'px')

    canvas = Plotter.Canvas(lumi=SPLumiStr(fs, sp) if sp is not None else fs)
    for tag in nums:
        canvas.addMainPlot(p[tag])
    canvas.firstPlot.SetMaximum(1.01)
    canvas.firstPlot.SetMinimum(0.)
    canvas.firstPlot.setTitles(X=h[tags[0]].GetXaxis().GetTitle(),
                               Y='Efficiency')
    for tag in p:
        p[tag].setColor(cols[tag], which='LM')

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

    canvas.cleanup('pdfs/RA_{}-Lxy{}-{}{}_HTo2XTo{}_{}.pdf'.format(
        'ComboMu' if colorAxis == 'nMuons' else 'ComboEff', pTCut, key,
        ARGS.CUTSTRING, fs,
        SPStr(sp) if sp is not None else 'Global'))
Beispiel #7
0
def makeDistPlot(quantity, criteria, fs, sp=None):
    # configy type stuff
    legs = ('All', 'Matched', 'NotMatched')
    tags = [
        quantity + '_' + ('All' + ('-4' if '-4' in criteria else '')
                          if 'All' in leg else criteria + '_' + leg)
        for leg in legs
    ]
    cols = (R.kBlack, R.kBlue, R.kRed)

    # get/add histograms
    if sp is None:
        h = {}
        for tag in tags:
            h[tag] = HistogramGetter.getHistogram(f, (fs, SIGNALPOINTS[0]),
                                                  tag).Clone()
        for SP in SIGNALPOINTS[1:]:
            for tag in tags:
                h[tag].Add(HistogramGetter.getHistogram(f, (fs, SP), tag))
    else:
        h = {}
        for tag in tags:
            h[tag] = HistogramGetter.getHistogram(f, (fs, sp), tag).Clone()

    # make plots
    p = {}
    for i, tag in enumerate(tags):
        p[tag] = Plotter.Plot(h[tag], legs[i], 'l', 'hist')

    # canvas, plots, min max
    logy = True
    canvas = Plotter.Canvas(lumi=SPLumiStr(fs, sp) if sp is not None else fs,
                            logy=logy)
    for tag in tags:
        canvas.addMainPlot(p[tag])
    canvas.setMaximum()
    if not logy:
        canvas.firstPlot.SetMinimum(0)
    else:
        canvas.firstPlot.SetMinimum(1.)
    if 'Lxy' in quantity:
        canvas.firstPlot.GetXaxis().SetRangeUser(0., 330.)

    # colors
    for i, tag in enumerate(tags):
        p[tag].SetLineColor(cols[i])

    # legend, cleanup
    canvas.makeLegend(lWidth=.2, pos='tr')
    canvas.legend.resizeHeight()

    canvas.cleanup('pdfs/LCD_{}Dist_{}{}_HTo2XTo{}_{}.pdf'.format(
        quantity, criteria, ARGS.CUTSTRING, fs,
        SPStr(sp) if sp is not None else 'Global'))
Beispiel #8
0
def makeStackPlot(key, colorAxis, fs, sp):

    if colorAxis == 'nMuons':
        tags = ['n' + key + '_' + m for m in mnames[1:]]
        legs = {tag: m + ' #mu' for tag, m in zip(tags, mnames[1:])}
        cols = {tag: R.kRed + i for i, tag in enumerate(tags)}

    elif colorAxis == 'Eff':
        tags = ['n' + k + '_' + key for k in hnames[1:]]
        legs = {tag: k for tag, k in zip(tags, hnames[1:])}
        cols = {tag: c for tag, c in zip(tags, colors[1:])}

    if sp is None:
        h = {}
        for tag in tags:
            h[tag] = HistogramGetter.getHistogram(f, (fs, SIGNALPOINTS[0]),
                                                  tag).Clone()
        for SP in SIGNALPOINTS[1:]:
            for tag in tags:
                h[tag].Add(HistogramGetter.getHistogram(f, (fs, SP), tag))
    else:
        h = {}
        for tag in tags:
            h[tag] = HistogramGetter.getHistogram(f, (fs, sp), tag).Clone()

    h['stack'] = R.THStack('hBG' + key, '')
    p = {}
    for tag in tags:
        if fs == '4Mu' and 'Event' in tag and colorAxis == 'Eff':
            h[tag].Scale(2.)
        h['stack'].Add(h[tag])
    p['stack'] = Plotter.Plot(h['stack'], '', '',
                              'hist' if colorAxis == 'nMuons' else 'nostack')
    for tag in tags:
        p[tag] = Plotter.Plot(h[tag], legs[tag], 'f', 'hist')

    for tag in tags:
        p[tag].setColor(cols[tag], which='LMF')

    canvas = Plotter.Canvas(lumi=SPLumiStr(fs, sp) if sp is not None else fs)
    for tag in ('stack', ):
        canvas.addMainPlot(p[tag])
    if colorAxis == 'nMuons':
        canvas.setMaximum(recompute=True)
    canvas.firstPlot.SetMinimum(0.)
    canvas.makeLegend(lWidth=.2, pos='tr', autoOrder=False)
    canvas.firstPlot.setTitles(X=h[tags[0]].GetXaxis().GetTitle(), Y='Counts')
    for tag in tags:
        canvas.addLegendEntry(p[tag])
    canvas.legend.resizeHeight()

    canvas.cleanup('pdfs/RA_{}-{}{}_HTo2XTo{}_{}.pdf'.format(
        'StackMu' if colorAxis == 'nMuons' else 'StackEff', key,
        ARGS.CUTSTRING, fs, sp if sp is not None else 'Global'))
Beispiel #9
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)))
Beispiel #10
0
def makePTCutPlot(fs, sp=None):
    # configy type stuff
    legs = ('All', 'Matched', 'Wrong', 'Right', 'Hopeless', 'Lost')
    tags = ['pT_' + tag for tag in legs]
    cols = (R.kBlack, R.kGreen, R.kOrange, R.kBlue, R.kRed, R.kMagenta)

    # get/add histograms
    if sp is None:
        h = {}
        for tag in tags:
            h[tag] = HistogramGetter.getHistogram(f, (fs, SIGNALPOINTS[0]),
                                                  tag).Clone()
        for SP in SIGNALPOINTS[1:]:
            for tag in tags:
                h[tag].Add(HistogramGetter.getHistogram(f, (fs, SP), tag))
    else:
        h = {}
        for tag in tags:
            h[tag] = HistogramGetter.getHistogram(f, (fs, sp), tag).Clone()

    # make plots
    p = {}
    for i, tag in enumerate(tags):
        p[tag] = Plotter.Plot(h[tag], legs[i], 'l', 'hist')

    # canvas, plots, min max
    logy = True
    canvas = Plotter.Canvas(lumi=SPLumiStr(fs, sp) if sp is not None else fs,
                            logy=logy)
    for tag in tags:
        canvas.addMainPlot(p[tag])
    canvas.setMaximum()
    if not logy:
        canvas.firstPlot.SetMinimum(0)
    else:
        canvas.firstPlot.SetMinimum(1.)
    #canvas.firstPlot.GetXaxis().SetRangeUser(0., 200.)
    canvas.firstPlot.GetXaxis().SetRangeUser(0., 30.)

    # colors
    for i, tag in enumerate(tags):
        p[tag].SetLineColor(cols[i])

    # legend, cleanup
    canvas.makeLegend(lWidth=.2, pos='tr')
    canvas.legend.resizeHeight()

    canvas.cleanup('pdfs/HPD_pTDist_HTo2XTo{}_{}.pdf'.format(
        fs,
        SPStr(sp) if sp is not None else 'Global'))
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)
def makeEffPlot(quantity, den, fs, sp=None):
    tags = (quantity + '_MSD', quantity + '_LCD', quantity + '_CID')

    effTag = quantity + '_CID'

    # get/add histograms
    if sp is None:
        h = {}
        for tag in tags:
            h[tag] = HistogramGetter.getHistogram(f, (fs, SIGNALPOINTS[0]),
                                                  tag).Clone()
        for SP in SIGNALPOINTS[1:]:
            for tag in tags:
                h[tag].Add(HistogramGetter.getHistogram(f, (fs, SP), tag))
    else:
        h = {}
        for tag in tags:
            h[tag] = HistogramGetter.getHistogram(f, (fs, sp), tag).Clone()

    hNum = h[quantity + '_CID']
    h[quantity + '_' + den].Add(h[quantity + '_CID'])
    hDen = h[quantity + '_' + den]

    graph = R.TGraphAsymmErrors(hNum, hDen, 'cp')

    # make plots
    p = Plotter.Plot(graph, '', 'l', 'px')

    # canvas, plots, min max
    canvas = Plotter.Canvas(lumi=SPLumiStr(fs, sp) if sp is not None else fs)
    canvas.addMainPlot(p)
    canvas.setMaximum()
    canvas.firstPlot.SetMinimum(0)

    # set titles
    canvas.firstPlot.setTitles(X=hNum.GetXaxis().GetTitle(), Y='Efficiency')

    # colors
    p.setColor(R.kBlue, which='M')

    # legend, cleanup
    #canvas.makeLegend(lWidth=.2, pos='tr')
    #canvas.legend.resizeHeight()

    canvas.cleanup('pdfs/3Mu_{}Eff-{}{}_HTo2XTo{}_{}.pdf'.format(
        quantity, den, ARGS.CUTSTRING, fs,
        SPStr(sp) if sp is not None else 'Global'))
Beispiel #14
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 makePlot(fs, sp, quantity):
    # configy type stuff
    tags = ('Matched', 'Junk')
    legs = {'Matched': 'Matched', 'Junk': 'Incorrect Pair'}
    cols = {'Matched': R.kBlue, 'Junk': R.kRed}

    # get/add histograms
    if sp is None:
        h = {}
        for tag in tags:
            h[tag] = HistogramGetter.getHistogram(
                f, (fs, SIGNALPOINTS[0]), quantity + '_' + tag).Clone()
        for SP in SIGNALPOINTS[1:]:
            for tag in tags:
                h[tag].Add(
                    HistogramGetter.getHistogram(f, (fs, SP),
                                                 quantity + '_' + tag))
    else:
        h = {}
        for tag in tags:
            h[tag] = HistogramGetter.getHistogram(f, (fs, sp), quantity + '_' +
                                                  tag).Clone()

    # make plots
    p = {}
    for tag in tags:
        p[tag] = Plotter.Plot(h[tag], legs[tag], 'l', 'hist')

    # canvas, plots, min max
    canvas = Plotter.Canvas(lumi=SPLumiStr(fs, sp) if sp is not None else fs,
                            logy=True)
    for tag in tags:
        canvas.addMainPlot(p[tag])
    canvas.setMaximum()

    # colors
    for tag in tags:
        p[tag].SetLineColor(cols[tag])

    # legend, cleanup
    canvas.makeLegend(lWidth=.2, pos='tr')
    canvas.legend.resizeHeight()

    canvas.cleanup('pdfs/PV_{}{}_HTo2XTo{}_{}.pdf'.format(
        quantity, args.CUTSTRING, fs,
        SPStr(sp) if sp is not None else 'Global'))
def makeSplit4Plot(quantity, fs, sp=None):
    tags = [quantity + '_' + tag for tag in ('CID', 'MSD', 'LCD', 'UMD')]
    legs = dict(
        zip(tags, ('correct', 'signal', 'lowest #chi^{2}/dof', 'unmatched')))
    cols = dict(zip(tags, (R.kBlue, R.kGreen, R.kMagenta, R.kRed)))

    # get/add histograms
    if sp is None:
        h = {}
        for tag in tags:
            h[tag] = HistogramGetter.getHistogram(f, (fs, SIGNALPOINTS[0]),
                                                  tag).Clone()
        for SP in SIGNALPOINTS[1:]:
            for tag in tags:
                h[tag].Add(HistogramGetter.getHistogram(f, (fs, SP), tag))
    else:
        h = {}
        for tag in tags:
            h[tag] = HistogramGetter.getHistogram(f, (fs, sp), tag).Clone()

    # make plots
    p = {}
    for tag in tags:
        p[tag] = Plotter.Plot(h[tag], legs[tag], 'l', 'hist')

    # canvas, plots, min max
    canvas = Plotter.Canvas(lumi=SPLumiStr(fs, sp) if sp is not None else fs,
                            logy=True)
    for tag in tags:
        canvas.addMainPlot(p[tag])
    canvas.setMaximum(scale=2.)
    canvas.firstPlot.SetMinimum(1.)

    # colors
    for tag in tags:
        p[tag].setColor(cols[tag], which='L')

    # legend, cleanup
    canvas.makeLegend(lWidth=.2, pos='tr')
    canvas.legend.resizeHeight()

    canvas.cleanup('pdfs/3Mu_{}Dist{}_HTo2XTo{}_{}.pdf'.format(
        quantity, ARGS.CUTSTRING, fs,
        SPStr(sp) if sp is not None else 'Global'))
Beispiel #17
0
def makePTCutPlot(fs, sp=None, PC=False, extra=''):
    # configy type stuff
    tags = TAGS[ARGS.FS + ('' if not PC else 'PC') + extra]
    legs = [CONFIG[tag]['LEG_H'] for tag in tags]
    cols = [CONFIG[tag]['COL'] for tag in tags]

    # get/add histograms
    if sp is None:
        h = {}
        for tag in tags:
            h[tag] = HistogramGetter.getHistogram(f, (fs, SIGNALPOINTS[0]),
                                                  tag).Clone()
        for SP in SIGNALPOINTS[1:]:
            for tag in tags:
                h[tag].Add(HistogramGetter.getHistogram(f, (fs, SP), tag))
    else:
        h = {}
        for tag in tags:
            h[tag] = HistogramGetter.getHistogram(f, (fs, sp), tag).Clone()

    # make plots
    p = {}
    for i, tag in enumerate(tags):
        p[tag] = Plotter.Plot(h[tag], legs[i], 'l', 'hist')

    # canvas, plots, min max
    canvas = Plotter.Canvas(lumi=SPLumiStr(fs, sp) if sp is not None else fs)
    for tag in tags:
        canvas.addMainPlot(p[tag])
    canvas.setMaximum()
    canvas.setMinimum()

    # colors
    for i, tag in enumerate(tags):
        p[tag].SetLineColor(cols[i])

    # legend, cleanup
    canvas.makeLegend(lWidth=.275, pos='tr')
    canvas.legend.resizeHeight()

    canvas.cleanup('pdfs/PC_Match{}{}_HTo2XTo{}_{}.pdf'.format(
        '-PC' if PC else '', extra, fs,
        SPStr(sp) if sp is not None else 'Global'))
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)
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)
Beispiel #20
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 makeSignal2DPlots():
    for quantity in ('normChi2', 'nTrkLay', 'nPxlHit', 'highPurity',
                     'isGlobal', 'isMedium', 'hitsBeforeVtx',
                     'missingHitsAfterVtx'):
        if quantity == 'nTrkLay':
            R.gStyle.SetPaintTextFormat('.1f')
        else:
            R.gStyle.SetPaintTextFormat('g')

        hkey = 'PAT-12-' + quantity
        HISTS = HG.getAddedSignalHistograms(FILES[fs], fs, (hkey, ))
        for sp in SIGNALPOINTS:
            HISTS[sp] = HG.getHistogram(FILES[fs], (fs, sp), hkey).Clone()

        if quantity != 'normChi2':
            opt = 'colz text'
        else:
            opt = 'colz'
        PLOTS = {hkey: Plotter.Plot(HISTS[hkey], '', '', opt)}
        for sp in SIGNALPOINTS:
            PLOTS[sp] = Plotter.Plot(HISTS[sp], '', '', opt)

        for sp in [
                hkey,
        ] + SIGNALPOINTS:
            canvas = Plotter.Canvas(lumi=fs + lumiExtra.get(CUTSTRING) if
                                    type(sp) != tuple else SPLumiStr(fs, *sp))
            canvas.addMainPlot(PLOTS[sp])
            canvas.firstPlot.SetMarkerColor(R.kWhite)

            if quantity == 'normChi2':
                canvas.firstPlot.GetXaxis().SetRangeUser(0., 10.)
                canvas.firstPlot.GetYaxis().SetRangeUser(0., 10.)

            canvas.scaleMargins(1.75, edges='R')
            canvas.scaleMargins(0.8, edges='L')
            canvas.cleanup('pdfs/ZEP_2D_{}_{}_{}_{}.pdf'.format(
                quantity, CUTSTRING, fs,
                'Global' if type(sp) != tuple else SPStr(sp)))
Beispiel #22
0
def makePTCutEffPlot(fs, sp=None, PC=False, extra=''):
    # configy type stuff
    tags = TAGS[ARGS.FS + ('' if not PC else 'PC') + extra]
    legs = [CONFIG[tag]['LEG_EFF'] for tag in tags]
    cols = [CONFIG[tag]['COL'] for tag in tags]

    # get/add histograms
    if sp is None:
        h = {}
        for tag in tags:
            h[tag] = HistogramGetter.getHistogram(f, (fs, SIGNALPOINTS[0]),
                                                  tag).Clone()
        for SP in SIGNALPOINTS[1:]:
            for tag in tags:
                h[tag].Add(HistogramGetter.getHistogram(f, (fs, SP), tag))
    else:
        h = {}
        for tag in tags:
            h[tag] = HistogramGetter.getHistogram(f, (fs, sp), tag).Clone()

    # clone everything, the h is about to be overwritten
    copies = {}
    for tag in tags:
        copies[tag] = h[tag].Clone()

    # nMatch: scale to first bin (gives ~efficiency)
    # others: divide by nMatch
    h[tags[0]].Scale(1. / copies[tags[0]].GetBinContent(1))
    for tag in tags[1:]:
        h[tag] = R.TGraphAsymmErrors(copies[tag], copies[tags[0]], 'cp')

    # make plots
    p = {}
    for i, tag in enumerate(tags):
        p[tag] = Plotter.Plot(h[tag], legs[i], 'p',
                              'p' + ('' if i == 0 else 'x'))

    # it's an efficiency so the scale is 0-1, but zoom in on the relevant part
    canvas = Plotter.Canvas(lumi=SPLumiStr(fs, sp) if sp is not None else fs)
    for tag in tags:
        canvas.addMainPlot(p[tag])
    canvas.firstPlot.SetMaximum(1.01)
    canvas.firstPlot.SetMinimum(0.90 if ARGS.FS == '2Mu2J' else 0.50)
    if ARGS.FS == '2Mu2J' and extra != '':
        canvas.firstPlot.SetMinimum(0.)
    #canvas.setMaximum()
    #canvas.setMinimum()

    # set colors
    for i, tag in enumerate(tags):
        p[tag].setColor(cols[i])

    # legend, cleanup
    if extra == '':
        canvas.makeLegend(lWidth=.275, pos='br')
        canvas.legend.resizeHeight()
        # hack for getting the legend in the right spot for 1000 and 400, as it turns out
        if sp is not None and sp[0] > 399:
            canvas.legend.moveLegend(X=-.35)
        else:
            canvas.legend.moveLegend(Y=.2)
    else:
        canvas.makeLegend(lWidth=.275, pos='tr')
        canvas.legend.resizeHeight()

    canvas.cleanup('pdfs/PC_MatchEff{}{}_HTo2XTo{}_{}.pdf'.format(
        '-PC' if PC else '', extra, fs,
        SPStr(sp) if sp is not None else 'Global'))
Beispiel #23
0
def makeEffPlots(quantity, fs, SP=None):
    HKeys = {
        'DSA_Eff': 'DSA_{}Eff',
        'RSA_Eff': 'RSA_{}Eff',
        'REF_Eff': 'REF_{}Eff',
        'REF_Den': 'REF_{}Den',
        'Den': '{}Den',
        #       'Extra'         : '{}Extra'        ,
        'DSA_ChargeEff': 'DSA_{}ChargeEff',
        'RSA_ChargeEff': 'RSA_{}ChargeEff',
        'REF_ChargeEff': 'REF_{}ChargeEff',
        'DSA_ChargeDen': 'DSA_{}ChargeDen',
        'RSA_ChargeDen': 'RSA_{}ChargeDen',
        'REF_ChargeDen': 'REF_{}ChargeDen',
    }
    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])
        if quantity != 'dR':
            h[key].Rebin(10)
        else:
            h[key].Rebin(5)

# Extra is commented out, same with FIRST SECOND
# so they don't appear on SRE plots by default now

    NumDens = (
        ('DSA_Eff', 'Den', 'DSA', R.kBlue),
        ('RSA_Eff', 'Den', 'RSA', R.kRed),
        ('REF_Eff', 'REF_Den', 'REF', R.kGreen),
        #       ('Extra'        , 'Den'          , 'Extra'     , R.kMagenta),
        ('DSA_ChargeEff', 'DSA_ChargeDen', 'DSA:Charge', R.kBlue),
        ('RSA_ChargeEff', 'RSA_ChargeDen', 'RSA:Charge', R.kRed),
        ('REF_ChargeEff', 'REF_ChargeDen', 'REF:Charge', R.kGreen),
    )

    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() + ';Reconstruction Efficiency')
        p[num] = Plotter.Plot(g[num], leg, 'elp', 'pe')


#   FIRST  = (0, 3)
#   SECOND = (3, 5)
#   FIRST  = (0, 2)
#   SECOND = (2, 4)
    FIRST = (0, 3)
    SECOND = (3, 6)
    CHARGE = ''
    for SECTION in (FIRST, SECOND):
        canvas = Plotter.Canvas(lumi=fs if SP is None else SPLumiStr(fs, *SP))
        for i in range(SECTION[0], SECTION[1]):
            key = NumDens[i][0]
            col = NumDens[i][3]
            canvas.addMainPlot(p[key])
            p[key].setColor(col)
        # aesthetic change
        if quantity == 'Lxy' or (quantity == 'd0' and CHARGE == ''):
            canvas.makeLegend(pos='bl')
        else:
            canvas.makeLegend(pos='br')
            canvas.legend.moveLegend(Y=0.25)
            canvas.legend.moveLegend(X=-.1)
        canvas.legend.resizeHeight()
        canvas.firstPlot.SetMinimum(0.)
        canvas.firstPlot.SetMaximum(1.)
        #RT.addBinWidth(canvas.firstPlot)
        # aesthetic change
        if quantity == 'dR':
            canvas.firstPlot.GetXaxis().SetRangeUser(0., 1.)
        elif quantity == 'pT':
            canvas.firstPlot.GetXaxis().SetRangeUser(0., 800.)
        canvas.cleanup('pdfs/SRE_{}{}Eff_{}HTo2XTo{}_{}.pdf'.format(
            quantity, CHARGE, 'Trig-' if TRIGGER else '', fs,
            'Global' if SP is None else SPStr(SP)))
        CHARGE = 'Charge'
Beispiel #24
0
def makeMultiplicityPlots(fs, sp):
    if ARGS.FS == '4Mu': return

    # configy type stuff
    pTCuts = (0, 5, 10, 15)
    splits = ('_', '_Matched_', '_NotMatched_')
    prettysplits = {
        '_': '',
        '_Matched_': ' (Matched)',
        '_NotMatched_': ' (Junk)'
    }
    quants = ('Muon', 'Dimuon')

    for q in quants:
        for split in splits:
            for logy in (True, False):
                tags = []
                legs = []
                cols = [R.kRed, R.kBlue, R.kGreen, R.kMagenta]
                for pTCut in pTCuts:
                    tags.append('n{}{}{}'.format(q, split, pTCut))
                    legs.append(
                        '{} GeV'.format(pTCut) if pTCut > 0 else 'no cut')

                # the code after this is identical to the makePTCutPlot code, except for the lumi string, min/max, and cleanup
                if sp is None:
                    h = {}
                    for tag in tags:
                        h[tag] = HistogramGetter.getHistogram(
                            f, (fs, SIGNALPOINTS[0]), tag).Clone()
                    for SP in SIGNALPOINTS[1:]:
                        for tag in tags:
                            h[tag].Add(
                                HistogramGetter.getHistogram(f, (fs, SP), tag))
                else:
                    h = {}
                    for tag in tags:
                        h[tag] = HistogramGetter.getHistogram(
                            f, (fs, sp), tag).Clone()

                p = {}
                for i, tag in enumerate(tags):
                    p[tag] = Plotter.Plot(h[tag], legs[i], 'l', 'hist')

                canvas = Plotter.Canvas(
                    lumi=(SPLumiStr(fs, sp) if sp is not None else fs) +
                    prettysplits[split],
                    logy=logy)
                for tag in tags:
                    canvas.addMainPlot(p[tag])
                if logy:
                    canvas.setMaximum(scale=2.)
                    canvas.firstPlot.SetMinimum(1.)
                else:
                    canvas.setMaximum()
                    canvas.firstPlot.SetMinimum(0.)

                for i, tag in enumerate(tags):
                    p[tag].SetLineColor(cols[i])

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

                canvas.cleanup('pdfs/PC_{}Mult{}{}HTo2XTo{}_{}.pdf'.format(
                    q, split, 'Log_' if logy else '', fs,
                    SPStr(sp) if sp is not None else 'Global'))
Beispiel #25
0
def optimizeCut(fs, sp, quantity):
    # get histograms
    s = getHistogram(f, fs, sp, quantity, 'Matched')
    b = getHistogram(f, fs, sp, quantity, 'Junk'   )

    # get cumulatives
    sCum = s.GetCumulative()
    bCum = b.GetCumulative()
    fom  = sCum.Clone()

    # print out suppression
    nBins = sCum.GetNbinsX()
    if quantity == 'LxyErr':
        ibin = 200
    else:
        ibin = 660
    srej = 1.-sCum.GetBinContent(ibin)/sCum.GetBinContent(nBins)
    brej = 1.-bCum.GetBinContent(ibin)/bCum.GetBinContent(nBins)
    #print '{:5s} {:4d} {:3d} {:4d} :: {:6s} :: reject {:6.2%} of signal, but {:6.2%} of background'.format(
    #        fs,
    #        sp[0], sp[1], sp[2],
    #        quantity,
    #        1.-sCum.GetBinContent(ibin)/sCum.GetBinContent(nBins),
    #        1.-bCum.GetBinContent(ibin)/bCum.GetBinContent(nBins),
    #)

    # fill f.o.m. histogram, and keep track of max f.o.m. and cut value
    nBins = sCum.GetNbinsX()
    xAxis = sCum.GetXaxis()
    fom_max = 0.
    opt_cut = 0.
    for ibin in range(1,nBins+1):
        val = FOM(sCum.GetBinContent(ibin), bCum.GetBinContent(ibin))
        if val > fom_max:
            fom_max = val
            opt_cut = xAxis.GetBinCenter(ibin)
        fom.SetBinContent(ibin, val)

    # make plots
    p = {}
    p['sig'] = Plotter.Plot(sCum, 'matched'     , 'l', 'hist')
    p['bg' ] = Plotter.Plot(bCum, 'other'       , 'l', 'hist')
    p['fom'] = Plotter.Plot(fom , 'S/#sqrt{S+B}', 'l', 'hist')

    # make canvas, colors, maximum
    canvas = Plotter.Canvas(lumi=SPLumiStr(fs, *sp))
    canvas.addMainPlot(p['sig'])
    canvas.addMainPlot(p['bg' ])
    canvas.addMainPlot(p['fom'])

    p['sig'].SetLineColor(R.kBlue )
    p['bg' ].SetLineColor(R.kRed  )
    p['fom'].SetLineColor(R.kGreen)

    canvas.setMaximum()

    # scale f.o.m. and make new axis
    fom.Scale(canvas.firstPlot.GetMaximum()/fom_max/1.05)
    axis = R.TGaxis(xAxis.GetXmax(), 0., xAxis.GetXmax(), canvas.firstPlot.GetMaximum(), 0., fom_max*1.05, 510, '+L')
    for attr in ('LabelFont', 'LabelOffset', 'TitleFont', 'TitleOffset', 'TitleSize'):
        getattr(axis, 'Set'+attr)(getattr(xAxis, 'Get'+attr)())
    axis.SetTitle('Figure of Merit')
    axis.CenterTitle()
    axis.Draw()
    canvas.scaleMargins(1.1, edges='R')

    # make the legend after
    canvas.makeLegend(lWidth=.2, pos='br')
    canvas.legend.resizeHeight()

    # draw optimum text and line
    x, y = canvas.legend.GetX1(), canvas.legend.GetY2()
    canvas.drawText(text='#color[{:d}]{{opt. cut = {:.2f}}}'.format(R.kBlack, opt_cut), pos=(x, y+0.05), align='bl')

    line = R.TLine(opt_cut, 0., opt_cut, canvas.firstPlot.GetMaximum())
    line.SetLineStyle(2)
    line.Draw()

    # save
    canvas.cleanup('OPT_{}_HTo2XTo{}_{}.pdf'.format(quantity, fs, SPStr(sp)))

    # save cut val
    if sp not in DATA[fs]: DATA[fs][sp] = {}
    if quantity not in DATA[fs][sp]: DATA[fs][sp][quantity] = {
        'opt':0,
        'srej':0,
        'brej':0,
    }
    DATA[fs][sp][quantity]['opt'] = opt_cut
    DATA[fs][sp][quantity]['srej'] = srej
    DATA[fs][sp][quantity]['brej'] = brej
Beispiel #26
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)
Beispiel #27
0
def optimizeCut(fs, sp, quantity):
    # get histograms
    s = HG.getHistogram(FILES['Signal'], (fs, sp), quantity)
    DHists, DPConfig = HG.getDataHistograms(FILES['Data'], quantity)
    b = DHists[quantity]['data']

    n = s.Integral(0, s.GetNbinsX()+1)
    s.Scale(ScaleFactor(sp, sigmaB=1.e-2))

    # get cumulatives
    sCum = s.GetCumulative(CONFIG[quantity]['forward'])
    bCum = b.GetCumulative(CONFIG[quantity]['forward'])
    fom  = sCum.Clone()

    print '**** Data (|DeltaPhi| > Pi/2) vs. HTo2XTo{} ({} GeV, {} GeV, {} mm) (|DeltaPhi| < Pi/2)'.format(fs, *sp)
    print '**** Quantity = {:s} ::: Passing (N-1) = {:.0f} ::: N_gen = {:.0f} ::: Sigma*B = {:.3f} pb ::: 2016 ILumi = 35922 /pb'.format(
            CONFIG[quantity]['pretty'], n, SignalInfo[sp]['sumWeights'][1], SignalInfo[sp]['sigmaBLimit'])
    print '{:>8s} {:>7s} {:>7s} {:>7s} {:>6s} {:>6s}'.format('CutVal', 'S', 'B=nOff', 'S+B=nOn', 'ZBi', 'ZPL')

    # fill f.o.m. histogram, and keep track of max f.o.m. and cut value
    nBins = sCum.GetNbinsX()
    xAxis = sCum.GetXaxis()

    fom_max = 0.
    opt_cut = 0.
    opt_s   = 0.
    opt_b   = 0.

    for ibin in range(1,nBins+1):
        S, B, cutVal, FOMs = calculateFOM(s, b, sCum, bCum, nBins, ibin, xAxis, CONFIG[quantity]['forward'])
        print '{:8.3f} {:7.3f} {:7.3f} {:7.3f} {:6.3f} {:6.3f}'.format(cutVal, S, B, S+B, FOMs['ZBi'], FOMs['ZPL'])

        if FOMs[FIGURE_OF_MERIT] > fom_max:
            fom_max = FOMs[FIGURE_OF_MERIT]
            opt_cut = cutVal
            opt_s   = S
            opt_b   = B

        fom.SetBinContent(ibin, FOMs[FIGURE_OF_MERIT])

    # make plots
    p = {}
    p['sig'] = Plotter.Plot(sCum, 'signal'   , 'l', 'hist')
    p['bg' ] = Plotter.Plot(bCum, 'data'     , 'l', 'hist')
    p['fom'] = Plotter.Plot(fom , PRETTY_LEG , 'l', 'hist')

    # make canvas, colors, maximum
    canvas = Plotter.Canvas(lumi=SPLumiStr(fs, *sp))
    canvas.addMainPlot(p['sig'])
    canvas.addMainPlot(p['bg' ])
    canvas.addMainPlot(p['fom'])

    p['sig'].SetLineColor(R.kBlue )
    p['bg' ].SetLineColor(R.kRed  )
    p['fom'].SetLineColor(R.kGreen)

    canvas.setMaximum()
    canvas.firstPlot.SetMinimum(0.)

    # scale f.o.m. and make new axis
    fom.Scale(canvas.firstPlot.GetMaximum()/fom_max/1.05)
    axis = R.TGaxis(xAxis.GetXmax(), 0., xAxis.GetXmax(), canvas.firstPlot.GetMaximum(), 0., fom_max*1.05, 510, '+L')
    for attr in ('LabelFont', 'LabelOffset', 'TitleFont', 'TitleOffset', 'TitleSize'):
        getattr(axis, 'Set'+attr)(getattr(xAxis, 'Get'+attr)())
    axis.SetTitle('Figure of Merit')
    axis.CenterTitle()
    axis.Draw()
    canvas.scaleMargins(1.1, edges='R')

    # make the legend after
    canvas.makeLegend(lWidth=.2, pos='br')
    canvas.legend.resizeHeight()
    canvas.legend.moveLegend(X=-.2, Y=.1)

    # draw optimum text and line
    x, y = canvas.legend.GetX1(), canvas.legend.GetY2()
    canvas.drawText(text='#color[{:d}]{{opt. cut = {:.2f}}}'.format(R.kBlack, opt_cut), pos=(x, y+0.05), align='bl')

    line = R.TLine(opt_cut, 0., opt_cut, canvas.firstPlot.GetMaximum())
    line.SetLineStyle(2)
    line.Draw()

    # save
    canvas.cleanup('pdfs/OPT_{}_{}_HTo2XTo{}_{}.pdf'.format(quantity, FIGURE_OF_MERIT, fs, SPStr(sp)))
def makeSplitDeltaPhiPlots():
    for ref in HISTS:
        if not type(ref) == tuple: continue
        for KEY in HISTS[ref]:
            if 'VSdeltaPhi' not 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])
            else:
                name = ref
                lumi = HistogramGetter.PLOTCONFIG[ref]['LATEX']
                if '_Matched' in KEY: continue

            H = HISTS[ref][KEY].Clone()
            nBins = H.GetNbinsX()

            h = {
                'Less': {
                    'hist': H.ProjectionY('Less', 1, nBins / 2),
                    'legName': '|#Delta#Phi|<#pi/2',
                    'color': R.kBlue
                },
                'More': {
                    'hist': H.ProjectionY('More', nBins / 2 + 1, nBins),
                    'legName': '|#Delta#Phi|>#pi/2',
                    'color': R.kRed
                },
            }

            p = {}
            for key in h:
                if h[key]['hist'].Integral() != 0:
                    h[key]['hist'].Scale(1. / h[key]['hist'].Integral())
                if nBins > 100: h[key]['hist'].Rebin(10)
                p[key] = Plotter.Plot(h[key]['hist'], h[key]['legName'], 'l',
                                      'hist')

            canvas = Plotter.Canvas(lumi=lumi)
            for key in h:
                canvas.addMainPlot(p[key])
                p[key].SetLineColor(h[key]['color'])
            canvas.makeLegend(pos='tl')
            canvas.legend.resizeHeight()
            canvas.setMaximum(recompute=True)
            canvas.firstPlot.setTitles(Y='Normalized Counts')

            pave = []
            for key in h:
                pave.append(canvas.makeStatsBox(p[key], color=h[key]['color']))
            for i, box in enumerate(pave):
                if i == 0: continue
                HEIGHT = pave[i - 1].GetY2NDC() - pave[i - 1].GetY1NDC()
                Plotter.MOVE_OBJECT(box, Y=-HEIGHT - .05)

            parse = re.match(r'Dim_(.*)VSdeltaPhi(.*)', KEY)
            yAxis, other = parse.group(1), parse.group(2)
            fname = 'pdfs/Dim_{}{}{}_Both_{}.pdf'.format(
                yAxis, other, CUTSTRING, name)
            canvas.cleanup(fname)
def makePerSamplePlots():
    for ref in HISTS:
        print "ref: ,", ref
        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']
            print "name: ", name, " lumi: ", lumi, " legName: ", legName
        else:
            name = ref
            lumi = HistogramGetter.PLOTCONFIG[ref]['LATEX']
            legName = HistogramGetter.PLOTCONFIG[ref]['LATEX']

        # histo filename
        fname = 'pdfs/muonQualityPlots_{}.pdf'.format(name)

        # canvas
        canvas = R.TCanvas('c', 'canvas', 0, 0, 800, 600)

        gStyle.SetOptStat(111111)
        #        gStyle.SetStatW(0.25)        # width of statistics box; default is 0.19
        #        gStyle.SetStatH(0.10)        # height of statistics box; default is 0.1
        #        gStyle.SetStatFontSize(0.07) # size for stat. box

        # delta R between nearest HLT and DSA muons
        canvas.Clear()
        htit = 'dR_HLT_DSA'
        pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
        pad.Draw()
        pad.Divide(1, 2)
        pad.cd(1)
        HISTS[ref][htit].Draw("hist")
        pad.cd(2)
        HISTS[ref][htit].Draw("hist")
        gPad.SetLogy(1)
        canvas.Print(fname + "(", "Title:" + htit)

        # delta R between nearest HLT and DSA muons for good events failing the default HLT-RECO match
        canvas.Clear()
        pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
        pad.Draw()
        pad.Divide(2, 2)
        pad.cd(1)
        HISTS[ref]['dR1_HLT_DSA_GoodEvent'].Draw("hist")
        pad.cd(2)
        HISTS[ref]['dR1_HLT_DSA_GoodEvent'].Draw("hist")
        gPad.SetLogy(1)
        pad.cd(3)
        HISTS[ref]['dR2_HLT_DSA_GoodEvent'].Draw("hist")
        pad.cd(4)
        HISTS[ref]['dR2_HLT_DSA_GoodEvent'].Draw("hist")
        gPad.SetLogy(1)
        canvas.Print(fname, "Title:dR_HLT_DSA, no HLT-RECO match, good events")

        # delta R between nearest HLT and DSA muons for bad events failing the default HLT-RECO match
        canvas.Clear()
        pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
        pad.Draw()
        pad.Divide(2, 2)
        pad.cd(1)
        HISTS[ref]['dR1_HLT_DSA_BadEvent'].Draw("hist")
        pad.cd(2)
        HISTS[ref]['dR1_HLT_DSA_BadEvent'].Draw("hist")
        gPad.SetLogy(1)
        pad.cd(3)
        HISTS[ref]['dR2_HLT_DSA_BadEvent'].Draw("hist")
        pad.cd(4)
        HISTS[ref]['dR2_HLT_DSA_BadEvent'].Draw("hist")
        gPad.SetLogy(1)
        canvas.Print(fname, "Title:dR_HLT_DSA, no HLT-RECO match, bad events")

        # number of unsuccessful and successful HLT-DSA matches
        canvas.Clear()
        htit = 'matches_HLT_DSA'
        HISTS[ref][htit].Draw("hist")
        HISTS[ref][htit].Draw("same text")
        canvas.Print(fname, "Title:" + htit)

        # some diagnostics for RECO muons matched to signal GEN muons but not matched to HLT muons
        canvas.Clear()
        pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
        pad.Draw()
        pad.Divide(2, 2)
        pad.cd(1)
        HISTS[ref]['unmatched_pt_res'].Draw("hist")
        pad.cd(2)
        HISTS[ref]['unmatched_invm_res'].Draw("hist")
        pad.cd(3)
        HISTS[ref]['unmatched_pt_rec_vs_pt_gen'].Draw("")
        pad.cd(4)
        HISTS[ref]['unmatched_pt_rec_vs_pt_gen_zoomed'].Draw("")
        canvas.Print(
            fname,
            "Title:RECO muons matched to signal GEN muons but not matched to HLT muons"
        )

        # N(CSC stations) vs N(DT stations)
        canvas.Clear()
        htit = 'CSC_vs_DT_Stations'
        HISTS[ref][htit].Draw("text")
        canvas.Print(fname, "Title:" + htit)

        # Nhits
        canvas.Clear()
        pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
        pad.Draw()
        pad.Divide(2, 2)
        pad.cd(1)
        HISTS[ref]['nMuonHits'].Draw("hist")
        pad.cd(2)
        HISTS[ref]['nDTCSCHits'].Draw("hist")
        pad.cd(3)
        HISTS[ref]['nDTHits'].Draw("hist")
        pad.cd(4)
        HISTS[ref]['nCSCHits'].Draw("hist")
        #        HISTS[ref]['nRPCHits'].Draw("hist")
        canvas.Print(fname, "Title:total number of hits")

        # Nhits for various Nstations
        canvas.Clear()
        pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
        pad.Draw()
        pad.Divide(2, 2)
        for istat in range(1, 5):
            pad.cd(istat)
            htit = 'nMuonHits_' + str(istat) + 'Stat'
            HISTS[ref][htit].Draw("hist")
        canvas.Print(fname, "Title:muon hits per station")

        canvas.Clear()
        pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
        pad.Draw()
        pad.Divide(2, 2)
        for istat in range(1, 5):
            pad.cd(istat)
            htit = 'nRPCHits_' + str(istat) + 'Stat'
            HISTS[ref][htit].Draw("hist")
        canvas.Print(fname, "Title:RPC hits per station")

        canvas.Clear()
        pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
        pad.Draw()
        pad.Divide(2, 2)
        for istat in range(1, 5):
            pad.cd(istat)
            htit = 'nCSCHits_vs_nDTHits_' + str(istat) + 'Stat'
            HISTS[ref][htit].Draw("text")
        canvas.Print(fname, "Title:CSC hits vs DT hits, per station")

        canvas.Clear()
        pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
        pad.Draw()
        pad.Divide(2, 2)
        for istat in range(1, 5):
            pad.cd(istat)
            htit = 'nDTCSCHits_' + str(istat) + 'Stat'
            HISTS[ref][htit].Draw("hist")
        canvas.Print(fname, "Title:DT+CSC hits per station, lin scale")

        canvas.Clear()
        pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
        gStyle.SetOptLogy(1)
        pad.Draw()
        pad.Divide(2, 2)
        for istat in range(1, 5):
            pad.cd(istat)
            htit = 'nDTCSCHits_' + str(istat) + 'Stat'
            HISTS[ref][htit].Draw("hist")
        gStyle.SetOptLogy(0)
        canvas.Print(fname, "Title:DT+CSC hits per station, log scale")

        canvas.Clear()
        pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
        pad.Draw()
        pad.Divide(2, 2)
        for istat in range(1, 5):
            pad.cd(istat)
            htit = 'nDTHits_' + str(istat) + 'Stat'
            HISTS[ref][htit].Draw("hist")
        canvas.Print(fname, "Title:DT hits per station, lin scale")

        canvas.Clear()
        pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
        gStyle.SetOptLogy(1)
        pad.Draw()
        pad.Divide(2, 2)
        for istat in range(1, 5):
            pad.cd(istat)
            htit = 'nDTHits_' + str(istat) + 'Stat'
            HISTS[ref][htit].Draw("hist")
        gStyle.SetOptLogy(0)
        canvas.Print(fname, "Title:DT hits per station, log scale")

        canvas.Clear()
        pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
        pad.Draw()
        pad.Divide(2, 2)
        for istat in range(1, 5):
            pad.cd(istat)
            htit = 'nCSCHits_' + str(istat) + 'Stat'
            HISTS[ref][htit].Draw("hist")
        canvas.Print(fname, "Title:CSC hits per station, lin scale")

        canvas.Clear()
        pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
        gStyle.SetOptLogy(1)
        pad.Draw()
        pad.Divide(2, 2)
        for istat in range(1, 5):
            pad.cd(istat)
            htit = 'nCSCHits_' + str(istat) + 'Stat'
            HISTS[ref][htit].Draw("hist")
        gStyle.SetOptLogy(0)
        canvas.Print(fname, "Title:CSC hits per station, log scale")

        # pT resolutions for groups of 3 DT+CSC hits
        htot = 17
        for ihist in range(0, htot):
            ipad = ihist % 8
            if ipad == 0:
                canvas.Clear()
                pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
                pad.Draw()
                pad.Divide(4, 2)
            pad.cd(ipad + 1)
            htit = 'pTres_DTCSChits_hist' + str(ihist)
            HISTS[ref][htit].Draw("hist")
            if ipad == 7 or ihist == htot - 1:
                canvas.Print(fname, "Title:pT res for groups of 3 hits")

        # pT res for groups of 3 hits, N(stat) > 1
        htot = 8
        for ihist in range(0, htot):
            ipad = ihist % 8
            if ipad == 0:
                canvas.Clear()
                pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
                pad.Draw()
                pad.Divide(4, 2)
            pad.cd(ipad + 1)
            htit = 'pTres_DTCSChits_Stat234_hist' + str(ihist)
            HISTS[ref][htit].Draw("hist")
            if ipad == 7 or ihist == htot - 1:
                canvas.Print(fname,
                             "Title:pT res for groups of 3 hits, N(stat) > 1")

        # pT res for 12-19 DTCSC hits, N(stat) > 1
        canvas.Clear()
        pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
        pad.Draw()
        pad.Divide(4, 2)
        for ihits in range(12, 20):
            pad.cd(ihits - 11)
            htit = 'pTres_Stat234_' + str(ihits) + 'DTCSChits'
            HISTS[ref][htit].Draw("hist")
        canvas.Print(fname, "Title:pT res for 12-19 DTCSC hits, N(stat) > 1")

        # resolutions in barrel, endcap, and overlap
        htot = 8  # hist8 and hist9 are empty
        for ihist in range(0, htot):
            ipad = ihist % 8
            if ipad == 0:
                canvas.Clear()
                pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
                pad.Draw()
                pad.Divide(4, 2)
            pad.cd(ipad + 1)
            htit = 'pTres_DThits_barrel_hist' + str(ihist)
            HISTS[ref][htit].Draw("hist")
            if ipad == 7 or ihist == htot - 1:
                canvas.Print(fname,
                             "Title:pT res for groups of 6 hits, barrel")

        htot = 10
        for ihist in range(0, htot):
            ipad = ihist % 8
            if ipad == 0:
                canvas.Clear()
                pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
                pad.Draw()
                pad.Divide(4, 2)
            pad.cd(ipad + 1)
            htit = 'pTres_CSChits_endcap_hist' + str(ihist)
            HISTS[ref][htit].Draw("hist")
            if ipad == 7 or ihist == htot - 1:
                canvas.Print(fname,
                             "Title:pT res for groups of 3 hits, endcap")

        htot = 8  # hist8 and hist9 are empty
        for ihist in range(0, htot):
            ipad = ihist % 8
            if ipad == 0:
                canvas.Clear()
                pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
                pad.Draw()
                pad.Divide(4, 2)
            pad.cd(ipad + 1)
            htit = 'pTres_DTCSChits_overlap_hist' + str(ihist)
            HISTS[ref][htit].Draw("hist")
            if ipad == 7 or ihist == htot - 1:
                canvas.Print(fname,
                             "Title:pT res for groups of 6 hits, overlap")

        # 1/pT resolutions for groups of 3 DT+CSC hits
        htot = 17
        for ihist in range(0, htot):
            ipad = ihist % 8
            if ipad == 0:
                canvas.Clear()
                pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
                pad.Draw()
                pad.Divide(4, 2)
            pad.cd(ipad + 1)
            htit = 'invpTres_DTCSChits_hist' + str(ihist)
            HISTS[ref][htit].Draw("hist")
            if ipad == 7 or ihist == htot - 1:
                canvas.Print(fname, "Title:1/pT res for groups of 3 hits")

        # 1/pT resolutions for groups of 3 hits, N(stat) > 1
        htot = 8
        for ihist in range(0, htot):
            ipad = ihist % 8
            if ipad == 0:
                canvas.Clear()
                pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
                pad.Draw()
                pad.Divide(4, 2)
            pad.cd(ipad + 1)
            htit = 'invpTres_DTCSChits_Stat234_hist' + str(ihist)
            HISTS[ref][htit].Draw("hist")
            if ipad == 7 or ihist == htot - 1:
                canvas.Print(
                    fname, "Title:1/pT res for groups of 3 hits, N(stat) > 1")

        # charge difference for groups of 3 hits
        htot = 17
        for ihist in range(0, htot):
            ipad = ihist % 8
            if ipad == 0:
                canvas.Clear()
                pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
                pad.Draw()
                pad.Divide(4, 2)
            pad.cd(ipad + 1)
            htit = 'qdif_DTCSChits_hist' + str(ihist)
            HISTS[ref][htit].Draw("hist")
            if ipad == 7 or ihist == htot - 1:
                canvas.Print(fname, "Title:q dif for groups of 3 hits")

        # charge difference for groups of 3 hits, N(stat) > 1
        htot = 8
        for ihist in range(0, htot):
            ipad = ihist % 8
            if ipad == 0:
                canvas.Clear()
                pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
                pad.Draw()
                pad.Divide(4, 2)
            pad.cd(ipad + 1)
            htit = 'qdif_DTCSChits_Stat234_hist' + str(ihist)
            HISTS[ref][htit].Draw("hist")
            if ipad == 7 or ihist == htot - 1:
                canvas.Print(fname,
                             "Title:q dif for groups of 3 hits, N(stat) > 1")

        # charge difference for 12-19 DTCSC hits, N(stat) > 1
        canvas.Clear()
        pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
        pad.Draw()
        pad.Divide(4, 2)
        for ihits in range(12, 20):
            pad.cd(ihits - 11)
            htit = 'qdif_Stat234_' + str(ihits) + 'DTCSChits'
            HISTS[ref][htit].Draw("hist")
        canvas.Print(fname, "Title:q dif for 12-19 DTCSC hits, N(stat) > 1")

        # d0 difference for groups of 3 hits
        htot = 17
        for ihist in range(0, htot):
            ipad = ihist % 8
            if ipad == 0:
                canvas.Clear()
                pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
                pad.Draw()
                pad.Divide(4, 2)
            pad.cd(ipad + 1)
            htit = 'd0dif_DTCSChits_hist' + str(ihist)
            HISTS[ref][htit].Draw("hist")
            if ipad == 7 or ihist == htot - 1:
                canvas.Print(fname, "Title:d0 dif for groups of 3 hits")

        # d0 difference for groups of 6 hits in barrel, endcap, and overlap
        htot = 8  # hist8 and hist9 are empty
        for ihist in range(0, htot):
            ipad = ihist % 8
            if ipad == 0:
                canvas.Clear()
                pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
                pad.Draw()
                pad.Divide(4, 2)
            pad.cd(ipad + 1)
            htit = 'd0dif_DThits_barrel_hist' + str(ihist)
            HISTS[ref][htit].Draw("hist")
            if ipad == 7 or ihist == htot - 1:
                canvas.Print(fname,
                             "Title:d0 dif for groups of 6 hits, barrel")

        htot = 10
        for ihist in range(0, htot):
            ipad = ihist % 8
            if ipad == 0:
                canvas.Clear()
                pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
                pad.Draw()
                pad.Divide(4, 2)
            pad.cd(ipad + 1)
            htit = 'd0dif_CSChits_endcap_hist' + str(ihist)
            HISTS[ref][htit].Draw("hist")
            if ipad == 7 or ihist == htot - 1:
                canvas.Print(fname,
                             "Title:d0 dif for groups of 3 hits, endcap")

        htot = 8  # hist8 and hist9 are empty
        for ihist in range(0, htot):
            ipad = ihist % 8
            if ipad == 0:
                canvas.Clear()
                pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
                pad.Draw()
                pad.Divide(4, 2)
            pad.cd(ipad + 1)
            htit = 'd0dif_DTCSChits_overlap_hist' + str(ihist)
            HISTS[ref][htit].Draw("hist")
            if ipad == 7 or ihist == htot - 1:
                canvas.Print(fname,
                             "Title:d0 dif for groups of 6 hits, overlap")

        # d0 difference for groups of 3 hits, N(stat) > 1
        htot = 8
        for ihist in range(0, htot):
            ipad = ihist % 8
            if ipad == 0:
                canvas.Clear()
                pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
                pad.Draw()
                pad.Divide(4, 2)
            pad.cd(ipad + 1)
            htit = 'd0dif_DTCSChits_Stat234_hist' + str(ihist)
            HISTS[ref][htit].Draw("hist")
            if ipad == 7 or ihist == htot - 1:
                canvas.Print(fname,
                             "Title:d0 dif for groups of 3 hits, N(stat) > 1")

        # sigma(pt)/pt vs chi2/ndof
        canvas.Clear()
        htit = 'dpt_over_pt_vs_chi2_over_ndof'
        HISTS[ref][htit].Draw("")
        canvas.Print(fname, "Title:" + htit)

        # sigma(pT)/pT per station
        canvas.Clear()
        pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
        pad.Draw()
        pad.Divide(2, 2)
        for istat in range(1, 5):
            pad.cd(istat)
            htit = 'dpt_over_pt_' + str(istat) + 'Stat'
            HISTS[ref][htit].Draw("hist")
        canvas.Print(fname, "Title:sigma(pT)/pT per station, lin scale")

        canvas.Clear()
        pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
        gStyle.SetOptLogy(1)
        pad.Draw()
        pad.Divide(2, 2)
        for istat in range(1, 5):
            pad.cd(istat)
            htit = 'dpt_over_pt_' + str(istat) + 'Stat'
            HISTS[ref][htit].Draw("hist")
        gStyle.SetOptLogy(0)
        canvas.Print(fname, "Title:sigma(pT)/pT per station, log scale")

        # sigma(pT)/pT for groups of 3 hits
        htot = 17
        for ihist in range(0, htot):
            ipad = ihist % 8
            if ipad == 0:
                canvas.Clear()
                pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
                pad.Draw()
                pad.Divide(4, 2)
            pad.cd(ipad + 1)
            htit = 'dpt_over_pt_DTCSChits_hist' + str(ihist)
            HISTS[ref][htit].Draw("hist")
            if ipad == 7 or ihist == htot - 1:
                canvas.Print(fname, "Title:sigma(pT)/pT for groups of 3 hits")

        # sigma(pT)/pT for groups of 3 hits, N(stat) > 1
        htot = 8
        for ihist in range(0, htot):
            ipad = ihist % 8
            if ipad == 0:
                canvas.Clear()
                pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
                pad.Draw()
                pad.Divide(4, 2)
            pad.cd(ipad + 1)
            htit = 'dpt_over_pt_DTCSChits_Stat234_hist' + str(ihist)
            HISTS[ref][htit].Draw("hist")
            if ipad == 7 or ihist == htot - 1:
                canvas.Print(
                    fname,
                    "Title:sigma(pT)/pT for groups of 3 hits, N(stat) > 1")

        # pT resolution in slices of sigma(pT)/pT
        htot = 10
        for ihist in range(0, htot):
            ipad = ihist % 10
            if ipad == 0:
                canvas.Clear()
                pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
                pad.Draw()
                pad.Divide(5, 2)
            pad.cd(ipad + 1)
            htit = 'pTres_for_dpt_over_pt_hist' + str(ihist)
            HISTS[ref][htit].Fit("gaus", "Q")
            #            HISTS[ref][htit].Draw("hist")
            if ipad == 9 or ihist == htot - 1:
                canvas.Print(fname, "Title:pT res in slices of sigma(pT)/pT")

        # pT resolution in slices of sigma(pT)/pT, Nhits > 12
        htot = 10
        for ihist in range(0, htot):
            ipad = ihist % 10
            if ipad == 0:
                canvas.Clear()
                pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
                pad.Draw()
                pad.Divide(5, 2)
            pad.cd(ipad + 1)
            htit = 'pTres_for_dpt_over_pt_passed_hist' + str(ihist)
            HISTS[ref][htit].Fit("gaus", "Q")
            #            HISTS[ref][htit].Draw("hist")
            if ipad == 9 or ihist == htot - 1:
                canvas.Print(
                    fname,
                    "Title:pT res in slices of sigma(pT)/pT, Nhits > 12")

        # pT pull in slices of sigma(pT)/pT
        htot = 10
        for ihist in range(0, htot):
            ipad = ihist % 10
            if ipad == 0:
                canvas.Clear()
                pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
                pad.Draw()
                pad.Divide(5, 2)
            pad.cd(ipad + 1)
            htit = 'pTpull_for_dpt_over_pt_hist' + str(ihist)
            #            HISTS[ref][htit].Fit("gaus","Q")
            HISTS[ref][htit].Draw("hist")
            if ipad == 9 or ihist == htot - 1:
                canvas.Print(fname, "Title:pT pull in slices of sigma(pT)/pT")

        # refitted muons for DSA muons failing dpT/pT cut
        canvas.Clear()
        pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
        pad.Draw()
        pad.Divide(2, 2)
        pad.cd(1)
        HISTS[ref]['eta_for_dpt_over_pt_gt_1'].Draw("hist")
        pad.cd(2)
        HISTS[ref]['pTres_ref_for_dpt_over_pt_gt_1'].Draw("hist")
        pad.cd(3)
        HISTS[ref]['dpt_over_pt_ref_for_dpt_over_pt_gt_1'].Draw("hist")
        pad.cd(4)
        HISTS[ref]['pTres_ref_for_dpt_over_pt_gt_1_ref_lt_1'].Draw("hist")
        canvas.Print(fname, "Title:refitted muons, sigma(pT)/pT > 1")

        # chi2/ndof per station
        canvas.Clear()
        pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
        pad.Draw()
        pad.Divide(2, 2)
        for istat in range(1, 5):
            pad.cd(istat)
            htit = 'chi2_over_ndof_' + str(istat) + 'Stat'
            HISTS[ref][htit].Draw("hist")
        canvas.Print(fname, "Title:chi2/ndof per station, lin scale")

        canvas.Clear()
        pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
        gStyle.SetOptLogy(1)
        pad.Draw()
        pad.Divide(2, 2)
        for istat in range(1, 5):
            pad.cd(istat)
            htit = 'chi2_over_ndof_' + str(istat) + 'Stat'
            HISTS[ref][htit].Draw("hist")
        gStyle.SetOptLogy(0)
        canvas.Print(fname, "Title:chi2/ndof per station, log scale")

        # chi2/ndof for groups of 3 hits
        htot = 17
        for ihist in range(0, htot):
            ipad = ihist % 8
            if ipad == 0:
                canvas.Clear()
                pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
                pad.Draw()
                pad.Divide(4, 2)
            pad.cd(ipad + 1)
            htit = 'chi2_over_ndof_DTCSChits_hist' + str(ihist)
            HISTS[ref][htit].Draw("hist")
            if ipad == 7 or ihist == htot - 1:
                canvas.Print(fname, "Title:chi2/ndof for groups of 3 hits")

        # chi2/ndof for groups of 3 hits, N(stat) > 1
        htot = 8
        for ihist in range(0, htot):
            ipad = ihist % 8
            if ipad == 0:
                canvas.Clear()
                pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
                pad.Draw()
                pad.Divide(4, 2)
            pad.cd(ipad + 1)
            htit = 'chi2_over_ndof_DTCSChits_Stat234_hist' + str(ihist)
            HISTS[ref][htit].Draw("hist")
            if ipad == 7 or ihist == htot - 1:
                canvas.Print(
                    fname, "Title:chi2/ndof for groups of 3 hits, N(stat) > 1")

        # pT resolution in slices of chi2/ndof
        htot = 10
        for ihist in range(0, htot):
            ipad = ihist % 10
            if ipad == 0:
                canvas.Clear()
                pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
                pad.Draw()
                pad.Divide(5, 2)
            pad.cd(ipad + 1)
            htit = 'pTres_for_chi2_over_ndof_hist' + str(ihist)
            HISTS[ref][htit].Fit("gaus", "Q")
            #            HISTS[ref][htit].Draw("hist")
            if ipad == 9 or ihist == htot - 1:
                canvas.Print(fname, "Title:pT res in slices of chi2/ndof")

        # pT resolution in slices of chi2/ndof, Nhits > 12
        htot = 10
        for ihist in range(0, htot):
            ipad = ihist % 10
            if ipad == 0:
                canvas.Clear()
                pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
                pad.Draw()
                pad.Divide(5, 2)
            pad.cd(ipad + 1)
            htit = 'pTres_for_chi2_over_ndof_passed_hist' + str(ihist)
            HISTS[ref][htit].Fit("gaus", "Q")
            #            HISTS[ref][htit].Draw("hist")
            if ipad == 9 or ihist == htot - 1:
                canvas.Print(
                    fname, "Title:pT res in slices of chi2/ndof, Nhits > 12")

        # placeholder for future histograms
        canvas.Clear()
        pad = R.TPad('pad', 'pad', 0, 0, 1, 1)
        pad.Draw()
        pad.Divide(4, 2)
        for ihist in range(16, 17):
            pad.cd(ihist - 15)
            htit = 'pTres_DTCSChits_hist' + str(ihist)
            HISTS[ref][htit].Draw("hist")
        canvas.Print(fname + ")", "Title:placeholder")
Beispiel #30
0
def makeEffPlot(quantity, criteria, fs, sp=None):
    # configy type stuff
    legs = ('All', 'Matched', 'NotMatched')
    tags = [
        quantity + '_' + ('All' + ('-4' if '-4' in criteria else '')
                          if 'All' in leg else criteria + '_' + leg)
        for leg in legs
    ]
    cols = (R.kBlack, R.kBlue, R.kRed)

    # get/add histograms
    if sp is None:
        h = {}
        for tag in tags:
            h[tag] = HistogramGetter.getHistogram(f, (fs, SIGNALPOINTS[0]),
                                                  tag).Clone()
        for SP in SIGNALPOINTS[1:]:
            for tag in tags:
                h[tag].Add(HistogramGetter.getHistogram(f, (fs, SP), tag))
    else:
        h = {}
        for tag in tags:
            h[tag] = HistogramGetter.getHistogram(f, (fs, sp), tag).Clone()

    for tag in tags:
        h[tag].Rebin(5)

    clones = {tag: h[tag].Clone() for tag in tags}
    for tag in tags[1:]:
        h[tag] = R.TGraphAsymmErrors(clones[tag], clones[tags[0]], 'cp')

    # make plots
    p = {}
    for i, tag in enumerate(tags):
        p[tag] = Plotter.Plot(h[tag], legs[i], 'l', 'px')

    # canvas, plots, min max
    canvas = Plotter.Canvas(lumi=SPLumiStr(fs, sp) if sp is not None else fs)
    for tag in tags:
        if 'All' in tag: continue
        canvas.addMainPlot(p[tag])
    canvas.setMaximum()
    canvas.firstPlot.SetMinimum(0)
    if 'Lxy' in quantity:
        canvas.firstPlot.GetXaxis().SetRangeUser(0., 330.)

    # set titles
    canvas.firstPlot.setTitles(X=clones[tags[0]].GetXaxis().GetTitle(),
                               Y='Efficiency')

    # colors
    for i, tag in enumerate(tags):
        p[tag].setColor(cols[i])

    # legend, cleanup
    canvas.makeLegend(lWidth=.2, pos='tr')
    canvas.legend.resizeHeight()

    if not (criteria in ('HPD-OC-C2S', 'HPD-C2S')
            and ARGS.CUTSTRING in ('', '_5GeV')):
        canvas.legend.moveLegend(Y=-.3)

    canvas.cleanup('pdfs/LCD_{}Eff_{}{}_HTo2XTo{}_{}.pdf'.format(
        quantity, criteria, ARGS.CUTSTRING, fs,
        SPStr(sp) if sp is not None else 'Global'))