def plot_fits(canvas,
              histos,
              x_range,
              x_bin_step,
              title_formatter,
              save_name,
              label,
              y_fit_range,
              y_range=None,
              title=None,
              xtitle=None,
              ytitle=None,
              hline=None):

    canvas.Clear()
    canvas.Divide(2, 3)

    root_is_dumb = []
    for i in range(1, 7):
        canvas.cd(i)

        title = title_formatter.format(i)
        graph, slices, fits = fit_slices(histos.get(title, default_histo2d),
                                         x_range,
                                         x_bin_step,
                                         y_fit_range=y_fit_range)
        graph.SetMarkerStyle(8)
        graph.SetMarkerSize(1)

        if y_range:
            graph.GetHistogram().SetMinimum(y_range[0])
            graph.GetHistogram().SetMaximum(y_range[1])
            graph.Draw('AP')
            root_is_dumb.append(graph)
        else:
            graph.Draw('AP')
            root_is_dumb.append(graph)

        if hline:
            line = TLine(x_range[0], hline, x_range[1], hline)
            line.SetLineStyle(8)
            line.SetLineWidth(1)
            line.Draw()
            root_is_dumb.append(line)

        if title:
            label.DrawLatex(0.1, 0.925, title)

        if xtitle:
            label.DrawLatex(0.5, 0.015, xtitle)

        if ytitle:
            label.SetTextAngle(90)
            label.DrawLatex(0.035, 0.5, ytitle)
            label.SetTextAngle(0)

    canvas.Print(save_name)

    # For the slices
    slice_can = TCanvas('slice_can', 'slice_can', 1200, 1600)
    slice_pdfname = title_formatter.split('_{}')[0] + '_slices.pdf'
    slice_can.Print(slice_pdfname + '[')
    for i in range(1, 7):
        title = title_formatter.format(i)
        graph, slices, fits = fit_slices(histos.get(title, default_histo2d),
                                         x_range, x_bin_step, y_fit_range)

        # Size of slices page
        nrows = 5
        ncols = int(np.ceil(len(slices) / nrows) + 1)
        slice_can.Clear()
        slice_can.Divide(ncols, nrows)
        for j, (s, f) in enumerate(zip(slices, fits)):
            slice_can.cd(j + 1)
            s.Draw()
            lab.DrawLatex(
                0.15, 0.88, '#mu = {0:6.4f}, #sigma = {1:6.4f}'.format(
                    f.GetParameter(1), f.GetParameter(2)))

        slice_can.Print(slice_pdfname)
    slice_can.Print(slice_pdfname + ']')
Ejemplo n.º 2
0
def make1DLimit(limits2d, par, parlatex, parmin, parmax, samples, boundScale,
                isX):
    limitplot = TCanvas("%slimit" % par, "%s limit" % par, 500, 500)

    limits1d = {
        '2s': [TGraphAsymmErrors(), 0],
        '1s': [TGraphAsymmErrors(), 1],
        'mean': [TGraphAsymmErrors(), 2],
        'obs': [TGraphAsymmErrors(), 3]
    }

    parSize = parmax - parmin

    lowerLimit = 0.0
    lowerLimitFound = False
    upperLimit = 0.0
    upperLimitFound = False

    cutoff = parmin * boundScale
    bound = 0.0
    if isX:
        bound = limits2d['-2s'][0].Interpolate(cutoff, 0.0)
    else:
        bound = limits2d['-2s'][0].Interpolate(0.0, cutoff)

    for i in range(samples):
        parval = parmin + i * parSize / samples

        if isX:
            obs = limits2d['obs'][0].Interpolate(parval, 0.0)
            mean = limits2d['mean'][0].Interpolate(parval, 0.0)
            p1s = limits2d['+1s'][0].Interpolate(parval, 0.0)
            m1s = limits2d['-1s'][0].Interpolate(parval, 0.0)
            p2s = limits2d['+2s'][0].Interpolate(parval, 0.0)
            m2s = limits2d['-2s'][0].Interpolate(parval, 0.0)
        else:
            obs = limits2d['obs'][0].Interpolate(0.0, parval)
            mean = limits2d['mean'][0].Interpolate(0.0, parval)
            p1s = limits2d['+1s'][0].Interpolate(0.0, parval)
            m1s = limits2d['-1s'][0].Interpolate(0.0, parval)
            p2s = limits2d['+2s'][0].Interpolate(0.0, parval)
            m2s = limits2d['-2s'][0].Interpolate(0.0, parval)

        #print m2s, m1s, mean, p1s, p2s

        if obs > 1 and not lowerLimitFound and parval < 0:
            lowerLimit = parval
            lowerLimitFound = True

        if obs < 1 and not upperLimitFound and parval > 0:
            upperLimit = parval
            upperLimitFound = True

        if m2s < bound and fabs(parval) > fabs(cutoff):
            #par1 observed limit
            limits1d['obs'][0].SetPoint(i, parval, obs)
            #mean and one sigma expected
            limits1d['mean'][0].SetPoint(i, parval, mean)
            limits1d['1s'][0].SetPoint(i, parval, mean)
            limits1d['1s'][0].SetPointError(i, 0, 0, mean - m1s, p1s - mean)
            #two sigma expected
            limits1d['2s'][0].SetPoint(i, parval, mean)
            limits1d['2s'][0].SetPointError(i, 0, 0, mean - m2s, p2s - mean)
        else:
            limits1d['obs'][0].SetPoint(i, parval, bound + 0.1)
            limits1d['mean'][0].SetPoint(i, parval, bound + 0.1)
            limits1d['1s'][0].SetPoint(i, parval, bound + 0.1)
            limits1d['1s'][0].SetPointError(i, 0, 0, 0, 0)
            limits1d['2s'][0].SetPoint(i, parval, bound + 0.1)
            limits1d['2s'][0].SetPointError(i, 0, 0, 0, 0)

    print "95% CL on" + " %s = [%.3g,%.3g]" % (par, lowerLimit, upperLimit)

    limitplot.cd()
    limitplot.SetLogy()

    limits1d['2s'][0].SetFillColor(ROOT.kGreen)
    limits1d['2s'][0].Draw("A E3")

    limits1d['1s'][0].SetFillColor(ROOT.kYellow)
    limits1d['1s'][0].Draw("SAME E3")

    limits1d['mean'][0].SetLineStyle(2)
    limits1d['mean'][0].SetLineWidth(2)
    limits1d['mean'][0].Draw("SAME C")

    limits1d['obs'][0].SetLineWidth(2)
    limits1d['obs'][0].Draw("SAME C")

    #titles
    limits1d['2s'][0].GetYaxis().SetTitle(
        "95% CL limit on #sigma/#sigma_{aTGC}")
    limits1d['2s'][0].GetYaxis().SetTitleFont(132)
    limits1d['2s'][0].GetXaxis().SetTitle(parlatex)
    limits1d['2s'][0].GetXaxis().SetTitleFont(132)

    limits1d['2s'][0].GetYaxis().SetRangeUser(
        limits1d['2s'][0].GetYaxis().GetXmin() * 0.75, bound)
    limits1d['2s'][0].GetXaxis().SetRangeUser(parmin * 0.985, parmax * 0.96)

    legend.SetX1NDC(0.183)
    legend.SetY1NDC(0.699)
    legend.SetX2NDC(0.524)
    legend.SetY2NDC(0.930)
    legend.Draw()

    text1d = TPaveText(0.359, 0.265, 0.758, 0.496, "NDC")
    text1d.SetFillStyle(0)
    text1d.SetBorderSize(0)
    text1d.AddText("95% CLs Limit on " + "#bf{%s}" % (parlatex))
    text1d.AddText(0, 0.35, "#intL dt= 4.7 fb^{-1}, #sqrt{s} = 7 TeV")
    text1d.Draw()

    text3.SetX1NDC(0.357)
    text3.SetY1NDC(0.246)
    text3.SetX2NDC(0.756)
    text3.SetY2NDC(0.305)
    text3.Draw()

    textlim = TPaveText(0.357, 0.197, 0.754, 0.246, "NDC")
    textlim.SetFillStyle(0)
    textlim.SetBorderSize(0)
    textlim.AddText("%.2g < %s  < %.2g" % (lowerLimit, parlatex, upperLimit))
    textlim.Draw()

    #lowLimitLine = TLine(lowerLimit,limits1d['2s'][0].GetYaxis().GetXmin()*0.75,
    #                     lowerLimit,1)
    #lowLimitLine.SetLineColor(14)
    #lowLimitLine.SetLineWidth(2)
    #lowLimitLine.Draw()
    #upLimitLine = TLine(upperLimit,limits1d['2s'][0].GetYaxis().GetXmin()*0.75,
    #                    upperLimit,1)
    #upLimitLine.SetLineColor(14)
    #upLimitLine.SetLineWidth(2)
    #upLimitLine.Draw()

    oneLine = TLine(parmin * 0.985, 1, parmax * 0.96, 1)
    oneLine.SetLineStyle(9)
    oneLine.SetLineColor(14)
    oneLine.Draw()

    limitplot.Draw()

    return limitplot.Clone()
Ejemplo n.º 3
0
def plotRatio(name, h1, v_hist, hs, log):
    c = Canvas('c')

    h_sum = TH1F('h_sum','sum',h1.GetNbinsX(), h1.GetXaxis().GetXmin(), h1.GetXaxis().GetXmax())
    for h in v_hist: h_sum.Add(h)
 
    pad1 = TPad('pad1', 'pad1', 0.0, 0.3, 1., 1.)
    pad1.SetBottomMargin(0.005)
    pad1.SetTicks(1,1)
    pad1.Draw()

    c.cd()
    pad2 = TPad('pad2', 'pad2', 0., 0.05, 1., 0.28)
    pad2.SetTopMargin(0.005)
    pad2.SetBottomMargin(0.3)
    pad2.SetTicks(1,1)
    pad2.Draw()

    pad1.cd()
    if log: pad1.SetLogy()
    stack = THStack('norm_stack','')
    h_mc_err = 0
    for h in v_hist: 
        stack.Add(h)
        if h_mc_err == 0: h_mc_err = h.Clone()
        else: h_mc_err.Add(h)
    stack.Draw('HIST')
    h_mc_err.Draw("e2 same")
    h_mc_err.SetMarkerSize(0)
    h_mc_err.SetFillColor(1)
    h_mc_err.SetFillStyle(3004)
    h_data = asym_error_bars(h1)
    h_data.SetLineColor(ROOT.kBlack)
    h_data.SetFillColor(ROOT.kBlack)
    h_data.SetLineWidth(2)
    h_data.Draw('p e2 same')
    hs.Draw('HIST same')
    ymax = h1.GetMaximum()*pow(10,1.0) if log else h1.GetMaximum()*1.5 
    stack.SetMaximum(ymax)
    if log: stack.SetMinimum(1)
    #stack.GetHistogram().GetYaxis().SetTitleFont(43)
    stack.GetHistogram().GetYaxis().SetTitleOffset(1.0)
    stack.GetHistogram().GetYaxis().SetTitleSize(0.05)
    stack.GetHistogram().GetYaxis().SetTitle('Events')
    pLabel, sLabel, lLabel = prelimLabel('left',log,h1.GetMaximum()), selectionLabel(lab,True,log,h1.GetMaximum()), lumiLabel(True,years)
    pLabel.Draw(), sLabel.Draw(), lLabel.Draw()
    legend = makeLegend(h1,v_hist,hs)
    legend.Draw()

    pad2.cd()
    h_ratio = h1.Clone('h_ratio')

    h_ratio.Sumw2()
    h_ratio.Divide(h_sum)
    h_ratio.SetMinimum(-0.499)
    h_ratio.SetMaximum(2.499)
    h_ratio.SetLineColor(ROOT.kBlack)
    h_ratio.SetMarkerStyle(20)
    h_ratio.SetMarkerColor(ROOT.kBlack)
    h_ratio.SetMarkerSize(0.7)
    h_ratio.Draw('p same')
    denom_err, denom_err2 = h_mc_err.Clone(), h_mc_err.Clone()
    denom_err2.Sumw2(False)
    denom_err.Divide(denom_err2)
    denom_err.Draw("e2same")
    denom_err.SetFillColor(1)
    denom_err.SetFillStyle(3004)

    l1 = TLine(h_ratio.GetXaxis().GetXmin(), 1, h_ratio.GetXaxis().GetXmax(), 1)
    l2 = TLine(h_ratio.GetXaxis().GetXmin(), 1.5, h_ratio.GetXaxis().GetXmax(), 1.5)
    l3 = TLine(h_ratio.GetXaxis().GetXmin(), 0.5, h_ratio.GetXaxis().GetXmax(), 0.5)
    l4 = TLine(h_ratio.GetXaxis().GetXmin(), 0., h_ratio.GetXaxis().GetXmax(), 0.)
    l5 = TLine(h_ratio.GetXaxis().GetXmin(), 2, h_ratio.GetXaxis().GetXmax(), 2.)
    l2.SetLineStyle(3), l3.SetLineStyle(3), l4.SetLineStyle(3), l5.SetLineStyle(3)
    l1.Draw(), l2.Draw(), l3.Draw(), l4.Draw(), l5.Draw()

    Prettify( h_ratio )

    #ax  = h_ratio.GetXaxis();
    #ax.SetNdivisions(506);

    if len(years) == 1: c.SaveAs('plots/%s/%s_%s.%s' % (years[0],name,selection,extension))
    else: c.SaveAs('plots/combined/%s_%s_%s.%s' % (name,selection,s_years,extension)) 
Ejemplo n.º 4
0
 text7.SetLineWidth(2)
 text7.Draw()
 text5 = TLatex(0.98, 0.95125, "#sqrt{s} = 13 TeV, 25 ns")
 text5.SetNDC()
 text5.SetTextAlign(31)
 text5.SetTextFont(42)
 text5.SetTextSize(0.04875)
 text5.SetLineWidth(2)
 text5.Draw()
 tmp_canvas.cd(2)
 if histogram_name in ["subFlightDistance3dSig"]:
     pulls[histogram_name_index].Draw("e1 X0")
 else:
     pulls[histogram_name_index].Draw("e1 x0")
 if histogram_name in ["subTrackSip3dSig"]:
     line1 = TLine(-10, 1.0, 10, 1.0)
     line1.SetLineStyle(2)
     line1.Draw()
     line2 = TLine(-10, 2.0, 10, 2.0)
     line2.SetLineStyle(2)
     line2.Draw()
 else:
     line1 = TLine(
         stacked_mc[histogram_name_index].GetXaxis().GetXmin(), 1.0,
         stacked_mc[histogram_name_index].GetXaxis().GetXmax(), 1.0)
     line1.SetLineStyle(2)
     line1.Draw()
     line2 = TLine(
         stacked_mc[histogram_name_index].GetXaxis().GetXmin(), 2.0,
         stacked_mc[histogram_name_index].GetXaxis().GetXmax(), 2.0)
     line2.SetLineStyle(2)
Ejemplo n.º 5
0
def addLine(theta, centerx, centery):
    line = TLine(centerx, centery, centerx + 200 * np.cos(theta),
                 centery + 200 * np.sin(theta))
    line.SetLineColor(2)
    return line
Ejemplo n.º 6
0
def drawCut(hist):
    #drawCut(80, 140, 0., hist['BkgSum'].GetMaximum())
    line1 = TLine(80, 0, 80, hist['BkgSum'].GetMaximum())
    line1.SetLineWidth(2)
    line1.SetLineStyle(7)
    line1.SetLineColor(1)
    line1.Draw()
    
    line2 = TLine(140, 0, 140, hist['BkgSum'].GetMaximum())
    line2.SetLineWidth(2)
    line2.SetLineStyle(7)
    line2.SetLineColor(1)
    line2.Draw()
    
    line1 = TLine(0.841, 0, 0.841, 15)
    line1.SetLineWidth(2)
    line1.SetLineStyle(7)
    line1.SetLineColor(1)
    line1.Draw()
    
    line1 = TLine(100, 0, 100, hist['BkgSum'].GetMaximum())
    line1.SetLineWidth(2)
    line1.SetLineStyle(7)
    line1.SetLineColor(1)
    line1.Draw()
Ejemplo n.º 7
0
def draw():
    hists = allHists()
    for region in regions:
        os.mkdir("plots/%s" % region)
        for variable in variables:
            hist_data = hists[region + "_" + variable + "_data"]
            mchists = []
            for i in processes:
                if i != 'data':
                    temp = hists[region + "_" + variable + "_" + i]
                    mchists.append(temp)
            hs = makeStack(mchists)
            h_bkg, h_ratio, h_ratio_err, upArrowBins = makeRatio(
                hist_data, mchists, hs)
            c, pad1, pad2 = createCanvasPads()
            XTitle, YTitle = (titles[variable])[0], (titles[variable])[1]
            #stack plot
            pad1.cd()
            leg = TLegend(0.60, 0.70, 0.90, 0.90)
            leg.SetNColumns(2)
            leg.SetFillStyle(0)
            leg.SetBorderSize(0)
            leg.AddEntry(hist_data, "data", "pe")
            for i in processes:
                if i != 'data':
                    leg.AddEntry(hists[region + "_" + variable + "_" + i], i,
                                 "f")
            leg.AddEntry(h_bkg, "uncertainty", 'f')
            Ymaximum = 3.5 * hist_data.GetBinContent(hist_data.GetMaximumBin())
            hs.SetMaximum(Ymaximum)
            hs.SetMinimum(0.001)
            hs.SetTitle("")
            hs.Draw("hist")  # thstack must draw first
            hs.GetYaxis().SetTitleSize(0.06)
            hs.GetYaxis().SetTitleOffset(1)
            hs.GetYaxis().SetTitle(YTitle)
            hs.GetXaxis().SetTitle("")
            hs.GetXaxis().SetTitleSize(0.)
            hs.GetXaxis().SetLabelSize(0.)
            h_bkg.Draw("E2 same")
            hist_data.SetMarkerStyle(20)
            hist_data.SetMarkerSize(0.8)
            hist_data.Draw("e x0 same")
            createLabels()
            leg.Draw("same")
            #ratio plot
            pad2.cd()
            h_ratio.SetMinimum(0.0)
            h_ratio.SetMaximum(2.0)
            h_ratio.GetYaxis().SetTitle("Data/Bkg")
            h_ratio.GetYaxis().SetTitleSize(0.06)
            h_ratio.GetYaxis().SetTitleOffset(1)
            h_ratio.GetXaxis().SetTitle(XTitle)
            h_ratio.GetXaxis().SetLabelSize(0.14)
            h_ratio.GetXaxis().SetLabelOffset(0.025)
            h_ratio.GetXaxis().SetTitleSize(0.13)
            h_ratio.GetXaxis().SetTitleOffset(1.05)
            h_ratio.GetYaxis().SetLabelSize(0.1)
            h_ratio.GetYaxis().SetTitleSize(0.14)
            h_ratio.GetYaxis().SetTitleOffset(0.40)
            h_ratio.GetYaxis().SetNdivisions(505)
            h_ratio.SetMarkerStyle(20)
            h_ratio.SetMarkerSize(0.8)
            h_ratio_err.SetMarkerSize(0)
            h_ratio_err.SetFillColor(17)
            h_ratio.Draw("e x0")
            h_ratio_err.Draw("e2 same")
            h_ratio.Draw("axis same")
            h_ratio.Draw("e x0 same")

            for iBin in upArrowBins:
                binCenter = h_ratio.GetBinCenter(iBin)
                a = TArrow(binCenter, 1.7, binCenter, 1.95, 0.01, "|>")
                a.SetLineWidth(3)
                a.SetLineColor(2)
                a.SetFillColor(2)
                a.Draw()

            line = TLine()
            line.DrawLine(h_ratio.GetXaxis().GetXmin(), 1.0,
                          h_ratio.GetXaxis().GetXmax(), 1.0)
            line.SetLineColor(kBlack)
            line.SetLineStyle(kDashed)
            line.DrawLine(h_ratio.GetXaxis().GetXmin(), 0.5,
                          h_ratio.GetXaxis().GetXmax(), 0.5)
            line.DrawLine(h_ratio.GetXaxis().GetXmin(), 1.5,
                          h_ratio.GetXaxis().GetXmax(), 1.5)

            c.SaveAs("plots/%s/%s.pdf" % (region, variable))
    hRhoVsPt.append(inFile.Get('rhovspt'))
    hRhoVsPt[iFile].SetName(f'hRhoVsPt_{iFile}')
    hRhoVsPt[iFile].SetDirectory(0)
    inFile.Close()

for iFile, fileNameFrac in enumerate(inFilesFrac):
    inFile = TFile.Open(fileNameFrac)
    hPromptFracVsPt.append(inFile.Get('hPromptFrac'))
    hPromptFracVsPt[iFile].SetName(f'hPromptFracVsPt_{iFile}')
    hPromptFracVsPt[iFile].SetDirectory(0)
    hNonPromptFracVsPt.append(inFile.Get('hFDFrac'))
    hNonPromptFracVsPt[iFile].SetName(f'hPromptFracVsPt_{iFile}')
    hNonPromptFracVsPt[iFile].SetDirectory(0)
    inFile.Close()

lineNoPol = TLine(0., 1. / 3, 1., 1. / 3)
lineNoPol.SetLineWidth(2)
lineNoPol.SetLineStyle(9)
lineNoPol.SetLineColor(GetROOTColor('kGrey+2'))

lineNoPolVsPt = TLine(ptMins[0], 1. / 3, ptMaxs[-1], 1. / 3)
lineNoPolVsPt.SetLineWidth(2)
lineNoPolVsPt.SetLineStyle(9)
lineNoPolVsPt.SetLineColor(GetROOTColor('kGrey+2'))

nPtBins = len(ptMins)
cRho00VsPromptFrac = TCanvas('cRho00VsPromptFrac', '', 1200, 400)
cRho00VsNonPromptFrac = TCanvas('cRho00VsNonPromptFrac', '', 1200, 400)
DivideCanvas(cRho00VsPromptFrac, nPtBins)
DivideCanvas(cRho00VsNonPromptFrac, nPtBins)
gRho00VsPromptFrac, gRho00VsNonPromptFrac, fRho00VsPromptFrac, fRho00VsNonPromptFrac = (
Ejemplo n.º 9
0
h_pionminus_long_trans.SetTitleSize(0.05)
h_pionminus_long_trans.SetLabelSize(0.05)
h_pionminus_long_trans.SetTitleSize(0.05)
c4.SetLeftMargin(0.15)
c4.SetBottomMargin(0.12)
c4.SetRightMargin(0.14)
gStyle.SetTitleH(0.07)

# FOR each row, for each column, fill TLine( 1,2,3,4)
#file_reader = csv.reader('NA49_pion_coverage.csv', 'rb', delimiter=' ,')
#    for row in file_reader:
#...         print ', '.join(row)
#xF    pT

#box 1
line1 = TLine(-0.1125, 0.35, -0.0875, 0.35)
line2 = TLine(-0.0875, 0.35, -0.0875, 0.25)
line3 = TLine(-0.0875, 0.25, -0.0625, 0.25)
line4 = TLine(-0.0625, 0.25, -0.0625, 0.75)
line5 = TLine(-0.0625, 0.75, -0.055, 0.75)
line6 = TLine(-0.055, 0.75, -0.055, 0.35)
line7 = TLine(-0.055, 0.35, 0.17, 0.35)
line8 = TLine(0.17, 0.35, 0.17, 0.65)
line9 = TLine(0.17, 0.65, 0.175, 0.65)
line10 = TLine(0.175, 0.65, 0.175, 0.35)
line11 = TLine(0.175, 0.35, 0.225, 0.35)
line12 = TLine(0.225, 0.35, 0.225, 0.325)
line13 = TLine(0.225, 0.325, 0.175, 0.325)
line14 = TLine(0.175, 0.325, 0.175, 0.025)
line15 = TLine(0.175, 0.025, 0.225, 0.025)
line16 = TLine(0.225, 0.025, 0.225, 0.045)
Ejemplo n.º 10
0
title.Draw()

# horizonthal file layout
file = TPave( 1, 8.5, 20, 11 )
file.SetFillColor( 11 )
file.Draw()
fileh = TPave( 1, 8.5, 2.5, 11 )
fileh.SetFillColor( 44 )
fileh.Draw()
lrh = TPave( 2.5, 8.5, 3.3, 11, 1 )
lrh.SetFillColor( 33 )
lrh.Draw()
lrh.DrawPave( 6.9, 8.5, 7.7, 11, 1 )
lrh.DrawPave( 10.5, 8.5, 11.3, 11, 1 )
lrh.DrawPave( 14.5, 8.5, 15.3, 11, 1 )
ldot = TLine( 1, 8.5, 0.5, 6.5 )
ldot.SetLineStyle( 2 )
ldot.Draw()
ldot.DrawLine( 2.5, 8.5, 9.4, 6.5 )
ldot.DrawLine( 10.5, 8.5, 10, 6.5 )
ldot.DrawLine( 11.3, 8.5, 19.5, 6.5 )
line = TLine( 2.6, 11, 2.6, 11.5 )
line.Draw()
line.DrawLine( 2.6, 11.5, 7, 11.5 )
arrow = TArrow( 7, 11.5, 7, 11.1, 0.01, '|>' )
arrow.SetFillStyle( 1001 )
arrow.Draw()
line.DrawLine( 7, 8.5, 7, 8.0 )
line.DrawLine( 7, 8.0, 10.6, 8 )
arrow.DrawArrow( 10.6,8, 10.6, 8.4, 0.01, '|>' )
line.DrawLine( 10.6, 11, 10.6, 11.5 )
Ejemplo n.º 11
0
def runAllPlots():
    c = TCanvas("c", "c", 800, 600)
    c.SetLogy()
    c.SetGrid(1, 1)

    # CONSTANTS
    kpb = 0.02
    eLo, eHi = 0.1, 12.
    binRange = 2.
    pks = [1.739, 1.836, 2.307, 2.464, 6.404]
    frankFlux = [4.95e+38, 4.95e+38, 3.94e+38, 2.27e+38, 4.06e+38]

    redondoScale = 1e19 * 0.511e-10**-2  # convert table to [cts / (keV cm^2 d)]
    jcapScale = 1e-13**2. * 365 * 1e4 * 1e-20  # (gae in paper * per yr * per m^2 * 10^-20 scaling)
    barnsPerAtom = 120.5
    nAvo = 6.0221409e+23
    phoScale = 72.64 / nAvo  # (ge mol mass / nAvo)
    axConvScale = phoScale / 1000  # (ge mol mass / nAvo / 1000 g/kg)
    beta = 1.
    sigAeScale = beta**-1 * 3. / (16. * np.pi * (1. / 137.) *
                                  511.**2.) * (1 - beta**(2. / 3.) / 3)

    # 1. Reproduce Redondo's data and Frank's axion flux points.

    axData, axEne, axFlux = [], [], []
    with open("../data/redondoFlux.txt") as f1:
        lines = f1.readlines()[11:]
        for line in lines:
            data = line.split()
            axData.append([float(data[0]), float(data[1])])
            axEne.append(float(data[0]))
            axFlux.append(float(data[1]) * redondoScale)
    axData = np.array(axData)

    g1 = TGraph(len(axEne), array('d', axEne), array('d', axFlux))
    g1.SetTitle(" ")
    g1.GetXaxis().SetTitle("Energy (kev)")
    g1.GetYaxis().SetTitle("flux (kev^{-1} cm^{-2} d^{-1})")
    g1.SetMarkerColor(ROOT.kRed)
    g1.SetMaximum(1.5e40)
    g1.SetMinimum(8e37)
    g1.Draw()
    l1 = TLine(pks[4], min(axFlux), pks[4], max(axFlux))
    l1.SetLineColor(ROOT.kRed)
    l1.Draw("same")

    # verify the algorithm to translate into a hist (used for RooFit) works correctly
    nBins = int((eHi - eLo) / kpb)
    h1 = TH1D("h1", "h1", nBins, eLo, eHi)
    for i in range(nBins):
        ene = i * kpb + eLo
        eneLo, eneHi = ene - kpb / 2., ene + kpb / 2.
        idx = np.where((axData[:, 0] >= eneLo) & (axData[:, 0] <= eneHi))
        flux = 0.
        with warnings.catch_warnings(
        ):  # ignore "mean of empty slice" errors (they're harmless)
            warnings.simplefilter("ignore", category=RuntimeWarning)
            flux = np.mean(axData[idx][:, 1]) * redondoScale
        if np.isnan(flux): flux = 0.
        h1.SetBinContent(i, flux)
    h1.SetLineColor(ROOT.kBlue)
    h1.Draw("same")

    g2 = TGraph(len(pks), array('d', pks), array('d', frankFlux))
    g2.SetMarkerStyle(20)
    g2.SetMarkerColor(ROOT.kRed)
    g2.Draw("P same")

    clintFlux = []
    ax = h1.GetXaxis()
    for pk in pks:
        # "* kpb" is same as using "width" option in integral
        intFlux = h1.Integral(ax.FindBin(pk - kpb * binRange),
                              ax.FindBin(pk + kpb * binRange)) * kpb
        clintFlux.append(intFlux)
    g3 = TGraph(len(pks), array('d', pks), array('d', clintFlux))
    g3.SetMarkerStyle(20)
    g3.SetMarkerColor(ROOT.kGreen)
    g3.Draw("P same")

    leg = TLegend(0.6, 0.6, 0.85, 0.85)
    leg.AddEntry(g1, "raw data", "p")
    leg.AddEntry(h1, "histo 0.02 kev/bin", "l")
    leg.AddEntry(l1, "6.404 kev", "l")
    leg.AddEntry(g2, "frank flux", "p")
    leg.AddEntry(g3, "clint flux", "p")
    leg.Draw("same")

    c.Print("../plots/axFluxCompare.pdf")

    # 2. Reproduce Graham's axion flux plot

    c.Clear()
    axFluxCm2Sec = [f * 86400**-1. for f in axFlux]
    g4 = TGraph(len(axEne), array('d', axEne), array('d', axFluxCm2Sec))
    g4.SetTitle(" ")
    g4.GetXaxis().SetTitle("Energy (kev)")
    g4.GetYaxis().SetTitle("flux (kev^{-1} cm^{-2} s^{-1})")
    g4.SetMarkerColor(ROOT.kBlue)
    g4.Draw()
    c.Print("../plots/axFluxGraham.pdf")

    # 3. Reproduce Redondo's JCAP figure 2 in : https://arxiv.org/pdf/1310.0823v1.pdf

    c.Clear()
    c.SetGrid(0, 0)
    c.SetCanvasSize(800, 800)
    c.SetLogy(0)
    axFluxJCAP = [f * jcapScale for f in axFlux]
    g5 = TGraph(len(axEne), array('d', axEne), array('d', axFluxJCAP))
    g5.SetTitle(" ")
    g5.GetXaxis().SetTitle("Energy (keV)")
    g5.GetYaxis().SetTitle("flux 10^{-20} kev^{-1} y^{-1}  m^{-2}")
    g5.SetMarkerColor(ROOT.kBlack)
    g5.SetMaximum(3.1)
    g5.SetMinimum(-0.1)
    g5.Draw()
    c.Print("../plots/axFluxJCAP.pdf")

    # 4. Plot the photoelectric cross section from mucal.

    phoData, phoEne, phoVal = [], [], []
    with open(
            "../data/ge76peXS.txt") as f2:  # 2499 entries, 0.01 kev intervals
        lines = f2.readlines()
        for line in lines:
            data = line.split()
            phoData.append([float(data[0]), float(data[1])])
            phoEne.append(float(data[0]))
            phoVal.append(float(data[1]))
    phoData, phoEne, phoVal = np.array(phoData), np.array(phoEne), np.array(
        phoVal)

    c.Clear()
    c.SetCanvasSize(800, 600)
    c.SetLogy(1)
    phoValScaled = [v * barnsPerAtom for v in phoVal]  # barns/atom
    g6 = TGraph(len(phoEne), array('d', phoEne), array('d', phoVal))
    g6.SetTitle(" ")
    g6.GetXaxis().SetTitle("Energy (keV)")
    g6.GetYaxis().SetTitle("#sigma_{pe} (cm^{2}/g)")
    g6.GetXaxis().SetRangeUser(0.1, 12.)
    g6.SetMinimum(10)
    g6.SetMaximum(3e5)
    g6.SetMarkerColor(ROOT.kBlue)
    g6.Draw()
    c.Print("../plots/mucalPho.pdf")

    # 5. Plot the axioelectric cross section (2 vals of beta, 1 and 5)

    c.Clear()
    c.SetGrid(1, 1)
    axioVal = [
        phoVal[idx] * sigAeScale * phoEne[idx]**2. * barnsPerAtom
        for idx in range(len(phoVal))
    ]

    g7 = TGraph(len(phoEne), array('d', phoEne), array('d', axioVal))
    g7.Draw("AL")

    g7.GetXaxis().SetTitle("Energy (keV)")
    g7.GetYaxis().SetTitle("#sigma_{ae} (barns/atom)")
    g7.GetXaxis().SetRangeUser(0.1, 12.)
    g7.SetTitle(" ")
    g7.SetLineColor(ROOT.kBlue)
    g7.SetLineWidth(2)
    g7.SetMinimum(1)
    g7.SetMaximum(6e2)
    c.Update()

    # 5 kev axion (new formula for sigma_ae)
    def sig_ae(E, m):
        beta = (1 - m**2. / E**2.)**(1. / 2)
        return (1 -
                (1. / 3.) * beta**(2. / 3.)) * (3. * E**2.) / (16. * np.pi *
                                                               (1. / 137.) *
                                                               511.**2. * beta)

    idx = np.where(phoEne > 5)
    axioVal2 = [
        phoVal[idx][i] * sig_ae(phoEne[idx][i], 5.) * barnsPerAtom
        for i in range(len(phoVal[idx]))
    ]
    axioVal2.insert(0, 0.)
    phoEne2 = phoEne[idx].tolist()
    phoEne2.insert(0, 5.)

    g8 = TGraph(len(phoEne2), array('d', phoEne2), array('d', axioVal2))
    g8.SetLineColor(ROOT.kRed)
    g8.Draw("L same")

    leg2 = TLegend(0.65, 0.75, 0.85, 0.85)
    leg2.AddEntry(g7, "m_{a}= 0 keV", "l")
    leg2.AddEntry(g8, "m_{a}= 5 keV", "l")
    leg2.Draw("same")

    # convert to histogram (for RooDataHist)
    nBins = int((eHi - eLo) / kpb)
    h2 = TH1D("h2", "h2", nBins, eLo, eHi)
    for i in range(nBins):
        ene = i * kpb + eLo
        eneLo, eneHi = ene - kpb / 2., ene + kpb / 2.
        # ignore "mean of empty slice" errors (they're harmless)
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", category=RuntimeWarning)
            idx = np.where((phoData[:, 0] >= eneLo) & (phoData[:, 0] <= eneHi))
            pho = np.mean(phoData[idx][:, 1])
            if np.isnan(pho) or len(phoData[idx][:, 1]) == 0: pho = 0.
            axio = pho * ene**2. * sigAeScale * barnsPerAtom
            h2.SetBinContent(i, axio)
    h2.SetLineColor(ROOT.kBlack)
    h2.Draw("hist same")

    c.Print("../plots/axioElectric.pdf")

    # 6. convolve the axion flux w/ the axioelectric effect.  (bins are different so use a histogram)

    nBins = int((eHi - eLo) / kpb)
    h3 = TH1D("h3", "", nBins, eLo, eHi)
    for i in range(nBins):
        ene = i * kpb + eLo
        eneLo, eneHi = ene - kpb / 2., ene + kpb / 2.
        # ignore "mean of empty slice" errors (they're harmless)
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", category=RuntimeWarning)

            # axioelectric x-section [cm^2 / kg]
            idx = np.where((phoData[:, 0] >= eneLo) & (phoData[:, 0] <= eneHi))
            pho = np.mean(phoData[idx][:, 1])
            if np.isnan(pho) or len(phoData[idx][:, 1]) == 0: pho = 0.
            axio = pho * ene**2. * sigAeScale * 1000.

            # axion flux [cts / (cm^2 d keV)]
            idx = np.where((axData[:, 0] >= eneLo) & (axData[:, 0] <= eneHi))
            flux = np.mean(axData[idx][:, 1]) * redondoScale
            if np.isnan(flux): flux = 0.

            # convolved [cts / (keV d kg)]
            axConv = axio * flux
            h3.SetBinContent(i, axConv)

    c.Clear()
    h3.SetLineColor(ROOT.kBlue)
    h3.SetMinimum(2e39)
    h3.SetMaximum(4e42)
    h3.GetXaxis().SetTitle("Energy (keV)")
    h3.GetYaxis().SetTitle("flux cts kev^{-1} d^{-1} kg^{-1}")
    h3.Draw("hist")
    c.Print("../plots/axionConv.pdf")

    # 7. reproduce the rest of frank's numbers in his tables from MY HISTOGRAMS
    # and calculate g_ae

    print "sig_ae factor: ", sigAeScale

    binRange = 2.
    phos, axos, cFlux, cRateHist = [], [], [], []
    ax1, ax3 = h1.GetXaxis(), h3.GetXaxis()
    for pk in pks:
        eneLo, eneHi = pk - kpb, pk + kpb

        # photoelectric
        idx = np.where((phoData[:, 0] >= eneLo) & (phoData[:, 0] <= eneHi))
        pho = np.mean(phoData[idx][:, 1]) * phoScale  # [cm^2 / atom]
        phos.append(pho)

        # axioelectric
        axos.append(pho * pk**2. * sigAeScale)

        # axion flux
        flux = h1.Integral(ax1.FindBin(pk - kpb * binRange),
                           ax1.FindBin(pk + kpb * binRange)) * kpb
        cFlux.append(flux)

        # axion rate - integrate histogram directly (proof it's correct if it matches frank's table)
        conv = h3.Integral(
            ax3.FindBin(pk - kpb * binRange),
            ax3.FindBin(pk + kpb * binRange)) * kpb * axConvScale
        cRateHist.append(conv)

    frankRates = [axos[i] * frankFlux[i] for i in range(len(axos))]
    cRateTable = [axos[i] * cFlux[i] for i in range(len(axos))]

    # stackoverflow trick to make list printing prettier
    class prettyfloat(float):
        def __repr__(self):
            return "%.2e" % self

    print "T3,C2: E^2 * (sigAeScale)             ", map(
        prettyfloat, [np.power(ax, 2.) * sigAeScale for ax in pks])
    print "T3,C3: sig_pe (cm^2/atom)             ", map(prettyfloat, phos)
    print "T3,C4: sig_ae                         ", map(prettyfloat, axos)
    print "T4,C2 (old): Phi_a (cm^2/d)           ", map(prettyfloat, frankFlux)
    print "T4,C2 (new):                          ", map(prettyfloat, clintFlux)
    print "T4,C4 (table): Phi_a * sig_ae (cts/d) ", map(
        prettyfloat, cRateTable)
    print "T4,C4 (histo):                        ", map(prettyfloat, cRateHist)

    # exposure,  expected counts, upper bound on g_ae
    malbekExpo = 89.5  # kg-d
    exposure = malbekExpo * 1000 * (
        1. / 72.64
    ) * nAvo  # [atom-d] = [kg d][1000 g/kg][1/72.64 mol/g][nAvo atom/mol]

    N_obs = 10.  # just a guess

    # Compare methods
    N_exp = exposure * sum(frankFlux[i] * axos[i] for i in range(4))
    g_ae = np.power(N_obs / N_exp, 1. / 4.)  # upper bound
    print "Frank's Table g_ae: %.2e" % g_ae

    N_exp = exposure * sum(cRateTable[i] for i in range(4))
    g_ae = np.power(N_obs / N_exp, 1. / 4.)  # upper bound
    print "Clint's Table g_ae: %.2e" % g_ae

    N_exp = exposure * sum(cRateHist[i] for i in range(4))
    g_ae = np.power(N_obs / N_exp, 1. / 4.)  # upper bound
    print "Clint's Histo g_ae: %.2e" % g_ae

    print "Histo peaks expected counts: ", N_exp
    N_exp = h3.Integral(ax3.FindBin(1.5),
                        ax3.FindBin(8.)) * kpb * axConvScale * exposure
    print "Continuum expected counts: ", N_exp

    # 8. do the tritium plot

    tritData, tritEne, tritVal = [], [], []
    with open("../data/TritiumSpectrum.txt") as f3:  # 20000 entries
        lines = f3.readlines()[1:]
        for line in lines:
            data = line.split()
            conv = float(data[2])  # raw spectrum convolved w/ ge cross section
            if conv < 0: conv = 0.
            tritData.append([float(data[1]), conv])
            tritEne.append(float(data[1]))
            tritVal.append(conv)
    tritData = np.array(tritData)

    c.Clear()
    c.SetLogy(0)
    g8 = TGraph(len(tritEne), array('d', tritEne), array('d', tritVal))
    g8.SetTitle(" ")
    g8.GetXaxis().SetTitle("Energy (keV)")
    g8.GetYaxis().SetTitle("Counts (norm.)")
    g8.SetMarkerColor(ROOT.kRed)
    g8.Draw()

    kpb = 0.02
    eLo, eHi = 0.1, 20.
    nBins = int((eHi - eLo) / kpb)
    h4 = TH1D("h4", "h4", nBins, eLo, eHi)
    for i in range(nBins):
        ene = i * kpb + eLo
        eneLo, eneHi = ene - kpb / 2., ene + kpb / 2.
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", category=RuntimeWarning)
            idx = np.where((tritData[:, 0] >= eneLo)
                           & (tritData[:, 0] <= eneHi))
            trit = np.mean(tritData[idx][:, 1])
            if np.isnan(trit): trit = 0.
            h4.SetBinContent(i, trit)
            if trit == 0.: print "Trit bin %d is zero" % i

    h4.SetLineColor(ROOT.kBlue)
    h4.Draw("hist same")
    c.Print("../plots/tritSpec.pdf")
Ejemplo n.º 12
0
WH.GetYaxis().SetTitle('<p_{T}^{Reco}/p_{T}^{Truth}>')
WH.GetYaxis().SetTitleOffset(1.05)
WH.GetYaxis().SetTitleSize(0.040)
WH.GetYaxis().SetLabelSize(0.040)

## Legend Setup
l = TLegend(0.60, 0.77, 0.88, 0.89)
l.SetFillColor(0)
l.SetBorderSize(0)
l.SetTextSize(0.04)
l.AddEntry(WH, 'WH #rightarrow l#nu b#bar{b} p_{T}^{Reco}', 'p')
l.AddEntry(ZH, 'ZH #rightarrow ll b#bar{b} p_{T}^{Reco}', 'p')
l.Draw('SAME')

## Text On Plot
t = TLatex()
t.SetNDC()
t.SetTextSize(0.04)
t.SetTextAlign(13)
t.DrawLatex(0.13, 0.87, '#bf{Simulation}')
t.DrawLatex(0.13, 0.83, '#bf{#it{2 b-Tag; 1l ; p_{T}^{V} inc.}}')

## Line at y = 1
line = TLine(20, 1, 280, 1)
line.SetLineWidth(2)
line.SetLineColor(1)
line.SetLineStyle(2)
line.Draw('SAME')

c.Print('Plots/Profile/prof_cw_ZH_WH.pdf')
Ejemplo n.º 13
0
c1.cd()

for i, graph in enumerate(graphsMem):
    if i == 0:
        graph.SetTitle('Threshold Scan;Threshold (DAC);Number of Hits')
        graph.GetYaxis().SetRangeUser(0, max(eventArray) * 1.1)
        graph.Draw("APL")
    else:
        graph.Draw("PL")

for graph in graphsCounter:
    graph.SetLineColor(3)
    graph.Draw("PL")

# Add line for nMax
line = TLine(0, max(eventArray), graphsMem[0].GetXaxis().GetXmax(),
             max(eventArray))
line.SetLineColor(2)
line.Draw()

print "Max number of events during scan: %s" % max(eventArray)

#########################
### Begin calibration ###
#########################

calibconf = config._confs[options.mpa - 1]
calibconfxmlroot = config._confsxmlroot[options.mpa - 1]

### Calculate trim values
trimOffsetArray = []
for i, pxl in enumerate(
def plot_sector_page(canvas,
                     histos,
                     title_formatter,
                     label,
                     save_name,
                     xtitle=None,
                     ytitle=None,
                     title=None,
                     log=False,
                     y_fit_range=None,
                     landscape=False,
                     x_range=None,
                     vline=None,
                     hline=None):

    root_garbage_can = []

    canvas.Clear()
    if landscape:
        canvas.Divide(3, 2)
    else:
        canvas.Divide(2, 3)

    for i in range(1, 7):
        canvas.cd(i)

        #if isinstance(histos[title_formatter.format(i)], TH1F):
        if isinstance(histos.get(title_formatter.format(i), default_histo),
                      TH1F):

            if y_fit_range:
                fit = TF1(title_formatter.format(i) + '_fit', 'gaus')
                histos.get(title_formatter.format(i),
                           default_histo).Fit(fit, '', 'R', y_fit_range[0],
                                              y_fit_range[1])

            if x_range:
                histos.get(title_formatter.format(i),
                           default_histo).GetXaxis().SetRangeUser(
                               x_range[0], x_range[1])

            histos.get(title_formatter.format(i),
                       default_histo).SetFillColorAlpha(55, 0.65)
            histos.get(title_formatter.format(i), default_histo).Draw()

            if y_fit_range:
                label.DrawLatex(
                    0.15, 0.86, '#mu = {0:6.4f}, #sigma = {1:6.4f}'.format(
                        fit.GetParameter(1), fit.GetParameter(2)))

        #elif isinstance(histos[title_formatter.format(i)], TH2F):
        elif isinstance(histos.get(title_formatter.format(i), default_histo),
                        TH2F):
            # histos[title_formatter.format(i)].Draw('colz')
            histos.get(title_formatter.format(i), default_histo).Draw('colz')
            if log:
                gPad.SetLogz()
        else:
            #raise NotImplementedException('plot_sector_page only supports TH1F, TH2F')
            pass

        if vline:
            line = TLine(
                vline,
                histos.get(title_formatter.format(i),
                           default_histo).GetYaxis().GetXmin(), vline,
                histos.get(title_formatter.format(i),
                           default_histo).GetYaxis().GetXmax())
            line.SetLineColor(1)
            line.SetLineStyle(1)
            line.Draw('same')
            root_garbage_can.append(line)

        if hline:
            xmin = histos.get(title_formatter.format(i)).GetXaxis().GetXmin()
            xmax = histos.get(title_formatter.format(i)).GetXaxis().GetXmax()
            line = TLine(xmin, hline, xmax, hline)
            line.SetLineColor(1)
            line.SetLineStyle(1)
            line.Draw('same')
            root_garbage_can.append(line)

        if title:
            label.DrawLatex(0.1, 0.925, title)

        if xtitle:
            label.DrawLatex(0.5, 0.015, xtitle)

        if ytitle:
            label.SetTextAngle(90)
            label.DrawLatex(0.04, 0.5, ytitle)
            label.SetTextAngle(0)

    canvas.Print(save_name)
Ejemplo n.º 15
0
def drawLine(x1, y1, x2, y2):
    line = TLine(x1, y1, x2, y2)
    line.SetLineStyle(2)
    line.SetLineWidth(2)
    line.Draw()
    return line
Ejemplo n.º 16
0
def plotPerDirectionBx(options):
    """Save directional fit plots (per BX) to PDF files"""
    name = options['scan'] + '_' + options['name'] + options['fitted']
    if 'method' in options:
        name += '_' + options['method']
    name += '_collected'
    f = openRootFileR(name)
    for bx in options['crossings']:
        plotname = plotName(name + '_bx' + str(bx), timestamp=False)
        filename = plotName(name + '_bx' + str(bx), timestamp=True)
        filepath = plotPath(name + '_bx' + str(bx), timestamp=True)
        print '<<< Save plot:', filepath
        graphs = f.Get(plotname)
        residuals = f.Get(plotname + '_residuals')
        if 'final' in options:
            graphs.SetTitle('')
            residuals.SetTitle('')

        gStyle.SetOptFit(options['optfit'])
        canvas = TCanvas(plotname + '_canvas', '', 700, 600)

        canvas.cd()
        canvas.SetMargin(0.13, 0.03, 0.33, 0.05)

        graphs.Draw('AP')
        gPad.Update()
        text = TLatex()
        text.SetNDC()
        for j, graph in enumerate(graphs.GetListOfGraphs()):
            graph.SetMarkerStyle(21)
            graph.SetMarkerColor(2 + 2 * j)
            graph.GetFunction(options['fit']).SetLineColor(2 + 2 * j)
            stats = graph.GetListOfFunctions().FindObject('stats')
            stats.SetTextColor(2 + 2 * j)
            stats.SetBorderSize(0)
            stats.SetTextSize(0.04)
            inverted = graph.GetFunction(
                options['fit']).GetParameter('p1') < 0.0
            text.SetTextFont(42)
            text.SetTextSize(0.04)
            text.SetTextColor(2 + 2 * j)
            if inverted and j == 0:
                text.DrawLatex(0.18, 0.54, options['scan'] + ' scan forward')
                stats.SetX1NDC(0.16)
                stats.SetX2NDC(0.53)
                stats.SetY1NDC(0.38)
                stats.SetY2NDC(0.53)
            elif inverted and j == 1:
                text.DrawLatex(0.61, 0.9, options['scan'] + ' scan backward')
                stats.SetX1NDC(0.59)
                stats.SetX2NDC(0.96)
                stats.SetY1NDC(0.74)
                stats.SetY2NDC(0.89)
            elif j == 0:
                text.DrawLatex(0.18, 0.9, options['scan'] + ' scan forward')
                stats.SetX1NDC(0.16)
                stats.SetX2NDC(0.53)
                stats.SetY1NDC(0.74)
                stats.SetY2NDC(0.89)
            else:
                text.DrawLatex(0.61, 0.54, options['scan'] + ' scan backward')
                stats.SetX1NDC(0.59)
                stats.SetX2NDC(0.96)
                stats.SetY1NDC(0.38)
                stats.SetY2NDC(0.53)
        graphs.GetXaxis().SetTitle('Nominal Position [#mum]')
        graphs.GetYaxis().SetTitle(options['ytitle'])
        graphs.GetYaxis().SetTitleOffset(1.3)
        if ('final' in options):
            text.SetTextColor(1)
            text.SetTextFont(42)
            text.SetTextSize(0.04)
            text.SetTextAlign(31)
            text.DrawLatex(0.97, 0.96, O['plotsig'])
            text.SetTextAlign(11)
            if options['final'] == 'wip':
                text.SetTextFont(52)
                text.SetTextSize(0.04)
                text.DrawLatex(0.13, 0.96, 'Work in Progress')
            else:
                text.SetTextFont(62)
                text.SetTextSize(0.05)
                text.DrawLatex(0.13, 0.96, 'CMS')
                text.SetTextFont(52)
                text.SetTextSize(0.04)
                text.DrawLatex(0.22, 0.96, 'Preliminary')
        for axis in [graphs.GetYaxis(), graphs.GetXaxis()]:
            axis.SetTitleSize(0.05)
            axis.SetLabelSize(0.04)
            axis.SetLabelOffset(0.01)
            axis.CenterTitle()

        pad = TPad('pad', 'pad', 0, 0, 1, 0.2)
        pad.Draw()
        pad.cd()
        pad.SetMargin(0.13, 0.03, 0.01, 0.01)
        for j, residual in enumerate(residuals.GetListOfGraphs()):
            residual.SetMarkerStyle(21)
            residual.SetMarkerColor(2 + 2 * j)
        residuals.Draw("AP")
        residuals.GetXaxis().SetTitle('')
        residuals.GetXaxis().SetLabelSize(0.0)
        residuals.GetXaxis().SetTickSize(0.151)
        residuals.GetYaxis().SetNdivisions(305)
        residuals.GetYaxis().SetTickSize(0.019)
        residuals.GetYaxis().SetLabelSize(0.2)
        residuals.GetYaxis().SetLabelOffset(0.01)
        pad.Update()
        line = TLine(pad.GetUxmin(), 0.0, pad.GetUxmax(), 0.0)
        line.SetLineColor(14)
        line.SetLineStyle(3)
        line.Draw()

        canvas.cd()
        text.SetTextFont(42)
        text.SetTextSize(0.05)
        text.SetTextAngle(90.0)
        text.DrawLatex(0.035, 0.0, 'Resid. ' + options['restitle'])

        if not 'final' in options:
            drawSignature(filename)
        # canvas.Modified()
        # canvas.Update()
        canvas.Print(filepath)
        canvas.Close()
    closeRootFile(f, name)
Ejemplo n.º 17
0
def drawCut(cut, ymin, ymax):
    line = TLine()
    line.SetLineWidth(2)
    line.SetLineStyle(7)
    line.SetLineColor(1)
    line.PaintLineNDC(cut, ymin, cut, ymax)
Ejemplo n.º 18
0
def addTRUGrid(subsystem, hist):
    """ Add a grid of TLines representing the TRU on a canvas.

    Note:
        Assumes that the canvas is already created.

    Note:
        Allocates a large number of TLines which have SetOwnership(obj, False),
        so this could lead to memory problems.

    """
    # TEMP
    logger.debug("TRU Grid histName: {0}".format(hist.histName))

    # Draw grid for TRUs in full EMCal SMs
    for x in range(8, 48, 8):
        line = TLine(x, 0, x, 60)
        SetOwnership(line, False)
        line.Draw()
    # 60 + 1 to ensure that 60 is plotted
    for y in range(12, 60 + 1, 12):
        line = TLine(0, y, 48, y)
        SetOwnership(line, False)
        line.Draw()

    # Draw grid for TRUs in 1/3 EMCal SMs
    line = TLine(0, 64, 48, 64)
    SetOwnership(line, False)
    line.Draw()
    line = TLine(24, 60, 24, 64)
    SetOwnership(line, False)
    line.Draw()

    # Draw grid for TRUs in 2/3 DCal SMs
    for x in range(8, 48, 8):
        if (x == 24):
            # skip PHOS hole
            continue
        line = TLine(x, 64, x, 100)
        SetOwnership(line, False)
        line.Draw()
    for y in range(76, 100, 12):
        line = TLine(0, y, 16, y)
        SetOwnership(line, False)
        line.Draw()
        # skip PHOS hole
        line = TLine(32, y, 48, y)
        SetOwnership(line, False)
        line.Draw()

    # Draw grid for TRUs in 1/3 DCal SMs
    line = TLine(0, 100, 48, 100)
    SetOwnership(line, False)
    line.Draw()
    line = TLine(24, 100, 24, 104)
    SetOwnership(line, False)
    line.Draw()
Ejemplo n.º 19
0
def myMarkerTextSmall2(x, y, lcolor, lstyle, mcolor, mstyle, msize, size, text):
    l = TLatex()
    l.SetTextAlign(12)
    l.SetTextSize(size/2.5)
    l.SetNDC()
    l.DrawLatex(x,y,text)

    yb1 = y-0.15*size
    yb2 = y+0.15*size
    xb1 = x-0.28*size-0.45*size
    xb2 = x+0.28*size-0.45*size

    print("box  = ",xb1,yb1,xb2,yb2)
    
    #print("line = ",xl1,yl1,xl2,yl2)
    mline1 = TLine(xb1,yb1,xb2,yb2)
    mline1.SetLineColor(lcolor)
    mline1.SetLineStyle(lstyle)
    mline1.SetLineWidth(2)
    y_new=(yb1+yb2)/2.
    mline1.DrawLineNDC(xb1,y_new,xb2,y_new)
    
    mline2 = TLine(xb1,yb1,xb2,yb2)
    mline2.SetLineColor(lcolor)
    mline2.SetLineStyle(lstyle)
    mline2.SetLineWidth(2)
    x_new=(xb1+xb2)/2.
    mline2.DrawLineNDC(x_new,yb1,x_new,yb2)

    marker = TMarker((xb1+xb2)/2.0,y,mstyle)
    marker.SetNDC()
    marker.SetMarkerColor(mcolor)
    marker.SetMarkerStyle(mstyle)
    marker.SetMarkerSize(msize)
    marker.Draw()
    
    return marker
Ejemplo n.º 20
0
def plotEfficiencyForPt(folder, pt):
    if (DEBUG):
        print prefix + 'was called'

    #Set plot style

    if (DEBUG):
        print prefix + "Getting histogram: %s" % (
            "hoMuonAnalyzer/efficiency/GenAndL1MuonPt" + str(pt) +
            "_Efficiency")

    l1Muon = fileHandler.getHistogram(
        "hoMuonAnalyzer/efficiency/GenAndL1MuonPt" + str(pt) + "_Efficiency")
    l1MuonAndHo = fileHandler.getHistogram(
        "hoMuonAnalyzer/efficiency/L1MuonHoRecoPt" + str(pt) + "_Efficiency")
    if (DEBUG):
        print prefix + "Getting histogram: %s" % (
            "hoMuonAnalyzer/efficiency/GenAndL1MuonAndHoAboveThrPt" + str(pt) +
            "_Efficiency")
    l1MuonAndHoAboveThr = fileHandler.getHistogram(
        "hoMuonAnalyzer/efficiency/GenAndL1MuonAndHoAboveThrPt" + str(pt) +
        "_Efficiency")

    canv = TCanvas("efficiencyCanvas" + str(pt), 'efficiencyCanvas' + str(pt),
                   1200, 1200)

    l1Muon.SetMarkerStyle(markerpairs[pt / 5 - 1][0])
    l1MuonAndHo.SetMarkerStyle(21)
    l1MuonAndHoAboveThr.SetMarkerStyle(markerpairs[pt / 5 - 1][1])

    l1Muon.SetMarkerColor(colorRwthDarkBlue)
    l1MuonAndHo.SetMarkerColor(ROOT.kBlue)
    l1MuonAndHoAboveThr.SetMarkerColor(colorRwthMagenta)

    l1Muon.SetLineColor(colorRwthDarkBlue)
    l1MuonAndHo.SetLineColor(ROOT.kBlue)
    l1MuonAndHoAboveThr.SetLineColor(colorRwthMagenta)

    upperPad = TPad("upperPad", "upperPad", .005, .25, .995, .995)
    lowerPad = TPad("lowerPad", "lowerPad", .005, .005, .995, .25)
    upperPad.SetBottomMargin(0)
    lowerPad.SetTopMargin(0)
    upperPad.Draw()
    lowerPad.Draw()
    upperPad.cd()
    l1Muon.Draw()
    #	l1MuonAndHo.Draw('same')
    l1MuonAndHoAboveThr.Draw('same')

    canv.Update()
    l1Muon.GetPaintedGraph().GetYaxis().SetTitleFont(62)
    l1Muon.GetPaintedGraph().GetYaxis().SetLabelFont(62)
    l1Muon.GetPaintedGraph().GetXaxis().SetRangeUser(0, 50)
    #.GetPaintedGraph()
    l1Muon.SetTitle("Efficiency, p_{T} = " + str(pt) + " GeV;p_{T};Eff.")
    canv.Update()

    line = TLine(pt, 0, pt, 1)
    line.SetLineColor(ROOT.kRed)
    line.SetLineWidth(2)
    line.Draw()

    legend = TLegend(0.5, 0.1, 0.9, 0.35)
    legend.AddEntry(l1Muon, 'L1 Efficiency', 'ep')
    legend.AddEntry(l1MuonAndHoAboveThr, 'L1 + HO hits > 0.2 GeV', 'ep')
    legend.AddEntry(line, 'Trg. threshold', 'e')
    legend.Draw()

    integralL1 = 0
    integralL1AndHo = 0
    for i in range(0, pt + 1):
        integralL1 += l1Muon.GetPassedHistogram().GetBinContent(pt + 1)
        integralL1AndHo += l1MuonAndHoAboveThr.GetPassedHistogram(
        ).GetBinContent(pt + 1)

    paveText = TPaveText(0.5, 0.35, 0.9, 0.4, 'NDC')
    if (not integralL1 == 0):
        paveText.AddText('%s: %.2f%% #pm %.2f%%' %
                         ('Reduction below threshold',
                          100 - integralL1AndHo / integralL1 * 100,
                          calcSigma(integralL1AndHo, integralL1) * 100))
        paveText.SetBorderSize(1)
        paveText.Draw()

    label = drawLabelCmsPrivateSimulation()
    ##### Try creating residuals
    lowerPad.cd()
    l1MuonGraph = l1Muon.GetPaintedGraph()
    l1MuonAndHoAboveThrGraph = l1MuonAndHoAboveThr.GetPaintedGraph()

    newGraph = TGraph()

    x1 = Double(0)
    y1 = Double(0)
    x2 = Double(0)
    y2 = Double(0)

    for i in range(0, 50):
        l1MuonGraph.GetPoint(i, x1, y1)
        l1MuonAndHoAboveThrGraph.GetPoint(i, x2, y2)
        newGraph.SetPoint(i, x1, (y1 - y2) * 100)

    newGraph.SetMarkerStyle(20)
    newGraph.GetYaxis().SetTitle("%")
    newGraph.Draw("a,p")
    newGraph.GetXaxis().SetLimits(0, 50)
    line2 = TLine(0, 0, 50, 0)
    line2.SetLineColor(ROOT.kRed)
    line2.SetLineWidth(2)
    line2.Draw()

    ##### Finally save the stuff

    canv.SaveAs("plots/efficiency/efficiency" + str(pt) + ".png")
    canv.SaveAs("plots/efficiency/efficiency" + str(pt) + ".pdf")

    f = TFile.Open("plots/efficiency/efficiency" + str(pt) + ".root",
                   "RECREATE")
    canv.Write()
    f.Close()
    return [
        l1Muon, l1MuonAndHoAboveThr, canv, legend, line, paveText, label,
        newGraph
    ]
Ejemplo n.º 21
0
            canvas.cd(2)
            for ratio in ratios:
                ratio.SetTitle("")
                ratio.SetTickLength(0.08)
                ratio.GetYaxis().SetTitle("ratio")
                ratio.GetXaxis().SetTitle("track |#eta|")
                ratio.GetYaxis().CenterTitle()
                ratio.GetYaxis().SetTitleSize(0.11)
                ratio.GetYaxis().SetTitleOffset(0.43)
                ratio.GetXaxis().SetTitleSize(0.11)
                ratio.GetYaxis().SetLabelSize(0.11)
                ratio.GetXaxis().SetLabelSize(0.11)
                ratio.GetYaxis().SetRangeUser(0.01, 3.2)
                ratio.GetYaxis().SetNdivisions(304)
                ratio.Draw("E0 same")
            l1 = TLine(0, 1, 4, 1)
            l1.SetLineStyle(3)
            l1.SetLineWidth(1)
            l1.Draw("same")

            outputFile.cd()
            canvas.Write()
            canvas.SaveAs(arguments.outputDir + "/" + plot_name + ".pdf")

#outputFile.Close()

########################################################################################
########################################################################################
########################################################################################
########################################################################################
Ejemplo n.º 22
0
# Magnetic center point of undulator
UNDULATOR_ZCENTER = numpy.sum(MaxByZChopped)
print 'UNDULATOR_ZCENTER: ', UNDULATOR_ZCENTER, '[m]'

# Start and end of Undulator in Z
UNDULATOR_ZSTART = UNDULATOR_ZCENTER - (PERIOD_LENGTH * (NPERIODS + 4) / 2)
UNDULATOR_ZEND = UNDULATOR_ZCENTER + (PERIOD_LENGTH * (NPERIODS + 4) / 2)
UNDULATOR_LENGTH = UNDULATOR_ZEND - UNDULATOR_ZSTART
print 'UNDULATOR ZSTART ZEND LENGTH:', UNDULATOR_ZSTART, UNDULATOR_ZEND, UNDULATOR_LENGTH

# Peak By to use in calculations
PEAK_BY = AvgMaxBy

# Draw Undulator fields and START, CENTER, END
if SectionNumber == 0:
    lStart = TLine(UNDULATOR_ZSTART, -1, UNDULATOR_ZSTART, 1)
    lStart.SetLineColor(2)
    lCenter = TLine(UNDULATOR_ZCENTER, -1, UNDULATOR_ZCENTER, 1)
    lCenter.SetLineColor(2)
    lEnd = TLine(UNDULATOR_ZEND, -1, UNDULATOR_ZEND, 1)
    lEnd.SetLineColor(2)

    cBxLines = TCanvas('Undulator_Bx')
    gBx.Draw("ACP")
    lStart.Draw()
    lCenter.Draw()
    lEnd.Draw()
    cBxLines.Write()

    cByLines = TCanvas('Undulator_By')
    gBy.Draw("ACP")
Ejemplo n.º 23
0
    pCMS1.Draw()
    pCMS11.Draw()
    pCMS12.Draw()
    pCMS2.Draw()
    #	pCMS22.Draw()
    leg = ROOT.TLegend(0.7, 0.75, 0.9, 0.9)
    leg.AddEntry(list_ratio[num], "JetHT", "PE")
    leg.AddEntry(list_ratio_mc[num], "QCD", "PE")
    leg.SetFillStyle(-1)
    leg.SetBorderSize(0)
    leg.SetTextFont(42)
    leg.SetTextSize(0.03)
    leg.Draw()

    if (btag == 0):
        line = TLine(presel_cuts[num], y_min, presel_cuts[num], y_max)
        line.SetLineStyle(9)
        line.SetLineColor(8)
        line.SetLineWidth(3)
        line.Draw()

    pad2 = ROOT.TPad("pad2", "pad2", 0., 0., 1., 1.)
    pad2.SetTopMargin(0.73)
    #	pad2.SetBottomMargin(0.)
    #	pad2.SetRightMargin(0.)
    pad2.SetFillColor(0)
    pad2.SetFillStyle(0)
    pad2.Draw()
    pad2.cd()
    frame2 = ROOT.TH1F("frame2", "", 1, xmin, xmax)
    frame2.SetMinimum(0.)
Ejemplo n.º 24
0
 binLabel = ''
 if etBin is not None and etaBin is not None:
   binLabel = '_'.join( [ str(etBin[0]).zfill(4), str(etaBin[0]).zfill(4) ] )
 canvas1 = TCanvas(title, title, 500, 500)
 histEff.SetTitle(title + ' in: ' + binLabel if binLabel else title )
 histEff.SetLineColor(kGray)
 histEff.SetMarkerColor(kGray)
 # FIXME Care with Transparent 
 histEff.SetFillColor(TColor.GetColorTransparent(kGray, .5))
 histEffCorr.SetLineColor(kBlue+1)
 histEffCorr.SetMarkerColor(kBlue+1)
 histEffCorr.SetFillColor(TColor.GetColorTransparent(kBlue+1, .5))
 drawopt='lpE2'
 AddHistogram(canvas1,histEff,drawopt)
 AddHistogram(canvas1,histEffCorr,drawopt)
 l0 = TLine(limits[0],refValue,limits[2],refValue)
 l0.SetLineColor(kBlack)
 l0.Draw()
 #l1 = TLine(limits[0],refValue_requested,limits[2],refValue_requested)
 #l1.SetLineColor(kGray+2)
 #l1.SetLineStyle(9)
 #l1.Draw()
 AddTopLabels( canvas1, [ eff_uncorr.thresstr( prefix = 'Raw threshold' )
                        , eff.thresstr( prefix = 'Threshold Correction' )
                        ]
             , legOpt='p')
 FormatCanvasAxes(canvas1, XLabelSize=18, YLabelSize=18, XTitleOffset=0.87, YTitleOffset=1.5)
 SetAxisLabels(canvas1, xname, '#epsilon(' + eff.pileupStr + ')' )
 FixYaxisRanges(canvas1, ignoreErrors=False, yminc=-eps)
 AutoFixAxes(canvas1, ignoreErrors=False)
 AddBinLines(canvas1, histEff)
Ejemplo n.º 25
0
def PlotDataMC(dataFiles_, mcFiles_, signalFiles_, dataDirec_, mcDirec_,
               signalDirec_, drawPads_, Lumi_, SigScale_, ol_, log_, Tags_,
               VarBatch_, CutsType_, verbose_, noQCD_):
    print "Plotting Data / MC"
    gROOT.ProcessLine(
        "gErrorIgnoreLevel = kError"
    )  # kPrint, kInfo, kWarning, kError, kBreak, kSysError, kFatal
    gStyle.SetOptStat(0)
    gStyle.SetErrorX(0.0001)
    HHWWggTags = []

    ##-- Get Tags
    for t in Tags_:
        HHWWggTags.append(t)
    cuts, cutNames = GetCuts(CutsType_)

    ##-- if var batch is loose, need separate titles for variables since it will be sum of vars * bools
    if (VarBatch_ == "Loose"):
        finalStateVars, varNames = GetVars(
            VarBatch_)  # get vars from var batch
        if (verbose_):
            print "finalStateVars = ", finalStateVars
            print "varNames = ", varNames
    else:
        finalStateVars = GetVars(VarBatch_)  # get vars from var batch
    if (verbose_):
        #print"cuts:",cuts
        print "cutNames:", cutNames
        print "vars:", finalStateVars

    ##-- For each data file (can just be one)
    for dF_ in dataFiles_:
        cutBatchTag_pairs = []
        dataNevents_list = []
        MC_names = []
        MC_Nevents_lists = []
        MC_Nevents_noweight_lists = []

        ##-- For each category (Ex: HHWWggTag_0, HHWWggTag_1, HHWWggTag_2, combined)
        for itag, HHWWggTag in enumerate(HHWWggTags):
            if (verbose_):
                print "tag:", HHWWggTag
            dPath = "%s/%s" % (dataDirec_, dF_)
            dFile = TFile.Open(dPath)
            if (HHWWggTag == "combined"):
                ch = TChain('tagsDumper/trees/Data_13TeV_HHWWggTag_0')
                ch.Add("%s/tagsDumper/trees/Data_13TeV_HHWWggTag_0" % (dPath))
                ch.Add("%s/tagsDumper/trees/Data_13TeV_HHWWggTag_1" % (dPath))
                ch.Add("%s/tagsDumper/trees/Data_13TeV_HHWWggTag_2" % (dPath))
            else:
                ch = TChain('tagsDumper/trees/Data_13TeV_%s' % (HHWWggTag))
                ch.Add(dPath)
            BLIND_CUT = "(CMS_hgg_mass < 115 || CMS_hgg_mass > 135)"
            MC_WEIGHT = "1*weight"
            ZERO_CUT = "ZERO_CUT"
            MC_CUT = "%s*(%s)*(%s)" % (MC_WEIGHT, BLIND_CUT, ZERO_CUT)
            DATA_CUT = "%s*(%s)" % (BLIND_CUT, ZERO_CUT)
            SIGNAL_CUT = "%s*(%s)" % (MC_WEIGHT, ZERO_CUT
                                      )  # no blind cut on signal

            ##-- For each cut
            for ic, cut in enumerate(cuts):
                #if(verbose_): print"Plotting with selection:",cut
                cutName = cutNames[ic]
                cutBatchTag = "%s_%s" % (cutName, HHWWggTag)
                cutBatchTag_pairs.append(cutBatchTag)
                dataNevents = -999
                these_MC_Nevents = []
                these_MC_Nevents_noweights = []
                outputFolder = "%s/%s" % (ol_, cutName)
                if (not os.path.exists(outputFolder)):
                    os.system('mkdir %s' % (outputFolder))
                    os.system('cp %s/index.php %s' % (ol_, outputFolder))
                MC_CUT += "*(%s)" % (cut)
                DATA_CUT += "*(%s)" % (cut)
                SIGNAL_CUT += "*(%s)" % (cut)

                ##-- For each variable
                for iv, v in enumerate(finalStateVars):
                    if (VarBatch_ == "Loose"): varTitle = varNames[iv]
                    else: varTitle = GetVarTitle(v)

                    if (verbose_): print "Plotting variable:", varTitle

                    MC_CUT = MC_CUT.replace(
                        "ZERO_CUT", "(%s != 0) && (%s != -999)" % (v, v))
                    DATA_CUT = DATA_CUT.replace(
                        "ZERO_CUT", "(%s != 0) && (%s != -999)" % (v, v))
                    SIGNAL_CUT = SIGNAL_CUT.replace(
                        "ZERO_CUT", "(%s != 0) && (%s != -999)" % (v, v))
                    MC_CUT_NOWEIGHT = MC_WEIGHT.replace(MC_WEIGHT, "(1)")

                    if (varTitle == "weight"):
                        MC_CUT = MC_CUT.replace(
                            MC_WEIGHT, "(1)"
                        )  # if you want to plot the "weight" variable, you should not scale it by weight!

                    ##-- Can add printing of cuts to debug
                    # if(verbose_):
                    # print"MC_CUT:",MC_CUT
                    # print"DATA_CUT:",DATA_CUT
                    ##--

                    legend = TLegend(0.55, 0.65, 0.89, 0.89)
                    legend.SetTextSize(0.025)
                    legend.SetBorderSize(0)
                    legend.SetFillStyle(0)
                    xbins, xmin, xmax = GetBins(varTitle)

                    ##-- Fill histogram with data
                    Data_h_tmp = TH1F('Data_h_tmp', varTitle, xbins, xmin,
                                      xmax)
                    Data_h_tmp.SetTitle("%s" % (varTitle))
                    Data_h_tmp.SetMarkerStyle(8)
                    exec('ch.Draw("%s >> Data_h_tmp","%s")' % (v, DATA_CUT))

                    ##-- Only save number of events for first variable. Should be same for all because same cut is used
                    if (iv == 0):
                        dataNevents = Data_h_tmp.GetEntries()
                        dataNevents_list.append(dataNevents)
                    # print"Blinded Data numEvents:",Data_h_tmp.GetEntries()
                    DataHist = Data_h_tmp.Clone("DataHist")
                    DataHist.SetDirectory(0)
                    legend.AddEntry(DataHist, "Data", "P")

                    ##-- Get histograms with MC Backgrounds
                    bkgStack = THStack("bkgStack", "bkgStack")
                    histos = []
                    histCategories = []
                    for i, mcF_ in enumerate(mcFiles_):
                        mcPath = "%s/%s" % (mcDirec_, mcF_)
                        mcFile = TFile.Open(mcPath)
                        treeName = GetMCTreeName(mcF_)
                        MC_Category = GetMCCategory(mcF_)
                        if (verbose_):
                            # print"Background File:",mcPath
                            print "Background:", MC_Category

                        ##-- If noQCD set to true, skip QCD for Tag_0 and Tag_1
                        if (MC_Category == "QCD") and (
                                noQCD_) and (HHWWggTag == "HHWWggTag_0"
                                             or HHWWggTag == "HHWWggTag_1"):
                            print "Skipping QCD"
                            these_MC_Nevents_noweights.append(
                                0)  # Set yields to 0 for table
                            these_MC_Nevents.append(
                                0)  # Set yields to 0 for table
                            if (itag == 0 and ic == 0 and iv == 0):
                                MCname = GetMCName(mcF_)
                                MC_names.append(
                                    MCname
                                )  # Skipping QCD, but still save name for yields because tag_2 may not be 0
                            continue

                        ##-- Define TChain based on categories
                        if (HHWWggTag == "combined"):
                            mc_ch = TChain(
                                'tagsDumper/trees/%s_13TeV_HHWWggTag_0' %
                                (treeName))
                            mc_ch.Add(
                                "%s/tagsDumper/trees/%s_13TeV_HHWWggTag_0" %
                                (mcPath, treeName))
                            mc_ch.Add(
                                "%s/tagsDumper/trees/%s_13TeV_HHWWggTag_1" %
                                (mcPath, treeName))
                            mc_ch.Add(
                                "%s/tagsDumper/trees/%s_13TeV_HHWWggTag_2" %
                                (mcPath, treeName))
                        else:
                            mc_ch = TChain('tagsDumper/trees/%s_13TeV_%s' %
                                           (treeName, HHWWggTag))
                            mc_ch.Add(mcPath)
                        xbins, xmin, xmax = GetBins(varTitle)
                        exec(
                            "MC_h_tmp_%s = TH1F('MC_h_tmp_%s',varTitle,xbins,xmin,xmax)"
                            % (i, i))
                        exec(
                            "MC_h_tmp_noweight_%s = TH1F('MC_h_tmp_noweight_%s',varTitle,xbins,xmin,xmax)"
                            % (i, i))
                        thisHist = eval("MC_h_tmp_%s" % (i))
                        mcColor = GetMCColor(MC_Category)

                        ##-- If GJet or QCD sample, need to remove prompt-prompt events
                        if (MC_Category == "GJet" or MC_Category == "QCD"):
                            if (verbose_): print "Remove prompt-prompt"
                            removePromptPromptCut = "(!((Leading_Photon_genMatchType == 1) && (Subleading_Photon_genMatchType == 1)))"  # selection: remove events where both photons are prompt
                            original_MC_CUT = "%s" % (MC_CUT)
                            this_MC_CUT = "%s*(%s)" % (original_MC_CUT,
                                                       removePromptPromptCut)
                            this_MC_CUT_NOWEIGHT = this_MC_CUT.replace(
                                MC_WEIGHT, "(1)")

                        eval("MC_h_tmp_%s.SetFillColor(eval(mcColor))" % (i))
                        eval("MC_h_tmp_%s.SetLineColor(eval(mcColor))" % (i))
                        if (MC_Category == "GJet" or MC_Category == "QCD"):
                            exec('mc_ch.Draw("%s >> MC_h_tmp_%s","%s")' %
                                 (v, i, this_MC_CUT))
                        else:
                            exec('mc_ch.Draw("%s >> MC_h_tmp_%s","%s")' %
                                 (v, i, MC_CUT))

                        eval("MC_h_tmp_%s.Scale(float(Lumi_))" % (i))

                        ##-- MC reweighting for HHWWgg backgrounds (turned off for now)
                        # reWeightVals = ReWeightMC(mcF_)
                        # doReWeight, reWeightScale = reWeightVals[0], reWeightVals[1]
                        # print"doReWeight,reWeightScale:",doReWeight, reWeightScale
                        # if(doReWeight):
                        #     if(verbose_):
                        #         print"ReWeighting MC"
                        #         print"With scale: ",reWeightScale
                        #     eval("MC_h_tmp_%s.Scale(float(reWeightScale))"%(i))
                        ##

                        ##-- Only save for 1st variable. Should be same for all variables
                        if (iv == 0):
                            if (MC_Category == "GJet" or MC_Category == "QCD"):
                                exec(
                                    'mc_ch.Draw("%s >> MC_h_tmp_noweight_%s","%s")'
                                    % (v, i, this_MC_CUT_NOWEIGHT))
                            else:
                                exec(
                                    'mc_ch.Draw("%s >> MC_h_tmp_noweight_%s","%s")'
                                    % (v, i, MC_CUT_NOWEIGHT))
                            these_MC_Nevents_noweights.append(
                                eval("MC_h_tmp_noweight_%s.Integral()" % (i)))
                            these_MC_Nevents.append(
                                eval("MC_h_tmp_%s.Integral()" % (i)))

                            ##-- Only need to get MC names once
                            if (itag == 0 and ic == 0 and iv == 0):
                                MCname = GetMCName(mcF_)
                                MC_names.append(
                                    MCname)  # get shorter MC name here

                        newHist = thisHist.Clone("newHist")
                        ##-- Set title based on treeName
                        newHist.SetTitle(MC_Category)
                        newHist.GetXaxis().SetTitle(mcF_)
                        newHist.SetDirectory(0)
                        histos.append(newHist)
                        histCategories.append(MC_Category)

                    sig_histos = []
                    sig_histCategories = []

                    ##-- Add Signal to plots
                    for i, sigF_ in enumerate(signalFiles_):
                        sigPath = "%s/%s" % (signalDirec_, sigF_)
                        sigFile = TFile.Open(sigPath)
                        treeName = GetMCTreeName(sigF_)
                        MC_Category = GetMCCategory(sigF_)
                        if (verbose_):
                            # print"Signal File:",sigPath
                            print "Signal:", MC_Category
                        if (HHWWggTag == "combined"):
                            mc_ch = TChain(
                                'tagsDumper/trees/%s_13TeV_HHWWggTag_0' %
                                (treeName))
                            mc_ch.Add(
                                "%s/tagsDumper/trees/%s_13TeV_HHWWggTag_0" %
                                (sigPath, treeName))
                            mc_ch.Add(
                                "%s/tagsDumper/trees/%s_13TeV_HHWWggTag_1" %
                                (sigPath, treeName))
                            mc_ch.Add(
                                "%s/tagsDumper/trees/%s_13TeV_HHWWggTag_2" %
                                (sigPath, treeName))
                        else:
                            mc_ch = TChain('tagsDumper/trees/%s_13TeV_%s' %
                                           (treeName, HHWWggTag))
                            mc_ch.Add(sigPath)
                        xbins, xmin, xmax = GetBins(varTitle)
                        exec(
                            "MC_h_tmp_%s = TH1F('MC_h_tmp_%s',v,xbins,xmin,xmax)"
                            % (i, i))
                        thisHist = eval("MC_h_tmp_%s" % (i))
                        mcColor = GetMCColor(MC_Category)
                        ##-- Style options for signal to distinguish from Data, Background
                        # eval("MC_h_tmp_%s.SetFillColor(eval(mcColor))"%(i))
                        # eval("MC_h_tmp_%s.SetFillStyle(3004)"%(i))
                        ##--
                        eval("MC_h_tmp_%s.SetFillColorAlpha(eval(mcColor),0.1)"
                             % (i))
                        eval("MC_h_tmp_%s.SetLineColor(eval(mcColor))" % (i))
                        exec('mc_ch.Draw("%s >> MC_h_tmp_%s","%s")' %
                             (v, i, SIGNAL_CUT))
                        eval("MC_h_tmp_%s.Scale(float(Lumi_))" %
                             (i))  # should scale to luminosity by default
                        SigXS_Scale = GetXScale(
                            "HHWWgg_v2-6"
                        )  # how to scale the XS which is by default in flashgg 1fb
                        if (verbose_): print "SigXS_Scale: ", SigXS_Scale
                        eval("MC_h_tmp_%s.Scale(float(SigXS_Scale))" %
                             (i))  # should scale to luminosity by default
                        newHist = thisHist.Clone("newHist")

                        ##-- Set title based on treeName
                        newHist.SetTitle(MC_Category)
                        newHist.GetXaxis().SetTitle(sigF_)
                        newHist.SetLineStyle(1)
                        newHist.SetLineWidth(5)

                        newHist.SetDirectory(0)
                        sig_histos.append(newHist)
                        sig_histCategories.append(MC_Category)

                    MC_AddedtoLegend = {
                        "QCD": 0,
                        "SMhgg": 0,
                        "GJet": 0,
                        "DiPhoJets": 0,
                        "DiPhoJetsBox": 0,
                        # "W1JetsToLNu" : 0,
                        # "W2JetsToLNu" : 0,
                        # "W3JetsToLNu" : 0,
                        # "W4JetsToLNu" : 0,
                        "WJets": 0,
                        "WW": 0,
                        "tt": 0,
                        "DY": 0,
                        "WGGJets": 0,
                        "WGJJ": 0,
                        "ttW": 0
                    }

                    Signals_AddedtoLegend = {"HHWWgg_SM": 0}

                    ##-- Order histograms by MC category
                    orderedHistos = OrderHistos(histos, histCategories)
                    sig_orderedHistos = OrderHistos(sig_histos,
                                                    sig_histCategories)

                    ##-- Add backgrounds to background stack
                    for h in orderedHistos:
                        bkgStack.Add(h, 'hist')
                        bkgName = h.GetTitle()
                        added = MC_AddedtoLegend[bkgName]
                        if (added): continue
                        else:
                            legend.AddEntry(h, bkgName, "F")
                            MC_AddedtoLegend[bkgName] = 1

                    ##-- By default draw background save background contributions. Later delete if not wanted
                    outName = "%s/BackgroundsTest_%s.png" % (outputFolder,
                                                             HHWWggTag)
                    bkgOutName = "%s/BackgroundsPADS_%s_%s.png" % (
                        outputFolder, varTitle, HHWWggTag)
                    SimpleDrawHisto(bkgStack, "PADS", bkgOutName, varTitle)
                    bkgOutName = bkgOutName.replace(".png", ".pdf")
                    SimpleDrawHisto(bkgStack, "PADS", bkgOutName, varTitle)

                    ##-- Add text box with selection type
                    offset = 0
                    selText = TLatex(0.129, 0.85, cutName)
                    selText.SetNDC(1)
                    selText.SetTextSize(0.04)
                    CatText = TLatex(0.129, 0.8, HHWWggTag)
                    CatText.SetNDC(1)
                    CatText.SetTextSize(0.04)
                    stackSum = bkgStack.GetStack().Last(
                    )  #->Draw(); # for computing ratio
                    stackSum.Sumw2()
                    stackSum.SetLineColor(kBlack)
                    stackSum.SetLineStyle(
                        7)  # to distinguish from data uncertainty
                    DataHist.SetLineColor(kBlack)
                    DataHist.Sumw2()
                    xTitle = GetXaxisTitle(varTitle)
                    DataHist.GetXaxis().SetTitle(xTitle)
                    if (log_):
                        DataHist.SetMinimum(0.01)
                        stackSum.SetMinimum(0.01)
                        bkgStack.SetMinimum(0.01)

                    ##-- Define ratio plot for computing Data / MC ratio
                    rp = TRatioPlot(DataHist, stackSum)
                    rp.SetH1DrawOpt("P")
                    rp.SetH2DrawOpt("hist")
                    # rp.SetGraphDrawOpt("PE2")
                    dMax = DataHist.GetMaximum()
                    bMax = stackSum.GetMaximum()
                    maxHeight = max(dMax, bMax)

                    ##-- Create the entire picture: Combine Data, MC, Data / MC ratio and signal in one plot

                    for fileType in ["pdf"]:
                        gStyle.SetErrorX(0.0001)
                        # varTitle = GetVarTitle(v)
                        outName = "%s/DataMC_%s_%s.%s" % (
                            outputFolder, varTitle, HHWWggTag, fileType)
                        if (log_):
                            outName = "%s/DataMC_%s_%s_log.%s" % (
                                outputFolder, varTitle, HHWWggTag, fileType)
                        else:
                            outName = "%s/DataMC_%s_%s_nonLog.%s" % (
                                outputFolder, varTitle, HHWWggTag, fileType)
                        DataMCRatio_c = TCanvas("DataMCRatio_c",
                                                "DataMCRatio_c", 600, 800)
                        rp.Draw("nogrid")
                        rp.GetLowYaxis().SetNdivisions(5)
                        DataMCRatio_c.Update()

                        ratioGraph = rp.GetCalculationOutputGraph()
                        ratioGraph.SetMarkerStyle(8)
                        ratioGraph.SetMarkerSize(0.5)

                        # rp.SetGraphDrawOpt("EP")
                        # rp.SetGraphDrawOpt("EPZ2")
                        # rp.GetLowerRefYaxis().SetTitle("Data / MC")

                        rp.GetUpperRefYaxis().SetTitle("Entries")
                        rp.GetLowerRefYaxis().SetTitle("Data / MC")
                        rp.GetLowerPad().Update()
                        if (log_):
                            rp.GetUpperRefYaxis().SetRangeUser(
                                0.1, maxHeight * 100.)
                        else:
                            rp.GetUpperRefYaxis().SetRangeUser(
                                0, maxHeight * 1.3)

                        UpperPad = rp.GetUpperPad()
                        UpperPad.cd()
                        bkgStack.Draw("same")
                        stackSum.Draw("sameE")
                        DataHist.Draw("samePE")
                        for sig_hist in sig_histos:
                            sigMax = sig_hist.GetMaximum()
                            if sigMax == 0: sigMax = 1

                            ##-- No user input signal scale
                            if (SigScale_ == -999):
                                sigScale = (float(maxHeight) / 10.) / float(
                                    sigMax
                                )  # in order to scale signal to 10th of max of plot
                                sig_hist.Scale(sigScale)

                            ##-- User input signal scale
                            else:
                                if (verbose_):
                                    print "user sig scale:", SigScale_
                                sigScale = SigScale_
                                sig_hist.Scale(sigScale)

                            for sig_h in sig_orderedHistos:
                                # sigName = "%s X %d"%(sig_h.GetTitle(),sigScale)
                                sigName = sig_h.GetTitle()
                                added = Signals_AddedtoLegend[sigName]
                                if (added): continue
                                else:
                                    legend.AddEntry(
                                        sig_h, "%s * %.5g" %
                                        (sig_h.GetTitle(), sigScale), "FL")
                                    Signals_AddedtoLegend[sigName]
                            sig_hist.Draw("samehist")
                        legend.Draw("same")
                        selText.Draw("same")
                        CatText.Draw("same")
                        rp.GetLowerRefGraph().SetMinimum(0.5)
                        rp.GetLowerRefGraph().SetMaximum(1.5)
                        Npoints = rp.GetLowerRefGraph().GetN()
                        for ip in range(0, Npoints):
                            rp.GetLowerRefGraph().SetPointEXhigh(ip, 0)
                            rp.GetLowerRefGraph().SetPointEXlow(ip, 0)
                        if (log_):
                            UpperPad.SetLogy()
                            UpperPad.Update()
                        rp.GetLowerPad().cd()
                        lowerPad = rp.GetLowerPad()
                        rp.GetLowerRefYaxis().SetTitle("Data / MC")
                        lineAtOne = TLine(lowerPad.GetUxmin(), 1,
                                          lowerPad.GetUxmax(), 1)
                        lineAtOne.SetLineStyle(3)
                        lineAtOne.Draw("same")
                        rp.GetLowerPad().Update()
                        DataMCRatio_c.Update()
                        DataMCRatio_c.SaveAs(outName)
                        outName = outName.replace(".pdf", ".png")
                        DataMCRatio_c.SaveAs(outName)
                    if (not drawPads_):
                        bkgOutName = "%s/BackgroundsPADS_%s_%s.png" % (
                            outputFolder, varTitle, HHWWggTag)
                        os.system('rm %s' % (bkgOutName))
                        bkgOutName = bkgOutName.replace(".png", ".pdf")
                        os.system('rm %s' % (bkgOutName))
                    MC_CUT = MC_CUT.replace(
                        "(%s != 0) && (%s != -999)" % (v, v), "ZERO_CUT")
                    DATA_CUT = DATA_CUT.replace(
                        "(%s != 0) && (%s != -999)" % (v, v), "ZERO_CUT")

                MC_Nevents_lists.append(these_MC_Nevents)
                MC_Nevents_noweight_lists.append(these_MC_Nevents_noweights)

        ##-- Produce table with number of events for each MC, total MC, and data
        CreateYieldsTables(cutBatchTag_pairs, dataNevents_list, MC_names,
                           MC_Nevents_lists, MC_Nevents_noweight_lists, ol_)
Ejemplo n.º 26
0
def Plot2DLinearFit( hist2D, title, xname
                   , limits, graph
                   , label, eff_uncorr, eff
                   , etBin = None, etaBin = None ):
  import array as ar
  from ROOT import TCanvas, gStyle, TLegend, kRed, kBlue, kBlack, TLine, kBird, kOrange
  from ROOT import TGraphErrors, TF1, TColor
  pileup_max = hist2D.GetYaxis().GetXmax()
  pileup_min = hist2D.GetYaxis().GetXmin()
  # Retrieve some usefull information
  gStyle.SetPalette(kBird)
  canvas3 = TCanvas(title,title, 500, 500)
  #canvas3.SetTopMargin(0.10)
  canvas3.SetRightMargin(0.12)
  canvas3.SetLeftMargin(0.10)
  #canvas3.SetBottomMargin(0.11)
  FormatCanvasAxes(canvas3, XLabelSize=18, YLabelSize=18, XTitleOffset=0.87, YTitleOffset=1.5)
  #hist2D.SetTitle('Neural Network output as a function o nvtx, '+partition_name)
  #hist2D.GetXaxis().SetTitle('Neural Network output (Discriminant)')
  #hist2D.GetYaxis().SetTitle(xname)
  #hist2D.GetZaxis().SetTitle('Counts')
  #if not useNoActivationFunctionInTheLastLayer: hist2D.SetAxisRange(-1,1, 'X' )
  hist2D.Draw('colz')
  (miny,maxy) = GetYaxisRanges(canvas3,check_all=True,ignorezeros=True,ignoreErrors=True)
  canvas3.SetLogz()
  # Invert graph
  nvtx_points        = ar.array( 'd', graph.GetX(), )
  nvtx_error_points  = ar.array( 'd', graph.GetEX(),)
  discr_points       = ar.array( 'd', graph.GetY(), )
  discr_error_points = ar.array( 'd', graph.GetEY(),)
  g1 = TGraphErrors(len(discr_points), discr_points, nvtx_points, discr_error_points, nvtx_error_points)
  g1.SetLineWidth(1)
  g1.SetLineColor(kBlack)
  g1.SetMarkerColor(kBlack)
  g1.SetMarkerSize(.6)
  g1.Draw("P same")
  tobject_collector.append(g1)
  l2 = TLine(eff_uncorr.thres,miny,eff_uncorr.thres,maxy)
  l2.SetLineColor(kRed)
  l2.SetLineWidth(2)
  l2.Draw("l,same")
  tobject_collector.append(l2)
  f1 = eff.f1
  l3 = TLine(f1.Eval(miny), miny, f1.Eval(maxy), maxy)
  l3.SetLineColor(kBlack)
  l3.SetLineWidth(2)
  l3.Draw("l,same")
  tobject_collector.append(l3)
  SetAxisLabels(canvas3,'Neural Network output (Discriminant)',xname,'Entries')
  t = DrawText(canvas3,[GetAtlasInternalText(), '', FixLength(label,16), '', GetSqrtsText()],.05,.70,.45,.9)
  t.SetTextAlign(12)
  t2 = DrawText(canvas3,[ '#color[2]{%s}' % eff_uncorr.thresstr( 'Fixed Threshold' )
                   , '#color[2]{#varepsilon=%s}' % eff_uncorr.asstr(addname = False, addthres = False )
                   , ''
                   , eff.threstr( prefix = 'Correction' )
                   , '#varepsilon=%s' % eff.asstr(addname = False, addthres = False )
                   ]
          ,.45,.70,.45,.9,totalentries=5, textsize = 14 )
  t2.SetTextAlign(12)
  AutoFixAxes( canvas3, ignoreErrors = True, limitXaxisToFilledBins = True, changeAllXAxis = True )
  return canvas3
Ejemplo n.º 27
0
tot.plotOn(phiFrame, Normalization(ratio))
bFrac = (nBkg.getValV()) / (nSig.getValV() + nBkg.getValV())
bkg.plotOn(phiFrame, LineColor(kRed), Normalization(bFrac), LineStyle(kDashed))
signal.plotOn(phiFrame, LineColor(kGreen), Normalization(1.0 - bFrac))
tot.paramOn(phiFrame, RooFit.Layout(0.57, 0.99, 0.65))

phiFrame.Draw()

sidesigma = np.sqrt(gamma.getValV()**2 + sigma.getValV()**2)

plotmax = 1.5 * float(nentries / binning)
lowside = -3. * sidesigma + mean.getValV()
upside = +3. * sidesigma + mean.getValV()

linelow = TLine(lowside, 0.0, lowside, plotmax)
lineup = TLine(upside, 0.0, upside, plotmax)
linelow.SetLineColor(kGreen)
lineup.SetLineColor(kGreen)
linelow.SetLineWidth(2)
lineup.SetLineWidth(2)

#linelow.Draw()
#lineup.Draw()

#tot.paramOn(phiFrame,RooFit.Layout(0.57,0.99,0.65))

c.SaveAs('phimassSPlot_' + outname + '.png')
c.SaveAs('phimassSPlot_' + outname + '.root')
c.Clear()
            hEffPromptRatio[model].SetDirectory(0)
            hEffFDRatio[model].SetDirectory(0)
            hEffPromptRatio[model].Divide(hEffPrompt[model], hEffPrompt['pythia'])
            hEffFDRatio[model].Divide(hEffFD[model], hEffFD['pythia'])
            for iPt in range(1, hEffPromptRatio[model].GetNbinsX()+1):
                hEffPromptRatio[model].SetBinError(iPt, 1.e-20)
                hEffFDRatio[model].SetBinError(iPt, 1.e-20)

        leg.AddEntry(hPtDistrD[model], legNames[model], 'l')
        legEff.AddEntry(hPtDistrD[model], legNames[model], 'lp')

ptMin = hEffPrompt['pythia'].GetBinLowEdge(1)
ptMax = hEffPrompt['pythia'].GetBinLowEdge(hEffPrompt['pythia'].GetNbinsX()) \
    + hEffPrompt['pythia'].GetBinWidth(hEffPrompt['pythia'].GetNbinsX())

lineatone = TLine(ptMin, 1., ptMax, 1.)
lineatone.SetLineWidth(2)
lineatone.SetLineStyle(9)
lineatone.SetLineColor(kBlack)

lineatoneWeight = TLine(0., 1., ptMax, 1.)
lineatoneWeight.SetLineWidth(2)
lineatoneWeight.SetLineStyle(9)
lineatoneWeight.SetLineColor(kBlack)

lineatoneWeightB = TLine(0., 1., ptMax*2, 1.)
lineatoneWeightB.SetLineWidth(2)
lineatoneWeightB.SetLineStyle(9)
lineatoneWeightB.SetLineColor(kBlack)

cShapesD = TCanvas('cShapesD', '', 1000, 500)
# ______________________________________________________________________________
if __name__ == '__main__':
    from ROOT import gROOT, gPad, gStyle, TFile, TCanvas, TH1F, TH2F, TPolyLine, TLatex, TColor, TEfficiency, TLine, TLatex, TGraph, TGraphAsymmErrors

    # ____________________________________________________________________________
    # Setup basic drawer
    gROOT.LoadMacro("tdrstyle.C")
    gROOT.ProcessLine("setTDRStyle();")
    #gROOT.SetBatch(True)
    gStyle.SetPadGridX(True)
    gStyle.SetPadGridY(True)
    gStyle.SetMarkerStyle(1)
    gStyle.SetEndErrorSize(0)
    gROOT.ForceStyle()

    tline = TLine()
    tline.SetLineColor(920 + 2)  # kGray+2
    tline.SetLineStyle(2)

    tlatexCMS1 = TLatex()
    tlatexCMS1.SetNDC()
    tlatexCMS1.SetTextFont(61)
    tlatexCMS1.SetTextSize(0.75 * 0.05)

    tlatexCMS2 = TLatex()
    tlatexCMS2.SetNDC()
    tlatexCMS2.SetTextFont(52)
    tlatexCMS2.SetTextSize(0.60 * 0.05)

    tlatexCMS3 = TLatex()
    tlatexCMS3.SetNDC()
Ejemplo n.º 30
0
                    marker_sizes = [1]
                    line_sizes = [2]
                    marker_colors=line_colors=fill_colors=[4]
                    fill_types = [0]
                    figname= histo_name
            
                    # call one plot
                    theone = oneplot()
                    theone._figtype = ["png"]
                    theone.initialize(list_histo=histos,names=names,legends=legends, opt_legends=opt_legends,
                                    xtitle=xtitle,ytitle=ytitle,
                                    figname=figname, 
                                    options=options, marker_types=marker_types, marker_colors=marker_colors, marker_sizes=marker_sizes,
                                    line_colors=line_colors, line_sizes=line_sizes,
                                    fill_colors=fill_colors, fill_types=fill_types)
                    newline = TLine(0.2,0.2,0.4,0.4)
                    newline.Draw()
                    theone.plot1DHistogram()
                    theone.finish()

        for var in VAR_0:
            histo_name = cut + "_" + var
            names = [var]
            histos = []

            # load histograms
            histo_tmp = fin.Get(histo_name)
            histo_tmp.Scale(100./histo_tmp.Integral(0, -1))
            histos.append(histo_tmp)

            # Draw histograms