Exemplo n.º 1
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="")
    (options, args) = parser.parse_args()

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

    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, TH1F, gStyle
    from ModelParser import ModelKey

    gStyle.SetPadTopMargin(0.05)
    gStyle.SetPadRightMargin(0.05)
    gStyle.SetOptStat(0000000)

    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,
                500)
    hs = THStack()
    hs1 = THStack()

    infile = TFile(options.inputfile, "READ")
    hBkg = infile.Get("Background_N%d%s" % (N, suffix))
    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")

    hData_N2 = infile.Get("Data_N2")
    hBkg_N2 = infile.Get("Background_N2")

    ratio_data = infile.Get("Data_N%d%s" % (N, suffix))
    ratio_data.Sumw2()
    ratio_data.Divide(hData_N2, hBkg_N2)

    ref_N2 = infile.Get("ReferenceTemplateN2_0")
    ref_N3 = infile.Get("ReferenceTemplateN3_0")
    ratio_fits = infile.Get("ReferenceTemplateN2_0")
    ratio_fits.Sumw2()
    ratio_fits.Divide(ref_N2, ref_N3)

    legend = TLegend(0.3026613, 0.6919492, 0.6094355, 0.8816102)
    legend.SetTextSize(0.041)
    #was 0.02966102
    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(ratio_data, "Data/Background", "p")
    legend.AddEntry(ratio_fits, "Fit-0 (N=2)/Fit-0 (N=3)", "l")

    legend_sm = TLegend(0.6271774, 0.6769492, 0.8308065, 0.8171186)
    legend_sm.SetTextSize(0.041)
    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(2)
            h.SetLineStyle(i + 2)

        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"])

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

    if isExclusive:
        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")
    #TH1F *ratio_data

    ratio_fits.SetLineColor(4)
    ratio_fits.SetMarkerStyle(0)
    ratio_fits.SetLineWidth(2)

    #hs1.SetMinimum(1e-1)
    ratio_fits.Draw("linee1")
    ratio_data.Draw("same")
    #hs.Draw("samenostack")
    #c.SetLogy(1)
    ratio_fits.GetXaxis().SetTitle("S_{T} (GeV)")
    ratio_fits.GetYaxis().SetTitle("Arbitrary Units")
    ratio_fits.GetYaxis().SetTitleOffset(1.1)

    ratio_fits.GetYaxis().SetTitleSize(0.045)
    ratio_fits.GetYaxis().SetLabelSize(0.045)
    ratio_fits.GetXaxis().SetTitleSize(0.045)
    ratio_fits.GetXaxis().SetLabelSize(0.045)
    ratio_fits.GetXaxis().Draw()
    ibin = 0
    if isExclusive:
        ratio_fits.GetXaxis().SetRangeUser(config.fit_range[0],
                                           config.fit_range[1] + 330)
        ibin = hData.FindBin(config.fit_range[0])
    else:
        ratio_fits.GetXaxis().SetRangeUser(config.norm_range[0],
                                           config.norm_range[1] + 330)
        ibin = hData.FindBin(config.norm_range[0])
    from Styles import formatUncertainty
    formatUncertainty(gBkg)
    #gBkg.Draw("LX")
    #hData.GetXaxis().SetNdivisions(510)

    #hData.Draw("esame")
    ratio_fits.SetTitle("")
    ratio_fits.SetMinimum(0)
    ratio_fits.SetMaximum(3)

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

    if isExclusive:
        cmslabel = TPaveText(0.45, 0.90, 0.60, 0.93, "brNDC")
    else:
        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")

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

    if isExclusive:
        c.Print("ST_Residuals_Mul%d.pdf" % N)
        c.Print("ST_Residuals_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...")
                          getFloat(getLowerBin(iEta), 'p')) * 0.25
                if printError and (iEn == "1_5" or iEn == '5_10'
                                   or iEn == '10_15' or iEn == '15_20'):
                    y1 = (getFloat(getUpperBin(iEn)) +
                          getFloat(getLowerBin(iEn))) / 2 - (
                              getFloat(getUpperBin(iEn)) -
                              getFloat(getLowerBin(iEn))) * 0.75
                else:
                    y1 = (getFloat(getUpperBin(iEn)) +
                          getFloat(getLowerBin(iEn))) / 2 - (
                              getFloat(getUpperBin(iEn)) -
                              getFloat(getLowerBin(iEn))) * 0.25
                y2 = (getFloat(getUpperBin(iEn)) + getFloat(getLowerBin(iEn))
                      ) / 2 + (getFloat(getUpperBin(iEn)) -
                               getFloat(getLowerBin(iEn))) * 0.25
                score_print = TPaveText(x1, y1, x2, y2)
                if [iEn, iEta] not in lowStatBins:
                    if printError:  #we print the error
                        for iLine in lineQte:

                            index1_a = iLine.find(' ')
                            index1_b = iLine.find(' ', index1_a + 1)
                            index1_c = iLine.find(' ', index1_b + 1)
                            index1_d = iLine.find(' ', index1_c + 1)
                            ETrange = iLine[0:index1_a]
                            ETArange = iLine[index1_a + 1:index1_b]
                            if iEn == ETrange and iEta == ETArange:
                                score_print.AddText('#pm {a}'.format(a=round(
                                    float(iLine[index1_c + 1:index1_d]), 1)))
                                score_print.SetFillColorAlpha(0, 0)
def plot_fit_results(histograms, category, channel):
    global variable, translate_options, b_tag_bin, save_path
    #ROOT.TH1.SetDefaultSumw2(False)
    ROOT.gROOT.SetBatch(True)
    ROOT.gROOT.ProcessLine('gErrorIgnoreLevel = 1001;')
    plotting.setStyle()
    gStyle.SetTitleYOffset(1.4)
    ROOT.gROOT.ForceStyle()

    for variable_bin in variable_bins_ROOT[variable]:
        path = save_path + '/' + variable + '/' + category + '/fit_results/'
        make_folder_if_not_exists(path)
        plotname = path + channel + '_bin_' + variable_bin + '.png'
        # check if template plots exist already
        if os.path.isfile(plotname):
            continue
        canvas = Canvas(width=700, height=500)
        canvas.SetLeftMargin(0.15)
        canvas.SetBottomMargin(0.15)
        canvas.SetTopMargin(0.05)
        canvas.SetRightMargin(0.05)
        legend = plotting.create_legend(x0=0.7, y1=0.8)
        h_data = histograms[variable_bin]['data']
        h_signal = histograms[variable_bin]['signal']
        h_background = histograms[variable_bin]['background']

        h_data.GetXaxis().SetTitle('Lepton #eta')
        h_data.GetYaxis().SetTitle('Number of Events')
        h_data.GetXaxis().SetTitleSize(0.05)
        h_data.GetYaxis().SetTitleSize(0.05)
        h_data.SetMinimum(0)
        h_data.SetMarkerSize(1)
        h_data.SetMarkerStyle(20)
        gStyle.SetEndErrorSize(20)
        h_data.Draw('P')

        h_signal.SetFillColor(kRed + 1)
        h_background.SetFillColor(kGreen - 3)
        h_signal.SetLineWidth(2)
        h_background.SetLineWidth(2)
        h_signal.SetFillStyle(1001)
        h_background.SetFillStyle(1001)

        mcStack = THStack("MC", "MC")
        mcStack.Add(h_background)
        mcStack.Add(h_signal)

        mcStack.Draw('hist same')
        h_data.Draw('error P same')
        legend.AddEntry(h_data, 'data', 'P')
        legend.AddEntry(h_signal, 'signal', 'F')
        legend.AddEntry(h_background, 'background', 'F')
        legend.Draw()

        mytext = TPaveText(0.5, 0.97, 1, 1.01, "NDC")
        channelLabel = TPaveText(0.18, 0.97, 0.5, 1.01, "NDC")
        if channel == 'electron':
            channelLabel.AddText("e, %s, %s" %
                                 ("#geq 4 jets", b_tag_bins_latex[b_tag_bin]))
        elif channel == 'muon':
            channelLabel.AddText("#mu, %s, %s" %
                                 ("#geq 4 jets", b_tag_bins_latex[b_tag_bin]))
        else:
            channelLabel.AddText("combined, %s, %s" %
                                 ("#geq 4 jets", b_tag_bins_latex[b_tag_bin]))
        mytext.AddText(
            "CMS Preliminary, L = %.1f fb^{-1} at #sqrt{s} = 8 TeV" % (5.8))

        mytext.SetFillStyle(0)
        mytext.SetBorderSize(0)
        mytext.SetTextFont(42)
        mytext.SetTextAlign(13)

        channelLabel.SetFillStyle(0)
        channelLabel.SetBorderSize(0)
        channelLabel.SetTextFont(42)
        channelLabel.SetTextAlign(13)
        mytext.Draw()
        channelLabel.Draw()

        canvas.Modified()
        canvas.Update()
        canvas.SaveAs(plotname)
        canvas.SaveAs(plotname.replace('png', 'pdf'))
Exemplo n.º 4
0
#gROOT.Reset()

c1 = TCanvas('c1', 'Tree Data Structure', 200, 10, 750, 940)
c1.Range(0, -0.1, 1, 1.15)

gBenchmark.Start('tree')

branchcolor = 26
leafcolor = 30
basketcolor = 42
offsetcolor = 43
#title = TPaveLabel(.3,1.05,.8,1.13,c1.GetTitle())
title = TPaveLabel(.3, 1.05, .8, 1.13, 'Tree Data Structure')
title.SetFillColor(16)
title.Draw()
tree = TPaveText(.01, .75, .15, 1.00)
tree.SetFillColor(18)
tree.SetTextAlign(12)
tnt = tree.AddText('Tree')
tnt.SetTextAlign(22)
tnt.SetTextSize(0.030)
tree.AddText('fScanField')
tree.AddText('fMaxEventLoop')
tree.AddText('fMaxVirtualSize')
tree.AddText('fEntries')
tree.AddText('fDimension')
tree.AddText('fSelectedRows')
tree.Draw()
farm = TPavesText(.01, 1.02, .15, 1.1, 9, 'tr')
tfarm = farm.AddText('CHAIN')
tfarm.SetTextSize(0.024)
def Measure_Integral(Fname1, Fname2, Title, XaxisT, low, high, freq, RootName):

    FNumber = int((high - low) / freq)

    LINK = [3]
    #    LINK=[15,16,17,18,19]
    LINKkChannel = [0, 1, 2, 3, 4, 5]
    #    LINKkChannel=[0]
    for linkChannel in LINKkChannel:
        for link in LINK:

            xIntegral = array("d", xrange(0, FNumber))
            yIntegral = array("d", xrange(0, FNumber))
            yIntegralErrUp = array("d", xrange(0, FNumber))
            yIntegralErrDown = array("d", xrange(0, FNumber))
            xIntegral_RMS = array("d", xrange(0, FNumber))
            yIntegral_RMS = array("d", xrange(0, FNumber))
            yIntegral_RMSErrUp = array("d", xrange(0, FNumber))
            yIntegral_RMSErrDown = array("d", xrange(0, FNumber))
            xRatio = array("d", xrange(0, FNumber))
            yRatio = array("d", xrange(0, FNumber))
            xSingleEv = array("d", xrange(0, 40))
            ySingleEv = array("d", xrange(0, 40))

            num = -1
            for iAmp in range(low, high, freq):
                num += 1
                Fname = Fname1 + str(iAmp) + Fname2

                f = open(Fname)
                data = getData(f)

                M = TH1F(Fname, Fname, 200, 0.4, 1.4)
                HistoSergey = TH1F(Fname, Fname, 200, -10, 200)
                M.SetDefaultSumw2()
                x = array("d", xrange(0, 1001))
                y = array("d", xrange(0, 1001))

                for event in xrange(0, 9):
                    for BX in xrange(0, 40):

                        xSingleEv[BX] = BX
                        ySingleEv[BX] = data[event][link][BX][linkChannel]
                        if BX < 16: HistoSergey.Fill(ySingleEv[BX])
                        if ySingleEv[BX] <= 0: ySingleEv[BX] = 0.1
                        if ySingleEv[BX] < 0.1: print "--->", ySingleEv[BX]

                    scanvas = MakeCanvas("mm", "nn", 800, 800)
                    scanvas.SetLogy()
                    GrSingleEv = TGraph(len(xSingleEv), xSingleEv, ySingleEv)

                    #                    SFit=TF1("fit", "gaus", 19,23)
                    #                    SFit.SetParameter(0, 250)
                    #                    SFit.SetParameter(1, 20.9)
                    #            SFit.SetParLimits(1, 20, 22)
                    #                    SFit.SetParameter(2, 1)
                    GrSingleEv.GetXaxis().SetRangeUser(0, 40)
                    GrSingleEv.GetYaxis().SetRangeUser(0.05, 100000)
                    GrSingleEv.Draw("AC*")
                    #                    GrSingleEv.Fit("fit","R0")
                    #                    SFit.Draw("same")
                    #                    FitParam=SFit.GetParameters()
                    #                    print "Gaus fit param 1, 2, 3= " , round(FitParam[0],4), round(FitParam[1],4), round(FitParam[2],4)
                    fitInfo = TPaveText(.20, 0.7, .60, 0.9, "NDC")
                    fitInfo.SetBorderSize(0)
                    fitInfo.SetFillStyle(0)
                    fitInfo.SetTextAlign(12)
                    fitInfo.SetTextSize(0.03)
                    fitInfo.SetTextColor(1)
                    fitInfo.SetTextFont(62)
                    fitInfo.AddText("eventNumber_" + str(event) + "_link" +
                                    str(link) + "_ch_" + str(linkChannel))
                    fitInfo.Draw()

                    scanvas.SaveAs("PLOT/singleEv_" + str(iAmp) + "_" +
                                   str(event) + RootName + "_link" +
                                   str(link) + "_ch_" + str(linkChannel) +
                                   ".pdf")

                sergeycanvas = MakeCanvas("mm", "nn", 800, 800)
                HistoSergey.Draw()
                sergeycanvas.SaveAs("SergeyHisto" + RootName + "_link" +
                                    str(link) + "_ch_" + str(linkChannel) +
                                    ".pdf")
Exemplo n.º 6
0
           "MPV results;Relative i#eta;Relative i#phi;Rec. E / GeV", 7, -3.5,
           3.5, 7, -3.5, 3.5, 20, 0, 4)

for i, scenario in enumerate(scenarioNameList):
    canvasList.append(
        TCanvas("canvasLandau" + str(i), "Canvas Landau" + str(i), 900, 900))
    canvasList[-1].Divide(5, 5)
    for j, nameTrunk in enumerate(nameTrunkList):
        canvasList[i].cd(j + 1)
        localHist = file.Get(nameTrunk + scenario)
        if (localHist):
            localHist.GetXaxis().SetRangeUser(-.1, 5)
            histoList.append(localHist)
            localHist.Draw()
            localHist.SetStats(0)
            paveText = TPaveText(0.4, 0.6, 0.9, 0.9, 'NDC')
            paveText.AddText('%s: %.2f' % ('Mean', localHist.GetMean()))
            if (localHist.GetEntries() > 3):
                localFit = TF1('fit' + str(i * len(nameTrunkList) + j),
                               "landau")
                localFit.SetParameter(1, 0.8)
                localFit.SetParameter(2, 0.15)
                if (j == int(len(nameTrunkList) / 2)):
                    localHist.Fit(localFit, "Q", "", 0.2, 3)
                else:
                    localHist.Fit(localFit, "Q", "", 0.2, 3)
                if (i == 2):
                    localI = j % 5
                    h3D.Fill(localI - 2, 2 - j / 5, localFit.GetParameter(1))
                    if (localFit.GetNDF() < 4):
                        lowStatisticsList.append([localI - 2, 2 - j / 5])
Exemplo n.º 7
0
pad3.GetFrame().SetFillColor(38)
pad3.GetFrame().SetBorderSize(8)
ntuple.SetMarkerColor(1)
ntuple.Draw('py:px','pz>1')
ntuple.SetMarkerColor(2)
ntuple.Draw('py:px','pz<1','same')
c1.Update()

#
# Display a 3-D scatter plot of 3 columns. Superimpose a different selection.
pad4.cd()
ntuple.Draw('pz:py:px','(pz<10 && pz>6)+(pz<4 && pz>3)')
ntuple.SetMarkerColor(4)
ntuple.Draw('pz:py:px','pz<6 && pz>4','same')
ntuple.SetMarkerColor(5)
ntuple.Draw('pz:py:px','pz<4 && pz>3','same')
l4 = TPaveText(-0.9,0.5,0.9,0.95)
l4.SetFillColor(42)
l4.SetTextAlign(12)
l4.AddText('You can interactively rotate this view in 2 ways:')
l4.AddText('  - With the RotateCube in clicking in this pad')
l4.AddText('  - Selecting View with x3d in the View menu')
l4.Draw()

#
# done
c1.cd()
c1.Update()
gStyle.SetStatColor(19)
gBenchmark.Show('ntuple1')
Exemplo n.º 8
0
def plotR2(h5, seql, poll):
    norm = 50000
    for var in range(0, NVARS):
        if var == PHI or var == ALPHA: continue
        for pobs in range(0, NPOBS):
            if pobs == A: continue
            for seq in seql:
                outdir_seq = os.path.join(outdir_q2w, SEQ_NAME[seq])
                if not os.path.isdir(outdir_seq): os.makedirs(outdir_seq)

                cname = ('R2_%s_1%s') % (POBS_NAME[pobs], VARS_NAME[var])
                l = TLine(0, 0, 180, 0)
                cR2 = TCanvas(cname, cname)  #"RvVar", "RvVar")
                hR2 = {}
                #pltnum=0
                for pol in poll:
                    outdir_pol = os.path.join(outdir_seq, POLS_NAME[pol])
                    if not os.path.isdir(outdir_pol): os.makedirs(outdir_pol)
                    if pol != AVG:
                        hR2[(pol)] = h5[(seq, pol, pobs)].Projection(var)
                        hR2[(pol)].Scale(1 / math.pi)
                        hR2[(pol)].Scale(1 / norm)
                        hR2[(pol)].SetLineColor(
                            gROOT.ProcessLine("%s" % POLS_COLOR[pol]))
                        hR2[(pol)].SetMarkerStyle(
                            gROOT.ProcessLine("kFullCircle"))
                    elif pol == AVG:
                        hR2[(AVG)] = hR2[(POS)].Clone("avg")
                        hR2[(AVG)].Add(hR2[(NEG)])
                        hR2[(AVG)].Scale(0.5)
                        if pobs == D:
                            hR2[(AVG)].SetMinimum(-0.003)
                            hR2[(AVG)].SetMaximum(0.003)
                    #Make Titles nice
                    hR2[(pol)].SetTitle("")
                    #hR2[(NEG)].SetTitle("")
                    #hR2[(AVG)].SetTitle("")

                    #cR2 = {}
                    #l = TLine(0,0,180,0)
                    #cname = ('R2%sV%s')%(VARS_NAME[var],VARS_NAME[var])
                    #if pltnum==0:
                    hR2[(pol)].Draw("ep")
                    #else:
                    #	hR2[(pol)].Draw("ep same")
                    # hR2[(NEG)].Draw("ep same")
                    #hR2[(AVG)].Draw("ep same")
                    l.Draw("same")
                    pt = TPaveText(0.3, 0.85, 0.7, 1.0, "NDC")
                    q2wt = pt.AddText('[Q^{2}][W] = %s' % q2wdir.GetName())
                    q2wt.SetTextColor(gROOT.ProcessLine("kBlue"))
                    vart = pt.AddText(
                        ("%s,%s: %s^{%s} vs. %s") %
                        (SEQ_NAME[seq], POLS_NAME[pol], POBS_NAME[pobs],
                         VARS_TITLE[0][var], VARS_TITLE[0][var]))
                    vart.SetTextSize(0.05)
                    pt.Draw()
                    csavename = ('%s/%s') % (outdir_pol, cR2.GetName())
                    cR2.SaveAs(('%s.png') % (csavename))
                    print('>>>convert %s.png %s.pdf') % (csavename, csavename)
                    rc = subprocess.call([
                        'convert',
                        '%s.png' % csavename,
                        '%s.pdf' % csavename
                    ])
                    if rc != 0: print '.png to .pdf failed for %s' % csavename
Exemplo n.º 9
0
h_N2_status.Draw()
c1.Print(outputdir + "N2_status.png")
h_N2_mass.Draw()
c1.Print(outputdir + "N2_mass.png")
h_N2_Pt.Draw()
c1.Print(outputdir + "N2_Pt.png")
h_N2_Eta.Draw()
c1.Print(outputdir + "N2_Eta.png")
h_N2_Phi.Draw()
c1.Print(outputdir + "N2_Phi.png")

fit = h_N2_lifetime_labframe.Fit("expo", "S")
par = [fit.Get().Parameter(i) for i in range(2)]
lifetimeoutput = "Mean Lifetime = " + str(1 / -par[1]) + " ps"
t = TPaveText()
t.SetTextFont(10)
t.AddText(lifetimeoutput)
h_N2_lifetime_labframe.Draw()
t.Draw()
c1.Print(outputdir + "N2_lifetime_labframe.png")
fit = h_N2_lifetime_restframe.Fit("expo", "S")
par = [fit.Get().Parameter(i) for i in range(2)]
lifetimeoutput = "Mean Lifetime = " + str(1 / -par[1]) + " ps"
t = TPaveText()
t.SetTextFont(10)
t.AddText(lifetimeoutput)
h_N2_lifetime_restframe.Draw()
t.Draw()
c1.Print(outputdir + "N2_lifetime_restframe.png")
fit = h_N2_ctau_labframe.Fit("expo", "S")
Exemplo n.º 10
0
def fit_hist(histo,
             cent_class,
             pt_range,
             ct_range,
             nsigma=3,
             model="pol2",
             fixsigma=-1,
             sigma_limits=None,
             mode=3,
             split=''):
    # canvas for plotting the invariant mass distribution
    cv = TCanvas(f'cv_{histo.GetName()}')

    # define the number of parameters depending on the bkg model
    if 'pol' in str(model):
        n_bkgpars = int(model[3]) + 1
    elif 'expo' in str(model):
        n_bkgpars = 2
    else:
        print(f'Unsupported model {model}')

    # define the fit function bkg_model + gauss
    fit_tpl = TF1('fitTpl', f'{model}(0)+gausn({n_bkgpars})', 0, 5)

    # redefine parameter names for the bkg_model
    for i in range(n_bkgpars):
        fit_tpl.SetParName(i, f'B_{i}')

    # define parameter names for the signal fit
    fit_tpl.SetParName(n_bkgpars, 'N_{sig}')
    fit_tpl.SetParName(n_bkgpars + 1, '#mu')
    fit_tpl.SetParName(n_bkgpars + 2, '#sigma')
    # define parameter values and limits
    fit_tpl.SetParameter(n_bkgpars, 40)
    fit_tpl.SetParLimits(n_bkgpars, 0.001, 10000)
    fit_tpl.SetParameter(n_bkgpars + 1, 2.991)
    fit_tpl.SetParLimits(n_bkgpars + 1, 2.986, 3)

    # define signal and bkg_model TF1 separately
    sigTpl = TF1('fitTpl', 'gausn(0)', 0, 5)
    bkg_tpl = TF1('fitTpl', f'{model}(0)', 0, 5)

    # plotting stuff for fit_tpl
    fit_tpl.SetNpx(300)
    fit_tpl.SetLineWidth(2)
    fit_tpl.SetLineColor(2)
    # plotting stuff for bkg model
    bkg_tpl.SetNpx(300)
    bkg_tpl.SetLineWidth(2)
    bkg_tpl.SetLineStyle(2)
    bkg_tpl.SetLineColor(2)

    # define limits for the sigma if provided
    if sigma_limits != None:
        fit_tpl.SetParameter(n_bkgpars + 2,
                             0.5 * (sigma_limits[0] + sigma_limits[1]))
        fit_tpl.SetParLimits(n_bkgpars + 2, sigma_limits[0], sigma_limits[1])
    # if the mc sigma is provided set the sigma to that value
    elif fixsigma > 0:
        fit_tpl.FixParameter(n_bkgpars + 2, fixsigma)
    # otherwise set sigma limits reasonably
    else:
        fit_tpl.SetParameter(n_bkgpars + 2, 0.002)
        fit_tpl.SetParLimits(n_bkgpars + 2, 0.001, 0.003)

    ########################################
    # plotting the fits
    if mode == 2:
        ax_titles = ';m (^{3}He + #pi) (GeV/#it{c})^{2};Counts' + f' / {round(1000 * histo.GetBinWidth(1), 2)} MeV'
    if mode == 3:
        ax_titles = ';m (d + p + #pi) (GeV/#it{c})^{2};Counts' + f' / {round(1000 * histo.GetBinWidth(1), 2)} MeV'

    # invariant mass distribution histo and fit
    histo.UseCurrentStyle()
    histo.SetLineColor(1)
    histo.SetMarkerStyle(20)
    histo.SetMarkerColor(1)
    histo.SetTitle(ax_titles)
    histo.SetMaximum(1.5 * histo.GetMaximum())
    histo.Fit(fit_tpl, "QRL", "", 2.96, 3.04)
    histo.Fit(fit_tpl, "QRL", "", 2.96, 3.04)
    histo.SetDrawOption("e")
    histo.GetXaxis().SetRangeUser(2.96, 3.04)
    # represent the bkg_model separately
    bkg_tpl.SetParameters(fit_tpl.GetParameters())
    bkg_tpl.SetLineColor(600)
    bkg_tpl.SetLineStyle(2)
    bkg_tpl.Draw("same")
    # represent the signal model separately
    sigTpl.SetParameter(0, fit_tpl.GetParameter(n_bkgpars))
    sigTpl.SetParameter(1, fit_tpl.GetParameter(n_bkgpars + 1))
    sigTpl.SetParameter(2, fit_tpl.GetParameter(n_bkgpars + 2))
    sigTpl.SetLineColor(600)
    # sigTpl.Draw("same")

    # get the fit parameters
    mu = fit_tpl.GetParameter(n_bkgpars + 1)
    muErr = fit_tpl.GetParError(n_bkgpars + 1)
    sigma = fit_tpl.GetParameter(n_bkgpars + 2)
    sigmaErr = fit_tpl.GetParError(n_bkgpars + 2)
    signal = fit_tpl.GetParameter(n_bkgpars) / histo.GetBinWidth(1)
    errsignal = fit_tpl.GetParError(n_bkgpars) / histo.GetBinWidth(1)
    bkg = bkg_tpl.Integral(mu - nsigma * sigma,
                           mu + nsigma * sigma) / histo.GetBinWidth(1)

    if bkg > 0:
        errbkg = math.sqrt(bkg)
    else:
        errbkg = 0
    # compute the significance
    if signal + bkg > 0:
        signif = signal / math.sqrt(signal + bkg)
        deriv_sig = 1 / math.sqrt(signal + bkg) - signif / (2 * (signal + bkg))
        deriv_bkg = -signal / (2 * (math.pow(signal + bkg, 1.5)))
        errsignif = math.sqrt((errsignal * deriv_sig)**2 +
                              (errbkg * deriv_bkg)**2)
    else:
        signif = 0
        errsignif = 0

    # print fit info on the canvas
    pinfo2 = TPaveText(0.5, 0.5, 0.91, 0.9, "NDC")
    pinfo2.SetBorderSize(0)
    pinfo2.SetFillStyle(0)
    pinfo2.SetTextAlign(30 + 3)
    pinfo2.SetTextFont(42)

    string = f'ALICE Internal, Pb-Pb 2018 {cent_class[0]}-{cent_class[1]}%'
    pinfo2.AddText(string)

    decay_label = {
        "": [
            '{}^{3}_{#Lambda}H#rightarrow ^{3}He#pi^{-} + c.c.',
            '{}^{3}_{#Lambda}H#rightarrow dp#pi^{-} + c.c.'
        ],
        "_matter": [
            '{}^{3}_{#Lambda}H#rightarrow ^{3}He#pi^{-}',
            '{}^{3}_{#Lambda}H#rightarrow dp#pi^{-}'
        ],
        "_antimatter": [
            '{}^{3}_{#bar{#Lambda}}#bar{H}#rightarrow ^{3}#bar{He}#pi^{+}',
            '{}^{3}_{#Lambda}H#rightarrow #bar{d}#bar{p}#pi^{+}'
        ],
    }

    string = decay_label[split][
        mode -
        2] + ', %i #leq #it{ct} < %i cm %i #leq #it{p}_{T} < %i GeV/#it{c} ' % (
            ct_range[0], ct_range[1], pt_range[0], pt_range[1])
    pinfo2.AddText(string)

    string = f'Significance ({nsigma:.0f}#sigma) {signif:.1f} #pm {errsignif:.1f} '
    pinfo2.AddText(string)

    string = f'S ({nsigma:.0f}#sigma) {signal:.0f} #pm {errsignal:.0f}'
    pinfo2.AddText(string)

    string = f'B ({nsigma:.0f}#sigma) {bkg:.0f} #pm {errbkg:.0f}'
    pinfo2.AddText(string)

    if bkg > 0:
        ratio = signal / bkg
        string = f'S/B ({nsigma:.0f}#sigma) {ratio:.4f}'

    pinfo2.AddText(string)
    pinfo2.Draw()
    gStyle.SetOptStat(0)

    st = histo.FindObject('stats')
    if isinstance(st, TPaveStats):
        st.SetX1NDC(0.12)
        st.SetY1NDC(0.62)
        st.SetX2NDC(0.40)
        st.SetY2NDC(0.90)
        st.SetOptStat(0)

    histo.Write()
    cv.Write()

    return (signal, errsignal, signif, errsignif, mu, muErr, sigma, sigmaErr)
    return (signal, errsignal, signif, errsignif, sigma, sigmaErr)
Exemplo n.º 11
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="")
    (options, args) = parser.parse_args()

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

    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
    from ModelParser import ModelKey

    gStyle.SetPadTopMargin(0.05)
    gStyle.SetPadRightMargin(0.05)

    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,
                500)
    hs = THStack()

    infile = TFile(options.inputfile, "READ")
    hBkg = infile.Get("Background_N%d%s" % (N, suffix))
    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")

    legend = TLegend(0.3326613, 0.6419492, 0.9294355, 0.9216102)
    legend.SetTextSize(0.02966102)
    legend.SetTextFont(42)
    legend.SetFillColor(0)
    legend.SetLineColor(0)
    if isExclusive:
        legend.SetHeader("N = %d" % N)
    else:
        legend.SetHeader("N #geq %d" % N)
    legend.AddEntry(hData, "Data", "p")
    legend.AddEntry(hBkg_, "Background", "l")
    legend.AddEntry(hBkg, "Uncertainty", "f")

    legend_sm = TLegend(0.6471774, 0.7669492, 0.8508065, 0.8771186)
    legend_sm.SetTextSize(0.02966102)
    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(2)
            h.SetLineStyle(i + 2)

        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"])

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


#   if isExclusive:
    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])
        hs.Add(h, "hist")
        legend_sm.AddEntry(h, config.sm_models[i], "f")

    #hs.Add(hData, "e")

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

    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])
    from Styles import formatUncertainty
    formatUncertainty(gBkg)
    gBkg.Draw("LX")
    hData.Draw("esame")

    hs.SetMinimum(5e-2)
    if isExclusive:
        hs.SetMaximum(hData.GetBinContent(ibin) * 20)
    else:
        #hs.SetMaximum(4e4)
        hs.SetMaximum(hData.GetBinContent(ibin) * 20)

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

    if isExclusive:
        cmslabel = TPaveText(0.5544355, 0.5127119, 0.8991935, 0.6292373,
                             "brNDC")
    else:
        cmslabel = TPaveText(0.1955645, 0.1631356, 0.5403226, 0.279661,
                             "brNDC")
    cmslabel.AddText(config.cmsTitle)
    cmslabel.AddText(config.cmsSubtitle)
    cmslabel.SetFillColor(0)
    cmslabel.Draw("plain")

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

    c.Update()

    raw_input("Press Enter to continue...")
Exemplo n.º 12
0
#
# The function "ls()" lists the directory contents of this file
#
fill.ls()

#
# Get object "sqroot" from the file.
#

sqroot = gROOT.FindObject( 'sqroot' )
sqroot.Print()

#
# Now fit histogram h1f with the function sqroot
#
h1f = gROOT.FindObject( 'h1f' )
h1f.SetFillColor( 45 )
h1f.Fit( 'sqroot' )

# We now annotate the picture by creating a PaveText object
# and displaying the list of commands in this macro
#
fitlabel = TPaveText( 0.6, 0.3, 0.9, 0.80, 'NDC' )
fitlabel.SetTextAlign( 12 )
fitlabel.SetFillColor( 42 )
fitlabel.ReadFile(path.join(str(gROOT.GetTutorialDir()), 'pyroot', 'fit1_py.py'))
fitlabel.Draw()
c1.Update()
gBenchmark.Show( 'fit1' )
Exemplo n.º 13
0
def main():

    cc.cd()
    cc.SetBorderMode(0)
    cc.SetFixedAspectRatio(1)
    cc.FeedbackMode(1)

    gStyle.SetOptStat(0)
    gStyle.SetGridStyle(1)
    gStyle.SetGridColor(11)

    hh=TH2D('hh',';X;Y',22,-10.5,11.5,22,-10.5,11.5)
    hi=TH2I('hi',';X;Y',22,-10.5,11.5,22,-10.5,11.5)
    setupHists([hh,hi])
    xax,yax=hh.GetXaxis(),hh.GetYaxis()
    hh.Draw('COLZ')
    hi.Draw('TEXTSAME')

    gPad.SetLogz()
    gPad.SetGrid(1,1)
    gPad.SetLeftMargin(0.09)
    gPad.SetRightMargin(0.11)

    #tt2=TPaveText(0.7,0.96,0.9,0.99,'NDC')
    ttM=TPaveText(-3+0.05, 7-4.45, 4.0, 8-4.51)
    tt2=TPaveText(-3+0.05, 7-5.45, 4.0, 8-5.51)

    ttX=TPaveText(-2, 7-8.00, 3, 8-8.00)
    ttY=TPaveText(-2, 7-9.00, 3, 8-9.00)
    ttZ=TPaveText(-2, 6-8.80, 3, 8-9.30)
    ttZ.AddText("positive = beam top/right")

    ttime=TPaveText(-10,-12.5,10,-11.8)
    tchan=TPaveText(0,0,0.9,1)
    setupPaveTexts([tt2,ttM,ttime,tchan,ttX,ttY,ttZ])
    ttM.SetTextColor(2)
    ttM.SetFillStyle(0)
    ttZ.SetFillStyle(0)
    tt2.SetFillStyle(0)

    tarrow=TText(-0.9,0.7,'Beam Right')
    tarrow.SetTextSizePixels(15)
    arrow=TArrow(-1.4,0.5,2.4,0.5,0.02,'|>')
    arrow.SetAngle(40)
    arrow.SetFillColor(1)
    arrow.SetLineWidth(2)

    tt=TText()
    tt.SetTextColor(1)
    tt.SetTextAngle(90)
    tt.SetTextSize(0.04)
    tt.DrawText(12.4,0,'kHz')
    tt.SetTextAngle(0)
    tt.SetTextColor(1)
    tt.DrawTextNDC(0.3,0.92,'FTC FADC SCALERS')

    bb=TBox()
    bb.SetFillStyle(1001)
    bb.SetFillColor(0)
    bb.SetLineWidth(1)
    bb.SetLineColor(1)
    bb.DrawBox(-3.47,-1.47,4.47,2.46)
    bb.DrawBox(-1.47,-3.47,2.49,4.47)
    bb.DrawBox(-2.47,-2.47,3.49,3.47)

    cc.cd()
    for xx in [ttM,tt2,ttime,arrow,tarrow,ttX,ttY,ttZ]: xx.Draw()
    cc2.cd()
    tchan.Draw('NDC')
    cc.cd()

    gPad.SetEditable(0)

    while True:

            for ch in ECAL.chans:
              loadPV(ch)
              ch=ch.vals
              xx,yy=ch['X'],ch['Y']
              #if (ch['PVVAL']>10):
               # print xx,yy,ch['PVVAL']

              # swap x to make it downstream view:
              xx=-xx

              #after, fix the fact x=0 / y=0 don't exists
              if xx<0: xx+=1
              if yy<0: yy+=1
              hh.SetBinContent(xax.FindBin(xx),yax.FindBin(yy),ch['PVVAL'])
              hi.SetBinContent(xax.FindBin(xx),yax.FindBin(yy),ch['PVVAL'])

            for xx in [ttime,tt2,ttM,ttX,ttY]: xx.Clear()
            [total,maximum,top,bottom,left,right]=calcRates(ECAL.chans)

            tt2.AddText('Total:  %.1f MHz'%(total/1000))
            ttM.AddText('Max:  %.0f kHz'%(maximum))

            if total>1e2:
              xasy = (right-left)/total
              yasy = (top-bottom)/total
              ttX.AddText('X-Asy:  %+.1f%%'%(100*xasy))
              ttY.AddText('Y-Asy:  %+.1f%%'%(100*yasy))
            else:
              ttX.AddText('X-Asy:  N/A')
              ttY.AddText('Y-Asy:  N/A')

            ttime.AddText(makeTime())

            if not gPad: sys.exit()

            if gPad.GetEvent()==11:
                xy=pix2xy(gPad)
                ee=ECAL.findChannelXY(xy[0],xy[1])
                if ee:
                    tchan.Clear()
                    tchan.AddText(printChannel(ee))
                    cc2.Modified()
                    cc2.Update()
            elif gPad.GetEvent()==12:
                tchan.Clear()
                cc2.Modified()
                cc2.Update()


            cc.Modified()
            cc.Update()

            time.sleep(2)
Exemplo n.º 14
0
parser = OptionParser()
parser.add_option('--plotDir',
                  metavar='P',
                  type='string',
                  action='store',
                  default='Summer2018Plots',
                  dest='plotDir',
                  help='output directory of plots')
(options, args) = parser.parse_args()

outDir = options.plotDir

execfile("input.py")

c1 = TCanvas('c1', 'c1', 1800, 1000)
pt1 = TPaveText(.05, .05, .15, .95)
pt2 = TPaveText(0.15, 0.05, 0.23, 0.95)
pt3 = TPaveText(0.23, 0.05, 0.31, 0.95)
pt4 = TPaveText(0.31, 0.05, 0.39, 0.95)
pt5 = TPaveText(0.39, 0.05, 0.47, 0.95)
pt6 = TPaveText(0.47, 0.05, 0.55, 0.95)
pt7 = TPaveText(0.55, 0.05, 0.63, 0.95)
pt8 = TPaveText(0.63, 0.05, 0.71, 0.95)
pt9 = TPaveText(0.71, 0.05, 0.79, 0.95)
pt10 = TPaveText(0.79, 0.05, 0.87, 0.95)
pt11 = TPaveText(0.87, 0.05, 0.95, 0.95)

pt1.AddText("Sample")
pt1.AddLine(0.0, 0.1, 1.0, 0.1)
pt1.AddText("DYToLL")
pt1.AddLine(0.0, 0.2, 1.00, .200)
Exemplo n.º 15
0
    def plotEfficiency(self, doFit = False):
        if hasattr(self, "Denominator") and hasattr(self, "Numerator"):
            if self._rebinFactor != 1:
                self.Denominator["hist"].Rebin(self._rebinFactor)
                self.Numerator["hist"].Rebin(self._rebinFactor)
		
            for ibin in range(-1, self.Numerator["hist"].GetNbinsX()+1):
                if self.Numerator["hist"].GetBinContent(ibin+1) > self.Denominator["hist"].GetBinContent(ibin+1):
                    print('Fixing bad bin:', (ibin+1))
                    self.Numerator["hist"].SetBinContent(ibin+1, self.Denominator["hist"].GetBinContent(ibin+1))
                    self.Numerator["hist"].SetBinError(ibin+1, self.Denominator["hist"].GetBinError(ibin+1))

            efficiencyGraph = TGraphAsymmErrors(self.Numerator["hist"], self.Denominator["hist"], "cp")

            pt_cmsPrelim = TPaveText(0.132832, 0.859453, 0.486216, 0.906716, "brNDC")
            pt_cmsPrelim.SetBorderSize(0)
            pt_cmsPrelim.SetFillStyle(0)
            pt_cmsPrelim.SetTextFont(62)
            pt_cmsPrelim.SetTextSize(0.0374065)
            pt_cmsPrelim.AddText("CMS Preliminary")

            pt_lumi = TPaveText(0.744361, 0.92928, 0.860902, 0.977667, "brNDC")
            pt_lumi.SetBorderSize(0)
            pt_lumi.SetFillStyle(0)
            pt_lumi.SetTextFont(42)
            pt_lumi.SetTextSize(0.0374065)
            pt_lumi.AddText(self._luminosityLabel)

            pt_leg = TPaveText(0.160401, 0.768657, 0.342105, 0.863184, "brNDC")
            pt_leg.SetBorderSize(0)
            pt_leg.SetFillStyle(0)
            pt_leg.SetTextFont(42)
            pt_leg.SetTextSize(0.0349127)
            pt_leg.SetTextAlign(12)
            if self._leg == "METLeg":
                legLabel = ""
                for filt in self._metHLTFilters[:-1]:
                    legLabel = legLabel + filt + ", "
                legLabel = legLabel + self._metHLTFilters[-1]
                pt_leg.AddText(legLabel)
                pt_leg.AddText(self._datasetLabel)
            if self._leg == "TrackLeg":
                pt_leg.AddText(self._path + "*")
                pt_leg.AddText(self._datasetLabel)
                legLabel = ""
                for filt in self._metHLTFilters[:-1]:
                    legLabel = legLabel + filt + ", "
                legLabel = legLabel + self._metHLTFilters[-1] + " applied"
                pt_leg.AddText(legLabel)
            if self._leg == "METPath":
                if self._path == "GrandOr":
                    pt_leg.AddText("OR of Signal Paths")
                else:
                    pt_leg.AddText(self._path + "*")
                pt_leg.AddText(self._datasetLabel)

            lumiLabel = TPaveText(0.66416, 0.937339, 0.962406, 0.992894, "brNDC")
            lumiLabel.SetBorderSize(0)
            lumiLabel.SetFillStyle(0)
            lumiLabel.SetTextFont(42)
            lumiLabel.SetTextSize(0.0387597)
            lumiLabel.AddText(str (self._luminosityLabel))

            oneLine = TLine(xlo, 1.0, xhi, 1.0)
            oneLine.SetLineWidth(3)
            oneLine.SetLineStyle(2)

            backgroundHist = TH1D("backgroundHist", "backgroundHist", 1, xlo, xhi)
            backgroundHist.GetYaxis().SetTitle("Trigger Efficiency")
            backgroundHist.GetYaxis().SetRangeUser(ylo, yhi)
            if self._leg == "METLeg" or self._leg == "METPath":
                backgroundHist.GetXaxis().SetTitle(self._metLegAxisTitle)
            elif self._leg == "TrackLeg":
                backgroundHist.GetXaxis().SetTitle(self._trackLegAxisTitle)

            SetStyle(backgroundHist)
            SetStyle(efficiencyGraph)

            self._canvas.cd()
            backgroundHist.Draw()
            efficiencyGraph.Draw("P")
            pt_cmsPrelim.Draw("same")
            pt_lumi.Draw("same")
            pt_leg.Draw("same")
            oneLine.Draw("same")

            if doFit:
                (fitFunc, fitText) = self.PlotFit(efficiencyGraph)
                fitFunc.Draw("same")
                fitText.Draw("same")

            if not os.path.exists('plots_' + self.Denominator["sample"]):
                os.mkdir('plots_' + self.Denominator["sample"])

            if self._leg == "METPath":
                self._canvas.SaveAs('plots_' + self.Denominator["sample"] + '/' + self._path + "_Efficiency.pdf")
            else:
                self._canvas.SaveAs('plots_' + self.Denominator["sample"] + '/' + self._path + "_" + self._leg + ".pdf")
            self._fout.cd()
            if self._tgraphSuffix is not None:
                efficiencyGraph.Write(self._path + "_" + self._leg + "_" + self._tgraphSuffix)
                if doFit:
                    fitFunc.Write(self._path + "_" + self._leg + "_" + self._tgraphSuffix + "_fitResult")
            else:
                efficiencyGraph.Write(self._path + "_" + self._leg)
                if doFit:
                    fitFunc.Write(self._path + "_" + self._leg + "_fitResult")

        else:
            print("Denominator and Numerator must be defined for path ", self._path, ", leg ", self._leg)
            return 0.0
Exemplo n.º 16
0
def make_mutefreq_plot(plotdir, gene_name, positions):
    nuke_colors = {
        'A': kRed + 1,
        'C': kBlue - 7,
        'G': kOrange - 3,
        'T': kGreen + 2
    }

    ibin = 0
    drawn_name_texts, lines, vlines, texts = {}, {}, {}, {}
    for info in positions:
        posname = info['name']

        # make label below bin
        drawn_name_texts[posname] = TPaveText(-0.5 + ibin, -0.1, 0.5 + ibin,
                                              -0.05)
        drawn_name_texts[posname].SetBorderSize(0)
        drawn_name_texts[posname].SetFillColor(0)
        drawn_name_texts[posname].SetFillStyle(0)
        drawn_name_texts[posname].AddText(-0.5 + ibin, -0.075,
                                          simplify_state_name(posname))

        total = 0.0
        lines[posname], vlines[posname], texts[posname] = [], [], []
        for nuke, prob in sorted(info['nuke_freqs'].items(),
                                 key=operator.itemgetter(1),
                                 reverse=True):
            # horizontal line at height total+prob
            lines[posname].append(
                TLine(-0.5 + ibin, total + prob, 0.5 + ibin, total + prob))
            lines[posname][-1].SetLineWidth(6)

            # vertical line from total to total+prob
            vlines[posname].append(TLine(ibin, total, ibin, total + prob))
            vlines[posname][-1].SetLineWidth(6)
            vlines[posname][-1].SetLineColor(nuke_colors[nuke])

            # write [ACGT] at midpoint between total and total+prob
            midpoint = 0.5 * (prob + 2 * total)
            texts[posname].append(
                TPaveText(-0.5 + ibin, midpoint - 0.04, 0.5 + ibin,
                          midpoint + 0.01))
            texts[posname][-1].AddText(-0.5 + ibin, midpoint, nuke)
            texts[posname][-1].SetBorderSize(0)
            texts[posname][-1].SetFillColor(0)
            texts[posname][-1].SetFillStyle(0)

            total += prob

        ibin += 1

    cvn = TCanvas('cvn-2', '', 1000, 300)
    n_bins = ibin
    hframe = TH1D(gene_name + '-emission-frame',
                  utils.unsanitize_name(gene_name), n_bins, -0.5, n_bins - 0.5)
    hframe.SetNdivisions(202, 'y')
    hframe.SetNdivisions(0, 'x')
    hframe.Draw()

    for state_name in lines.keys():
        drawn_name_texts[state_name].Draw()
        for itrans in range(len(lines[state_name])):
            # lines[state_name][itrans].Draw()  # hm, maybe don't need the horizontal lines any more
            vlines[state_name][itrans].Draw()
            # texts[state_name][itrans].Draw()  # don't label the bases at the moment, you can tell by the color just fine

    cvn.SaveAs(plotdir + '/plots/' + gene_name + '.png')
Exemplo n.º 17
0
#gPad.SetRightMargin(0.15)
h_theta_phi.GetZaxis().SetRangeUser(0, 1)

h_theta_phi.GetXaxis().SetRangeUser(60, 120)
h_theta_phi.GetYaxis().SetRangeUser(-90, -45)
h_theta_phi.SetMarkerSize(2.5)
gPad.SetBottomMargin(0.17)
gPad.SetLeftMargin(0.13)
gPad.SetTopMargin(0.15)
gPad.SetRightMargin(0.15)

h_theta_phi.GetYaxis().SetTitleSize(0.07)
h_theta_phi.GetXaxis().SetTitleSize(0.07)
h_theta_phi.GetYaxis().SetTitleOffset(0.8)

pt = TPaveText(0.13, 0.855, 0.42, 0.98, "ndc")
pt.AddText("MicroBooNE")
pt.SetFillColor(0)
pt.SetBorderSize(0)
pt.SetShadowColor(0)
h_theta_phi.Draw("colz texte")

pt.Draw()
h_theta_phi.SaveAs("plots/%s/e_theta_phi_%s.root" %
                   ("data" if data else "mc", algo))
c_theta_phi.SaveAs("plots/%s/e_theta_phi.pdf" % ("data" if data else "mc"))

c_theta_phi.Update()

c_theta_l = TCanvas("c_theta_l", "theta_l")
c_theta_l.cd()
Exemplo n.º 18
0
        fs.append(f / NN)
        f = 0.0
    #Average the final 100 values?
    avgs.append(np.mean(fs[len(fs) - 100:len(fs)]))

c1 = TCanvas()
tg = TGraph()

for i in xrange(len(avgs)):
    tg.SetPoint(i, i, avgs[i])

looks_minos()

tf = TF1("tf", "[0]*exp([1]*x)+[2]", 0, 10)
title = TPaveText(0.5014368, 0.7478814, 0.9022989, 0.8177966, "nbNDC")
title.SetFillColor(0)
title.SetFillStyle(0)
title.SetLineColor(0)

title.AddText("p0 exp(p1*n) + p2")

tg.SetMarkerStyle(6)
tg.Fit("tf")
gStyle.SetOptFit(1111)
tg.SetLineWidth(2)
tg.Draw("AL")
title.Draw("SAMES")

tg.GetYaxis().SetTitle("<#sigma_{x} #sigma_{y}>")
tg.GetXaxis().SetTitle("n")
Exemplo n.º 19
0
    logging.basicConfig(level=logging.INFO)

assert isfile(args.pulls_file)

import ROOT
from ROOT import TFile, TPaveText, gStyle, gROOT

tfile = TFile(args.pulls_file)

gStyle.SetOptStat(0)
gROOT.SetBatch()

#c1 = TCanvas("c1","Pull Shorter Version",200,10,800,800);
##c1.SetGrid();
#c1.DrawFrame(0.85,0.75,1.15,1.25);

nuisancs = tfile.Get('nuisancs')
nuisancs.Draw()

pt = TPaveText(.5, 1.7, 0.5 + args.label_width, 2.7)
if 'pulls_of_nuisances_both' in args.pulls_file:
    pt.AddText("both channels")
elif 'pulls_of_nuisances_mu' in args.pulls_file:
    pt.AddText("muon-tau channel")
else:
    pt.AddText("electron-tau channel")

pt.Draw("same")

nuisancs.SaveAs(args.pulls_file.replace('.root', '.png'))
Exemplo n.º 20
0
def drawhist(isMET, reg, dirPath):
    path_before = "analysis_histogram/2018_old/"
    path_after = "analysis_histogram/2018_hem_cut_updated/"

    if isMET:
        openfcomb = TFile(path_before + "combined_data_MET.root")
        openfAB = TFile(path_before + "combined_data_MET_AB.root")
        openfCD_bfr = TFile(path_before + "combined_data_MET_CD.root")
        openfCD = TFile(path_after + "combined_data_MET_CD.root")

        h_jet1phi_1b = []
        jet1phi_comb_top1b = openfcomb.Get("h_reg_TopmunuCR_1b_Jet1Phi")
        h_jet1phi_1b.append(jet1phi_comb_top1b)
        jet1phi_AB_top1b = openfAB.Get("h_reg_TopmunuCR_1b_Jet1Phi")
        h_jet1phi_1b.append(jet1phi_AB_top1b)
        jet1phi_CD_bfr_top1b = openfCD_bfr.Get("h_reg_TopmunuCR_1b_Jet1Phi")
        h_jet1phi_1b.append(jet1phi_CD_bfr_top1b)
        jet1phi_CD_top1b = openfCD.Get("h_reg_TopmunuCR_1b_Jet1Phi")
        h_jet1phi_1b.append(jet1phi_CD_top1b)

        h_jet1eta_1b = []
        jet1eta_comb_top1b = openfcomb.Get("h_reg_TopmunuCR_1b_Jet1Eta")
        h_jet1eta_1b.append(jet1eta_comb_top1b)
        jet1eta_AB_top1b = openfAB.Get("h_reg_TopmunuCR_1b_Jet1Eta")
        h_jet1eta_1b.append(jet1eta_AB_top1b)
        jet1eta_CD_bfr_top1b = openfCD_bfr.Get("h_reg_TopmunuCR_1b_Jet1Eta")
        h_jet1eta_1b.append(jet1eta_CD_bfr_top1b)
        jet1eta_CD_top1b = openfCD.Get("h_reg_TopmunuCR_1b_Jet1Eta")
        h_jet1eta_1b.append(jet1eta_CD_top1b)

        #h_MET_1b = []
        #MET_comb_top1b = openfcomb.Get("h_reg_TopmunuCR_1b_MET")
        #h_MET_1b.append(MET_comb_top1b)
        #MET_AB_top1b = openfAB.Get("h_reg_TopmunuCR_1b_MET")
        #h_MET_1b.append(MET_AB_top1b)
        #MET_CD_top1b = openfCD.Get("h_reg_TopmunuCR_1b_MET")
        #h_MET_1b.append(MET_CD_top1b)

        h_METphi_1b = []
        METphi_comb_top1b = openfcomb.Get("h_reg_TopmunuCR_1b_METPhi")
        h_METphi_1b.append(METphi_comb_top1b)
        METphi_AB_top1b = openfAB.Get("h_reg_TopmunuCR_1b_METPhi")
        h_METphi_1b.append(METphi_AB_top1b)
        METphi_CD_bfr_top1b = openfCD_bfr.Get("h_reg_TopmunuCR_1b_METPhi")
        h_METphi_1b.append(METphi_CD_bfr_top1b)
        METphi_CD_top1b = openfCD.Get("h_reg_TopmunuCR_1b_METPhi")
        h_METphi_1b.append(METphi_CD_top1b)

        h_RecoilPhi_1b = []
        RecoilPhi_comb_top1b = openfcomb.Get("h_reg_TopmunuCR_1b_RecoilPhi")
        h_RecoilPhi_1b.append(RecoilPhi_comb_top1b)
        RecoilPhi_AB_top1b = openfAB.Get("h_reg_TopmunuCR_1b_RecoilPhi")
        h_RecoilPhi_1b.append(RecoilPhi_AB_top1b)
        RecoilPhi_CD_bfr_top1b = openfCD_bfr.Get(
            "h_reg_TopmunuCR_1b_RecoilPhi")
        h_RecoilPhi_1b.append(RecoilPhi_CD_bfr_top1b)
        RecoilPhi_CD_top1b = openfCD.Get("h_reg_TopmunuCR_1b_RecoilPhi")
        h_RecoilPhi_1b.append(RecoilPhi_CD_top1b)

        h_jet1phi_2b = []
        jet1phi_comb_top2b = openfcomb.Get("h_reg_TopmunuCR_2b_Jet1Phi")
        h_jet1phi_2b.append(jet1phi_comb_top2b)
        jet1phi_AB_top2b = openfAB.Get("h_reg_TopmunuCR_2b_Jet1Phi")
        h_jet1phi_2b.append(jet1phi_AB_top2b)
        jet1phi_CD_bfr_top2b = openfCD_bfr.Get("h_reg_TopmunuCR_2b_Jet1Phi")
        h_jet1phi_2b.append(jet1phi_CD_bfr_top2b)
        jet1phi_CD_top2b = openfCD.Get("h_reg_TopmunuCR_2b_Jet1Phi")
        h_jet1phi_2b.append(jet1phi_CD_top2b)

        h_jet2phi_2b = []
        jet2phi_comb_top2b = openfcomb.Get("h_reg_TopmunuCR_2b_Jet2Phi")
        h_jet2phi_2b.append(jet2phi_comb_top2b)
        jet2phi_AB_top2b = openfAB.Get("h_reg_TopmunuCR_2b_Jet2Phi")
        h_jet2phi_2b.append(jet2phi_AB_top2b)
        jet2phi_CD_bfr_top2b = openfCD_bfr.Get("h_reg_TopmunuCR_2b_Jet2Phi")
        h_jet2phi_2b.append(jet2phi_CD_bfr_top2b)
        jet2phi_CD_top2b = openfCD.Get("h_reg_TopmunuCR_2b_Jet2Phi")
        h_jet2phi_2b.append(jet2phi_CD_top2b)

        h_jet1eta_2b = []
        jet1eta_comb_top2b = openfcomb.Get("h_reg_TopmunuCR_2b_Jet1Eta")
        h_jet1eta_2b.append(jet1eta_comb_top2b)
        jet1eta_AB_top2b = openfAB.Get("h_reg_TopmunuCR_2b_Jet1Eta")
        h_jet1eta_2b.append(jet1eta_AB_top2b)
        jet1eta_CD_bfr_top2b = openfCD_bfr.Get("h_reg_TopmunuCR_2b_Jet1Eta")
        h_jet1eta_2b.append(jet1eta_CD_bfr_top2b)
        jet1eta_CD_top2b = openfCD.Get("h_reg_TopmunuCR_2b_Jet1Eta")
        h_jet1eta_2b.append(jet1eta_CD_top2b)

        h_jet2eta_2b = []
        jet2eta_comb_top2b = openfcomb.Get("h_reg_TopmunuCR_2b_Jet2Eta")
        h_jet2eta_2b.append(jet2eta_comb_top2b)
        jet2eta_AB_top2b = openfAB.Get("h_reg_TopmunuCR_2b_Jet2Eta")
        h_jet2eta_2b.append(jet2eta_AB_top2b)
        jet2eta_CD_bfr_top2b = openfCD_bfr.Get("h_reg_TopmunuCR_2b_Jet2Eta")
        h_jet2eta_2b.append(jet2eta_CD_bfr_top2b)
        jet2eta_CD_top2b = openfCD.Get("h_reg_TopmunuCR_2b_Jet2Eta")
        h_jet2eta_2b.append(jet2eta_CD_top2b)

        #h_MET_2b = []
        #MET_comb_top2b = openfcomb.Get("h_reg_TopmunuCR_2b_MET")
        #h_MET_2b.append(MET_comb_top2b)
        #MET_AB_top2b = openfAB.Get("h_reg_TopmunuCR_2b_MET")
        #h_MET_2b.append(MET_AB_top2b)
        #MET_CD_top2b = openfCD.Get("h_reg_TopmunuCR_2b_MET")
        #h_MET_2b.append(MET_CD_top2b)

        h_METphi_2b = []
        METphi_comb_top2b = openfcomb.Get("h_reg_TopmunuCR_2b_METPhi")
        h_METphi_2b.append(METphi_comb_top2b)
        METphi_AB_top2b = openfAB.Get("h_reg_TopmunuCR_2b_METPhi")
        h_METphi_2b.append(METphi_AB_top2b)
        METphi_CD_bfr_top2b = openfCD_bfr.Get("h_reg_TopmunuCR_2b_METPhi")
        h_METphi_2b.append(METphi_CD_bfr_top2b)
        METphi_CD_top2b = openfCD.Get("h_reg_TopmunuCR_2b_METPhi")
        h_METphi_2b.append(METphi_CD_top2b)

        #h_RecoilPhi_2b = []
        #RecoilPhi_comb_top2b = openfcomb.Get("h_reg_TopmunuCR_2b_RecoilPhi")
        #h_RecoilPhi_2b.append(RecoilPhi_comb_top2b)
        #RecoilPhi_AB_top2b = openfAB.Get("h_reg_TopmunuCR_2b_RecoilPhi")
        #h_RecoilPhi_2b.append(RecoilPhi_AB_top2b)
        #RecoilPhi_CD_top2b = openfCD.Get("h_reg_TopmunuCR_2b_RecoilPhi")
        #h_RecoilPhi_2b.append(RecoilPhi_CD_top2b)

        alllist = []
        alllist.append(h_jet1phi_1b)
        #alllist.append(h_jet2phi_1b)
        alllist.append(h_jet1eta_1b)
        #alllist.append(h_jet2eta_1b)
        #alllist.append(h_MET_1b)
        alllist.append(h_METphi_1b)
        alllist.append(h_RecoilPhi_1b)
        alllist.append(h_jet1phi_2b)
        alllist.append(h_jet2phi_2b)
        alllist.append(h_jet1eta_2b)
        alllist.append(h_jet2eta_2b)
        #alllist.append(h_MET_2b)
        alllist.append(h_METphi_2b)
        #alllist.append(h_RecoilPhi_2b)

        #print "1", alllist, len(alllist)

    if not isMET:
        openfcomb = TFile(path_before + "combined_data_SE.root")
        openfcomb_aftr = TFile(path_after + "combined_data_SE.root")
        openfAB = TFile(path_before + "combined_data_SE_AB.root")
        openfAB_aftr = TFile(path_after + "combined_data_SE_AB.root")
        openfCD_bfr = TFile(path_before + "combined_data_SE_CD.root")
        openfCD = TFile(path_after + "combined_data_SE_CD.root")

        h_jet1phi_1b = []
        jet1phi_comb_top1b = openfcomb.Get("h_reg_TopenuCR_1b_Jet1Phi")
        h_jet1phi_1b.append(jet1phi_comb_top1b)

        jet1phi_comb_aftr_top1b = openfcomb_aftr.Get(
            "h_reg_TopenuCR_1b_Jet1Phi")
        h_jet1phi_1b.append(jet1phi_comb_aftr_top1b)

        jet1phi_AB_top1b = openfAB.Get("h_reg_TopenuCR_1b_Jet1Phi")
        h_jet1phi_1b.append(jet1phi_AB_top1b)

        jet1phi_AB_aftr_top1b = openfAB_aftr.Get("h_reg_TopenuCR_1b_Jet1Phi")
        h_jet1phi_1b.append(jet1phi_AB_aftr_top1b)

        jet1phi_CD_bfr_top1b = openfCD_bfr.Get("h_reg_TopenuCR_1b_Jet1Phi")
        h_jet1phi_1b.append(jet1phi_CD_bfr_top1b)

        jet1phi_CD_top1b = openfCD.Get("h_reg_TopenuCR_1b_Jet1Phi")
        h_jet1phi_1b.append(jet1phi_CD_top1b)

        h_jet1eta_1b = []
        jet1eta_comb_top1b = openfcomb.Get("h_reg_TopenuCR_1b_Jet1Eta")
        h_jet1eta_1b.append(jet1eta_comb_top1b)

        jet1eta_comb_aftr_top1b = openfcomb_aftr.Get(
            "h_reg_TopenuCR_1b_Jet1Eta")
        h_jet1eta_1b.append(jet1eta_comb_aftr_top1b)

        jet1eta_AB_top1b = openfAB.Get("h_reg_TopenuCR_1b_Jet1Eta")
        h_jet1eta_1b.append(jet1eta_AB_top1b)

        jet1eta_AB_aftr_top1b = openfAB_aftr.Get("h_reg_TopenuCR_1b_Jet1Eta")
        h_jet1eta_1b.append(jet1eta_AB_aftr_top1b)

        jet1eta_CD_bfr_top1b = openfCD_bfr.Get("h_reg_TopenuCR_1b_Jet1Eta")
        h_jet1eta_1b.append(jet1eta_CD_bfr_top1b)

        jet1eta_CD_top1b = openfCD.Get("h_reg_TopenuCR_1b_Jet1Eta")
        h_jet1eta_1b.append(jet1eta_CD_top1b)

        h_MET_1b = []
        MET_comb_top1b = openfcomb.Get("h_reg_TopenuCR_1b_MET")
        h_MET_1b.append(MET_comb_top1b)

        MET_comb_aftr_top1b = openfcomb_aftr.Get("h_reg_TopenuCR_1b_MET")
        h_MET_1b.append(MET_comb_aftr_top1b)

        MET_AB_top1b = openfAB.Get("h_reg_TopenuCR_1b_MET")
        h_MET_1b.append(MET_AB_top1b)

        MET_AB_aftr_top1b = openfAB_aftr.Get("h_reg_TopenuCR_1b_MET")
        h_MET_1b.append(MET_AB_aftr_top1b)

        MET_CD_bfr_top1b = openfCD_bfr.Get("h_reg_TopenuCR_1b_MET")
        h_MET_1b.append(MET_CD_bfr_top1b)

        MET_CD_top1b = openfCD.Get("h_reg_TopenuCR_1b_MET")
        h_MET_1b.append(MET_CD_top1b)

        h_METphi_1b = []
        METphi_comb_top1b = openfcomb.Get("h_reg_TopenuCR_1b_METPhi")
        h_METphi_1b.append(METphi_comb_top1b)

        METphi_comb_aftr_top1b = openfcomb_aftr.Get("h_reg_TopenuCR_1b_METPhi")
        h_METphi_1b.append(METphi_comb_aftr_top1b)

        METphi_AB_top1b = openfAB.Get("h_reg_TopenuCR_1b_METPhi")
        h_METphi_1b.append(METphi_AB_top1b)

        METphi_AB_aftr_top1b = openfAB_aftr.Get("h_reg_TopenuCR_1b_METPhi")
        h_METphi_1b.append(METphi_AB_aftr_top1b)

        METphi_CD_bfr_top1b = openfCD_bfr.Get("h_reg_TopenuCR_1b_METPhi")
        h_METphi_1b.append(METphi_CD_bfr_top1b)

        METphi_CD_top1b = openfCD.Get("h_reg_TopenuCR_1b_METPhi")
        h_METphi_1b.append(METphi_CD_top1b)

        h_Recoil_1b = []
        Recoil_comb_top1b = openfcomb.Get("h_reg_TopenuCR_1b_Recoil")
        h_Recoil_1b.append(Recoil_comb_top1b)

        Recoil_comb_aftr_top1b = openfcomb_aftr.Get("h_reg_TopenuCR_1b_Recoil")
        h_Recoil_1b.append(Recoil_comb_aftr_top1b)

        Recoil_AB_top1b = openfAB.Get("h_reg_TopenuCR_1b_Recoil")
        h_Recoil_1b.append(Recoil_AB_top1b)

        Recoil_AB_aftr_top1b = openfAB_aftr.Get("h_reg_TopenuCR_1b_Recoil")
        h_Recoil_1b.append(Recoil_AB_aftr_top1b)

        Recoil_CD_bfr_top1b = openfCD_bfr.Get("h_reg_TopenuCR_1b_Recoil")
        h_Recoil_1b.append(Recoil_CD_bfr_top1b)

        Recoil_CD_top1b = openfCD.Get("h_reg_TopenuCR_1b_Recoil")
        h_Recoil_1b.append(Recoil_CD_top1b)

        h_RecoilPhi_1b = []
        RecoilPhi_comb_top1b = openfcomb.Get("h_reg_TopenuCR_1b_RecoilPhi")
        h_RecoilPhi_1b.append(RecoilPhi_comb_top1b)

        RecoilPhi_comb_aftr_top1b = openfcomb_aftr.Get(
            "h_reg_TopenuCR_1b_RecoilPhi")
        h_RecoilPhi_1b.append(RecoilPhi_comb_aftr_top1b)

        RecoilPhi_AB_top1b = openfAB.Get("h_reg_TopenuCR_1b_RecoilPhi")
        h_RecoilPhi_1b.append(RecoilPhi_AB_top1b)

        RecoilPhi_AB_aftr_top1b = openfAB_aftr.Get(
            "h_reg_TopenuCR_1b_RecoilPhi")
        h_RecoilPhi_1b.append(RecoilPhi_AB_aftr_top1b)

        RecoilPhi_CD_bfr_top1b = openfCD_bfr.Get("h_reg_TopenuCR_1b_RecoilPhi")
        h_RecoilPhi_1b.append(RecoilPhi_CD_bfr_top1b)

        RecoilPhi_CD_top1b = openfCD.Get("h_reg_TopenuCR_1b_RecoilPhi")
        h_RecoilPhi_1b.append(RecoilPhi_CD_top1b)

        h_jet1phi_2b = []
        jet1phi_comb_top2b = openfcomb.Get("h_reg_TopenuCR_2b_Jet1Phi")
        h_jet1phi_2b.append(jet1phi_comb_top2b)

        jet1phi_comb_aftr_top2b = openfcomb_aftr.Get(
            "h_reg_TopenuCR_2b_Jet1Phi")
        h_jet1phi_2b.append(jet1phi_comb_aftr_top2b)

        jet1phi_AB_top2b = openfAB.Get("h_reg_TopenuCR_2b_Jet1Phi")
        h_jet1phi_2b.append(jet1phi_AB_top2b)

        jet1phi_AB_aftr_top2b = openfAB_aftr.Get("h_reg_TopenuCR_2b_Jet1Phi")
        h_jet1phi_2b.append(jet1phi_AB_aftr_top2b)

        jet1phi_CD_bfr_top2b = openfCD_bfr.Get("h_reg_TopenuCR_2b_Jet1Phi")
        h_jet1phi_2b.append(jet1phi_CD_bfr_top2b)

        jet1phi_CD_top2b = openfCD.Get("h_reg_TopenuCR_2b_Jet1Phi")
        h_jet1phi_2b.append(jet1phi_CD_top2b)

        h_jet2phi_2b = []
        jet2phi_comb_top2b = openfcomb.Get("h_reg_TopenuCR_2b_Jet2Phi")
        h_jet2phi_2b.append(jet2phi_comb_top2b)

        jet2phi_comb_aftr_top2b = openfcomb_aftr.Get(
            "h_reg_TopenuCR_2b_Jet2Phi")
        h_jet2phi_2b.append(jet2phi_comb_aftr_top2b)

        jet2phi_AB_top2b = openfAB.Get("h_reg_TopenuCR_2b_Jet2Phi")
        h_jet2phi_2b.append(jet2phi_AB_top2b)

        jet2phi_AB_aftr_top2b = openfAB_aftr.Get("h_reg_TopenuCR_2b_Jet2Phi")
        h_jet2phi_2b.append(jet2phi_AB_aftr_top2b)

        jet2phi_CD_bfr_top2b = openfCD_bfr.Get("h_reg_TopenuCR_2b_Jet2Phi")
        h_jet2phi_2b.append(jet2phi_CD_bfr_top2b)

        jet2phi_CD_top2b = openfCD.Get("h_reg_TopenuCR_2b_Jet2Phi")
        h_jet2phi_2b.append(jet2phi_CD_top2b)

        h_jet1eta_2b = []
        jet1eta_comb_top2b = openfcomb.Get("h_reg_TopenuCR_2b_Jet1Eta")
        h_jet1eta_2b.append(jet1eta_comb_top2b)

        jet1eta_comb_aftr_top2b = openfcomb_aftr.Get(
            "h_reg_TopenuCR_2b_Jet1Eta")
        h_jet1eta_2b.append(jet1eta_comb_aftr_top2b)

        jet1eta_AB_top2b = openfAB.Get("h_reg_TopenuCR_2b_Jet1Eta")
        h_jet1eta_2b.append(jet1eta_AB_top2b)

        jet1eta_AB_aftr_top2b = openfAB_aftr.Get("h_reg_TopenuCR_2b_Jet1Eta")
        h_jet1eta_2b.append(jet1eta_AB_aftr_top2b)

        jet1eta_CD_bfr_top2b = openfCD_bfr.Get("h_reg_TopenuCR_2b_Jet1Eta")
        h_jet1eta_2b.append(jet1eta_CD_bfr_top2b)

        jet1eta_CD_top2b = openfCD.Get("h_reg_TopenuCR_2b_Jet1Eta")
        h_jet1eta_2b.append(jet1eta_CD_top2b)

        h_jet2eta_2b = []
        jet2eta_comb_top2b = openfcomb.Get("h_reg_TopenuCR_2b_Jet2Eta")
        h_jet2eta_2b.append(jet2eta_comb_top2b)

        jet2eta_comb_aftr_top2b = openfcomb_aftr.Get(
            "h_reg_TopenuCR_2b_Jet2Eta")
        h_jet2eta_2b.append(jet2eta_comb_aftr_top2b)

        jet2eta_AB_top2b = openfAB.Get("h_reg_TopenuCR_2b_Jet2Eta")
        h_jet2eta_2b.append(jet2eta_AB_top2b)

        jet2eta_AB_aftr_top2b = openfAB_aftr.Get("h_reg_TopenuCR_2b_Jet2Eta")
        h_jet2eta_2b.append(jet2eta_AB_aftr_top2b)

        jet2eta_CD_bfr_top2b = openfCD_bfr.Get("h_reg_TopenuCR_2b_Jet2Eta")
        h_jet2eta_2b.append(jet2eta_CD_bfr_top2b)

        jet2eta_CD_top2b = openfCD.Get("h_reg_TopenuCR_2b_Jet2Eta")
        h_jet2eta_2b.append(jet2eta_CD_top2b)

        h_MET_2b = []
        MET_comb_top2b = openfcomb.Get("h_reg_TopenuCR_2b_MET")
        h_MET_2b.append(MET_comb_top2b)

        MET_comb_aftr_top2b = openfcomb_aftr.Get("h_reg_TopenuCR_2b_MET")
        h_MET_2b.append(MET_comb_aftr_top2b)

        MET_AB_top2b = openfAB.Get("h_reg_TopenuCR_2b_MET")
        h_MET_2b.append(MET_AB_top2b)

        MET_AB_aftr_top2b = openfAB_aftr.Get("h_reg_TopenuCR_2b_MET")
        h_MET_2b.append(MET_AB_aftr_top2b)

        MET_CD_bfr_top2b = openfCD_bfr.Get("h_reg_TopenuCR_2b_MET")
        h_MET_2b.append(MET_CD_bfr_top2b)

        MET_CD_top2b = openfCD.Get("h_reg_TopenuCR_2b_MET")
        h_MET_2b.append(MET_CD_top2b)

        h_METphi_2b = []
        METphi_comb_top2b = openfcomb.Get("h_reg_TopenuCR_2b_METPhi")
        h_METphi_2b.append(METphi_comb_top2b)

        METphi_comb_aftr_top2b = openfcomb_aftr.Get("h_reg_TopenuCR_2b_METPhi")
        h_METphi_2b.append(METphi_comb_aftr_top2b)

        METphi_AB_top2b = openfAB.Get("h_reg_TopenuCR_2b_METPhi")
        h_METphi_2b.append(METphi_AB_top2b)

        METphi_AB_aftr_top2b = openfAB_aftr.Get("h_reg_TopenuCR_2b_METPhi")
        h_METphi_2b.append(METphi_AB_aftr_top2b)

        METphi_CD_bfr_top2b = openfCD_bfr.Get("h_reg_TopenuCR_2b_METPhi")
        h_METphi_2b.append(METphi_CD_bfr_top2b)

        METphi_CD_top2b = openfCD.Get("h_reg_TopenuCR_2b_METPhi")
        h_METphi_2b.append(METphi_CD_top2b)

        h_Recoil_2b = []
        Recoil_comb_top2b = openfcomb.Get("h_reg_TopenuCR_2b_Recoil")
        h_Recoil_2b.append(Recoil_comb_top2b)

        Recoil_comb_aftr_top2b = openfcomb_aftr.Get("h_reg_TopenuCR_2b_Recoil")
        h_Recoil_2b.append(Recoil_comb_aftr_top2b)

        Recoil_AB_top2b = openfAB.Get("h_reg_TopenuCR_2b_Recoil")
        h_Recoil_2b.append(Recoil_AB_top2b)

        Recoil_AB_aftr_top2b = openfAB_aftr.Get("h_reg_TopenuCR_2b_Recoil")
        h_Recoil_2b.append(Recoil_AB_aftr_top2b)

        Recoil_CD_bfr_top2b = openfCD_bfr.Get("h_reg_TopenuCR_2b_Recoil")
        h_Recoil_2b.append(Recoil_CD_bfr_top2b)

        Recoil_CD_top2b = openfCD.Get("h_reg_TopenuCR_2b_Recoil")
        h_Recoil_2b.append(Recoil_CD_top2b)

        h_RecoilPhi_2b = []
        RecoilPhi_comb_top2b = openfcomb.Get("h_reg_TopenuCR_2b_RecoilPhi")
        h_RecoilPhi_2b.append(RecoilPhi_comb_top2b)

        RecoilPhi_comb_aftr_top2b = openfcomb_aftr.Get(
            "h_reg_TopenuCR_2b_RecoilPhi")
        h_RecoilPhi_2b.append(RecoilPhi_comb_aftr_top2b)

        RecoilPhi_AB_top2b = openfAB.Get("h_reg_TopenuCR_2b_RecoilPhi")
        h_RecoilPhi_2b.append(RecoilPhi_AB_top2b)

        RecoilPhi_AB_aftr_top2b = openfAB_aftr.Get(
            "h_reg_TopenuCR_2b_RecoilPhi")
        h_RecoilPhi_2b.append(RecoilPhi_AB_aftr_top2b)

        RecoilPhi_CD_bfr_top2b = openfCD_bfr.Get("h_reg_TopenuCR_2b_RecoilPhi")
        h_RecoilPhi_2b.append(RecoilPhi_CD_bfr_top2b)

        RecoilPhi_CD_top2b = openfCD.Get("h_reg_TopenuCR_2b_RecoilPhi")
        h_RecoilPhi_2b.append(RecoilPhi_CD_top2b)

        alllist = []
        alllist.append(h_jet1phi_1b)
        alllist.append(h_jet1eta_1b)
        alllist.append(h_MET_1b)
        alllist.append(h_METphi_1b)
        alllist.append(h_Recoil_1b)
        alllist.append(h_RecoilPhi_1b)
        alllist.append(h_jet1phi_2b)
        alllist.append(h_jet2phi_2b)
        alllist.append(h_jet1eta_2b)
        alllist.append(h_jet2eta_2b)
        alllist.append(h_MET_2b)
        alllist.append(h_METphi_2b)
        alllist.append(h_Recoil_2b)
        alllist.append(h_RecoilPhi_2b)

        #print "2", alllist, len(alllist)

    effectMET_ABCD_1b = effect(h_Pre=MET_comb_top1b,
                               h_Post=MET_comb_aftr_top1b)
    print "HEM effect on MET of Topenu 1b ABCD:", effectMET_ABCD_1b, "%"
    print " "
    effectMET_AB_1b = effect(h_Pre=MET_AB_top1b, h_Post=MET_AB_aftr_top1b)
    print "HEM effect on MET of Topenu 1b AB:", effectMET_AB_1b, "%"
    print " "
    effectMET_CD_1b = effect(h_Pre=MET_CD_bfr_top1b, h_Post=MET_CD_top1b)
    print "HEM effect on MET of Topenu 1b CD:", effectMET_CD_1b, "%"
    print " "

    c = PlotTemplates.myCanvas()
    gPad.GetUymax()
    gPad.SetLogy()
    gStyle.SetOptStat(0)
    gStyle.SetOptTitle(0)

    leg = PlotTemplates.SetLegend(coordinate_=[.37, .76, .78, .9], ncol=2)
    leg.SetTextSize(0.017)

    xAxisName = [
        "Jet1 #phi", "Jet1 #eta", "MET (GeV)", "MET #phi", "Recoil (GeV)",
        "Recoil #phi", "Jet1 #phi", "Jet2 #phi", "Jet1 #eta", "Jet2 #eta",
        "MET (GeV)", "MET #phi", "Recoil (GeV)", "Recoil #phi"
    ]

    color = [1, 2, 4, 3, 6, 28]
    color_bfr = [1, 4, 6]
    legendName = [
        "2018 ABCD (Before HEM Veto)", "2018 ABCD (After HEM Veto)",
        "2018 AB (Before HEM Veto)", "2018 AB (After HEM Veto)",
        "2018 CD (Before HEM Veto)", "2018 CD (After HEM Veto)"
    ]
    legendName_bfr = ["2018 ABCD", "2018 AB", "2018 CD"]

    for i in range(len(alllist)):
        leg.Clear()
        if (i == 2) or (i == 4) or (i == 10) or (i == 12):
            h = alllist[i]

            for j in range(len(h)):
                h[j].SetLineWidth(3)
                #h[j].SetMarkerStyle(20)
                #h[j].SetMarkerSize(0.5)
                h[j].SetLineColor(color[j])
                #h[j].SetMarkerColor(color[j])
                h[j].GetXaxis().SetTitle(xAxisName[i])
                h[j].GetYaxis().SetTitle("Events/Bin")
                leg.AddEntry(h[j], legendName[j])
                #h[j].Draw("histsame")
                #leg.Draw()

        else:
            h = alllist[i]

            #print i, "x-axis :", h[0].GetNbinsX(), h[0].GetXaxis().GetBinLowEdge(1)

            for j in range(len(h)):
                h[j].Scale(1 / h[j].Integral())
                h[j].SetLineWidth(3)
                #h[j].SetMarkerStyle(20)
                #h[j].SetMarkerSize(0.5)
                h[j].SetLineColor(color[j])
                #h[j].SetMarkerColor(color[j])
                h[j].GetXaxis().SetTitle(xAxisName[i])
                h[j].GetYaxis().SetTitle("Events/Bin")
                leg.AddEntry(h[j], legendName[j])
                #h[j].Draw("histsame")
                #leg.Draw()

        h[0].Draw("hist")
        h[1].Draw("histsame")
        h[2].Draw("histsame")
        h[3].Draw("histsame")
        h[4].Draw("histsame")
        h[5].Draw("histsame")
        leg.Draw()

        energy = PlotTemplates.drawenergy(is2017=False)
        for k in energy:
            k.Draw()

        pavetxt = [
            "Top (e#nu) + 1b CR", "Top (e#nu) + 1b CR", "Top (e#nu) + 1b CR",
            "Top (e#nu) + 1b CR", "Top (e#nu) + 1b CR", "Top (e#nu) + 1b CR",
            "Top (e#nu) + 2b CR", "Top (e#nu) + 2b CR", "Top (e#nu) + 2b CR",
            "Top (e#nu) + 2b CR", "Top (e#nu) + 2b CR", "Top (e#nu) + 2b CR",
            "Top (e#nu) + 2b CR", "Top (e#nu) + 2b CR"
        ]

        pt = TPaveText(0.2177181, 0.855, 0.4540537, 0.885, "brNDC")
        pt.SetBorderSize(0)
        pt.SetTextAlign(12)
        pt.SetFillStyle(0)
        pt.SetTextFont(52)
        pt.AddText(pavetxt[i])
        pt.Draw()

        name = [
            "_1b_jet1phi", "_1b_jet1eta", "_1b_MET", "_1b_METphi",
            "_1b_Recoil", "_1b_Recoilphi", "_2b_jet1phi", "_2b_jet2phi",
            "_2b_jet1eta", "_2b_jet2eta", "_2b_MET", "_2b_METphi",
            "_2b_Recoil", "_2b_RecoilPhi"
        ]

        c.Update()

        dt = datetime.now()
        dt_str = dt.strftime("%Y%m%d_%H%M")

        subdirPath = dirPath + "/" + reg + "_" + dt_str
        if not (os.path.exists(subdirPath)):
            os.mkdir(subdirPath)
        dirPDF = subdirPath + "/pdf"
        dirPNG = subdirPath + "/png"
        if not (os.path.exists(dirPDF)):
            os.mkdir(dirPDF)
        if not (os.path.exists(dirPNG)):
            os.mkdir(dirPNG)

        c.SaveAs(dirPDF + "/" + reg + name[i] + "_new.pdf")
        c.SaveAs(dirPNG + "/" + reg + name[i] + "_new.png")
Exemplo n.º 21
0
def makePlots():

    # gROOT.SetStyle('Plain') # white background
    # gStyle.SetOptStat(222211)

    ROOT.gROOT.ProcessLine('.L ../tdrstyle.C')
    ROOT.gROOT.Reset()
    ROOT.gROOT.ProcessLine('setTDRStyle()')  #Set CMS TDR style

    inputFile = TFile(output_name + '.root', 'READ')

    histos_SR1 = dict()
    histos_SR2 = dict()
    histos_LSB = dict()
    histos_RSB = dict()
    histos_MC = dict()

    keys = [
        'photon_pt', 'photon_eta', 'dimuon_pt', 'dimuon_rapidity', 'chib_pt'
    ]

    for key in keys:
        histos_SR1[key] = inputFile.Get(key + '_SR1')
        histos_SR2[key] = inputFile.Get(key + '_SR2')
        histos_LSB[key] = inputFile.Get(key + '_LSB')
        histos_RSB[key] = inputFile.Get(key + '_RSB')
        histos_MC[key] = inputFile.Get(key + '_MC')

    titles = dict(
        photon_pt='photon E_{T};E_{T}(#gamma) [GeV];Entries / 100 MeV',
        photon_eta='photon_eta;#eta(#gamma);Entries / 0.05',
        dimuon_pt='#Upsilon p_{T};p_{T}(#Upsilon) [GeV];Entries / GeV',
        dimuon_rapidity='#Upsilon rapidity(#Upsilon);y(#Upsilon);Entries / 0.1',
        chib_pt='#chi_{b} p_{T};p_{T}(#chi_{b}) [GeV];Entries / GeV',
    )

    titles_chib = dict(
        photon_pt='photon E_{T};E_{T}(#gamma) [GeV];A.U.',
        photon_eta='photon_eta;#eta(#gamma);A.U.',
        dimuon_pt='#Upsilon p_{T};p_{T}(#Upsilon) [GeV];A.U.',
        dimuon_rapidity='#Upsilon rapidity(#Upsilon);y(#Upsilon);A.U.',
        chib_pt='#chi_{b} p_{T};p_{T}(#chi_{b}) [GeV];A.U.',
    )

    logY = dict(
        photon_pt=0,
        photon_eta=0,
        dimuon_pt=0,
        dimuon_rapidity=0,
        chib_pt=0,
    )

    maxY = dict(
        photon_pt=750,
        photon_eta=350,
        dimuon_pt=800,
        dimuon_rapidity=400,
        chib_pt=800,
    )

    integralData1 = histos_SR1[keys[0]].Integral()
    integralData2 = histos_SR2[keys[0]].Integral()
    integralData = integralData1 + integralData2

    for histo in histos_LSB.values() + histos_RSB.values() + histos_MC.values(
    ):
        if (histo.Integral() != 0):
            histo.Scale(1. / histo.Integral())
            histo.Rebin(3)
    for histo in histos_SR1.values() + histos_SR2.values():
        histo.Rebin(3)

    fBG = 0.48  #0.28
    fLSB = 0.5

    histos_BG = dict()
    for key in keys:
        histos_BG[key] = histos_RSB[key].Clone()
        histos_BG[key].SetNameTitle(key + '_BG', 'bgd from side-bands')
        histos_BG[key].Scale(1 - fLSB)
        histos_BG[key].Add(histos_LSB[key], fLSB)

    histos_Signal1 = dict()
    histos_Signal2 = dict()
    histos_Signal = dict()
    histos_SR = dict()
    for key in keys:
        histos_Signal1[key] = histos_SR1[key].Clone()
        histos_Signal1[key].SetNameTitle(key + '_signal1', 'Signal1')
        histos_Signal1[key].Add(histos_BG[key], -1 * integralData1 * fBG)

        histos_Signal2[key] = histos_SR2[key].Clone()
        histos_Signal2[key].SetNameTitle(key + '_signal2', 'Signal2')
        histos_Signal2[key].Add(histos_BG[key], -1 * integralData2 * fBG)

        histos_Signal[key] = histos_Signal1[key].Clone()
        histos_Signal[key].Add(histos_Signal2[key])
        histos_Signal[key].SetNameTitle(key + '_signal', 'data bkg-subtracted')

        histos_SR[key] = histos_SR1[key].Clone()
        histos_SR[key].Add(histos_SR2[key])
        histos_SR[key].SetNameTitle(key + '_SR', 'data')

    for histo in histos_Signal.values() + histos_BG.values():
        if (histo.Integral() != 0):
            histo.Scale(1. / histo.Integral())

    # Normalize SR to their original value, MC to be comparable with signal background-subtracted and background such that Signal+background = SR
    for histo in histos_MC.values():
        histo.Scale(integralData * (1 - fBG))
    for histo in histos_BG.values():
        histo.Scale(integralData * fBG)
    for histo in histos_LSB.values():
        histo.Scale(integralData * fBG * fLSB)
    for histo in histos_RSB.values():
        histo.Scale(integralData * fBG * (1 - fLSB))

    chi2Prob = dict()
    kolmogorovProb = dict()
    h_ratio = dict()
    for key in histos_Signal.keys():
        h_ratio[key] = histos_SR[key].Clone()
        histo_sum_MC_BG = histos_MC[key].Clone()
        histo_sum_MC_BG.Add(histos_BG[key])
        h_ratio[key].Divide(histo_sum_MC_BG)
        h_ratio[key].SetNameTitle(key + '_ratio', titles[key])
        h_ratio[key].SetMarkerStyle(20)
        h_ratio[key].SetMarkerSize(1)
        h_ratio[key].GetYaxis().SetLabelSize(0.18)
        h_ratio[key].GetYaxis().SetTitle('DATA/MC')
        h_ratio[key].GetYaxis().SetTitleSize(0.22)
        h_ratio[key].GetYaxis().SetTitleOffset(0.2)
        h_ratio[key].GetYaxis().SetNdivisions(005)
        h_ratio[key].GetXaxis().SetLabelSize(0.16)
        h_ratio[key].GetXaxis().SetTitleSize(0.16)
        h_ratio[key].SetMaximum(1.5)
        h_ratio[key].SetMinimum(0.667)
        chi2Prob[key] = histos_SR[key].Chi2Test(
            histo_sum_MC_BG)  #, 'UW')#, 'NORM')
        kolmogorovProb[key] = histos_SR[key].KolmogorovTest(histo_sum_MC_BG)

    for histo in histos_SR.values():
        histo.SetLineColor(ROOT.kBlack)
        histo.SetLineWidth(2)
        histo.SetMarkerColor(ROOT.kBlack)
        histo.SetMarkerStyle(20)

    for histo in histos_SR1.values() + histos_Signal1.values():
        histo.SetLineColor(ROOT.kBlue)
        histo.SetLineWidth(2)
        histo.SetMarkerColor(ROOT.kBlue)
        histo.SetMarkerStyle(22)

    for histo in histos_SR2.values() + histos_Signal2.values():
        histo.SetLineColor(ROOT.kRed)
        histo.SetLineWidth(2)
        histo.SetMarkerColor(ROOT.kRed)
        histo.SetMarkerStyle(23)

    for histo in histos_Signal.values():
        histo.SetLineColor(ROOT.kBlack)
        histo.SetLineWidth(2)
        # histo.SetMarkerColor(ROOT.kBlack)
        # histo.SetMarkerStyle(21)

    for histo in histos_BG.values():
        histo.SetLineColor(ROOT.kRed)
        histo.SetLineWidth(2)
        histo.SetFillColor(ROOT.kRed)
        # histo.SetMarkerColor(ROOT.kRed)
        # histo.SetMarkerStyle(22)

    # for histo in histos_RSB.values():
    #     histo.SetLineColor(ROOT.kViolet)
    #     histo.SetLineWidth(2)

    for histo in histos_MC.values():
        histo.SetLineColor(ROOT.kBlue)
        histo.SetLineWidth(2)
        histo.SetFillColor(ROOT.kBlue)
        # histo.SetMarkerColor(ROOT.kBlue)
        # histo.SetMarkerStyle(20)

    outputFile = TFile(output_name + '_plots.root', 'RECREATE')
    for histo in histos_Signal.values() + histos_MC.values(
    ) + histos_BG.values() + histos_SR.values():
        histo.Write()
    outputFile.Close()

    canvas = TCanvas("canvas", "canvas")
    canvas.Print(outputFile_name + "[")  #apre file .ps

    for key in keys:
        pad1 = TPad("pad1", "The pad 80% of the height", 0.0, 0.2, 1.0, 1.0)
        pad1.cd()
        pad1.SetLogy(logY[key])
        hs = THStack('hs', titles[key])
        #hs.Add(histos_SR[key])
        #hs.Add(histos_Signal[key])
        hs.Add(histos_BG[key])
        hs.Add(histos_MC[key])
        #hs.Add(histos_LSB[key])
        #hs.Add(histos_RSB[key])
        #maxHisto = max(hs.GetMaximum(), histos_SR[key].GetMaximum())
        hs.SetMaximum(maxY[key])  #maxHisto)
        hs.Draw('HIST')
        histos_SR[key].Draw('same')
        leg = pad1.BuildLegend(.65, .93, .95, .7)
        leg.SetFillStyle(0)
        leg.SetBorderSize(0)
        leg.Draw("SAME")
        pad2 = TPad("pad2", "The pad 20% of the height", 0.0, 0.01, 1.0, 0.2)
        pad2.cd()
        h_ratio[key].Draw()
        xmin = h_ratio[key].GetBinLowEdge(1)
        xmax = h_ratio[key].GetBinLowEdge(
            h_ratio[key].GetNbinsX()) + h_ratio[key].GetBinWidth(
                h_ratio[key].GetNbinsX())
        line0 = TLine(xmin, 1, xmax, 1)
        line0.SetLineColor(ROOT.kBlue)
        line0.SetLineWidth(2)
        line0.Draw('same')
        canvas.cd()
        pad1.Draw()
        pad2.Draw()
        canvas.Update()
        canvas.Print(outputFile_name)
        canvas.Print('plots/' + key + '_' + mc_ptSpectrum + '.png')
        canvas.Print('plots/' + key + '_' + mc_ptSpectrum + '.pdf')
        canvas.Print('plots/' + key + '_' + mc_ptSpectrum + '.root')

        # Make comparisison between chib1 and chib2
        histos_SR1[key].Scale(1. / histos_SR1[key].Integral())
        histos_SR2[key].Scale(1. / histos_SR2[key].Integral())
        histos_Signal1[key].Scale(1. / histos_Signal1[key].Integral())
        histos_Signal2[key].Scale(1. / histos_Signal2[key].Integral())
        # histos_SR1[key].Rebin(3)
        # histos_SR2[key].Rebin(3)
        # histos_Signal1[key].Rebin(3)
        # histos_Signal2[key].Rebin(3)
        hsc = THStack('hsc', titles_chib[key])
        hsc.Add(histos_Signal1[key])
        hsc.Add(histos_Signal2[key])
        #hsc.SetMaximum(maxY[key])
        hsc.Draw('nostack')
        legc = canvas.BuildLegend(.65, .93, .95, .7)
        legc.SetFillStyle(0)
        legc.SetBorderSize(0)
        legc.Draw("SAME")
        print 'kolmogorov prob SR     ' + key + ' ' + str(
            histos_SR1[key].KolmogorovTest(histos_SR2[key]))
        print 'kolmogorov prob Signal ' + key + ' ' + str(
            histos_Signal1[key].KolmogorovTest(histos_Signal2[key]))
        cfr = 2 if key not in ['dimuon_pt', 'chib_pt'] else 5
        kolmogorovProb_chi = round(
            histos_Signal1[key].KolmogorovTest(histos_Signal2[key]), cfr)
        pvtxt = TPaveText(.2, .0, 0.5, 0.1, "NDC")
        pvtxt.SetFillStyle(0)
        pvtxt.SetBorderSize(0)
        pvtxt.SetTextSize(0.04)
        pvtxt.AddText('Kolmogorov prob = ' + str(kolmogorovProb_chi))
        pvtxt.Draw()
        canvas.Update()
        canvas.Print(outputFile_name)
        canvas.Print('plots/' + key + '_' + mc_ptSpectrum + '_comparison' +
                     '.png')
        canvas.Print('plots/' + key + '_' + mc_ptSpectrum + '_comparison' +
                     '.pdf')
        canvas.Print('plots/' + key + '_' + mc_ptSpectrum + '_comparison' +
                     '.root')

    canvas.Clear()
    canvas.Print(outputFile_name + "]")  #chiude file .ps

    for key in keys:
        print '\n'
        print key + ' Kolmogorov probability: ' + str(chi2Prob[key])
        print key + ' chiSqure probability: ' + str(kolmogorovProb[key])
    #print 'Kolmogorov probability with sidebands: '+str(histos_MC['dimuon_pt'].KolmogorovTest(histos_LSB['dimuon_pt'])) #

    inputFile.Close()
Exemplo n.º 22
0
        ccos = cos(2 * pi / numberOfPoints * i) + 1
        esin = sin(2 * pi / (numberOfCircles * d) * j) + 1
        x = j * (csin + esin)
        y = j * ccos
        z = j
        pm3d.SetPoint(i, x, y, z)

# set marker size, color & style
    pm3d.SetMarkerSize(1)
    pm3d.SetMarkerColor(2 + (d == (j & d)))
    pm3d.SetMarkerStyle(3)

    # draw
    pm3d.Draw()

    # save a reference
    polymarkers.append(pm3d)

gBenchmark.Show('tornado')

ct = gBenchmark.GetCpuTime('tornado')
timeStr = 'Execution time: %g sec.' % ct

text = TPaveText(0.1, 0.81, 0.9, 0.97)
text.SetFillColor(42)
text.AddText('PyROOT example: tornado.py')
text.AddText(timeStr)
text.Draw()

sky.Update()
Exemplo n.º 23
0
                    ]

                    hist = TH1D(hisName, "", 50, 5.5, 5.7)
                    plbl0.Draw('lbtkMass>>' + hisName, '&&'.join(myCutLists))
                    print 'hiiii --- {0}'.format(hist.GetEntries())
                    print 'hiiii --- ' + '&&'.join(myCutLists)

                    hist.SetStats(False)
                    hist.SetTitle(
                        "#Lambda^{0}_{b}#rightarrow J/#psi p K under cut")
                    hist.GetXaxis().SetTitle('#Lambda^{0}_{b} Mass (GeV)')
                    hist.GetYaxis().SetTitle('event/4MeV')
                    hist.SetMaximum(hist.GetMaximum() * 1.5)
                    hist.SetMinimum(0.)
                    hist.Draw()
                    hist.Write()

                    text = TPaveText(0.41, 0.70, 0.85, 0.85, 'NDC')
                    text.AddText('Total Entries {0}'.format(hist.GetEntries()))
                    text.SetFillStyle(4000)
                    text.SetFillColor(4000)
                    text.Draw('same')

                    canv.Modified()
                    canv.SaveAs('{}/h_{}.eps'.format(figFolder, hisName))
                    canv.SaveAs(pdfFile)

canv.SaveAs(pdfFile + ']')
mySavingROOTFilt.Close()
rootFile.Close()
Exemplo n.º 24
0
def main():

    if True:
        mf=TGMainFrame(gClient.GetRoot(),1500,475)
        gvf=TGVerticalFrame(mf,1500,475)
        rec=TRootEmbeddedCanvas("ccc",gvf,1500,450)
        rec2=TRootEmbeddedCanvas("ccc2",gvf,1500,25)
        gvf.AddFrame(rec,TGLayoutHints(ROOT.kLHintsExpandX|ROOT.kLHintsTop))
        gvf.AddFrame(rec2,TGLayoutHints(ROOT.kLHintsExpandX|ROOT.kLHintsBottom))
        mf.AddFrame(gvf,TGLayoutHints(ROOT.kLHintsExpandX))
        cc=rec.GetCanvas()
        cc2=rec2.GetCanvas()
        mf.SetEditable(0)
        mf.SetWindowName('HPS ECAL FADC SCALERS')
        mf.MapSubwindows()
        mf.Resize(1501,476)# resize to get proper frame placement
        mf.MapWindow()
    else:
        cc=TCanvas('cc','',1500,450)
   
    cc.cd()
    cc.SetBorderMode(0)
    cc.SetFixedAspectRatio(1)
    cc.FeedbackMode(1)
    
    gStyle.SetOptStat(0)
    gStyle.SetGridStyle(1)
    gStyle.SetGridColor(11)

    hh=TH2D('hh',';X;Y',46,-22,24,11,-5,6)
    hi=TH2I('hi',';X;Y',46,-22,24,11,-5,6)
    setupHists([hh,hi])
    xax,yax=hh.GetXaxis(),hh.GetYaxis()
    hh.Draw('COLZ')
    hi.Draw('TEXTSAME')
    
    gPad.SetLogz()
    gPad.SetGrid(1,1)
    gPad.SetLeftMargin(0.05)
    
    tt1=TPaveText(0.1,0.9,0.3,1.0,'NDC')
    tt2=TPaveText(0.7,0.91,0.9,0.99,'NDC')
    ttT=TPaveText(-22+13+0.05,6-5,-22+22,7-5-0.05)
    ttB=TPaveText(-22+13+0.05,4-5+0.05,-22+22,5-5)
    ttM=TPaveText(-22+0+0.05,5-5+0.05,-22+13,6-5.01)
    ttime=TPaveText(-10,-6.5,10,-5.8)
    tchan=TPaveText(0,0,0.9,1)
    setupPaveTexts([tt1,tt2,ttT,ttB,ttM,ttime,tchan])
    ttM.SetTextColor(2)
    
    bb=TBox()
    bb.SetFillStyle(1001)
    bb.SetFillColor(0)
    bb.SetLineWidth(1)
    bb.SetLineColor(1)
    bb.DrawBox(-9+0.05,-1,0,1.97)
    bb.DrawBox(-24,0,24.05,0.97)
    
    tarrow=TText(14.5,0.3,'Beam Left')
    arrow=TArrow(19,0.5,23,0.5,0.02,'|>')
    arrow.SetAngle(40)
    arrow.SetFillColor(1)
    arrow.SetLineWidth(2)
    
    tt=TText()
    tt.SetTextColor(1)
    tt.SetTextAngle(90)
    tt.SetTextSize(0.08)
    tt.DrawText(25.4,0,'kHz')
    tt.SetTextAngle(0)
    tt.SetTextColor(2)
    tt.DrawTextNDC(0.3,0.92,'ECAL FADC SCALERS')
   
    cc.cd()
    for xx in [tt2,ttT,ttB,ttM,arrow,tarrow,ttime]: xx.Draw()
    cc2.cd()
    tchan.Draw('NDC')
    cc.cd()
    
    ll=TLine()
    ll.DrawLine(xax.GetXmin(),yax.GetXmin(),xax.GetXmax(),yax.GetXmin())
    ll.DrawLine(xax.GetXmin(),yax.GetXmax(),xax.GetXmax(),yax.GetXmax())
    ll.DrawLine(xax.GetXmin(),yax.GetXmin(),xax.GetXmin(),0)
    ll.DrawLine(xax.GetXmax(),yax.GetXmin(),xax.GetXmax(),0)
    ll.DrawLine(xax.GetXmin(),yax.GetXmax(),xax.GetXmin(),1)
    ll.DrawLine(xax.GetXmax(),yax.GetXmax(),xax.GetXmax(),1)
    ll.DrawLine(xax.GetXmax(),0,0,0)
    ll.DrawLine(xax.GetXmax(),1,0,1)
    ll.DrawLine(xax.GetXmin(),0,-9,0)
    ll.DrawLine(xax.GetXmin(),1,-9,1)
    ll.DrawLine(-9,-1,0,-1)
    ll.DrawLine(-9,2,0,2)
    ll.DrawLine(-9,1,-9,2)
    ll.DrawLine(-9,-1,-9,0)
    ll.DrawLine(0,-1,0,0)
    ll.DrawLine(0,1,0,2)
   
    gPad.SetEditable(0)

    while True:

#        try:

            zvals=getPVS()
            for ii in range(len(zvals)):
                hh.SetBinContent(xax.FindBin(XVALS[ii]),yax.FindBin(YVALS[ii]),zvals[ii])
                hi.SetBinContent(xax.FindBin(XVALS[ii]),yax.FindBin(YVALS[ii]),zvals[ii])
            
            for xx in [ttime,tt2,ttT,ttB,ttM]: xx.Clear()
            [top,bottom,maximum]=calcRates(zvals)
            tt2.AddText('Total:  %.1f MHz'%((top+bottom)/1000))
            ttT.AddText('%.1f MHz'%(top/1000))
            ttB.AddText('%.1f MHz'%(bottom/1000))
            ttM.AddText('MAX SINGLE CRYSTAL = %.0f kHz'%(maximum))
            ttime.AddText(makeTime())
          
            if gPad.GetEvent()==11:
                xy=pix2xy(gPad)
                ee=ECAL.findChannelXY(xy[0],xy[1])
                if ee:
                    tchan.Clear()
                    tchan.AddText(printChannel(ee))
                    cc2.Modified()
                    cc2.Update()
            elif gPad.GetEvent()==12:
                tchan.Clear()
                cc2.Modified()
                cc2.Update()
    
    
            cc.Modified()
            cc.Update()
        
            time.sleep(1)
Exemplo n.º 25
0
## \author Wim Lavrijsen

from ROOT import TCanvas, TPaveLabel, TPaveText, TText, TArrow, TLine
from ROOT import gROOT

c1 = TCanvas('c1', 'ROOT FilDir description', 700, 900)
c1.Range(1, 1, 19, 24.5)

title = TPaveLabel(4, 23, 16, 24.2, 'ROOT File/Directory/Key description')
title.SetFillColor(16)
title.Draw()

keycolor = 42
dircolor = 21
objcolor = 46
file = TPaveText(2, 19, 6, 22)
file.SetFillColor(39)
file.Draw()
file.SetTextSize(0.04)
file.AddText('TFile')
file.AddText('Header')
arrow = TArrow(6, 20.5, 17, 20.5, 0.02, '|>')
arrow.SetFillStyle(1001)
arrow.SetLineWidth(2)
arrow.Draw()
free = TPaveText(8, 20, 11, 21)
free.SetFillColor(18)
free.Draw()
free.AddText('First:Last')
free2 = TPaveText(12, 20, 15, 21)
free2.SetFillColor(18)
Exemplo n.º 26
0
def compareDatasets(trigger, leg, datasets, lineColors, legendLabels, axisTitle, canvas, dataLumi, metHLTFilters, outputSuffix = None):

    inputFiles = [TFile.Open("triggerEfficiency_" + x + ".root") for x in datasets]
    efficiencies = [x.Get(trigger + "_" + leg) for x in inputFiles]

    for iEff in range(len(efficiencies)):
        SetStyle(efficiencies[iEff])
        efficiencies[iEff].SetLineColor(lineColors[iEff])
        efficiencies[iEff].SetMarkerColor(lineColors[iEff])

    oneLine = TLine(xlo, 1.0, xhi, 1.0)
    oneLine.SetLineWidth(3)
    oneLine.SetLineStyle(2)

    backgroundHist = TH1D("backgroundHist", "backgroundHist", 1, xlo, xhi)
    backgroundHist.GetYaxis().SetTitle("Trigger Efficiency")
    backgroundHist.GetYaxis().SetRangeUser(ylo, yhi)
    backgroundHist.GetXaxis().SetTitle(axisTitle)
    SetStyle(backgroundHist)

    canvas.cd()
    backgroundHist.Draw()
    for eff in efficiencies:
        eff.Draw("CP same")
    #oneLine.Draw("same")

    pt_cmsPrelim = TPaveText(0.132832, 0.859453, 0.486216, 0.906716, "brNDC")
    pt_cmsPrelim.SetBorderSize(0)
    pt_cmsPrelim.SetFillStyle(0)
    pt_cmsPrelim.SetTextFont(62)
    pt_cmsPrelim.SetTextSize(0.0374065)
    if dataLumi > 0:
        pt_cmsPrelim.AddText("CMS Preliminary")
    else:
        pt_cmsPrelim.AddText("CMS Simulation")
    pt_cmsPrelim.Draw("same")

    if dataLumi > 0:
        pt_lumi = TPaveText(0.744361, 0.92928, 0.860902, 0.977667, "brNDC")
        pt_lumi.SetBorderSize(0)
        pt_lumi.SetFillStyle(0)
        pt_lumi.SetTextFont(42)
        pt_lumi.SetTextSize(0.0374065)
        pt_lumi.AddText("{:.2f}".format(dataLumi / 1000.0) + " fb^{-1}, 13 TeV")
        pt_lumi.Draw("same")

    pt_leg = TPaveText(0.160401, 0.768657, 0.342105, 0.863184, "brNDC")
    pt_leg.SetBorderSize(0)
    pt_leg.SetFillStyle(0)
    pt_leg.SetTextFont(42)
    pt_leg.SetTextSize(0.025)
    pt_leg.SetTextAlign(12)
    if leg == "METLeg":
        legLabel = ""
        for filt in metHLTFilters[:-1]:
            legLabel = legLabel + filt + ", "
        legLabel = legLabel + metHLTFilters[-1]
        pt_leg.AddText(legLabel)
    if leg == "TrackLeg":
        pt_leg.AddText(trigger + "*")
        legLabel = ""
        for filt in metHLTFilters[:-1]:
            legLabel = legLabel + filt + ", "
        legLabel = legLabel + metHLTFilters[-1] + " applied"
        pt_leg.AddText(legLabel)
    if leg == "METPath":
        if trigger == "GrandOr":
            pt_leg.AddText("OR of Signal Paths")
        else:
            if len(trigger) > 25 and len(trigger.split("_")) > 2:
                firstLine = trigger.split("_")[0] + "_" + trigger.split("_")[1] + "_"
                pt_leg.AddText(firstLine)
                secondLine = ""
                for line in trigger.split("_")[2:-1]:
                    secondLine += line + "_"
                secondLine += trigger.split("_")[-1] + "*"
                pt_leg.AddText(secondLine)
            else:
                pt_leg.AddText(trigger + "*")
    pt_leg.Draw("same")

    legendLabel = trigger

    legend = TLegend(0.65, 0.75, 0.93, 0.88)
    legend.SetBorderSize(0)
    legend.SetFillColor(0)
    legend.SetFillStyle(0)
    legend.SetTextFont(42)
    if leg == 'METLeg':
        legend.SetHeader('MET Leg')
    elif leg == 'TrackLeg':
        legend.SetHeader('Track Leg')
    for iEff in range(len(efficiencies)):
        legend.AddEntry(efficiencies[iEff], legendLabels[iEff], 'P')
    legend.Draw("same")

    if outputSuffix is not None:
        canvas.SaveAs('compareDatasets_' + trigger + '_' + leg + '_' + outputSuffix + '.pdf')
    else:
        canvas.SaveAs('compareDatasets_' + trigger + '_' + leg + '_.pdf')

    for inputFile in inputFiles:
        inputFile.Close()

    return
def make_template_plots(histograms, category, channel):
    global variable, translate_options, b_tag_bin, save_path
    ROOT.TH1.SetDefaultSumw2(False)
    ROOT.gROOT.SetBatch(True)
    ROOT.gROOT.ProcessLine('gErrorIgnoreLevel = 1001;')
    plotting.setStyle()
    gStyle.SetTitleYOffset(1.4)
    ROOT.gROOT.ForceStyle()

    for variable_bin in variable_bins_ROOT[variable]:
        path = save_path + '/' + variable + '/' + category + '/fit_templates/'
        make_folder_if_not_exists(path)
        plotname = path + channel + '_templates_bin_' + variable_bin + '.png'
        # check if template plots exist already
        if os.path.isfile(plotname):
            continue
        canvas = Canvas(width=700, height=500)
        canvas.SetLeftMargin(0.15)
        canvas.SetBottomMargin(0.15)
        canvas.SetTopMargin(0.05)
        canvas.SetRightMargin(0.05)
        legend = plotting.create_legend(x0=0.7, y1=0.8)
        h_signal = histograms[variable_bin]['signal']
        h_VJets = histograms[variable_bin]['V+Jets']
        h_QCD = histograms[variable_bin]['QCD']

        h_signal.GetXaxis().SetTitle('Lepton #eta')
        h_signal.GetYaxis().SetTitle('Normalised Events')
        h_signal.GetXaxis().SetTitleSize(0.05)
        h_signal.GetYaxis().SetTitleSize(0.05)
        h_signal.SetMinimum(0)
        h_signal.SetMaximum(0.2)
        h_signal.SetLineWidth(2)
        h_VJets.SetLineWidth(2)
        h_QCD.SetLineWidth(2)
        h_signal.SetLineColor(kRed + 1)
        h_VJets.SetLineColor(kBlue)
        h_QCD.SetLineColor(kYellow)
        h_signal.Draw('hist')
        h_VJets.Draw('hist same')
        h_QCD.Draw('hist same')
        legend.AddEntry(h_signal, 'signal', 'l')
        legend.AddEntry(h_VJets, 'V+Jets', 'l')
        legend.AddEntry(h_QCD, 'QCD', 'l')
        legend.Draw()

        mytext = TPaveText(0.5, 0.97, 1, 1.01, "NDC")
        channelLabel = TPaveText(0.18, 0.97, 0.5, 1.01, "NDC")
        if channel == 'electron':
            channelLabel.AddText("e, %s, %s" %
                                 ("#geq 4 jets", b_tag_bins_latex[b_tag_bin]))
        elif channel == 'muon':
            channelLabel.AddText("#mu, %s, %s" %
                                 ("#geq 4 jets", b_tag_bins_latex[b_tag_bin]))
        else:
            channelLabel.AddText("combined, %s, %s" %
                                 ("#geq 4 jets", b_tag_bins_latex[b_tag_bin]))
        mytext.AddText(
            "CMS Preliminary, L = %.1f fb^{-1} at #sqrt{s} = 8 TeV" % (5.8))

        mytext.SetFillStyle(0)
        mytext.SetBorderSize(0)
        mytext.SetTextFont(42)
        mytext.SetTextAlign(13)

        channelLabel.SetFillStyle(0)
        channelLabel.SetBorderSize(0)
        channelLabel.SetTextFont(42)
        channelLabel.SetTextAlign(13)
        mytext.Draw()
        channelLabel.Draw()

        canvas.Modified()
        canvas.Update()
        canvas.SaveAs(plotname)
        canvas.SaveAs(plotname.replace('png', 'pdf'))
Exemplo n.º 28
0
def compare(trigger, leg, data, mc, axisTitle, canvas, dataLumi, metHLTFilters):
    dataFile = TFile.Open("triggerEfficiency_" + data + ".root", "read")
    mcFile = TFile.Open("triggerEfficiency_" + mc + ".root", "read")

    dataEff = dataFile.Get(trigger + "_" + leg)
    mcEff = mcFile.Get(trigger + "_" + leg)

    SetStyle(dataEff)
    SetStyle(mcEff)
    mcEff.SetLineColor(600)
    mcEff.SetMarkerColor(600)

    oneLine = TLine(xlo, 1.0, xhi, 1.0)
    oneLine.SetLineWidth(3)
    oneLine.SetLineStyle(2)

    backgroundHist = TH1D("backgroundHist", "backgroundHist", 1, xlo, xhi)
    backgroundHist.GetYaxis().SetTitle("Trigger Efficiency")
    backgroundHist.GetYaxis().SetRangeUser(ylo, yhi)
    backgroundHist.GetXaxis().SetTitle(axisTitle)
    SetStyle(backgroundHist)

    canvas.cd()
    backgroundHist.Draw()
    dataEff.Draw("CP same")
    mcEff.Draw("CP same")
    #oneLine.Draw("same")

    pt_cmsPrelim = TPaveText(0.132832, 0.859453, 0.486216, 0.906716, "brNDC")
    pt_cmsPrelim.SetBorderSize(0)
    pt_cmsPrelim.SetFillStyle(0)
    pt_cmsPrelim.SetTextFont(62)
    pt_cmsPrelim.SetTextSize(0.0374065)
    pt_cmsPrelim.AddText("CMS Preliminary")
    pt_cmsPrelim.Draw("same")

    pt_lumi = TPaveText(0.744361, 0.92928, 0.860902, 0.977667, "brNDC")
    pt_lumi.SetBorderSize(0)
    pt_lumi.SetFillStyle(0)
    pt_lumi.SetTextFont(42)
    pt_lumi.SetTextSize(0.0374065)
    pt_lumi.AddText("{:.2f}".format(dataLumi / 1000.0) + " fb^{-1}, 13 TeV")
    pt_lumi.Draw("same")

    pt_leg = TPaveText(0.160401, 0.768657, 0.342105, 0.863184, "brNDC")
    pt_leg.SetBorderSize(0)
    pt_leg.SetFillStyle(0)
    pt_leg.SetTextFont(42)
    pt_leg.SetTextSize(0.025)
    pt_leg.SetTextAlign(12)
    if leg == "METLeg":
        legLabel = ""
        for filt in metHLTFilters[:-1]:
            legLabel = legLabel + filt + ", "
        legLabel = legLabel + metHLTFilters[-1]
        pt_leg.AddText(legLabel)
    if leg == "TrackLeg":
        pt_leg.AddText(trigger + "*")
        legLabel = ""
        for filt in metHLTFilters[:-1]:
            legLabel = legLabel + filt + ", "
        legLabel = legLabel + metHLTFilters[-1] + " applied"
        pt_leg.AddText(legLabel)
    if leg == "METPath":
        if trigger == "GrandOr":
            pt_leg.AddText("OR of Signal Paths")
        else:
            if len(trigger) > 25 and len(trigger.split("_")) > 2:
                firstLine = trigger.split("_")[0] + "_" + trigger.split("_")[1] + "_"
                pt_leg.AddText(firstLine)
                secondLine = ""
                for line in trigger.split("_")[2:-1]:
                    secondLine += line + "_"
                secondLine += trigger.split("_")[-1] + "*"
                pt_leg.AddText(secondLine)
            else:
                pt_leg.AddText(trigger + "*")
    pt_leg.Draw("same")

    dataLabel = '2015 data'
    if '2016BC' in data:
        dataLabel = '2016 B+C data'
    if '2016DEFGH' in data:
        dataLabel = '2016 D-H data'
    if '2017' in data:
        dataLabel = '2017 data'
    if '2018' in data:
        dataLabel = '2018 data'

    legendLabel = trigger

    legend = TLegend(0.65, 0.75, 0.93, 0.88)
    legend.SetBorderSize(0)
    legend.SetFillColor(0)
    legend.SetFillStyle(0)
    legend.SetTextFont(42)
    if leg == 'METLeg':
        legend.SetHeader('MET Leg')
    elif leg == 'TrackLeg':
        legend.SetHeader('Track Leg')
    legend.AddEntry(dataEff, dataLabel, 'P')
    legend.AddEntry(mcEff, 'W #rightarrow l#nu MC', 'P')
    legend.Draw("same")

    outputDirectory = 'plots_compare'
    if 'BC' in data:
        outputDirectory = 'plots_compareBC'
    if 'DEFGH' in data:
        outputDirectory = 'plots_compareDEFGH'

    if not os.path.exists(outputDirectory):
        os.mkdir(outputDirectory)

    canvas.SaveAs(outputDirectory + '/' + trigger + '_' + leg + '.pdf')

    mcFile.Close()
    dataFile.Close()

    return
def make_plots_ROOT(histograms, category, save_path, histname, channel):
    global variable, translateOptions, k_value, b_tag_bin, maximum
    ROOT.TH1.SetDefaultSumw2(False)
    ROOT.gROOT.SetBatch(True)
    ROOT.gROOT.ProcessLine('gErrorIgnoreLevel = 1001;')
    plotting.setStyle()
    gStyle.SetTitleYOffset(2.)
    ROOT.gROOT.ForceStyle()
    canvas = Canvas(width=700, height=500)
    canvas.SetLeftMargin(0.18)
    canvas.SetBottomMargin(0.15)
    canvas.SetTopMargin(0.05)
    canvas.SetRightMargin(0.05)
    legend = plotting.create_legend(x0=0.6, y1=0.5)

    hist_data = histograms['unfolded']
    hist_data.GetXaxis().SetTitle(translate_options[variable] + ' [GeV]')
    hist_data.GetYaxis().SetTitle('#frac{1}{#sigma} #frac{d#sigma}{d' +
                                  translate_options[variable] + '} [GeV^{-1}]')
    hist_data.GetXaxis().SetTitleSize(0.05)
    hist_data.GetYaxis().SetTitleSize(0.05)
    hist_data.SetMinimum(0)
    hist_data.SetMaximum(maximum[variable])
    hist_data.SetMarkerSize(1)
    hist_data.SetMarkerStyle(8)
    plotAsym = TGraphAsymmErrors(hist_data)
    plotStatErr = TGraphAsymmErrors(hist_data)

    xsections = read_unfolded_xsections(channel)
    bins = variable_bins_ROOT[variable]
    assert (len(bins) == len(xsections['central']))

    for bin_i in range(len(bins)):
        scale = 1  # / width
        centralresult = xsections['central'][bin_i]
        fit_error = centralresult[1]
        uncertainty = calculateTotalUncertainty(xsections, bin_i)
        uncertainty_total_plus = uncertainty['Total+'][0]
        uncertainty_total_minus = uncertainty['Total-'][0]
        uncertainty_total_plus, uncertainty_total_minus = symmetriseErrors(
            uncertainty_total_plus, uncertainty_total_minus)
        error_up = sqrt(fit_error**2 + uncertainty_total_plus**2) * scale
        error_down = sqrt(fit_error**2 + uncertainty_total_minus**2) * scale
        plotStatErr.SetPointEYhigh(bin_i, fit_error * scale)
        plotStatErr.SetPointEYlow(bin_i, fit_error * scale)
        plotAsym.SetPointEYhigh(bin_i, error_up)
        plotAsym.SetPointEYlow(bin_i, error_down)

    gStyle.SetEndErrorSize(20)
    plotAsym.SetLineWidth(2)
    plotStatErr.SetLineWidth(2)
    hist_data.Draw('P')
    plotStatErr.Draw('same P')
    plotAsym.Draw('same P Z')
    legend.AddEntry(hist_data, 'unfolded', 'P')

    hist_measured = histograms['measured']
    hist_measured.SetMarkerSize(1)
    hist_measured.SetMarkerStyle(20)
    hist_measured.SetMarkerColor(2)
    #hist_measured.Draw('same P')
    #legend.AddEntry(hist_measured, 'measured', 'P')

    for key, hist in sorted(histograms.iteritems()):
        if not 'unfolded' in key and not 'measured' in key:
            hist.SetLineStyle(7)
            hist.SetLineWidth(2)
            # setting colours
            if 'POWHEG' in key or 'matchingdown' in key:
                hist.SetLineColor(kBlue)
            elif 'MADGRAPH' in key or 'matchingup' in key:
                hist.SetLineColor(kRed + 1)
            elif 'MCATNLO' in key or 'scaleup' in key:
                hist.SetLineColor(kGreen - 3)
            elif 'scaledown' in key:
                hist.SetLineColor(kMagenta + 3)
            hist.Draw('hist same')
            legend.AddEntry(hist, translate_options[key], 'l')

    legend.Draw()

    mytext = TPaveText(0.5, 0.97, 1, 1.01, "NDC")
    channelLabel = TPaveText(0.18, 0.97, 0.5, 1.01, "NDC")
    if 'electron' in histname:
        channelLabel.AddText(
            "e, %s, %s, k = %s" %
            ("#geq 4 jets", b_tag_bins_latex[b_tag_bin], k_value))
    elif 'muon' in histname:
        channelLabel.AddText(
            "#mu, %s, %s, k = %s" %
            ("#geq 4 jets", b_tag_bins_latex[b_tag_bin], k_value))
    else:
        channelLabel.AddText(
            "combined, %s, %s, k = %s" %
            ("#geq 4 jets", b_tag_bins_latex[b_tag_bin], k_value))
    mytext.AddText("CMS Preliminary, L = %.1f fb^{-1} at #sqrt{s} = 8 TeV" %
                   (5.8))

    mytext.SetFillStyle(0)
    mytext.SetBorderSize(0)
    mytext.SetTextFont(42)
    mytext.SetTextAlign(13)

    channelLabel.SetFillStyle(0)
    channelLabel.SetBorderSize(0)
    channelLabel.SetTextFont(42)
    channelLabel.SetTextAlign(13)
    mytext.Draw()
    channelLabel.Draw()

    canvas.Modified()
    canvas.Update()

    path = save_path + '/' + variable + '/' + category
    make_folder_if_not_exists(path)
    canvas.SaveAs(path + '/' + histname + '_kv' + str(k_value) + '.png')
    canvas.SaveAs(path + '/' + histname + '_kv' + str(k_value) + '.pdf')
Exemplo n.º 30
0
def createPlots_(plot, geometry):
    """Cumulative material budget from simulation.
    
       Internal function that will produce a cumulative profile of the
       material budget inferred from the simulation starting from the
       single detectors that compose the tracker. It will iterate over
       all existing detectors contained in the DETECTORS
       dictionary. The function will automatically skip non-existent
       detectors.

    """

    IBs = ["InnerServices", "Phase2PixelBarrel", "TIB", "TIDF", "TIDB"]
    theDirname = "Figures"

    if plot not in plots.keys():
        print("Error: chosen plot name not known %s" % plot)
        return

    hist_X0_detectors = OrderedDict()
    hist_X0_IB = None
    hist_X0_elements = OrderedDict()

    for subDetector, color in six.iteritems(DETECTORS):
        h = get1DHisto_(subDetector, plots[plot].plotNumber, geometry)
        if not h:
            print('Warning: Skipping %s' % subDetector)
            continue
        hist_X0_detectors[subDetector] = h

        # Merge together the "inner barrel detectors".
        if subDetector in IBs:
            hist_X0_IB = assignOrAddIfExists_(hist_X0_IB,
                                              hist_X0_detectors[subDetector])

        # category profiles
        for label, [num, color, leg] in six.iteritems(hist_label_to_num):
            if label is 'SUM': continue
            hist_label = get1DHisto_(subDetector, num + plots[plot].plotNumber,
                                     geometry)
            hist_X0_elements[label] = assignOrAddIfExists_(
                hist_X0_elements.setdefault(label, None),
                hist_label,
            )
            hist_X0_elements[label].SetFillColor(color)

    cumulative_matbdg = TH1D("CumulativeSimulMatBdg", "CumulativeSimulMatBdg",
                             hist_X0_IB.GetNbinsX(),
                             hist_X0_IB.GetXaxis().GetXmin(),
                             hist_X0_IB.GetXaxis().GetXmax())
    cumulative_matbdg.SetDirectory(0)

    # colors
    for det, color in six.iteritems(DETECTORS):
        setColorIfExists_(hist_X0_detectors, det, color)

    # First Plot: BeamPipe + Pixel + TIB/TID + TOB + TEC + Outside
    # stack
    stackTitle_SubDetectors = "Tracker Material Budget;%s;%s" % (
        plots[plot].abscissa, plots[plot].ordinate)
    stack_X0_SubDetectors = THStack("stack_X0", stackTitle_SubDetectors)
    for det, histo in six.iteritems(hist_X0_detectors):
        stack_X0_SubDetectors.Add(histo)
        cumulative_matbdg.Add(histo, 1)

    # canvas
    can_SubDetectors = TCanvas("can_SubDetectors", "can_SubDetectors", 800,
                               800)
    can_SubDetectors.Range(0, 0, 25, 25)
    can_SubDetectors.SetFillColor(kWhite)

    # Draw
    stack_X0_SubDetectors.SetMinimum(plots[plot].ymin)
    stack_X0_SubDetectors.SetMaximum(plots[plot].ymax)
    stack_X0_SubDetectors.Draw("HIST")
    stack_X0_SubDetectors.GetXaxis().SetLimits(plots[plot].xmin,
                                               plots[plot].xmax)

    # Legenda
    theLegend_SubDetectors = TLegend(0.180, 0.8, 0.98, 0.92)
    theLegend_SubDetectors.SetNColumns(3)
    theLegend_SubDetectors.SetFillColor(0)
    theLegend_SubDetectors.SetFillStyle(0)
    theLegend_SubDetectors.SetBorderSize(0)

    for det, histo in six.iteritems(hist_X0_detectors):
        theLegend_SubDetectors.AddEntry(histo, det, "f")

    theLegend_SubDetectors.Draw()

    # text
    text_SubDetectors = TPaveText(0.180, 0.727, 0.402, 0.787, "NDC")
    text_SubDetectors.SetFillColor(0)
    text_SubDetectors.SetBorderSize(0)
    text_SubDetectors.AddText("CMS Simulation")
    text_SubDetectors.SetTextAlign(11)
    text_SubDetectors.Draw()

    # Store
    can_SubDetectors.Update()
    if not checkFile_(theDirname):
        os.mkdir(theDirname)
    can_SubDetectors.SaveAs("%s/Tracker_SubDetectors_%s.pdf" %
                            (theDirname, plot))
    can_SubDetectors.SaveAs("%s/Tracker_SubDetectors_%s.root" %
                            (theDirname, plot))

    # Second Plot: BeamPipe + SEN + ELE + CAB + COL + SUP + OTH/AIR +
    # Outside stack
    stackTitle_Materials = "Tracker Material Budget;%s;%s" % (
        plots[plot].abscissa, plots[plot].ordinate)
    stack_X0_Materials = THStack("stack_X0", stackTitle_Materials)
    stack_X0_Materials.Add(hist_X0_detectors["BeamPipe"])
    for label, [num, color, leg] in six.iteritems(hist_label_to_num):
        if label is 'SUM':
            continue
        stack_X0_Materials.Add(hist_X0_elements[label])

    # canvas
    can_Materials = TCanvas("can_Materials", "can_Materials", 800, 800)
    can_Materials.Range(0, 0, 25, 25)
    can_Materials.SetFillColor(kWhite)

    # Draw
    stack_X0_Materials.SetMinimum(plots[plot].ymin)
    stack_X0_Materials.SetMaximum(plots[plot].ymax)
    stack_X0_Materials.Draw("HIST")
    stack_X0_Materials.GetXaxis().SetLimits(plots[plot].xmin, plots[plot].xmax)

    # Legenda
    theLegend_Materials = TLegend(0.180, 0.8, 0.95, 0.92)
    theLegend_Materials.SetNColumns(3)
    theLegend_Materials.SetFillColor(0)
    theLegend_Materials.SetBorderSize(0)

    theLegend_Materials.AddEntry(hist_X0_detectors["BeamPipe"], "Beam Pipe",
                                 "f")
    for label, [num, color, leg] in six.iteritems(hist_label_to_num):
        if label is 'SUM':
            continue
        theLegend_Materials.AddEntry(hist_X0_elements[label], leg, "f")
    theLegend_Materials.Draw()

    # text
    text_Materials = TPaveText(0.180, 0.727, 0.402, 0.787, "NDC")
    text_Materials.SetFillColor(0)
    text_Materials.SetBorderSize(0)
    text_Materials.AddText("CMS Simulation")
    text_Materials.SetTextAlign(11)
    text_Materials.Draw()

    # Store
    can_Materials.Update()
    can_Materials.SaveAs("%s/Tracker_Materials_%s.pdf" % (theDirname, plot))
    can_Materials.SaveAs("%s/Tracker_Materials_%s.root" % (theDirname, plot))

    return cumulative_matbdg