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)))
Пример #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 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)
Пример #4
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'))
Пример #5
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'))
Пример #6
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 makeEffPlot(fs, sp):
    if sp is None:
        hNum = HG.getAddedSignalHistograms(FILES[fs], fs, 'Lxy-Num')['Lxy-Num']
        hDen = HG.getAddedSignalHistograms(FILES[fs], fs, 'Lxy-Den')['Lxy-Den']
    else:
        hNum = HG.getHistogram(FILES[fs], (fs, sp), 'Lxy-Num').Clone()
        hDen = HG.getHistogram(FILES[fs], (fs, sp), 'Lxy-Den').Clone()

        hNumInt = hNum.Integral(hNum.GetXaxis().FindBin(65.),
                                hNum.GetNbinsX() + 1)
        hDenInt = hDen.Integral(hDen.GetXaxis().FindBin(65.),
                                hDen.GetNbinsX() + 1)

        #if sp == (sp[0], sp[1], SIGNALS[sp[0]][sp[1]][0]): return
        print '{:5s} {:4d} {:3d} {:4d} ::: {:5.0f} {:5.0f} {:7.2%}'.format(
            fs, sp[0], sp[1], sp[2], hNumInt, hDenInt,
            hNumInt / hDenInt if hDenInt != 0. else 0.)

        return

    hNum.Rebin(2)
    hDen.Rebin(2)

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

    p = Plotter.Plot(g, '', '', 'p')

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

    c.addMainPlot(p)
    p.setColor(R.kBlue, which='LM')

    c.firstPlot.SetMinimum(0.)
    c.firstPlot.SetMaximum(1.)
    c.firstPlot.setTitles(X='', copy=hNum)
    c.firstPlot.setTitles(
        Y='Efficiency for pairing criteria to select correct dimuons')

    if ARGS.SQUARE:
        c.firstPlot.scaleTitleOffsets(1.1, 'X')
    c.cleanup('pdfs/PC_Lxy_{}_{}.pdf'.format(
        fs, 'Global' if sp is None else SPStr(sp)),
              mode='LUMI')
Пример #8
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)
Пример #11
0
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'))
def makeEffPlot(fs, sp):
    if sp is None:
        hNum = HG.getAddedSignalHistograms(FILES[fs], fs,
                                           ['nRec' + MUON for MUON in MUONS])
        hDen = HG.getAddedSignalHistograms(FILES[fs], fs,
                                           ['nGen' + 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:
        hNum, hDen = {}, {}
        for MUON in MUONS:
            hNum['nRec' + MUON] = HG.getHistogram(FILES[fs], (fs, sp),
                                                  'nRec' + MUON).Clone()
            hDen['nGen' + MUON] = HG.getHistogram(FILES[fs], (fs, sp),
                                                  'nGen' + 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}}
    g, p = {}, {}
    for MUON in MUONS:
        hNum['nRec' + MUON].Rebin(10)
        hDen['nGen' + MUON].Rebin(10)
        g[MUON] = R.TGraphAsymmErrors(hNum['nRec' + MUON], hDen['nGen' + MUON],
                                      'cp')
        p[MUON] = Plotter.Plot(g[MUON], MUON, 'l', 'p')
        c.addMainPlot(p[MUON])
        p[MUON].setColor(pretty[MUON]['col'], which='LM')

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

    c.firstPlot.SetMinimum(0.)
    c.firstPlot.SetMaximum(1.)
    c.firstPlot.setTitles(X='', Y='', copy=hNum['nRecDSA'])
    if ARGS.SQUARE:
        c.firstPlot.scaleTitleOffsets(1.1, 'X')

    c.cleanup('pdfs/REFF_Lxy{}_{}_{}.pdf'.format(
        '_Trig' if ARGS.TRIGGER else '', fs,
        'Global' if sp is None else SPStr(sp)),
              mode='LUMI')
Пример #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 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'))
Пример #15
0
def makeRepEffectPlots(sp=None):

    lumi = 'H#rightarrow2X#rightarrow2#mu'
    if sp is None:
        lumi += ', all samples combined'
    else:
        lumi += ' ({} GeV, {} GeV, {} mm)'.format(*sp)

    hkeys = ('Lxy-before', 'Lxy-after')
    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()

    nPass = HISTS['Lxy-after'].Integral(
        HISTS['Lxy-after'].GetXaxis().FindBin(65.),
        HISTS['Lxy-after'].GetNbinsX() + 1)
    nTot = HISTS['Lxy-before'].Integral(
        HISTS['Lxy-before'].GetXaxis().FindBin(65.),
        HISTS['Lxy-before'].GetNbinsX() + 1)
    print nPass / nTot

    for key in hkeys:
        HISTS[key].Rebin(2)
    g = R.TGraphAsymmErrors(HISTS['Lxy-after'], HISTS['Lxy-before'], 'cp')
    p = Plotter.Plot(g, '', '', 'p')

    canvas = Plotter.Canvas(lumi=lumi, cWidth=600 if ARGS.SQUARE else 800)
    canvas.addMainPlot(p)
    p.setColor(R.kBlue)

    canvas.firstPlot.setTitles(X='generated L_{xy} [cm]',
                               Y='Dimuons after / before association')

    canvas.firstPlot.SetMaximum(1.)
    canvas.firstPlot.SetMinimum(0.)

    if ARGS.SQUARE:
        canvas.firstPlot.scaleTitleOffsets(1.1, 'X')
    canvas.cleanup('pdfs/REPEFF_Signal_{}.pdf'.format(
        'Global' if sp is None else SPStr(sp)),
                   mode='LUMI')
Пример #16
0
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'))
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')
Пример #18
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)
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)))
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')
Пример #23
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
Пример #24
0
def getHistogram(f, fs, sp, quantity, which):
    return f.Get(quantity+'_'+which+'_HTo2XTo'+fs+'_'+SPStr(sp)).Clone()
Пример #25
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))
Пример #26
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)
Пример #27
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)
Пример #28
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)))
Пример #29
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)))
Пример #30
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)