Example #1
0
def test_init():

    l = Legend(2)
    h = Hist(10, 0, 1)
    l.AddEntry(h)
    hr = TH1D("test", "", 10, 0, 1)
    l.AddEntry(hr)
Example #2
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)
    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()
Example #4
0
def drawDataLegend(inputdatastack, inputstack, plotData, BLINDEDLIST,
                   defaultlabelsize, Region):
    datalegend_entries = 2  #figure out how to remove this magic number
    datamargin = 0.10
    datarightmargin = 0.00
    datatopmargin = 0.05
    dataentryheight = 0.045
    dataentrysep = 0.06
    datalegend = Legend(datalegend_entries,
                        leftmargin=0.26,
                        topmargin=datatopmargin,
                        rightmargin=datarightmargin,
                        entryheight=dataentryheight,
                        entrysep=dataentrysep,
                        margin=datamargin,
                        textfont=43,
                        textsize=defaultlabelsize,
                        header=None)
    datalegend.SetLineColor(0)

    if plotData:
        if Region not in BLINDEDLIST:
            datalegend.AddEntry(
                inputdatastack.sum,
                label="Data [" +
                str(round(inputdatastack.sum.integral(overflow=True), 1)) +
                "]",
                style="EP")

    errorband = inputstack.sum.Clone()
    errorband.SetLineWidth(10)
    errorband.SetFillStyle(3244)
    errorband.SetFillColor(922)

    if Region == "A" or Region == "B" or Region == "D" or Region == "VRC" or Region == "VRD":
        datalegend.AddEntry(
            inputstack.sum,
            label="SM [" +
            str(round(float(inputstack.sum.integral(overflow=True)), 1)) +
            "\pm" + str(
                round(
                    float(
                        inputstack.sum.integral(error=True, overflow=True)[1]),
                    1)) + "]",
            style="L")
    else:
        datalegend.AddEntry(
            inputstack.sum,
            label="SM [" +
            str(round(float(inputstack.sum.integral(overflow=True)), 1)) + "]",
            style="L")
    datalegend.Draw("SAME")
    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()
Example #6
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)
Example #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)
Example #8
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
    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)
Example #10
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()
Example #11
0
def drawBackgroundLegend(backgroundstacks, stack, LegendExtraInformation,
                         defaultlabelsize, Region):
    legend_entries = 4  #figure out how to remove this magic number

    margin = 0.30
    rightmargin = 0.07
    topmargin = 0.05
    entryheight = 0.045
    entrysep = 0.06

    legend = Legend(legend_entries,
                    leftmargin=0.49,
                    topmargin=topmargin,
                    rightmargin=rightmargin,
                    entryheight=entryheight,
                    entrysep=entrysep,
                    margin=margin,
                    textfont=43,
                    textsize=defaultlabelsize,
                    header=None)

    legend.SetLineColor(0)

    totalyield, totalerror = stack.sum.integral(error=True, overflow=True)

    for LegendGroup in backgroundstacks:
        if LegendGroup is 'Data': continue

        backgroundyield, backgrounderror = backgroundstacks[
            LegendGroup].sum.integral(error=True, overflow=True)
        if LegendExtraInformation == "Relative" and totalyield != 0:
            relativeyield = str(round(100 * backgroundyield / totalyield, 1))
            legend.AddEntry(backgroundstacks[LegendGroup].sum,
                            label=LegendGroup + " [" + relativeyield + "%]",
                            style="F")
        elif LegendExtraInformation == "Absolute":
            legend.AddEntry(backgroundstacks[LegendGroup].sum,
                            label=LegendGroup + " (" +
                            str(round(backgroundyield, 1)) + ")",
                            style="F")
        else:
            legend.AddEntry(backgroundstacks[LegendGroup].sum,
                            label=LegendGroup,
                            style="F")

    legend.Draw("SAME")
Example #12
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)
Example #13
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)
Example #14
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))
    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)
Example #16
0
def plot_distributions(input_file, distribution_plots):
  with root_open(input_file) as file:
    for name,histo_configs in distribution_plots.items():
      canvas = Canvas(700,700)
      legend = Legend(len(histo_configs), leftmargin=0.4, margin=0.3)
      histograms = []
      for histo_config in histo_configs:
        histogram = file.Get(histo_config.name)
        if len(histo_config.range)==2:
          histogram.SetAxisRange(histo_config.range[0], histo_config.range[1], 'X')
        histogram.color = histo_config.color
        histogram.markerstyle = histo_config.marker
        legend.AddEntry(histogram, label=histo_config.legend, style='ep')
        histograms.append(histogram)
      xmin, xmax, ymin, ymax = get_limits(histograms, logy=False)
      option = ''
      for histogram in histograms:
        histogram.SetAxisRange(ymin,ymax,'Y')
        histogram.Draw(option)
        option += ' same'
      legend.Draw()
      canvas.Print('plots/{}.png'.format(name))
Example #17
0
        # loop over all histograms, set their styles, split them up, scale if need
        for hist in hists:
          group = groups.get(hist.title)
          hist_styles = group.get('styles', {})

          # auto loop through colors and add color if not set
          if not any('color' in k for k in hist_styles.keys()):
            hist_styles['color'] = hist_styles.get('color', next(default_colors))
          # decorate it
          hist.decorate(**hist_styles)

          # set axis
          get_axis(hist, 'x').SetNdivisions(canvasConfigs.get('ndivisions', 1), canvasConfigs.get('ndivisions opt', True))

          # add each hist to the legend
          legend.AddEntry(hist)#, style=group.get('legendstyle', 'F'))

          # rebin?
          rebin = plots_path.get('rebin', plots_config.get('rebin', None))
          if rebin is not None:
            hist.rebin(rebin)

          # exclusion, so we don't need to plot it
          if hist.title in plots_path.get('exclude', []): continue
          if group.get('stack it', False):
            # overwrite with solid when stacking
            hist.fillstyle = 'solid'
            stackHists.append(hist)
          else:
            soloHists.append(hist)
Example #18
0
fit_data = FitData(h_data, templates, fit_boundaries=(0, h_data.nbins()))

fit_collection = FitDataCollection()
fit_collection.add(fit_data)

minuit_fitter = Minuit(fit_collection, method='logLikelihood', verbose=True)
minuit_fitter.fit()

results = minuit_fitter.readResults()

c.cd(2)
ymax = h_data.GetBinContent(h_data.GetMaximumBin()) * 1.1
h_data.GetYaxis().SetRangeUser(0, ymax)
h_data.Draw('PE')
leg = Legend(nTemplates + 2)
leg.AddEntry(h_data, style='LEP')
h_tSumAfter = 0

print '----> Target \t Fit Result'
if useT1:
    h_t1After = h_t1.Clone()
    h_t1After.Scale(results['t1'][0] / h_t1.Integral())
    h_t1After.Draw('SAME HIST')
    h_tSumAfter += h_t1After
    leg.AddEntry(h_t1After, style='L')
    t1AfterCont = h_t1.Integral() * t1Scale * h_data.Integral() / (
        h_t1.Integral() * t1Scale + h_t2.Integral() * t2Scale +
        h_t3.Integral() * t3Scale)
    print '%s : \t %.3g \t %.3g +/- %.3g' % (
        t1Name, t1AfterCont, results['t1'][0], results['t1'][1])
    scan1 = results['t1'][2]
Example #19
0
    def __make_overlay(self, pileup, threshold, hists, fits, labels, header):
        with preserve_current_style():
            name = self.filename_format.format(pileup=pileup,
                                               threshold=threshold)
            # Draw each efficiency (with fit)
            draw_args = {"xtitle": self.offline_title, "ytitle": "Efficiency"}
            # TODO: special case should not be implemented here!
            if 'Jet' in name and 'HiRange' in name:
                draw_args['xlimits'] = [20, 2000]

            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()

            xmin = 0
            xmax = self.x_max
            # TODO: also specialisation, needs removal
            if ("HT" in name):
                xmax = 800
                xmin = 30
            if ("MET" in name):
                xmin = 0
                xmax = 400
            if ("Jet" in name):
                xmin = 20
                xmax = 400
            if ("HiRange" in name):
                xmax = 2000

            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 val in range(100, xmax, 100):
                line = ROOT.TLine(val, 0., val, 1.)
                line.SetLineStyle("dashed")
                line.SetLineColor(15)
                line.Draw()

            # Save canvas to file
            self.save_canvas(canvas, name)
Example #20
0
#     h_.fit('pol1')
#     fitfunc = h_.GetFunction('pol1')
#     offset, slope = fitfunc.GetParameter(0), fitfunc.GetParameter(1)
#     fitfuncs.append(fitfunc)
for i, h_ in enumerate(todraw):
    h_.color = COLORS[i]
draw(todraw)
leg = Legend(3,
             pad=canvas,
             margin=0.25,
             leftmargin=0.45,
             topmargin=0.02,
             entrysep=0.01,
             entryheight=0.02,
             textsize=12)
leg.AddEntry(ratios[0.2][0], label='iso boundary=0.2')
leg.AddEntry(ratios[0.3][0], label='iso boundary=0.3')
leg.AddEntry(ratios[0.4][0], label='iso boundary=0.4')
leg.Draw()
title = TitleAsLatex('[4#mu VR] Ratio of maxiso <high> to maxiso <low>')
title.Draw()
canvas.SaveAs('{}/ch4mu_vr_ratio_maxiso.pdf'.format(outdir, ))
canvas.clear()

ratios = {}
ratios[0.7] = create_ratioplot(h, xbound_bin=14)
ratios[0.8] = create_ratioplot(h, xbound_bin=16)
ratios[0.9] = create_ratioplot(h, xbound_bin=18)
todraw = [ratios[0.7][1], ratios[0.8][1], ratios[0.9][1]]
for i, h_ in enumerate(todraw):
    h_.color = COLORS[i]
Example #21
0
        os.makedirs(args.output)

    plots_written = []

    with io.open(layout_filename, 'r') as layout_file:
        log.info("Plotting all histograms")
        for path, subdirs, histos in layout_file.walk(class_pattern='TH1F'):
            for histo in histos:
                log.info("Plotting %s in %s", histo, path)
                data_histo = data_view.Get(os.path.join(path, histo))
                mc_histo = mc_view.Get(os.path.join(path, histo))
                log.info("Data histo has %f entries", data_histo.Integral())
                mc_histo.Draw()
                data_histo.Draw('same')
                legend = Legend(7, leftmargin=0.5)
                legend.AddEntry(mc_histo)
                legend.AddEntry(data_histo)
                legend.SetBorderSize(0)
                legend.Draw()
                mc_histo.SetMaximum(
                    1.2 * max(mc_histo.GetMaximum(), data_histo.GetMaximum()))

                plot_filename = os.path.join(
                    args.output,
                    path.replace('/', '_') + '_' + histo + '.pdf')
                plots_written.append(plot_filename)
                canvas.SaveAs(plot_filename)

    with open(os.path.join(args.output, 'plot_list.txt'), 'w') as plot_list:
        for plot_filename in plots_written:
            plot_list.write(plot_filename + '\n')
Example #22
0
# plot with ROOT
canvas = Canvas(width=700, height=500)

# try setting logy=True and uncommenting the two lines below
xmin, xmax, ymin, ymax = get_limits([stack, h3], logy=False)
stack.SetMaximum(ymax)
#stack.SetMinimum(ymin)
#canvas.SetLogy()

stack.Draw('HIST E1 X0')
h3.Draw('SAME E1 X0')
stack.xaxis.SetTitle('Mass')
stack.yaxis.SetTitle('Events')
# set the number of expected legend entries
legend = Legend(3, leftmargin=0.45, margin=0.3)
legend.AddEntry(h1, style='F')
legend.AddEntry(h2, style='F')
legend.AddEntry(h3, style='LEP')
legend.Draw()
label = ROOT.TText(0.3, 0.8, 'ROOT')
label.SetTextFont(43)
label.SetTextSize(25)
label.SetNDC()
label.Draw()
canvas.Modified()
canvas.Update()

# plot with matplotlib
set_style('ATLAS', mpl=True)
fig = plt.figure(figsize=(7, 5), dpi=100)
axes = plt.axes()
Example #23
0
        if bg_bool == "Plot":
            background = root_open(backgroundMC_location + "/" + rootfile)
            compressed = background.CompressedAnalysis
            print compressed
            histname = "hist" + rootfile
            histogram = histname + "(" + nbins + "," + xmin + "," + xmax + ")"

            histname = compressed.Draw(variable + ">>" + histogram,
                                       selection=weight * total,
                                       drawstyle='hist',
                                       fillstyle='solid',
                                       linecolor='black',
                                       fillcolor=color)
            print histname
            print background_name
            legend.AddEntry(histname, label=background_name,
                            style='F')  #was label=background_name
            stack.Add(histname)

    #=================== DATA SAMPLES ====================================#
    objects = []
    dataobjects = []
    for (datafilename, data_weight, data_bool) in zip(data_list,
                                                      data_weight_list,
                                                      data_bool_list):
        print datafilename, data_weight, data_bool
        if data_bool == "Plot":
            print "datafilename: ", datafilename
            data = root_open(data_location + "/" + datafilename)
            treesSR = data.CompressedAnalysis
            datacut = total
            if data_weight != "1":
Example #24
0
x_max = gr.GetXaxis().GetXmax()
y_min = gr.GetXaxis().GetXmin()
y_max = gr.GetXaxis().GetXmax()
gr.Draw('a3')
gr.Draw('Xp same')

# a straight line y=x to be a reference
f_dia = ROOT.TF1("f_dia", "x",
                 h1.GetXaxis().GetXmin(),
                 h1.GetXaxis().GetXmax())
f_dia.SetLineColor(9)
f_dia.SetLineWidth(2)
f_dia.SetLineStyle(2)
f_dia.Draw("same")

leg = Legend(3,
             pad=pad,
             leftmargin=0.45,
             topmargin=0.45,
             rightmargin=0.05,
             textsize=20)
leg.AddEntry(gr, "QQ points", "p")
leg.AddEntry(gr, "68% CL band", "f")
leg.AddEntry(f_dia, "Diagonal line", "l")
leg.Draw()

c.Modified()
c.Update()
c.Draw()
wait()
Example #25
0
    def plot(self):

        evaluator = Evaluator(self.model, self.transformation, self.features)
        makedirs(self.plt_dir, exist_ok=True)
        makedirs('/'.join([self.plt_dir, 'lin']), exist_ok=True)
        makedirs('/'.join([self.plt_dir, 'log']), exist_ok=True)
        makedirs('/'.join([self.plt_dir, 'lin', 'png']), exist_ok=True)
        makedirs('/'.join([self.plt_dir, 'lin', 'root']), exist_ok=True)
        makedirs('/'.join([self.plt_dir, 'log', 'png']), exist_ok=True)
        makedirs('/'.join([self.plt_dir, 'log', 'root']), exist_ok=True)
        makedirs('/'.join([self.plt_dir, 'lnt_region', 'lin']), exist_ok=True)
        makedirs('/'.join([self.plt_dir, 'lnt_region', 'log']), exist_ok=True)
        makedirs('/'.join([self.plt_dir, 'lnt_region', 'lin', 'png']),
                 exist_ok=True)
        makedirs('/'.join([self.plt_dir, 'lnt_region', 'lin', 'root']),
                 exist_ok=True)
        makedirs('/'.join([self.plt_dir, 'lnt_region', 'log', 'png']),
                 exist_ok=True)
        makedirs('/'.join([self.plt_dir, 'lnt_region', 'log', 'root']),
                 exist_ok=True)
        makedirs('/'.join([self.plt_dir, 'shapes', 'lin']), exist_ok=True)
        makedirs('/'.join([self.plt_dir, 'shapes', 'log']), exist_ok=True)
        makedirs('/'.join([self.plt_dir, 'shapes', 'lin', 'png']),
                 exist_ok=True)
        makedirs('/'.join([self.plt_dir, 'shapes', 'lin', 'root']),
                 exist_ok=True)
        makedirs('/'.join([self.plt_dir, 'shapes', 'log', 'png']),
                 exist_ok=True)
        makedirs('/'.join([self.plt_dir, 'shapes', 'log', 'root']),
                 exist_ok=True)

        # NN evaluator
        print('============> starting reading the trees')
        print('Plots will be stored in: ', self.plt_dir)
        now = time()
        signal = []
        if self.process_signals:
            signal = self.get_signal_samples(self.channel,
                                             self.base_dir,
                                             self.post_fix,
                                             self.selection_data,
                                             mini=self.mini_signals)
        else:
            signal = []
        data = self.get_data_samples(self.channel, self.base_dir,
                                     self.post_fix, self.selection_data)
        mc = self.get_mc_samples(self.channel, self.base_dir, self.post_fix,
                                 self.selection_mc)
        print('============> it took %.2f seconds' % (time() - now))

        # evaluate FR
        for isample in (mc + data):  #+signal):
            isample.df['fr'] = evaluator.evaluate(isample.df)
            # already corrected, ready to be applied in lnt-not-tight
            isample.df['fr_corr'] = isample.df['fr'] / (1. - isample.df['fr'])

        # apply an extra selection to the pandas dataframes
        if len(self.pandas_selection):
            for isample in (mc + data + signal):
                isample.df = isample.df.query(self.pandas_selection)

        # split the dataframe in tight and lnt-not-tight (called simply lnt for short)
        print('============> splitting dataframe in tight and loose not tight')
        for isample in (mc + data + signal):
            isample.df_tight = isample.df.query(self.selection_tight)
            if isample not in signal:
                isample.df_lnt = isample.df.query(self.selection_lnt)
            # free some mem
            del isample.df
            gc.collect()
        print('============> ... done')

        # sort depending on their position in the stack
        mc.sort(key=lambda x: x.position_in_stack)

        # now we plot
        self.create_canvas(self.do_ratio)

        for ivar in variables:

            variable, bins, label, xlabel, ylabel, extra_sel = ivar.var, ivar.bins, ivar.label, ivar.xlabel, ivar.ylabel, ivar.extra_selection

            print('plotting', label)

            ######################################################################################
            # plot MC stacks, in tight and lnt
            ######################################################################################

            stack_prompt = []
            stack_nonprompt = []
            stack_nonprompt_control = []

            for imc in mc:

                if extra_sel:
                    mc_df_tight = imc.df_tight.query(extra_sel)
                    mc_df_lnt = imc.df_lnt.query(extra_sel)
                else:
                    mc_df_tight = imc.df_tight
                    mc_df_lnt = imc.df_lnt

                histo_tight = Hist(bins,
                                   title=imc.label,
                                   markersize=0,
                                   legendstyle='F',
                                   name=imc.datacard_name + '#' + label + '#t')
                weights = self.total_weight_calculator(
                    mc_df_tight, ['weight'] + imc.extra_signal_weights,
                    [self.lumi, imc.lumi_scaling])
                histo_tight.fill_array(mc_df_tight[variable],
                                       weights=weights *
                                       self.relaxed_mc_scaling)

                histo_tight.fillstyle = 'solid'
                histo_tight.fillcolor = 'steelblue' if self.data_driven else imc.colour
                histo_tight.linewidth = 0

                stack_prompt.append(histo_tight)

                # optionally remove the MC subtraction in loose-not-tight
                # may help if MC stats is terrible (and it often is)
                if self.data_driven:
                    if self.mc_subtraction:
                        histo_lnt = Hist(bins,
                                         title=imc.label,
                                         markersize=0,
                                         legendstyle='F',
                                         name=imc.datacard_name + '#' + label +
                                         '#lnt')
                        weights = self.total_weight_calculator(
                            mc_df_lnt,
                            ['weight', 'fr_corr'] + imc.extra_signal_weights,
                            [-1., self.lumi, imc.lumi_scaling])
                        histo_lnt.fill_array(mc_df_lnt[variable],
                                             weights=weights *
                                             self.relaxed_mc_scaling)

                        histo_lnt.fillstyle = 'solid'
                        histo_lnt.fillcolor = 'skyblue' if self.data_driven else imc.colour
                        histo_lnt.linewidth = 0
                        stack_nonprompt.append(histo_lnt)

                    histo_lnt_control = Hist(bins,
                                             title=imc.label,
                                             markersize=0,
                                             legendstyle='F',
                                             name=imc.datacard_name + '#' +
                                             label + '#lntcontrol')
                    weights_control = self.total_weight_calculator(
                        mc_df_lnt, ['weight'] + imc.extra_signal_weights,
                        [self.lumi, imc.lumi_scaling])
                    histo_lnt_control.fill_array(mc_df_lnt[variable],
                                                 weights=weights_control *
                                                 self.relaxed_mc_scaling)

                    histo_lnt_control.fillstyle = 'solid'
                    histo_lnt_control.fillcolor = imc.colour
                    histo_lnt_control.linewidth = 0

                    #                     print(histo_lnt_control)
                    #                     print(histo_lnt_control.fillcolor)
                    #                     print(imc.name, imc.colour)
                    #                     print(histo_lnt_control.integral())
                    stack_nonprompt_control.append(histo_lnt_control)

            # merge different samples together (add the histograms)
            # prepare two temporary containers for the post-grouping histograms
            stack_prompt_tmp = []
            stack_nonprompt_tmp = []
            stack_nonprompt_control_tmp = []
            for ini, fin in [(stack_prompt, stack_prompt_tmp),
                             (stack_nonprompt, stack_nonprompt_tmp),
                             (stack_nonprompt_control,
                              stack_nonprompt_control_tmp)]:
                for k, v in groups.items():
                    grouped = []
                    for ihist in ini:
                        if ihist.name.split('#')[0] in v:
                            grouped.append(ihist)
                        elif ihist.name.split('#')[0] not in togroup:
                            fin.append(ihist)
                    if len(grouped):
                        group = sum(grouped)
                        group.title = k
                        group.name = '#'.join([k] + ihist.name.split('#')[1:])
                        group.fillstyle = grouped[0].fillstyle
                        group.fillcolor = grouped[0].fillcolor
                        group.linewidth = grouped[0].linewidth
                    fin.append(group)

            stack_prompt = stack_prompt_tmp
            stack_nonprompt = stack_nonprompt_tmp
            stack_nonprompt_control = stack_nonprompt_control_tmp

            ######################################################################################
            # plot the signals
            ######################################################################################

            all_signals = []
            signals_to_plot = []

            for isig in signal:

                if variable not in self.datacards:
                    if not isig.toplot:
                        continue

                if variable == 'fr' or variable == 'fr_corr':
                    continue

                if extra_sel:
                    isig_df_tight = isig.df_tight.query(extra_sel)
                else:
                    isig_df_tight = isig.df_tight

                histo_tight = Hist(
                    bins,
                    title=isig.label,
                    markersize=0,
                    legendstyle='L',
                    name=isig.datacard_name + '#' + label
                )  # the "#" thing is a trick to give hists unique name, else ROOT complains
                weights = self.total_weight_calculator(
                    isig_df_tight, ['weight'] + isig.extra_signal_weights,
                    [self.lumi, isig.lumi_scaling])
                histo_tight.fill_array(isig_df_tight[variable],
                                       weights=weights)
                histo_tight.color = isig.colour
                histo_tight.fillstyle = 'hollow'
                histo_tight.linewidth = 2
                histo_tight.linestyle = 'dashed'
                histo_tight.drawstyle = 'HIST'

                all_signals.append(histo_tight)
                if isig.toplot: signals_to_plot.append(histo_tight)

            ######################################################################################
            # plot the data
            ######################################################################################

            data_prompt = []
            data_nonprompt = []
            data_nonprompt_control = []

            for idata in data:

                if extra_sel:
                    idata_df_tight = idata.df_tight.query(extra_sel)
                    idata_df_lnt = idata.df_lnt.query(extra_sel)
                else:
                    idata_df_tight = idata.df_tight
                    idata_df_lnt = idata.df_lnt

                histo_tight = Hist(bins,
                                   title=idata.label,
                                   markersize=1,
                                   legendstyle='LEP')
                histo_tight.fill_array(idata_df_tight[variable])

                data_prompt.append(histo_tight)

                if self.data_driven:
                    histo_lnt = Hist(bins,
                                     title=idata.label,
                                     markersize=0,
                                     legendstyle='F')
                    histo_lnt.fill_array(idata_df_lnt[variable],
                                         weights=idata_df_lnt.fr_corr)

                    histo_lnt.fillstyle = 'solid'
                    histo_lnt.fillcolor = 'skyblue'
                    histo_lnt.linewidth = 0

                    histo_lnt_control = Hist(bins,
                                             title=idata.label,
                                             markersize=1,
                                             legendstyle='LEP')
                    histo_lnt_control.fill_array(idata_df_lnt[variable])

                    data_nonprompt.append(histo_lnt)
                    data_nonprompt_control.append(histo_lnt_control)

            if self.data_driven:
                # put the prompt backgrounds together
                all_exp_prompt = sum(stack_prompt)
                all_exp_prompt.title = 'prompt'

                # put the nonprompt backgrounds together
                all_exp_nonprompt = sum(stack_nonprompt + data_nonprompt)
                all_exp_nonprompt.fillstyle = 'solid'
                all_exp_nonprompt.fillcolor = 'skyblue'
                all_exp_nonprompt.linewidth = 0
                all_exp_nonprompt.title = 'nonprompt'

                # create the stacks
                stack = HistStack([all_exp_prompt, all_exp_nonprompt],
                                  drawstyle='HIST',
                                  title='')
                stack_control = HistStack(stack_nonprompt_control,
                                          drawstyle='HIST',
                                          title='')

            else:
                stack = HistStack(stack_prompt, drawstyle='HIST', title='')

            # stat uncertainty
            hist_error = stack.sum  #sum([all_exp_prompt, all_exp_nonprompt])
            hist_error.drawstyle = 'E2'
            hist_error.fillstyle = '/'
            hist_error.color = 'gray'
            hist_error.title = 'stat. unc.'
            hist_error.legendstyle = 'F'

            if self.data_driven:
                hist_error_control = stack_control.sum
                hist_error_control.drawstyle = 'E2'
                hist_error_control.fillstyle = '/'
                hist_error_control.color = 'gray'
                hist_error_control.title = 'stat. unc.'
                hist_error_control.legendstyle = 'F'

            # put the data together
            all_obs_prompt = sum(data_prompt)
            all_obs_prompt.title = 'observed'

            if self.data_driven:
                all_obs_nonprompt_control = sum(data_nonprompt_control)
                all_obs_nonprompt_control.title = 'observed'
                all_obs_nonprompt_control.drawstyle = 'EP'

            # prepare the legend
            print(signals_to_plot)
            for jj in signals_to_plot:
                print(jj.name, jj.integral())
            if len(signals_to_plot):
                legend = Legend([all_obs_prompt, stack, hist_error],
                                pad=self.main_pad,
                                leftmargin=0.,
                                rightmargin=0.,
                                topmargin=0.,
                                textfont=42,
                                textsize=0.025,
                                entrysep=0.01,
                                entryheight=0.04)
                legend_signals = Legend(signals_to_plot,
                                        pad=self.main_pad,
                                        leftmargin=0.,
                                        rightmargin=0.,
                                        topmargin=0.,
                                        textfont=42,
                                        textsize=0.025,
                                        entrysep=0.01,
                                        entryheight=0.04)
                legend_signals.SetBorderSize(0)
                legend_signals.x1 = 0.42
                legend_signals.y1 = 0.74
                legend_signals.x2 = 0.88
                legend_signals.y2 = 0.90
                legend_signals.SetFillColor(0)
                legend.SetBorderSize(0)
                legend.x1 = 0.2
                legend.y1 = 0.74
                legend.x2 = 0.45
                legend.y2 = 0.90
                legend.SetFillColor(0)
            else:
                legend = Legend([all_obs_prompt, stack, hist_error],
                                pad=self.main_pad,
                                leftmargin=0.,
                                rightmargin=0.,
                                topmargin=0.,
                                textfont=42,
                                textsize=0.03,
                                entrysep=0.01,
                                entryheight=0.04)
                legend.SetBorderSize(0)
                legend.x1 = 0.55
                legend.y1 = 0.74
                legend.x2 = 0.88
                legend.y2 = 0.90
                legend.SetFillColor(0)

            # plot with ROOT, linear and log scale
            for islogy in [False, True]:

                things_to_plot = [stack, hist_error]
                if not self.blinded:
                    things_to_plot.append(all_obs_prompt)

                # plot signals, as an option
                if self.plot_signals:
                    things_to_plot += signals_to_plot

                # set the y axis range
                # FIXME! setting it by hand to each object as it doesn't work if passed to draw
                if islogy:
                    yaxis_max = 40. * max(
                        [ithing.max() for ithing in things_to_plot])
                else:
                    yaxis_max = 1.65 * max(
                        [ithing.max() for ithing in things_to_plot])
                if islogy: yaxis_min = 0.01
                else: yaxis_min = 0.

                for ithing in things_to_plot:
                    ithing.SetMaximum(yaxis_max)
                draw(things_to_plot,
                     xtitle=xlabel,
                     ytitle=ylabel,
                     pad=self.main_pad,
                     logy=islogy)

                # expectation uncertainty in the ratio pad
                ratio_exp_error = Hist(bins)
                ratio_data = Hist(bins)
                for ibin in hist_error.bins_range():
                    ratio_exp_error.set_bin_content(ibin, 1.)
                    ratio_exp_error.set_bin_error(
                        ibin,
                        hist_error.get_bin_error(ibin) /
                        hist_error.get_bin_content(ibin)
                        if hist_error.get_bin_content(ibin) != 0. else 0.)
                    ratio_data.set_bin_content(
                        ibin,
                        all_obs_prompt.get_bin_content(ibin) /
                        hist_error.get_bin_content(ibin)
                        if hist_error.get_bin_content(ibin) != 0. else 0.)
                    ratio_data.set_bin_error(
                        ibin,
                        all_obs_prompt.get_bin_error(ibin) /
                        hist_error.get_bin_content(ibin)
                        if hist_error.get_bin_content(ibin) != 0. else 0.)

                ratio_data.drawstyle = 'EP'
                ratio_data.title = ''

                ratio_exp_error.drawstyle = 'E2'
                ratio_exp_error.markersize = 0
                ratio_exp_error.title = ''
                ratio_exp_error.fillstyle = '/'
                ratio_exp_error.color = 'gray'

                for ithing in [ratio_data, ratio_exp_error]:
                    ithing.xaxis.set_label_size(
                        ithing.xaxis.get_label_size() * 3.
                    )  # the scale should match that of the main/ratio pad size ratio
                    ithing.yaxis.set_label_size(
                        ithing.yaxis.get_label_size() * 3.
                    )  # the scale should match that of the main/ratio pad size ratio
                    ithing.xaxis.set_title_size(
                        ithing.xaxis.get_title_size() * 3.
                    )  # the scale should match that of the main/ratio pad size ratio
                    ithing.yaxis.set_title_size(
                        ithing.yaxis.get_title_size() * 3.
                    )  # the scale should match that of the main/ratio pad size ratio
                    ithing.yaxis.set_ndivisions(405)
                    ithing.yaxis.set_title_offset(0.4)

                things_to_plot = [ratio_exp_error]
                if not self.blinded:
                    things_to_plot.append(ratio_data)

                draw(things_to_plot,
                     xtitle=xlabel,
                     ytitle='obs/exp',
                     pad=self.ratio_pad,
                     logy=False,
                     ylimits=(0.5, 1.5))

                line = ROOT.TLine(min(bins), 1., max(bins), 1.)
                line.SetLineColor(ROOT.kBlack)
                line.SetLineWidth(1)
                self.ratio_pad.cd()
                line.Draw('same')

                #                 chi2_score_text = '\chi^{2}/NDF = %.1f' %(all_obs_prompt.Chi2Test(hist_error, 'UW CHI2/NDF'))
                chi2_score_text = 'p-value = %.2f' % (all_obs_prompt.Chi2Test(
                    hist_error, 'UW'))
                chi2_score = ROOT.TLatex(0.7, 0.81, chi2_score_text)
                chi2_score.SetTextFont(43)
                chi2_score.SetTextSize(15)
                chi2_score.SetNDC()
                chi2_score.Draw('same')

                self.canvas.cd()
                # FIXME! add SS and OS channels
                if self.full_channel == 'mmm': channel = '\mu\mu\mu'
                elif self.full_channel == 'eee': channel = 'eee'
                elif self.full_channel == 'mem_os':
                    channel = '\mu^{\pm}\mu^{\mp}e'
                elif self.full_channel == 'mem_ss':
                    channel = '\mu^{\pm}\mu^{\pm}e'
                elif self.full_channel == 'eem_os':
                    channel = 'e^{\pm}e^{\mp}\mu'
                elif self.full_channel == 'eem_ss':
                    channel = 'e^{\pm}e^{\pm}\mu'
                else:
                    assert False, 'ERROR: Channel not valid.'
                finalstate = ROOT.TLatex(0.68, 0.68, channel)
                finalstate.SetTextFont(43)
                finalstate.SetTextSize(25)
                finalstate.SetNDC()
                finalstate.Draw('same')

                self.canvas.cd()
                # remove old legend
                for iprim in self.canvas.primitives:
                    if isinstance(iprim, Legend):
                        self.canvas.primitives.remove(iprim)
                legend.Draw('same')
                if self.plot_signals:
                    legend_signals.Draw('same')
                CMS_lumi(self.main_pad,
                         4,
                         0,
                         lumi_13TeV="%d, L = %.1f fb^{-1}" %
                         (self.year, self.lumi / 1000.))
                self.canvas.Modified()
                self.canvas.Update()
                for iformat in ['pdf', 'png', 'root']:
                    self.canvas.SaveAs('/'.join([
                        self.plt_dir, 'log' if islogy else 'lin',
                        iformat if iformat != 'pdf' else '',
                        '%s%s.%s' %
                        (label, '_log' if islogy else '_lin', iformat)
                    ]))

                # plot distributions in loose not tight
                # check MC contamination there
                if self.data_driven and variable not in ['fr', 'fr_corr']:
                    things_to_plot = [
                        stack_control, hist_error_control,
                        all_obs_nonprompt_control
                    ]
                    # set the y axis range
                    # FIXME! setting it by hand to each object as it doesn't work if passed to draw
                    if islogy:
                        yaxis_max = 40. * max(
                            [ithing.max() for ithing in things_to_plot])
                    else:
                        yaxis_max = 1.65 * max(
                            [ithing.max() for ithing in things_to_plot])
                    if islogy: yaxis_min = 0.01
                    else: yaxis_min = 0.

                    for ithing in things_to_plot:
                        ithing.SetMaximum(yaxis_max)
                        ithing.SetMinimum(yaxis_min)

                    draw(things_to_plot,
                         xtitle=xlabel,
                         ytitle=ylabel,
                         pad=self.main_pad,
                         logy=islogy,
                         ylimits=(yaxis_min, yaxis_max))

                    new_legend = Legend(
                        stack_control.hists +
                        [hist_error_control, all_obs_nonprompt_control],
                        pad=self.main_pad,
                        leftmargin=0.,
                        rightmargin=0.,
                        topmargin=0.,
                        textfont=42,
                        textsize=0.03,
                        entrysep=0.01,
                        entryheight=0.04)
                    new_legend.SetBorderSize(0)
                    new_legend.x1 = 0.55
                    new_legend.y1 = 0.71
                    new_legend.x2 = 0.88
                    new_legend.y2 = 0.90
                    new_legend.SetFillColor(0)

                    # divide MC to subtract by data
                    stack_nonprompt_control_scaled_list = []
                    for ihist in stack_control.hists:
                        new_hist = copy(ihist)
                        for ibin in new_hist.bins_range():
                            new_hist.SetBinContent(
                                ibin,
                                np.nan_to_num(
                                    np.divide(
                                        new_hist.GetBinContent(ibin),
                                        all_obs_nonprompt_control.
                                        GetBinContent(ibin))))
                            new_hist.SetBinError(
                                ibin,
                                np.nan_to_num(
                                    np.divide(
                                        new_hist.GetBinError(ibin),
                                        all_obs_nonprompt_control.
                                        GetBinContent(ibin))))
                        stack_nonprompt_control_scaled_list.append(new_hist)

                    stack_control_scaled = HistStack(
                        stack_nonprompt_control_scaled_list,
                        drawstyle='HIST',
                        title='')
                    stack_control_scaled_err = stack_control_scaled.sum
                    stack_control_scaled_err.drawstyle = 'E2'
                    stack_control_scaled_err.fillstyle = '/'
                    stack_control_scaled_err.color = 'gray'
                    stack_control_scaled_err.title = 'stat. unc.'
                    stack_control_scaled_err.legendstyle = 'F'

                    draw([stack_control_scaled, stack_control_scaled_err],
                         xtitle=xlabel,
                         ytitle='MC/data',
                         pad=self.ratio_pad,
                         logy=False)

                    stack_control_scaled.xaxis.set_label_size(
                        stack_control_scaled.xaxis.get_label_size() * 3.
                    )  # the scale should match that of the main/ratio pad size ratio
                    stack_control_scaled.yaxis.set_label_size(
                        stack_control_scaled.yaxis.get_label_size() * 3.
                    )  # the scale should match that of the main/ratio pad size ratio
                    stack_control_scaled.xaxis.set_title_size(
                        stack_control_scaled.xaxis.get_title_size() * 3.
                    )  # the scale should match that of the main/ratio pad size ratio
                    stack_control_scaled.yaxis.set_title_size(
                        stack_control_scaled.yaxis.get_title_size() * 3.
                    )  # the scale should match that of the main/ratio pad size ratio
                    stack_control_scaled.yaxis.set_ndivisions(405)
                    stack_control_scaled.yaxis.set_title_offset(0.4)
                    stack_control_scaled.SetMinimum(0.)
                    stack_control_scaled.SetMaximum(1.5)

                    CMS_lumi(self.main_pad,
                             4,
                             0,
                             lumi_13TeV="%d, L = %.1f fb^{-1}" %
                             (self.year, self.lumi / 1000.))

                    self.canvas.cd()
                    # remove old legend
                    for iprim in self.canvas.primitives:
                        if isinstance(iprim, Legend):
                            self.canvas.primitives.remove(iprim)

                    # draw new legend
                    new_legend.Draw('same')

                    self.canvas.Modified()
                    self.canvas.Update()

                    for iformat in ['pdf', 'png', 'root']:
                        self.canvas.SaveAs('/'.join([
                            self.plt_dir, 'lnt_region',
                            'log' if islogy else 'lin',
                            iformat if iformat != 'pdf' else '',
                            '%s%s.%s' %
                            (label, '_log' if islogy else '_lin', iformat)
                        ]))

                    # compare shapes in tight and loose not tight

                    # data in tight
                    all_obs_prompt_norm = copy(all_obs_prompt)
                    if all_obs_prompt_norm.integral() != 0:
                        all_obs_prompt_norm.Scale(
                            np.nan_to_num(
                                np.divide(1., all_obs_prompt_norm.integral())))
                    #import pdb; pdb.set_trace()
                    all_obs_prompt_norm.drawstyle = 'hist e'
                    all_obs_prompt_norm.linecolor = 'black'
                    all_obs_prompt_norm.markersize = 0
                    all_obs_prompt_norm.legendstyle = 'LE'
                    all_obs_prompt_norm.title = ''
                    all_obs_prompt_norm.label = 'data - tight'

                    # data MC subtracted in loose
                    all_obs_prompt_mc_sub_norm = copy(all_obs_prompt)
                    all_obs_prompt_mc_sub_norm.add(all_exp_prompt, -1)
                    all_obs_prompt_mc_sub_norm.Scale(
                        np.nan_to_num(
                            np.divide(1.,
                                      all_obs_prompt_mc_sub_norm.integral())))
                    all_obs_prompt_mc_sub_norm.drawstyle = 'hist e'
                    all_obs_prompt_mc_sub_norm.linecolor = 'green'
                    all_obs_prompt_mc_sub_norm.markersize = 0
                    all_obs_prompt_mc_sub_norm.legendstyle = 'LE'
                    all_obs_prompt_mc_sub_norm.title = ''
                    all_obs_prompt_mc_sub_norm.label = '(data-MC) - tight'

                    # data in loose
                    all_obs_nonprompt_control_norm = copy(
                        all_obs_nonprompt_control)
                    all_obs_nonprompt_control_norm.Scale(
                        np.nan_to_num(
                            np.divide(
                                1.,
                                all_obs_nonprompt_control_norm.integral())))
                    all_obs_nonprompt_control_norm.drawstyle = 'hist e'
                    all_obs_nonprompt_control_norm.linecolor = 'red'
                    all_obs_nonprompt_control_norm.markersize = 0
                    all_obs_nonprompt_control_norm.legendstyle = 'LE'
                    all_obs_nonprompt_control_norm.title = ''
                    all_obs_nonprompt_control_norm.label = 'data - l-n-t'

                    # data MC subtracted in loose
                    all_obs_nonprompt_control_mc_sub_norm = copy(
                        all_obs_nonprompt_control)
                    all_obs_nonprompt_control_mc_sub_norm.add(
                        stack_control.sum, -1)
                    all_obs_nonprompt_control_mc_sub_norm.Scale(
                        np.nan_to_num(
                            np.divide(
                                1.,
                                all_obs_nonprompt_control_mc_sub_norm.integral(
                                ))))
                    all_obs_nonprompt_control_mc_sub_norm.drawstyle = 'hist e'
                    all_obs_nonprompt_control_mc_sub_norm.linecolor = 'blue'
                    all_obs_nonprompt_control_mc_sub_norm.markersize = 0
                    all_obs_nonprompt_control_mc_sub_norm.legendstyle = 'LE'
                    all_obs_nonprompt_control_mc_sub_norm.title = ''
                    all_obs_nonprompt_control_mc_sub_norm.label = '(data-MC) - l-n-t'

                    things_to_plot = [
                        all_obs_prompt_norm,
                        all_obs_prompt_mc_sub_norm,
                        all_obs_nonprompt_control_norm,
                        all_obs_nonprompt_control_mc_sub_norm,
                    ]

                    yaxis_max = max([ii.GetMaximum() for ii in things_to_plot])

                    draw(things_to_plot,
                         xtitle=xlabel,
                         ytitle=ylabel,
                         pad=self.main_pad,
                         logy=islogy,
                         ylimits=(yaxis_min, 1.55 * yaxis_max))

                    self.canvas.cd()
                    # remove old legend
                    for iprim in self.canvas.primitives:
                        if isinstance(iprim, Legend):
                            self.canvas.primitives.remove(iprim)

                    shape_legend = Legend([],
                                          pad=self.main_pad,
                                          leftmargin=0.,
                                          rightmargin=0.,
                                          topmargin=0.,
                                          textfont=42,
                                          textsize=0.03,
                                          entrysep=0.01,
                                          entryheight=0.04)
                    shape_legend.AddEntry(all_obs_prompt_norm,
                                          all_obs_prompt_norm.label,
                                          all_obs_prompt_norm.legendstyle)
                    shape_legend.AddEntry(
                        all_obs_prompt_mc_sub_norm,
                        all_obs_prompt_mc_sub_norm.label,
                        all_obs_prompt_mc_sub_norm.legendstyle)
                    shape_legend.AddEntry(
                        all_obs_nonprompt_control_norm,
                        all_obs_nonprompt_control_norm.label,
                        all_obs_nonprompt_control_norm.legendstyle)
                    shape_legend.AddEntry(
                        all_obs_nonprompt_control_mc_sub_norm,
                        all_obs_nonprompt_control_mc_sub_norm.label,
                        all_obs_nonprompt_control_mc_sub_norm.legendstyle)
                    shape_legend.SetBorderSize(0)
                    shape_legend.x1 = 0.50
                    shape_legend.y1 = 0.71
                    shape_legend.x2 = 0.88
                    shape_legend.y2 = 0.90
                    shape_legend.SetFillColor(0)
                    shape_legend.Draw('same')

                    # plot ratios
                    all_obs_prompt_norm_ratio = copy(all_obs_prompt_norm)
                    all_obs_prompt_mc_sub_norm_ratio = copy(
                        all_obs_prompt_mc_sub_norm)
                    all_obs_nonprompt_control_norm_ratio = copy(
                        all_obs_nonprompt_control_norm)
                    all_obs_nonprompt_control_mc_sub_norm_ratio = copy(
                        all_obs_nonprompt_control_mc_sub_norm)

                    all_obs_prompt_norm_ratio.Divide(
                        all_obs_prompt_mc_sub_norm_ratio)
                    all_obs_nonprompt_control_norm_ratio.Divide(
                        all_obs_prompt_mc_sub_norm_ratio)
                    all_obs_nonprompt_control_mc_sub_norm_ratio.Divide(
                        all_obs_prompt_mc_sub_norm_ratio)

                    things_to_plot_ratio = [
                        all_obs_prompt_norm_ratio,
                        all_obs_nonprompt_control_norm_ratio,
                        all_obs_nonprompt_control_mc_sub_norm_ratio,
                    ]

                    for ithing in things_to_plot_ratio:
                        ithing.xaxis.set_label_size(
                            ithing.xaxis.get_label_size() * 3.
                        )  # the scale should match that of the main/ratio pad size ratio
                        ithing.yaxis.set_label_size(
                            ithing.yaxis.get_label_size() * 3.
                        )  # the scale should match that of the main/ratio pad size ratio
                        ithing.xaxis.set_title_size(
                            ithing.xaxis.get_title_size() * 3.
                        )  # the scale should match that of the main/ratio pad size ratio
                        ithing.yaxis.set_title_size(
                            ithing.yaxis.get_title_size() * 3.
                        )  # the scale should match that of the main/ratio pad size ratio
                        ithing.yaxis.set_ndivisions(405)
                        ithing.yaxis.set_title_offset(0.4)
                        ithing.SetMinimum(0.)
                        ithing.SetMaximum(2.)

                    draw(things_to_plot_ratio,
                         xtitle=xlabel,
                         ytitle='1/(data-MC)_{tight}',
                         pad=self.ratio_pad,
                         logy=False,
                         ylimits=(0., 2.))
                    self.ratio_pad.cd()
                    line.Draw('same')

                    CMS_lumi(self.main_pad,
                             4,
                             0,
                             lumi_13TeV="%d, L = %.1f fb^{-1}" %
                             (self.year, self.lumi / 1000.))

                    self.canvas.Modified()
                    self.canvas.Update()

                    for iformat in ['pdf', 'png', 'root']:
                        self.canvas.SaveAs('/'.join([
                            self.plt_dir, 'shapes', 'log' if islogy else 'lin',
                            iformat if iformat != 'pdf' else '',
                            '%s%s.%s' %
                            (label, '_log' if islogy else '_lin', iformat)
                        ]))

            # save only the datacards you want, don't flood everything
            if len(self.datacards) and label not in self.datacards:
                continue

            # FIXME! allow it to save datacards even for non data driven bkgs
            if self.data_driven:
                self.create_datacards(data=all_obs_prompt,
                                      bkgs={
                                          'prompt': all_exp_prompt,
                                          'nonprompt': all_exp_nonprompt
                                      },
                                      signals=all_signals,
                                      label=label)
Example #26
0
        for i, s in enumerate(samples):
            histName = '{}_{}__{}'.format(histType, chan, s)
            h = getattr(f, histName).Clone()
            # h.xaxis.SetRange(1, h.nbins()+1)
            h.title = s
            h.Scale(1. / h.Integral())
            h.drawstyle = 'hist pmc plc'
            h.legendstyle = 'L'
            if s == 'data':
                h.fillstyle = '\\'
                h.color = 'salmon'
                h.drawstyle = 'hist'
                h.legendstyle = 'F'
            hs.append(h)
            legend.AddEntry(h)

        xmin, xmax, ymin, ymax = get_limits(hs)
        draw(hs, pad=c, ytitle='norm. counts/50', ylimits=(0, ymax))
        legend.Draw()
        title = TitleAsLatex('[{}] {}'.format(chan.replace('mu', '#mu'),
                                              histType))
        title.Draw()
        draw_labels('59.74 fb^{-1} (13 TeV)',
                    cms_position='left',
                    extra_text='work-in-progress')

        c.SaveAs('{}/{}_{}.pdf'.format(outdir, histType, chan))
        c.Clear()

f.Close()
Example #27
0
                               1.)

            try:
                axislabel = axislabels[axislabel]
            except:
                axislabel = axislabel
            tmpratio.GetXaxis().SetTitle(axislabel)

    if plotWithROOT:
        pad1.cd()
        ROOT.ATLASLabel(0.2, 0.9,
                        "Internal      %s, %s" % (regionName, kindOfRegion))

        legend = Legend(4, leftmargin=0.45, margin=0.35, topmargin=0.07)
        hists["DataMain"].SetTitle("Data 15+16 %s fb^{-1}" % lumiscale)
        legend.AddEntry(hists["DataMain"], style='ep')
        # sortedHistsToStack.reverse()
        for BG in reversed(sortedHistsToStack):
            BG.SetTitle(BG.GetTitle().replace("MassiveCB", ""))
            legend.AddEntry(BG, style='F')
        for signalsample in signalsamples:
            skip = 1
            try:
                if any([
                        thissig in signalsample
                        for thissig in plottedsignals[regionName]
                ]):
                    skip = 0
            except:
                skip = 1
Example #28
0
dn.Reset()
dn.fill_array(transform(dn_scores))

# Plot the nominal, up, and down scores

canvas = Canvas()
nominal.SetMaximum(max(dn) * 1.1)
nominal.Draw()
nominal.xaxis.SetTitle('BDT Score')
nominal.yaxis.SetTitle('Events')

up.Draw('same hist')
dn.Draw('same hist')

leg = Legend(3, pad=canvas, leftmargin=.5)
leg.AddEntry(nominal, style='LEP')
leg.AddEntry(up, style='L')
leg.AddEntry(dn, style='L')
leg.Draw()
canvas.SaveAs('canvas_original.png')

# Take the ratio of systematic / nominal

ratio_up = up / nominal
ratio_dn = dn / nominal

ratio_canvas = Canvas()
ratio_canvas.SetLogy()
ratio_up.SetMinimum(0.001)
ratio_up.Draw('hist')
ratio_dn.Draw('same hist')
Example #29
0
frame.SetMaximum(1)
frame.SetMinimum(0)
frame.axis().SetTitle("Number of vertices")
frame.axis(2).SetTitle("Efficiency (w.r.t. reco. p_{T}>40 GeV)")

canvas.SetLogy(False)
canvas.SetLeftMargin(0.2)

frame.Draw()
l1_efficiency.Draw('pe same')
uct_efficiency.Draw('pe same')
uct_iso_efficiency.Draw('pe same')

legend = Legend(3, topmargin=0.25, leftmargin=0.25)
legend.AddEntry(l1_efficiency, 'lp', 'Current Tau44')
legend.AddEntry(uct_efficiency, 'lp',
                'Upgrade RlxTau25 Rel. Rate %0.2f' % (9488. / 9355))
legend.AddEntry(uct_iso_efficiency, 'lp',
                'Upgrade IsoTau25 Rel. Rate %0.2f' % (6224. / 9355))
legend.SetBorderSize(0)
legend.SetTextSize(0.03)

legend.Draw()

canvas.SaveAs("eff_vs_pu.png")
canvas.SaveAs("eff_vs_pu.pdf")

frame.Draw()
l1_efficiency.Draw('pe same')
uct_efficiency.Draw('pe same')
ljisotot.Add(psljiso)
ljisotot.color = "#000000"

for p in [pljiso, pproxyiso, psljiso, ljisotot]:
    p.markersize = 0.5
    p.legendstyle = 'LEP'

draw([pljiso, pproxyiso, psljiso, ljisotot], )  # ylimits=(3e-3,1), logy=True)
leg = Legend(4,
             pad=canvas,
             topmargin=0.02,
             margin=0.2,
             entryheight=0.015,
             entrysep=0.01,
             textsize=10)
leg.AddEntry(pproxyiso, label='proxy muon iso')
leg.AddEntry(pljiso, label='lepton-jet iso (proxy events)')
leg.AddEntry(psljiso, label='lepton-jet iso (signal events)')
leg.AddEntry(ljisotot, label='lepton-jet iso (signal+proxy events)')
leg.Draw()
canvas.SaveAs('{}/ch4mu_isolationprofiles.pdf'.format(outdir))
canvas.clear()

proxymusf = pljiso.Clone()
proxymusf.Divide(pproxyiso)
draw([proxymusf], ylimits=(0, 2))
leg = Legend([proxymusf],
             pad=canvas,
             topmargin=0.02,
             margin=0.2,
             entryheight=0.015,