def thresholds(var, title, xtitle, nbin, low, high, region):
    cutter = cuts[region]
    weight = cutter
    can = TCanvas("can", "can", 1000, 900)
    can.SetBottomMargin(0.3)
    can.SetRightMargin(0.06)
    can.cd()
    gPad.SetLogy(1)
    gStyle.SetOptStat(0)
    backs = TH1D('a', 'a', nbin, low, high)
    backs.SetFillStyle(3344)
    backs.SetFillColor(1)
    phojet = TH1D('b', 'b', nbin, low, high)
    phojet.SetFillColor(7)
    phojet.SetLineColor(7)
    qcd = TH1D('c', 'c', nbin, low, high)
    qcd.SetFillColor(5)
    qcd.SetLineColor(5)
    stack = THStack('d', title + ";" + xtitle + ";" + "Events")
    Variables = {}
    print "Variable: " + var
    for tre in List:
        histName = var + tre
        Variables[tre] = TH1F(histName, ";" + xtitle + ";" + "Events", nbin,
                              low, high)
        #		if tre == "dipho":
        #			weight = cutter+"&& (JetPho_dR<0.1)"
        treepj[tre].Draw(var + ">>" + histName, weight)
        Variables[tre].Sumw2()
        scalable = lumi * crossx[tre] * kFact[tre] / Nevents[tre]
        Variables[tre].Scale(scalable)
        if tre.startswith("df"):
            Variables[tre].SetLineColor(colors[tre])
            Variables[tre].SetLineWidth(3)
        if tre.startswith("GJets"):
            backs.Add(Variables[tre])
            phojet.Add(Variables[tre])
        if tre.startswith("QCD"):
            backs.Add(Variables[tre])
            qcd.Add(Variables[tre])
        if tre.startswith("DiPhoton"):
            Variables[tre].SetFillColor(3)
            Variables[tre].SetLineColor(3)
            backs.Add(Variables[tre])
    Variables['Data'] = TH1F('data', ";" + xtitle + ";" + "Events", nbin, low,
                             high)
    treepj['Data'].Draw(var + ">>data", cutter, "goff")
    Variables['Data'].SetLineColor(1)
    Variables['Data'].SetLineWidth(2)
    stack.Add(Variables['DiPhoton'])
    stack.Add(qcd)
    stack.Add(phojet)
    stack.SetMaximum(1000000.0)
    stack.SetMinimum(0.001)
    stack.Draw("hist")
    stack.GetXaxis().SetLabelSize(0)
    backs.Draw("e2same")
    Variables['Data'].Draw("e1same")
    Variables['df1en0'].Draw("histsame")
    Variables['df1en1'].Draw("histsame")
    Variables['df1en2'].Draw("histsame")
    Variables['df1en3'].Draw("histsame")
    pad = TPad("pad", "pad", 0.0, 0.0, 1.0, 1.0)
    pad.SetTopMargin(0.7)
    pad.SetFillColor(0)
    pad.SetGridy(1)
    pad.SetFillStyle(0)
    pad.Draw()
    pad.cd(0)
    pad.SetRightMargin(0.06)
    Pull = TH1D('Pull', 'Pull', nbin, low, high)
    Pull = Variables['Data'].Clone()
    Pull.Divide(backs)
    Pull.SetMarkerStyle(20)
    Pull.SetMaximum(2.0)
    Pull.SetMinimum(0.0)
    Pull.SetFillColor(2)
    Pull.GetXaxis().SetTitle(xtitle)
    Pull.GetYaxis().SetTitleSize(0.04)
    Pull.GetYaxis().SetTitle('Data/MC')
    Pull.SetMarkerSize(0.7)
    Pull.GetYaxis().SetNdivisions(5)
    line = TF1("line", "1", low, high)
    line.SetLineColor(2)
    line.SetLineWidth(2)
    Pull.Draw("e1")
    line.Draw('same')
    latex2 = TLatex()
    latex2.SetNDC()
    latex2.SetTextSize(0.035)
    latex2.SetTextAlign(31)  # align right
    latex2.DrawLatex(
        0.87, 0.95,
        "Work In Progress, " + str(lumi) + " fb^{-1} at #sqrt{s} = 13 TeV")
    led = TLegend(0.7, 0.7, 0.94, 0.9)
    led.AddEntry(phojet, "#gamma + Jet", 'f')
    led.AddEntry(qcd, "QCD DiJet", 'f')
    led.AddEntry(Variables['DiPhoton'], "#gamma + #gamma", 'f')
    led.AddEntry(Variables['df1en0'], "f_{D} = 1E0")
    led.AddEntry(Variables['df1en1'], "f_{D} = 1E-1")
    led.AddEntry(Variables['df1en2'], "f_{D} = 1E-2")
    led.AddEntry(Variables['df1en3'], "f_{D} = 1E-3")
    led.AddEntry(Variables['Data'], "Data")
    led.SetFillColor(0)
    led.Draw("same")
    can.SaveAs("plots/" + region + "-" + var + ".pdf")
    can.Close()
    phojet.Delete()
    qcd.Delete()
def makeMaxLikelihoodFitPlot(filelist, variableName, variableLabel):

    nPoints = len(variableName)

    xbins_mu = array('f', [])
    xbins_mu_err_up = array('f', [])
    xbins_mu_err_dn = array('f', [])
    ybins_mu = array('f', [])
    ybins_mu_err_up = array('f', [])
    ybins_mu_err_dn = array('f', [])
    ybins_mu_err_up_2s = array('f', [])
    ybins_mu_err_dn_2s = array('f', [])

    binName = []

    muValue = ROOT.TH1F("muValue", "", 100, -5, 5)
    muErrUpOneSigma = ROOT.TH1F("muErrUpOneSigma", "", 100, -5, 5)
    muErrUpTwoSigma = ROOT.TH1F("muErrUpTwoSigma", "", 100, -5, 5)
    muErrDownOneSigma = ROOT.TH1F("muErrDownOneSigma", "", 100, -5, 5)
    muErrDownTwoSigma = ROOT.TH1F("muErrDownTwoSigma", "", 100, -5, 5)

    muValue.Sumw2()
    muErrUpOneSigma.Sumw2()
    muErrUpTwoSigma.Sumw2()
    muErrDownOneSigma.Sumw2()
    muErrDownTwoSigma.Sumw2()

    for ivar in range(len(variableName)):
        for ifile in range(len(filelist)):
            if filelist[ifile].find(variableName[ivar] + "_" +
                                    options.channel) != -1:
                binName.append(variableLabel[ivar])

                muValue.Reset("ICES")
                muErrUpOneSigma.Reset("ICES")
                muErrUpTwoSigma.Reset("ICES")
                muErrDownOneSigma.Reset("ICES")
                muErrDownTwoSigma.Reset("ICES")

                getSignalStrenght(filelist[ifile], muValue, muErrUpOneSigma,
                                  muErrUpTwoSigma, muErrDownOneSigma,
                                  muErrDownTwoSigma)

                xbins_mu.append(ivar + 0.5)
                xbins_mu_err_up.append(0.5)
                xbins_mu_err_dn.append(0.5)
                ybins_mu.append(muValue.GetMean())
                ybins_mu_err_up.append(muErrUpOneSigma.GetMean())
                ybins_mu_err_dn.append(muErrDownOneSigma.GetMean())
                ybins_mu_err_up_2s.append(muErrUpTwoSigma.GetMean())
                ybins_mu_err_dn_2s.append(muErrDownTwoSigma.GetMean())

                break

    gr_mu_1s = ROOT.TGraphAsymmErrors(nPoints, xbins_mu, ybins_mu,
                                      xbins_mu_err_dn, xbins_mu_err_up,
                                      ybins_mu_err_dn, ybins_mu_err_up)
    gr_mu_1s.SetLineColor(1)
    gr_mu_1s.SetMarkerColor(1)
    gr_mu_1s.SetMarkerStyle(20)
    gr_mu_1s.SetLineWidth(5)
    gr_mu_1s.SetMarkerSize(1.6)

    gr_mu_2s = ROOT.TGraphAsymmErrors(nPoints, xbins_mu, ybins_mu,
                                      xbins_mu_err_dn, xbins_mu_err_up,
                                      ybins_mu_err_dn_2s, ybins_mu_err_up_2s)
    gr_mu_2s.SetLineColor(ROOT.kBlue)
    gr_mu_2s.SetMarkerColor(ROOT.kBlue)
    gr_mu_2s.SetMarkerStyle(20)
    gr_mu_2s.SetLineWidth(3)
    gr_mu_2s.SetMarkerSize(1.6)

    ban1s = TLatex(950, 1., ("#mu SM injected"))
    ban1s.SetTextSize(0.028)
    ban1s.SetTextColor(1)

    can = ROOT.TCanvas("can", "can", 1050, 650)
    hrl = can.DrawFrame(0, options.rMin * 0.75, nPoints, options.rMax * 1.25)
    hrl.SetBins(len(binName), 0, nPoints)

    for ibin in range(hrl.GetNbinsX()):
        hrl.GetXaxis().SetBinLabel(ibin + 1, binName[ibin])

    hrl.GetYaxis().SetTitle("signal strenght")
    hrl.GetYaxis().SetTitleOffset(0.95)

    can.SetGrid()

    gr_mu_2s.Draw("P")
    gr_mu_1s.Draw("Psame")

    tex = ROOT.TLatex(0.892, 0.957, " 14 TeV")
    tex.SetNDC()
    tex.SetTextAlign(31)
    tex.SetTextFont(42)
    tex.SetTextSize(0.04)
    tex.SetLineWidth(2)
    tex.Draw("same")

    tex2 = ROOT.TLatex(0.173, 0.957, "Delphes")
    tex2.SetNDC()
    tex2.SetTextFont(61)
    tex2.SetTextSize(0.04)
    tex2.SetLineWidth(2)
    tex2.Draw()

    tex3 = ROOT.TLatex(0.332, 0.957, "Simulation Preliminary")
    tex3.SetNDC()
    tex3.SetTextFont(52)
    tex3.SetTextSize(0.035)
    tex3.SetLineWidth(2)
    tex3.Draw()

    can.SaveAs(
        "%s/maximumLikelihoodFit_%s.pdf" %
        (options.outputPlotDIR, options.channel), "pdf")
    can.SaveAs(
        "%s/maximumLikelihoodFit_%s.png" %
        (options.outputPlotDIR, options.channel), "png")
Beispiel #3
0
def ATLAS_LABEL(x, y, color=1):
    l = TLatex()
    l.SetNDC()
    l.SetTextFont(72)
    l.SetTextColor(color)
    l.DrawLatex(x, y, "ATLAS")
def plot_sector_page(canvas,
                     histos1,
                     histos2,
                     config1,
                     config2,
                     title_formatter,
                     save_name,
                     xtitle=None,
                     ytitle=None,
                     title=None,
                     x_range=None):
    """ Compare two distributions in one plot, using root. """

    label = TLatex()
    label.SetNDC()
    label.SetTextSize(0.045)

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

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

        #_, __, values1, errors1 = numpify(histos1.get(title_formatter.format(i), default_histo))
        #_, __, values2, errors2 = numpify(histos2.get(title_formatter.format(i), default_histo))

        #scale = np.sum(values1 * values2) / np.sum(values2**2)

        histos1.get(title_formatter.format(i), default_histo).SetLineColor(1)
        histos1.get(title_formatter.format(i), default_histo).Scale(
            1 /
            histos1.get(title_formatter.format(i), default_histo).GetMaximum())

        histos2.get(title_formatter.format(i), default_histo).SetLineColor(99)
        histos2.get(title_formatter.format(i), default_histo).Scale(
            1 /
            histos2.get(title_formatter.format(i), default_histo).GetMaximum())
        #histos2.get(title_formatter.format(i), default_histo).Scale(scale)

        hmax = max(
            histos1.get(title_formatter.format(i), default_histo).GetMaximum(),
            histos2.get(title_formatter.format(i), default_histo).GetMaximum())

        histos1.get(title_formatter.format(i),
                    default_histo).SetMaximum(hmax * 1.1)
        histos2.get(title_formatter.format(i),
                    default_histo).SetMaximum(hmax * 1.1)

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

        histos1.get(title_formatter.format(i), default_histo).Draw('hist')
        histos2.get(title_formatter.format(i), default_histo).Draw('histsame')

        # Annotate the figure with the configuration names.
        caption1 = '#color[1]({0})'.format(config1).replace('(', '{').replace(
            ')', '}')
        caption2 = '#color[99]({0})'.format(config2).replace('(', '{').replace(
            ')', '}')

        label.DrawLatex(0.75, 0.86, caption1)
        label.DrawLatex(0.75, 0.825, caption2)

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

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

        if ytitle:
            label.SetTextAngle(90)
            label.DrawLatex(0.02, 0.65, ytitle)
            label.SetTextAngle(0)

    canvas.Print(save_name)
Beispiel #5
0
    def __reweightCanvas(self, can, addLabels, addTopXNumbers):
        import numpy as np, ROOT
        from ROOT import TGaxis, TLatex, kBlack
        if can.GetPrimitive('pad_top'):
            self.__reweightCanvas(can.GetPrimitive('pad_top'), False,
                                  addTopXNumbers)
        if can.GetPrimitive('pad_bot'):
            self.__reweightCanvas(can.GetPrimitive('pad_bot'), self.addLabels,
                                  False)
        if can.GetPrimitive('pad_bot') or can.GetPrimitive('pad_bot'): return
        can.cd()
        # First we "remove" previous axis
        xaxis = GetXaxis(can)
        # Now create new axis
        #xaxis.SetName("__xaxis_ignored")
        # Now draw new canvas
        #xmin, xmax = GetXaxisRanges(can)
        #import os
        #c = ROOT.TCanvas(self.func.GetName(),self.func.GetName())
        #self.func.Draw()
        #c.SaveAs( os.path.join( 'e26_RunByRun_noAdjustment', c.GetName() +'.pdf' ) )
        #can.cd()
        #chopt = "+C" + ("U" if not addLabels else "")
        chopt = "+CU"
        axis = TGaxis(can.GetUxmin(), can.GetUymin(), can.GetUxmax(),
                      can.GetUymin(), self.func.GetName(),
                      10000 * self.N3 + 100 * self.N2 + 1 * self.N1, chopt)
        axis.SetNoExponent(False)
        #axis.SetExponentOffset()
        if xaxis:
            axis.ImportAxisAttributes(xaxis)
            xaxis.SetTickLength(0)
            xaxis.SetLabelOffset(999.)
        if self.labelSize: axis.SetLabelSize(self.labelSize)
        #1 + 100*N2 + *N3N
        axis.Draw()
        from .PlotFunctions import tobject_collector
        if addTopXNumbers:
            _, ymax = GetYaxisRanges(can,
                                     check_all=True,
                                     ignorezeros=True,
                                     ignoreErrors=False)
            for xc in self.xcenters:
                text = TLatex(self.func.Eval(xc), ymax, str(xc))
                text.SetTextFont(43)
                text.SetTextSize(2)
                text.SetTextAlign(12)
                text.SetTextAngle(90)
                text.SetTextColor(ROOT.kBlack)
                text.Draw()
                tobject_collector.append(text)
        if addLabels:
            binLow, binHigh, nBins = self.__getXEdges(chopt)
            #labelPos = map( lambda x: (x,self.func.GetX(x),(self.func.GetX(x)-self.xedges[0])/(self.xedges[-1]-self.xedges[0]))
            #              , np.linspace(binLow,binHigh, nBins) )
            labelPos = map(
                lambda x:
                (x, self.func.Eval(x), (self.func.Eval(x) - self.xedges[0]) /
                 (self.xedges[-1] - self.xedges[0])),
                np.linspace(binLow, binHigh, nBins))
            ypos = can.GetUymin() - 0.04 * (can.GetUymax() - can.GetUymin())
            #labels = []
            for x, mx, pmx in labelPos:
                text = TLatex(mx, ypos, str(x))
                text.SetTextFont(43)
                #text.SetTextSizePixels(textPerc)
                text.SetTextAlign(23)
                text.SetTextColor(ROOT.kBlack)
                text.SetTextSize(14)
                text.Draw()
                tobject_collector.append(text)
                #labels.append(text)
            #gxc = (self.xedges[-1]-self.xedges[0] )/2
            #lLabels = len(labels)
            #for i, text in enumerate(labels):
            #    xc = text.GetBBoxCenter()
            #    if xc < gxc:
            #        if i+1 < lLabels:
            #            text2 = labels[i+1]
            #            while conflict(text.GetBBox(),text2.GetBBox()):
            #                sizes[i] = possible_sizes[sizes[i]+1]
            #                 text.SetTextSize( getNewSize

        ##AdjustBinSize (Double_t A1, Double_t A2, Int_t nold, Double_t &BinLow, Double_t &BinHigh, Int_t &nbins, Double_t &BinWidth)
        #lLabels = [labels.At(i) for i in range(labels.GetEntries())]
        tobject_collector.append(axis)
        #can.Modified()
        #can.Update()
        return axis
mg.SetTitle("Multi-graph Title; X-axis Title; Y-axis Title");
mg.Draw('apl, same')
canv.Update()
mg.GetXaxis().SetTitle("#kappa_t (no kinematics)")
mg.GetYaxis().SetTitle("-2#Delta lnL")
gPad.Modified()

mg.GetYaxis().SetRangeUser(0.,55.)
xmin = mg.GetXaxis().GetXmin()
xmax = mg.GetXaxis().GetXmax()
mg.GetXaxis().SetRangeUser(xmin,xmax)


#mg.Draw('ap')

lat = TLatex()
lat.SetNDC()
lat.SetTextFont(43)
lat.SetTextSize(32)
lat.DrawLatex(0.12, 0.92, "#bf{CMS} #it{Internal}")
lat.SetTextSize(26)
lat.DrawLatex(0.14, 0.845, "pp #rightarrow tH+t#bar{t}H, H #rightarrow WW*/ZZ*/#tau#tau")
##lat.DrawLatex(0.14, 0.8, "2lss only - ttH-sel + ttW-sel")
#lat.DrawLatex(0.14, 0.755, addLabel)

leg.Draw('same')

line1 = TLine(xmin,1, xmax, 1)
line1.SetLineStyle(2)
line2 = TLine(xmin,4, xmax, 4)
line2.SetLineStyle(2)
Beispiel #7
0

bgeff=float(wbgmeff)/float(wbgmeffD)

print "mass cut eff",bgeff
print "donelooping"
ROC=TGraph()
ROCwmass=TGraph()
for iitop in xrange(reso):

	ROC.SetPoint(iitop,sigN[iitop]/sigD[iitop],qcdN[iitop]/qcdD[iitop])
	ROCwmass.SetPoint(iitop,sigNwmass[iitop]/sigD[iitop],qcdNwmass[iitop]/qcdD[iitop])
output = ROOT.TFile("histosQCDmassana_"+str(sys.argv[1]).replace(".dat","")+".root","recreate")
output.cd()
print "nncut bkg red"
prelim = TLatex()
prelim.SetNDC()
canvs = []
for ptb in ptbinsform:
	ptstrs = [str(int(2000.0*ptb[0])),str(int(2000.0*ptb[1]))]
	ptstr = ptstrs[0]+"to"+ptstrs[1]
	print ptstr,"L",bgeff*100.*Mplots[ptstr+"postL"].Integral()/(Mplots[ptstr+"pre"].Integral()+Mplots[ptstr+"postL"].Integral()),"%"
	print ptstr,"M",bgeff*100.*Mplots[ptstr+"postM"].Integral()/(Mplots[ptstr+"pre"].Integral()+Mplots[ptstr+"postM"].Integral()),"%"
	print ptstr,"T",bgeff*100.*Mplots[ptstr+"postT"].Integral()/(Mplots[ptstr+"pre"].Integral()+Mplots[ptstr+"postT"].Integral()),"%"
	 
	canvs.append(TCanvas("c"+ptstr))
	if Mplots[ptstr+"postM"].Integral()>0:
		Mplots[ptstr+"pre"].Scale(1.0/Mplots[ptstr+"pre"].Integral())
		Mplots[ptstr+"postM"].Scale(1.0/Mplots[ptstr+"postM"].Integral())

		Mplots[ptstr+"pre"].SetLineColor(1)
Beispiel #8
0
def DoCompareLimitPlots(Channel, tauIsolation, leptonIsolation, LTCut,lowY, highY):
    print "\n\n*********************" , Channel
    for cut0 in FitType:
        Hist = ['hist0', 'hist1', 'hist2', 'hist3']

        canvas = TCanvas()
        gStyle.SetOptStat(0)
        gStyle.SetOptStat(0);
        gStyle.SetOptTitle(0);
        canvas.SetFillColor(0)
        canvas.SetGridx()
        canvas.SetGridy()

        HistBG = TH1F("BG", "", 10, 0, 10)
        HistBG.GetXaxis().SetRangeUser(0, 4)
        HistBG.GetXaxis().SetLabelSize(.05)
        HistBG.GetXaxis().SetTitle("LT(=Pt_{l1} + Pt_{l2}) [GeV]")
        HistBG.GetXaxis().SetTitleOffset(1.4)
        HistBG.GetYaxis().SetRangeUser(lowY, highY)
        HistBG.GetYaxis().SetTitle("Expected Limit")
        for i in range(len(LTCut)):
            HistBG.GetXaxis().SetBinLabel(i + 1, str(LTCut[i]))
        HistBG.Draw()

        InFile = ROOT.TFile.Open("OutFile_" +cut0+Channel+".root", "READ")
        for j in range(len(leptonIsolation)):
            Hist[j] = InFile.Get(str(leptonIsolation[j]))
            Hist[j].SetMarkerStyle(20)
            Hist[j].SetMarkerSize(1.3)
            Hist[j].SetLineWidth(2)
            Hist[j].SetLineColor(j + 6)
            Hist[j].Draw("Plsame")

        l = TLegend(0.70, 0.70, 0.9, 0.9, "", "brNDC")
        l.SetBorderSize(0)
        l.SetFillColor(0)
        l.SetTextSize(.03)
        for k in range(len(leptonIsolation)):
            lgnd = "Isolation < " + str(leptonIsolation[k])
            l.AddEntry(Hist[k], lgnd, "lpf")
        l.Draw()

        #Text in Histogram
        t = TLatex()
        t.SetNDC()
        t.SetTextFont(62)
        t.SetTextAlign(12)
        t.SetTextSize(0.035)
        t.DrawLatex(0.1, .92, "CMS Preliminary 2012")
        t.DrawLatex(0.35, .92, "#sqrt{s} = 8 TeV, L = 19.8 fb^{-1}")
        t.SetTextColor(2)
        t.DrawLatex(0.65, .92, " LL"+Channel)
        t.DrawLatex(0.75, .92, cut0+"Mass")


        canvas.SaveAs("finalCompare_"+cut0 + Channel + "_NewSystematic.pdf")
Beispiel #9
0
h_QCD = TH1F("h_QCD", 'CR Summary plot', len(labels), 0, len(labels))
h_STop = TH1F("h_STop", 'CR Summary plot', len(labels), 0, len(labels))
h_TT = TH1F("h_TT", 'CR Summary plot', len(labels), 0, len(labels))
h_WJets = TH1F("h_WJets", 'CR Summary plot', len(labels), 0, len(labels))
h_DYJets = TH1F("h_DYJets", 'CR Summary plot', len(labels), 0, len(labels))
h_data = TH1F("h_data", 'CR Summary plot', len(labels), 0, len(labels))

myHists = [h_DIBOSON, h_ZJets, h_GJets, h_QCD, h_STop, h_TT, h_WJets, h_DYJets]
colors = [
    kBlue + 2, kAzure + 1, kCyan - 9, kGray + 1, kOrange + 1, kOrange - 2,
    kViolet - 3, kGreen + 2
]

path = 'rootfile/*.root'

latex = TLatex()
latex.SetNDC()
latex.SetTextSize(0.04)
latex.SetTextAlign(31)
latex.SetTextAlign(11)

files = sorted(glob.glob(path))

for file in files:
    f = TFile.Open(file, 'read')
    print(f)
    if 'Mu' in file.split('/')[-1]:
        h_DIBOSON_mu = f.Get('DIBOSON')
        h_ZJets_mu = f.Get('ZJets')
        h_GJets_mu = f.Get('GJets')
        h_QCD_mu = f.Get('QCD')
    # ____________________________________________________________________________
    # Setup basic drawer
    gROOT.LoadMacro("tdrstyle.C")
    gROOT.ProcessLine("setTDRStyle();")
    #gROOT.SetBatch(True)
    gStyle.SetPadGridX(True)
    gStyle.SetPadGridY(True)
    gStyle.SetMarkerStyle(1)
    gStyle.SetEndErrorSize(0)
    gROOT.ForceStyle()

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

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

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

    tlatexCMS3 = TLatex()
    tlatexCMS3.SetNDC()
    tlatexCMS3.SetTextFont(42)
    tlatexCMS3.SetTextSize(0.60 * 0.05)
    tlatexCMS3.SetTextAlign(11)
Beispiel #11
0
def compare_num_den(ratio=ratio):
    ###

    for i, a in enumerate(sample_list):
        print a

        chain[a] = TChain("trigger/tree")
        for j, ss in enumerate(sign_sampl[a]['files']):
            print "ss: ", ss
            chain[a].Add(NTUPLEDIR + ss + ".root")
        if variable[options.variable]['nbins'] > 0:
            hist[a] = TH1F(a, ";" + variable[options.variable]['title'],
                           variable[options.variable]['nbins'],
                           variable[options.variable]['min'],
                           variable[options.variable]['max'])
            hist_num[a] = TH1F(a + "_num",
                               ";" + variable[options.variable]['title'],
                               variable[options.variable]['nbins'],
                               variable[options.variable]['min'],
                               variable[options.variable]['max'])
        hist_num[a].Sumw2()
        hist[a].Sumw2()

        print "variable: ", options.variable
        if "signal" in a:
            chain[a].Project(a, options.variable, cut_den_signal)
            print "cut denominator signal: ", cut_den_signal
            print "cut numerator signal: ", cut_num_signal
        else:
            chain[a].Project(a, options.variable, cut_den)
            print "cut denominator: ", cut_den
            print "cut numerator: ", cut_num

        hist[a].SetOption("%s" % chain[a].GetTree().GetEntriesFast())

        if "signal" in a:
            chain[a].Project(a + "_num", options.variable, cut_num_signal)
        else:
            chain[a].Project(a + "_num", options.variable, cut_num)

        hist_num[a].SetOption("%s" % chain[a].GetTree().GetEntriesFast())

        if options.variable == "nPV":
            bins = np.array([0., 10., 15., 20., 25., 30., 35., 40., 50., 70.])
        else:
            bins = np.array([
                0., 20., 40., 60., 80., 100., 120., 140., 160., 180., 200.,
                250., 300., 500., 1000.
            ])
            if len(bins_special):
                bins = bins_special

        if REBIN:
            hist[a] = hist[a].Rebin(len(bins) - 1, a + "_den2", bins)
            hist_num[a] = hist_num[a].Rebin(len(bins) - 1, a + "_num2", bins)

    can = TCanvas("can", "can", 1000, 800)  #900 if ratio else 800)
    if COMPARE != "":
        can.Divide(1, 2)
        setTopPad(can.GetPad(1), ratio)
        setBotPad(can.GetPad(2), ratio)
        can.cd(1)
        can.cd(1).SetGrid()
    else:
        ratio = 0
        can.SetGrid()
        can.cd()

    if ratio:
        if probe != PROBEL1:
            #leg = TLegend(0.12+0.3, 0.1, 0.68+0.2, 0.3)#0.45)
            leg = TLegend(0.12 + 0.3, 0.1, 0.68 + 0.25,
                          0.3 + 0.15)  #0.45)#DCMS
        else:
            #leg = TLegend(0.12+0.3, 0.1, 0.68+0.2, 0.3)#0.45)
            leg = TLegend(0.12 + 0.3, 0.1, 0.68 + 0.5, 0.3 + 0.5)  #0.45)
        leg.SetTextSize(0.032)
        leg.SetTextSize(0.045)  #DCMS

    else:
        if probe != PROBEL1:
            leg = TLegend(0.1, 0.75, 0.68, 0.88)  #0.45)
        else:
            leg = TLegend(0.1, 0.12, 0.68, 0.25)  #0.45)
        leg.SetTextSize(0.028)

    if "DPG" in options.cut:
        leg = TLegend(0.3, 0.12, 0.88, 0.35)

    if not options.efficiency:
        can.SetLogy()
        leg = TLegend(0.5, 0.65, 0.68, 0.9)  #0.45)
        leg.SetTextSize(0.028)

    #leg.SetFillStyle(0)

    for i, s in enumerate(sample_list):
        if options.efficiency:
            graph[s] = TGraphAsymmErrors()
            graph[s].BayesDivide(hist_num[s], hist[s])
        else:
            if options.normalized:
                hist[s].Scale(1. / hist[s].Integral())
                hist_num[s].Scale(1. / hist_num[s].Integral())
            graph[s] = TGraphAsymmErrors(hist[s])
            graph_num[s] = TGraphAsymmErrors(hist_num[s])
        graph[s].SetMarkerSize(1.)
        graph[s].SetMarkerStyle(markers[i])  #(sign_sampl[s]['marker'])
        graph[s].SetMarkerColor(colors[i])  #(2)
        graph[s].SetFillColor(colors[i])  #(2)
        graph[s].SetLineColor(colors[i])  #(2)
        graph[s].SetLineWidth(2)
        if options.efficiency:
            graph[s].GetYaxis().SetRangeUser(0., maxeff)
            graph[s].GetYaxis().SetTitle(
                "Efficiency")  #("Efficiency (L1+HLT)")
            graph[s].GetYaxis().SetTitleOffset(0.9)  #("Efficiency (L1+HLT)")
            graph[s].GetYaxis().SetTitleSize(0.05)  #DCMS
        else:
            graph[s].SetMinimum(0.01)
            graph_num[s].SetMarkerSize(1.)
            graph_num[s].SetMarkerStyle(markers[i])  #(sign_sampl[s]['marker'])
            graph_num[s].SetMarkerColor(colors[i + 3])  #(2)
            graph_num[s].SetFillColor(colors[i + 3])  #(2)
            graph_num[s].SetLineColor(colors[i + 3])  #(2)
            graph_num[s].SetLineWidth(2)
            graph_num[s].SetLineStyle(2)
        graph[s].GetXaxis().SetRangeUser(variable[options.variable]['min'],
                                         variable[options.variable]['max'])
        graph[s].GetXaxis().SetTitle(variable[options.variable]['title'])
        graph[s].GetXaxis().SetTitleSize(0.04)  #DCMS
        graph[s].GetXaxis().SetTitleOffset(1.1)
        #?#if COMPARE=="":
        #?#    graph[s].GetYaxis().SetTitleOffset(1.5)
        #?#else:
        #?#    graph[s].GetYaxis().SetTitleOffset(1)
        eff[s] = TH1F()
        eff[s].Sumw2()
        eff[s] = hist_num[s].Clone("eff_" + s)
        eff[s].Divide(eff[s], hist[s], 1, 1, "cl=0.683 b(1,1) mode")
        if i == 0:
            graph[s].Draw("AP")
        else:
            graph[s].Draw("P,sames")

        if not options.efficiency:
            graph_num[s].Draw("P,sames")
            if PROBE_label != "":
                leg.SetHeader("#splitline{Ref: " + ref + "}{" + PROBE_label +
                              "}")
            else:
                leg.SetHeader("#splitline{Ref: " + ref + "}{" + probe + "}")
            leg.AddEntry(graph[s], s + ', den', 'PL')
            leg.AddEntry(graph_num[s], s + ', num', 'PL')

        if COMPARE != "" and options.efficiency:
            if PROBE_label != "":
                leg.SetHeader("#splitline{Ref: " + ref + "}{Probe: " +
                              PROBE_label + "}")
            else:
                leg.SetHeader("#splitline{Ref: " + ref + "}{" + probe + "}")
            if s == "signal":
                leg.AddEntry(graph[s], "Signal, m_{#pi} = 15, 20 GeV", 'PL')
            else:
                leg.AddEntry(graph[s], s, 'PL')

        elif COMPARE == "" and options.efficiency:
            leg.SetHeader("Ref: " + ref)
            if PROBE_label == "":
                leg.AddEntry(graph[s], probe, 'PL')
            else:
                leg.AddEntry(graph[s], PROBE_label, 'PL')

        if "DPG" in options.cut:
            leg.Clear()
            leg.SetHeader("Den: #mu trigger & 1 offline #mu; num: L1 seed")
            #leg.AddEntry(graph[s],s,'PL')
            leg.SetTextSize(0.036)

            #new_file = TFile("macro/rootfiles/MET_trigger_eff_data_" + sign_sampl[s]['label'] + sign_sampl[s]['howmany'] + "_" + str(options.variable) + "_" +  options.dataset+ "_v5.root",'RECREATE')
            #graph[s].Write("graph_2018")

    if "DPG" in options.cut:
        leg.Clear()
        leg.SetHeader("Den: #mu trigger & 1 offline #mu; num: L1 seed")
        leg.AddEntry(graph[name_data], 'Data', 'PL')
        leg.AddEntry(graph[name_mc], 'MC backgrounds', 'PL')
        leg.SetTextSize(0.036)

    leg.SetBorderSize(0)
    leg.Draw()

    etichetta = TLatex()
    etichetta.SetNDC()
    etichetta.SetTextSize(0.04)
    etichetta.SetTextColor(1)
    if COMPARE == "":
        etichetta.DrawLatex(0.3, 0.4, sign_sampl[s]['nice_label'])

    latex = TLatex()
    latex.SetNDC()
    latex.SetTextSize(0.047)
    latex.SetTextColor(1)
    latex.SetTextFont(42)
    latex.SetTextAlign(33)
    latex.SetTextSize(0.051)  #47
    if LUMI > 0:
        if ratio:
            #latex.DrawLatex(0.9, 0.985, "%.1f fb^{-1}  (13 TeV, 2016)" % (float(LUMI/1000.)))
            latex.DrawLatex(0.9, 0.99, "%.1f fb^{-1}  (13 TeV, 2016)" %
                            (float(LUMI / 1000.)))  #DCMS
        else:
            latex.DrawLatex(
                0.9, 0.96,
                "%.1f fb^{-1}  (13 TeV, 2016)" % (float(LUMI / 1000.)))
    latex.SetTextFont(62)
    if ratio:
        latex.DrawLatex(0.20, 0.98, "CMS")
    else:
        latex.DrawLatex(0.20, 0.96, "CMS")
    latex.SetTextFont(52)
    if "DPG" in options.cut:
        if ratio:
            latex.DrawLatex(0.46, 0.98, "Work in Progress")
        else:
            latex.DrawLatex(0.46, 0.96, "Work in Progress")
    else:
        if ratio:
            if "SingleMu" in name_data:
                latex.DrawLatex(0.36, 0.98, "Preliminary")
            else:
                latex.DrawLatex(0.36, 0.98, "Simulation")
        else:
            if "SingleMu" in name_data:
                latex.DrawLatex(0.36, 0.96, "Preliminary")
            else:
                latex.DrawLatex(0.36, 0.96, "Simulation")

    can.Update()

    if COMPARE and name_mc != "" and name_data != "":
        can.cd(2)
        can.cd(2).SetGrid()
        err = eff[name_mc].Clone("EffErr;")
        err.SetTitle("")
        err.GetYaxis().SetTitle("Data / MC")
        err.GetYaxis().SetTitleOffset(0.9)
        err.GetYaxis().SetTitleSize(0.05)  #DCMS
        err.GetXaxis().SetTitleSize(0.05)  #DCMS
        for a in range(1, err.GetNbinsX() + 1):
            err.SetBinContent(a, 1)
            if eff[name_mc].GetBinContent(a) > 0:
                err.SetBinError(a, eff[name_mc].GetBinError(
                    a))  #?#/eff[name_mc].GetBinContent(a))
        setBotStyle(err, miny=0.5, maxy=1.5)
        errLine = err.Clone("errLine")
        errLine.SetLineWidth(2)
        errLine.SetFillStyle(0)
        errLine.SetLineColor(2)  #L#
        errLine.SetLineStyle(2)  #L#
        err.Draw("E2")
        errLine.Draw("SAME, HIST")
        res = eff[name_data].Clone("Residues")
        for a in range(0, res.GetNbinsX() + 1):
            if eff[name_mc].GetBinContent(a) > 0:
                res.SetBinContent(
                    a,
                    res.GetBinContent(a) / eff[name_mc].GetBinContent(a))
                res.SetBinError(
                    a,
                    res.GetBinError(a) / eff[name_mc].GetBinContent(a))
        setBotStyle(res, miny=0., maxy=2.)
        res.SetMarkerStyle(21)
        res.SetMarkerColor(1)
        res.SetLineColor(1)
        res.SetLineWidth(1)
        res.Draw("SAME, PE0")
    can.Update()

    outpath = ""
    outpath += "/afs/desy.de/user/l/lbenato/LLP_code/CMSSW_8_0_26_patch1/src/Analyzer/LLP/macro/TriggerTurnOn/"

    if not options.efficiency:
        outpath += "Distributions/"

    if options.goodplots:
        outpath = "/afs/desy.de/user/l/lbenato/LLP_code/CMSSW_8_0_26_patch1/src/Analyzer/LLP/macro/TriggerTurnOn/good_plots/"

    if COMPARE != "":
        compare_string = "_vs_" + COMPARE + "_"
    else:
        compare_string = ""

    if options.normalized:
        norm_label = "_norm"
    else:
        norm_label = ""

    if SAVE:
        if PROBE_label == "":
            can.Print(outpath + "TriggerTurnOn_" + sign_sampl[s]['label'] +
                      sign_sampl[s]['howmany'] + compare_string + "_" +
                      str((options.variable).replace('.', '_')) + "_" +
                      str(probe) + "_" + str(options.cut) + "_" +
                      options.dataset + goodstring + norm_label +
                      "_v8trigger_DCMS.png")
            can.Print(outpath + "TriggerTurnOn_" + sign_sampl[s]['label'] +
                      sign_sampl[s]['howmany'] + compare_string + "_" +
                      str((options.variable).replace('.', '_')) + "_" +
                      str(probe) + "_" + str(options.cut) + "_" +
                      options.dataset + goodstring + norm_label +
                      "_v8trigger_DCMS.pdf")

        else:
            can.Print(outpath + "TriggerTurnOn_" + sign_sampl[s]['label'] +
                      sign_sampl[s]['howmany'] + compare_string + "_" +
                      str((options.variable).replace('.', '_')) + "_" +
                      PROBE_label + "_" + str(options.cut) + "_" +
                      options.dataset + goodstring + norm_label +
                      "_v8trigger_DCMS.png")
            can.Print(outpath + "TriggerTurnOn_" + sign_sampl[s]['label'] +
                      sign_sampl[s]['howmany'] + compare_string + "_" +
                      str((options.variable).replace('.', '_')) + "_" +
                      PROBE_label + "_" + str(options.cut) + "_" +
                      options.dataset + goodstring + norm_label +
                      "_v8trigger_DCMS.pdf")

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
Beispiel #12
0
    can.Print(output_title)


if __name__ == '__main__':

    input_filename = 'histos.root'
    input_file = TFile(input_filename)
    histos = load_histos(input_file)
    print(histos.keys())

    gStyle.SetOptStat(0)
    gStyle.SetOptTitle(0)
    gStyle.SetPalette(57)

    can = TCanvas('can', 'can', 1080, 720)
    tex = TLatex()
    tex.SetNDC()
    tex.SetTextFont(42)
    tex.SetTextSize(0.05)
    tex.SetTextColor(1)

    lab = TLatex()
    lab.SetNDC()
    lab.SetTextFont(42)
    lab.SetTextSize(0.04)
    lab.SetTextColor(1)
    """
    can.cd(1)
    histos['histos_w_ctof_proton'].SetLineColor(1)
    histos['histos_w_ctof_proton'].Draw('same')
    histos['histos_w_ctof_proton_pass_angle'].SetLineColor(55)
Beispiel #13
0
def plot_map_root(file_path, map_name, wp):
    from ROOT import gStyle, gROOT, TFile, TCanvas, TF1, TLatex
    import os
    # rho_min = -6.0
    # rho_max = -2.1
    # pt_min = 200
    # pt_max = 1200
    rho_min = -10
    rho_max = 0
    pt_min = 0
    pt_max = 1500
    disc_min = 0.12
    disc_max = 0.3
    left_margin = 0.14
    right_margin = 0.16
    top_margin = 0.08
    bottom_margin = 0.12
    out_dir = os.path.dirname(file_path)
    out_file_path = out_dir+("/" if len(out_dir)>0 else "")+map_name;
    gStyle.SetPadTickY(1)
    gStyle.SetPadTickX(1)
    gStyle.SetLegendBorderSize(0)
    
    gROOT.SetBatch(True)
    gStyle.SetOptStat(0)
    gStyle.SetOptFit(0)
    gStyle.SetTitleOffset(0.86,"X")
    gStyle.SetTitleOffset(1.6,"Y")
    gStyle.SetPadLeftMargin(left_margin)
    gStyle.SetPadBottomMargin(bottom_margin)
    gStyle.SetPadTopMargin(top_margin)
    gStyle.SetPadRightMargin(right_margin)
    
    gStyle.SetMarkerSize(0.5)
    gStyle.SetHistLineWidth(1)
    gStyle.SetTitleSize(0.05, "XYZ")
    gStyle.SetLabelSize(0.04, "XYZ")
    gStyle.SetNdivisions(506, "XYZ")
    gStyle.SetNumberContours(25)
    gStyle.SetLegendBorderSize(0)
    f = TFile(file_path)
    hist = f.Get(map_name)
  
    hist.GetXaxis().SetTitle("#rho")
    hist.GetYaxis().SetTitle("p_{T} [GeV]")
    if('n2' in map_name.lower()):
        hist.GetZaxis().SetTitle("N2^{DDT} %.1f"%(wp*100)+"% quantile")
    else:
        hist.GetZaxis().SetTitle("DeepBoosted WvsQCD %.1f"%(wp*100)+"% quantile")
        disc_max=1
    hist.GetXaxis().SetRangeUser(rho_min, rho_max)
    hist.GetYaxis().SetRangeUser(pt_min, pt_max)
    if(disc_max>hist.GetMaximum()):
        hist.GetZaxis().SetRangeUser(disc_min, disc_max)

    Font=43
    TitleSize=24.0
    TitleOffset=1.3
    LabelSize=18.0
    hist.GetYaxis().SetTitleFont(Font)
    hist.GetYaxis().SetTitleSize(TitleSize)
    hist.GetYaxis().SetTitleOffset(TitleOffset)
    hist.GetYaxis().SetLabelFont(Font)
    hist.GetYaxis().SetLabelSize(LabelSize)

    hist.GetXaxis().SetTitleFont(Font)
    hist.GetXaxis().SetTitleSize(TitleSize)
    hist.GetXaxis().SetTitleOffset(TitleOffset)
    hist.GetXaxis().SetLabelFont(Font)
    hist.GetXaxis().SetLabelSize(LabelSize)
    
    hist.GetZaxis().SetTitleFont(Font)
    hist.GetZaxis().SetTitleSize(TitleSize)
    hist.GetZaxis().SetTitleOffset(TitleOffset)
    hist.GetZaxis().SetLabelFont(Font)
    hist.GetZaxis().SetLabelSize(LabelSize)
    
    hist.GetZaxis().SetNdivisions(510)
    
    hist.SetTitle(map_name.replace('_',' '))
    hist.SetTitleFont(43)
    hist.SetTitleSize(18.0)
	
    # isomasses = [20,55,80,120,200]
    # isomasses = [20,65,80,125,200]
    # isomasses = range(40,200,20)
    isomasses = [40,80,120,200]
    str_isomass = "%.2f*TMath::Exp(-x/2)"
    tf1_isomasses = []
    for i in range(len(isomasses)):
        msd = isomasses[i]
        new_isomass = TF1('isomass_%i'%int(msd),str_isomass%msd,rho_min,rho_max)
        # new_isomass.SetLineColor(920+i)
        new_isomass.SetLineColorAlpha(1,0.4)
        tf1_isomasses.append(new_isomass)


    c1 = TCanvas("c1","c1",700,600)
    c1.cd()
    hist.Draw("colz")
    latex = TLatex()
    latex.SetNDC(1)
    latex.SetTextColor(1)
    latex.SetTextFont(43)
    latex.SetTextSize(15.5)
    latex.SetTextAngle(297)
    for i in range(len(isomasses)):
        x_pitch = (1-left_margin-right_margin)/(rho_max-rho_min)
        y_pitch = (1-bottom_margin-top_margin)/(pt_max-pt_min)
        msd = isomasses[i]
        pt=msd*np.exp(-rho_min/2)
        pt = 0.5*(pt_max-pt_min)+pt_min if pt > pt_max else pt
        angle = ((180/np.pi)*np.arctan(2*x_pitch/(pt*y_pitch)))+272
        latex.SetTextAngle(angle)
        tf1_isomass = tf1_isomasses[i]
        tf1_isomass.Draw('SAME')
        x_pos = left_margin+((2*np.log(msd/pt)-rho_min))*x_pitch+0.01
        y_pos = bottom_margin+(pt-pt_min)*y_pitch +0.01
        latex.DrawLatex(x_pos,y_pos,'m_{SD} = %.1f GeV'%msd)
    c1.SaveAs(out_file_path+".pdf")
    del c1
    myhist["meas1"] = TH1D("myhist_meas1", "meas1", 256, -0.7, 0.5)
    ### Then get the saved histogram into the new one and normalize to ns from s by *1.e9
    mytree["meas1"].Draw("area*1.e9>>myhist_meas1", "", "")

    today = datetime.date.today()
    fTag = today.strftime("%Y%m%d")
    fName = options.input
    i = fName.find("/")
    while i > 0:
        fName = fName[i + 1:]
        i = fName.find("/")
    fName = fName[:-5]

    myhist["meas1"].SetTitle("%s" % fName)
    myhist["meas1"].GetXaxis().SetTitle("area [V#times ns]")
    myhist["meas1"].GetYaxis().SetTitle("counts")

    c1.Update()

    ## Fit meas1
    fitopt = [0.05, 0.04]
    vEng_1, sFit_1, myfit_1 = AlphaSourceFitter().GausFitEngPeak(
        myhist["meas1"], "meas1", fitopt, 1.)

    t = TLatex(-0.6, 1600, "peak = %f#pm%f V#times ns" % (vEng_1, sFit_1))
    t.Draw()

    if (os.path.isdir("Results/%s" % fTag)) == False:
        os.mkdir("Results/%s" % fTag)
    c1.SaveAs("Results/%s/%s.pdf" % (fTag, fName))
Beispiel #15
0
def limit(channel, signal):
    multF = 1.  # in fb
    filename = "./limitOutput_" + options.name + "/" + signal + "_MChi1_MPhi%d_scalar" + options.bjets + "_" + channel + "_AsymptoticLimits_grepOutput.txt"
    if (options.mediator == 'SC'):
        filename = "./limitOutput_" + options.name + "/" + signal + "_MChi1_MPhi%d_scalar" + options.bjets + "_" + channel + "_AsymptoticLimits_grepOutput.txt"
    elif (options.mediator == 'PS'):
        filename = "./limitOutput_" + options.name + "/" + signal + "_MChi1_MPhi%d_pseudo" + options.bjets + "_" + channel + "_AsymptoticLimits_grepOutput.txt"
    else:
        print 'WRONG mediator type'
    mass, val = fillValues(filename)

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

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

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

    Exp2s.SetLineWidth(2)
    Exp2s.SetLineStyle(1)
    Obs0s.SetLineWidth(3)
    Obs0s.SetMarkerStyle(0)
    Obs0s.SetLineColor(1)
    Exp0s.SetLineStyle(2)
    Exp0s.SetLineWidth(3)
    Exp1s.SetFillColor(417)  #kGreen+1
    Exp1s.SetLineColor(417)  #kGreen+1
    Exp2s.SetFillColor(800)  #kOrange
    Exp2s.SetLineColor(800)  #kOrange
    Exp2s.GetXaxis().SetTitle("m_{#phi} (GeV)")
    Exp2s.GetXaxis().SetTitleSize(Exp2s.GetXaxis().GetTitleSize() * 1.25)
    Exp2s.GetXaxis().SetNoExponent(True)
    Exp2s.GetXaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetTitle("#sigma/#sigma_{th}")
    Exp2s.GetYaxis().SetTitleOffset(1.5)
    Exp2s.GetYaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetMoreLogLabels()

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

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

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

    c1 = TCanvas("c1", "Exclusion Limits", 800, 600)
    c1.cd()
    #SetPad(c1.GetPad(0))
    c1.GetPad(0).SetTopMargin(0.06)
    c1.GetPad(0).SetRightMargin(0.05)
    c1.GetPad(0).SetTicks(1, 1)
    #c1.GetPad(0).SetGridx()
    #c1.GetPad(0).SetGridy()
    c1.GetPad(0).SetLogx()
    c1.GetPad(0).SetLogy()
    Exp2s.Draw("A3")
    Exp1s.Draw("SAME, 3")
    Exp0s.Draw("SAME, L")
    if not options.blind: Obs0s.Draw("SAME, L")
    #Theory[0].Draw("SAME, L")
    #Theory[1].Draw("SAME, L")
    #setHistStyle(Exp2s)
    Exp2s.GetXaxis().SetTitleSize(0.045)
    Exp2s.GetXaxis().SetMoreLogLabels(True)
    Exp2s.GetXaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetTitleSize(0.04)
    Exp2s.GetXaxis().SetLabelSize(0.04)
    Exp2s.GetYaxis().SetLabelSize(0.04)
    Exp2s.GetXaxis().SetTitleOffset(1)
    Exp2s.GetYaxis().SetTitleOffset(1.25)
    Exp2s.GetYaxis().SetMoreLogLabels(True)
    Exp2s.GetYaxis().SetNoExponent(True)
    Exp2s.GetYaxis().SetRangeUser(0.1, 1000.)
    #else: Exp2s.GetYaxis().SetRangeUser(0.1, 1.e2)
    Exp2s.GetXaxis().SetRangeUser(mass[0], mass[-1])
    drawAnalysis("tDM")
    drawRegion(channel, True)
    drawCMS(LUMI, "Preliminary")

    if True:
        if (options.mediator == 'SC'):
            massT, valT = fillValues("./limitOutput_" + options.name + "/" +
                                     signal.replace('tttDM', 'tDM') +
                                     "_MChi1_MPhi%d_scalar" + options.bjets +
                                     "_" + channel +
                                     "_AsymptoticLimits_grepOutput.txt")
        elif (options.mediator == 'PS'):
            massT, valT = fillValues("./limitOutput_" + options.name + "/" +
                                     signal.replace('tttDM', 'tDM') +
                                     "_MChi1_MPhi%d_pseudo" + options.bjets +
                                     "_" + channel +
                                     "_AsymptoticLimits_grepOutput.txt")
        ExpT, ObsT = TGraphAsymmErrors(), TGraphAsymmErrors()
        for i, m in enumerate(massT):
            if not m in val: continue
            ExpT.SetPoint(ExpT.GetN(), m, valT[m][3] * multF)
            ObsT.SetPoint(ObsT.GetN(), m, valT[m][0] * multF)
        ExpT.SetLineWidth(3)
        ExpT.SetLineColor(602)  #602
        ExpT.SetLineStyle(5)
        ObsT.SetLineWidth(3)
        ObsT.SetLineColor(602)
        ExpT.SetMarkerStyle(21)
        ObsT.SetMarkerStyle(22)
        ExpT.SetMarkerColor(602)
        ObsT.SetMarkerColor(602)
        ExpT.Draw("SAME, PC")
        #if not options.blind: ObsT.Draw("SAME, P")

        if (options.mediator == 'SC'):
            massTTT, valTTT = fillValues("./limitOutput_" + options.name +
                                         "/" +
                                         signal.replace('tttDM', 'ttDM') +
                                         "_MChi1_MPhi%d_scalar" +
                                         options.bjets + "_" + channel +
                                         "_AsymptoticLimits_grepOutput.txt")
        elif (options.mediator == 'PS'):
            massTTT, valTTT = fillValues("./limitOutput_" + options.name +
                                         "/" +
                                         signal.replace('tttDM', 'ttDM') +
                                         "_MChi1_MPhi%d_pseudo" +
                                         options.bjets + "_" + channel +
                                         "_AsymptoticLimits_grepOutput.txt")

        ExpTTT, ObsTTT = TGraphAsymmErrors(), TGraphAsymmErrors()
        for i, m in enumerate(massTTT):
            if not m in val: continue
            ExpTTT.SetPoint(ExpTTT.GetN(), m, valTTT[m][3] * multF)
            ObsTTT.SetPoint(ObsTTT.GetN(), m, valTTT[m][0] * multF)
        ExpTTT.SetLineWidth(3)
        ExpTTT.SetLineColor(634)  #602
        ExpTTT.SetLineStyle(5)
        ObsTTT.SetLineWidth(3)
        ObsTTT.SetLineColor(634)
        ExpTTT.SetMarkerStyle(21)
        ObsTTT.SetMarkerStyle(22)
        ExpTTT.SetMarkerColor(634)
        ObsTTT.SetMarkerColor(634)
        ExpTTT.Draw("SAME, PC")
        #if not options.blind: ObsTTT.Draw("SAME, P")

    # legend
    top = 0.9
    nitems = 4 + 2

    leg = TLegend(0.55, top - nitems * 0.3 / 5., 0.95, top)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    leg.SetHeader("95% CL limits")
    leg.AddEntry(Obs0s, "Observed", "l")
    leg.AddEntry(Exp0s, "Expected (t+DM, tt+DM)", "l")
    leg.AddEntry(Exp1s, "#pm 1 s. d.", "f")
    leg.AddEntry(Exp2s, "#pm 2 s. d.", "f")
    if True:
        leg.AddEntry(ExpT, "Expected (t+DM)", "p")
        leg.AddEntry(ExpTTT, "Expected (tt+DM)", "p")

    leg.Draw()
    c1.GetPad(0).RedrawAxis()
    c1.GetPad(0).Update()
    if gROOT.IsBatch():
        c1.Print("plotsLimit_" + options.name + "/Exclusion_" + channel + "_" +
                 options.mediator + "_" + options.bjets + ".png")
        c1.Print("plotsLimit_" + options.name + "/Exclusion_" + channel + "_" +
                 options.mediator + "_" + options.bjets + ".pdf")

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

    #    print "p1s[",
    #    for i in range(Exp0s.GetN()):
    #        print Exp0s.GetY()[i]+Exp1s.GetErrorYhigh(i), ",",
    #    print "],"
    #    print "m1s[",
    #    for i in range(Exp0s.GetN()):
    #        print Exp0s.GetY()[i]-Exp1s.GetErrorYlow(i), ",",
    #    print "],"
    #    print "[",
    #    for i in range(Exp0s.GetN()):
    #        print Exp0s.GetY()[i], ",",
    #    print "]"

    return

    # ---------- Significance ----------
    c2 = TCanvas("c2", "Significance", 800, 600)
    c2.cd()
    c2.GetPad(0).SetTopMargin(0.06)
    c2.GetPad(0).SetRightMargin(0.05)
    c2.GetPad(0).SetTicks(1, 1)
    c2.GetPad(0).SetGridx()
    c2.GetPad(0).SetGridy()
    Sign.GetYaxis().SetRangeUser(0., 5.)
    Sign.Draw("AL3")
    drawCMS(LUMI, "Preliminary")
    drawAnalysis(channel[1:3])
    if gROOT.IsBatch():
        c2.Print("plotsLimit_" + options.name + "/Significance/" + channel +
                 "_" + options.mediator + "_" + options.bjets + ".png")
        c2.Print("plotsLimit_" + options.name + "/Significance/" + channel +
                 "_" + options.mediator + "_" + options.bjets + ".pdf")
#    c2.Print("plotsLimit/Significance/"+channel+suffix+".root")
#    c2.Print("plotsLimit/Significance/"+channel+suffix+".C")

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

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

    drawCMS(LUMI, "Preliminary")
    drawAnalysis(channel[1:3])
    if gROOT.IsBatch():
        c3.Print("plotsLimit_" + options.name + "/pValue/" + channel + suffix +
                 "_" + options.mediator + "_" + options.bjets + ".png")
        c3.Print("plotsLimit_" + options.name + "/pValue/" + channel + suffix +
                 "_" + options.mediator + "_" + options.bjets + ".pdf")
#    c3.Print("plotsLimit/pValue/"+channel+suffix+".root")
#    c3.Print("plotsLimit/pValue/"+channel+suffix+".C")

# --------- Best Fit ----------
    c4 = TCanvas("c4", "Best Fit", 800, 600)
    c4.cd()
    c4.GetPad(0).SetTopMargin(0.06)
    c4.GetPad(0).SetRightMargin(0.05)
    c4.GetPad(0).SetTicks(1, 1)
    c4.GetPad(0).SetGridx()
    c4.GetPad(0).SetGridy()
    Best.Draw("AL3")
    drawCMS(LUMI, "Preliminary")
    drawAnalysis(channel[1:3])
    if gROOT.IsBatch():
        c4.Print("plotsLimit_" + options.name + "/BestFit/" + channel +
                 suffix + "_" + options.mediator + "_" + options.bjets +
                 ".png")
        c4.Print("plotsLimit_" + options.name + "/BestFit/" + channel +
                 suffix + "_" + options.mediator + "_" + options.bjets +
                 ".pdf")


#    c4.Print("plotsLimit/BestFit/"+channel+suffix+".root")
#    c4.Print("plotsLimit/BestFit/"+channel+suffix+".C")

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

    file2016B = open("default2016Pt/PtResolutionVsPt_%s_B.pkl" % trackType,
                     'rb')
    file2016O = open("default2016Pt/PtResolutionVsPt_%s_O.pkl" % trackType,
                     'rb')
    file2016E = open("default2016Pt/PtResolutionVsPt_%s_E.pkl" % trackType,
                     'rb')
    file2017B = open("defaultPtSplit/PtResolutionVsPt_%s_B.pkl" % trackType,
                     'rb')
    file2017O = open("defaultPtSplit/PtResolutionVsPt_%s_O.pkl" % trackType,
                     'rb')
    file2017E = open("defaultPtSplit/PtResolutionVsPt_%s_E.pkl" % trackType,
                     'rb')
    file2018B = open("default2018Pt/PtResolutionVsPt_%s_B.pkl" % trackType,
                     'rb')
    file2018O = open("default2018Pt/PtResolutionVsPt_%s_O.pkl" % trackType,
                     'rb')
    file2018E = open("default2018Pt/PtResolutionVsPt_%s_E.pkl" % trackType,
                     'rb')

    results2016B = pickle.load(file2016B)
    results2016O = pickle.load(file2016O)
    results2016E = pickle.load(file2016E)

    results2017B = pickle.load(file2017B)
    results2017O = pickle.load(file2017O)
    results2017E = pickle.load(file2017E)

    results2018B = pickle.load(file2018B)
    results2018O = pickle.load(file2018O)
    results2018E = pickle.load(file2018E)

    graph2016B = getGraph(results2016B, "2016B")
    graph2016O = getGraph(results2016O, "2016O")
    graph2016E = getGraph(results2016E, "2016E")

    graph2017B = getGraph(results2017B, "2017B")
    graph2017O = getGraph(results2017O, "2017O")
    graph2017E = getGraph(results2017E, "2017E")

    graph2018B = getGraph(results2018B, "2018B")
    graph2018O = getGraph(results2018O, "2018O")
    graph2018E = getGraph(results2018E, "2018E")

    canv = TCanvas("c1", "c1", 800, 1200)

    plotPad = TPad("plotPad", "plotPad", 0, 0., 1, 1)
    # ~ ratioPad = TPad("ratioPad","ratioPad",0,0.,1,0.3)
    style = setTDRStyle()
    gStyle.SetOptStat(0)
    plotPad.UseCurrentStyle()
    # ~ ratioPad.UseCurrentStyle()
    plotPad.Draw()
    # ~ ratioPad.Draw()
    plotPad.cd()
    plotPad.cd()
    plotPad.SetGrid()
    gStyle.SetTitleXOffset(1.45)
    gStyle.SetTitleYOffset(1.55)

    xMax = 0.15
    if trackType == "Inner":
        xMax = 0.3
    if trackType == "Outer":
        xMax = 0.5

    plotPad.DrawFrame(0, 0, 2000, xMax, ";p_{T} [GeV]; p_{T} resolution [%]")

    graph2016B.Draw("samepe")
    # ~ graph2016O.Draw("samepe")
    graph2016E.Draw("samepe")
    graph2016B.SetLineColor(kRed)
    graph2016B.SetMarkerColor(kRed)
    graph2016O.SetLineColor(kGreen)
    graph2016O.SetMarkerColor(kGreen)
    graph2016E.SetLineColor(kBlue)
    graph2016E.SetMarkerColor(kBlue)

    latex = TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)
    latex.SetNDC(True)
    latexCMS = TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.055)
    latexCMS.SetNDC(True)
    latexCMSExtra = TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.03)
    latexCMSExtra.SetNDC(True)

    latex.DrawLatex(0.95, 0.96, "(13 TeV)")

    cmsExtra = "#splitline{Preliminary}{}"
    latexCMS.DrawLatex(0.19, 0.88, "CMS")
    if "Simulation" in cmsExtra:
        yLabelPos = 0.81
    else:
        yLabelPos = 0.84

    latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))

    leg = TLegend(0.52, 0.76, 0.95, 0.91, "%s 2016" % trackType, "brNDC")
    leg.SetFillColor(10)
    leg.SetFillStyle(0)
    leg.SetLineColor(10)
    leg.SetShadowColor(0)
    leg.SetBorderSize(1)
    leg.AddEntry(graph2016B, "Barrel", "l")
    # ~ leg.AddEntry(graph2016O,"Overlap","l")
    leg.AddEntry(graph2016E, "Endcap", "l")

    leg.Draw()

    plotPad.RedrawAxis()

    canv.Print("PtResolutionCompare_%s_2016.pdf" % trackType)
    canv.Print("PtResolutionCompare_%s_2016.root" % trackType)

    canv = TCanvas("c1", "c1", 800, 1200)

    plotPad = TPad("plotPad", "plotPad", 0, 0., 1, 1)
    # ~ ratioPad = TPad("ratioPad","ratioPad",0,0.,1,0.3)
    style = setTDRStyle()
    gStyle.SetOptStat(0)
    plotPad.UseCurrentStyle()
    # ~ ratioPad.UseCurrentStyle()
    plotPad.Draw()
    # ~ ratioPad.Draw()
    plotPad.cd()
    plotPad.cd()
    plotPad.SetGrid()
    gStyle.SetTitleXOffset(1.45)
    gStyle.SetTitleYOffset(1.55)

    xMax = 0.15
    if trackType == "Inner":
        xMax = 0.3
    if trackType == "Outer":
        xMax = 0.5

    plotPad.DrawFrame(0, 0, 2000, xMax, ";p_{T} [GeV]; p_{T} resolution [%]")

    graph2017B.Draw("samepe")
    # ~ graph2017O.Draw("samepe")
    graph2017E.Draw("samepe")
    graph2017B.SetLineColor(kRed)
    graph2017B.SetMarkerColor(kRed)
    graph2017O.SetLineColor(kGreen)
    graph2017O.SetMarkerColor(kGreen)
    graph2017E.SetLineColor(kBlue)
    graph2017E.SetMarkerColor(kBlue)

    latex = TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)
    latex.SetNDC(True)
    latexCMS = TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.055)
    latexCMS.SetNDC(True)
    latexCMSExtra = TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.03)
    latexCMSExtra.SetNDC(True)

    latex.DrawLatex(0.95, 0.96, "(13 TeV)")

    cmsExtra = "#splitline{Preliminary}{}"
    latexCMS.DrawLatex(0.19, 0.88, "CMS")
    if "Simulation" in cmsExtra:
        yLabelPos = 0.81
    else:
        yLabelPos = 0.84

    latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))

    leg = TLegend(0.52, 0.76, 0.95, 0.91, "%s 2017" % trackType, "brNDC")
    leg.SetFillColor(10)
    leg.SetFillStyle(0)
    leg.SetLineColor(10)
    leg.SetShadowColor(0)
    leg.SetBorderSize(1)
    leg.AddEntry(graph2017B, "Barrel", "l")
    # ~ leg.AddEntry(graph2017O,"Overlap","l")
    leg.AddEntry(graph2017E, "Endcap", "l")

    leg.Draw()

    plotPad.RedrawAxis()

    canv.Print("PtResolutionCompare_%s_2017.pdf" % trackType)
    canv.Print("PtResolutionCompare_%s_2017.root" % trackType)

    canv = TCanvas("c1", "c1", 800, 1200)

    plotPad = TPad("plotPad", "plotPad", 0, 0., 1, 1)
    # ~ ratioPad = TPad("ratioPad","ratioPad",0,0.,1,0.3)
    style = setTDRStyle()
    gStyle.SetOptStat(0)
    plotPad.UseCurrentStyle()
    # ~ ratioPad.UseCurrentStyle()
    plotPad.Draw()
    # ~ ratioPad.Draw()
    plotPad.cd()
    plotPad.cd()
    plotPad.SetGrid()
    gStyle.SetTitleXOffset(1.45)
    gStyle.SetTitleYOffset(1.55)

    xMax = 0.15
    if trackType == "Inner":
        xMax = 0.3
    if trackType == "Outer":
        xMax = 0.5

    plotPad.DrawFrame(0, 0, 2000, xMax, ";p_{T} [GeV]; p_{T} resolution [%]")

    graph2018B.Draw("samepe")
    # ~ graph2018O.Draw("samepe")
    graph2018E.Draw("samepe")
    graph2018B.SetLineColor(kRed)
    graph2018B.SetMarkerColor(kRed)
    graph2018O.SetLineColor(kGreen)
    graph2018O.SetMarkerColor(kGreen)
    graph2018E.SetLineColor(kBlue)
    graph2018E.SetMarkerColor(kBlue)

    latex = TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)
    latex.SetNDC(True)
    latexCMS = TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.055)
    latexCMS.SetNDC(True)
    latexCMSExtra = TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.03)
    latexCMSExtra.SetNDC(True)

    latex.DrawLatex(0.95, 0.96, "(13 TeV)")

    cmsExtra = "#splitline{Preliminary}{}"
    latexCMS.DrawLatex(0.19, 0.88, "CMS")
    if "Simulation" in cmsExtra:
        yLabelPos = 0.81
    else:
        yLabelPos = 0.84

    latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))

    leg = TLegend(0.52, 0.76, 0.95, 0.91, "%s 2018" % trackType, "brNDC")
    leg.SetFillColor(10)
    leg.SetFillStyle(0)
    leg.SetLineColor(10)
    leg.SetShadowColor(0)
    leg.SetBorderSize(1)
    leg.AddEntry(graph2018B, "Barrel", "l")
    # ~ leg.AddEntry(graph2018O,"Overlap","l")
    leg.AddEntry(graph2018E, "Endcap", "l")

    leg.Draw()

    plotPad.RedrawAxis()

    canv.Print("PtResolutionCompare_%s_2018.pdf" % trackType)
    canv.Print("PtResolutionCompare_%s_2018.root" % trackType)
Beispiel #17
0
h5.SetLineColor(3)
h5.SetLineWidth(2)
h5.SetLineStyle(1)

h1.SetMarkerStyle(9)
h2.SetMarkerStyle(9)
h3.SetMarkerStyle(9)
h4.SetMarkerStyle(9)
h5.SetMarkerStyle(9)

h3.GetXaxis().SetRangeUser(0, 16)
h3.GetYaxis().SetRangeUser(0, 0.6)
h3.GetYaxis().SetRangeUser(0, 0.6)

t = TLatex(0.3, .05, "e^{-}")
t1 = TLatex(1.3, .05, "#nu_{e}")
t2 = TLatex(2.3, .05, "#mu^{-}")
t3 = TLatex(3.3, .05, "#nu_{#mu}")
t4 = TLatex(4.3, .05, "#gamma")
t5 = TLatex(5.1, .05, "K_{L}^{0}")
t6 = TLatex(6.3, .05, "#pi^{+}")
t7 = TLatex(7.1, .05, "K_{S}^{0}")
t8 = TLatex(8.1, .05, "K^{+}")
t9 = TLatex(9.3, .05, "n")
t10 = TLatex(10.3, .05, "p")
t11 = TLatex(11.3, .05, "#Sigma^{-}")
t12 = TLatex(12.3, .05, "#Lambda")
t13 = TLatex(13.3, .05, "#Xi^{-}")
t14 = TLatex(14.3, .05, "#Sigma^{+}")
t15 = TLatex(15.3, .05, "#Xi^{0}")
Beispiel #18
0
    graph_HV_L1.SetPoint(n, int(a), float(HV_scan_L1[a]))
    n = n + 1
graph_HV_L1.SetMarkerSize(1.)
graph_HV_L1.SetMarkerStyle(21)
graph_HV_L1.SetMarkerColor(418)
graph_HV_L1.SetFillColor(868)
graph_HV_L1.SetFillStyle(3844)
graph_HV_L1.SetLineColor(418 - 1)
graph_HV_L1.SetLineWidth(2)
graph_HV_L1.SetLineStyle(2)
graph_HV_L1.GetXaxis().SetTitle("HV [V]")
graph_HV_L1.GetYaxis().SetTitleOffset(1.2)
graph_HV_L1.GetYaxis().SetTitle("efficiency")
graph_HV_L1.GetYaxis().SetRangeUser(0, 1.01)
graph_HV_L1.Draw("APL")
latex = TLatex()
latex.SetNDC()
latex.SetTextSize(0.04)
latex.SetTextColor(1)
latex.SetTextFont(42)
latex.SetTextAlign(33)
latex.SetTextSize(0.04)
latex.SetTextFont(62)
latex.DrawLatex(0.30, 0.96, "GIF++")
etichetta = TLatex()
etichetta.SetNDC()
etichetta.SetTextSize(0.04)
etichetta.SetTextColor(418)
etichetta.SetTextFont(102)
etichetta.DrawLatex(
    0.2, 0.8, "#splitline{SL1_L1 HV scan}{Runs: " + str(run_interval) + "}")
Beispiel #19
0
line2 = TLine(0.225, 0.05, 0.225, 0.75)
line3 = TLine(0.225, 0.75, -0.0125, 0.75)
line4 = TLine(-0.0125, 0.75, -0.0125, 0.05)

#box 2
line5 = TLine(-0.0125, 0.8, 0.225, 0.8)
line6 = TLine(0.225, 0.8, 0.225, 1)
line7 = TLine(0.225, 1, -0.0125, 1)
line8 = TLine(-0.0125, 1, -0.0125, 0.8)

lineVector = [line1, line2, line3, line4, line5, line6, line7, line8]
for line in lineVector:
    line.SetLineColor(ROOT.kBlack)
    line.SetLineWidth(3)
    line.Draw()

leg = TLegend(.54, .75, .58, .79)
leg.SetFillStyle(0)
leg.SetLineWidth(4)
leg.Draw()

text = TLatex(.6, .75, "NA49 Coverage")
text.SetTextColor(ROOT.kBlack)
text.SetNDC()
text.SetTextSize(1.4 / 30.)
text.SetTextAlign(11)
#text.DrawLatex(.48, .55, "#Square");
text.Draw()

raw_input("Please press enter to exit.")
Beispiel #20
0
cc = TCanvas()
biasstd.SetMinimum(0)
biasstd.SetMaximum(biasstd.GetMaximum()*1.5)
biasstd.Draw()
bias.SetLineColor(4)
bias.Draw("same")
std.SetLineColor(2)
std.Draw("same")

ll = TLegend(0.3, 0.7, 0.6, 0.9)
ll.SetFillStyle(0)
ll.SetTextFont(42)
ll.SetTextSize(0.035)
ll.SetBorderSize(0)
tt = TLatex()
tt.SetNDC()
tt.SetTextFont(42)
ll.AddEntry( std, '#sqrt{#sum std^{2}/N_{bin}}', 'l')
ll.AddEntry( bias, '#sqrt{#sum bias^{2}/N_{bin}}', 'l')
ll.AddEntry( biasstd, '#sqrt{#sum (std^{2} + bias^{2})/N_{bin}}', 'l')
ll.Draw()
cc.SaveAs("biasstd"+options.toy+"_"+options.lepType+".pdf")


ccc = TCanvas()
gPad.SetGridy()
for bin in xrange(0,hBias_pt.GetNbinsX()):
    print 'bin ', bin, hBias_pt.GetBinContent(bin+1)
hBias_pt.GetYaxis().SetTitle("Bias")
hBias_pt.GetXaxis().SetTitle("Top quark p_{T} (GeV)")
Beispiel #21
0
def overlay(hists, ytitle, header, addon):

    print('number of histograms = ', len(hists))

    canvas = TCanvas()
    leg = TLegend(0.2, 0.7, 0.5, 0.9)
    LegendSettings(leg, 1)

    col = [1, 2, 4, 6, 8, 9, 12]

    ymax = -1
    ymin = 100

    for ii, hist in enumerate(hists):
        hist.GetYaxis().SetTitle('efficiency')
        hist.SetLineColor(col[ii])
        hist.SetMarkerColor(col[ii])
        hist.SetLineWidth(2)
        hist.SetMarkerSize(1)

        for ip in range(hist.GetN()):
            x = Double(-1)
            y = Double(-1)
            hist.GetPoint(ip, x, y)

            if ymin > y:
                ymin = y
            if ymax < y:
                ymax = y

#
#        if ymax < hist.GetMaximum():
#            ymax = hist.GetMaximum()
#        if ymin > hist.GetMinimum():
#            ymin = hist.GetMinimum()

        if ii == 0:
            hist.Draw("Azp")
        else:

            hist.Draw("pzsame")

#        print hist.GetName(), hist.GetTitle()
        legname = hist.GetName()

        leg.AddEntry(hist, legname, 'lep')

    for hist in hists:
        hist.SetMaximum(ymax * 2)


#        hist.SetMinimum(ymin*0.5)

    leg.Draw()

    tex = TLatex(
        hists[-1].GetXaxis().GetXmin() + 0.01 *
        (hists[-1].GetXaxis().GetXmax() - hists[-1].GetXaxis().GetXmin()),
        ymax * 2.1, addon.replace('tau_', ''))

    tex.SetTextFont(42)
    tex.SetTextSize(0.03)
    tex.Draw()

    tex2 = TLatex(
        hists[-1].GetXaxis().GetXmin() + 0.87 *
        (hists[-1].GetXaxis().GetXmax() - hists[-1].GetXaxis().GetXmin()),
        ymax * 2.1, tlabel)

    tex2.SetTextFont(42)
    tex2.SetTextSize(0.03)
    tex2.Draw()

    save(canvas, 'compare_' + runtype + '/' + header)
Beispiel #22
0
c.SetLeftMargin(L / W)
c.SetRightMargin(R / W)
c.SetTopMargin(T / H)
c.SetBottomMargin(B / H)

c.Divide(3, 2)
xMin, xMax, yMin, yMax = 0., 80., 0., 0.25
for i, h in enumerate(hList):
    c.cd(i + 1)
    gFakeRate[h].GetXaxis().SetRangeUser(xMin, xMax)
    gFakeRate[h].SetMinimum(yMin)
    gFakeRate[h].SetMaximum(yMax)
    gFakeRate[h].SetLineWidth(2)
    gFakeRate[h].SetMarkerStyle(20)
    gFakeRate[h].SetMarkerSize(1.0)
    gFakeRate[h].SetMarkerColor(kRed)
    gFakeRate[h].GetXaxis().SetTitle('p_t (GeV/c)')

    gFakeRate[h].Draw('e')
    lTex1 = TLatex(0.5 * xMax, 0.5 * yMax, 'test')
    lTex1.SetTextSize(0.04)
    lTex1.Draw()

c.Draw()
raw_input()

fOut.cd()
fOut.Write()
fOut.Close()
Beispiel #23
0
def drawCMS(lumi, text, onTop=False):
    latex = TLatex()
    latex.SetNDC()
    latex.SetTextSize(0.04)
    latex.SetTextColor(1)
    latex.SetTextFont(42)
    latex.SetTextAlign(33)
    if not onTop: latex.SetTextAlign(11)
    if not onTop:
        latex.DrawLatex(0.12, 0.91 if len(text) > 0 else 0.84,
                        "Madgraph Simulation")
        if (type(lumi) is float or type(lumi) is int) and float(lumi) > 0:
            latex.DrawLatex(0.65, 0.91,
                            "%s, %.1f fb^{-1} " % (text, float(lumi) / 1000.))
        elif type(lumi) is str:
            latex.DrawLatex(0.65, 0.91, "%s, %s fb^{-1} " % (text, lumi))
    else:
        latex.DrawLatex(0.23, 0.94, "Madgraph Simulation")
        if (type(lumi) is float or type(lumi) is int) and float(lumi) > 0:
            latex.DrawLatex(0.65, 0.94,
                            "%s, %.1f fb^{-1} " % (text, float(lumi) / 1000.))
        elif type(lumi) is str:
            latex.DrawLatex(0.65, 0.94, "%s, %s fb^{-1} " % (text, lumi))
Beispiel #24
0
def drawEtaValues():
    """Function to draw the eta.

    Function to draw the eta references on top of an already existing
    TCanvas. The lines and labels drawn are collected inside a list and
    the list is returned to the user to extend the live of the objects
    contained, otherwise no lines and labels will be drawn, since they
    will be garbage-collected as soon as this function returns.
    """

    # Add eta labels
    keep_alive = []
    etas = [
        -3.4, -3.0, -2.8, -2.6, -2.4, -2.2, -2.0, -1.8, -1.6, -1.4, -1.2, -1.,
        -0.8, -0.6, -0.4, -0.2, 0., 0.2, 0.4, 0.6, 0.8, 1., 1.2, 1.4, 1.6, 1.8,
        2., 2.2, 2.4, 2.6, 2.8, 3.0, 3.4
    ]

    etax = 2940.
    etay = 1240.
    lineL = 100.
    offT = 10.

    for ieta in etas:
        th = 2 * atan(exp(-ieta))
        talign = 21

        #IP
        lineh = TLine(-20., 0., 20., 0.)
        lineh.Draw()
        linev = TLine(0., -10., 0., 10.)
        linev.Draw()
        keep_alive.append(lineh)
        keep_alive.append(linev)

        x1 = 0
        y1 = 0
        if ieta > -1.6 and ieta < 1.6:
            x1 = etay / tan(th)
            y1 = etay
        elif ieta <= -1.6:
            x1 = -etax
            y1 = -etax * tan(th)
            talign = 11
        elif ieta >= 1.6:
            x1 = etax
            y1 = etax * tan(th)
            talign = 31
        x2 = x1 + lineL * cos(th)
        y2 = y1 + lineL * sin(th)
        xt = x2
        yt = y2 + offT

        line1 = TLine(x1, y1, x2, y2)
        line1.Draw()
        keep_alive.append(line1)

        text = "%3.1f" % ieta
        t1 = TLatex(xt, yt, '%s' % ('#eta = 0' if ieta == 0 else text))
        t1.SetTextSize(0.03)
        t1.SetTextAlign(talign)
        t1.Draw()
        keep_alive.append(t1)
    return keep_alive
def compareMassRes(trackType):

    fileCB = open(
        "BoosteddefaultLeadingCB/MassResolutionVsPt_%s_BE16.pkl" % trackType,
        "rb")
    fileDCB = open(
        "BoosteddefaultLeading/MassResolutionVsPt_%s_BE16.pkl" % trackType,
        "rb")
    fileCruijff = open(
        "BoosteddefaultLeadingCruijff/MassResolutionVsPt_%s_BE16.pkl" %
        trackType, "rb")

    resultsCB = pickle.load(fileCB)
    resultsDCB = pickle.load(fileDCB)
    resultsCruijff = pickle.load(fileCruijff)

    graphCB = getGraph(resultsCB, "CB", Data=True)
    graphDCB = getGraph(resultsDCB, "DCB", Data=True)
    graphCruijff = getGraph(resultsCruijff, "Cruijff", Data=True)

    ratioCB = getRatio(resultsCB, resultsDCB, "ratioCB", Data=True)
    ratioCruijff = getRatio(resultsCruijff,
                            resultsDCB,
                            "ratioCruijff",
                            Data=True)

    canv = TCanvas("c1", "c1", 800, 800)

    plotPad = TPad("plotPad", "plotPad", 0, 0, 1, 1)
    #~ ratioPad = TPad("ratioPad","ratioPad",0,0.,1,0.3)
    style = setTDRStyle()
    gStyle.SetOptStat(0)
    plotPad.UseCurrentStyle()
    #~ ratioPad.UseCurrentStyle()
    plotPad.Draw()
    #~ ratioPad.Draw()
    plotPad.cd()
    plotPad.cd()
    plotPad.SetGrid()
    gStyle.SetTitleXOffset(1.45)

    xMax = 20
    if trackType == "Inner":
        xMax = 10
    if trackType == "Outer":
        xMax = 20

    plotPad.DrawFrame(0, 0, 452, xMax, ";p_{T} [GeV]; #chi^{2}/N_{dof}")

    graphCB.Draw("samepe")
    graphDCB.Draw("samepe")
    graphCruijff.Draw("samepe")
    graphDCB.SetLineColor(kRed)
    graphDCB.SetMarkerColor(kRed)
    graphCruijff.SetLineColor(kBlue)
    graphCruijff.SetMarkerColor(kBlue)

    latex = TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)
    latex.SetNDC(True)
    latexCMS = TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.055)
    latexCMS.SetNDC(True)
    latexCMSExtra = TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.03)
    latexCMSExtra.SetNDC(True)

    latex.DrawLatex(0.95, 0.96, "(13 TeV)")

    cmsExtra = "#splitline{Preliminary}{}"
    latexCMS.DrawLatex(0.19, 0.88, "CMS")
    if "Simulation" in cmsExtra:
        yLabelPos = 0.81
    else:
        yLabelPos = 0.84

    latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))

    leg = TLegend(0.52, 0.76, 0.95, 0.91, "%s BB" % trackType, "brNDC")
    leg.SetFillColor(10)
    leg.SetFillStyle(0)
    leg.SetLineColor(10)
    leg.SetShadowColor(0)
    leg.SetBorderSize(1)
    leg.AddEntry(graphCB, "Single-Sided CB", "l")
    leg.AddEntry(graphDCB, "Double-Sided CB", "l")
    leg.AddEntry(graphCruijff, "Cruijff", "l")

    leg.Draw()

    plotPad.RedrawAxis()

    #~ ratioPad.cd()

    #~ ratioBB.SetLineColor(kRed)

    #~ ratioPad.DrawFrame(0,0.5,6000,1.5,";;ratio")

    #~ ratioBB.Draw("samepe")

    canv.Print("chi2CompareVsPt_%s_BE16.pdf" % trackType)
def plotsinglevar(
    mode="MM",
    filename="../codeHF/AnalysisResults_O2.root",
    dirname="hf-task-xicc-mc",
    latex="Xi_{cc}",
    iptBin=2,
    histonmasssig="hPtRecGenDiff",  # hPtRecGenDiff hXSecVtxPosDiff
    xmin=-2.0,
    xmax=2.0,
    ymin=0.1,
    ymax=1.0e6,
    rebin=4,
    logx=1,
    logy=1,
    xminfit=-2.0,
    xmaxfit=2.0,
    title="",
    xaxis="Xi_{cc} X vertex reco - gen (cm)",
    dofit=0,
):
    gStyle.SetOptStat(0)
    gROOT.SetBatch(1)

    fileSig = TFile(filename)
    histo2d = fileSig.Get("%s/%s" % (dirname, histonmasssig))
    hvar = histo2d.ProjectionX("hvar", iptBin + 1, iptBin + 1)
    hvar.GetXaxis().SetRangeUser(xmin, xmax)
    hvar.Draw()
    ptMin = histo2d.GetYaxis().GetBinLowEdge(iptBin + 1)
    ptMax = ptMin + histo2d.GetYaxis().GetBinWidth(iptBin + 1)
    # ymax = hvar.GetMaximum() * 10
    # ymin = hvar.GetMinimum()
    hempty = TH2F("hempty", ";%s; Entries" % xaxis, 100, xmin, xmax, 100, ymin,
                  ymax)
    hempty.GetXaxis().SetLabelFont(42)
    hempty.GetXaxis().SetTitleOffset(1)
    hempty.GetXaxis().SetLabelSize(0.03)
    hempty.GetXaxis().SetTitleFont(42)
    hempty.GetYaxis().SetLabelFont(42)
    hempty.GetYaxis().SetTitleOffset(1.35)
    hempty.GetYaxis().SetTitleFont(42)
    hempty.GetZaxis().SetLabelFont(42)
    hempty.GetZaxis().SetTitleOffset(1)
    hempty.GetZaxis().SetTitleFont(42)

    canvas = TCanvas("canvas", "A Simple Graph Example", 881, 176, 668, 616)
    gStyle.SetOptStat(0)
    canvas.SetHighLightColor(2)
    canvas.Range(-1.25, -4.625, 11.25, 11.625)
    canvas.SetFillColor(0)
    canvas.SetBorderMode(0)
    canvas.SetBorderSize(2)
    canvas.SetFrameBorderMode(0)
    canvas.SetFrameBorderMode(0)
    if logx == 1:
        canvas.SetLogx()
    if logy == 1:
        canvas.SetLogy()
    canvas.cd()
    hempty.Draw("")
    hvar.Draw("PEsame")
    latexa = TLatex()
    latexa.SetTextSize(0.04)
    latexa.SetTextFont(42)
    latexa.SetTextAlign(3)
    xave = xmin + (xmax - xmin) / 4.0
    latexa.DrawLatex(xave, ymax * 0.2,
                     "%.1f < p_{T} (%s) < %.1f GeV" % (ptMin, latex, ptMax))
    if dofit:
        f = TF1("f", "gaus")
        hvar.Fit("f", "R", "", xminfit, xmaxfit)
        latexb = TLatex()
        latexb.SetTextSize(0.04)
        latexb.SetTextFont(42)
        latexb.SetTextAlign(3)
        mean = f.GetParameter(1)
        sigma = f.GetParameter(2)
        latexb.DrawLatex(xave, ymax * 0.35,
                         "#mu = %.5f, #sigma = %.5f" % (mean, sigma))
    canvas.SaveAs("%s%s.pdf" % (histonmasssig, mode))
Beispiel #27
0
def myText(x, y, color=1, size=0.08, text=""):
    l = TLatex()
    l.SetTextSize(size)
    l.SetNDC()
    l.SetTextColor(color)
    l.DrawLatex(x, y, text)
Beispiel #28
0
def ATLASLabel(x, y, text="Internal", color=1):
    l = TLatex()
    l.SetNDC()
    l.SetTextFont(72)
    l.SetTextColor(color)
    delx = 0.115 * 696 * gPad.GetWh() / (472 * gPad.GetWw())
    l.DrawLatex(x, y, "ATLAS")
    if True:
        p = TLatex()
        p.SetNDC()
        p.SetTextFont(42)
        p.SetTextColor(color)
        p.DrawLatex(x + delx, y, text)
Beispiel #29
0
def ATLASLabel(x, y, shift, studytype, color=1):
    l = TLatex(x, y, "ATLAS")
    l.SetNDC()
    l.SetTextFont(72)
    l.SetTextColor(color)
    l.DrawLatex(x, y, "ATLAS")
    if (studytype != ""):
        p = TLatex(x + shift, y, studytype)
        p.SetNDC()
        p.SetTextFont(42)
        p.SetTextColor(color)
        p.DrawLatex(x + shift, y, studytype)
def pileup(isCorr):
    Corr = ['', '(event_weight)']
    can = TCanvas("can", "can", 1000, 900)
    gStyle.SetOptStat(0)
    phojet = TH1D('b', 'b', 60, 0, 60)
    phojet.SetMarkerColor(7)
    qcd = TH1D('c', 'c', 60, 0, 60)
    qcd.SetMarkerColor(5)
    Variables = {}
    for tre in List:
        Variables[tre] = TH1F(tre, ";Number of Vertices;Events", 60, 0, 60)
        #		if tre == "dipho":
        #			weight = cutter+"&& (JetPho_dR<0.1)"
        treeTrig[tre].Draw("NVerts>>" + tre, Corr[isCorr])
        Variables[tre].Sumw2()
        scalable = lumi * crossx[tre] * kFact[tre] / Nevents[tre]
        Variables[tre].Scale(scalable)
        if tre.startswith("df"):
            Variables[tre].SetMarkerColor(colors[tre])
            Variables[tre].SetLineWidth(3)
            scalable = Variables[tre].Integral()
            Variables[tre].Scale(1 / scalable)
        if tre.startswith("pj"):
            phojet.Add(Variables[tre])
        if tre.startswith("qcd"):
            qcd.Add(Variables[tre])
        if tre.startswith("dipho"):
            Variables[tre].SetMarkerColor(3)
            scalable = Variables[tre].Integral()
            Variables[tre].Scale(1 / scalable)
    scalable = phojet.Integral()
    phojet.Scale(1 / scalable)
    scalable = qcd.Integral()
    qcd.Scale(1 / scalable)
    data = TH1D('data', '', 60, 0, 60)
    dataFi = TFile(
        "/uscms_data/d3/dokstolp/darkphoton/13TeV/Analysis/CMSSW_8_0_18_patch1/src/Runner/Weights/forPileup/Data.root",
        "OPEN")
    data = dataFi.Get("hist")
    scalar = data.Integral()
    data.Scale(1 / scalar)
    data.SetLineColor(1)
    data.SetLineWidth(2)
    data.Draw("e1")
    Variables['df1en0'].Draw("e1same")
    Variables['df1en1'].Draw("e1same")
    Variables['df1en2'].Draw("e1same")
    Variables['df1en3'].Draw("e1same")
    Variables['dipho'].Draw('e1same')
    qcd.Draw('e1same')
    phojet.Draw('e1same')
    latex2 = TLatex()
    latex2.SetNDC()
    latex2.SetTextSize(0.035)
    latex2.SetTextAlign(31)  # align right
    latex2.DrawLatex(
        0.87, 0.95,
        "Work In Progress, " + str(lumi) + " fb^{-1} at #sqrt{s} = 13 TeV")
    led = TLegend(0.7, 0.7, 0.94, 0.9)
    led.AddEntry(phojet, "#gamma + Jet", 'f')
    led.AddEntry(qcd, "QCD DiJet", 'f')
    led.AddEntry(Variables['dipho'], "#gamma + #gamma", 'f')
    led.AddEntry(Variables['df1en0'], "f_D = 1E0}")
    led.AddEntry(Variables['df1en1'], "f_D = 1E-1}")
    led.AddEntry(Variables['df1en2'], "f_D = 1E-2}")
    led.AddEntry(Variables['df1en3'], "f_D = 1E-3}")
    led.AddEntry(data, "Data")
    led.SetFillColor(0)
    led.Draw("same")
    can.SaveAs("plots/pileup-" + isCorr + ".pdf")
    can.Close()
    phojet.Delete()
    qcd.Delete()