Пример #1
0
def plotDataOverMCEff(hist_mc_tight, hist_mc_loose, hist_data_tight, hist_data_loose, plot_name='fakerate.pdf', mc_leg='MC', obs_leg='Observed', ratio_leg='Obs/MC'):

    g = TGraphAsymmErrors(hist_mc_tight)
    g.Divide(hist_mc_tight, hist_mc_loose)
    g.GetYaxis().SetTitle('Misidentification rate')
    g.GetXaxis().SetTitle(hist_mc_tight.GetXaxis().GetTitle())
    g.GetYaxis().SetTitleOffset(1.2)
    g.GetYaxis().SetTitleOffset(1.3)

    g.SetLineColor(2)
    g.SetMarkerColor(2)

    g_data = TGraphAsymmErrors(hist_data_tight)
    g_data.Divide(hist_data_tight, hist_data_loose)

    # if g_data.GetN() != hist_data_tight.GetNbinsX():
    #     import pdb; pdb.set_trace()

    g_data.GetYaxis().SetTitle('Misidentification rate')
    g_data.GetXaxis().SetTitle(hist_data_tight.GetXaxis().GetTitle())
    g_data.GetYaxis().SetTitleOffset(1.2)
    g_data.GetYaxis().SetTitleOffset(1.3)
    g_data.SetMarkerColor(1)

    g_vals = g.GetY()
    g_data_vals = g_data.GetY()

    g_ratio = g_data.Clone('ratio')

    for i in xrange(g_data.GetN()):
        ratio = g_data_vals[i]/g_vals[i] if g_vals[i] else 0.
        g_ratio.SetPoint(i, g.GetX()[i], ratio)

        rel_y_low = math.sqrt((g_data.GetErrorYlow(i)/g_data_vals[i])**2 + (g.GetErrorYlow(i)/g_vals[i])**2) if g_data_vals[i] > 0. and g_vals[i] > 0. else 0.

        g_ratio.SetPointEYlow(i, rel_y_low * ratio)

        rel_y_high = math.sqrt((g_data.GetErrorYhigh(i)/g_data_vals[i])**2 + (g.GetErrorYhigh(i)/g_vals[i])**2) if g_data_vals[i] > 0. and g_vals[i] > 0. else 0.

        g_ratio.SetPointEYhigh(i, rel_y_high * ratio)

    # Gymnastics to get same label sizes etc in ratio and main plot
    ytp_ratio = 2.
    xtp_ratio = 2.

    # hr.GetYaxis().SetNdivisions(4)

    g_ratio.GetYaxis().SetTitleSize(g.GetYaxis().GetTitleSize() * xtp_ratio)
    g_ratio.GetXaxis().SetTitleSize(g.GetXaxis().GetTitleSize() * ytp_ratio)

    g_ratio.GetYaxis().SetTitleOffset(g.GetYaxis().GetTitleOffset() / xtp_ratio)
    g_ratio.GetXaxis().SetTitleOffset(g.GetXaxis().GetTitleOffset())  # / ytp_ratio)

    g_ratio.GetYaxis().SetLabelSize(g.GetYaxis().GetLabelSize() * xtp_ratio)
    g_ratio.GetXaxis().SetLabelSize(g.GetXaxis().GetLabelSize() * ytp_ratio)

    g_data.GetXaxis().SetLabelColor(0)
    g_data.GetXaxis().SetLabelSize(0)
    g.GetXaxis().SetLabelColor(0)
    g.GetXaxis().SetLabelSize(0)

    g_ratio.GetXaxis().SetTitle(g.GetXaxis().GetTitle())

    maxy = 1.3 * max(g.GetMaximum(), g_data.GetMaximum(), 0.05)
    g.GetYaxis().SetRangeUser(0.0011, maxy)

    cv, pad, padr = HistDrawer.buildCanvas()

    pad.cd()

    g.Draw('AP')
    g_data.Draw('P')

    legend = TLegend(0.23, 0.73, 0.43, 0.91)
    legend.SetFillColor(0)
    legend.SetFillStyle(0)
    legend.SetLineColor(0)
    legend.SetLineWidth(0)

    legend.AddEntry(g.GetName(), mc_leg, 'lep')
    legend.AddEntry(g_data.GetName(), obs_leg, 'lep')

    legend.Draw()

    padr.cd()
    g_ratio.GetYaxis().SetRangeUser(0.01, 1.99)
    g_ratio.GetYaxis().SetTitle(ratio_leg)
    g_ratio.Draw('AP')

    drawRatioLines(g_ratio)

    cv.Print(plot_name)

    g.GetYaxis().SetRangeUser(0.0001, 1)
    pad.SetLogy(True)
    cv.Print(plot_name.replace('.', '_log.'))
    f = ROOT.TFile(plot_name.replace('.', '_log.').replace('.pdf', '.root'), 'RECREATE')
    g.Write()
    g_data.Write()
    cv.Write()
    f.Close()
Пример #2
0
def plotBoxes(labels, **kwargs):
    '''Plot boxes.'''
    print color("plotBoxes()", color="magenta", prepend=">>>\n>>> ")
    # https://wiki.physik.uzh.ch/cms/limits:brazilianplotexample
    # https://root.cern.ch/doc/master/classTHistPainter.html#HP07
    # text label https://root.cern.ch/root/roottalk/roottalk98/0616.html
    #            https://root.cern.ch/phpBB3/viewtopic.php?t=18534
    #            https://root.cern.ch/doc/master/classTGaxis.html#GA10a
    # boxes https://root.cern.ch/doc/master/classTGraphPainter.html#GP03b

    # SIGNAL strength & mass
    S_exp = kwargs.get('S_exp', 1)
    mass = kwargs.get('mass', 28)
    green = TGraphAsymmErrors()
    yellow = TGraphAsymmErrors()
    limit = TGraphAsymmErrors()
    labels = labels[::-1]  # reverse order: top to bottom
    width = 0.2

    #     (down,up) = (1000,0)
    #     for i, label in enumerate(labels):
    #         #norm_LA = N_tot / (lumi*1000*MC_dict[label]) # /1000 convert fb to pb
    #         #print ">>> LA normalization of %s: N_tot/(lumi*1000*N) = %.1f/(%.1f*1000*%.1f) = %.3f" % (label,N_tot,lumi,MC_dict[label],norm_LA)
    #         filename = getOutputFilename(label,mass,S_exp=S_exp)
    #         limits  = getLimits(filename) #,scale=norm_LA
    #         limit.SetPoint(  i,limits[2],i+1 )
    #         green.SetPoint(  i,limits[2],i+1 ) # -/+ 1 sigma
    #         yellow.SetPoint( i,limits[2],i+1 ) # -/+ 2 sigma
    #         limit.SetPointError(  i,                  0,                  0,width,width ) # -/+ 1 sigma
    #         green.SetPointError(  i,limits[2]-limits[1],limits[3]-limits[2],width,width ) # -/+ 1 sigma
    #         yellow.SetPointError( i,limits[2]-limits[0],limits[4]-limits[2],width,width ) # -/+ 2 sigma
    #         if down > limits[0]: down = limits[0]
    #         if   up < limits[4]: up   = limits[4]

    (down, up) = (1000, 0)
    labels = [
        "mt-2",
        "mt-2",
        "mt-1",
        "mt-1",
    ]
    extralabels = [
        "_noOpt",
        "_Opt",
        "_noOpt",
        "_Opt",
    ]
    for i, (label, extralabel) in enumerate(zip(labels, extralabels)):
        #norm_LA = N_tot / (lumi*1000*MC_dict[label]) # /1000 convert fb to pb
        #print ">>> LA normalization of %s: N_tot/(lumi*1000*N) = %.1f/(%.1f*1000*%.1f) = %.3f" % (label,N_tot,lumi,MC_dict[label],norm_LA)
        filename = getOutputFilename(label,
                                     mass,
                                     extralabel=extralabel,
                                     S_exp=S_exp)
        limits = getLimits(filename)  #,scale=norm_LA
        limit.SetPoint(i, limits[2], i + 1)
        green.SetPoint(i, limits[2], i + 1)  # -/+ 1 sigma
        yellow.SetPoint(i, limits[2], i + 1)  # -/+ 2 sigma
        limit.SetPointError(i, 0, 0, width, width)  # -/+ 1 sigma
        green.SetPointError(i, limits[2] - limits[1], limits[3] - limits[2],
                            width, width)  # -/+ 1 sigma
        yellow.SetPointError(i, limits[2] - limits[0], limits[4] - limits[2],
                             width, width)  # -/+ 2 sigma
        if down > limits[0]: down = limits[0]
        if up < limits[4]: up = limits[4]
    labels = [
        "mt-2_label",
        "mt-2",
        "mt-1_label",
        "mt-1",
    ]

    N = len(labels)
    canvas = TCanvas("canvas", "canvas", 100, 100, 800, 600)
    canvas.SetTopMargin(0.08)
    canvas.SetBottomMargin(0.12)
    canvas.SetLeftMargin(0.14)
    canvas.SetRightMargin(0.04)
    canvas.SetGrid(1, 0)
    #canvas.SetTicks(1,0)
    #canvas.SetLogx()
    green.SetFillColor(kGreen + 1)
    yellow.SetFillColor(kOrange)
    limit.SetLineWidth(2)

    frame = TH2F("frame", "frame", 200, down - (up * 0.1), up * 1.1,
                 2 * (N + 1), 0, N + 1)  #canvas.DrawFrame(0.001,0,10,N+1)
    frame.GetXaxis().SetTitleSize(0.05)
    frame.GetYaxis().SetLabelSize(0.0)  #8)
    frame.GetXaxis().SetLabelSize(0.045)
    frame.GetXaxis().SetTitleOffset(1.14)
    frame.GetYaxis().SetNdivisions(N + 1, 0, 0,
                                   False)  # ndiv = N1 + 100*N2 + 10000*N3
    #frame.GetXaxis().CenterTitle(True)
    xtitle = "95% upper limit on #sigma#timesBR(X#rightarrow#tau#tau) [pb]"
    frame.GetXaxis().SetTitle(xtitle)
    # if S_exp is 0:
    #     yaxis_title = "95% upper limit on #sigma#timesBR(X#rightarrow#tau#tau)/LA"

    #frame.GetXaxis().SetRangeUser(0,up*1.10)
    #frame.SetMinimum(0)
    #frame.SetMaximum(up*1.10) #ymax)
    #frame.GetYaxis().SetLimits(0,N+1)
    frame.Draw("AXIS")
    yellow.Draw("2 SAME")
    green.Draw("2 SAME")
    limit.Draw("P SAME")

    labelfontsize = 0.042
    text = TLatex()
    text.SetTextSize(labelfontsize)
    text.SetTextAlign(23)
    text.SetTextFont(42)

    #labelfontwidth = labelfontsize*stringWidth(*[label_dict_split[k] for k in label_dict_split])
    #xtext = frame.GetXaxis().GetXmin()-frame.GetXaxis().GetXmax()*0.04 # manual
    xtext = marginCenter(canvas, frame.GetXaxis())  # automatic
    for i, label in enumerate(labels):
        bin = frame.GetYaxis().FindBin(i + 1)
        ytext = frame.GetYaxis().GetBinCenter(bin)
        #print "(x,y)=(%s,%s)"%(xtext,ytext)
        text.DrawLatex(xtext, ytext, label_dict_split[label] + "  ")
        # limit.GetYaxis().SetBinLabel(bin-1,label_dict_split[label])

    #frame.GetYaxis().LabelsOption('H') # draw horizontal
    #gPad.Modified()
    #gPad.Update()
    CMS_lumi.CMS_lumi(canvas, 13, 0)

    print " "
    canvas.SaveAs("%s/upperLimitBoxes-S%s.png" % (PLOT_DIR, S_exp))
    canvas.SaveAs("%s/upperLimitBoxes-S%s.pdf" % (PLOT_DIR, S_exp))
    canvas.Close()
Пример #3
0
    expm1.append(
        float(line.rstrip().split()[4]) / xsec_ -
        float(line.rstrip().split()[3]) / xsec_)
    expmed.append(float(line.rstrip().split()[4]) / xsec_)
    expp1.append(
        float(line.rstrip().split()[5]) / xsec_ -
        float(line.rstrip().split()[4]) / xsec_)
    expp2.append(
        float(line.rstrip().split()[6]) / xsec_ -
        float(line.rstrip().split()[4]) / xsec_)
    obs.append(float(line.rstrip().split()[7]) / xsec_)
    errx.append(0.0)
    print masspointstr, float(line.rstrip().split()[3]), xsec_, float(
        line.rstrip().split()[3]) / xsec_

g_exp2 = TGraphAsymmErrors(int(len(MH4)), MH4, expmed, errx, errx, expm2,
                           expp2)
g_exp2.SetName("exp2")
g_exp1 = TGraphAsymmErrors(int(len(MH4)), MH4, expmed, errx, errx, expm1,
                           expp1)
g_exp1.SetName("exp1")
g_expmed = TGraphAsymmErrors(int(len(MH4)), MH4, expmed)
g_expmed.SetName("expmed")
g_obs = TGraphAsymmErrors(int(len(MH4)), MH4, obs)
g_obs.SetName("obs")

#g_expm2  = TGraphAsymmErrors(int(len(med)), med, expm2 )   ;  g_expm2.SetName("expm2")
#g_expm1  = TGraphAsymmErrors(int(len(med)), med, expm1 )   ;  g_expm1.SetName("expm1")
#g_expmed = TGraphAsymmErrors(int(len(med)), med, expmed)   ;  g_expmed.SetName("expmed")
#g_expp1  = TGraphAsymmErrors(int(len(med)), med, expp1 )   ;  g_expp1.SetName("expp1")
#g_expp2  = TGraphAsymmErrors(int(len(med)), med, expp2 )   ;  g_expp2.SetName("expp2")
#g_obs    = TGraphAsymmErrors(int(len(med)), med, obs   )   ;  g_obs.SetName("obs")
Пример #4
0
h_after_selection_cum.Draw()
time.sleep(11)


"""
h_efficiency = h_after_selection
h_efficiency.Divide(h_after_selection,h_before_selection,1.0,1.0,"B")
#h_efficiency = h_before_selection
#h_efficiency.Divide(h_before_selection,h_after_selection,1.0,1.0,"B")
h_efficiency.Draw()
time.sleep(11)
"""



g_efficiency = GAE()
g_efficiency.Divide(h_after_selection_cum, h_before_selection, "cl=0.683 b(1,1) mode")

#from tools import DrawErrorBand
#DrawErrorBand(g_efficiency)

#"""
g_efficiency.SetTitle('efficiency')
g_efficiency.SetFillColor(5)

g_efficiency.SetMarkerStyle(21)
g_efficiency.SetMarkerColor(4)

#g_efficiency.Draw('ALP')
#g_efficiency.Draw('3A')
#"""
Пример #5
0
for j in range(n_bins):
    bin_cont_j_fp  = h_after_selection.GetBinContent(j+1)
    cum_fp        += bin_cont_j_fp
    bin_cont_fp    = tot_weight_b - cum_fp
    h_c_b.SetBinContent(j+1, bin_cont_fp)

    bin_cont_j_tp  = h_true_positive.GetBinContent(j+1)
    cum_tp        += bin_cont_j_tp
    bin_cont_tp    = tot_weight_s - cum_tp
    h_c_s.SetBinContent(j+1, bin_cont_tp)
#h_c_b.Draw()
#slp(22)
'''
###############################################################

g_efficiency = GAE()
g_tpr = GAE()

g_efficiency.Divide(h_c_b, h_before_selection, "cl=0.683 b(1,1) mode")
g_tpr.Divide(h_c_s, h_true, "cl=0.683 b(1,1) mode")

# for debugging:
'''
g_efficiency.SetTitle('efficiency')
g_efficiency.SetFillColor(5)
g_efficiency.SetMarkerStyle(21)
g_efficiency.SetMarkerColor(4)
#g_efficiency.Draw('ALP')
#g_efficiency.Draw('ALPE1')
#g_efficiency.Draw('3A')a
#slp(33)
Пример #6
0
def draw_limits_per_category( nchannels, xmin, xmax, obs, expect, upper1sig, lower1sig, upper2sig, lower2sig ):

    channel = np.array( [ nchannels - 1.5 - float(i) for i in range( 0, nchannels ) ] )
    ey      = np.full( nchannels, 0.494 )
    zero    = np.zeros( nchannels )

    gexpect1sig = TGraphAsymmErrors( nchannels, expect, channel, lower1sig, upper1sig, ey, ey )
    gexpect1sig.SetFillColor( kGreen )
    gexpect1sig.SetLineWidth( 2 )
    gexpect1sig.SetLineStyle( 2 )
    
    gexpect2sig = TGraphAsymmErrors( nchannels, expect, channel, lower2sig, upper2sig, ey, ey )
    gexpect2sig.SetFillColor( kYellow )
    gexpect2sig.SetLineWidth( 2 )
    gexpect2sig.SetLineStyle( 2 )

    gexpect2sig.Draw("2")
    gexpect1sig.Draw("2")

    gobs = TGraphErrors( nchannels, obs, channel, zero, ey )
    gobs.SetMarkerStyle( 21 )
    gobs.SetMarkerSize( 1.5 )
    gobs.SetLineWidth( 2 )
    #gobs.Draw("pz")

    # dashed line at median expected limits
    l = TLine()
    l.SetLineStyle( 2 )
    l.SetLineWidth( 2 )
    for bin in range( nchannels ):
        l.DrawLine( expect[bin], channel[bin]-ey[bin], expect[bin], channel[bin]+ey[bin] )

    # line to separate individual and combined limits
    l.SetLineStyle( 1 )
    l.SetLineWidth( 1 )
    l.DrawLine( xmin, 0, xmax, 0 )

    # legend
    leg = TLegend( 0.32, 0.73, 0.55, 0.9 )
    leg.SetFillColor( 4000 )
    leg.AddEntry( gexpect1sig, "Expected #pm1#sigma", "FL" )
    leg.AddEntry( gexpect2sig, "Expected #pm2#sigma", "FL" )
    #leg.AddEntry( gobs,        "Observed", "pl" )
    leg.Draw()

    return gobs, gexpect1sig, gexpect2sig, leg
Пример #7
0
def pullsVertical(fileName):

    with open(fileName) as f:
        content = f.readlines()

    content_nostat = [x for x in content if not 'CMS_stat' in x]

    nbins, off = len(content_nostat), 0.10

    b_pulls = TH1F("b_pulls", ";;Pulls", nbins, 0. - off, nbins - off)
    s_pulls = TH1F("s_pulls", ";;Pulls", nbins, 0. + off, nbins + off)  #

    for i, s in enumerate(content_nostat):
        l = s.split()
        b_pulls.GetXaxis().SetBinLabel(i + 1, l[0])
        s_pulls.GetXaxis().SetBinLabel(i + 1, l[0])
        b_pulls.SetBinContent(i + 1, float(l[1]))
        b_pulls.SetBinError(i + 1, float(l[2]))
        s_pulls.SetBinContent(i + 1, float(l[3]))
        s_pulls.SetBinError(i + 1, float(l[4]))

    b_pulls.SetFillStyle(3005)
    b_pulls.SetFillColor(923)
    b_pulls.SetLineColor(923)
    b_pulls.SetLineWidth(1)
    b_pulls.SetMarkerStyle(20)
    b_pulls.SetMarkerSize(1.25)

    s_pulls.SetLineColor(602)
    s_pulls.SetMarkerColor(602)
    s_pulls.SetMarkerStyle(24)  #24
    s_pulls.SetLineWidth(1)

    b_pulls.GetYaxis().SetRangeUser(-2.5, 2.5)

    # Graphs
    h_pulls = TH2F("pulls", "", 6, -3., 3., nbins, 0, nbins)
    B_pulls = TGraphAsymmErrors(nbins)
    S_pulls = TGraphAsymmErrors(nbins)

    boxes = []

    c1 = TCanvas("c1", "Pulls", 600, 150 + nbins * 10)  #nbins*20)
    c1.cd()
    c1.SetGrid(0, 1)
    c1.GetPad(0).SetTopMargin(0.01)
    c1.GetPad(0).SetRightMargin(0.01)
    c1.GetPad(0).SetBottomMargin(0.10)
    c1.GetPad(0).SetLeftMargin(0.25)  #(0.25)#(0.065)
    c1.GetPad(0).SetTicks(1, 1)

    for i, s in enumerate(content_nostat):
        l = s.split()
        if "1034h" in l[0]: l[0] = "CMS_PDF_13TeV"
        h_pulls.GetYaxis().SetBinLabel(i + 1, l[0].replace('CMS2016_', ''))  #C
        #        y1 = gStyle.GetPadBottomMargin()
        #        y2 = 1. - gStyle.GetPadTopMargin()
        #        h = (y2 - y1) / float(nbins)
        #        y1 = y1 + float(i) * h
        #        y2 = y1 + h
        #        box = TPaveText(0, y1, 1, y2, 'NDC')
        #        box.SetFillColor(0)
        #        box.SetTextSize(0.02)
        #        box.SetBorderSize(0)
        #        box.SetTextAlign(12)
        #        box.SetMargin(0.005)
        #        if i % 2 == 0:
        #            box.SetFillColor(18)
        #        box.Draw()
        #        boxes.append(box)
        B_pulls.SetPoint(i + 1, float(l[1]), float(i + 1) - 0.3)  #C
        B_pulls.SetPointError(i + 1, float(l[2]), float(l[2]), 0., 0.)  #C

    for i, s in enumerate(content_nostat):
        l = s.split()
        S_pulls.SetPoint(i + 1, float(l[3]), float(i + 1) - 0.7)  #C
        S_pulls.SetPointError(i + 1, float(l[4]), float(l[4]), 0., 0.)  #C

    h_pulls.GetXaxis().SetTitle("(#hat{#theta} - #theta_{0}) / #Delta#theta")
    h_pulls.GetXaxis().SetLabelOffset(0.01)
    h_pulls.GetXaxis().SetTitleOffset(1.)
    h_pulls.GetYaxis().SetNdivisions(nbins, 0, 0)

    B_pulls.SetFillColor(1)
    B_pulls.SetLineColor(1)
    B_pulls.SetLineStyle(1)
    B_pulls.SetLineWidth(2)
    B_pulls.SetMarkerColor(1)
    B_pulls.SetMarkerStyle(20)
    B_pulls.SetMarkerSize(1)  #(0.75)

    S_pulls.SetFillColor(629)
    S_pulls.SetLineColor(629)
    S_pulls.SetMarkerColor(629)
    S_pulls.SetLineWidth(2)
    S_pulls.SetMarkerStyle(20)
    S_pulls.SetMarkerSize(1)

    box1 = TBox(-1., 0., 1., nbins)
    box1.SetFillStyle(3001)
    #box1.SetFillStyle(0)
    box1.SetFillColor(417)
    box1.SetLineWidth(2)
    box1.SetLineStyle(2)
    box1.SetLineColor(417)

    box2 = TBox(-2., 0., 2., nbins)
    box2.SetFillStyle(3001)
    #box2.SetFillStyle(0)
    box2.SetFillColor(800)
    box2.SetLineWidth(2)
    box2.SetLineStyle(2)
    box2.SetLineColor(800)

    leg = TLegend(0.1, 0., 0.7, 0.05)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)
    leg.SetFillColor(0)
    leg.SetNColumns(2)
    leg.AddEntry(B_pulls, "B-only fit", "lp")
    leg.AddEntry(S_pulls, "S+B fit", "lp")

    h_pulls.Draw("")
    box2.Draw()
    box1.Draw()
    B_pulls.Draw("P6SAME")
    S_pulls.Draw("P6SAME")
    leg.Draw()

    #    drawCMS(35867, "Preliminary")
    #    drawAnalysis("VH")
    #    drawRegion(outName)

    c1.Print(outName + ".png")
    c1.Print(outName + ".pdf")

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
Пример #8
0
def makeLimitPlot(output,
                  obs,
                  exp,
                  chan,
                  interference,
                  printStats=False,
                  obs2="",
                  ratioLabel=""):

    fileObs = open(obs, 'r')
    fileExp = open(exp, 'r')

    observedx = []
    observedy = []
    obsLimits = {}
    xSecs = getXSecs("CI_%s" % interference, 1.3)
    for entry in fileObs:
        massPoint = float(entry.split()[0])
        limitEntry = float(entry.split()[1]) * xSecs[int(
            float(entry.split()[0]))]
        if massPoint not in obsLimits: obsLimits[massPoint] = []
        obsLimits[massPoint].append(limitEntry)
    if printStats: print "len obsLimits:", len(obsLimits)
    for massPoint in sorted(obsLimits):
        observedx.append(massPoint)
        observedy.append(numpy.mean(obsLimits[massPoint]))
        if (numpy.std(obsLimits[massPoint]) / numpy.mean(obsLimits[massPoint])
                > 0.05):
            print massPoint, " mean: ", numpy.mean(
                obsLimits[massPoint]), " std dev: ", numpy.std(
                    obsLimits[massPoint]), " from: ", obsLimits[massPoint]

    if not obs2 == "":
        fileObs2 = open(obs2, 'r')

        observedx2 = []
        observedy2 = []
        obsLimits2 = {}
        for entry in fileObs2:
            massPoint = float(entry.split()[0])
            limitEntry = float(entry.split()[1]) * xSecs[int(
                float(entry.split()[0]))]
            if massPoint not in obsLimits2: obsLimits2[massPoint] = []
            obsLimits2[massPoint].append(limitEntry)
        if printStats: print "len obsLimits:", len(obsLimits2)
        for massPoint in sorted(obsLimits2):
            observedx2.append(massPoint)
            observedy2.append(numpy.mean(obsLimits2[massPoint]))
            if (numpy.std(obsLimits2[massPoint]) /
                    numpy.mean(obsLimits2[massPoint]) > 0.05):
                print massPoint, " mean: ", numpy.mean(
                    obsLimits2[massPoint]), " std dev: ", numpy.std(
                        obsLimits2[massPoint]
                    ), " from: ", obsLimits2[massPoint]

    limits = {}
    expectedx = []
    expectedy = []
    expected1SigLow = []
    expected1SigHigh = []
    expected2SigLow = []
    expected2SigHigh = []
    for entry in fileExp:
        massPoint = float(entry.split()[0])
        limitEntry = float(entry.split()[1]) * xSecs[int(
            float(entry.split()[0]))]
        if massPoint not in limits: limits[massPoint] = []
        limits[massPoint].append(limitEntry)

    if printStats: print "len limits:", len(limits)
    for massPoint in sorted(limits):
        limits[massPoint].sort()
        numLimits = len(limits[massPoint])
        nrExpts = len(limits[massPoint])
        medianNr = int(nrExpts * 0.5)
        #get indexes:
        upper1Sig = int(nrExpts * (1 - (1 - 0.68) * 0.5))
        lower1Sig = int(nrExpts * (1 - 0.68) * 0.5)
        upper2Sig = int(nrExpts * (1 - (1 - 0.95) * 0.5))
        lower2Sig = int(nrExpts * (1 - 0.95) * 0.5)
        if printStats:
            print massPoint, ":", limits[massPoint][lower2Sig], limits[
                massPoint][lower1Sig], limits[massPoint][medianNr], limits[
                    massPoint][upper1Sig], limits[massPoint][upper2Sig]
        #fill lists:
        expectedx.append(massPoint)
        print massPoint, limits[massPoint][medianNr]
        expectedy.append(limits[massPoint][medianNr])
        expected1SigLow.append(limits[massPoint][lower1Sig])
        expected1SigHigh.append(limits[massPoint][upper1Sig])
        expected2SigLow.append(limits[massPoint][lower2Sig])
        expected2SigHigh.append(limits[massPoint][upper2Sig])

    expX = numpy.array(expectedx)
    expY = numpy.array(expectedy)

    values2 = []
    xPointsForValues2 = []
    values = []
    xPointsForValues = []
    if printStats: print "length of expectedx: ", len(expectedx)
    if printStats: print "length of expected1SigLow: ", len(expected1SigLow)
    if printStats: print "length of expected1SigHigh: ", len(expected1SigHigh)

    #Here is some Voodoo via Sam:
    for x in range(0, len(expectedx)):
        values2.append(expected2SigLow[x])
        xPointsForValues2.append(expectedx[x])
    for x in range(len(expectedx) - 1, 0 - 1, -1):
        values2.append(expected2SigHigh[x])
        xPointsForValues2.append(expectedx[x])
    if printStats: print "length of values2: ", len(values2)

    for x in range(0, len(expectedx)):
        values.append(expected1SigLow[x])
        xPointsForValues.append(expectedx[x])
    for x in range(len(expectedx) - 1, 0 - 1, -1):
        values.append(expected1SigHigh[x])
        xPointsForValues.append(expectedx[x])
    if printStats: print "length of values: ", len(values)

    exp2Sig = numpy.array(values2)
    xPoints2 = numpy.array(xPointsForValues2)
    exp1Sig = numpy.array(values)
    xPoints = numpy.array(xPointsForValues)
    if printStats: print "xPoints2: ", xPoints2
    if printStats: print "exp2Sig: ", exp2Sig
    if printStats: print "xPoints: ", xPoints
    if printStats: print "exp1Sig: ", exp1Sig
    GraphErr2Sig = TGraphAsymmErrors(len(xPoints), xPoints2, exp2Sig)
    GraphErr2Sig.SetFillColor(ROOT.kYellow + 1)
    GraphErr1Sig = TGraphAsymmErrors(len(xPoints), xPoints, exp1Sig)
    GraphErr1Sig.SetFillColor(ROOT.kGreen)

    cCL = TCanvas("cCL", "cCL", 0, 0, 800, 500)
    gStyle.SetOptStat(0)

    if not obs2 == "":
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1)
        ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3)
        plotPad.Draw()
        ratioPad.Draw()
        plotPad.cd()
    else:
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
        plotPad.Draw()
        plotPad.cd()

    expX = numpy.array(expectedx)
    expY = numpy.array(expectedy)
    GraphExp = TGraph(len(expX), expX, expY)
    GraphExp.SetLineWidth(3)
    GraphExp.SetLineStyle(2)
    GraphExp.SetLineColor(ROOT.kBlue)

    obsX = numpy.array(observedx)
    obsY = numpy.array(observedy)
    if printStats: print "obsX: ", obsX
    if printStats: print "obsY: ", obsY

    if SMOOTH:
        smooth_obs = TGraphSmooth("normal")
        GraphObs_nonSmooth = TGraph(len(obsX), obsX, obsY)
        GraphObs = smooth_obs.SmoothSuper(GraphObs_nonSmooth, "linear", 0,
                                          0.005)
    else:
        GraphObs = TGraph(len(obsX), obsX, obsY)

    GraphObs.SetLineWidth(3)
    if not obs2 == "":

        ratio = []
        ratiox = []
        for index, val in enumerate(observedy):
            mass = observedx[index]
            foundIndex = -1
            for index2, mass2 in enumerate(observedx2):
                if mass == mass2:
                    foundIndex = index2

            if foundIndex > 0:
                ratio.append(observedy2[foundIndex] / val)
                ratiox.append(mass)
        ratioA = numpy.array(ratio)
        ratioX = numpy.array(ratiox)
        obsX2 = numpy.array(observedx2)
        obsY2 = numpy.array(observedy2)
        ratioGraph = TGraph(len(ratioX), ratioX, ratioA)
        if printStats: print "obsX2: ", obsX2
        if printStats: print "obsY2: ", obsY2

        if SMOOTH:
            smooth_obs2 = TGraphSmooth("normal")
            GraphObs2_nonSmooth = TGraph(len(obsX2), obsX2, obsY2)
            GraphObs2 = smooth_obs2.SmoothSuper(GraphObs2_nonSmooth, "linear",
                                                0, 0.005)
        else:
            GraphObs2 = TGraph(len(obsX2), obsX2, obsY2)

        GraphObs2.SetLineWidth(3)

    xSecCurves = []
    xSecCurves.append(getXSecCurve("CI_%s" % interference, 1.3))

    #Draw the graphs:
    plotPad.SetLogy()
    DummyGraph = TH1F("DummyGraph", "", 100, 10, 34)
    DummyGraph.GetXaxis().SetTitle("#Lambda [TeV]")
    if chan == "mumu":
        DummyGraph.GetYaxis().SetTitle(
            "95% CL limit on #sigma(pp#rightarrow CI+X#rightarrow#mu#mu +X) [pb]"
        )
    elif chan == "elel":
        DummyGraph.GetYaxis().SetTitle(
            "95% CL limit on #sigma(pp#rightarrow CI+X#rightarrowee +X) [pb]")
    elif chan == "elmu":
        DummyGraph.GetYaxis().SetTitle(
            "95% CL limit on #sigma(pp#rightarrow CI+X#rightarrowfont[12]{ll}) [pb]"
        )

    gStyle.SetOptStat(0)
    DummyGraph.GetXaxis().SetRangeUser(10, 34)

    DummyGraph.SetMinimum(1e-3)
    DummyGraph.SetMaximum(5)
    DummyGraph.GetXaxis().SetLabelSize(0.04)
    DummyGraph.GetXaxis().SetTitleSize(0.045)
    DummyGraph.GetXaxis().SetTitleOffset(1.)
    DummyGraph.GetYaxis().SetLabelSize(0.04)
    DummyGraph.GetYaxis().SetTitleSize(0.045)
    DummyGraph.GetYaxis().SetTitleOffset(1.)
    DummyGraph.Draw()
    if (FULL):
        GraphErr2Sig.Draw("F")
        GraphErr1Sig.Draw("F")
        GraphExp.Draw("lpsame")
    else:
        if obs2 == "":
            GraphExp.Draw("lp")
    if not EXPONLY:
        GraphObs.Draw("plsame")
    if not obs2 == "":
        GraphObs2.SetLineColor(ROOT.kRed)
        GraphObs2.SetLineStyle(ROOT.kDashed)
        GraphObs2.Draw("plsame")
    for curve in xSecCurves:
        curve.Draw("lsame")
        #curve.Draw("ALP")

    plCMS = TPaveLabel(.12, .81, .22, .88, "CMS", "NBNDC")
    #plCMS.SetTextSize(0.8)
    plCMS.SetTextAlign(12)
    plCMS.SetTextFont(62)
    plCMS.SetFillColor(0)
    plCMS.SetFillStyle(0)
    plCMS.SetBorderSize(0)

    plCMS.Draw()

    plPrelim = TPaveLabel(.12, .76, .25, .82, "Preliminary", "NBNDC")
    plPrelim.SetTextSize(0.6)
    plPrelim.SetTextAlign(12)
    plPrelim.SetTextFont(52)
    plPrelim.SetFillColor(0)
    plPrelim.SetFillStyle(0)
    plPrelim.SetBorderSize(0)
    plPrelim.Draw()

    cCL.SetTickx(1)
    cCL.SetTicky(1)
    cCL.RedrawAxis()
    cCL.Update()

    #leg=TLegend(0.65,0.65,0.87,0.87,"","brNDC")
    leg = TLegend(0.540517, 0.623051, 0.834885, 0.878644, "", "brNDC")
    #    	leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC")
    leg.SetTextSize(0.032)
    if not obs2 == "":
        if ratioLabel == "":
            ratioLabel = "Variant/Default"
        ratioLabels = ratioLabel.split("/")
        print ratioLabels
        leg.AddEntry(GraphObs, "%s Observed 95%% CL limit" % ratioLabels[1],
                     "l")
        leg.AddEntry(GraphObs2, "%s Observed 95%% CL limit" % ratioLabels[0],
                     "l")

    else:
        if not EXPONLY:
            leg.AddEntry(GraphObs, "Observed 95% CL limit", "l")
        leg.AddEntry(GraphExp, "Expected 95% CL limit, median", "l")
        if (FULL):
            leg.AddEntry(GraphErr1Sig, "Expected 95% CL limit, 1 s.d.", "f")
            leg.AddEntry(GraphErr2Sig, "Expected 95% CL limit, 2 s.d.", "f")

    leg1 = TLegend(0.665517, 0.483051, 0.834885, 0.623051, "", "brNDC")
    leg1.SetTextSize(0.032)

    leg1.AddEntry(xSecCurves[0], labels[interference], "l")

    leg.SetLineWidth(0)
    leg.SetLineStyle(0)
    leg.SetFillStyle(0)
    leg.SetLineColor(0)
    leg.Draw("hist")

    leg1.SetLineWidth(0)
    leg1.SetLineStyle(0)
    leg1.SetFillStyle(0)
    leg1.SetLineColor(0)
    leg1.Draw("hist")
    if "Moriond" in output:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "36.3 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "35.9 fb^{-1} (13 TeV, ee)", "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "35.9 fb^{-1} (13 TeV, ee) + 36.3 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")
    else:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)",
                                "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")

    plLumi.SetTextSize(0.5)
    plLumi.SetTextFont(42)
    plLumi.SetFillColor(0)
    plLumi.SetBorderSize(0)
    plLumi.Draw()

    plotPad.RedrawAxis()

    if not obs2 == "":

        ratioPad.cd()

        line = ROOT.TLine(200, 1, 5500, 1)
        line.SetLineStyle(ROOT.kDashed)

        ROOT.gStyle.SetTitleSize(0.12, "Y")
        ROOT.gStyle.SetTitleYOffset(0.35)
        ROOT.gStyle.SetNdivisions(000, "Y")
        ROOT.gStyle.SetNdivisions(408, "Y")
        ratioPad.DrawFrame(200, 0.8, 5500, 1.2, "; ; %s" % ratioLabel)

        line.Draw("same")

        ratioGraph.Draw("sameP")

    cCL.Update()
    printPlots(cCL, output)
Пример #9
0
def main():  # pylint: disable=too-many-locals, too-many-statements, too-many-branches
    """
    Main plotting function
    """
    gROOT.SetBatch(True)

    # pylint: disable=unused-variable

    parser = argparse.ArgumentParser()
    parser.add_argument("--database-analysis",
                        "-d",
                        dest="database_analysis",
                        help="analysis database to be used",
                        required=True)
    parser.add_argument("--analysis",
                        "-a",
                        dest="type_ana",
                        help="choose type of analysis",
                        required=True)
    parser.add_argument("--input",
                        "-i",
                        dest="input_file",
                        help="results input file",
                        required=True)

    args = parser.parse_args()

    typean = args.type_ana
    shape = typean[len("jet_"):]
    print("Shape:", shape)

    file_in = args.input_file
    with open(args.database_analysis, "r") as file_db:
        data_param = yaml.safe_load(file_db)
    case = list(data_param.keys())[0]
    datap = data_param[case]

    logger = get_logger()

    i_cut = file_in.rfind("/")
    rootpath = file_in[:i_cut]

    # plotting
    # LaTeX string
    p_latexnhadron = datap["analysis"][typean]["latexnamehadron"]
    p_latexbin2var = datap["analysis"][typean]["latexbin2var"]
    v_varshape_latex = datap["analysis"][typean]["var_shape_latex"]

    # first variable (hadron pt)
    lpt_finbinmin = datap["analysis"][typean]["sel_an_binmin"]
    lpt_finbinmax = datap["analysis"][typean]["sel_an_binmax"]
    var1ranges = lpt_finbinmin.copy()
    var1ranges.append(lpt_finbinmax[-1])

    # second variable (jet pt)
    v_var2_binning = datap["analysis"][typean]["var_binning2"]  # name
    lvar2_binmin_reco = datap["analysis"][typean].get("sel_binmin2_reco", None)
    lvar2_binmax_reco = datap["analysis"][typean].get("sel_binmax2_reco", None)
    p_nbin2_reco = len(lvar2_binmin_reco)  # number of reco bins
    lvar2_binmin_gen = datap["analysis"][typean].get("sel_binmin2_gen", None)
    lvar2_binmax_gen = datap["analysis"][typean].get("sel_binmax2_gen", None)
    p_nbin2_gen = len(lvar2_binmin_gen)  # number of gen bins
    var2ranges_reco = lvar2_binmin_reco.copy()
    var2ranges_reco.append(lvar2_binmax_reco[-1])
    var2binarray_reco = array(
        "d",
        var2ranges_reco)  # array of bin edges to use in histogram constructors
    var2ranges_gen = lvar2_binmin_gen.copy()
    var2ranges_gen.append(lvar2_binmax_gen[-1])
    var2binarray_gen = array(
        "d",
        var2ranges_gen)  # array of bin edges to use in histogram constructors

    # observable (z, shape,...)
    v_varshape_binning = datap["analysis"][typean][
        "var_binningshape"]  # name (reco)
    v_varshape_binning_gen = datap["analysis"][typean][
        "var_binningshape_gen"]  # name (gen)
    lvarshape_binmin_reco = \
        datap["analysis"][typean].get("sel_binminshape_reco", None)
    lvarshape_binmax_reco = \
        datap["analysis"][typean].get("sel_binmaxshape_reco", None)
    p_nbinshape_reco = len(lvarshape_binmin_reco)  # number of reco bins
    lvarshape_binmin_gen = \
        datap["analysis"][typean].get("sel_binminshape_gen", None)
    lvarshape_binmax_gen = \
        datap["analysis"][typean].get("sel_binmaxshape_gen", None)
    p_nbinshape_gen = len(lvarshape_binmin_gen)  # number of gen bins
    varshaperanges_reco = lvarshape_binmin_reco.copy()
    varshaperanges_reco.append(lvarshape_binmax_reco[-1])
    varshapebinarray_reco = array(
        "d", varshaperanges_reco
    )  # array of bin edges to use in histogram constructors
    varshaperanges_gen = lvarshape_binmin_gen.copy()
    varshaperanges_gen.append(lvarshape_binmax_gen[-1])
    varshapebinarray_gen = array(
        "d", varshaperanges_gen
    )  # array of bin edges to use in histogram constructors

    file_results = TFile.Open(file_in)
    if not file_results:
        logger.fatal(make_message_notfound(file_in))

    ibin2 = 1

    suffix = "%s_%g_%g" % (v_var2_binning, lvar2_binmin_gen[ibin2],
                           lvar2_binmax_gen[ibin2])

    # HF data
    nameobj = "%s_hf_data_%d_stat" % (shape, ibin2)
    hf_data_stat = file_results.Get(nameobj)
    if not hf_data_stat:
        logger.fatal(make_message_notfound(nameobj, file_in))
    nameobj = "%s_hf_data_%d_syst" % (shape, ibin2)
    hf_data_syst = file_results.Get(nameobj)
    if not hf_data_syst:
        logger.fatal(make_message_notfound(nameobj, file_in))

    # HF PYTHIA
    nameobj = "%s_hf_pythia_%d_stat" % (shape, ibin2)
    hf_pythia_stat = file_results.Get(nameobj)
    if not hf_pythia_stat:
        logger.fatal(make_message_notfound(nameobj, file_in))

    # HF ratio
    nameobj = "%s_hf_ratio_%d_stat" % (shape, ibin2)
    hf_ratio_stat = file_results.Get(nameobj)
    if not hf_ratio_stat:
        logger.fatal(make_message_notfound(nameobj, file_in))
    nameobj = "%s_hf_ratio_%d_syst" % (shape, ibin2)
    hf_ratio_syst = file_results.Get(nameobj)
    if not hf_ratio_syst:
        logger.fatal(make_message_notfound(nameobj, file_in))

    # inclusive data
    nameobj = "%s_incl_data_%d_stat" % (shape, ibin2)
    incl_data_stat = file_results.Get(nameobj)
    if not incl_data_stat:
        logger.fatal(make_message_notfound(nameobj, file_in))
    nameobj = "%s_incl_data_%d_syst" % (shape, ibin2)
    incl_data_syst = file_results.Get(nameobj)
    if not incl_data_syst:
        logger.fatal(make_message_notfound(nameobj, file_in))

    # inclusive PYTHIA
    nameobj = "%s_incl_pythia_%d_stat" % (shape, ibin2)
    incl_pythia_stat = file_results.Get(nameobj)
    if not incl_pythia_stat:
        logger.fatal(make_message_notfound(nameobj, file_in))
    nameobj = "%s_incl_pythia_%d_syst" % (shape, ibin2)
    incl_pythia_syst = file_results.Get(nameobj)
    if not incl_pythia_syst:
        logger.fatal(make_message_notfound(nameobj, file_in))

    # inclusive ratio
    nameobj = "%s_incl_ratio_%d_stat" % (shape, ibin2)
    incl_ratio_stat = file_results.Get(nameobj)
    if not incl_ratio_stat:
        logger.fatal(make_message_notfound(nameobj, file_in))
    nameobj = "%s_incl_ratio_%d_syst" % (shape, ibin2)
    incl_ratio_syst = file_results.Get(nameobj)
    if not incl_ratio_syst:
        logger.fatal(make_message_notfound(nameobj, file_in))

    # quark PYTHIA
    nameobj = "%s_quark_pythia_%d_stat" % (shape, ibin2)
    quark_pythia_stat = file_results.Get(nameobj)
    if not quark_pythia_stat:
        logger.fatal(make_message_notfound(nameobj, file_in))
    nameobj = "%s_quark_pythia_%d_syst" % (shape, ibin2)
    quark_pythia_syst = file_results.Get(nameobj)
    if not quark_pythia_syst:
        logger.fatal(make_message_notfound(nameobj, file_in))

    # gluon PYTHIA
    nameobj = "%s_gluon_pythia_%d_stat" % (shape, ibin2)
    gluon_pythia_stat = file_results.Get(nameobj)
    if not gluon_pythia_stat:
        logger.fatal(make_message_notfound(nameobj, file_in))
    nameobj = "%s_gluon_pythia_%d_syst" % (shape, ibin2)
    gluon_pythia_syst = file_results.Get(nameobj)
    if not gluon_pythia_syst:
        logger.fatal(make_message_notfound(nameobj, file_in))

    # plot the results with systematic uncertainties and models

    size_can = [800, 800]
    size_can_double = [800, 1000]
    offsets_axes = [0.8, 1.1]
    offsets_axes_double = [0.8, 0.8]
    margins_can = [0.1, 0.13, 0.1, 0.03]
    margins_can_double = [0.1, 0.1, 0.1, 0.1]
    margins_can_double = [0., 0., 0., 0.]
    size_thg = 0.05
    offset_thg = 0.85

    gStyle.SetErrorX(0)  # do not plot horizontal error bars of histograms
    fontsize = 0.035
    opt_leg_g = "FP"
    opt_plot_g = "2"

    list_new = []  # list to avoid loosing objects created in loops

    # labels

    x_latex = 0.16
    y_latex_top = 0.83
    y_step = 0.055

    title_x = v_varshape_latex
    title_y = "(1/#it{N}_{jet}) d#it{N}/d%s" % v_varshape_latex
    title_full = ";%s;%s" % (title_x, title_y)
    title_full_ratio = ";%s;data/MC: ratio of %s" % (title_x, title_y)
    title_full_ratio_double = f";{title_x};MC/data"

    text_alice = "#bf{ALICE}, pp, #sqrt{#it{s}} = 13 TeV"
    text_alice_sim = "#bf{ALICE} Simulation, pp, #sqrt{#it{s}} = 13 TeV"
    text_pythia = "PYTHIA 8 (Monash)"
    text_pythia_short = "PYTHIA 8"
    text_pythia_split = "#splitline{PYTHIA 8}{(Monash)}"
    text_jets = "charged jets, anti-#it{k}_{T}, #it{R} = 0.4"
    text_ptjet = "%g #leq %s < %g GeV/#it{c}, |#it{#eta}_{jet}| #leq 0.5" % (
        lvar2_binmin_reco[ibin2], p_latexbin2var, lvar2_binmax_reco[ibin2])
    text_pth = "%g #leq #it{p}_{T}^{%s} < %g GeV/#it{c}, |#it{y}_{%s}| #leq 0.8" % (
        lpt_finbinmin[0], p_latexnhadron,
        min(lpt_finbinmax[-1], lvar2_binmax_reco[ibin2]), p_latexnhadron)
    text_ptcut = "#it{p}_{T, incl. ch. jet}^{leading track} #geq 5.33 GeV/#it{c}"
    text_ptcut_sim = "#it{p}_{T, incl. ch. jet}^{leading h^{#pm}} #geq 5.33 GeV/#it{c} (varied)"
    text_sd = "Soft Drop (#it{z}_{cut} = 0.1, #it{#beta} = 0)"

    title_thetag = "#it{#theta}_{g} = #it{R}_{g}/#it{R}"
    radius_jet = 0.4

    # colour and marker indeces
    c_hf_data = 0
    c_incl_data = 1
    c_hf_mc = 2
    c_incl_mc = 6
    c_quark_mc = 5
    c_gluon_mc = 0

    # markers
    m_hf_data = get_marker(0)
    m_incl_data = get_marker(1)
    m_hf_mc = get_marker(0, 2)
    m_incl_mc = get_marker(1, 2)
    m_quark_mc = get_marker(2)
    m_gluon_mc = get_marker(3)

    # make the horizontal error bars smaller
    if shape == "nsd":
        for gr in [
                hf_data_syst, incl_data_syst, hf_ratio_syst, incl_ratio_syst,
                incl_pythia_syst, quark_pythia_syst, gluon_pythia_syst
        ]:
            for i in range(gr.GetN()):
                gr.SetPointEXlow(i, 0.1)
                gr.SetPointEXhigh(i, 0.1)

    # data, HF and inclusive

    hf_data_syst_cl = hf_data_syst.Clone()

    leg_pos = [.72, .75, .85, .85]
    list_obj = [hf_data_syst, incl_data_syst, hf_data_stat, incl_data_stat]
    labels_obj = ["%s-tagged" % p_latexnhadron, "inclusive", "", ""]
    colours = [
        get_colour(i, j) for i, j in zip((c_hf_data, c_incl_data, c_hf_data,
                                          c_incl_data), (2, 2, 1, 1))
    ]
    markers = [m_hf_data, m_incl_data, m_hf_data, m_incl_data]
    y_margin_up = 0.46
    y_margin_down = 0.05
    cshape_data, list_obj_data_new = make_plot("cshape_data_" + suffix, size=size_can, \
        list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \
        colours=colours, markers=markers, leg_pos=leg_pos, margins_y=[y_margin_down, y_margin_up], margins_c=margins_can, \
        title=title_full)
    for gr, c in zip((hf_data_syst, incl_data_syst), (c_hf_data, c_incl_data)):
        gr.SetMarkerColor(get_colour(c))
    list_obj_data_new[0].SetTextSize(fontsize)
    if shape == "nsd":
        hf_data_syst.GetXaxis().SetNdivisions(5)
    # Draw a line through the points.
    if shape == "nsd":
        for h in (hf_data_stat, incl_data_stat):
            h_line = h.Clone(h.GetName() + "_line")
            h_line.SetLineStyle(2)
            h_line.Draw("l hist same")
            list_new.append(h_line)
    cshape_data.Update()
    if shape == "rg":
        # plot the theta_g axis
        gr_frame = hf_data_syst
        axis_rg = gr_frame.GetXaxis()
        rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst())
        rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast())
        thetag_min = rg_min / radius_jet
        thetag_max = rg_max / radius_jet
        y_axis = cshape_data.GetUymax()
        axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min,
                             thetag_max, 510, "-")
        axis_thetag.SetTitle(title_thetag)
        axis_thetag.SetTitleSize(size_thg)
        axis_thetag.SetLabelSize(0.036)
        axis_thetag.SetTitleFont(42)
        axis_thetag.SetLabelFont(42)
        axis_thetag.SetLabelOffset(0)
        axis_thetag.SetTitleOffset(offset_thg)
        cshape_data.SetTickx(0)
        axis_thetag.Draw("same")
    # Draw LaTeX
    y_latex = y_latex_top
    list_latex_data = []
    for text_latex in [
            text_alice, text_jets, text_ptjet, text_pth, text_ptcut, text_sd
    ]:
        latex = TLatex(x_latex, y_latex, text_latex)
        list_latex_data.append(latex)
        draw_latex(latex, textsize=fontsize)
        y_latex -= y_step
    cshape_data.Update()
    cshape_data.SaveAs("%s/%s_data_%s.pdf" % (rootpath, shape, suffix))

    # data and PYTHIA, HF

    leg_pos = [.72, .65, .85, .85]
    list_obj = [hf_data_syst_cl, hf_data_stat, hf_pythia_stat]
    labels_obj = ["data", "", text_pythia_split]
    colours = [
        get_colour(i, j)
        for i, j in zip((c_hf_data, c_hf_data, c_hf_mc), (2, 1, 1))
    ]
    markers = [m_hf_data, m_hf_data, m_hf_mc]
    y_margin_up = 0.4
    y_margin_down = 0.05
    cshape_data_mc_hf, list_obj_data_mc_hf_new = make_plot("cshape_data_mc_hf_" + suffix, size=size_can, \
        list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \
        colours=colours, markers=markers, leg_pos=leg_pos, margins_y=[y_margin_down, y_margin_up], margins_c=margins_can, \
        title=title_full)
    for gr, c in zip([hf_data_syst_cl], [c_hf_data]):
        gr.SetMarkerColor(get_colour(c))
    leg_data_mc_hf = list_obj_data_mc_hf_new[0]
    leg_data_mc_hf.SetHeader("%s-tagged" % p_latexnhadron)
    leg_data_mc_hf.SetTextSize(fontsize)
    if shape == "nsd":
        hf_data_syst_cl.GetXaxis().SetNdivisions(5)
        #axis_nsd = hf_data_syst_cl.GetHistogram().GetXaxis()
        #x1 = axis_nsd.GetBinLowEdge(1)
        #x2 = axis_nsd.GetBinUpEdge(axis_nsd.GetNbins())
        #axis_nsd.Set(5, x1, x2)
        #for ibin in range(axis_nsd.GetNbins()):
        #    axis_nsd.SetBinLabel(ibin + 1, "%d" % ibin)
        #axis_nsd.SetNdivisions(5)
    cshape_data_mc_hf.Update()
    if shape == "rg":
        # plot the theta_g axis
        axis_rg = hf_data_stat.GetXaxis()
        rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst())
        rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast())
        thetag_min = rg_min / radius_jet
        thetag_max = rg_max / radius_jet
        y_axis = cshape_data_mc_hf.GetUymax()
        axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min,
                             thetag_max, 510, "-")
        axis_thetag.SetTitle(title_thetag)
        axis_thetag.SetTitleSize(size_thg)
        axis_thetag.SetLabelSize(0.036)
        axis_thetag.SetTitleFont(42)
        axis_thetag.SetLabelFont(42)
        axis_thetag.SetLabelOffset(0)
        axis_thetag.SetTitleOffset(offset_thg)
        cshape_data_mc_hf.SetTickx(0)
        axis_thetag.Draw("same")
    # Draw LaTeX
    y_latex = y_latex_top
    list_latex_data_mc_hf = []
    for text_latex in [text_alice, text_jets, text_ptjet, text_pth, text_sd]:
        latex = TLatex(x_latex, y_latex, text_latex)
        list_latex_data_mc_hf.append(latex)
        draw_latex(latex, textsize=fontsize)
        y_latex -= y_step
    cshape_data_mc_hf.Update()
    cshape_data_mc_hf.SaveAs("%s/%s_data_mc_hf_%s.pdf" %
                             (rootpath, shape, suffix))

    # data and PYTHIA, inclusive

    #leg_pos = [.68, .65, .85, .85]
    list_obj = [
        incl_data_syst, incl_pythia_syst, incl_data_stat, incl_pythia_stat
    ]
    labels_obj = ["data", text_pythia_split]
    colours = [
        get_colour(i, j) for i, j in zip((c_incl_data, c_incl_mc, c_incl_data,
                                          c_incl_mc), (2, 2, 1, 1))
    ]
    markers = [m_incl_data, m_incl_mc, m_incl_data, m_incl_mc]
    y_margin_up = 0.4
    y_margin_down = 0.05
    cshape_data_mc_incl, list_obj_data_mc_incl_new = make_plot("cshape_data_mc_incl_" + suffix, size=size_can, \
        list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \
        colours=colours, markers=markers, leg_pos=leg_pos, margins_y=[y_margin_down, y_margin_up], margins_c=margins_can, \
        title=title_full)
    for gr, c in zip([incl_data_syst, incl_pythia_syst],
                     [c_incl_data, c_incl_mc]):
        gr.SetMarkerColor(get_colour(c))
    leg_data_mc_incl = list_obj_data_mc_incl_new[0]
    leg_data_mc_incl.SetHeader("inclusive")
    leg_data_mc_incl.SetTextSize(fontsize)
    if shape == "nsd":
        incl_data_syst.GetXaxis().SetNdivisions(5)
    cshape_data_mc_incl.Update()
    if shape == "rg":
        # plot the theta_g axis
        axis_rg = incl_data_stat.GetXaxis()
        rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst())
        rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast())
        thetag_min = rg_min / radius_jet
        thetag_max = rg_max / radius_jet
        y_axis = cshape_data_mc_incl.GetUymax()
        axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min,
                             thetag_max, 510, "-")
        axis_thetag.SetTitle(title_thetag)
        axis_thetag.SetTitleSize(size_thg)
        axis_thetag.SetLabelSize(0.036)
        axis_thetag.SetTitleFont(42)
        axis_thetag.SetLabelFont(42)
        axis_thetag.SetLabelOffset(0)
        axis_thetag.SetTitleOffset(offset_thg)
        cshape_data_mc_incl.SetTickx(0)
        axis_thetag.Draw("same")
    # Draw LaTeX
    y_latex = y_latex_top
    list_latex_data_mc_incl = []
    for text_latex in [text_alice, text_jets, text_ptjet, text_ptcut, text_sd]:
        latex = TLatex(x_latex, y_latex, text_latex)
        list_latex_data_mc_incl.append(latex)
        draw_latex(latex, textsize=fontsize)
        y_latex -= y_step
    cshape_data_mc_incl.Update()
    cshape_data_mc_incl.SaveAs("%s/%s_data_mc_incl_%s.pdf" %
                               (rootpath, shape, suffix))

    # Ratios data/MC, HF and inclusive

    line_1 = TLine(lvarshape_binmin_reco[0], 1, lvarshape_binmax_reco[-1], 1)
    line_1.SetLineStyle(9)
    line_1.SetLineColor(1)
    line_1.SetLineWidth(3)

    #leg_pos = [.72, .7, .85, .85] # with header
    leg_pos = [.72, .75, .85, .85]  # without header
    list_obj = [
        hf_ratio_syst, line_1, incl_ratio_syst, hf_ratio_stat, incl_ratio_stat
    ]
    labels_obj = ["%s-tagged" % p_latexnhadron, "inclusive"]
    colours = [
        get_colour(i, j) for i, j in zip((c_hf_data, c_incl_data, c_hf_data,
                                          c_incl_data), (2, 2, 1, 1))
    ]
    markers = [m_hf_data, m_incl_data, m_hf_data, m_incl_data]
    y_margin_up = 0.52
    y_margin_down = 0.05
    if shape == "nsd":
        y_margin_up = 0.22
    cshape_ratio, list_obj_ratio_new = make_plot("cshape_ratio_" + suffix, size=size_can, \
        list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \
        colours=colours, markers=markers, leg_pos=leg_pos, margins_y=[y_margin_down, y_margin_up], margins_c=margins_can, \
        title=title_full_ratio)
    cshape_ratio.Update()
    for gr, c in zip((hf_ratio_syst, incl_ratio_syst),
                     (c_hf_data, c_incl_data)):
        gr.SetMarkerColor(get_colour(c))
    leg_ratio = list_obj_ratio_new[0]
    leg_ratio.SetTextSize(fontsize)
    #leg_ratio.SetHeader("data/MC")
    if shape == "nsd":
        hf_ratio_syst.GetXaxis().SetNdivisions(5)
    cshape_ratio.Update()
    if shape == "rg":
        # plot the theta_g axis
        gr_frame = hf_ratio_syst
        axis_rg = gr_frame.GetXaxis()
        rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst())
        rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast())
        thetag_min = rg_min / radius_jet
        thetag_max = rg_max / radius_jet
        y_axis = cshape_ratio.GetUymax()
        axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min,
                             thetag_max, 510, "-")
        axis_thetag.SetTitle(title_thetag)
        axis_thetag.SetTitleSize(size_thg)
        axis_thetag.SetLabelSize(0.036)
        axis_thetag.SetTitleFont(42)
        axis_thetag.SetLabelFont(42)
        axis_thetag.SetLabelOffset(0)
        axis_thetag.SetTitleOffset(offset_thg)
        cshape_ratio.SetTickx(0)
        axis_thetag.Draw("same")
    # Draw LaTeX
    y_latex = y_latex_top
    list_latex_ratio = []
    for text_latex in [
            text_alice, text_jets, text_ptjet, text_pth, text_ptcut, text_sd,
            text_pythia
    ]:
        latex = TLatex(x_latex, y_latex, text_latex)
        list_latex_ratio.append(latex)
        draw_latex(latex, textsize=fontsize)
        y_latex -= y_step
    cshape_ratio.Update()
    cshape_ratio.SaveAs("%s/%s_ratio_%s.pdf" % (rootpath, shape, suffix))

    # PYTHIA, HF, inclusive, quark, gluon

    incl_pythia_syst_cl = incl_pythia_syst.Clone()

    y_min_h, y_max_h = get_y_window_his([
        hf_pythia_stat, incl_pythia_stat, quark_pythia_stat, gluon_pythia_stat
    ])
    y_min_g, y_max_g = get_y_window_gr(
        [incl_pythia_syst, quark_pythia_syst, gluon_pythia_syst])
    y_min = min(y_min_h, y_min_g)
    y_max = max(y_max_h, y_max_g)
    y_margin_up = 0.46
    y_margin_down = 0.05
    y_min_plot, y_max_plot = get_plot_range(y_min, y_max, y_margin_down,
                                            y_margin_up)

    #leg_pos = [.6, .65, .75, .85]
    leg_pos = [.72, .55, .85, .85]
    list_obj = [
        incl_pythia_syst, quark_pythia_syst, gluon_pythia_syst, hf_pythia_stat,
        incl_pythia_stat, quark_pythia_stat, gluon_pythia_stat
    ]
    labels_obj = ["inclusive", "quark", "gluon", "%s-tagged" % p_latexnhadron]
    colours = [
        get_colour(i, j)
        for i, j in zip((c_incl_mc, c_quark_mc, c_gluon_mc, c_hf_mc, c_incl_mc,
                         c_quark_mc, c_gluon_mc), (2, 2, 2, 1, 1, 1, 1))
    ]
    markers = [
        m_incl_mc, m_quark_mc, m_gluon_mc, m_hf_mc, m_incl_mc, m_quark_mc,
        m_gluon_mc
    ]
    y_margin_up = 0.46
    y_margin_down = 0.05
    cshape_mc, list_obj_mc_new = make_plot("cshape_mc_" + suffix, size=size_can, \
        list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \
        colours=colours, markers=markers, leg_pos=leg_pos, range_y=[y_min_plot, y_max_plot], margins_c=margins_can, \
        title=title_full)
    cshape_mc.Update()
    for gr, c in zip((incl_pythia_syst, quark_pythia_syst, gluon_pythia_syst),
                     (c_incl_mc, c_quark_mc, c_gluon_mc)):
        gr.SetMarkerColor(get_colour(c))
    leg_mc = list_obj_mc_new[0]
    leg_mc.SetTextSize(fontsize)
    leg_mc.SetHeader(text_pythia_split)
    if shape == "nsd":
        incl_pythia_syst.GetXaxis().SetNdivisions(5)
    cshape_mc.Update()
    if shape == "rg":
        # plot the theta_g axis
        axis_rg = hf_pythia_stat.GetXaxis()
        rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst())
        rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast())
        thetag_min = rg_min / radius_jet
        thetag_max = rg_max / radius_jet
        y_axis = cshape_mc.GetUymax()
        axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min,
                             thetag_max, 510, "-")
        axis_thetag.SetTitle(title_thetag)
        axis_thetag.SetTitleSize(size_thg)
        axis_thetag.SetLabelSize(0.036)
        axis_thetag.SetTitleFont(42)
        axis_thetag.SetLabelFont(42)
        axis_thetag.SetLabelOffset(0)
        axis_thetag.SetTitleOffset(offset_thg)
        cshape_mc.SetTickx(0)
        axis_thetag.Draw("same")
    # Draw LaTeX
    y_latex = y_latex_top
    list_latex_mc = []
    for text_latex in [
            text_alice_sim, text_jets, text_ptjet, text_pth, text_ptcut_sim,
            text_sd
    ]:
        latex = TLatex(x_latex, y_latex, text_latex)
        list_latex_mc.append(latex)
        draw_latex(latex, textsize=fontsize)
        y_latex -= y_step
    cshape_mc.Update()
    cshape_mc.SaveAs("%s/%s_mc_%s.pdf" % (rootpath, shape, suffix))

    # PYTHIA, HF, quark, gluon

    #leg_pos = [.6, .65, .75, .85]
    leg_pos = [.72, .61, .85, .85]
    list_obj = [
        quark_pythia_syst, gluon_pythia_syst, hf_pythia_stat,
        quark_pythia_stat, gluon_pythia_stat
    ]
    labels_obj = ["quark", "gluon", "%s-tagged" % p_latexnhadron]
    colours = [
        get_colour(i, j)
        for i, j in zip((c_quark_mc, c_gluon_mc, c_hf_mc, c_quark_mc,
                         c_gluon_mc), (2, 2, 1, 1, 1))
    ]
    markers = [m_quark_mc, m_gluon_mc, m_hf_mc, m_quark_mc, m_gluon_mc]
    y_margin_up = 0.46
    y_margin_down = 0.05
    cshape_mc, list_obj_mc_new = make_plot("cshape_mc_qgd_" + suffix, size=size_can, \
        list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \
        colours=colours, markers=markers, leg_pos=leg_pos, range_y=[y_min_plot, y_max_plot], margins_c=margins_can, \
        title=title_full)
    cshape_mc.Update()
    for gr, c in zip((quark_pythia_syst, gluon_pythia_syst),
                     (c_quark_mc, c_gluon_mc)):
        gr.SetMarkerColor(get_colour(c))
    leg_mc = list_obj_mc_new[0]
    leg_mc.SetTextSize(fontsize)
    leg_mc.SetHeader(text_pythia_split)
    if shape == "nsd":
        quark_pythia_syst.GetXaxis().SetNdivisions(5)
    cshape_mc.Update()
    if shape == "rg":
        # plot the theta_g axis
        axis_rg = hf_pythia_stat.GetXaxis()
        rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst())
        rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast())
        thetag_min = rg_min / radius_jet
        thetag_max = rg_max / radius_jet
        y_axis = cshape_mc.GetUymax()
        axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min,
                             thetag_max, 510, "-")
        axis_thetag.SetTitle(title_thetag)
        axis_thetag.SetTitleSize(size_thg)
        axis_thetag.SetLabelSize(0.036)
        axis_thetag.SetTitleFont(42)
        axis_thetag.SetLabelFont(42)
        axis_thetag.SetLabelOffset(0)
        axis_thetag.SetTitleOffset(offset_thg)
        cshape_mc.SetTickx(0)
        axis_thetag.Draw("same")
    # Draw LaTeX
    y_latex = y_latex_top
    list_latex_mc = []
    for text_latex in [
            text_alice_sim, text_jets, text_ptjet, text_pth, text_ptcut_sim,
            text_sd
    ]:
        latex = TLatex(x_latex, y_latex, text_latex)
        list_latex_mc.append(latex)
        draw_latex(latex, textsize=fontsize)
        y_latex -= y_step
    cshape_mc.Update()
    cshape_mc.SaveAs("%s/%s_mc_qgd_%s.pdf" % (rootpath, shape, suffix))

    # PYTHIA, HF, inclusive

    #leg_pos = [.6, .65, .75, .85]
    leg_pos = [.72, .67, .85, .85]
    list_obj = [incl_pythia_syst_cl, incl_pythia_stat, hf_pythia_stat]
    labels_obj = ["inclusive", "", "%s-tagged" % p_latexnhadron]
    colours = [
        get_colour(i, j)
        for i, j in zip((c_incl_mc, c_incl_mc, c_hf_mc), (2, 1, 1))
    ]
    markers = [m_incl_mc, m_incl_mc, m_hf_mc]
    y_margin_up = 0.46
    y_margin_down = 0.05
    cshape_mc, list_obj_mc_new = make_plot("cshape_mc_id_" + suffix, size=size_can, \
        list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \
        colours=colours, markers=markers, leg_pos=leg_pos, range_y=[y_min_plot, y_max_plot], margins_c=margins_can, \
        title=title_full)
    # Draw a line through the points.
    if shape == "nsd":
        for h in (incl_pythia_stat, hf_pythia_stat):
            h_line = h.Clone(h.GetName() + "_line")
            h_line.SetLineStyle(2)
            h_line.Draw("l hist same")
            list_new.append(h_line)
    cshape_mc.Update()
    incl_pythia_syst_cl.SetMarkerColor(get_colour(c_incl_mc))
    leg_mc = list_obj_mc_new[0]
    leg_mc.SetTextSize(fontsize)
    leg_mc.SetHeader(text_pythia_split)
    if shape == "nsd":
        incl_pythia_syst_cl.GetXaxis().SetNdivisions(5)
    cshape_mc.Update()
    if shape == "rg":
        # plot the theta_g axis
        axis_rg = hf_pythia_stat.GetXaxis()
        rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst())
        rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast())
        thetag_min = rg_min / radius_jet
        thetag_max = rg_max / radius_jet
        y_axis = cshape_mc.GetUymax()
        axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min,
                             thetag_max, 510, "-")
        axis_thetag.SetTitle(title_thetag)
        axis_thetag.SetTitleSize(size_thg)
        axis_thetag.SetLabelSize(0.036)
        axis_thetag.SetTitleFont(42)
        axis_thetag.SetLabelFont(42)
        axis_thetag.SetLabelOffset(0)
        axis_thetag.SetTitleOffset(offset_thg)
        cshape_mc.SetTickx(0)
        axis_thetag.Draw("same")
    # Draw LaTeX
    y_latex = y_latex_top
    list_latex_mc = []
    for text_latex in [
            text_alice_sim, text_jets, text_ptjet, text_pth, text_ptcut_sim,
            text_sd
    ]:
        latex = TLatex(x_latex, y_latex, text_latex)
        list_latex_mc.append(latex)
        draw_latex(latex, textsize=fontsize)
        y_latex -= y_step
    cshape_mc.Update()
    cshape_mc.SaveAs("%s/%s_mc_id_%s.pdf" % (rootpath, shape, suffix))

    # data inclusive vs PYTHIA, quark, gluon

    #leg_pos = [.6, .65, .75, .85]
    #leg_pos = [.72, .55, .85, .85]
    leg_pos = [.6, .7, .85, .85]
    list_obj = [
        incl_data_syst, quark_pythia_syst, gluon_pythia_syst, incl_data_stat,
        quark_pythia_stat, gluon_pythia_stat
    ]
    labels_obj = ["inclusive (data)", "quark (PYTHIA 8)", "gluon (PYTHIA 8)"]
    colours = [
        get_colour(i, j)
        for i, j in zip((c_incl_data, c_quark_mc, c_gluon_mc, c_incl_data,
                         c_quark_mc, c_gluon_mc), (2, 2, 2, 1, 1, 1))
    ]
    markers = [
        m_incl_data, m_quark_mc, m_gluon_mc, m_incl_data, m_quark_mc,
        m_gluon_mc
    ]
    y_margin_up = 0.3
    y_margin_down = 0.05
    cshape_mc, list_obj_mc_new = make_plot("cshape_mc_data_iqg" + suffix, size=size_can, \
        list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \
        colours=colours, markers=markers, leg_pos=leg_pos, margins_y=[y_margin_down, y_margin_up], margins_c=margins_can, \
        title=title_full)
    for gr, c in zip((incl_data_syst, quark_pythia_syst, gluon_pythia_syst),
                     (c_incl_data, c_quark_mc, c_gluon_mc)):
        gr.SetMarkerColor(get_colour(c))
    leg_mc = list_obj_mc_new[0]
    leg_mc.SetTextSize(fontsize)
    cshape_mc.Update()
    cshape_mc.SaveAs("%s/%s_data_i_mc_qg_%s.pdf" % (rootpath, shape, suffix))

    # data + MC/data, HF and inclusive

    # print relative syst. unc.
    for name, gr in zip(("HF", "inclusive"), (hf_data_syst, incl_data_syst)):
        print(f"Rel. syst. unc. for {name} {shape}")
        e_plus_min = float("inf")
        e_minus_min = float("inf")
        e_plus_max = 0.
        e_minus_max = 0.
        for i in range(gr.GetN()):
            y = gr.GetPointY(i)
            e_plus = 100 * gr.GetErrorYhigh(i)
            e_minus = 100 * gr.GetErrorYlow(i)
            e_plus /= y
            e_minus /= y
            e_plus_min = min(e_plus_min, e_plus)
            e_minus_min = min(e_minus_min, e_minus)
            e_plus_max = max(e_plus_max, e_plus)
            e_minus_max = max(e_minus_max, e_minus)
            # print(f"Point {i}, up {e_plus:.2g} %, down {e_minus:.2g} %")
        # print(f"Minima: up {e_plus_min:.2g} %, down {e_minus_min:.2g} %")
        # print(f"Maxima: up {e_plus_max:.2g} %, down {e_minus_max:.2g} %")
        print(
            f"Absolutes: min: {min(e_plus_min, e_minus_min):.2g} %, max {max(e_plus_max, e_minus_max):.2g} %"
        )

    # explicit y ranges [zg, rg, nsd]
    list_range_y = [[0, 9], [0, 6], [0, 0.7]]  # data
    list_range_y_rat = [[0, 2], [0, 2], [0, 2]]  # mc/data ratios
    i_shape = 0 if shape == "zg" else 1 if shape == "rg" else 2
    print(f"Index {i_shape}")

    # data
    leg_pos = [.7, .75, .82, .85]
    list_obj = [hf_data_syst, incl_data_syst, hf_data_stat, incl_data_stat]
    labels_obj = ["%s-tagged" % p_latexnhadron, "inclusive", "", ""]
    colours = [
        get_colour(i, j) for i, j in zip((c_hf_data, c_incl_data, c_hf_data,
                                          c_incl_data), (2, 2, 1, 1))
    ]
    markers = [m_hf_data, m_incl_data, m_hf_data, m_incl_data]
    y_margin_up = 0.42
    y_margin_down = 0.05
    cshape_datamc_all = TCanvas("cshape_datamc_" + suffix,
                                "cshape_datamc_" + suffix)
    cshape_datamc_all.Divide(1, 2)
    pad1 = cshape_datamc_all.cd(1)
    pad2 = cshape_datamc_all.cd(2)
    pad1.SetPad(0., 0.3, 1, 1)
    pad2.SetPad(0., 0., 1, 0.3)
    pad1.SetBottomMargin(0.)
    pad2.SetBottomMargin(0.25)
    pad1.SetTopMargin(0.1)
    pad2.SetTopMargin(0.)
    pad1.SetLeftMargin(0.12)
    pad2.SetLeftMargin(0.12)
    pad1.SetTicks(1, 1)
    pad2.SetTicks(1, 1)
    cshape_datamc_all, list_obj_data_new = make_plot("cshape_datamc_" + suffix, size=size_can_double, \
        can=cshape_datamc_all, pad=1, \
        list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=[0.8, 1.1], \
        colours=colours, markers=markers, leg_pos=leg_pos, margins_c=margins_can_double, \
        # margins_y=[y_margin_down, y_margin_up], \
        range_y=list_range_y[i_shape], \
        title=title_full)
    for gr, c in zip((hf_data_syst, incl_data_syst), (c_hf_data, c_incl_data)):
        gr.SetMarkerColor(get_colour(c))
    list_obj_data_new[0].SetTextSize(fontsize)
    hf_data_syst.GetYaxis().SetLabelSize(0.1 * 3 / 7)
    #hf_data_syst.GetYaxis().SetTitleSize(0.1)
    if shape == "nsd":
        hf_data_syst.GetXaxis().SetNdivisions(5)
    # Draw a line through the points.
    if shape == "nsd":
        for h in (hf_data_stat, incl_data_stat):
            h_line = h.Clone(h.GetName() + "_line")
            h_line.SetLineStyle(2)
            h_line.Draw("l hist same")
            list_new.append(h_line)
    cshape_datamc_all.Update()
    if shape == "rg":
        # plot the theta_g axis
        gr_frame = hf_data_syst
        axis_rg = gr_frame.GetXaxis()
        rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst())
        rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast())
        thetag_min = rg_min / radius_jet
        thetag_max = rg_max / radius_jet
        y_axis = pad1.GetUymax()
        axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min,
                             thetag_max, 510, "-")
        axis_thetag.SetTitle(title_thetag)
        axis_thetag.SetTitleSize(size_thg)
        axis_thetag.SetLabelSize(0.036)
        axis_thetag.SetTitleFont(42)
        axis_thetag.SetLabelFont(42)
        axis_thetag.SetLabelOffset(0)
        axis_thetag.SetTitleOffset(offset_thg)
        cshape_datamc_all.cd(1).SetTickx(0)
        axis_thetag.Draw("same")
    # Draw LaTeX
    y_latex = y_latex_top
    list_latex_data = []
    for text_latex in [
            text_alice, text_jets, text_ptjet, text_pth, text_ptcut, text_sd
    ]:
        latex = TLatex(x_latex, y_latex, text_latex)
        list_latex_data.append(latex)
        draw_latex(latex, textsize=fontsize)
        y_latex -= y_step
    cshape_datamc_all.Update()

    # MC/data
    leg_pos = [.15, .85, .85, .95]
    hf_ratio_pythia_stat = hf_pythia_stat.Clone(
        f"{hf_pythia_stat.GetName()}_rat")
    hf_ratio_pythia_stat.Divide(hf_data_stat)
    # hf_ratio_pythia_stat = hf_data_stat.Clone(f"{hf_data_stat.GetName()}_rat") # version data/MC
    # hf_ratio_pythia_stat.Divide(hf_pythia_stat) # version data/MC
    # create a graph with PYTHIA points and with zero syst. unc.
    hf_pythia_stat_zero = hf_pythia_stat.Clone(
        f"{hf_pythia_stat.GetName()}_zero")
    for i in range(hf_pythia_stat_zero.GetNbinsX()):
        hf_pythia_stat_zero.SetBinError(i + 1, 0)
    gStyle.SetErrorX(
        0.5
    )  # we have to restore the histogram bin width to propagate it to graph
    hf_pythia_syst = TGraphAsymmErrors(
        hf_pythia_stat_zero)  # convert histogram into a graph
    gStyle.SetErrorX(0)  # set back the intended settings
    hf_ratio_pythia_syst = divide_graphs(hf_pythia_syst, hf_data_syst)
    # hf_ratio_pythia_syst = divide_graphs(hf_data_syst, hf_pythia_syst) # version data/MC
    incl_ratio_pythia_stat = incl_pythia_stat.Clone(
        f"{incl_pythia_stat.GetName()}_rat")
    incl_ratio_pythia_stat.Divide(incl_data_stat)
    incl_ratio_pythia_syst = divide_graphs(incl_pythia_syst, incl_data_syst)
    # incl_ratio_pythia_stat = incl_data_stat.Clone(f"{incl_data_stat.GetName()}_rat") # version data/MC
    # incl_ratio_pythia_stat.Divide(incl_pythia_stat) # version data/MC
    # incl_ratio_pythia_syst = divide_graphs(incl_data_syst, incl_pythia_syst) # version data/MC
    list_obj = [
        hf_ratio_pythia_syst, incl_ratio_pythia_syst, hf_ratio_pythia_stat,
        incl_ratio_pythia_stat, line_1
    ]
    labels_obj = [
        f"{p_latexnhadron}-tagged {text_pythia_short}",
        f"inclusive {text_pythia_short}", "", ""
    ]
    colours = [
        get_colour(i, j)
        for i, j in zip((c_hf_mc, c_incl_mc, c_hf_mc, c_incl_mc), (2, 2, 1, 1))
    ]
    markers = [m_hf_mc, m_incl_mc, m_hf_mc, m_incl_mc]
    y_margin_up = 0.2
    y_margin_down = 0.05
    cshape_datamc_all, list_obj_data_mc_hf_new = make_plot("cshape_data_mc_hf_" + suffix, size=size_can_double, \
        can=cshape_datamc_all, pad=2, \
        list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=[1, 1.3 * 3/7], \
        colours=colours, markers=markers, leg_pos=leg_pos, margins_c=margins_can_double, \
        # margins_y=[y_margin_down, y_margin_up], \
        range_y=list_range_y_rat[i_shape], \
        title=title_full_ratio_double)
    hf_ratio_pythia_syst.GetXaxis().SetLabelSize(0.1)
    hf_ratio_pythia_syst.GetXaxis().SetTitleSize(0.1)
    hf_ratio_pythia_syst.GetYaxis().SetLabelSize(0.1)
    hf_ratio_pythia_syst.GetYaxis().SetTitleSize(0.1)
    for gr, c in zip([hf_ratio_pythia_syst, incl_ratio_pythia_syst],
                     [c_hf_mc, c_incl_mc]):
        gr.SetMarkerColor(get_colour(c))
    leg_data_mc_hf = list_obj_data_mc_hf_new[0]
    #leg_data_mc_hf.SetHeader("%s-tagged" % p_latexnhadron)
    leg_data_mc_hf.SetTextSize(fontsize * 7 / 3)
    leg_data_mc_hf.SetNColumns(2)
    if shape == "nsd":
        hf_ratio_pythia_syst.GetXaxis().SetNdivisions(5)
    cshape_datamc_all.Update()
    # Draw LaTeX
    #y_latex = y_latex_top
    #list_latex_data_mc_hf = []
    #for text_latex in [text_alice, text_jets, text_ptjet, text_pth, text_sd]:
    #    latex = TLatex(x_latex, y_latex, text_latex)
    #    list_latex_data_mc_hf.append(latex)
    #    draw_latex(latex, textsize=fontsize)
    #    y_latex -= y_step
    #cshape_datamc_all.Update()
    pad1.RedrawAxis()
    pad2.RedrawAxis()
    cshape_datamc_all.SaveAs("%s/%s_datamc_all_%s.pdf" %
                             (rootpath, shape, suffix))
Пример #10
0
#vxs = array('d',xsection)
vxs = array('d', xsecTimesAcc)
vx = array('d', x)
vyObs = array('d', yObs)
vyExp = array('d', yExp)
vy1 = array('d', y1)
vy2 = array('d', y2)
vexl = array('d', exl)
vexh = array('d', exh)
vey1l = array('d', ey1l)
vey1h = array('d', ey1h)
vey2l = array('d', ey2l)
vey2h = array('d', ey2h)

g1 = TGraphAsymmErrors(len(vx), vx, vy1, vexl, vexh, vey1l, vey1h)
g2 = TGraphAsymmErrors(len(vx), vx, vy2, vexl, vexh, vey2l, vey2h)
gObs = TGraph(len(vx), vx, vyObs)
gExp = TGraph(len(vx), vx, vyExp)
gxs = TGraph(len(vx), vx, vxs)

gDinko = TGraph(len(masses), massesTeV_v, xs_exp_limits)

g1.SetFillColor(ROOT.kYellow)
g1.SetLineColor(ROOT.kYellow)
g2.SetFillColor(ROOT.kGreen)
g2.SetLineColor(ROOT.kGreen)
gExp.SetLineWidth(2)
gExp.SetLineStyle(9)
gObs.SetLineWidth(2)
gObs.SetLineStyle(1)
Пример #11
0
def CutBaseBenchmarkNew(df_test_orig,
                        inDict,
                        JetPrfx_bkg,
                        refAttr='pt',
                        isSigAttrStr='is_signal',
                        weightAttrStr='weight'):
    refAttrLabel = JetPrfx_bkg + refAttr
    tt = df_test_orig.copy()
    sg = tt[isSigAttrStr] == 1
    bg = tt[isSigAttrStr] == 0

    BA_l = {}
    #pick out events that satisfiy the cut
    for iAttr, iList in inDict.iteritems():
        iAttr = 'J1' + iAttr
        if iList[0] == '<': BA_l[iAttr] = tt[JetPrfx_bkg + iAttr] < iList[1]
        elif iList[0] == '>': BA_l[iAttr] = tt[JetPrfx_bkg + iAttr] > iList[1]

    pos = tt[refAttrLabel]
    pos_sgn = tt[weightAttrStr]
    pos_bkg = tt[weightAttrStr]
    n_pos = tt[weightAttrStr]
    for iAttr, iList in inDict.iteritems():
        iAttr = 'J1' + iAttr
        pos = pos[BA_l[iAttr]]  #events that pass the selection(all the cuts)
        pos_sgn = pos_sgn[
            BA_l[iAttr]]  #signal events that pass the selection(all the cuts)
        pos_bkg = pos_bkg[BA_l[
            iAttr]]  #background events that pass the selection(all the cuts)
        n_pos = n_pos[BA_l[iAttr]]  #see below
    pos_sgn = pos_sgn[sg]
    pos_bkg = pos_bkg[bg]
    n_pos = float(n_pos.sum())  #sum up the weights

    n_sgn = float(tt[weightAttrStr][sg].sum())  #sum of weights from all signal
    n_bkg = float(
        tt[weightAttrStr][bg].sum())  #sum of weights from all background
    n_pos_sgn = float(pos_sgn.sum(
    ))  #sum of weights of signal events that pass the selection
    n_pos_bkg = float(pos_bkg.sum(
    ))  #sum of weights of background events that pass the selection
    sgn_eff = np.divide(n_pos_sgn, n_sgn)
    fls_eff = np.divide(n_pos_bkg, n_bkg)
    print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Benchmark:'
    print 'num of total test events: ', tt[refAttrLabel].count()
    print "num of signals          : ", n_sgn
    print 'num of background       : ', n_bkg
    print "num of pos events       : ", n_pos
    print "num of pos bkg          : ", n_pos_bkg
    print "num of pos sgn          : ", n_pos_sgn
    print "true positive rate      : ", sgn_eff
    print "false positive rate     : ", fls_eff
    #return tt[weightAttrStr][sg], tt[weightAttrStr][bg], pos_sgn, pos_bkg#sgn_eff, fls_eff

    df_sg = tt[weightAttrStr][sg]
    df_bg = tt[weightAttrStr][bg]
    df_pos_sgn = pos_sgn
    df_pos_bkg = pos_bkg
    bin_i = 0
    bin_f = 1
    #def CutBaseROC(df_sg, df_bg, df_pos_sgn, df_pos_bkg):
    h_cut_pre_tpr = TH1F('h_cut_pre_tpr', 'hist_cut_pre_tpr', 1, bin_i, bin_f)
    h_cut_pos_tpr = TH1F('h_cut_pos_tpr', 'hist_cut_pos_tpr', 1, bin_i, bin_f)

    h_cut_pre_fpr = TH1F('h_cut_pre_fpr', 'hist_cut_pre_fpr', 1, bin_i, bin_f)
    h_cut_pos_fpr = TH1F('h_cut_pos_fpr', 'hist_cut_pos_fpr', 1, bin_i, bin_f)

    root_numpy.fill_hist(h_cut_pre_tpr, df_sg, df_sg)
    root_numpy.fill_hist(h_cut_pos_tpr, df_pos_sgn, df_pos_sgn)

    root_numpy.fill_hist(h_cut_pre_fpr, df_bg, df_bg)
    root_numpy.fill_hist(h_cut_pos_fpr, df_pos_bkg, df_pos_bkg)

    g_cut_tpr = GAE()
    g_cut_fpr = GAE()
    g_cut_tpr.Divide(h_cut_pos_tpr, h_cut_pre_tpr, "cl=0.683 b(1,1) mode")
    g_cut_fpr.Divide(h_cut_pos_fpr, h_cut_pre_fpr, "cl=0.683 b(1,1) mode")

    g_size_cut = 1

    x = Double()
    y = Double()
    x_s = Double()
    y_s = Double()

    arr_x = np.zeros(g_size_cut)
    arr_y = np.zeros(g_size_cut)
    arr_x_s = np.zeros(g_size_cut)
    arr_y_s = np.zeros(g_size_cut)

    for i in xrange(g_size_cut):
        g_cut_fpr.GetPoint(i, x, y)
        arr_x[i] = x
        arr_y[i] = y

        g_cut_tpr.GetPoint(i, x_s, y_s)
        arr_x_s[i] = x_s
        arr_y_s[i] = y_s

    buffer_l = g_cut_fpr.GetEYlow()
    buffer_l.SetSize(g_size_cut)
    arr_l = np.array(buffer_l, copy=True)

    buffer_h = g_cut_fpr.GetEYhigh()
    buffer_h.SetSize(g_size_cut)
    arr_h = np.array(buffer_h, copy=True)

    buffer_l_s = g_cut_tpr.GetEYlow()
    buffer_l_s.SetSize(g_size_cut)
    arr_l_s = np.array(buffer_l_s, copy=True)

    buffer_h_s = g_cut_tpr.GetEYhigh()
    buffer_h_s.SetSize(g_size_cut)
    arr_h_s = np.array(buffer_h_s, copy=True)
    print len(arr_h)
    print len(arr_l)

    print 'TPR: ', arr_y_s
    print 'FPR: ', arr_y
    print arr_l_s
    print arr_l
    print arr_h_s
    print arr_h
    out_dict = {}
    out_dict['tpr'] = arr_y_s[0]
    out_dict['fpr'] = arr_y[0]
    out_dict['tpr_e_l'] = arr_l_s[0]
    out_dict['fpr_e_l'] = arr_l[0]
    out_dict['tpr_e_h'] = arr_h_s[0]
    out_dict['fpr_e_h'] = arr_h[0]

    return out_dict
    exit()

era = str(sys.argv[1])
subdir = str(sys.argv[2])

#---------

# Produce trend plots for each layer

graphs = []

for layer in range(1, 35):

    print('producing trend plot for layer ' + str(layer))

    graphs.append(TGraphAsymmErrors())
    eff_vs_run = graphs[-1]

    xlabels = add_points(eff_vs_run, hiteffdir + "/" + era, subdir, layer)

    eff_vs_run.SetTitle(get_layer_name(layer))
    #eff_vs_run.GetXaxis().SetTitle("run number")
    eff_vs_run.GetYaxis().SetTitle("hit efficiency")

    c1 = TCanvas()
    eff_vs_run.SetMarkerStyle(20)
    eff_vs_run.SetMarkerSize(.8)
    eff_vs_run.Draw("AP")
    c1.Print("SiStripHitEffTrendPlot_layer" + str(layer) + ".png")

# Superimpose graphs for each subdet
Пример #13
0
def pullsVertical_noBonly(fileName):
    
    content = filterPullFile(fileName)
    nbins, off = len(content), 0.10
    
    # Graphs
    h_pulls = TH2F("pulls", "", 6, -3., 3., nbins, 0, nbins)
    S_pulls = TGraphAsymmErrors(nbins)
    
    boxes = []
    
    canvas = TCanvas("canvas", "Pulls", 720, 300+nbins*18)#nbins*20)
    canvas.cd()
    canvas.SetGrid(0, 1)
    canvas.SetTopMargin(0.01)
    canvas.SetRightMargin(0.01)
    canvas.SetBottomMargin(0.10)
    canvas.SetLeftMargin(0.40)
    canvas.SetTicks(1, 1)
    
    for i, s in enumerate(content):
        l = s.split()
        h_pulls.GetYaxis().SetBinLabel(i+1, l[0])
        S_pulls.SetPoint(i,float(l[3]),float(i+1)-0.5)
        S_pulls.SetPointError(i,float(l[4]),float(l[4]),0.,0.)
    
    h_pulls.GetXaxis().SetTitle("(#hat{#theta} - #theta_{0}) / #Delta#theta")
    h_pulls.GetXaxis().SetLabelOffset(0.0)
    h_pulls.GetXaxis().SetTitleOffset(0.8)
    h_pulls.GetXaxis().SetLabelSize(0.045)
    h_pulls.GetXaxis().SetTitleSize(0.050)
    h_pulls.GetYaxis().SetLabelSize(0.046)
    h_pulls.GetYaxis().SetNdivisions(nbins, 0, 0)
    
    S_pulls.SetFillColor(kBlack)
    S_pulls.SetLineColor(kBlack)
    S_pulls.SetMarkerColor(kBlack)
    S_pulls.SetLineWidth(2)
    S_pulls.SetMarkerStyle(20)
    S_pulls.SetMarkerSize(1)
    
    box1 = TBox(-1., 0., 1., nbins)
    #box1.SetFillStyle(3001) # 3001 checkered
    #box1.SetFillStyle(0)
    box1.SetFillColor(kGreen+1) # 417
    box1.SetLineWidth(2)
    box1.SetLineStyle(2)
    box1.SetLineColor(kGreen+1) # 417
    
    box2 = TBox(-2., 0., 2., nbins)
    #box2.SetFillStyle(3001) # 3001 checkered
    #box2.SetFillStyle(0)
    box2.SetFillColor(kOrange) # 800
    box2.SetLineWidth(2)
    box2.SetLineStyle(2)
    box2.SetLineColor(kOrange) # 800
    
    leg = TLegend(0.01, 0.01, 0.3, 0.15)
    leg.SetTextSize(0.05)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)
    leg.SetFillColor(0)
    #leg.SetNColumns(2)
    leg.AddEntry(S_pulls, "S+B fit", "lp")
    if text: leg.AddEntry(0, text, "")
    
    h_pulls.Draw("")
    box2.Draw()
    box1.Draw()
    S_pulls.Draw("P6SAME")
    leg.Draw()
    canvas.RedrawAxis()
    
    canvas.Print(outName+".png")
    canvas.Print(outName+".pdf")
    
    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
Пример #14
0
    err_up *= xsec / 100.
    err_down *= xsec / 100.

    h = rFile.Get('h_xsec_' + str(mttbin))
    err_toys = h.GetRMS()

    err_up = (err_up**2 + err_toys**2)**.5
    err_down = (err_down**2 + err_toys**2)**.5

    err_up = round(err_up, 2)
    err_down = round(err_down, 2)

    return [xsec, err_up, err_down]


g_th_164 = TGraphAsymmErrors()
g_th_162 = TGraphAsymmErrors()
g_th_166 = TGraphAsymmErrors()
g_exp = TGraphAsymmErrors()

tot_xsec = 0
for bin in range(1, 5):
    tot_xsec += (getXsec(bin))[0]

print tot_xsec

for bin in range(1, 5):
    g_th_164.SetPoint(bin - 1, scales[bin - 1],
                      th_xsec_164[bin - 1] / tot_xsec_164)
    g_th_164.SetPointError(bin - 1, scales[bin - 1] - bins[bin - 1],
                           bins[bin] - scales[bin - 1], 0, 0)
Пример #15
0
def main():

    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("-i", "--inputfile", dest="inputfile")
    parser.add_option("-N", "--multiplicity", dest="N", type="int", default=3)
    parser.add_option("-x", "--exclusive", action="store_true",\
          dest="isExclusive", default=False)
    parser.add_option("-l", "--label", dest="label", type="string", default="")
    parser.add_option("-z",
                      "--zeyneplabel",
                      action="store_true",
                      dest="zeynep",
                      default=True)
    (options, args) = parser.parse_args()

    N = options.N
    isExclusive = options.isExclusive
    label_text = options.label

    zeynep = options.zeynep

    if isExclusive and not (N == 2 or N == 3):
        parser.error("Exclusive plot only for N =2 or 3")

    import configurations as config
    from ROOT import TFile, TCanvas, THStack, TLegend, TPaveText, gStyle, TPad, TH1F, TGraphAsymmErrors, TMath
    from ModelParser import ModelKey

    gStyle.SetPadTopMargin(0.05)
    gStyle.SetPadRightMargin(0.05)
    gStyle.SetPadBottomMargin(0.20)

    gStyle.SetErrorX(0.)

    suffix = ""
    if not isExclusive:
        suffix = "up"

    sm_files = []
    for model in config.sm_models:
        f = TFile("%s/%s.root" % (config.sm_dir, model), "READ")
        sm_files.append(f)

    bh_weights = []
    bh_files = []
    from BHXsec import BHXsec
    xsec = BHXsec()
    for model in config.bh_showcase:
        f = TFile("%s/%s.root" % (config.bh_dir, model), "READ")
        bh_files.append(f)
        h = f.Get("plotsNoCut/ST")
        nEvents = h.GetEntries()
        bh_weights.append(
            xsec.get(model) / nEvents * config.integrated_luminosity)

    c = TCanvas("ST_Mul%d%s" % (N, suffix), "ST_Mul%d%s" % (N, suffix), 500,
                600)
    hs = THStack()
    hs1 = THStack()

    infile = TFile(options.inputfile, "READ")
    hBkg = infile.Get("Background_N%d%s" % (N, suffix))
    #hnewBkg = infile.Get("histoTemplateN3_0")
    hnewBkg = infile.Get("ReferenceTemplateN3_0")
    gBkg = infile.Get("BackgroundGraph_N%d%s" % (N, suffix))
    hData = infile.Get("Data_N%d%s" % (N, suffix))
    hBkg = infile.Get("Background_N%d%s" % (N, suffix))
    hBkg.SetMarkerSize(0)
    hBkg_ = hBkg.Clone("BkgLine")
    hBkg.SetFillColor(33)
    hBkg.SetLineColor(33)
    hBkg_.SetLineWidth(3)
    hBkg_.SetLineColor(862)

    hs.Add(hBkg, "e3")
    hnewBkg.SetLineWidth(3)
    hnewBkg.Scale(10 * 3.407)
    hs.Add(hnewBkg, "l")

    legend = TLegend(0.2826613, 0.4819492, 0.6094355,
                     0.9416102)  # - only for N >= 2 and 3
    #legend = TLegend(0.3026613,0.5519492,0.6094355,0.9416102) # was 0.4919...zeynep

    #legend = TLegend(0.3526613,0.5519492,0.6094355,0.9416102) # was 0.4919...

    #legend.SetTextSize(0.041); #was 0.02966102
    legend.SetTextSize(0.037)
    legend.SetTextFont(42)
    legend.SetFillColor(0)
    legend.SetLineColor(0)
    if isExclusive:
        legend.SetHeader("Multiplicity N = %d" % N)
    else:
        legend.SetHeader("Multiplicity N #geq %d" % N)
    legend.AddEntry(hData, "Data", "lep")
    #legend.AddEntry(hnewBkg, "N=3 Fit Rescaled","l")
    legend.AddEntry(hBkg_, "Background", "l")
    legend.AddEntry(hBkg, "Uncertainty", "f")

    legend_sm = TLegend(0.6471774, 0.7069492, 0.8508065, 0.8471186)
    #   legend_sm = TLegend(0.6271774,0.7369492,0.8308065,0.8771186)
    #   legend_sm.SetTextSize(0.037);
    legend_sm.SetTextSize(0.037)

    legend_sm.SetTextFont(42)
    legend_sm.SetFillColor(0)
    legend_sm.SetLineColor(0)

    for i, f in enumerate(bh_files):
        h = f.Get("plotsN%d%s/ST" % (N, suffix))
        h.Rebin(config.rebin)
        h.Scale(bh_weights[i])

        # Add background
        for ibin in range(h.GetNbinsX()):
            h.SetBinContent(ibin+1,\
                  h.GetBinContent(ibin+1)\
                  + hBkg.GetBinContent(ibin+1))

            h.SetLineWidth(3)
            #h.SetLineColor(i+2)
            h.SetLineStyle(i + 2)

            #if i == 0:
            #h.SetLineColor(814)
            if i == 0:
                h.SetLineStyle(5)
                h.SetLineColor(899)
            if i == 1:
                h.SetLineStyle(9)
                h.SetLineColor(4)
            if i == 2:
                h.SetLineStyle(3)
                h.SetLineColor(614)

        hs.Add(h, "hist")
        model = ModelKey(config.bh_showcase[i])
        bh_legend = "M_{D} = %.1f TeV, M_{BH}^{ min} = %.1f TeV, n = %d" % (\
              model.parameter["MD"],
              model.parameter["M"],
              model.parameter["n"])
        if i == 3:
            bh_legend = "M_{D} = 3.0 TeV, M_{QBH}^{ min} = 4.0 TeV, n = 4"

        legend.AddEntry(h, bh_legend, "l")

#      qbh_legend = "M_{D} = 4.0 TeV, M_{QBH}^{ min} = 5.0 TeV, n = 5"

#      legend.AddEntry(h, qbh_legend, "l")

#if isExclusive:
    zeynep = True
    if zeynep:
        for i, f in enumerate(sm_files):
            h = f.Get("plotsN%d%s/ST" % (N, suffix))
            h.Rebin(config.rebin)
            h.Scale(config.integrated_luminosity)
            h.SetFillColor(config.sm_colors[i])
            h.SetLineColor(config.sm_colors[i])
            hs1.Add(h, "hist")
            legend_sm.AddEntry(h, config.sm_models[i], "f")

    #hs.Add(hData, "e")

    hs.Draw("nostack")
    hs1.Draw("same")

    c.SetLogy(1)
    hs.GetXaxis().SetTitle("S_{T} (GeV)")
    hs.GetYaxis().SetTitle(hData.GetYaxis().GetTitle())
    hs.GetYaxis().SetTitleOffset(1.25)

    hs.GetYaxis().SetTitleSize(0.04)
    hs.GetYaxis().SetLabelSize(0.04)
    hs.GetXaxis().SetTitleSize(0.01)
    hs.GetXaxis().SetLabelSize(0.01)

    ibin = 0
    #if isExclusive:
    #   hs.GetXaxis().SetRangeUser(config.fit_range[0], config.maxST)
    #   ibin = hData.FindBin(config.fit_range[0])
    #else:
    #   hs.GetXaxis().SetRangeUser(config.norm_range[0], config.maxST)
    #   ibin = hData.FindBin(config.norm_range[0])

    if isExclusive:
        hs.GetXaxis().SetRangeUser(1800, config.maxST)
        ibin = hData.FindBin(1800)
    else:
        hs.GetXaxis().SetRangeUser(config.norm_range[0], config.maxST)
        ibin = hData.FindBin(config.norm_range[0])

    from Styles import formatUncertainty
    formatUncertainty(gBkg)
    gBkg.Draw("LX")
    hData.Draw("sameex0")

    hs.SetMinimum(5e-1)
    if isExclusive:
        hs.SetMaximum(1e7)

#     hs.SetMaximum(hData.GetBinContent(ibin) * 40)
    else:
        #hs.SetMaximum(1e8)
        hs.SetMaximum(hData.GetBinContent(ibin) *
                      20)  # or 1e7 for N>=3 and use 4 models

    legend.Draw("plain")
    #if isExclusive:
    if zeynep:
        legend_sm.Draw("plain")

    if isExclusive:
        cmslabel = TPaveText(0.45, 0.96, 0.60, 0.99, "brNDC")
    else:
        cmslabel = TPaveText(0.45, 0.96, 0.60, 0.99, "brNDC")
    cmslabel.AddText(config.cmsTitle)
    #cmslabel.AddText(config.cmsSubtitle)
    cmslabel.SetFillColor(0)
    cmslabel.SetTextSize(0.041)
    cmslabel.Draw("plain")

    label = TPaveText(0.8891129, 0.8644068, 0.9435484, 0.9258475, "brNDC")
    label.SetFillColor(0)
    #label.SetTextSize(0.0529661);
    label.SetTextSize(0.0529661)
    label.AddText(label_text)
    label.Draw("plain")

    c.RedrawAxis()

    #Divide

    ibin = hData.FindBin(config.norm_range[0])
    #print ibin

    fbin = hData.FindBin(config.maxST)
    #print fbin

    hData.Sumw2()
    hBkg_.Sumw2()

    Pull = TH1F("", "", fbin - ibin + 1, (ibin - 1) * 100, fbin * 100)
    Pull2 = TH1F("", "", fbin - ibin + 1, (ibin - 1) * 100, fbin * 100)

    Ratio = hData.Clone()
    Ratio.Add(hBkg_, -1)
    #Ratio.Divide(hBkg_)

    Band = TGraphAsymmErrors(fbin - ibin + 1)

    for i in range(ibin - 1, fbin + 1):
        i += 1
        if hData.GetBinContent(i) != 0:
            value = hData.GetBinContent(i) + (hBkg_.GetBinError(i) *
                                              hBkg_.GetBinError(i))
            #print Ratio.GetBinError(i),  value**(0.5)
            #print i-19,i,(i)*100, hData.GetBinContent(i) , hBkg_.GetBinContent(i),hData.GetBinContent(i) - hBkg_.GetBinContent(i)
            Pull.SetBinContent(
                i - 19, (hData.GetBinContent(i) - hBkg_.GetBinContent(i)) /
                Ratio.GetBinError(i))
            #print Ratio.GetBinError(i), abs(Ratio.GetBinContent(i))*0.05
            #Pull.SetBinContent(i-19,(hData.GetBinContent(i) - hBkg_.GetBinContent(i))/ Ratio.GetBinError(i))
            #Pull.SetBinContent(i-19,(hData.GetBinContent(i) / hBkg_.GetBinContent(i)))
            Pull.SetBinError(i - 19, Ratio.GetBinError(i))
            #Pull.SetBinError(i-19,hData.GetBinError(i)/gBkg.GetErrorY(i))
            if (hBkg_.GetBinContent(i) * 0.05 > hBkg_.GetBinError(i)):
                #print "bin error too small changing the error to: ", hBkg_.GetBinContent(i)*0.05
                Pull2.SetBinContent(
                    i - 19,
                    (hnewBkg.GetBinContent(i) - hBkg_.GetBinContent(i)) /
                    (hBkg_.GetBinContent(i) * 0.05))
            else:
                Pull2.SetBinContent(
                    i - 19,
                    (hnewBkg.GetBinContent(i) - hBkg_.GetBinContent(i)) /
                    hBkg_.GetBinError(i))
            #print hBkg_.GetBinError(i), hBkg_.GetBinContent(i)*0.05
            #print i, " Pull2: ", Pull2.GetBinContent(i-19), "hnewBkg.GetBinContent(i-1): " , hnewBkg.GetBinContent(i-1), "hBkg_.GetBinContent(i): ", hBkg_.GetBinContent(i)
        else:
            Pull.SetBinContent(i - 19, 0)
            Pull2.SetBinContent(
                i - 19,
                (hnewBkg.GetBinContent(i - 1) - hBkg_.GetBinContent(i)) /
                hBkg_.GetBinError(i))

        Band.SetPoint(i, hBkg_.GetBinCenter(i), 1.0)
        #print hBkg_.GetBinContent(i), hBkg_.GetBinError(i)
        up = abs(1. - ((hBkg_.GetBinContent(i) + hBkg_.GetBinError(i)) /
                       hBkg_.GetBinContent(i)))
        down = abs(1. - ((hBkg_.GetBinContent(i) - hBkg_.GetBinError(i)) /
                         hBkg_.GetBinContent(i)))
        Band.SetPointError(i, 0., 0., down, up)

    #Band.Print()
    pad = TPad("pad", "pad", 0.0, 0.0, 1.0, 1.0)

    pad.SetTopMargin(0.799999)
    pad.SetRightMargin(0.05)
    pad.SetBottomMargin(0.09)

    pad.SetFillColor(0)
    #pad.SetGridy(1)
    pad.SetFillStyle(0)
    pad.Draw("same")
    pad.cd(0)

    Ratio.SetMarkerStyle(20)
    Pull.SetMarkerStyle(20)
    Pull.SetLineColor(1)
    Pull.SetMarkerSize(0.9)
    #Pull.SetMaximum(3)
    #Pull.SetMinimum(-1)

    Pull.SetMaximum(2.5)
    Pull.SetMinimum(-2.5)
    Pull.GetYaxis().SetNdivisions(5, 1)

    Pull.GetXaxis().SetTitle('S_{T} (GeV)')
    Pull.GetXaxis().SetLabelSize(0.04)

    Pull.GetYaxis().SetTitleOffset(1.05)
    Pull.GetYaxis().SetLabelSize(0.02)
    Pull.GetYaxis().SetTitleSize(0.025)
    Pull.GetYaxis().CenterTitle(1)

    Pull.GetYaxis().SetTitle('#sigma(Data-Bkg)')

    Pull.SetFillColor(2)
    Pull.Draw("HIST")
    Pull2.SetLineColor(862)
    Pull2.SetLineWidth(3)
    Pull2.SetLineStyle(2)
    #Pull2.Draw("SAME")
    formatUncertainty(Band)
    Band.SetFillStyle(3001)

    # Band.Draw("le3")
    # Pull.Draw("ex0same")
    pad.RedrawAxis()

    gStyle.SetOptStat(0)

    #block1 =TPaveText(0.370,0.84,0.351,0.86,"brNDC"); # for N>=2 and >=3 only
    #block1 =TPaveText(0.361,0.85,0.377,0.87,"brNDC");
    #block1 =TPaveText(0.333,0.88,0.354,0.85,"brNDC") #for n = 2 only

    block1 = TPaveText(0.331, 0.82, 0.357, 0.85, "brNDC")
    #FOR n=3 only
    block1.SetFillColor(0)
    block1.Draw("plain")

    #block2 =TPaveText(0.305,0.84,0.333,0.86,"brNDC"); # for N>=2 and >=3 only
    #block2 =TPaveText(0.395,0.85,0.41,0.87,"brNDC");
    #block2 =TPaveText(0.296,0.88,0.316,0.85,"brNDC"); for n =2 only

    block2 = TPaveText(0.295, 0.82, 0.317, 0.85, "brNDC")
    #FOR n=3 only
    block2.SetFillColor(0)
    block2.Draw("plain")

    if isExclusive:
        c.Print("ST_Mul%d.pdf" % N)
        c.Print("ST_Mul%d.png" % N)
    else:
        c.Print("ST_Mul%dup.pdf" % N)
        c.Print("ST_Mul%dup.png" % N)
    c.Update()

    raw_input("Press Enter to continue...")
Пример #16
0
    1.169e-05
])
theory_v = TVectorD(8, theory_a)
mass_a = array("d", [1250, 1500, 1750, 2000, 2250, 2500, 2750, 3000])
mass_v = TVectorD(8, mass_a)
err_a = array("d", [0, 0, 0, 0, 0, 0, 0, 0, 0])
err_v = TVectorD(8, err_a)

## theory_a = array("d",[0.0006434760289,0.0005751010031,0.0005231099785,0.0005344069796,0.0005340549978])
## theory_v = TVectorD(5,theory_a)
## mass_a = array("d",[1750,2000,2500,2750,3000])
## mass_v = TVectorD(5,mass_a)
## err_a = array("d",[0,0,0,0,0,0])
## err_v = TVectorD(5,err_a)

theory = TGraphAsymmErrors(mass_v, theory_v, err_v, err_v, err_v, err_v)
theory.SetLineColor(4)
theory.SetLineStyle(9)
theory.SetLineWidth(3)

observed_p = TGraphAsymmErrors(massv, obsv, masserrv, masserrv, obserrv,
                               obserrv)
observed_p.SetLineColor(ROOT.kBlack)
observed_p.SetLineWidth(2)
observed_p.SetMarkerStyle(20)
expected_p = TGraphAsymmErrors(massv, expv, masserrv, masserrv, experrv,
                               experrv)
expected_p.SetLineColor(ROOT.kBlack)
expected_p.SetLineWidth(2)
expected_p.SetLineStyle(2)
Пример #17
0
    def TextFileToRootGraphs(self, limit_text_file):#, limit_text_filename):
        filename = limit_text_file #limit_text_filename
        limit_root_file = limit_text_file.replace(".txt",".root")
        
        f = open(filename,"r")
        med=array('f')
        mchi=array('f')
        expm2=array('f')
        expm1=array('f')
        expmed=array('f')
        expp1=array('f')
        expp2=array('f')
        obs=array('f')
        errx=array('f')
    
        for line in f:
            med.append(float(line.rstrip().split()[0]))
            mchi.append(float(line.rstrip().split()[1]))
            
            expm2.append(float(line.rstrip().split()[4]) - float(line.rstrip().split()[2]) )
            expm1.append(float(line.rstrip().split()[4]) - float(line.rstrip().split()[3]) )
            expmed.append(float(line.rstrip().split()[4]))
            expp1.append(float(line.rstrip().split()[5]) - float(line.rstrip().split()[4]) )
            expp2.append(float(line.rstrip().split()[6]) - float(line.rstrip().split()[4]) )

            obs.append(float(line.rstrip().split()[7]))
            errx.append(0.0)
    
        print ('expm2: ', expm2)
        print ('expm1: ', expm1)
        print ('expmed: ', expmed)
        print ('expp1: ', expp1)
        print ('expp2: ', expp2)
    
        g_exp2  = TGraphAsymmErrors(int(len(med)), med, expmed, errx, errx, expm2, expp2 )   ;  g_exp2.SetName("exp2")
        g_exp1  = TGraphAsymmErrors(int(len(med)), med, expmed, errx, errx, expm1, expp1 )   ;  g_exp1.SetName("exp1")
        g_expmed = TGraphAsymmErrors(int(len(med)), med, expmed)   ;  g_expmed.SetName("expmed")
        g_obs    = TGraphAsymmErrors(int(len(med)), med, obs   )   ;  g_obs.SetName("obs")
    
        f1 = TFile(limit_root_file,'RECREATE')
        g_exp2.Write()
        g_exp1.Write()
        g_expmed.Write()
        g_obs.Write()
        f1.Write()
        f1.Close()
        return limit_root_file
Пример #18
0
def limits():

    # put real limits here: lepton+jets, dilepton, combined
    obs = np.array([1, 1, 1])

    expect = np.array([1, 1, 1])
    upper1sig = np.array([1.352, 0.736390352249, 0.636])
    lower1sig = np.array([0.9153, 0.500572919846, 0.439])
    upper2sig = np.array([3.125, 1.66185164452, 1.455])
    lower2sig = np.array([1.4717, 0.805953979492, 0.715])

    channel = np.array([1.5, 0.5, -0.5])
    ey = np.array([0.495, 0.495, 0.495])
    zero = np.zeros(nchannels)

    xmin = 0.7
    xmax = 30

    c, h = draw_canvas_histo(
        xmin, xmax,
        "95% CL limit on #mu = #sigma/#sigma_{SM} at m_{H} = 125 GeV")
    c.SetLogx()

    gexpect1sig = TGraphAsymmErrors(nchannels, expect, channel, lower1sig,
                                    upper1sig, ey, ey)
    gexpect1sig.SetFillColor(kGreen)
    gexpect1sig.SetLineWidth(2)
    gexpect1sig.SetLineStyle(2)

    gexpect2sig = TGraphAsymmErrors(nchannels, expect, channel, lower2sig,
                                    upper2sig, ey, ey)
    gexpect2sig.SetFillColor(kYellow)
    gexpect2sig.SetLineWidth(2)
    gexpect2sig.SetLineStyle(2)

    gexpect2sig.Draw("2")
    gexpect1sig.Draw("2")

    gobs = TGraphErrors(nchannels, obs, channel, zero, ey)
    gobs.SetMarkerStyle(21)
    gobs.SetMarkerSize(1.5)
    gobs.SetLineWidth(2)
    #gobs.Draw("pz")

    # dashed line at median expected limits
    l = TLine()
    l.SetLineStyle(2)
    l.SetLineWidth(2)
    for bin in range(nchannels):
        l.DrawLine(expect[bin], channel[bin] - ey[bin], expect[bin],
                   channel[bin] + ey[bin])

    # line to separate individual and combined limits
    l.SetLineStyle(1)
    l.SetLineWidth(1)
    l.DrawLine(xmin, 0, xmax, 0)

    # legend
    leg = TLegend(0.67, 0.75, 0.95, 0.9)
    leg.SetFillColor(4000)
    leg.AddEntry(gexpect1sig, "Expected #pm1#sigma", "FL")
    leg.AddEntry(gexpect2sig, "Expected #pm2#sigma", "FL")
    #leg.AddEntry( gobs,        "Observed", "pl" )
    leg.Draw()

    #draw_disclaimer()

    c.RedrawAxis()
    c.Modified()
    c.Update()
    c.SaveAs("limits.pdf")
Пример #19
0
def convertHistToGraph(hist):
    graph = TGraphAsymmErrors(hist.GetNbinsX())
    for i in range(hist.GetNbinsX()):
        graph.SetPoint(i,
                       hist.GetXaxis().GetBinCenter(i), hist.GetBinContent(i))
        graph.SetPointError(i,
                            hist.GetXaxis().GetBinWidth(i) / 2.,
                            hist.GetXaxis().GetBinWidth(i) / 2.,
                            hist.GetBinError(i), hist.GetBinError(i))
    graph.SetLineWidth(hist.GetLineWidth())
    graph.SetLineStyle(hist.GetLineStyle())
    graph.SetLineColor(hist.GetLineColor())
    graph.SetMarkerSize(hist.GetMarkerSize())
    graph.SetMarkerStyle(hist.GetMarkerStyle())
    graph.SetMarkerColor(hist.GetMarkerColor())
    graph.SetFillStyle(hist.GetFillStyle())
    graph.SetFillColor(hist.GetFillColor())
    return graph
Пример #20
0
def main(options, args):
    gROOT.Reset()

    #load our super special Polarization PDF
    gROOT.ProcessLine('.L RooPolarizationPdf.cxx+')
    gROOT.ProcessLine('.L RooPolarizationConstraint.cxx+')

    #setup integration
    intConf = ROOT.RooAbsReal.defaultIntegratorConfig()
    #intConf.Print('v')
    #intConf.method1D().setLabel('RooAdaptiveGaussKronrodIntegrator1D')

    output = TFile.Open('PolVsPt' + options.fitFrame + '.root', 'recreate')
    output.cd()

    lth_pt_p = TGraphAsymmErrors()
    lphi_pt_p = TGraphAsymmErrors()
    lthphi_pt_p = TGraphAsymmErrors()
    lthtilde_pt_p = TGraphAsymmErrors()
    f_pt_p = TGraphAsymmErrors()

    lth_pt_p_list = TList()
    lphi_pt_p_list = TList()
    lthphi_pt_p_list = TList()

    lth_pt_p.SetName('lth_pt_p')
    lphi_pt_p.SetName('lphi_pt_p')
    lthphi_pt_p.SetName('lthphi_pt_p')
    lthtilde_pt_p.SetName('lthtilde_pt_p')
    f_pt_p.SetName('f_pt_p')

    lth_pt_np = TGraphAsymmErrors()
    lphi_pt_np = TGraphAsymmErrors()
    lthphi_pt_np = TGraphAsymmErrors()
    lthtilde_pt_np = TGraphAsymmErrors()
    f_pt_np = TGraphAsymmErrors()

    lth_pt_np_list = TList()
    lphi_pt_np_list = TList()
    lthphi_pt_np_list = TList()

    lth_pt_np.SetName('lth_pt_np')
    lphi_pt_np.SetName('lphi_pt_np')
    lthphi_pt_np.SetName('lthphi_pt_np')
    lthtilde_pt_np.SetName('lthtilde_pt_np')
    f_pt_np.SetName('f_pt_np')

    total_nonzero_points = 0

    for f in args:

        infile = TFile.Open(f)

        #ws = output.Get(f[:f.find('.root')].split('-')[0])
        frame = f[:f.find('.root')].split('-')[1]
        rapBin = f[:f.find('.root')].split('-')[2].split('_')[0]
        ptBin = f[:f.find('.root')].split('-')[2].split('_')[1]

        lth_p = infile.Get('lth_p_rap' + rapBin)

        for point in range(lth_p.GetN()):
            x = ROOT.Double(0)
            y = ROOT.Double(0)
            exl = float(0)
            exh = float(0)
            eyl = float(0)
            eyh = float(0)
            lth_p.GetPoint(point, x, y)
            if x != 0.0 and y != 0.0:

                infile.Get('lth_p_rap' + rapBin).GetPoint(point, x, y)
                lth_pt_p.SetPoint(total_nonzero_points, x, y)

                infile.Get('lphi_p_rap' + rapBin).GetPoint(point, x, y)
                lphi_pt_p.SetPoint(total_nonzero_points, x, y)

                infile.Get('lthphi_p_rap' + rapBin).GetPoint(point, x, y)
                lthphi_pt_p.SetPoint(total_nonzero_points, x, y)

                infile.Get('lthtilde_p_rap' + rapBin).GetPoint(point, x, y)
                lthtilde_pt_p.SetPoint(total_nonzero_points, x, y)

                infile.Get('f_p_rap' + rapBin).GetPoint(point, x, y)
                f_pt_p.SetPoint(total_nonzero_points, x, y)

                exh = infile.Get('lth_p_rap' + rapBin).GetErrorXhigh(point)
                exl = infile.Get('lth_p_rap' + rapBin).GetErrorXlow(point)
                eyh = infile.Get('lth_p_rap' + rapBin).GetErrorYhigh(point)
                eyl = infile.Get('lth_p_rap' + rapBin).GetErrorYlow(point)
                lth_pt_p.SetPointError(total_nonzero_points, exl, exh, eyl,
                                       eyh)

                exh = infile.Get('lphi_p_rap' + rapBin).GetErrorXhigh(point)
                exl = infile.Get('lphi_p_rap' + rapBin).GetErrorXlow(point)
                eyh = infile.Get('lphi_p_rap' + rapBin).GetErrorYhigh(point)
                eyl = infile.Get('lphi_p_rap' + rapBin).GetErrorYlow(point)
                lphi_pt_p.SetPointError(total_nonzero_points, exl, exh, eyl,
                                        eyh)

                exh = infile.Get('lthphi_p_rap' + rapBin).GetErrorXhigh(point)
                exl = infile.Get('lthphi_p_rap' + rapBin).GetErrorXlow(point)
                eyh = infile.Get('lthphi_p_rap' + rapBin).GetErrorYhigh(point)
                eyl = infile.Get('lthphi_p_rap' + rapBin).GetErrorYlow(point)
                lthphi_pt_p.SetPointError(total_nonzero_points, exl, exh, eyl,
                                          eyh)

                exh = infile.Get('lthtilde_p_rap' +
                                 rapBin).GetErrorXhigh(point)
                exl = infile.Get('lthtilde_p_rap' + rapBin).GetErrorXlow(point)
                eyh = infile.Get('lthtilde_p_rap' +
                                 rapBin).GetErrorYhigh(point)
                eyl = infile.Get('lthtilde_p_rap' + rapBin).GetErrorYlow(point)
                lthtilde_pt_p.SetPointError(total_nonzero_points, exl, exh,
                                            eyl, eyh)

                exh = infile.Get('f_p_rap' + rapBin).GetErrorXhigh(point)
                exl = infile.Get('f_p_rap' + rapBin).GetErrorXlow(point)
                eyh = infile.Get('f_p_rap' + rapBin).GetErrorYhigh(point)
                eyl = infile.Get('f_p_rap' + rapBin).GetErrorYlow(point)
                f_pt_p.SetPointError(total_nonzero_points, exl, exh, eyl, eyh)

                infile.Get('lth_np_rap' + rapBin).GetPoint(point, x, y)
                lth_pt_np.SetPoint(total_nonzero_points, x, y)

                infile.Get('lphi_np_rap' + rapBin).GetPoint(point, x, y)
                lphi_pt_np.SetPoint(total_nonzero_points, x, y)

                infile.Get('lthphi_np_rap' + rapBin).GetPoint(point, x, y)
                lthphi_pt_np.SetPoint(total_nonzero_points, x, y)

                infile.Get('lthtilde_np_rap' + rapBin).GetPoint(point, x, y)
                lthtilde_pt_np.SetPoint(total_nonzero_points, x, y)

                infile.Get('f_np_rap' + rapBin).GetPoint(point, x, y)
                f_pt_np.SetPoint(total_nonzero_points, x, y)

                exh = infile.Get('lth_np_rap' + rapBin).GetErrorXhigh(point)
                exl = infile.Get('lth_np_rap' + rapBin).GetErrorXlow(point)
                eyh = infile.Get('lth_np_rap' + rapBin).GetErrorYhigh(point)
                eyl = infile.Get('lth_np_rap' + rapBin).GetErrorYlow(point)
                lth_pt_np.SetPointError(total_nonzero_points, exl, exh, eyl,
                                        eyh)

                exh = infile.Get('lphi_np_rap' + rapBin).GetErrorXhigh(point)
                exl = infile.Get('lphi_np_rap' + rapBin).GetErrorXlow(point)
                eyh = infile.Get('lphi_np_rap' + rapBin).GetErrorYhigh(point)
                eyl = infile.Get('lphi_np_rap' + rapBin).GetErrorYlow(point)
                lphi_pt_np.SetPointError(total_nonzero_points, exl, exh, eyl,
                                         eyh)

                exh = infile.Get('lthphi_np_rap' + rapBin).GetErrorXhigh(point)
                exl = infile.Get('lthphi_np_rap' + rapBin).GetErrorXlow(point)
                eyh = infile.Get('lthphi_np_rap' + rapBin).GetErrorYhigh(point)
                eyl = infile.Get('lthphi_np_rap' + rapBin).GetErrorYlow(point)
                lthphi_pt_np.SetPointError(total_nonzero_points, exl, exh, eyl,
                                           eyh)

                exh = infile.Get('lthtilde_np_rap' +
                                 rapBin).GetErrorXhigh(point)
                exl = infile.Get('lthtilde_np_rap' +
                                 rapBin).GetErrorXlow(point)
                eyh = infile.Get('lthtilde_np_rap' +
                                 rapBin).GetErrorYhigh(point)
                eyl = infile.Get('lthtilde_np_rap' +
                                 rapBin).GetErrorYlow(point)
                lthtilde_pt_np.SetPointError(total_nonzero_points, exl, exh,
                                             eyl, eyh)

                exh = infile.Get('f_np_rap' + rapBin).GetErrorXhigh(point)
                exl = infile.Get('f_np_rap' + rapBin).GetErrorXlow(point)
                eyh = infile.Get('f_np_rap' + rapBin).GetErrorYhigh(point)
                eyl = infile.Get('f_np_rap' + rapBin).GetErrorYlow(point)
                f_pt_np.SetPointError(total_nonzero_points, exl, exh, eyl, eyh)

                total_nonzero_points += 1

    output.cd()

    lth_pt_p.Write()
    lphi_pt_p.Write()
    lthphi_pt_p.Write()
    lthtilde_pt_p.Write()
    f_pt_p.Write()

    lth_pt_np.Write()
    lphi_pt_np.Write()
    lthphi_pt_np.Write()
    lthtilde_pt_np.Write()
    f_pt_np.Write()

    output.Close()
    # cross sections from theory if comparison enabled
    if compareToFc or compareToNb:
        crossSecPrompt = [
            h.Integral(h.GetXaxis().FindBin(ptMin * 1.0001),
                       h.GetXaxis().FindBin(ptMax * 0.9999), 'width') /
            (ptMax - ptMin) for h in hCrossSecPrompt
        ]
        crossSecFD = [
            h.Integral(h.GetXaxis().FindBin(ptMin * 1.0001),
                       h.GetXaxis().FindBin(ptMax * 0.9999), 'width') /
            (ptMax - ptMin) for h in hCrossSecFD
        ]

        if compareToFc:
            gPromptFracFcVsCut.append(TGraphAsymmErrors(nSets))
            gPromptFracFcVsCut[iPt].SetNameTitle(
                f'gPromptFracFcVsCut_{ptString}',
                f'{commonString};#it{{f}}_{{prompt}}')
            gFDFracFcVsCut.append(TGraphAsymmErrors(nSets))
            gFDFracFcVsCut[iPt].SetNameTitle(
                f'gFDFracFcVsCut_{ptString}',
                f'{commonString};#it{{f}}_{{FD}}')
            SetObjectStyle(gPromptFracFcVsCut[iPt],
                           color=kRed + 3,
                           fillalpha=0.3,
                           markerstyle=kOpenCircle,
                           markersize=2.)
            SetObjectStyle(gFDFracFcVsCut[iPt],
                           color=kAzure + 3,
                           fillalpha=0.3,
Пример #22
0
    def getGraph(self,dset):
        from array import array
        from ROOT import TMultiGraph, TLegend, TGraphAsymmErrors
        n = len(self.__x)
        if n != len(self.__y) or n != len(self.__yErrLow) or n != len(self.__yErrHigh):
            raise StandardError, "The length of the x(%s), y(%s) and y error(%s,%s) lists does not match"%(len(self.__x), len(self.__y), len(self.__yErrLow), len(self.__yErrHigh))

        result = TMultiGraph()
        legendPosition = [float(i) for i in self.__getStyleOption("legendPosition").split()]
        legend = TLegend(*legendPosition)
        legend.SetFillColor(0)
        result.SetTitle("%s;%s;%s"%(self.__title,self.__xTitle,self.__yTitle))
        #(refArrays, refLabel) = self.__getRefernceGraphArrays()
        #refGraph = TGraphAsymmErrors(*refArrays)

        #refGraph.SetLineWidth(2)
        #refGraph.SetLineColor(int(self.__config.get("reference","lineColor")))
        #refGraph.SetFillColor(int(self.__config.get("reference","fillColor")))
        #result.Add(refGraph,"L3")
        #legend.AddEntry(refGraph,self.__config.get("reference","name"))

        xErr = array("d",[0 for i in range(n)])
        print "__x = ", self.__x
        print "__y = ", self.__y
        lst = []

        for inc in range (0,n):
            d={}
            d['run']=self.__runs[inc]
            d['x']=self.__x[inc]
            d['y']=self.__y[inc]
            d['yErr']=self.__yErrLow[inc]
            d['yTitle']=self.__yTitle
            if self.__config.has_option(self.__section,"yMin") and self.__config.has_option(self.__section,"yMax") :
                d['ymin']=float(self.__config.get(self.__section,"yMin"))
                d['ymax']=float(self.__config.get(self.__section,"yMax"))
            else:
                d['ymin']=0
                d['ymax']=0
            lst.append(d)


        obj ={}
        obj[self.__title]=lst
 #finalObj[self.__title]=lst                                                                                                                           
        #finalList.append(finalObj)                                                                                                                   

       # save_path = './JSON/'
        #completeName = os.path.join(save_path, self.__title+".json")
        if not os.path.exists("./JSON_RECO"):
            os.makedirs("./JSON_RECO")
        if not os.path.exists("JSON_RECO/"+dset):
            os.makedirs("JSON_RECO/"+dset)
        with open("./JSON_RECO/"+dset+"/"+self.__title+".json", 'w') as outfile:
            json.dump(obj, outfile,indent=4)
        print  json.dumps(obj,indent=2)

        graph = TGraphAsymmErrors(n, self.__x, self.__y, xErr, xErr, self.__yErrLow,self.__yErrHigh)
        graph.SetLineWidth(2)
        graph.SetFillColor(0)
        graph.SetLineColor(int(self.__getStyleOption("lineColor")))
        graph.SetMarkerColor(int(self.__getStyleOption("markerColor")))
        graph.SetMarkerStyle(int(self.__getStyleOption("markerStyle")))
        graph.SetMarkerSize(float(self.__getStyleOption("markerSize")))

        sysGraph = TGraphAsymmErrors(n, self.__x, self.__y, xErr, xErr, self.__ySysErrLow,self.__ySysErrHigh)
        sysGraph.SetLineWidth(1)
        sysGraph.SetFillColor(0)
        sysGraph.SetLineColor(int(self.__getStyleOption("lineColor")))
        sysGraph.SetMarkerColor(int(self.__getStyleOption("markerColor")))
        sysGraph.SetMarkerStyle(int(self.__getStyleOption("markerStyle")))
        sysGraph.SetMarkerSize(float(self.__getStyleOption("markerSize")))
        #TOMAS removed sys error from the plot
        #result.Add(sysGraph,"[]")
        result.Add(graph,"P")
#        result.SetName("MultiPlots")
#         result.SetTitle("%s;%s;%s"%(self.__title,self.__xTitle,self.__yTitle))
        result.SetName("MG_%s"%(self.__title))
        legend.AddEntry(graph, self.__getStyleOption("name"))
        
        #for (x,y,yErr) in zip(self.__x, self.__y, zip(self.__yErrLow,self.__yErrHigh)):
        #    self.__addAnnotaion("hallo",x,y,yErr)

        return (result, legend)
Пример #23
0
def draw(samples, hist, data, back, sign, snorm=1, ratio=0, poisson=False, log=False):
    # If not present, create BkgSum
    if not 'BkgSum' in hist.keys():
        hist['BkgSum'] = hist['data_obs'].Clone("BkgSum") if 'data_obs' in hist else hist[back[0]].Clone("BkgSum")
        hist['BkgSum'].Reset("MICES")
        for i, s in enumerate(back): hist['BkgSum'].Add(hist[s])
    hist['BkgSum'].SetMarkerStyle(0)
    
    # Some style
    for i, s in enumerate(data):
        hist[s].SetMarkerStyle(21)
        hist[s].SetMarkerSize(1.25)
    for i, s in enumerate(sign):
        hist[s].SetLineWidth(3)
        hist[s].SetLineStyle(samples[s]['linestyle'])
        
    for i, s in enumerate(data+back+sign+['BkgSum']):
        addOverflow(hist[s], False) # Add overflow
    
    # Set Poisson error bars
    #if len(data) > 0: hist['data_obs'].SetBinErrorOption(1) # doesn't work
    
    # Poisson error bars for data
    if poisson:
        alpha = 1 - 0.6827
        hist['data_obs'].SetBinErrorOption(TH1.kPoisson)
        data_graph = TGraphAsymmErrors(hist['data_obs'].GetNbinsX())
        data_graph.SetMarkerStyle(hist['data_obs'].GetMarkerStyle())
        data_graph.SetMarkerSize(hist['data_obs'].GetMarkerSize())
        res_graph = data_graph.Clone()
        for i in range(hist['data_obs'].GetNbinsX()):
            N = hist['data_obs'].GetBinContent(i+1)
            B = hist['BkgSum'].GetBinContent(i+1)
            L =  0 if N==0 else ROOT.Math.gamma_quantile(alpha/2,N,1.)
            U =  ROOT.Math.gamma_quantile_c(alpha/2,N+1,1)
            data_graph.SetPoint(i, hist['data_obs'].GetXaxis().GetBinCenter(i+1), N if not N==0 else -1.e99)
            data_graph.SetPointError(i, hist['data_obs'].GetXaxis().GetBinWidth(i+1)/2., hist['data_obs'].GetXaxis().GetBinWidth(i+1)/2., N-L, U-N)
            res_graph.SetPoint(i, hist['data_obs'].GetXaxis().GetBinCenter(i+1), N/B if not B==0 and not N==0 else -1.e99)
            res_graph.SetPointError(i, hist['data_obs'].GetXaxis().GetBinWidth(i+1)/2., hist['data_obs'].GetXaxis().GetBinWidth(i+1)/2., (N-L)/B if not B==0 else -1.e99, (U-N)/B if not B==0 else -1.e99)
    
    
    # Create stack
    bkg = THStack("Bkg", ";"+hist['BkgSum'].GetXaxis().GetTitle()+";Events")
    for i, s in enumerate(back): bkg.Add(hist[s])
    
    # Legend
    n = len([x for x in data+back+['BkgSum']+sign if samples[x]['plot']])
    for i, s in enumerate(sign):
        if 'sublabel' in samples[s]: n+=1
        if 'subsublabel' in samples[s]: n+=1
    #leg = TLegend(0.68, 0.9-0.05*n, 0.93, 0.9)
    leg = TLegend(0.68-0.05, 0.9-0.05*n, 0.93, 0.9)#DCMS
    leg.SetTextSize(0.03)#DCMS
    leg.SetBorderSize(0)
    leg.SetFillStyle(0) #1001
    leg.SetFillColor(0)
    leg.SetHeader("Signal x-sec=%.0f pb"%(1*snorm))
    if len(data) > 0:
        leg.AddEntry(hist[data[0]], samples[data[0]]['label'], "ple1")
    for i, s in reversed(list(enumerate(['BkgSum']+back))):
        leg.AddEntry(hist[s], samples[s]['label'], "f")    
    for i, s in enumerate(sign):
        leg.AddEntry(hist[s], samples[s]['label'], "f")

    
    # --- Display ---
    c1 = TCanvas("c1", hist.values()[-1].GetXaxis().GetTitle(), 1000, 800 if ratio else 700)
    
    if ratio:
        c1.Divide(1, 2)
        setTopPad(c1.GetPad(1), ratio)
        setBotPad(c1.GetPad(2), ratio)
    c1.cd(1)
    c1.GetPad(bool(ratio)).SetTopMargin(0.06)
    c1.GetPad(bool(ratio)).SetRightMargin(0.05)
    c1.GetPad(bool(ratio)).SetTicks(1, 1)
    if log:
        c1.GetPad(bool(ratio)).SetLogy()
        #c1.GetPad(bool(ratio)).SetLogx()
        
    # Draw
    bkg.Draw("HIST") # stack
    hist['BkgSum'].Draw("SAME, E2") # sum of bkg
    if poisson: data_graph.Draw("SAME, PE")
    elif len(data) > 0: hist['data_obs'].Draw("SAME, PE")
    for i, s in enumerate(sign):
        if samples[s]['plot']:
            hist[s].DrawNormalized("SAME, HIST", hist[s].Integral()*snorm) # signals


    # Determine range
    if 'data_obs' in hist:
        bkg.SetMaximum((2.5 if log else 1.2)*max(bkg.GetMaximum(), hist['data_obs'].GetBinContent(hist['data_obs'].GetMaximumBin())+hist['data_obs'].GetBinError(hist['data_obs'].GetMaximumBin())))
        bkg.SetMinimum(max(min(hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin()), hist['data_obs'].GetMinimum()), 5.e-1)  if log else 0.)
        bkg.SetMinimum(5.e-1)#!!
        bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset()*1.075)
    else:
        bkg.SetMaximum(bkg.GetMaximum()*(2.5 if log else 1.2))
        bkg.SetMinimum(5.e-1 if log else 0.)
        bkg.SetMinimum(5.e-1)#!!
        bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset()*1.075)
    if log:
        bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4)
        bkg.GetYaxis().SetMoreLogLabels(True)
        bkg.SetMinimum(5.e-1)#!!
        bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset()*1.075)

    #w#bkg.SetMaximum(2.e7)
    leg.Draw()
    #drawCMS(LUMI, "Preliminary")
    #drawRegion(channel)
    #drawAnalysis("LL")
    
    setHistStyle(bkg, 1.2 if ratio else 1.1)
    setHistStyle(hist['BkgSum'], 1.2 if ratio else 1.1)

    if ratio:
        c1.cd(2)
        err = hist['BkgSum'].Clone("BkgErr;")
        err.SetTitle("")
        err.GetYaxis().SetTitle("Data / Bkg")
        for i in range(1, err.GetNbinsX()+1):
            err.SetBinContent(i, 1)
            if hist['BkgSum'].GetBinContent(i) > 0:
                err.SetBinError(i, hist['BkgSum'].GetBinError(i)/hist['BkgSum'].GetBinContent(i))
        setBotStyle(err)
        errLine = err.Clone("errLine")
        errLine.SetLineWidth(2)
        errLine.SetFillStyle(0)
        errLine.SetLineColor(2)#L#
        errLine.SetLineStyle(2)#L#
        #err.GetXaxis().SetLabelOffset(err.GetXaxis().GetLabelOffset()*5)
        #err.GetXaxis().SetTitleOffset(err.GetXaxis().GetTitleOffset()*2)
        err.Draw("E2")
        errLine.Draw("SAME, HIST")
        if 'data_obs' in hist:
            res = hist['data_obs'].Clone("Residues")
            for i in range(0, res.GetNbinsX()+1):
                if hist['BkgSum'].GetBinContent(i) > 0: 
                    res.SetBinContent(i, res.GetBinContent(i)/hist['BkgSum'].GetBinContent(i))
                    res.SetBinError(i, res.GetBinError(i)/hist['BkgSum'].GetBinContent(i))
            setBotStyle(res)
            if poisson: res_graph.Draw("SAME, PE0")
            else: res.Draw("SAME, PE0")
            if len(err.GetXaxis().GetBinLabel(1))==0: # Bin labels: not a ordinary plot
                drawRatio(hist['data_obs'], hist['BkgSum'])
                drawKolmogorov(hist['data_obs'], hist['BkgSum'])
        else: res = None
    c1.Update()
    
    # return list of objects created by the draw() function
    return [c1, bkg, leg, err if ratio else None, errLine if ratio else None, res if ratio else None, data_graph if poisson else None, res_graph if poisson else None]
Пример #24
0
def main(argv):
    LOADTREE_ANADIR = "/net/user/aguilar/work/IceCube/scripts/IC59/"

    tr = TChain("Level3")
    tr.Add(LOADTREE_ANADIR + "final.nugen_numu_9.6kf_6471_E2_E27.root")

    tr.GetEntries()

    MCzenith = ctypes.c_double(0)
    tr.SetBranchAddress("mcZr", MCzenith)

    MCazimuth = ctypes.c_double(0)
    tr.SetBranchAddress("mcAr", MCazimuth)

    eneMC = ctypes.c_double(0)
    tr.SetBranchAddress("mcEn", eneMC)

    SMPEzenith = ctypes.c_double(0)
    tr.SetBranchAddress("mZd", SMPEzenith)

    SMPEazimuth = ctypes.c_double(0)
    tr.SetBranchAddress("mAd", SMPEazimuth)

    ene = ctypes.c_double(0)
    tr.SetBranchAddress("mmueEn", ene)

    sigma = ctypes.c_double(0)
    tr.SetBranchAddress("mpfSigmaDeg", sigma)

    oneW = ctypes.c_double(0)
    tr.SetBranchAddress("OW", oneW)

    nEv = ctypes.c_double(0)
    tr.SetBranchAddress("NEvents", nEv)

    h = TH2D("pull", "pull", 50, 1, 9, 1000, 0.01, 300)
    h.SetStats(0)
    h.GetXaxis().SetTitle("log_{10}(MuEx_energy [GeV])")
    h.GetYaxis().SetTitle("Pull: #Delta#Psi/#sigma_{parab.}")
    g = TGraphAsymmErrors(50)
    medians = [[] for i in range(0, 50)]
    mediansW = [[] for i in range(0, 50)]

    go = TGraph(50)
    go.SetMarkerStyle(22)
    go.SetMarkerColor(4)

    hEneW = TH1D(
        "hEneW",
        "MCPrimary energy; log_{10}(E [GeV]); #frac{d#Phi}{dE} [GeV^{-1} cm^{-2} s^{-1} sr^{-1} ( #frac{E}{GeV} )^{-2} ",
        100, 1, 9.5)
    hREneW = TH1D(
        "hREneW",
        "Reco energy SplineMPEMuEXDiff; log_{10}(E [GeV]); #frac{d#Phi}{dE} [GeV^{-1} cm^{-2} s^{-1} sr^{-1} ( #frac{E}{GeV} )^{-2}",
        100, 1, 9)

    for i in range(0, tr.GetEntries()):
        tr.GetEntry(i)
        #if not hem(np.radians(SMPEzenith.value)):
        #    continue
        #if np.radians(sigma.value)>np.radians(5.):
        #    continue
        w = weight(oneW.value, eneMC.value, nEv.value)
        hEneW.Fill(log10(eneMC.value), w)
        hREneW.Fill(log10(ene.value), w)
        dAngle = SpaceAngleRad(MCzenith.value, MCazimuth.value,
                               np.radians(SMPEzenith.value),
                               np.radians(SMPEazimuth.value))
        h.Fill(log10(ene.value), dAngle / np.radians(sigma.value), w)
        if h.GetXaxis().FindBin(log10(ene.value)) > 0 and h.GetXaxis().FindBin(
                log10(ene.value)) < 51:
            medians[h.GetXaxis().FindBin(log10(ene.value)) - 1].append(
                dAngle / np.radians(sigma.value))
            mediansW[h.GetXaxis().FindBin(log10(ene.value)) - 1].append(w)
        #if i>200:
        #break
    npoints = 0

    for i in range(1, h.GetNbinsX() + 1):
        if len(medians[i - 1]) > 3:
            wp = weighted_percentile(0.5, np.asarray(medians[i - 1]),
                                     np.asarray(mediansW[i - 1]))
            if wp > 30.: continue
            print wp
            g.SetPoint(npoints, h.GetXaxis().GetBinCenter(i), wp)
            g.SetPointError(
                npoints, 0., 0.,
                weighted_percentile(0.5 - 0.341, np.asarray(medians[i - 1]),
                                    np.asarray(mediansW[i - 1])),
                weighted_percentile(0.5 + 0.341, np.asarray(medians[i - 1]),
                                    np.asarray(mediansW[i - 1])))
            npoints += 1

    c0 = TCanvas()
    hEneW.Draw()
    c01 = TCanvas()
    hREneW.Draw()

    g.Set(npoints)
    g.SetMarkerStyle(20)
    gStyle.SetPalette(1)
    gStyle.SetOptLogz(1)
    spline = TSpline5("spl", TGraph(g))
    filename = "SplineforCorr_IC59.root"
    #if hem(0.):
    #    filename=filename+"down.root"
    #else:
    #    filename=filename+"up.root"
    fout = TFile(filename, "RECREATE")
    spline.Write()
    fout.Close()

    print "loading mpfSigmaDegRescaledIC59.C"
    ROOT.gROOT.ProcessLine(".L mpfSigmaDegRescaledIC59.C+")
    #print "loading RescaledSigma_IC59.C"
    #ROOT.gROOT.ProcessLine(".L RescaledSigma_IC59.C+")
    try:
        ROOT.loadSplines_IC59()
    except:
        pass
    npoints = 0
    for i in range(1, h.GetNbinsX() + 1):
        if len(medians[i - 1]) > 3:
            wp = weighted_percentile(0.5, np.asarray(medians[i - 1]),
                                     np.asarray(mediansW[i - 1]))
            #if wp>30.: continue
            #if hem(0.):
            #plotZen=0.
            #else:
            #plotZen=100.
            go.SetPoint(
                npoints,
                h.GetXaxis().GetBinCenter(i),
                ROOT.mpfSigmaDegRescaledIC59(
                    1., pow(10,
                            h.GetXaxis().GetBinCenter(i))))
            #go.SetPoint(npoints,h.GetXaxis().GetBinCenter(i),ROOT.RescaledSigma_IC59(1.,pow(10,h.GetXaxis().GetBinCenter(i))))
            npoints += 1
    go.Set(npoints)

    del medians[:]
    del medians
    del mediansW[:]
    del mediansW

    c = TCanvas()
    c.SetLogy()
    c.SetGridx()
    c.SetGridy()
    h.SetMinimum(1)
    h.Draw("colz")
    g.Draw("pl same")
    go.Draw("pl same")
    # spline.Draw("lp same")

    h2 = TH2D("pull - corrected", "pull - corrected", 50, 1, 9, 100, 0.01, 30)
    h2.GetXaxis().SetTitle("log_{10}(E [GeV])")
    h2.GetYaxis().SetTitle("Pull_{corr}: #Delta#Psi/f_{corr}(#sigma_{parab.})")

    g2 = TGraphAsymmErrors(50)
    medians2 = [[] for i in range(0, 50)]
    medians2W = [[] for i in range(0, 50)]
    g2.SetMarkerStyle(20)

    for i in range(0, tr.GetEntries()):
        tr.GetEntry(i)
        #if not hem(np.radians(SMPEzenith.value)): continue
        #if np.radians(sigma.value)>np.radians(5.):
        #    continue
        w = weight(oneW.value, eneMC.value, nEv.value)
        dAngle = SpaceAngleRad(MCzenith.value, MCazimuth.value,
                               np.radians(SMPEzenith.value),
                               np.radians(SMPEazimuth.value))
        h2.Fill(
            log10(ene.value),
            dAngle / (np.radians(sigma.value) * spline.Eval(log10(ene.value))),
            w)
        if h.GetXaxis().FindBin(log10(ene.value)) > 0 and h.GetXaxis().FindBin(
                log10(ene.value)) < 51:
            medians2[h.GetXaxis().FindBin(log10(ene.value)) - 1].append(
                dAngle /
                (np.radians(sigma.value) * spline.Eval(log10(ene.value))))
            medians2W[h.GetXaxis().FindBin(log10(ene.value)) - 1].append(w)
        #if i>200:
        #break

    npoints = 0
    for i in range(1, h2.GetNbinsX() + 1):
        if len(medians2[i - 1]) > 3:
            wp = weighted_percentile(0.5, np.asarray(medians2[i - 1]),
                                     np.asarray(medians2W[i - 1]))
            #if wp>30.: continue
            g2.SetPoint(npoints, h.GetXaxis().GetBinCenter(i), wp)
            g2.SetPointError(
                npoints, 0., 0.,
                weighted_percentile(0.5 - 0.341, np.asarray(medians2[i - 1]),
                                    np.asarray(medians2W[i - 1])),
                weighted_percentile(0.5 + 0.341, np.asarray(medians2[i - 1]),
                                    np.asarray(medians2W[i - 1])))
            npoints += 1

    del medians2[:]
    del medians2
    del medians2W[:]
    del medians2W

    g2.Set(npoints)
    c2 = TCanvas()
    c2.SetLogy()
    c2.SetGridx()
    c2.SetGridy()
    h2.SetStats(0)
    h2.SetMinimum(1)
    h2.Draw("colz")
    g2.Draw("pl same")

    h3 = TH2D("pull - corrected xcheck", "pull - corrected xcheck", 50, 1, 9,
              100, 0.01, 30)
    h3.GetXaxis().SetTitle("log_{10}(E [GeV])")
    h3.GetYaxis().SetTitle("Pull_{corr}: #Delta#Psi/f_{corr}(#sigma_{parab.})")
    g3 = TGraphAsymmErrors(50)
    medians3 = [[] for i in range(0, 50)]
    medians3W = [[] for i in range(0, 50)]
    g3.SetMarkerStyle(20)
    SigmaBins = [(0.5, 0.6, 1), (0.6, 0.7, 2), (0.7, 0.9, 4), (0.9, 1.3, 1),
                 (1.3, 1.7, 2)]
    h_pdf_corr = []
    for b in range(len(SigmaBins)):
        h_pdf_corr.append(
            TH1D("h_pdf_corr" + str(b),
                 "h_pdf_corr" + str(b) + ";#Delta#Psi [deg]", 50, 0, 3))
        h_pdf_corr[-1].SetLineColor(SigmaBins[b][2])
        h_pdf_corr[-1].SetLineWidth(2)

    for i in range(0, tr.GetEntries()):
        tr.GetEntry(i)
        #if not hem(np.radians(SMPEzenith.value)): continue
        #if np.radians(sigma.value)>np.radians(5.):
        #    continue
        w = weight(oneW.value, eneMC.value, nEv.value)
        dAngle = SpaceAngleRad(MCzenith.value, MCazimuth.value,
                               np.radians(SMPEzenith.value),
                               np.radians(SMPEazimuth.value))
        pull = dAngle / ROOT.mpfSigmaDegRescaledIC59(np.radians(sigma.value),
                                                     ene.value)
        s_cor = ROOT.mpfSigmaDegRescaledIC59(np.radians(sigma.value),
                                             ene.value)
        #pull=dAngle/ROOT.RescaledSigma_IC59(np.radians(sigma.value),ene.value)
        #s_cor=ROOT.RescaledSigma_IC59(np.radians(sigma.value),ene.value)
        h3.Fill(log10(ene.value), pull, w)
        for b in range(len(SigmaBins)):
            if SigmaBins[b][0] <= np.degrees(
                    s_cor) and SigmaBins[b][1] > np.degrees(s_cor):
                h_pdf_corr[b].Fill(np.degrees(dAngle), w)

        if h.GetXaxis().FindBin(log10(ene.value)) > 0 and h.GetXaxis().FindBin(
                log10(ene.value)) < 51:
            medians3[h.GetXaxis().FindBin(log10(ene.value)) - 1].append(pull)
            medians3W[h.GetXaxis().FindBin(log10(ene.value)) - 1].append(w)
        #if i>200:
        #break

    npoints = 0
    for i in range(1, h2.GetNbinsX() + 1):
        if len(medians3[i - 1]) > 3:
            wp = weighted_percentile(0.5, np.asarray(medians3[i - 1]),
                                     np.asarray(medians3W[i - 1]))
            #if wp>30.: continue
            g3.SetPoint(npoints, h.GetXaxis().GetBinCenter(i), wp)
            g3.SetPointError(
                npoints, 0., 0.,
                weighted_percentile(0.5 - 0.341, np.asarray(medians3[i - 1]),
                                    np.asarray(medians3W[i - 1])),
                weighted_percentile(0.5 + 0.341, np.asarray(medians3[i - 1]),
                                    np.asarray(medians3W[i - 1])))
            npoints += 1

    c30 = TCanvas()
    leg = ROOT.TLegend(0.7, 0.7, 1., 1.)
    ffunc = []
    for b in range(3):
        h_pdf_corr[b].Sumw2()
        if b == 0:
            h_pdf_corr[b].Draw("HIST")
        else:
            h_pdf_corr[b].Draw("same HIST")

        ffunc.append(TF1("ffunc" + str(b), CircGaus, 0.001, 3., 2))
        ffunc[-1].SetLineColor(SigmaBins[b][2])
        ffunc[-1].SetParameter(0, 1.)
        ffunc[-1].SetParameter(1, 1.)

        h_pdf_corr[b].Fit(ffunc[-1], "R")
        ffunc[-1].Draw("same")
        leg.AddEntry(
            h_pdf_corr[b],
            "range: " + str(SigmaBins[b][0]) + " to " + str(SigmaBins[b][1]) +
            " #sigma_{fit}=" + '{:.2f}'.format(ffunc[-1].GetParameter(0)), "l")
    leg.Draw()

    c31 = TCanvas()
    leg1 = ROOT.TLegend(0.7, 0.7, 1., 1.)
    ffunc = []
    for b in range(3, 5):
        h_pdf_corr[b].Sumw2()
        if b == 0:
            h_pdf_corr[b].Draw("HIST")
        else:
            h_pdf_corr[b].Draw("same HIST")
        ffunc.append(TF1("ffunc" + str(b), CircGaus, 0.001, 3., 2))
        ffunc[-1].SetLineColor(SigmaBins[b][2])
        ffunc[-1].SetParameter(0, 1.)
        ffunc[-1].SetParameter(1, 1.)

        h_pdf_corr[b].Fit(ffunc[-1], "R")
        ffunc[-1].Draw("same")
        leg1.AddEntry(
            h_pdf_corr[b],
            "range: " + str(SigmaBins[b][0]) + " to " + str(SigmaBins[b][1]) +
            " #sigma_{fit}=" + '{:.2f}'.format(ffunc[-1].GetParameter(0)), "l")
    leg1.Draw()

    g3.Set(npoints)
    c3 = TCanvas()
    c3.SetLogy()
    c3.SetGridx()
    c3.SetGridy()
    h3.SetStats(0)
    h3.SetMinimum(1)
    h3.Draw("colz")
    g3.Draw("pl same")
    #c3.SaveAs("mpfSigmaDegRescaledIC79V2_corrected.png")
    raw_input("Press Enter to continue...")
Пример #25
0
def main():
    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option("-i", "--inputfile", dest="inputfile")
    parser.add_option("-o", "--ouputfile", dest="outputfile")
    parser.add_option("-b", "--batch", action="store_true",\
          dest="isBatch", default=False)
    parser.add_option("--normalization", nargs=2,\
          type="float", dest="norm_range")
    parser.add_option("--fit", nargs=2,\
          type="float", dest="fit_range")
    (options, args) = parser.parse_args()

    isSaveOutput = options.outputfile is not None

    if not (options.inputfile):
        parser.error("Please specify inputfiles.")

    import configurations as config

    integrated_luminosity = config.integrated_luminosity

    if options.fit_range:
        fit_range = options.fit_range
        norm_range = (fit_range[1] - 200., fit_range[1])
    else:
        fit_range = config.fit_range
        norm_range = config.norm_range

    # Override normalization range from input
    if options.norm_range:
        norm_range = options.norm_range

    from Styles import formatST, formatTemplate, formatUncertainty
    from ROOT import TFile, TF1, TH1D, TMath, TCanvas, TLegend,\
          TGraphAsymmErrors, TVectorD, gStyle

    gStyle.SetPadTopMargin(0.05)
    gStyle.SetPadRightMargin(0.05)
    #gStyle.SetOptFit(2222222)
    #gStyle.SetStatX(0.95)
    #gStyle.SetStatY(0.95)
    gStyle.SetOptStat(0000000)
    gStyle.SetOptFit(0000000)
    from ROOT import TFile, TCanvas, TMultiGraph, TLegend, TPaveText

    #input file name
    infile = TFile(options.inputfile, "READ")

    from HistoStore import HistoStore
    store = HistoStore()
    canvas = HistoStore()

    print "Fit range: %d - %d GeV" % fit_range
    print "Normalization range: %d - %d GeV" % norm_range
    print "Integrated luminosity: %d inv. pb" % integrated_luminosity

    # Fit
    for N in config.exclusive_multiplicities:
        hST = infile.Get("plots%dJets/ST" % N)
        hST.GetXaxis().SetNdivisions(510)
        if not options.isBatch:
            c = TCanvas("TemplateN%d" % N, "TemplateN%d" % N, 500, 500)
            canvas.book(c)
            formatST(hST)
            hST.SetTitle("")
            hST.Draw("e")
            hST.GetXaxis().SetRangeUser(fit_range[0], config.maxST)
            hST.GetYaxis().SetRangeUser(1e-2, 2e4)
            hST.GetYaxis().SetTitleOffset(1.25)
            hST.GetYaxis().SetTitleSize(0.04)
            hST.GetYaxis().SetLabelSize(0.04)
            hST.GetXaxis().SetTitleSize(0.04)
            hST.GetXaxis().SetLabelSize(0.04)
            c.SetLogy(1)

        for i, formula in enumerate(config.templates):
            print "formula %d" % (i)
            if N == 2:
                f = TF1("templateN%d_%d" % (N, i), formula, 0, 10000)
            elif N == 3:
                f = store.get("templateN2_%d" % i).Clone("templateN%d_%d" %
                                                         (N, i))
            if i < 3:
                hST.Fit(f, "QN0", "", 1800, 2800)
                hST.Fit(f, "QN0", "", 1800, 2800)
                hST.Fit(f, "QN0", "", 1800, 2800)
                hST.Fit(f, "QN0", "", 1800, 2800)
                hST.Fit(f, "QN0", "", 1800, 2800)
                hST.Fit(f, "QN0", "", 1800, 2800)
                hST.Fit(f, "QN0", "", 1800, 2800)
                hST.Fit(f, "QN0", "", 1800, 2800)
                hST.Fit(f, "QN0", "", 1800, 2800)
                hST.Fit(f, "QN0", "", 1800, 2800)
                hST.Fit(f, "QN0", "", 1800, 2800)
                hST.Fit(f, "QN0", "", 1800, 2800)
                hST.Fit(f, "QN0", "", 1800, 2800)
                hST.Fit(f, "QN0", "", 1800, 2800)
                hST.Fit(f, "QN0", "", 1800, 2800)
                hST.Fit(f, "QN0", "", 1800, 2800)
                hST.Fit(f, "QN0", "", 1800, 2800)
                hST.Fit(f, "QN0", "", 1800, 2800)
                hST.Fit(f, "QN0", "", 1800, 2800)
                hST.Fit(f, "QN0", "", 1800, 2800)
                hST.Fit(f, "QN0", "", 1800, 2800)
                hST.Fit(f, "QN0", "", 1800, 2800)
                hST.Fit(f, "QN0", "", 1800, 2800)
                hST.Fit(f, "QN0", "", 1800, 2800)
                hST.Fit(f, "N0", "", 1800, 2800)
            elif i == 0:
                hST.Fit(f, "Q0", "", fit_range[0], fit_range[1])
            elif i > 2:
                hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
                hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
                hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
                hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
                hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
                hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
                hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
                hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
                hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
                hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
                hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
                hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
                hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
                hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
                hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
                hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
                hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
                hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
                hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
                hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
                hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
                hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
                hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
                hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])
                hST.Fit(f, "QN0", "", fit_range[0], fit_range[1])

            formatTemplate(f, N, i)
            store.book(f)

            if not options.isBatch:
                f.Draw("same")

            hTemplate = hST.Clone("histoTemplateN%d_%d" % (N, i))
            hTemplate.Reset()
            hTemplate.Eval(f)
            formatTemplate(hTemplate, N, i)
            store.book(hTemplate)

            if i == 0:
                hRef = hTemplate.Clone("ReferenceTemplateN%d_0" % N)
                store.book(hRef)

            # Print Chi-squre/Ndof
            print "N = %d, Chi^2/Ndof = %0.2f/%d" %\
                  (N, f.GetChisquare(), f.GetNDF())
        if not options.isBatch:
            c.Update()
            c.Print("TemplateN%d.pdf" % N)
            c.Print("TemplateN%d.png" % N)

    # Calculate scale/error
    from OptimizationTools import OptimizeScale
    for histoN, templateN in [[2, 3]]:
        hST = store.get("ReferenceTemplateN%d_0" % histoN)
        hTemplate = store.get("ReferenceTemplateN%d_0" % templateN)

        hlnL, scale, err = OptimizeScale(hST, hTemplate, norm_range)
        hlnL.SetName("LogLikelihood_%dto%d" % (templateN, histoN))
        store.book(hlnL)

        for i in range(len(config.templates)):
            hTemplate = store.get("histoTemplateN%d_%d" % (templateN, i))
            hTemplate_ = hTemplate.Clone("histoTemplateN%d_%d__RescaledToN%d" %
                                         (templateN, i, histoN))
            hTemplate_.Scale(scale)
            store.book(hTemplate_)

    # Shape Uncertainty
    hBkgTemplate = store.get("histoTemplateN2_0")
    hBkgTemplate.Rebin(config.rebin)
    nbins = hBkgTemplate.GetNbinsX()
    vST = TVectorD(nbins)
    vBkg = TVectorD(nbins)
    vexl = TVectorD(nbins)
    vexh = TVectorD(nbins)
    shape_el = TVectorD(nbins)
    shape_eh = TVectorD(nbins)
    rel_shape_el = TVectorD(nbins)
    rel_shape_eh = TVectorD(nbins)
    for i in range(nbins):
        vST[i] = hBkgTemplate.GetBinCenter(i + 1)
        if (vST[i] < config.com):
            vBkg[i] = hBkgTemplate.GetBinContent(i + 1)
        else:
            vBkg[i] = 0.0
        vexl[i] = 0.0
        vexh[i] = 0.0
        shape_el[i] = 0.0
        shape_eh[i] = 0.0
        rel_shape_el[i] = 0.0
        rel_shape_eh[i] = 0.0

    for i in range(len(config.templates)):
        for label in [
                "histoTemplateN2_%d", "histoTemplateN3_%d__RescaledToN2"
        ]:
            if label % i == "histoTemplateN2_0":
                continue
            h = store.get(label % i)
            h.Rebin(config.rebin)
            for ibin in range(nbins):
                diff = h.GetBinContent(ibin + 1) - vBkg[ibin]
                if diff > 0 and diff > shape_eh[ibin]:
                    shape_eh[ibin] = diff
                elif diff < 0 and abs(diff) > shape_el[ibin]:
                    shape_el[ibin] = abs(diff)

    # Relative Shape Uncertaincy
    for i in range(nbins):
        if vBkg[i] > 0:
            #rel_shape_el[i] = rel_shape_el[i] / vBkg[i]
            #hape_eh[i] = rel_shape_eh[i] / vBkg[i]
            max_err = max(shape_el[i], shape_eh[i])
            shape_el[i] = max_err
            shape_eh[i] = max_err
            rel_shape_el[i] = max_err / vBkg[i]
            rel_shape_eh[i] = max_err / vBkg[i]
        else:
            rel_shape_el[i] = 0.0
            rel_shape_eh[i] = 0.0
        #print vST[i], vBkg[i], rel_shape_el[i], rel_shape_eh[i]
    gShapeUncertainty = TGraphAsymmErrors(vST, vBkg, vexl, vexh, shape_el,
                                          shape_eh)
    gShapeUncertainty.SetName("Shape_Uncertainty")
    formatUncertainty(gShapeUncertainty)
    store.book(gShapeUncertainty)

    gRelShapeUncertainty = TGraphAsymmErrors(vST, vexl, vexl, vexh,
                                             rel_shape_el, rel_shape_eh)
    gRelShapeUncertainty.SetName("Relative_Shape_Uncertainty")
    formatUncertainty(gRelShapeUncertainty)
    store.book(gRelShapeUncertainty)

    # Generate Backgrouds
    for N in config.label_for_data:
        hST = infile.Get("plotsN%s/ST" % N)
        rel_scale_err2 = 0.0
        scale_factor = 1.0
        for Nref in config.label_for_ref:
            if N == Nref:
                continue

            template = store.get("ReferenceTemplateN%s_0" % Nref)

            hlnL, scale, err = OptimizeScale(hST, template, norm_range)
            hlnL.SetName("LogLikelihood_%sto%s" % (Nref, N))
            store.book(hlnL)

            if Nref == "2":
                scale_factor = scale
            rel_scale_err2 += err / scale * err / scale

            print "%s/%s %.3f $\pm$ %.3f" % (N, Nref, scale, err)

        vy = TVectorD(nbins)
        veyh = TVectorD(nbins)
        veyl = TVectorD(nbins)
        for i in range(nbins):
            vy[i] = vBkg[i] * scale_factor
            veyh[i] = vy[i] * TMath.Sqrt(rel_scale_err2 +
                                         rel_shape_eh[i] * rel_shape_eh[i])
            veyl[i] = vy[i] * TMath.Sqrt(rel_scale_err2 +
                                         rel_shape_el[i] * rel_shape_el[i])

        print "Scaling uncertainty (%s): %.2f" %\
              (N, TMath.sqrt(rel_scale_err2) * 100.0)

        gBkg = TGraphAsymmErrors(vST, vy, vexl, vexh, veyl, veyh)
        gBkg.SetName("BackgroundGraph_N%s" % N)
        formatUncertainty(gBkg)
        store.book(gBkg)

        hST.Rebin(config.rebin)
        hST.SetName("Data_N%s" % N)
        formatST(hST)
        store.book(hST)

        hBkg = hST.Clone("Background_N%s" % N)
        hBkg.Reset()
        store.book(hBkg)

        for i in range(nbins):
            ibin = hBkg.FindBin(vST[i])
            hBkg.SetBinContent(ibin, vy[i])
            hBkg.SetBinError(ibin, max(veyh[i], vexl[i]))

        from OptimizationTools import Integral
        hIntBkg = hBkg.Clone("IntegralBackground_N%s" % N)
        Integral(hIntBkg)
        store.book(hIntBkg)

        hIntData = hST.Clone("IntegralData_N%s" % N)
        Integral(hIntData)
        store.book(hIntData)

    # Plot Shape Uncertainty
    if not options.isBatch:
        legend_shape = TLegend(0.4244355, 0.4241525, 0.9395968, 0.8652542)
        legend_shape.SetTextFont(42)
        legend_shape.SetFillColor(0)
        legend_shape.SetLineColor(0)
        legend_shape.SetTextSize(0.036)
        c = TCanvas("ShapeUncertaintyN2", "ShapeUncertaintyN2", 500, 500)
        canvas.book(c)
        gShapeUncertainty.Draw("AC3")
        gShapeUncertainty.GetXaxis().SetNdivisions(510)
        gShapeUncertainty.GetXaxis().SetRangeUser(fit_range[0], config.maxST)
        gShapeUncertainty.GetYaxis().SetRangeUser(5e-2, 5e6)

        legend_shape.AddEntry(store.get("Data_N2"), "Data (N = 2)", "p")
        legend_shape.AddEntry(gShapeUncertainty, "Shape Uncertainty", "f")
        for i in range(len(config.templates)):
            for label in [
                    "histoTemplateN2_%d", "histoTemplateN3_%d__RescaledToN2"
            ]:
                h = store.get(label % i)
                h.GetXaxis().SetRangeUser(fit_range[0], config.maxST)
                h.Draw("histcsame")
                h.GetXaxis().SetNdivisions(510)
                if label == "histoTemplateN2_%d":
                    N = 2
                else:
                    N = 3
                legend_shape.AddEntry(h,
                                      "Parameterization %d (N = %d)" % (i, N),
                                      "l")
        store.get("Data_N2").Draw("esame")
        cmslabel = TPaveText(0.45, 0.90, 0.60, 0.93, "brNDC")
        cmslabel.AddText(config.cmsTitle)
        #cmslabel.AddText(config.cmsSubtitle)
        cmslabel.SetFillColor(0)
        cmslabel.SetTextSize(0.041)
        cmslabel.Draw("plain")
        c.SetLogy(1)
        legend_shape.Draw("plain")
        c.Update()
        c.Print("ShapeUncertaintyN2.pdf")
        c.Print("ShapeUncertaintyN2.png")

    if isSaveOutput:
        store.saveAs(options.outputfile)

    if not options.isBatch:
        raw_input("Press Enter to continue...")
Пример #26
0
def limit():
    method = ''
    channel = "bb"
    if INCLUDEACC:
        particleP = "X"
    else:
        particleP = "Z'"
    particle = 'b#bar{b}'
    multF = ZPTOBB
    THEORY = ['A1', 'B3']
    if INCLUDEACC: THEORY.append('SSM')

    suffix = "_" + BTAGGING
    if ISMC: suffix += "_MC"
    if SY: suffix += "_comb"
    #if method=="cls": suffix="_CLs"
    if INCLUDEACC: suffix += "_acc"

    if SY:
        filename = "./combine/limits/" + BTAGGING + "/combined_run2/" + YEAR + "_M%d.txt"
    else:
        filename = "./combine/limits/" + BTAGGING + "/" + YEAR + "_M%d.txt"
    if CATEGORY != "":
        if SY:
            if CATEGORY == 'bb_bq':
                filename = filename.replace(
                    BTAGGING + "/combined_run2/",
                    BTAGGING + "/combined_run2/" + CATEGORY + "_combined_")
            else:
                filename = filename.replace(
                    BTAGGING + "/combined_run2/", BTAGGING +
                    "/single_category/combined_run2/" + CATEGORY + "_")
        else:
            filename = filename.replace(
                BTAGGING + "/",
                BTAGGING + "/single_category/" + CATEGORY + "_")
        suffix += "_" + CATEGORY
    if ISMC: filename = filename.replace(".txt", "_MC.txt")
    mass, val = fillValues(filename)

    #print "mass =",mass
    #print "val =", val

    Obs0s = TGraph()
    Exp0s = TGraph()
    Exp1s = TGraphAsymmErrors()
    Exp2s = TGraphAsymmErrors()
    Sign = TGraph()
    pVal = TGraph()
    Best = TGraphAsymmErrors()
    Theory = {}

    for i, m in enumerate(mass):
        if not m in val:
            print "Key Error:", m, "not in value map"
            continue

        if INCLUDEACC:
            acc_factor = ACCEPTANCE[m]
        else:
            acc_factor = 1.

        n = Exp0s.GetN()
        Obs0s.SetPoint(n, m, val[m][0] * multF * acc_factor)
        Exp0s.SetPoint(n, m, val[m][3] * multF * acc_factor)
        Exp1s.SetPoint(n, m, val[m][3] * multF * acc_factor)
        Exp1s.SetPointError(n, 0., 0.,
                            (val[m][3] - val[m][2]) * multF * acc_factor,
                            (val[m][4] - val[m][3]) * multF * acc_factor)
        Exp2s.SetPoint(n, m, val[m][3] * multF * acc_factor)
        Exp2s.SetPointError(n, 0., 0.,
                            (val[m][3] - val[m][1]) * multF * acc_factor,
                            (val[m][5] - val[m][3]) * multF * acc_factor)
        if len(val[m]) > 6: Sign.SetPoint(n, m, val[m][6])
        if len(val[m]) > 7: pVal.SetPoint(n, m, val[m][7])
        if len(val[m]) > 8: Best.SetPoint(n, m, val[m][8])
        if len(val[m]) > 10:
            Best.SetPointError(n, 0., 0., abs(val[m][9]), val[m][10])
        #print "m =", m, " --> Xsec*Br =", val[m][3]

    for t in THEORY:
        Theory[t] = TGraphAsymmErrors()
        Xs_dict = HVT[t]['Z']['XS'] if t != 'SSM' else SSM['Z']
        for m in sorted(Xs_dict.keys()):
            if INCLUDEACC and t != 'SSM':
                acc_factor = ACCEPTANCE[m]
            else:
                acc_factor = 1.
            if m < SIGNALS[0] or m > SIGNALS[-1]: continue
            #if m < mass[0] or m > mass[-1]: continue
            #if t!= 'SSM' and m>4500: continue ## I don't have the higher mass xs
            if m > 4500: continue
            XsZ, XsZ_Up, XsZ_Down = 0., 0., 0.
            if t != 'SSM':
                XsZ = 1000. * HVT[t]['Z']['XS'][m] * SSM["BrZ"][
                    m]  #assuming the same BR as the SSM Z' one
                XsZ_Up = XsZ * (1. + math.hypot(HVT[t]['Z']['QCD'][m][0] - 1.,
                                                HVT[t]['Z']['PDF'][m][0] - 1.))
                XsZ_Down = XsZ * (1. -
                                  math.hypot(1. - HVT[t]['Z']['QCD'][m][0],
                                             1. - HVT[t]['Z']['PDF'][m][0]))
            else:
                XsZ = 1000. * SSM['Z'][m] * SSM["BrZ"][m]
                XsZ_Up = XsZ * (1. +
                                math.hypot(HVT['A1']['Z']['QCD'][m][0] - 1.,
                                           HVT['A1']['Z']['PDF'][m][0] - 1.))
                XsZ_Down = XsZ * (1. -
                                  math.hypot(1. - HVT['A1']['Z']['QCD'][m][0],
                                             1. - HVT['A1']['Z']['PDF'][m][0]))

            n = Theory[t].GetN()
            Theory[t].SetPoint(n, m, XsZ * acc_factor)
            Theory[t].SetPointError(n, 0., 0., (XsZ - XsZ_Down) * acc_factor,
                                    (XsZ_Up - XsZ) * acc_factor)

            Theory[t].SetLineColor(theoryLineColor[t])
            Theory[t].SetFillColor(theoryFillColor[t])
            Theory[t].SetFillStyle(theoryFillStyle[t])
            Theory[t].SetLineWidth(2)
            #Theory[t].SetLineStyle(7)

    Exp2s.SetLineWidth(2)
    Exp2s.SetLineStyle(1)
    Obs0s.SetLineWidth(3)
    Obs0s.SetMarkerStyle(0)
    Obs0s.SetLineColor(1)
    Exp0s.SetLineStyle(2)
    Exp0s.SetLineWidth(3)
    Exp1s.SetFillColor(417)  #kGreen+1
    Exp1s.SetLineColor(417)  #kGreen+1
    Exp2s.SetFillColor(800)  #kOrange
    Exp2s.SetLineColor(800)  #kOrange
    Exp2s.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)")
    Exp2s.GetXaxis().SetTitleSize(Exp2s.GetXaxis().GetTitleSize() * 1.25)
    Exp2s.GetXaxis().SetNoExponent(True)
    Exp2s.GetXaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetTitle(
        "#sigma(" + particleP + ") #bf{#it{#Beta}}(" + particleP +
        " #rightarrow " + particle +
        "){} (fb)".format(" #times #Alpha" if INCLUDEACC else ""))
    Exp2s.GetYaxis().SetTitleOffset(1.5)
    Exp2s.GetYaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetMoreLogLabels()

    Sign.SetLineWidth(2)
    Sign.SetLineColor(629)
    Sign.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)")
    Sign.GetXaxis().SetTitleSize(Sign.GetXaxis().GetTitleSize() * 1.1)
    Sign.GetYaxis().SetTitle("Significance")

    pVal.SetLineWidth(2)
    pVal.SetLineColor(629)
    pVal.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)")
    pVal.GetXaxis().SetTitleSize(pVal.GetXaxis().GetTitleSize() * 1.1)
    pVal.GetYaxis().SetTitle("local p-Value")

    Best.SetLineWidth(2)
    Best.SetLineColor(629)
    Best.SetFillColor(629)
    Best.SetFillStyle(3003)
    Best.GetXaxis().SetTitle("m_{" + particleP + "} (GeV)")
    Best.GetXaxis().SetTitleSize(Best.GetXaxis().GetTitleSize() * 1.1)
    Best.GetYaxis().SetTitle("Best Fit (pb)")

    c1 = TCanvas("c1", "Exclusion Limits", 800, 600)
    c1.cd()
    #SetPad(c1.GetPad(0))
    c1.GetPad(0).SetTopMargin(0.06)
    c1.GetPad(0).SetRightMargin(0.05)
    c1.GetPad(0).SetLeftMargin(0.12)
    c1.GetPad(0).SetTicks(1, 1)
    #c1.GetPad(0).SetGridx()
    #c1.GetPad(0).SetGridy()
    c1.GetPad(0).SetLogy()
    Exp2s.Draw("A3")
    Exp1s.Draw("SAME, 3")
    for t in THEORY:
        Theory[t].Draw("SAME, L3")
        Theory[t].Draw("SAME, L3X0Y0")
    Exp0s.Draw("SAME, L")
    if not options.blind: Obs0s.Draw("SAME, L")
    #setHistStyle(Exp2s)
    Exp2s.GetXaxis().SetTitleSize(0.050)
    Exp2s.GetYaxis().SetTitleSize(0.050)
    Exp2s.GetXaxis().SetLabelSize(0.045)
    Exp2s.GetYaxis().SetLabelSize(0.045)
    Exp2s.GetXaxis().SetTitleOffset(0.90)
    Exp2s.GetYaxis().SetTitleOffset(1.25)
    Exp2s.GetYaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetNoExponent(True)
    if INCLUDEACC:
        Exp2s.GetYaxis().SetRangeUser(0.05, 5.e3)
    else:
        Exp2s.GetYaxis().SetRangeUser(0.1, 5.e3)
    #else: Exp2s.GetYaxis().SetRangeUser(0.1, 1.e2)
    #Exp2s.GetXaxis().SetRangeUser(mass[0], min(mass[-1], MAXIMUM[channel] if channel in MAXIMUM else 1.e6))
    Exp2s.GetXaxis().SetRangeUser(SIGNALS[0], SIGNALS[-1])
    #drawAnalysis(channel)
    drawAnalysis("")
    #drawRegion(channel, True)
    drawRegion("", True)
    #drawCMS(LUMI, "Simulation Preliminary") #Preliminary
    if CATEGORY == "":
        #drawCMS(LUMI, "Work in Progress", suppressCMS=True)
        drawCMS(LUMI, "Preliminary")
        #drawCMS(LUMI, "", suppressCMS=True)
    else:
        #drawCMS(LUMI, "Work in Progress, "+CAT_LABELS[CATEGORY], suppressCMS=True)
        drawCMS(LUMI, "Preliminary   " + CAT_LABELS[CATEGORY])
        #drawCMS(LUMI, CAT_LABELS[CATEGORY], suppressCMS=True)

    # legend
    top = 0.9
    nitems = 4 + len(THEORY)

    leg = TLegend(0.55, top - nitems * 0.3 / 5., 0.98, top)
    #leg = TLegend(0.45, top-nitems*0.3/5., 0.98, top)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    leg.SetHeader("95% CL upper limits")
    leg.AddEntry(Obs0s, "Observed", "l")
    leg.AddEntry(Exp0s, "Expected", "l")
    leg.AddEntry(Exp1s, "#pm 1 std. deviation", "f")
    leg.AddEntry(Exp2s, "#pm 2 std. deviation", "f")
    for t in THEORY:
        leg.AddEntry(Theory[t], theoryLabel[t], "fl")
    leg.Draw()
    latex = TLatex()
    latex.SetNDC()
    latex.SetTextSize(0.045)
    latex.SetTextFont(42)
    #latex.DrawLatex(0.66, leg.GetY1()-0.045, particleP+" #rightarrow "+particle+"h")

    leg2 = TLegend(0.12, 0.225 - 2 * 0.25 / 5., 0.65, 0.225)
    leg2.SetBorderSize(0)
    leg2.SetFillStyle(0)  #1001
    leg2.SetFillColor(0)
    c1.GetPad(0).RedrawAxis()

    leg2.Draw()
    if not options.blind: Obs0s.Draw("SAME, L")
    c1.GetPad(0).Update()

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")

    c1.Print("combine/plotsLimit/ExclusionLimits/" + YEAR + suffix + ".png")
    c1.Print("combine/plotsLimit/ExclusionLimits/" + YEAR + suffix + ".pdf")
    if 'ah' in channel or 'sl' in channel:
        c1.Print("combine/plotsLimit/ExclusionLimits/" + YEAR + suffix + ".C")
        c1.Print("combine/plotsLimit/ExclusionLimits/" + YEAR + suffix +
                 ".root")

    for t in THEORY:
        print "Model", t, ":",
        for m in range(mass[0], mass[-1], 1):
            if not (Theory[t].Eval(m) > Obs0s.Eval(m)) == (
                    Theory[t].Eval(m + 1) > Obs0s.Eval(m + 1)):
                print m, "(obs)",
            if not (Theory[t].Eval(m) > Exp0s.Eval(m)) == (
                    Theory[t].Eval(m + 1) > Exp0s.Eval(m + 1)):
                print m, "(exp)",
        print ""

    return  ##FIXME

    # ---------- Significance ----------
    c2 = TCanvas("c2", "Significance", 800, 600)
    c2.cd()
    c2.GetPad(0).SetTopMargin(0.06)
    c2.GetPad(0).SetRightMargin(0.05)
    c2.GetPad(0).SetTicks(1, 1)
    c2.GetPad(0).SetGridx()
    c2.GetPad(0).SetGridy()
    Sign.GetYaxis().SetRangeUser(0., 5.)
    Sign.Draw("AL3")
    drawCMS(LUMI, "Preliminary")
    #drawCMS(LUMI, "Work in Progress", suppressCMS=True)
    drawAnalysis(channel[1:3])
    c2.Print("combine/plotsLimit/Significance/" + YEAR + suffix + ".png")
    c2.Print("combine/plotsLimit/Significance/" + YEAR + suffix + ".pdf")
    #    c2.Print("plotsLimit/Significance/"+YEAR+suffix+".root")
    #    c2.Print("plotsLimit/Significance/"+YEAR+suffix+".C")

    # ---------- p-Value ----------
    c3 = TCanvas("c3", "p-Value", 800, 600)
    c3.cd()
    c3.GetPad(0).SetTopMargin(0.06)
    c3.GetPad(0).SetRightMargin(0.05)
    c3.GetPad(0).SetTicks(1, 1)
    c3.GetPad(0).SetGridx()
    c3.GetPad(0).SetGridy()
    c3.GetPad(0).SetLogy()
    pVal.Draw("AL3")
    pVal.GetYaxis().SetRangeUser(2.e-7, 0.5)

    ci = [
        1., 0.317310508, 0.045500264, 0.002699796, 0.00006334, 0.000000573303,
        0.000000001973
    ]
    line = TLine()
    line.SetLineColor(922)
    line.SetLineStyle(7)
    text = TLatex()
    text.SetTextColor(922)
    text.SetTextSize(0.025)
    text.SetTextAlign(12)
    for i in range(1, len(ci) - 1):
        line.DrawLine(pVal.GetXaxis().GetXmin(), ci[i] / 2,
                      pVal.GetXaxis().GetXmax(), ci[i] / 2)
        text.DrawLatex(pVal.GetXaxis().GetXmax() * 1.01, ci[i] / 2,
                       "%d #sigma" % i)

    drawCMS(LUMI, "Preliminary")
    #drawCMS(LUMI, "Work in Progress", suppressCMS=True)
    drawAnalysis(channel[1:3])
    c3.Print("combine/plotsLimit/pValue/" + YEAR + suffix + ".png")
    c3.Print("combine/plotsLimit/pValue/" + YEAR + suffix + ".pdf")
    #    c3.Print("plotsLimit/pValue/"+YEAR+suffix+".root")
    #    c3.Print("plotsLimit/pValue/"+YEAR+suffix+".C")

    # --------- Best Fit ----------
    c4 = TCanvas("c4", "Best Fit", 800, 600)
    c4.cd()
    c4.GetPad(0).SetTopMargin(0.06)
    c4.GetPad(0).SetRightMargin(0.05)
    c4.GetPad(0).SetTicks(1, 1)
    c4.GetPad(0).SetGridx()
    c4.GetPad(0).SetGridy()
    Best.Draw("AL3")
    drawCMS(LUMI, "Preliminary")
    #drawCMS(LUMI, "Work in Progress", suppressCMS=True)
    drawAnalysis(channel[1:3])
    c4.Print("combine/plotsLimit/BestFit/" + YEAR + suffix + ".png")
    c4.Print("combine/plotsLimit/BestFit/" + YEAR + suffix + ".pdf")
    #    c4.Print("plotsLimit/BestFit/"+YEAR+suffix+".root")
    #    c4.Print("plotsLimit/BestFit/"+YEAR+suffix+".C")

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")

    if 'ah' in channel:
        outFile = TFile("bands.root", "RECREATE")
        outFile.cd()
        pVal.Write("graph")
        Best.Write("best")
        outFile.Close()
Пример #27
0
def plotPValues(labels, masses0, **kwargs):
    print color("plotPValues()", color="magenta", prepend=">>>\n>>> ")

    # SIGNAL strength & mass
    S_exps = kwargs.get('S_exps', 1)
    if not isinstance(S_exps, list): S_exps = [S_exps]
    bins = kwargs.get('bins', [])
    ymin = 0.00005
    #if S_exp > 80: ymin = 0.000000000000000000000001

    # LOOP over LABELS
    for label in labels:
        print color("plotPValues - %s" % (label),
                    color="grey",
                    prepend="\n>>> ")

        masses = array('d', [])
        zeros = array('d', [])
        limitObs = array('d', [])
        limitExps = []
        for S_exp in S_exps:
            limitExps.append(array('d', []))

        up2s = []
        for i, mass in enumerate(masses0):
            bin = -1
            if bins: bin = bins[i]
            for S_exp, limitExp in zip(S_exps, limitExps):
                filename = getOutputFilename(label,
                                             mass,
                                             method="ProfileLikelihood",
                                             S_exp=S_exp,
                                             bin=bin,
                                             extralabel=".SignifExp")
                limitExp.append(getLimits(filename, brazilian=False))
            filename = getOutputFilename(label,
                                         mass,
                                         method="ProfileLikelihood",
                                         S_exp=S_exp,
                                         bin=bin,
                                         extralabel=".SignifObs")
            limitObs.append(getLimits(filename, brazilian=False))
            masses.append(mass)
            zeros.append(0.0)

        v_masses = TVectorD(len(masses), masses)
        v_zeros = TVectorD(len(zeros), zeros)
        v_limitObs = TVectorD(len(limitObs), limitObs)
        v_limitExps = []
        for limitExp in limitExps:
            v_limitExps.append(TVectorD(len(limitExp), limitExp))

        W = 800
        H = 600
        T = 0.08 * H
        B = 0.12 * H
        L = 0.12 * W
        R = 0.04 * W
        canvas = TCanvas("canvas", "canvas", 100, 100, W, H)
        canvas.SetFillColor(0)
        canvas.SetBorderMode(0)
        canvas.SetFrameFillStyle(0)
        canvas.SetFrameBorderMode(0)
        canvas.SetLeftMargin(L / W)
        canvas.SetRightMargin(R / W)
        canvas.SetTopMargin(T / H)
        canvas.SetBottomMargin(B / H)
        canvas.SetTickx(0)
        canvas.SetTicky(0)
        canvas.SetGrid()
        canvas.SetLogy()  # log
        canvas.cd()

        frame = canvas.DrawFrame(1.4, 0.001, 4.1, 10)
        frame.GetYaxis().CenterTitle()
        frame.GetYaxis().SetTitleSize(0.05)
        frame.GetXaxis().SetTitleSize(0.05)
        frame.GetXaxis().SetLabelSize(0.04)
        frame.GetYaxis().SetLabelSize(0.04)
        frame.GetYaxis().SetTitleOffset(1.14)
        frame.GetXaxis().SetNdivisions(508)
        frame.GetYaxis().CenterTitle(False)
        frame.GetYaxis().SetTitle("local p-value")
        #frame.GetYaxis().SetTitle("95% upper limit on #sigma / #sigma_{SM}")
        frame.GetXaxis().SetTitle("X#rightarrow#tau#tau mass [GeV]")
        frame.SetMinimum(ymin)
        frame.SetMaximum(1.5)
        frame.GetXaxis().SetLimits(min(masses), max(masses))

        latex = TLatex()
        latex.SetTextSize(0.4 * canvas.GetTopMargin())
        latex.SetTextColor(2)
        f1 = TF1("f1", "0.15866", min(masses), max(masses))
        f1.SetLineColor(2)
        f1.SetLineWidth(2)
        f1.Draw("lsame")
        latex.DrawLatex(min(masses) + 1, 0.15866 * 1.1, "1#sigma")
        f2 = TF1("f2", "0.02275", min(masses), max(masses))
        f2.SetLineColor(2)
        f2.SetLineWidth(2)
        f2.Draw("lsame")
        latex.DrawLatex(min(masses) + 1, 0.02275 * 1.1, "2#sigma")
        f3 = TF1("f3", "0.0013499", min(masses), max(masses))
        f3.SetLineColor(2)
        f3.SetLineWidth(2)
        f3.Draw("lsame")
        latex.DrawLatex(min(masses) + 1, 0.0013499 * 1.1, "3#sigma")

        graph_limitExps = []
        colors = [4, 2, 3, 6, 7, 8]
        for i, v_limitExp in enumerate(v_limitExps):
            graph_limitExps.append(
                TGraphAsymmErrors(v_masses, v_limitExp, v_zeros, v_zeros,
                                  v_zeros, v_zeros))
            graph_limitExps[-1].SetLineColor(colors[i])
            graph_limitExps[-1].SetLineWidth(2)
            graph_limitExps[-1].SetLineStyle(2)
            graph_limitExps[-1].Draw("Lsame")

        graph_limitObs = TGraphAsymmErrors(v_masses, v_limitObs, v_zeros,
                                           v_zeros, v_zeros, v_zeros)
        graph_limitObs.SetLineColor(1)
        graph_limitObs.SetLineWidth(2)
        graph_limitObs.Draw("Csame")

        CMS_lumi.CMS_lumi(canvas, 13, 0)
        ROOT.gPad.SetTicks(1, 1)
        frame.Draw('sameaxis')

        x1 = 0.62
        x2 = x1 + 0.24
        y1 = 0.15
        y2 = y1 + 0.20
        legend = TLegend(x1, y1, x2, y2)
        legend.SetFillStyle(0)
        legend.SetBorderSize(0)
        legend.SetTextSize(0.041)
        legend.SetTextFont(42)
        legend.SetHeader("%s" % (label_dict[label]))
        legend.AddEntry(graph_limitObs, "observed", 'L')  #p-value
        for S_exp, graph_limitExp in zip(S_exps, graph_limitExps):
            if len(S_exps) > 1:
                legend.AddEntry(graph_limitExp, "expected (S%s)" % (S_exp),
                                'L')
            else:
                legend.AddEntry(graph_limitExp, "expected (S%s)" % (S_exp),
                                'L')
        legend.Draw("same")
        gPad.RedrawAxis()

        print " "
        canvas.SaveAs("%s/p-value-local-%s-S%s.png" % (PLOT_DIR, label, S_exp))
        canvas.SaveAs("%s/p-value-local-%s-S%s.pdf" % (PLOT_DIR, label, S_exp))
        canvas.Close()
Пример #28
0
def limit2HDM():
    global signals
    signals = range(800, 2000 + 1, 50)
    multF = HTOBB
    THEORY = ['T1', 'T2']

    mass, val = fillValues("./combine/AZh/AZh_M%d.txt")
    Obs0s = TGraph()
    Exp0s = TGraph()
    Exp1s = TGraphAsymmErrors()
    Exp2s = TGraphAsymmErrors()

    massB, valB = fillValues("./combine/BBAZh/BBAZh_M%d.txt")
    Obs0sB = TGraph()
    Exp0sB = TGraph()
    Exp1sB = TGraphAsymmErrors()
    Exp2sB = TGraphAsymmErrors()

    for i, m in enumerate(mass):
        if not m in val:
            print "Key Error:", m, "not in value map"
            continue

        n = Exp0s.GetN()
        Obs0s.SetPoint(n, m, val[m][0] * multF)
        Exp0s.SetPoint(n, m, val[m][3] * multF)
        Exp1s.SetPoint(n, m, val[m][3] * multF)
        Exp1s.SetPointError(n, 0., 0., val[m][3] * multF - val[m][2] * multF,
                            val[m][4] * multF - val[m][3] * multF)
        Exp2s.SetPoint(n, m, val[m][3] * multF)
        Exp2s.SetPointError(n, 0., 0., val[m][3] * multF - val[m][1] * multF,
                            val[m][5] * multF - val[m][3] * multF)

        Obs0sB.SetPoint(n, m, valB[m][0] * multF)
        Exp0sB.SetPoint(n, m, valB[m][3] * multF)
        Exp1sB.SetPoint(n, m, valB[m][3] * multF)
        Exp1sB.SetPointError(n, 0., 0.,
                             valB[m][3] * multF - valB[m][2] * multF,
                             valB[m][4] * multF - valB[m][3] * multF)
        Exp2sB.SetPoint(n, m, valB[m][3] * multF)
        Exp2sB.SetPointError(n, 0., 0.,
                             valB[m][3] * multF - valB[m][1] * multF,
                             valB[m][5] * multF - valB[m][3] * multF)

    col = 629
    Exp2s.SetLineWidth(2)
    Exp2s.SetLineStyle(1)
    Obs0s.SetLineWidth(3)
    Obs0s.SetMarkerStyle(0)
    Obs0s.SetLineColor(1)
    Exp0s.SetLineStyle(2)
    Exp0s.SetLineWidth(3)
    Exp0s.SetLineColor(1)
    #    Exp1s.SetFillColorAlpha(col, 0.4) #kGreen+1
    #    Exp1s.SetLineColorAlpha(col, 0.4)
    #    Exp2s.SetFillColorAlpha(col, 0.2) #kOrange
    #    Exp2s.SetLineColorAlpha(col, 0.2)
    Exp1s.SetFillColor(417)
    Exp1s.SetLineColor(417)
    Exp2s.SetFillColor(800)
    Exp2s.SetLineColor(800)

    colB = 922
    Exp2sB.SetLineWidth(2)
    Obs0sB.SetLineStyle(9)
    Obs0sB.SetLineWidth(3)
    Obs0sB.SetMarkerStyle(0)
    Obs0sB.SetLineColor(colB)
    Exp0sB.SetLineStyle(8)
    Exp0sB.SetLineWidth(3)
    Exp0sB.SetLineColor(colB)
    Exp1sB.SetFillColorAlpha(colB, 0.4)  #kGreen+1
    Exp1sB.SetLineColorAlpha(colB, 0.4)
    Exp2sB.SetFillColorAlpha(colB, 0.2)  #kOrange
    Exp2sB.SetLineColorAlpha(colB, 0.2)

    Exp2s.GetXaxis().SetTitle("m_{A} (GeV)")
    Exp2s.GetXaxis().SetTitleSize(Exp2s.GetXaxis().GetTitleSize() * 1.25)
    Exp2s.GetXaxis().SetNoExponent(True)
    Exp2s.GetXaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetTitle(
        "#sigma(A) #bf{#it{#Beta}}(A #rightarrow Zh) #bf{#it{#Beta}}(h #rightarrow bb) (fb)"
    )
    Exp2s.GetYaxis().SetTitleOffset(1.5)
    Exp2s.GetYaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetMoreLogLabels()

    Theory = {}
    #for t in THEORY:
    #    Theory[t] = TGraphAsymmErrors()
    #    for m in sorted(THDM[t]['ggA'].keys()):
    #        if m < mass[0] or m > mass[-1]: continue
    #        Xs, Xs_Up, Xs_Down = 0., 0., 0.
    #        Xs = THDM[t]['ggA'][m]
    #        Xs_Up = Xs*(1.+math.sqrt((THDM['PDF']['ggA'][m][0]-1.)**2 + (THDM['QCD']['ggA'][m][0]-1.)**2))
    #        Xs_Down = Xs*(1.-math.sqrt((1.-THDM['PDF']['ggA'][m][1])**2 + (1.-THDM['QCD']['ggA'][m][1])**2))
    #        n = Theory[t].GetN()
    #        Theory[t].SetPoint(n, m, Xs)
    #        Theory[t].SetPointError(n, 0., 0., (Xs-Xs_Down), (Xs_Up-Xs))

    #    Theory[t].SetLineColor(theoryLineColor[t])
    #    Theory[t].SetFillColor(theoryFillColor[t])
    #    Theory[t].SetFillStyle(theoryFillStyle[t])
    #    Theory[t].SetLineWidth(2)
    #        #Theory[t].SetLineStyle(7)

    c1 = TCanvas("c1", "Exclusion Limits", 800, 600)
    c1.cd()
    #SetPad(c1.GetPad(0))
    c1.GetPad(0).SetTopMargin(0.06)
    c1.GetPad(0).SetRightMargin(0.05)
    c1.GetPad(0).SetLeftMargin(0.12)
    c1.GetPad(0).SetTicks(1, 1)
    c1.GetPad(0).SetLogy()
    Exp2s.Draw("A3")
    Exp1s.Draw("SAME, 3")
    Exp0s.Draw("SAME, L")
    #    Exp2sB.Draw("SAME, 3")
    #    Exp1sB.Draw("SAME, 3")
    Exp0sB.Draw("SAME, L")
    if not options.blind:
        Obs0s.Draw("SAME, L")
        Obs0sB.Draw("SAME, L")
    for t in THEORY:
        Theory[t].Draw("SAME, L3")
        Theory[t].Draw("SAME, L3X0Y0")
    #setHistStyle(Exp2s)


#    Exp2s.GetXaxis().SetTitleSize(0.045)
#    Exp2s.GetYaxis().SetTitleSize(0.04)
#    Exp2s.GetXaxis().SetLabelSize(0.04)
#    Exp2s.GetYaxis().SetLabelSize(0.04)
#    Exp2s.GetXaxis().SetTitleOffset(1)
#    Exp2s.GetYaxis().SetTitleOffset(1.25)
    Exp2s.GetXaxis().SetTitleSize(0.050)
    Exp2s.GetYaxis().SetTitleSize(0.050)
    Exp2s.GetXaxis().SetLabelSize(0.045)
    Exp2s.GetYaxis().SetLabelSize(0.045)
    Exp2s.GetXaxis().SetTitleOffset(0.90)
    Exp2s.GetYaxis().SetTitleOffset(1.25)
    Exp2s.GetYaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetRangeUser(0.5, 1.e3)
    Exp2s.GetXaxis().SetRangeUser(mass[0], mass[-1])
    drawAnalysis('AZh')
    drawRegion('AZHsl', True)
    drawCMS(LUMI, "")  #Preliminary
    #drawCMS(LUMI, "Work in Progress", suppressCMS=True)

    # legend
    leg = TLegend(0.6, 0.90, 0.99, 0.90)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    leg.SetHeader("95% CL upper limits")
    leg.AddEntry(None, "gg #rightarrow A #rightarrow Zh",
                 "")  #"95% CL upper limits"
    leg.AddEntry(Obs0s, "Observed", "l")
    leg.AddEntry(Exp0s, "Expected", "l")
    leg.AddEntry(Exp1s, "#pm 1 std. deviation", "f")
    leg.AddEntry(Exp2s, "#pm 2 std. deviation", "f")
    leg.AddEntry(None, "", "")
    leg.AddEntry(None, "bbA #rightarrow Zh", "")
    leg.AddEntry(Obs0sB, "Observed", "l")
    leg.AddEntry(Exp0sB, "Expected", "l")
    leg.SetY1(leg.GetY2() - leg.GetNRows() * 0.045)
    leg.Draw()

    #    latex = TLatex()
    #    latex.SetNDC()
    #    latex.SetTextSize(0.040)
    #    latex.SetTextFont(42)
    #    latex.DrawLatex(0.65, leg.GetY1()-0.045, "cos(#beta-#alpha)=0.25, tan(#beta)=1")

    #    legB = TLegend(0.12, 0.4-4*0.3/5., 0.65, 0.4)
    legB = TLegend(0.15, 0.27, 0.68, 0.27)
    legB.SetBorderSize(0)
    legB.SetFillStyle(0)  #1001
    legB.SetFillColor(0)
    for t in THEORY:
        legB.AddEntry(Theory[t], theoryLabel[t], "fl")
    legB.AddEntry(None, "cos(#beta-#alpha)=0.25, tan(#beta)=1", "")
    legB.SetY1(legB.GetY2() - legB.GetNRows() * 0.045)
    legB.Draw()

    c1.GetPad(0).RedrawAxis()
    leg.Draw()

    c1.Update()

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")

    c1.Print("plotsLimit/Exclusion/THDM.png")
    c1.Print("plotsLimit/Exclusion/THDM.pdf")
Пример #29
0
def makeLimitPlot(output,
                  obs,
                  exp,
                  chan,
                  printStats=False,
                  obs2="",
                  ratioLabel=""):
    fileForHEPData = TFile("plots/" + output + "_forHEPData.root", "RECREATE")
    fileObs = open(obs, 'r')
    fileExp = open(exp, 'r')

    observedx = []
    observedy = []
    obsLimits = {}
    for entry in fileObs:
        massPoint = float(entry.split()[0])
        limitEntry = float(entry.split()[1])
        if massPoint not in obsLimits: obsLimits[massPoint] = []
        obsLimits[massPoint].append(limitEntry)
    if printStats: print "len obsLimits:", len(obsLimits)
    for massPoint in sorted(obsLimits):
        observedx.append(massPoint)
        observedy.append(numpy.mean(obsLimits[massPoint]))
        if (numpy.std(obsLimits[massPoint]) / numpy.mean(obsLimits[massPoint])
                > 0.05):
            print massPoint, " mean: ", numpy.mean(
                obsLimits[massPoint]), " std dev: ", numpy.std(
                    obsLimits[massPoint]), " from: ", obsLimits[massPoint]

    if not obs2 == "":
        fileObs2 = open(obs2, 'r')

        observedx2 = []
        observedy2 = []
        obsLimits2 = {}
        for entry in fileObs2:
            massPoint = float(entry.split()[0])
            limitEntry = float(entry.split()[1])
            if massPoint not in obsLimits2: obsLimits2[massPoint] = []
            obsLimits2[massPoint].append(limitEntry)
        if printStats: print "len obsLimits:", len(obsLimits2)
        for massPoint in sorted(obsLimits2):
            observedx2.append(massPoint)
            observedy2.append(numpy.mean(obsLimits2[massPoint]))
            if (numpy.std(obsLimits2[massPoint]) /
                    numpy.mean(obsLimits2[massPoint]) > 0.05):
                print massPoint, " mean: ", numpy.mean(
                    obsLimits2[massPoint]), " std dev: ", numpy.std(
                        obsLimits2[massPoint]
                    ), " from: ", obsLimits2[massPoint]

    limits = {}
    expectedx = []
    expectedy = []
    expected1SigLow = []
    expected1SigHigh = []
    expected2SigLow = []
    expected2SigHigh = []
    for entry in fileExp:
        massPoint = float(entry.split()[0])
        limitEntry = float(entry.split()[1])
        if massPoint not in limits: limits[massPoint] = []
        limits[massPoint].append(limitEntry)

    if printStats: print "len limits:", len(limits)
    for massPoint in sorted(limits):
        limits[massPoint].sort()
        numLimits = len(limits[massPoint])
        nrExpts = len(limits[massPoint])
        medianNr = int(nrExpts * 0.5)
        #get indexes:
        upper1Sig = int(nrExpts * (1 - (1 - 0.68) * 0.5))
        lower1Sig = int(nrExpts * (1 - 0.68) * 0.5)
        upper2Sig = int(nrExpts * (1 - (1 - 0.95) * 0.5))
        lower2Sig = int(nrExpts * (1 - 0.95) * 0.5)
        if printStats:
            print massPoint, ":", limits[massPoint][lower2Sig], limits[
                massPoint][lower1Sig], limits[massPoint][medianNr], limits[
                    massPoint][upper1Sig], limits[massPoint][upper2Sig]
        #fill lists:
        expectedx.append(massPoint)
        print massPoint, limits[massPoint][medianNr]
        expectedy.append(limits[massPoint][medianNr])
        expected1SigLow.append(limits[massPoint][lower1Sig])
        expected1SigHigh.append(limits[massPoint][upper1Sig])
        expected2SigLow.append(limits[massPoint][lower2Sig])
        expected2SigHigh.append(limits[massPoint][upper2Sig])

    expX = numpy.array(expectedx)
    expY = numpy.array(expectedy)

    values2 = []
    xPointsForValues2 = []
    values = []
    xPointsForValues = []
    xPointsForErrors = []
    if printStats: print "length of expectedx: ", len(expectedx)
    if printStats: print "length of expected1SigLow: ", len(expected1SigLow)
    if printStats: print "length of expected1SigHigh: ", len(expected1SigHigh)

    #Here is some Voodoo via Sam:
    for x in range(0, len(expectedx)):
        values2.append(expected2SigLow[x])
        xPointsForValues2.append(expectedx[x])
        xPointsForErrors.append(0)
    for x in range(len(expectedx) - 1, 0 - 1, -1):
        values2.append(expected2SigHigh[x])
        xPointsForValues2.append(expectedx[x])
    if printStats: print "length of values2: ", len(values2)

    for x in range(0, len(expectedx)):
        values.append(expected1SigLow[x])
        xPointsForValues.append(expectedx[x])
    for x in range(len(expectedx) - 1, 0 - 1, -1):
        values.append(expected1SigHigh[x])
        xPointsForValues.append(expectedx[x])
    if printStats: print "length of values: ", len(values)

    exp2Sig = numpy.array(values2)
    xPoints2 = numpy.array(xPointsForValues2)
    exp1Sig = numpy.array(values)
    xPoints = numpy.array(xPointsForValues)
    xPointsErrors = numpy.array(xPointsForErrors)
    if printStats: print "xPoints2: ", xPoints2
    if printStats: print "exp2Sig: ", exp2Sig
    if printStats: print "xPoints: ", xPoints
    if printStats: print "exp1Sig: ", exp1Sig

    GraphErr2SigForHEPData = TGraphAsymmErrors(len(expX), expX, expY,
                                               numpy.array(xPointsErrors),
                                               numpy.array(xPointsErrors),
                                               numpy.array(expected2SigLow),
                                               numpy.array(expected2SigHigh))
    GraphErr1SigForHEPData = TGraphAsymmErrors(len(expX), expX, expY,
                                               numpy.array(xPointsErrors),
                                               numpy.array(xPointsErrors),
                                               numpy.array(expected1SigLow),
                                               numpy.array(expected1SigHigh))

    GraphErr2Sig = TGraphAsymmErrors(len(xPoints), xPoints2, exp2Sig)
    GraphErr2Sig.SetFillColor(ROOT.kOrange)
    GraphErr1Sig = TGraphAsymmErrors(len(xPoints), xPoints, exp1Sig)
    GraphErr1Sig.SetFillColor(ROOT.kGreen + 1)
    #cCL=TCanvas("cCL", "cCL",0,0,567,384)
    cCL = TCanvas("cCL", "cCL", 0, 0, 600, 450)
    gStyle.SetOptStat(0)
    gStyle.SetPadRightMargin(0.063)
    gStyle.SetPadLeftMargin(0.14)
    gStyle.SetPadBottomMargin(0.12)

    if not obs2 == "":
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1)
        ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3)
        plotPad.Draw()
        ratioPad.Draw()
        plotPad.cd()
    else:
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
        plotPad.Draw()
        plotPad.cd()

    expX = numpy.array(expectedx)
    expY = numpy.array(expectedy)
    GraphExp = TGraph(len(expX), expX, expY)
    GraphExp.SetLineWidth(3)
    GraphExp.SetLineStyle(2)
    GraphExp.SetLineColor(ROOT.kBlue)

    obsX = numpy.array(observedx)
    obsY = numpy.array(observedy)
    if printStats: print "obsX: ", obsX
    if printStats: print "obsY: ", obsY

    if SMOOTH:
        smooth_obs = TGraphSmooth("normal")
        GraphObs_nonSmooth = TGraph(len(obsX), obsX, obsY)
        GraphObs = smooth_obs.SmoothSuper(GraphObs_nonSmooth, "linear", 0,
                                          0.005)
    else:
        GraphObs = TGraph(len(obsX), obsX, obsY)

    GraphObs.SetLineWidth(3)
    if not obs2 == "":

        ratio = []
        ratiox = []
        for index, val in enumerate(observedy):
            mass = observedx[index]
            foundIndex = -1
            for index2, mass2 in enumerate(observedx2):
                if mass == mass2:
                    foundIndex = index2

            if foundIndex > 0:
                ratio.append(observedy2[foundIndex] / val)
                ratiox.append(mass)
        ratioA = numpy.array(ratio)
        ratioX = numpy.array(ratiox)
        obsX2 = numpy.array(observedx2)
        obsY2 = numpy.array(observedy2)
        ratioGraph = TGraph(len(ratioX), ratioX, ratioA)
        if printStats: print "obsX2: ", obsX2
        if printStats: print "obsY2: ", obsY2

        if SMOOTH:
            smooth_obs2 = TGraphSmooth("normal")
            GraphObs2_nonSmooth = TGraph(len(obsX2), obsX2, obsY2)
            GraphObs2 = smooth_obs2.SmoothSuper(GraphObs2_nonSmooth, "linear",
                                                0, 0.005)
        else:
            GraphObs2 = TGraph(len(obsX2), obsX2, obsY2)

        GraphObs2.SetLineWidth(3)

    if SPIN2:
        signals = ["RS_kMpl01", "RS_kMpl005", "RS_kMpl001"]
    elif GUT:
        signals = ["ssm", "psi", "kai", "eta", "I", "S", "N"]
    else:
        signals = ["ssm", "psi"]

    xSecCurves = []
    for signal in signals:
        xSecCurves.append(getXSecCurve(signal, kFacs[signal]))
        #xSecCurves.append(getXSecCurve(signal,kFacs[signal],massDependent=True))

    #Draw the graphs:
    plotPad.SetLogy()
    DummyGraph = TH1F("DummyGraph", "", 100, 200, 5500)
    DummyGraph.GetXaxis().SetTitle("M [GeV]")
    if SPIN2:
        DummyGraph.GetYaxis().SetTitle(
            "[#sigma#upoint#font[12]{B}] G_{KK} / [#sigma#upoint#font[12]{B}] Z"
        )
    else:
        DummyGraph.GetYaxis().SetTitle(
            "[#sigma#upoint#font[12]{B}] Z' / [#sigma#upoint#font[12]{B}] Z")

#	if SPIN2:
#	    	if chan=="mumu":
#       	 		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrow#mu^{+}#mu^{-}+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu^{+}#mu^{-}+X)")
#    		elif chan=="elel":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)")
#    		elif chan=="elmu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)")
#	else:
#    		if chan=="mumu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrow#mu^{+}#mu^{-}+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu^{+}#mu^{-}+X)")
#    		elif chan=="elel":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)")
#    		elif chan=="elmu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)")

    gStyle.SetOptStat(0)
    DummyGraph.GetXaxis().SetRangeUser(200, 5500)

    DummyGraph.SetMinimum(1e-8)
    DummyGraph.SetMaximum(1e-4)
    DummyGraph.GetXaxis().SetLabelSize(0.055)
    DummyGraph.GetXaxis().SetTitleSize(0.055)
    DummyGraph.GetXaxis().SetTitleOffset(1.05)
    DummyGraph.GetYaxis().SetLabelSize(0.055)
    DummyGraph.GetYaxis().SetTitleSize(0.055)
    DummyGraph.GetYaxis().SetTitleOffset(1.3)
    DummyGraph.Draw()
    if (FULL):
        GraphErr2Sig.Draw("F")
        GraphErr1Sig.Draw("F")
        GraphExp.Draw("lpsame")
    else:
        if obs2 == "":
            GraphExp.Draw("lp")
    if not EXPONLY:
        GraphObs.Draw("plsame")
    if not obs2 == "":
        GraphObs2.SetLineColor(ROOT.kRed)
        GraphObs2.SetLineStyle(ROOT.kDashed)
        GraphObs2.Draw("plsame")
    for curve in xSecCurves:
        curve.Draw("lsame")

    plCMS = TPaveLabel(.16, .81, .27, .88, "CMS", "NBNDC")
    #plCMS.SetTextSize(0.8)
    plCMS.SetTextAlign(12)
    plCMS.SetTextFont(62)
    plCMS.SetFillColor(0)
    plCMS.SetFillStyle(0)
    plCMS.SetBorderSize(0)

    plCMS.Draw()

    plPrelim = TPaveLabel(.16, .76, .27, .82, "Preliminary", "NBNDC")
    plPrelim.SetTextSize(0.6)
    plPrelim.SetTextAlign(12)
    plPrelim.SetTextFont(52)
    plPrelim.SetFillColor(0)
    plPrelim.SetFillStyle(0)
    plPrelim.SetBorderSize(0)
    if "2017" in output or "Combination" in output:
        plPrelim.Draw()

    cCL.SetTickx(1)
    cCL.SetTicky(1)
    cCL.RedrawAxis()
    cCL.Update()

    #leg=TLegend(0.65,0.65,0.87,0.87,"","brNDC")
    #leg=TLegend(0.540517,0.623051,0.834885,0.878644,"","brNDC")   Default
    leg = TLegend(0.5, 0.58, 0.834885, 0.878644, "", "brNDC")
    if SPIN2:
        leg = TLegend(0.5, 0.58, 0.834885, 0.878644, "", "brNDC")
#    	leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC")
    leg.SetTextSize(0.0425)
    if not obs2 == "":
        if ratioLabel == "":
            ratioLabel = "Variant/Default"
        ratioLabels = ratioLabel.split("/")
        print ratioLabels
        leg.AddEntry(GraphObs, "%s Obs. 95%% CL limit" % ratioLabels[1], "l")
        leg.AddEntry(GraphObs2, "%s Obs. 95%% CL limit" % ratioLabels[0], "l")

    else:
        if not EXPONLY:
            leg.AddEntry(GraphObs, "Obs. 95% CL limit", "l")
        leg.AddEntry(GraphExp, "Exp. 95% CL limit, median", "l")
        if (FULL):
            leg.AddEntry(GraphErr1Sig, "Exp. (68%)", "f")
            leg.AddEntry(GraphErr2Sig, "Exp. (95%)", "f")

    leg1 = TLegend(0.7, 0.4, 0.9, 0.55, "", "brNDC")
    leg1.SetTextSize(0.05)
    if GUT:
        leg1 = TLegend(0.6, 0.35, 0.75, 0.623051, "", "brNDC")
    if SPIN2:
        leg1 = TLegend(0.7, 0.35, 0.9, 0.58, "G_{KK} (LO x 1.6)", "brNDC")
        leg1.SetTextSize(0.045)
    for index, signal in enumerate(signals):
        xSecCurves[index].SetName(labels[signal])
        xSecCurves[index].Write(labels[signal])
        leg1.AddEntry(xSecCurves[index], labels[signal], "l")
    leg1.SetBorderSize(0)

    leg.SetLineWidth(0)
    leg.SetLineStyle(0)
    leg.SetFillStyle(0)
    leg.SetLineColor(0)
    leg.Draw("hist")

    leg1.SetLineWidth(0)
    leg1.SetLineStyle(0)
    leg1.SetFillStyle(0)
    leg1.SetLineColor(0)
    leg1.Draw("hist")
    if "Moriond" in output:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .885, .9, .99,
                                "36.3 fb^{-1} (13 TeV, #mu^{+}#mu^{-})",
                                "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .885, .9, .99,
                                "35.9 fb^{-1} (13 TeV, ee)", "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .27, .885, .9, .99,
                "35.9 fb^{-1} (13 TeV, ee) + 36.3 fb^{-1} (13 TeV, #mu^{+}#mu^{-})",
                "NBNDC")

    elif "2017" in output or "Combination" in output:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .885, .9, .99,
                                "36.3 fb^{-1} (13 TeV, #mu^{+}#mu^{-})",
                                "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .885, .9, .99,
                                "41.4 fb^{-1} (13 TeV, ee)", "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .27, .885, .9, .99,
                "77.3 fb^{-1} (13 TeV, ee) + 36.3 fb^{-1} (13 TeV, #mu^{+}#mu^{-})",
                "NBNDC")
    else:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "13.0 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99, "2.7 fb^{-1} (13 TeV, ee)",
                                "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "12.4 fb^{-1} (13 TeV, ee) + 13.0 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")

    plLumi.SetTextSize(0.5)
    plLumi.SetTextFont(42)
    plLumi.SetFillColor(0)
    plLumi.SetBorderSize(0)
    plLumi.Draw()

    plotPad.SetTicks(1, 1)
    plotPad.RedrawAxis()

    if not obs2 == "":

        ratioPad.cd()

        line = ROOT.TLine(200, 1, 5500, 1)
        line.SetLineStyle(ROOT.kDashed)

        ROOT.gStyle.SetTitleSize(0.12, "Y")
        ROOT.gStyle.SetTitleYOffset(0.35)
        ROOT.gStyle.SetNdivisions(000, "Y")
        ROOT.gStyle.SetNdivisions(408, "Y")
        ratioPad.DrawFrame(200, 0.8, 5500, 1.2, "; ; %s" % ratioLabel)

        line.Draw("same")

        ratioGraph.Draw("sameP")

    GraphErr2SigForHEPData.SetName("graph2Sig")
    GraphErr2SigForHEPData.Write("graph2Sig")

    GraphErr1SigForHEPData.SetName("graph1Sig")
    GraphErr1SigForHEPData.Write("graph1Sig")

    GraphExp.SetName("graphExp")
    GraphExp.Write("graphExp")

    GraphObs.SetName("graphObs")
    GraphObs.Write("graphObs")

    fileForHEPData.Write()
    fileForHEPData.Close()
    cCL.Update()
    printPlots(cCL, output)
Пример #30
0
def plotMCEffs(input_list, plot_name='fakerate.pdf'):
    '''input_list expects tuples with structure:
       (hist tight, hist loose, legend line, colour)
    '''

    graphs = []

    for (hist_tight, hist_loose, legend, colour, style) in input_list:
        g = TGraphAsymmErrors(hist_tight)
        g.Divide(hist_tight, hist_loose)
        g.GetYaxis().SetTitle('Misidentification rate')
        g.GetXaxis().SetTitle(hist_tight.GetXaxis().GetTitle())
        g.GetYaxis().SetTitleOffset(1.2)
        g.GetYaxis().SetTitleOffset(1.3)

        g.SetLineColor(colour)
        g.SetLineStyle(style)
        g.SetMarkerColor(colour)
        g.SetMarkerStyle(19+style)

        g.legend = legend

        graphs.append(g)


    ratio_graphs = []

    base_graph = graphs[0]
    for graph in graphs[1:]:

        g_vals = base_graph.GetY()
        g_data_vals = graph.GetY()

        g_ratio = graph.Clone('ratio')

        for i in xrange(graph.GetN()):
            ratio = g_data_vals[i]/g_vals[i] if g_vals[i] else 0.
            g_ratio.SetPoint(i, base_graph.GetX()[i], ratio)

            rel_y_low = math.sqrt((graph.GetErrorYlow(i)/g_data_vals[i])**2 + (base_graph.GetErrorYlow(i)/g_vals[i])**2) if g_data_vals[i] > 0.0000001 and g_vals[i] > 0.0000001 else 0.

            g_ratio.SetPointEYlow(i, rel_y_low * ratio)

            rel_y_high = math.sqrt((graph.GetErrorYhigh(i)/g_data_vals[i])**2 + (base_graph.GetErrorYhigh(i)/g_vals[i])**2) if g_data_vals[i] > 0.0000001 and g_vals[i] > 0.0000001 else 0.

            g_ratio.SetPointEYhigh(i, rel_y_high * ratio)

        ratio_graphs.append(g_ratio)

    # Gymnastics to get same label sizes etc in ratio and main plot
    ytp_ratio = 2.
    xtp_ratio = 2.

    # hr.GetYaxis().SetNdivisions(4)
    for g_ratio in ratio_graphs:
        g_ratio.GetYaxis().SetTitleSize(g.GetYaxis().GetTitleSize() * xtp_ratio)
        g_ratio.GetXaxis().SetTitleSize(g.GetXaxis().GetTitleSize() * ytp_ratio)

        g_ratio.GetYaxis().SetTitleOffset(g.GetYaxis().GetTitleOffset() / xtp_ratio)
        g_ratio.GetXaxis().SetTitleOffset(g.GetXaxis().GetTitleOffset())  # / ytp_ratio)

        g_ratio.GetYaxis().SetLabelSize(g.GetYaxis().GetLabelSize() * xtp_ratio)
        g_ratio.GetXaxis().SetLabelSize(g.GetXaxis().GetLabelSize() * ytp_ratio)

        g_ratio.GetXaxis().SetTitle(base_graph.GetXaxis().GetTitle())


    for graph in graphs:
        graph.GetXaxis().SetLabelColor(0)
        graph.GetXaxis().SetLabelSize(0)


    maxy = 1.3 * max([gr.GetMaximum() for gr in graphs] + [1./1.25])
    for g in graphs:
        g.GetYaxis().SetRangeUser(0.0011, maxy)

    cv, pad, padr = HistDrawer.buildCanvas()

    pad.cd()

    base_graph.Draw('AP')
    for graph in graphs[1:]:
        graph.Draw('P')

    legend = TLegend(0.63, 0.63, 0.93, 0.91)
    legend.SetFillColor(0)
    legend.SetFillStyle(0)
    legend.SetLineColor(0)
    legend.SetLineWidth(0)

    legend2 = TLegend(0.78, 0.63, 0.93, 0.91)
    legend2.SetFillColor(0)
    legend2.SetFillStyle(0)
    legend2.SetLineColor(0)
    legend2.SetLineWidth(0)

    for graph in graphs:
        if 'opp' in graph.legend:
            legend2.AddEntry(graph.GetName(), graph.legend, 'lep')
        else:
            legend.AddEntry(graph.GetName(), graph.legend, 'lep')

    legend.Draw()
    legend2.Draw()

    padr.cd()

    for g_ratio in ratio_graphs:
        g_ratio.GetYaxis().SetRangeUser(0.01, 1.99)
        g_ratio.GetYaxis().SetTitle('Ratio to '+base_graph.legend)
        g_ratio.Draw('AP' if g_ratio == ratio_graphs[0] else 'P')

    drawRatioLines(g_ratio)

    cv.Print(plot_name)

    g.GetYaxis().SetRangeUser(0.0001, 1)
    pad.SetLogy(True)
    cv.Print(plot_name.replace('.', '_log.'))
    f = ROOT.TFile(plot_name.replace('.', '_log.').replace('.pdf', '.root'), 'RECREATE')
    g.Write()
    # g_data.Write()
    cv.Write()
    f.Close()