Exemplo n.º 1
0
def draw_efficiency(eff_s, rej_b, field, category, textsize=22):

    xtitle = get_xtitle(field)

    c = Canvas()
    c.SetGridx()
    c.SetGridy()
    eff_s.painted_graph.yaxis.SetRangeUser(0, 1.10)
    eff_s.painted_graph.yaxis.title = 'Efficiency'
    eff_s.painted_graph.xaxis.title = xtitle
    eff_s.painted_graph.Draw('AP')
    rej_b.color = 'red'
    rej_b.markerstyle = 'square'
    rej_b.painted_graph.Draw('sameP')
    right_axis = ROOT.TGaxis(ROOT.gPad.GetUxmax(), ROOT.gPad.GetUymin(),
                             ROOT.gPad.GetUxmax(), ROOT.gPad.GetUymax(), 0,
                             1.10, 510, "+L")
    right_axis.SetLineColor(ROOT.kRed)
    right_axis.SetLabelColor(ROOT.kRed)
    right_axis.SetTextColor(ROOT.kRed)
    right_axis.SetTitle('Rejection = 1 - #epsilon_{B}')
    right_axis.Draw('same')
    ROOT.gStyle.SetPadTickY(0)
    ROOT.gPad.Update()
    ROOT.gStyle.SetPadTickY(1)
    label = ROOT.TLatex(c.GetLeftMargin() + 0.04, 0.9, category.label)
    label.SetNDC()
    label.SetTextFont(43)
    label.SetTextSize(textsize)
    label.Draw()
    leg = Legend([eff_s, rej_b], pad=c)
    # textsize=20, leftmargin=0.6, topmargin=0.6)
    leg.Draw('same')
    return c
Exemplo n.º 2
0
def test_init():

    l = Legend(2)
    h = Hist(10, 0, 1)
    l.AddEntry(h)
    hr = TH1D("test", "", 10, 0, 1)
    l.AddEntry(hr)
def extract_MET(f_tt, f_qcd, f_wjet):

    # get trees from files
    t_tt = f_tt.Get("Delphes")
    t_qcd = f_qcd.Get("Delphes")
    t_wjet = f_wjet.Get("Delphes")

    # get number of entries
    tt_n_entries = t_tt.GetEntries()
    qcd_n_entries = t_qcd.GetEntries()
    wjet_n_entries = t_wjet.GetEntries()

    # define leaves
    var_tt = "MissingET.MET"
    var_qcd = "MissingET.MET"
    var_wjet = "MissingET.MET"

    leaf_tt = t_tt.GetLeaf(var_tt)
    leaf_qcd = t_qcd.GetLeaf(var_qcd)
    leaf_wjet = t_wjet.GetLeaf(var_wjet)

    # create the histograms
    MET_tt = Hist(MET_NBINS, MET_NLO, MET_NHI, title='MET_tt', legendstyle='L')
    MET_qcd = Hist(MET_NBINS,
                   MET_NLO,
                   MET_NHI,
                   title='MET_qcd',
                   legendstyle='L')
    MET_wjet = Hist(MET_NBINS,
                    MET_NLO,
                    MET_NHI,
                    title='MET_wjet',
                    legendstyle='L')

    # FILLING THE TREE
    fill_MET_tree(tt_n_entries, t_tt, leaf_tt, MET_tt)
    fill_MET_tree(qcd_n_entries, t_qcd, leaf_qcd, MET_qcd)
    fill_MET_tree(wjet_n_entries, t_wjet, leaf_wjet, MET_wjet)

    #set line colors
    MET_tt.SetLineColor('blue')
    MET_qcd.SetLineColor('green')
    MET_wjet.SetLineColor('red')

    #begin drawing stuff
    c1 = Canvas()
    MET_qcd.SetStats(0)
    MET_qcd.Draw('HIST')
    MET_tt.Draw('HIST SAME')
    MET_wjet.Draw('HIST SAME')

    #make legend
    l1 = Legend([MET_tt, MET_qcd, MET_wjet], textfont=42, textsize=.03)
    l1.Draw()

    #save as pdf
    c1.SaveAs("../plots/MET_plots/MET.pdf")

    #make the plots wait on screen
    wait(True)
Exemplo n.º 4
0
    def __make_overlay(self, hists, fits, labels, ytitle, suffix=""):
        with preserve_current_style():
            # Draw each resolution (with fit)
            xtitle = self.online_title
            canvas = draw(hists,
                          draw_args={
                              "xtitle": xtitle,
                              "ytitle": ytitle
                          })
            if fits:
                for fit, hist in zip(fits, hists):
                    fit["asymmetric"].linecolor = hist.GetLineColor()
                    fit["asymmetric"].Draw("same")

            # Add labels
            label_canvas()

            # Add a legend
            legend = Legend(len(hists),
                            header="Pile-up bin",
                            topmargin=0.35,
                            entryheight=0.035)
            for hist, label in zip(hists, labels):
                legend.AddEntry(hist, label)
            legend.SetBorderSize(0)
            legend.Draw()

            # Save canvas to file
            name = self.filename_format.format(pileup="all")
            self.save_canvas(canvas, name + suffix)
Exemplo n.º 5
0
def draw_hists(hists,
               field,
               category,
               textsize=22,
               logy=False,
               unit_area=False):

    xtitle = get_xtitle(field)

    c = Canvas()
    c.SetGridx()
    c.SetGridy()
    c.SetLogy(logy)

    if not isinstance(hists, (list, tuple)):
        hists = [hists]

    if unit_area:
        for h in hists:
            if h.integral() != 0:
                h /= h.integral()

    hists[0].xaxis.title = xtitle
    hists[0].yaxis.title = 'Arbitrary Unit'

    y_max = get_ymax(hists)
    hists[0].yaxis.SetRangeUser(0., 1.05 * y_max)
    hists[0].Draw('HIST')

    colors = [
        'black',
        'red',
        'orange',
        'blue',
        'green',
        'purple',
        'yellow',
        'pink',
    ]
    if len(hists) > len(colors):
        colors = len(hists) * colors
    for hist, col in zip(hists, colors):
        hist.color = col
        hist.color = col
        hist.fillstyle = 'hollow'
        hist.markersize = 0
        hist.linewidth = 2
        hist.linestyle = 'solid'
        hist.drawstyle = 'hist E0'
        hist.legendstyle = 'l'
        hist.Draw('SAMEHIST')
    label = ROOT.TLatex(c.GetLeftMargin() + 0.04, 0.9, category.label)
    label.SetNDC()
    label.SetTextFont(43)
    label.SetTextSize(textsize)
    label.Draw()
    leg = Legend(hists, pad=c, textsize=20)
    # textsize=20, leftmargin=0.6, topmargin=0.6)
    leg.Draw('same')
    return c
Exemplo n.º 6
0
 def make_a_legend(entries=5):
     vh_legend = Legend(
         entries, rightmargin=0.26, topmargin=0.05, leftmargin=0.375)
     vh_legend.SetEntrySeparation(0.0)
     vh_legend.SetMargin(0.35)
     vh_legend.SetBorderSize(0)
     return vh_legend
Exemplo n.º 7
0
    def __make_overlay(self, pileup, threshold, hists, fits, labels, header):
        with preserve_current_style():
            # Draw each efficiency (with fit)
            canvas = draw(hists,
                          draw_args={
                              "xtitle": self.offline_title,
                              "ytitle": "Efficiency"
                          })
            if len(fits) > 0:
                for fit, hist in zip(fits, hists):
                    fit["asymmetric"].linecolor = hist.GetLineColor()
                    fit["asymmetric"].Draw("same")

            # Add labels
            label_canvas()

            # Add a legend
            legend = Legend(
                len(hists),
                header=self.legend_title,
                topmargin=0.35,
                rightmargin=0.3,
                leftmargin=0.7,
                textsize=0.035,
                entryheight=0.035,
            )
            for hist, label in zip(hists, labels):
                legend.AddEntry(hist, label)
            legend.SetBorderSize(0)
            legend.Draw()

            # Save canvas to file
            name = self.filename_format.format(pileup=pileup,
                                               threshold=threshold)
            self.save_canvas(canvas, name)
Exemplo n.º 8
0
    def __make_overlay(self, hists, fits, labels, thresholds, suffix=""):
        with preserve_current_style():
            # Draw each rate vs pileup (with fit)
            xtitle = "< \\mu >"
            ytitle = "Rate (kHz)"
            canvas = draw(hists, draw_args={"xtitle": xtitle, "ytitle": ytitle, "xlimits": (20, 50), "ylimits": (0, 5)})
            if fits:
                for fit, hist in zip(fits, hists):
                    fit["asymmetric"].linecolor = hist.GetLineColor()
                    fit["asymmetric"].Draw("same")

            # Add labels
            label_canvas()

            # Add a legend
            legend = Legend(
                len(hists),
                header=self.legend_title,
                topmargin=0.02,
                leftmargin=0.22,
                rightmargin=0.78,
                textsize=0.025,
                entryheight=0.028,
            )

            for hist, label in zip(hists, labels):
                legend.AddEntry(hist, label)

            legend.SetBorderSize(0)
            legend.Draw()

            # Save canvas to file
            name = self.filename_format.format(threshold=thresholds[0])
            self.save_canvas(canvas, name + suffix)
Exemplo n.º 9
0
def draw_DR(DR_tt, DR_qcd, DR_wjet):

    #set line colors
    DR_tt.SetLineColor(4)
    DR_qcd.SetLineColor(8)
    DR_wjet.SetLineColor(2)

    DR_tt.legendstyle = 'L'
    DR_qcd.legendstyle = 'L'
    DR_wjet.legendstyle = 'L'

    #begin drawing stuff
    c1 = Canvas()
    DR_qcd.SetStats(0)
    DR_qcd.Draw('HIST')
    DR_tt.Draw('HIST SAME')
    DR_wjet.Draw('HIST SAME')

    #make legend
    l1 = Legend([DR_tt, DR_qcd, DR_wjet], textfont=42, textsize=.03)
    l1.Draw()

    #save as pdf
    c1.SaveAs("DeltaR.pdf")

    #make the plots wait on screen
    wait(True)
Exemplo n.º 10
0
def plotResults(variable, data, templates, results):

    resCan = Canvas()
    leg = Legend(nTemplates + 2)

    data.Draw('PE')
    leg.AddEntry(data, style='LEP')
    nBins = len(inputTemplates[variable]['data'][whichBinFromFile])
    h_tSumAfter = Hist(nBins, 0, nBins, title='after_' + variable)

    if useT1:
        plotTemplateAfter(templates[tNames['t1']], results[tNames['t1']][0],
                          resCan, leg, h_tSumAfter)
        pass
    if useT2:
        plotTemplateAfter(templates[tNames['t2']], results[tNames['t2']][0],
                          resCan, leg, h_tSumAfter)
        pass
    if useT3:
        plotTemplateAfter(templates[tNames['t3']], results[tNames['t3']][0],
                          resCan, leg, h_tSumAfter)
        pass
    if useT4:
        plotTemplateAfter(templates[tNames['t4']], results[tNames['t4']][0],
                          resCan, leg, h_tSumAfter)
        pass
    leg.Draw()

    h_tSumAfter.SetLineColor(2)
    h_tSumAfter.SetLineStyle(7)
    h_tSumAfter.SetMarkerSize(0)
    h_tSumAfter.Draw('SAME HIST')
    resCan.Update()

    return resCan, h_tSumAfter
Exemplo n.º 11
0
def routine(chan, var):
    hs_b, hs_a = [], []
    htitle = None
    numbers = defaultdict(dict)

    # before
    chandir = getattr(beforef, 'ch' + chan)
    for it, sigtag in enumerate(sigTAGS):
        h = getattr(getattr(chandir.sig, sigtag), var)  # Hist
        if htitle is None: htitle = h.title
        h.title = sigtag + ' w/ mu iso'
        h.drawstyle = 'hist'
        h.color = sigCOLORS[it]
        h.linewidth = 2
        h.legendstyle = 'L'
        hs_b.append(h)
        numbers[sigtag]['before'] = h.integral()

    # after
    chandir = getattr(afterf, 'ch' + chan)
    for it, sigtag in enumerate(sigTAGS):
        h = getattr(getattr(chandir.sig, sigtag), var)  # Hist
        h.title = 'w/o mu iso'
        h.drawstyle = 'hist'
        h.color = sigCOLORS[it]
        h.linewidth = 2
        h.linestyle = 'dashed'
        h.legendstyle = 'L'
        hs_a.append(h)
        numbers[sigtag]['after'] = h.integral()

    print('>', chan, var)
    df = pd.DataFrame(numbers).T
    df['incr %'] = (df['after'] - df['before']) / df['before'] * 100
    print(df[['before', 'after', 'incr %']])
    draw(hs_b + hs_a, logy=True)

    legend = Legend(len(hs_b),
                    pad=canvas,
                    margin=0.25,
                    leftmargin=0.3,
                    topmargin=0.02,
                    entrysep=0.01,
                    entryheight=0.02,
                    textsize=10)
    legend.SetNColumns(2)
    for _b, _a in zip(hs_b, hs_a):
        legend.AddEntry(_b)
        legend.AddEntry(_a)
    legend.Draw()

    title = TitleAsLatex('[{}] '.format(chan.replace('mu', '#mu')) + htitle)
    title.Draw()
    draw_labels('59.74 fb^{-1} (13 TeV)',
                cms_position='left',
                extra_text='work-in-progress')

    canvas.SaveAs('{}/ch{}_{}.pdf'.format(outdir, chan, var))
    canvas.Clear()
Exemplo n.º 12
0
def routine(chan, cutbin, var, title):
    hs=[]
    chandir = getattr(f, 'ch'+chan)

    effs=OrderedDict()
    for it, sigtag in enumerate(sigTAGS):
        h = getattr(getattr(chandir.sig, sigtag), var) # Hist
        h_total = h.integral(overflow=True)

        h_ = h.clone()
        for i in range(1, h.nbins()+1):
            h_[i] = h.integral(1, xbin2=i)/h_total
            h_[i].error = 0
            if i==cutbin: effs[sigtag] = h.integral(1, xbin2=i)/h_total
        h_.title = sigtag
        h_.drawstyle = 'hist'
        h_.color = sigCOLORS[it]
        h_.linewidth = 2
        h_.legendstyle='L'
        hs.append(h_)
    mineff = min(effs.values())
    aveeff = sum(effs.values())/len(effs)
    effs['sig_ave'] = aveeff
    effs['sig_min'] = mineff

    h = getattr(chandir.data, var)
    h_total = h.integral(overflow=True)
    if h_total!=0:
        h_ = h.empty_clone()
        for i in range(1, h.nbins()+1):
            h_[i] = h.integral(1, xbin2=i)/h_total
            h_[i].error = 0
            if i==cutbin: effs['data'] = h.integral(1, xbin2=i)/h_total
        h_.drawstyle = 'hist'
        h_.title='cosmic shower'
        h_.color = 'black'
        h_.linestyle = 'dashed'
        h_.legendstyle='L'
        h_.linewidth=2
        hs.append(h_)


    print('>',chan, var)
    maxlen = max([len(k) for k in effs])
    for k in effs:
        fmt = '{:%d}:{:.2f}'%(maxlen+2)+'%'
        print(fmt.format(k, effs[k]*100))


    legend = Legend(hs, pad=c, margin=0.1, topmargin=0.02, entryheight=0.02, textsize=12)
    axes, limits =draw(hs, ylimits=(0., 1.5), ytitle='(backward) cut efficiency',)
    legend.Draw()
    title = TitleAsLatex('[{}] '.format(chan.replace('mu', '#mu'))+title)
    title.Draw()
    draw_labels('59.74 fb^{-1} (13 TeV)', cms_position='left', extra_text='work-in-progress')
    ROOT.gPad.SetGrid()

    c.SaveAs('{}/ch{}_{}.pdf'.format(outdir, chan, var))
    c.Clear()
Exemplo n.º 13
0
def test_init():

    with invisible_canvas():
        l = Legend(2)
        h = Hist(10, 0, 1)
        l.AddEntry(h)
        hr = TH1D("test", "", 10, 0, 1)
        l.AddEntry(hr)
Exemplo n.º 14
0
def do_stuff(file_name, plot=True):
    tiq_data = TIQData(file_name)
    NFRAMES = 100
    LFRAMES = 1024

    tiq_data.read(nframes=NFRAMES, lframes=LFRAMES, sframes=1)
    center = tiq_data.center

    # do fft
    ff, pp, _ = tiq_data.get_fft()

    freq_lower = center + ff[0] / 1e6
    freq_upper = center + ff[-1] / 1e6

    # create hist
    h1 = Hist(NFRAMES * LFRAMES,
              freq_lower,
              freq_upper,
              name='h1',
              title='Frequency Spectrum',
              drawstyle='hist',
              legendstyle='F',
              fillstyle='/',
              linecolor='green')

    for i in range(len(pp)):
        h1.set_bin_content(i, pp[i])

    # set visual attributes
    h1.GetXaxis().SetTitle('Freuqency [MHz]')
    h1.linecolor = 'green'
    # h1.fillcolor = 'green'
    # h1.fillstyle = '/'

    if plot:
        # plot
        c = Canvas(name='c1', width=700, height=500)
        c.set_left_margin(0.15)
        c.set_bottom_margin(0.15)
        c.set_top_margin(0.10)
        c.set_right_margin(0.05)
        c.toggle_editor()
        c.toggle_event_status()
        c.toggle_tool_bar()
        # c.set_crosshair()

        h1.Draw()

        # create the legend
        legend = Legend([h1],
                        pad=c,
                        header='Header',
                        leftmargin=0.05,
                        rightmargin=0.5)
        legend.Draw()

        # wait for key press
        wait()
Exemplo n.º 15
0
 def _create_legend(self):
     nentries = len([pdic['legend_title'] for pdic in self._plottables if pdic['legend_title'] != ''])
     leg = Legend(nentries, leftmargin=0, rightmargin=0, entrysep=0.01,
                  textsize=self.style.legendSize, textfont=43, margin=0.1, )
     if self.legend.title:
         leg.SetHeader(self.legend.title)
     leg.SetBorderSize(0)  # no box
     leg.SetFillStyle(0)   # transparent background of legend TPave(!)
     return leg
Exemplo n.º 16
0
    def __make_overlay(self, pileup, threshold, hists, fits, labels, header):
        with preserve_current_style():
            name = self.filename_format.format(pileup=pileup,
                                               threshold=threshold)

            xmin = hists[0].GetTotalHistogram().GetBinLowEdge(1)
            xmax = hists[0].GetTotalHistogram().GetBinLowEdge(
                hists[0].GetTotalHistogram().GetNbinsX() + 1)

            # Draw each efficiency (with fit)
            draw_args = {
                "xtitle": self.offline_title,
                "ytitle": "Efficiency",
                "xlimits": [xmin, xmax]
            }

            canvas = draw(hists, draw_args=draw_args)
            if len(fits) > 0:
                for fit, hist in zip(fits, hists):
                    fit["asymmetric"].linecolor = hist.GetLineColor()
                    fit["asymmetric"].Draw("same")

            # Add labels
            label_canvas()

            # Add a legend
            legend = Legend(
                len(hists),
                header=self.legend_title,
                topmargin=0.35,
                rightmargin=0.3,
                leftmargin=0.7,
                textsize=0.025,
                entryheight=0.028,
            )

            for hist, label in zip(hists, labels):
                legend.AddEntry(hist, label)

            legend.SetBorderSize(0)
            legend.Draw()

            for val in [0.25, 0.5, 0.75, 0.95, 1.]:
                line = ROOT.TLine(xmin, val, xmax, val)
                line.SetLineStyle("dashed")
                line.SetLineColor(15)
                line.Draw()

            for thresh in self.thresholds.bins:
                line = ROOT.TLine(thresh, 0., thresh, 1.)
                line.SetLineStyle("dashed")
                line.SetLineColor(15)
                line.Draw()

            # Save canvas to file
            self.save_canvas(canvas, name)
Exemplo n.º 17
0
def routine(chan):
    hs = []
    effs = OrderedDict()
    chandir = getattr(f, 'ch'+chan)
    for t in chandir.sig.keys():
        sigtag = t.name
        h = getattr(getattr(chandir.sig, sigtag), 'njet') # Hist
        h_total = h.integral(overflow=True)
        if h_total==0: continue

        h_ = h.clone()
        for i in range(1, h.nbins()+1):
            h_[i] = h.integral(xbin2=i)/h_total
            h_[i].error = 0
            if i==2: effs[sigtag] = h.integral(xbin2=i)/h_total
        h_.title = sigtag
        h_.drawstyle = 'PLC hist'
        h_.legendstyle='L'
        hs.append(h_)
    mineff = min(effs.values())
    aveeff = sum(effs.values())/len(effs)
    effs['sig_ave'] = aveeff
    effs['sig_min'] = mineff

    for h in getattr(chandir.bkg, 'njet'):
        h_total = h.integral(overflow=True)
        if h_total==0: continue
        h_ = h.empty_clone()
        for i in range(1, h.nbins()+1):
            h_[i] = h.integral(xbin2=i)/h_total
            h_[i].error = 0
            if i==2: effs[h.title] = h.integral(xbin2=i)/h_total
        h_.drawstyle = 'hist'
        h_.title=h.title
        h_.color = bkgCOLORS[h.title]
        h_.linestyle = 'dashed'
        h_.legendstyle='L'
        h_.linewidth=2
        hs.append(h_)

    print('>',chan)
    maxlen = max([len(k) for k in effs])
    for k in effs:
        fmt = '{:%d}:{:.2f}'%(maxlen+2)+'%'
        print(fmt.format(k, effs[k]*100))

    legend = Legend(hs, pad=c, margin=0.1, topmargin=0.02, entryheight=0.02, textsize=12)
    axes, limits =draw(hs, ylimits=(0., 1.5), ytitle='(backward) cut efficiency',)
    legend.Draw()
    title = TitleAsLatex('[{}] Njet (pT>50GeV) efficiency'.format(chan.replace('mu', '#mu')))
    title.Draw()
    draw_labels('59.74 fb^{-1} (13 TeV)', cms_position='left', extra_text='work-in-progress')
    ROOT.gPad.SetGrid()

    c.SaveAs('{}/ch{}_njet.pdf'.format(outdir, chan))
    c.Clear()
Exemplo n.º 18
0
    def make_composition(parentDirectory,
                         denomHistName,
                         outfn,
                         numerHistNames={},
                         titleText=None,
                         binsToMerge=None):
        sampleNames = [k.name for k in parentDirectory.keys()]
        if len(sampleNames) == 0:
            raise ValueError('No sample directory found!')

        hDenom = getattr(getattr(parentDirectory, sampleNames[0]),
                         denomHistName).clone()
        if binsToMerge: hDenom = hDenom.merge_bins(binsToMerge)
        hNumerS = {
            label : getattr(getattr(parentDirectory, sampleNames[0]), hName).clone() \
            for label, hName in numerHistNames.items()
            }

        for s in sampleNames[1:]:
            hDenom.Add(
                getattr(getattr(parentDirectory, s), denomHistName).clone())
            for label, hName in numerHistNames.items():
                hNumerS[label].Add(
                    getattr(getattr(parentDirectory, s), hName).clone())

        # stack up
        _stack = HistStack()
        for i, (label, h) in enumerate(hNumerS.items()):
            if binsToMerge: h = h.merge_bins(binsToMerge)
            h.title = label
            h.fillcolor = sigCOLORS[i + 6]
            h.drawstyle = 'hist'
            h.fillstyle = 'solid'
            h.linewidth = 0
            h.legendstyle = 'F'
            _stack.Add(h)

        draw([_stack, hDenom], logy=False)

        if titleText:
            title = TitleAsLatex(titleText)
            title.Draw()

        leg = Legend([hDenom, _stack],
                     margin=0.25,
                     leftmargin=0.45,
                     topmargin=0.02,
                     entrysep=0.01,
                     entryheight=0.02,
                     textsize=12)
        leg.Draw()

        canvas.SaveAs(outfn)
        canvas.clear()
Exemplo n.º 19
0
def plot_pt(chan, obj):
    assert (chan in ['2mu2e', '4mu'])
    assert (obj in ['mu', 'el'])

    chandir = getattr(f, 'ch' + chan)
    masskeys_ = [k.name for k in chandir.keys()]
    # mzd=5
    masskeys = [k for k in masskeys_ if k.endswith('mA-5')]
    masskeys.sort(key=get_first)
    hs = []
    for i, masskey in enumerate(masskeys):
        massdir = getattr(chandir, masskey)
        lifetimekeys_ = [k.name for k in massdir.keys()]
        # lxy=3
        lifetimekeys = [k for k in lifetimekeys_ if k.startswith('lxy-3')]
        if not lifetimekeys: continue

        lifetimedir = getattr(massdir, lifetimekeys[0])
        h = getattr(lifetimedir, '%s0pt' % obj)

        h.scale(1. / h.integral())
        h.title = 'm_{#chi#chi} = %d GeV' % int(get_first(masskey))
        h.color = sigCOLORS[i]
        h.legendstyle = 'LEP'
        h.markersize = 0.5

        hs.append(h)

    legItems = [h for h in hs]
    draw(hs, logy=True, ytitle='Normalized counts/1GeV')
    legheader = 'm_{Z_{d}} = 5 GeV, lxy = 3 cm'
    leg = Legend(legItems,
                 pad=canvas,
                 margin=0.25,
                 topmargin=0.02,
                 entryheight=0.02,
                 entrysep=0.01,
                 textsize=12,
                 header=legheader)
    leg.Draw()

    if obj == 'mu': htitle = 'leading #mu p_{T}'
    elif obj == 'el': htitle = 'leading electron p_{T}'
    title = TitleAsLatex('[{}] '.format(chan.replace('mu', '#mu')) + htitle)
    title.Draw()
    draw_labels('59.74 fb^{-1} (13 TeV)',
                cms_position='left',
                extra_text='Simulation Preliminary')

    canvas.SaveAs('{}/ch{}_{}0pt.pdf'.format(outdir, chan, obj))
    canvas.clear()
Exemplo n.º 20
0
    def compare_efficiency(parentDirectory,
                           efficiencyName,
                           titleText,
                           outfn,
                           baseLegendText=None,
                           binsToMerge=None,
                           numerAdds=[],
                           additionalLegendTexts=[]):
        base_efficiency = get_efficiency(parentDirectory,
                                         efficiencyName + '__total',
                                         efficiencyName + '__match',
                                         binsToMerge=binsToMerge,
                                         numerAdd=None).graph
        base_efficiency.drawstyle = 'AP'
        base_efficiency.markercolor = sigCOLORS[6]
        base_efficiency.linecolor = sigCOLORS[6]

        comp_efficiencies = []
        for numerAdd in numerAdds:
            g = get_efficiency(parentDirectory,
                               efficiencyName + '__total',
                               efficiencyName + '__match',
                               binsToMerge=binsToMerge,
                               numerAdd=numerAdd).graph
            comp_efficiencies.append(g)
        for i, g in enumerate(comp_efficiencies):
            g.drawstyle = 'P'
            g.markercolor = sigCOLORS[i + 7]
            g.linecolor = sigCOLORS[i + 7]
        draw([base_efficiency] + [g for g in comp_efficiencies],
             xtitle='Lxy [cm]',
             ytitle='Efficiency')

        title = TitleAsLatex(titleText)
        title.Draw()

        if baseLegendText:
            leg = Legend(1 + len(numerAdds),
                         margin=0.25,
                         leftmargin=0.45,
                         topmargin=0.02,
                         entrysep=0.01,
                         entryheight=0.03,
                         textsize=14)
            leg.AddEntry(base_efficiency, baseLegendText, style='LEP')
            for g, t in zip(comp_efficiencies, additionalLegendTexts):
                leg.AddEntry(g, t, style='LEP')
            leg.Draw()

        canvas.SaveAs(outfn)
        canvas.clear()
Exemplo n.º 21
0
def plot_boundstatemass(chan):
    assert (chan in ['2mu2e', '4mu'])

    chandir = getattr(f, 'ch' + chan)
    masskeys_ = [k.name for k in chandir.keys()]
    # mzd=0.25
    masskeys = [k for k in masskeys_ if k.endswith('mA-0p25')]
    masskeys.sort(key=get_first)
    hs = []
    htitle = None
    for i, masskey in enumerate(masskeys):
        massdir = getattr(chandir, masskey)
        lifetimekeys_ = [k.name for k in massdir.keys()]
        # lxy=150
        lifetimekeys = [k for k in lifetimekeys_ if k.startswith('lxy-150')]
        if not lifetimekeys: continue

        lifetimedir = getattr(massdir, lifetimekeys[0])
        h = getattr(lifetimedir, 'psmass')

        h.scale(1. / h.integral())
        if htitle is None: htitle = h.title
        h.title = 'm_{#chi#chi} = %d GeV' % int(get_first(masskey))
        h.color = sigCOLORS[i]
        h.legendstyle = 'LEP'
        h.markersize = 0.5

        hs.append(h)

    legItems = [h for h in hs]
    ROOT.gPad.SetLogy(0)
    draw(hs, logy=False, ytitle='Normalized counts/1GeV')
    legheader = 'm_{Z_{d}} = 0.25 GeV, lxy = 150 cm'
    leg = Legend(legItems,
                 pad=canvas,
                 margin=0.25,
                 topmargin=0.02,
                 entryheight=0.02,
                 entrysep=0.01,
                 textsize=12,
                 header=legheader)
    leg.Draw()

    title = TitleAsLatex('[{}] '.format(chan.replace('mu', '#mu')) + htitle)
    title.Draw()
    draw_labels('59.74 fb^{-1} (13 TeV)',
                cms_position='left',
                extra_text='Simulation Preliminary')

    canvas.SaveAs('{}/ch{}_boundstatemass.pdf'.format(outdir, chan))
    canvas.clear()
Exemplo n.º 22
0
def routine(varname, chan):
    htitle = None
    hs = []
    chandir = getattr(f, 'ch' + chan)

    bkghs = getattr(chandir.bkg, varname).GetHists()
    bkgh = bkghs.pop()
    for h in bkghs:
        bkgh.Add(h)
    for it, sigtag in enumerate(sigTAGS):
        h = getattr(getattr(chandir.sig, sigtag), varname)  # Hist
        if not htitle: htitle = h.title

        h_ = h.empty_clone()
        for i in range(1, h.nbins() + 1):
            sigN = h.integral(xbin1=i, overflow=True)
            bkgN = bkgh.integral(xbin1=i, overflow=True)
            if bkgN == 0: h[i] = h[i - 1]
            else: h_[i] = sigN / math.sqrt(bkgN)
            ## tried s/sqrt(b), s/sqrt(s+b), 2(sqrt(s+b)-sqrt(b))
            ## shape slightly different, trend similar, conclusion remain the same
            # h_[i] = 2*(math.sqrt(sigN+bkgN)-math.sqrt(bkgN))
            h_[i].error = 0
        h_.title = sigtag
        h_.color = sigCOLORS[it]
        h_.drawstyle = 'hist'  #'PLC hist'
        h_.linewidth = 2
        h_.legendstyle = 'L'
        h_.xaxis.SetTitle(h.xaxis.GetTitle())
        h_.yaxis.SetTitle('(forward) s/#sqrt{b}')
        hs.append(h_)

    legend = Legend(hs,
                    pad=c,
                    margin=0.25,
                    topmargin=0.02,
                    entrysep=0.01,
                    entryheight=0.02,
                    textsize=11)
    axes, limits = draw(hs, logy=True, logx=False, ylimits=(1e-5, 1e3))
    ROOT.gPad.SetGrid()
    legend.Draw()
    title = TitleAsLatex('[{}] {}'.format(chan.replace('mu', '#mu'), htitle))
    title.Draw()
    draw_labels('59.74 fb^{-1} (13 TeV)',
                cms_position='left',
                extra_text='work-in-progress')

    c.SaveAs('{}/ch{}_{}.pdf'.format(outdir, chan, varname))
    c.Clear()
Exemplo n.º 23
0
    def __make_overlay(self,
                       hists,
                       fits,
                       labels,
                       ytitle,
                       suffix="",
                       setlogy=False):
        with preserve_current_style():
            # Draw each resolution (with fit)

            xtitle = ""
            if 'Jet' in self.online_title:
                xtitle = "Jet #it{p}_{T} (GeV)"
            if 'HT' in self.online_title:
                xtitle = "#it{H}_{T} (GeV)"
            if 'MET' in self.online_title:
                xtitle = "#it{E}_{T}^{miss} (GeV)"

            canvas = draw(hists,
                          draw_args={
                              "xtitle": xtitle,
                              "ytitle": ytitle,
                              "logy": setlogy,
                              "ylimits": (0.1, 50000)
                          })
            if fits:
                for fit, hist in zip(fits, hists):
                    fit["asymmetric"].linecolor = hist.GetLineColor()
                    fit["asymmetric"].Draw("same")

            # Add labels
            label_canvas()

            # Add a legend
            legend = Legend(len(hists),
                            header=self.legend_title,
                            topmargin=0.35,
                            rightmargin=0.2,
                            leftmargin=0.8,
                            entryheight=0.028,
                            textsize=0.03)
            for hist, label in zip(hists, labels):
                legend.AddEntry(hist, label)
            legend.SetBorderSize(0)
            legend.Draw()

            # Save canvas to file
            name = self.filename_format.format(pileup="all")
            self.save_canvas(canvas, name + suffix)
Exemplo n.º 24
0
def draw_curve_7(_func, name, title, ylow, yhigh):
    """ Draw 7TeV trigger efficiency curves """
    graphs = []
    for (trigger, color) in triggers:
        tool = ROOT.TauTriggerCorrections(
            os.path.join(base, 'triggerSF_%s.root' % trigger))
        func = getattr(tool, _func)
        eff = map(lambda x: func(x, 0), pt)
        eff_low = map(lambda x: func(x, -1), pt)
        eff_high = map(lambda x: func(x, 1), pt)
        graph = Graph(len(pt), name=trigger)
        for i, (p, e, e_low,
                e_high) in enumerate(zip(pt, eff, eff_low, eff_high)):
            graph.SetPoint(i, p / 1000, e)
            graph.SetPointError(i, 0.4, 0.4, e - e_low, e_high - e)
        graph.linecolor = color
        graph.linewidth = 2
        graph.fillstyle = '/'
        graph.fillcolor = color
        graphs.append(graph)
    c = Canvas()
    leg = Legend(len(graphs),
                 pad=c,
                 topmargin=0.4,
                 leftmargin=0.3,
                 textsize=25,
                 margin=0.2)
    for i, g in enumerate(graphs):
        if i == 0:
            g.Draw('3AC')
            g.xaxis.title = '#font[52]{p}_{T} [GeV]'
            g.xaxis.SetLimits(20, 100)
            g.yaxis.SetLimits(ylow, yhigh)
            g.yaxis.SetRangeUser(ylow, yhigh)
            g.yaxis.title = title
        else:
            g.Draw('3C SAME')
        leg.AddEntry(g, g.name, 'L')
    leg.Draw()
    lines = []
    for thresh in (25, 35):
        line = Line(thresh, ylow, thresh, yhigh)
        line.linestyle = 'dashed'
        line.linewidth = 2
        line.Draw()
        lines.append(line)
    c.SaveAs('trigger_{0}.png'.format(name))
    c.SaveAs('trigger_{0}.eps'.format(name))
Exemplo n.º 25
0
    def make_plot(parentDirectory,
                  efficiencyName,
                  titleText,
                  outfn,
                  legendText=None,
                  drawHist=False,
                  binsToMerge=None,
                  numerAdd=None):

        _efficiency = get_efficiency(parentDirectory,
                                     efficiencyName + '__total',
                                     efficiencyName + '__match',
                                     binsToMerge=binsToMerge,
                                     numerAdd=numerAdd)
        _graph = _efficiency.graph
        _graph.drawstyle = 'AP'
        draw(_graph, xtitle='Lxy [cm]', ytitle='Efficiency')

        title = TitleAsLatex(titleText)
        title.Draw()

        if legendText:
            leg = Legend(1,
                         margin=0.25,
                         leftmargin=0.45,
                         topmargin=0.02,
                         entrysep=0.01,
                         entryheight=0.02,
                         textsize=12)
            leg.AddEntry(_graph, legendText, style='LEP')
            leg.Draw()

        canvas.SaveAs(outfn)
        canvas.clear()

        if drawHist:
            _total, _passed = _efficiency.total, _efficiency.passed
            _passed.markercolor = 'red'

            draw([_total, _passed], logy=True)
            title.Draw()
            leg = Legend(2,
                         margin=0.25,
                         leftmargin=0.45,
                         topmargin=0.02,
                         entrysep=0.01,
                         entryheight=0.02,
                         textsize=12)
            leg.AddEntry(_total, label='total', style='LEP')
            leg.AddEntry(_passed, label='passed', style='LEP')
            leg.Draw()
            canvas.SaveAs(outfn.replace('.pdf', '__HIST.pdf'))
            canvas.clear()
Exemplo n.º 26
0
    def __make_overlay(self, hists, fits, labels, ytitle, suffix=""):
        with preserve_current_style():
            # Draw each resolution (with fit)
            # TODO: this feels like it does not belong here
            for hist in hists:
                hist.GetYaxis().SetRangeUser(0, 0.1)
                hist.GetYaxis().SetTitleOffset(1.4)

            xtitle = self.resolution_method.label.format(
                on=self.online_title, off=self.offline_title)
            canvas = draw(hists,
                          draw_args={
                              "xtitle": xtitle,
                              "ytitle": ytitle
                          })
            if fits:
                for fit, hist in zip(fits, hists):
                    fit["asymmetric"].linecolor = hist.GetLineColor()
                    fit["asymmetric"].Draw("same")

            # Add labels
            label_canvas()

            # Add a legend
            legend = Legend(
                len(hists),
                header=self.legend_title,
                topmargin=0.35,
                rightmargin=0.3,
                leftmargin=0.7,
                textsize=0.03,
                entryheight=0.03,
            )

            for hist, label in zip(hists, labels):
                legend.AddEntry(hist, label)
            legend.SetBorderSize(0)
            legend.Draw()

            ymax = 1.2 * max([hist.GetMaximum() for hist in hists])
            line = ROOT.TLine(0., 0., 0., ymax)
            line.SetLineColor(15)

            # Save canvas to file
            name = self.filename_format.format(pileup="all")
            self.save_canvas(canvas, name + suffix)
Exemplo n.º 27
0
def draw_efficiencies(effs, field, category, textsize=22):

    xtitle = get_xtitle(field)

    c = Canvas()
    c.SetGridx()
    c.SetGridy()
    if not isinstance(effs, (list, tuple)):
        effs = [effs]

    h = Hist(10, effs[0].painted_graph.xaxis.min,
             effs[0].painted_graph.xaxis.max)
    h.yaxis.SetRangeUser(0.0, 1.1)
    h.Draw('HIST')
    h.yaxis.title = 'Efficiency'
    h.xaxis.title = xtitle

    colors = [
        'black',
        'red',
        'orange',
        'blue',
        'green',
        'purple',
        'yellow',
        'pink',
    ]
    if len(effs) > len(colors):
        colors = len(effs) * colors
    for eff, col in zip(effs, colors):
        eff.color = col
        eff.color = col
        eff.painted_graph.legendstyle = 'l'
        eff.painted_graph.Draw('SAMEP')
    label = ROOT.TLatex(c.GetLeftMargin() + 0.04, 0.9, category.label)
    label.SetNDC()
    label.SetTextFont(43)
    label.SetTextSize(textsize)
    label.Draw()
    leg = Legend(effs, pad=c, textsize=20)
    # textsize=20, leftmargin=0.6, topmargin=0.6)
    leg.Draw('same')
    return c
Exemplo n.º 28
0
def routine(chan):
    chdir = getattr(f, 'ch' + chan).sig
    paramTags = [x.name for x in chdir.keys()]
    paramTags = [x for x in paramTags if x.endswith('lxy-300')]
    paramTags.sort()

    hs, legItems = [], []
    htitle = None
    for i, paramTag in enumerate(paramTags):
        h = getattr(chdir, paramTag).dplxy
        if htitle is None: htitle = h.title
        h.title = paramTag.rsplit('_', 1)[0] + ' (N:{}, O:{})'.format(
            h.integral(), h.overflow())
        h.color = sigCOLORS[i]
        h.legendstyle = 'LEP'
        h.markersize = 0.5
        h.scale(10**i / h.integral())
        hs.append(h)
        legItems.append(h)

    xmin_, xmax_, ymin_, ymax_ = get_limits(hs, logy=True)
    draw(
        hs,
        logy=True,
    )
    legend = Legend(legItems,
                    pad=canvas,
                    margin=0.25,
                    leftmargin=0.3,
                    topmargin=0.02,
                    entryheight=0.02,
                    entrysep=0.01,
                    textsize=12,
                    header='private signal samples <lxy>=300')
    legend.Draw()
    title = TitleAsLatex('[{}] '.format(chan.replace('mu', '#mu')) + htitle)
    title.Draw()
    draw_labels('59.74 fb^{-1} (13 TeV)',
                cms_position='left',
                extra_text='work-in-progress')

    canvas.SaveAs('{}/ch{}_dplxy.pdf'.format(outdir, chan))
    canvas.Clear()
Exemplo n.º 29
0
def plot_lxy(chan):
    assert (chan in ['2mu2e', '4mu'])
    masstag = 'mXX-150_mA-0p25'

    chandir = getattr(f, 'ch' + chan)
    massdir = getattr(chandir, masstag)
    lifetimekeys = [k.name for k in massdir.keys()]
    lifetimekeys.sort(key=get_first)
    hs = []
    for i, lifetimekey in enumerate(lifetimekeys):
        h = getattr(massdir, lifetimekey).dplxy

        h.scale(1. / h.integral())
        h.title = 'lxy: {:g} cm'.format(get_first(lifetimekey))
        h.color = sigCOLORS[i]
        h.legendstyle = 'LEP'
        h.markersize = 0.5

        hs.append(h)

    legItems = [h for h in hs]
    draw(hs, logy=True, ytitle='Normalized counts/1cm')
    legheader = 'm_{#chi#chi} = 150 GeV, m_{Z_{d}} = 0.25 GeV'
    leg = Legend(legItems,
                 pad=canvas,
                 margin=0.25,
                 topmargin=0.02,
                 entryheight=0.02,
                 entrysep=0.01,
                 textsize=12,
                 header=legheader)
    leg.Draw()

    htitle = 'Dark photon lxy'
    title = TitleAsLatex('[{}] '.format(chan.replace('mu', '#mu')) + htitle)
    title.Draw()
    draw_labels('59.74 fb^{-1} (13 TeV)',
                cms_position='left',
                extra_text='Simulation Preliminary')

    canvas.SaveAs('{}/ch{}_dplxy.pdf'.format(outdir, chan))
    canvas.clear()
Exemplo n.º 30
0
def routine(chan, masstag):
    massdir = getattr(getattr(f, 'ch' + chan), masstag)
    lifetimeTags = [x.name for x in massdir.keys()]

    get_lxy = lambda t: float(t.split('_')[0].split('-')[-1].replace('p', '.'))
    get_ctau = lambda t: float(
        t.split('_')[1].split('-')[-1].replace('p', '.'))

    lifetimeTags.sort(key=get_lxy)
    hs, legItems = [], []
    htitle = None
    for i, lifetimeTag in enumerate(lifetimeTags):
        h = getattr(massdir, lifetimeTag).dplxy
        if htitle is None: htitle = h.title
        h.title = 'lxy: {:g} (N={})'.format(get_lxy(lifetimeTag),
                                            h.integral(overflow=True))
        h.color = sigCOLORS[i]
        h.legendstyle = 'LEP'
        h.markersize = 0.5
        hs.append(h)
        legItems.append(h)

    xmin_, xmax_, ymin_, ymax_ = get_limits(hs, logy=True)
    draw(hs, logy=True, ylimits=(0.1, ymax_))
    legend = Legend(legItems,
                    pad=canvas,
                    margin=0.25,
                    topmargin=0.02,
                    entryheight=0.02,
                    entrysep=0.01,
                    textsize=12,
                    header=masstag)
    legend.Draw()
    title = TitleAsLatex('[{}] '.format(chan.replace('mu', '#mu')) + htitle)
    title.Draw()
    draw_labels('59.74 fb^{-1} (13 TeV)',
                cms_position='left',
                extra_text='work-in-progress')

    canvas.SaveAs('{}/ch{}_dplxy__{}.png'.format(outdir, chan, masstag))
    canvas.Clear()