Beispiel #1
0
 def buildLegend(self, legendFile, objects ):
     '''For each object, use the corresponding legend entry'''
     legendDesc = open( legendFile )
     FLOAT = '-*\d+[.\d*]*'
     pattmp = '\s*(FLOAT)\s+(FLOAT)\s+(FLOAT)\s+(FLOAT)\s*'
     pattern = re.compile( pattmp.replace('FLOAT', FLOAT) )
     legendEntries = []
     for line in legendDesc.readlines():
         line = line.rstrip()
         match = pattern.match( line )
         if match!=None:
             x1 = float(match.group(1))
             x2 = float(match.group(2))
             y1 = float(match.group(3))
             y2 = float(match.group(4))
         else:
             legendEntries.append( line )
     # print x1, x2, y1, y2, legendEntries
     if len(legendEntries)!= len(objects):
         raise ValueError('if you specify a legend file, it should have the correct number of lines.')
     
     TLegend.__init__( self, x1, x2, y1, y2)
     for entry,hist in zip(legendEntries,objects):
         self.AddEntry( hist, entry)
def main():
    """
    Simply plot semi-visible jets histograms stored in nanoAOD files for a quick look at distributions.
    User specifies a list of the files they wish to be read in, and one file corresponds to one "model",
    (i.e., a combination of semi-visible jet-specific parameters). The current collection of histograms
    gives a quick look at the kinematics. If the user wishes to add more, the histogram must be
    initialised in the SVJModel class with the others, added to hist_list, then filled in the big for()
    loop in this function.
    """

    if not os.path.exists(os.path.join(os.getcwd(), 'Plots')):
        os.mkdir('Plots')

    # Build list of files from input argument
    with open(args.file_list) as input_files:
        input_file_list = input_files.readlines()

    # Create list of models, each element in list contains object with all information about each model
    models = []
    for file in input_file_list:
        if file.startswith('#') or file.startswith('\n'):
            continue
        file = file.replace('\n', '')
        model_name = os.path.basename(file.replace('.root', ''))
        models.append(SVJModel(name=model_name, file_path=file))

    # For each model, initialise histograms, set line colours and write legend entry
    for i, model in enumerate(models):
        model.initialise_histos()
        model.get_hist_colour(i)
        model.write_legend_entry(model.name)

    # Initialise the canvas and set aesthetics
    canv = TCanvas("canv", "canv", 800, 600)
    canv.SetLogy()
    gStyle.SetOptStat(0)
    gStyle.SetOptTitle(0)

    # Initialise legend and set colours
    leg_height = len(
        models) * 0.06  # make y-length of legend dependent on n_models
    legend_frame = TLegend(0.6, 0.9 - leg_height, 0.9, 0.9)
    #leg_height = len(models) * 0.03
    #legend_frame = TLegend(0.2, 0.9 - leg_height, 0.8, 0.9)
    #legend_frame.SetNColumns(2)
    legend_frame.SetTextSize(0.022)

    # Open root files, then fill and draw individual histograms
    for i, model in enumerate(models):
        print(Fore.MAGENTA +
              "Running over model {0}/{1}".format(i + 1, len(models)))
        openFile = TFile(model.file_path)
        tree = openFile.Get("Events")
        nEvents = tree.GetEntries()

        # Initialise progress bar
        widgets = [Percentage(), Bar('>'), ETA()]
        pbar = ProgressBar(widgets=widgets, maxval=nEvents).start()

        # Fill all histograms
        for entry in xrange(nEvents):
            treeEntry = tree.GetEntry(entry)
            model.nJetHist.Fill(tree.nJet)

            for jet in xrange(len(tree.Jet_pt)):
                model.allJetPtHist.Fill(tree.Jet_pt[jet])

            if len(tree.Jet_pt) > 0:
                model.leadJetPtHist.Fill(tree.Jet_pt[0])
                dPhiMetJ = tree.MET_phi - tree.Jet_phi[0]
                model.dPhiMetJHist.Fill(dPhiMetJ)

            model.metPtHist.Fill(tree.MET_pt)

            if len(tree.Jet_phi) >= 2:
                deltaPhi = tree.Jet_phi[0] - tree.Jet_phi[1]
                model.dPhiJJHist.Fill(deltaPhi)

            pbar.update(entry + 1)

        pbar.finish()

        # Normalise histograms, then draw and save
        for hist in model.hist_list:
            hist.Scale(
                1. / hist.GetEntries()
            )  # fine for most hists, but means allJetPt gets normalised by total n_jets
            drawIndivHistos(model, hist, canv)

    # Draw histograms for each model overlaid and save
    n_hist_types = len(models[0].hist_list)
    for hist in xrange(n_hist_types):
        drawMultipleHistos([model.hist_list[hist] for model in models], canv,
                           legend_frame)
Beispiel #3
0
    hist.Scale(sf)
    hist.Draw("GOFF")
    max_hist = hist.GetMaximum()
    title = hist.GetTitle()
    hist.SetTitle("")
    hist.GetYaxis().SetRangeUser(0, 1.2 * max_hist)

    # set title and axis labels
    hist.GetXaxis().SetLabelSize(0.03)
    hist.GetXaxis().SetTitle("%s [GeV]" % (title))
    hist.GetYaxis().SetLabelSize(0.03)
    hist.GetYaxis().SetTitleOffset(1.5)
    hist.GetYaxis().SetTitle("Events / %s [GeV]" % (hist.GetBinWidth(1)))

    # fill legend
    leg = TLegend(0.7, 0.75, 0.88, 0.88)
    leg.AddEntry(hist, "TTbar", "f")
    leg.SetFillColor(0)
    leg.SetBorderSize(0)

    # line at W mass
    l = TLine(80.4, 0, 80.4, 1.05 * max_hist)
    l.SetLineStyle(3)

    # and draw
    c.cd()
    hist.Draw('hist')
    leg.Draw('sames')
    if (variable == "goodJ3J4_mass"): l.Draw()

    cpr.prelim_alt(19700, 0.05)
    "D1=0 kV D2= 3 kV  E1= 4 kV E2 =4 kV",
    "D1=0 kV D2= 3 kV  E1= 4 kV E2 =3 kV",
    "D1=0 kV D2= 3 kV  E1= 4  kV E2 =2 kV",
    "D1=0 kV D2= 3 kV  E1= 4 kV E2 =1 kV",
    "D1=0 kV D2= 3 kV  E1= 4 kV E2 =0 kV"
]

for config in reversed(listOfFiles):
    histogram = addClusters(config)
    histogram[0].SetFillColorAlpha(colorCounter, 0.6)
    histogram[0].SetLineColor(colorCounter)
    histogram[0].SetLineWidth(5)
    colorCounter = colorCounter + 1
    histogramList.append(histogram[0])
    nameList.append(config)

legend = TLegend(0.55, 0.55, 0.90, 0.90)
counter = 0
for histogram in histogramList:
    if histogram == histogramList[0]:
        histogram.GetYaxis().SetRangeUser(0, 5)
        histogram.Draw("histsame")
    else:
        histogram.Draw("histsame")
    legend.AddEntry(histogram, nameList[counter])
    counter = counter + 1

canvas.Update()
legend.Draw("same")
canvas.Print("/home/helga/gitThesis/thesis/Grace/fig/scan2RealData.pdf")
Beispiel #5
0
linex = TLine(145, 0, 205, 0)
linex.SetLineWidth(1)
linex.Draw()

liney = TLine(173, -0.00825, 173, 0.00725)
if mass == "167":
    liney = TLine(173, -0.0096, 173, 0.0059)

if nlo:
    liney = TLine(173, -0.01025, 173, 0.0055)

liney.SetLineWidth(1)
liney.SetLineStyle(2)
liney.Draw()

l = TLegend(0.6, 0.6, 0.8, 0.8)
if mass == "167":
    l = TLegend(0.6, 0.62, 0.8, 0.82)

if nlo:
    l = TLegend(0.6, 0.65, 0.80, 0.85)
l.AddEntry(final2, "n = 2", "L")
l.AddEntry(final3, "n = 3", "L")
l.AddEntry(final5, "n = 5", "L")
l.AddEntry(final15, "n = 15", "L")
l.SetTextSize(0.04)
l.SetLineColor(0)
l.SetFillColor(0)
l.Draw()

if nlo:
Beispiel #6
0
def plotFit():

    axPeak = 2.464

    # load workspace
    f = TFile("./data/splitWorkspace.root")
    fitWorkspace = f.Get("fitWorkspace")
    fData = fitWorkspace.allData().front()
    fitResult = fitWorkspace.allGenericObjects().front()
    nPars = fitResult.floatParsFinal().getSize()
    fEnergy = fitWorkspace.var("energy_keV")
    modelPDF = fitWorkspace.pdf("model")
    # fitWorkspace.Print()

    pdfNames = ["ext-axion"]

    # -- create spectrum rooplot --
    nCol = float(gStyle.GetNumberOfColors())
    binSize = 0.04
    nBins = int((eHi - eLo) / binSize + 0.5)
    fSpec = fEnergy.frame(RF.Range(eLo, eHi), RF.Bins(nBins))
    fData.plotOn(fSpec)
    modelPDF.plotOn(fSpec, RF.LineColor(ROOT.kRed), RF.Name("FullModel"))
    chiSquare = fSpec.chiSquare(nPars)
    modelPDF.plotOn(fSpec, RF.Components(pdfNames[0]),
                    RF.LineColor(ROOT.kBlue), RF.Name(pdfNames[0]))

    # -- make a fake Gaussian --
    # gaus = ROOT.TF1("g","gaus",-3, eHi)
    # gaus.SetParameters(10., axPeak, getSigma(axPeak))
    # gaus.SetParameter(0,10.)
    # gaus.SetParameter(1, axPeak)
    # gaus.SetParameter(2, getSigma(axPeak))
    # erf
    # rrvGaus = ROOT.RooRealVar("ax","ax",-3.,3.)
    # rarGaus = RF.bindFunction("gaus", ROOT.TMath.Erf, rrvGaus)
    # rarGaus.Print()
    # frame2 = rrvGaus.frame(RF.Title("mygaus"))
    # rarGaus.plotOn(frame2, RF.LineColor(ROOT.kGreen), RF.LineStyle(ROOT.kDashed), RF.Name("axGaus"))
    # c0 = TCanvas("c0","",800,600)
    # frame2.Draw()
    # c0.Print("./plots/testGaus.pdf")

    # -- print fit results --
    print "-- SHIFTFIT RESULTS -- "
    print "%-10s = %.3f" % ("chiSq", chiSquare)
    fitValsFinal = getRooArgDict(fitResult.floatParsFinal())

    bkgVal = 0.
    for name in sorted(fitValsFinal):
        fitVal = fitValsFinal[name]
        if "amp-" in name:
            error = fitWorkspace.var(name).getError()
            print "%-10s = best %-7.3f  error %.3f (w/o profile)" % (
                name, fitVal, error)
        elif "mu-" in name:
            # compare the energy offset
            pkName = name[3:]
            pct = 100 * (1 - fitVal / axPeak)
            print "%-10s : fit %-6.3f  lit %-6.3f  (%.3f%%)" % (name, fitVal,
                                                                axPeak, pct)
        elif "sig-" in name:
            # compare the sigma difference
            pkName = name[4:]
            pct = 100 * (1 - fitVal / getSigma(axPeak))
            print "%-10s : fit %-6.3f  func %-6.3f  (%.3f%%)" % (
                name, fitVal, getSigma(axPeak), pct)
        else:
            print "%s = %.4f (%.4f)" % (name, fitVal, fitVal / nBins)
            bkgVal = fitVal / nBins
            continue

    # -- make spectrum plot --
    c = TCanvas("c", "Bob Ross's Canvas", 1400, 1000)
    c.SetRightMargin(0.2)
    fSpec.SetTitle(" ")
    fSpec.Draw()

    ymax = fSpec.GetMaximum()
    l1 = ROOT.TLine(axPeak, 0., axPeak, ymax)
    l1.SetLineColor(ROOT.kBlue)
    l1.SetLineWidth(2)
    l1.Draw("same")

    leg = TLegend(0.83, 0.6, 0.97, 0.9)
    leg.AddEntry(fSpec.findObject("FullModel"),
                 "model #chi^{2}=%.3f" % chiSquare, "l")
    leg.AddEntry(fSpec.findObject("FullModel"), "cts/bin=%.2f" % bkgVal, "")
    leg.AddEntry(fSpec.findObject(pdfNames[0]), "axion gaussian", "l")
    leg.AddEntry(l1, "axion-%.2f" % axPeak, "l")
    leg.Draw("same")

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

    # -- get FC Limit --
    # Calculate the confidence interval for the axion peak, which is too low to use profile likelihood.
    # TFeldmanCousins version:
    # https://root.cern.ch/root/html/tutorials/math/FeldmanCousins.C.html
    # RooStats version:
    # https://root.cern.ch/root/html/tutorials/roostats/StandardFeldmanCousinsDemo.C.html
    # FC Paper: https://arxiv.org/pdf/physics/9711021.pdf
    f = TFeldmanCousins(0.95)
    N_obs = 1.
    N_bkg = bkgVal / 3.
    ul = f.CalculateUpperLimit(N_obs, N_bkg)
    ll = f.GetLowerLimit()
    print "For %.2f events observed, and %.2f background events," % (N_obs,
                                                                     N_bkg)
    print "F-C method gives UL: %.2f and LL %.2f (90%% CL)" % (ul, ll)
Beispiel #7
0
 plot = TGraph(6, x, std)
 plot.SetTitle('#sigma zones')
 plot.SetMarkerStyle(21)
 c = TCanvas("c", "c", 1200, 400)
 c.Divide(3, 1)
 c.cd(1)
 hist_double.Draw("COL")
 c.cd(2)
 hist1.Draw()
 hist1.SetStats(0)
 hist2.Draw("SAME")
 hist3.Draw("SAME")
 hist4.Draw("SAME")
 hist5.Draw("SAME")
 hist6.Draw("SAME")
 legend1 = TLegend(0.65, 0.55, 0.95, 0.85)
 legend1.AddEntry(hist1, zonas[0], "l")
 legend1.AddEntry(hist2, zonas[1], "l")
 legend1.AddEntry(hist3, zonas[2], "l")
 legend1.AddEntry(hist4, zonas[3], "l")
 legend1.AddEntry(hist5, zonas[4], "l")
 legend1.AddEntry(hist6, zonas[5], "l")
 legend1.SetTextSize(0.023)
 legend1.Draw()
 c.cd(3)
 plot.Draw("")
 c.Draw()
 if tn == L:
     c.SaveAs(
         "/home/camsdiaz/Documents/Tandem/work2-findingvariables/plots/"
         + name + " L.png")
Beispiel #8
0
    SipMC[i].GetXaxis().SetTitle("SIP")
    SipMC[i].GetXaxis().SetLabelFont(43)
    SipMC[i].GetXaxis().SetLabelSize(15)
    SipMC[i].GetYaxis().SetTitleSize(20)
    SipMC[i].GetYaxis().SetTitleFont(43)
    SipMC[i].GetYaxis().SetTitleOffset(1.8)
    SipMC[i].GetYaxis().SetLabelFont(43)
    SipMC[i].GetYaxis().SetLabelSize(15)
    SipMC[i].GetYaxis().SetTitle("Events")

    SipMC[i].SetTitle("")

    gStyle.SetOptStat(0)

    # legend
    legend = TLegend(0.74, 0.68, 0.94, 0.87)
    legend.AddEntry(SipDATA[i], "Data", "p")
    legend.AddEntry(SipMC[i], "Drell-Yan MC", "f")
    legend.SetFillColor(kWhite)
    legend.SetLineColor(kBlack)
    legend.SetTextFont(43)
    legend.SetTextSize(20)
    legend.Draw()

    canvas.Update()

    #lower plot pad
    canvas.cd()
    pad2 = TPad("pad2", "pad2", 0, 0.05, 1, 0.3)
    pad2.SetGridy()
    pad2.Draw()
Beispiel #9
0
latex.SetTextAlign(31)  # align right
latex.DrawLatex(0.45, 0.95, "CMS Preliminary")

latex2 = TLatex()
latex2.SetNDC()
latex2.SetTextSize(0.04)
latex2.SetTextAlign(31)  # align right
latex2.DrawLatex(0.87, 0.95, "19.6 fb^{-1} at #sqrt{s} = 8 TeV")

latex4 = TLatex()
latex4.SetNDC()
latex4.SetTextSize(0.04)
latex4.SetTextAlign(31)  # align right
latex4.DrawLatex(0.80, 0.87, "")

legend = TLegend(.566, .684, .84, .84)
legend.AddEntry(observed_p, '95% C.L. Observed', "lp")
legend.AddEntry(expected_p, '95% C.L. Expected', "l")
legend.AddEntry(expected68, '#pm 1#sigma Expected', "f")
legend.AddEntry(expected95, '#pm 2#sigma Expected', "f")
legend.AddEntry(theory, "G_{KK} c = 0.01", "l")

legend.SetShadowColor(0)
legend.SetFillColor(0)
legend.SetLineColor(0)
legend.Draw()

c4.SaveAs("limit_c01.root")

raw_input("Press Enter to continue...")
Beispiel #10
0
def plotDataMC(args,plot):
	

	hCanvas = TCanvas("hCanvas", "Distribution", 800,800)
	if args.ratio:
		plotPad = ROOT.TPad("plotPad","plotPad",0,0.3,1,1)
		ratioPad = ROOT.TPad("ratioPad","ratioPad",0,0.,1,0.3)
		setTDRStyle()		
		plotPad.UseCurrentStyle()
		ratioPad.UseCurrentStyle()
		plotPad.Draw()	
		ratioPad.Draw()	
		plotPad.cd()
	else:
		plotPad = ROOT.TPad("plotPad","plotPad",0,0,1,1)
		setTDRStyle()
		plotPad.UseCurrentStyle()
		plotPad.Draw()	
		plotPad.cd()	
		
	# Data load processes
	colors = createMyColors()		
	if args.use2016:
		data = Process(Data2016, normalized=True)
	elif args.use2018:
		data = Process(Data2018, normalized=True)
	else:	
		data = Process(Data, normalized=True)

	eventCounts = totalNumberOfGeneratedEvents(path,plot.muon)	
	negWeights = negWeightFractions(path,plot.muon)
	#print negWeights

	# Background load processes	
	backgrounds = copy(args.backgrounds)
	if plot.useJets:
		if "Wjets" in backgrounds:
			backgrounds.remove("Wjets")
		backgrounds.insert(0,"Jets")
	processes = []
	for background in backgrounds:
		if args.use2016:
			if background == "Jets":
				processes.append(Process(getattr(Backgrounds2016,background),eventCounts,negWeights,normalized=True))
			else:	
				processes.append(Process(getattr(Backgrounds2016,background),eventCounts,negWeights))
		else:
			if background == "Jets":
				processes.append(Process(getattr(Backgrounds,background),eventCounts,negWeights,normalized=True))
			else:	
				processes.append(Process(getattr(Backgrounds,background),eventCounts,negWeights))
	
	# Signal load processes
	signals = []
	for signal in args.signals:
		if args.use2016:
			if args.ADD: signals.append(Process(getattr(Signals2016ADD, signal), eventCounts, negWeights))
			else: signals.append(Process(getattr(Signals2016,signal),eventCounts,negWeights))
		else:	
			if args.ADD: signals.append(Process(getattr(SignalsADD, signal), eventCounts, negWeights))
			else: signals.append(Process(getattr(Signals,signal),eventCounts,negWeights))
		
	legend = TLegend(0.55, 0.6, 0.925, 0.925)
	legend.SetFillStyle(0)
	legend.SetBorderSize(0)
	legend.SetTextFont(42)
	
	legendEta = TLegend(0.35, 0.55, 0.9, 0.9)
	legendEta.SetFillStyle(0)
	legendEta.SetBorderSize(0)
	legendEta.SetTextFont(42)
	legendEta.SetNColumns(2)


	latex = ROOT.TLatex()
	latex.SetTextFont(42)
	latex.SetTextAlign(31)
	latex.SetTextSize(0.04)
	latex.SetNDC(True)
	latexCMS = ROOT.TLatex()
	latexCMS.SetTextFont(61)
	latexCMS.SetTextSize(0.06)
	latexCMS.SetNDC(True)
	latexCMSExtra = ROOT.TLatex()
	latexCMSExtra.SetTextFont(52)
	latexCMSExtra.SetTextSize(0.045)
	latexCMSExtra.SetNDC(True)	
	legendHists = []
	
	# Modify legend information
	legendHistData = ROOT.TH1F()
	if args.data:	
		legend.AddEntry(legendHistData,"Data","pe")	
		legendEta.AddEntry(legendHistData,"Data","pe")	

	for process in reversed(processes):
		if not plot.muon and "#mu^{+}#mu^{-}" in process.label:
			process.label = process.label.replace("#mu^{+}#mu^{-}","e^{+}e^{-}")
		temphist = ROOT.TH1F()
		temphist.SetFillColor(process.theColor)
		legendHists.append(temphist.Clone)
		legend.AddEntry(temphist,process.label,"f")
		legendEta.AddEntry(temphist,process.label,"f")
	
	if args.signals !=0:
		processesWithSignal = []
		for process in processes:
			processesWithSignal.append(process)
		for Signal in signals:
			processesWithSignal.append(Signal)
			temphist = ROOT.TH1F()
			temphist.SetFillColor(Signal.theColor)
			temphist.SetLineColor(Signal.theLineColor)
			legendHists.append(temphist.Clone)		
			legend.AddEntry(temphist,Signal.label,"l")
			legendEta.AddEntry(temphist,Signal.label,"l")
	

	# Modify plot pad information	
	nEvents=-1

	ROOT.gStyle.SetOptStat(0)
	
	intlumi = ROOT.TLatex()
	intlumi.SetTextAlign(12)
	intlumi.SetTextSize(0.045)
	intlumi.SetNDC(True)
	intlumi2 = ROOT.TLatex()
	intlumi2.SetTextAlign(12)
	intlumi2.SetTextSize(0.07)
	intlumi2.SetNDC(True)
	scalelabel = ROOT.TLatex()
	scalelabel.SetTextAlign(12)
	scalelabel.SetTextSize(0.03)
	scalelabel.SetNDC(True)
	metDiffLabel = ROOT.TLatex()
	metDiffLabel.SetTextAlign(12)
	metDiffLabel.SetTextSize(0.03)
	metDiffLabel.SetNDC(True)
	chi2Label = ROOT.TLatex()
	chi2Label.SetTextAlign(12)
	chi2Label.SetTextSize(0.03)
	chi2Label.SetNDC(True)
	hCanvas.SetLogy()


	# Luminosity information	
	plotPad.cd()
	plotPad.SetLogy(0)
	logScale = plot.log
	
	if logScale == True:
		plotPad.SetLogy()
	if args.use2016:	
		lumi = 35.9*1000
		if plot.muon:
			lumi = 36.3*1000
	elif args.use2018:	
		lumi = 59.97*1000
		if plot.muon:
			lumi = 61.608*1000
	else:
		lumi = 41.529*1000
		if plot.muon:
			lumi = 42.135*1000
	if args.use2016:		
		zScaleFac = zScale2016["muons"]
		if not plot.muon:
			zScaleFac = zScale2016["electrons"]
	elif args.use2018:		
		zScaleFac = zScale2018["muons"]
		if not plot.muon:
			zScaleFac = zScale2018["electrons"]
	else:
		zScaleFac = zScale["muons"]
		if not plot.muon:
			zScaleFac = zScale["electrons"]
			
			
	# Data and background loading	
	if plot.plot2D:	
		datahist = data.loadHistogramProjected(plot,lumi,zScaleFac)	
		
		stack = TheStack2D(processes,lumi,plot,zScaleFac)
	else:
		datahist = data.loadHistogram(plot,lumi,zScaleFac)	
		
		stack = TheStack(processes,lumi,plot,zScaleFac)

	if args.data:
		yMax = datahist.GetBinContent(datahist.GetMaximumBin())
		if "Mass" in plot.fileName:
			yMin = 0.00001
		else:
			yMin = 0.01
		xMax = datahist.GetXaxis().GetXmax()
		xMin = datahist.GetXaxis().GetXmin()
	else:	
		yMax = stack.theHistogram.GetBinContent(datahist.GetMaximumBin())
		yMin = 0.01
		xMax = stack.theHistogram.GetXaxis().GetXmax()
		xMin = stack.theHistogram.GetXaxis().GetXmin()	
	if plot.yMax == None:
		if logScale:
			yMax = yMax*10000
		else:
			yMax = yMax*1.5
	else: yMax = plot.yMax
	
	if "Mass" in plot.fileName:
		yMax = 20000000	
	
	if not plot.yMin == None:
		yMin = plot.yMin
	if not plot.xMin == None:
		xMin = plot.xMin
	if not plot.xMax == None:
		xMax = plot.xMax
	#if args.ADD and args.use2016: 
	#	xMin = 1700
	#	xMax = 4000
	#	yMax = 1.0
	if "CosThetaStarBBM1800" in plot.fileName:
		yMax = 3
	plotPad.DrawFrame(xMin,yMin,xMax,yMax,"; %s ; %s" %(plot.xaxis,plot.yaxis))
	
	
	drawStack = stack
 	#~ print datahist.Integral(datahist.FindBin(60),datahist.FindBin(120))/drawStack.theHistogram.Integral(drawStack.theHistogram.FindBin(60),drawStack.theHistogram.FindBin(120))
 	#~ low = 900
 	#~ high = 1300
 	#~ print datahist.Integral(datahist.FindBin(low),datahist.FindBin(high))
 	#~ print drawStack.theHistogram.Integral(datahist.FindBin(low),datahist.FindBin(high))

	
	# Draw background from stack
	drawStack.theStack.Draw("samehist")							


	# Draw signal information
	if len(args.signals) != 0:
		signalhists = []
		for Signal in signals:
			if plot.plot2D: # plot collins-soper angle
				signalhist = Signal.loadHistogramProjected(plot,lumi, zScaleFac)
				signalhist.SetLineWidth(2)
				signalBackgrounds = deepcopy(backgrounds)
				signalBackgrounds.remove("DrellYan")
				signalProcesses = []
				for background in signalBackgrounds:
					if background == "Jets":
						signalProcesses.append(Process(getattr(Backgrounds,background),eventCounts,negWeights,normalized=True))
					else:	
						signalProcesses.append(Process(getattr(Backgrounds,background),eventCounts,negWeights))
				signalStack = TheStack2D(signalProcesses,lumi,plot, zScaleFac)
				signalhist.Add(signalStack.theHistogram)
				signalhist.SetMinimum(0.1)
				signalhist.Draw("samehist")
				signalhists.append(signalhist)	
			else:
				signalhist = Signal.loadHistogram(plot,lumi,zScaleFac)
				signalhist.SetLineWidth(2)
				signalBackgrounds = deepcopy(backgrounds)
				signalBackgrounds.remove("DrellYan") # signalBackgrounds = ["Jets", "Other"]
				signalProcesses = []
				for background in signalBackgrounds:
					if background == "Jets":
						signalProcesses.append(Process(getattr(Backgrounds,background),eventCounts,negWeights,normalized=True))
					else:	
						signalProcesses.append(Process(getattr(Backgrounds,background),eventCounts,negWeights))
				signalStack = TheStack(signalProcesses,lumi,plot,zScaleFac)
				signalhist.Add(signalStack.theHistogram)
				signalhist.SetMinimum(0.0001)
				signalhist.Draw("samehist")
				signalhists.append(signalhist)	

	# Draw data
	datahist.SetMinimum(0.0001)
	if args.data:
		datahist.Draw("samep")	

	# Draw legend
	if "Eta" in plot.fileName or "CosTheta" in plot.fileName:
		legendEta.Draw()
	else:
		legend.Draw()

	plotPad.SetLogx(plot.logX)
	
	latex.DrawLatex(0.95, 0.96, "%.1f fb^{-1} (13 TeV)"%(float(lumi)/1000,))
	yLabelPos = 0.85
	cmsExtra = "Private Work"
	if not args.data:
		cmsExtra = "#splitline{Private Work}{Simulation}"
		yLabelPos = 0.82	
	latexCMS.DrawLatex(0.19,0.89,"CMS")
	latexCMSExtra.DrawLatex(0.19,yLabelPos,"%s"%(cmsExtra))
	#~ print datahist.Integral()
	if args.ratio:
		try:
			ratioPad.cd()
			ratioPad.SetLogx(plot.logX)
		except AttributeError:
			print ("Plot fails. Look up in errs/failedPlots.txt")
			outFile =open("errs/failedPlots.txt","a")
			outFile.write('%s\n'%plot.filename%("_"+run.label+"_"+dilepton))
			outFile.close()
			plot.cuts=baseCut
			return 1
		ratioGraphs =  ratios.RatioGraph(datahist,drawStack.theHistogram, xMin=xMin, xMax=xMax,title="Data / MC",yMin=0.0,yMax=2,ndivisions=10,color=ROOT.kBlack,adaptiveBinning=10000)
		ratioGraphs.draw(ROOT.gPad,True,False,True,chi2Pos=0.8)
					

	ROOT.gPad.RedrawAxis()
	plotPad.RedrawAxis()
	if args.ratio:

		ratioPad.RedrawAxis()
	if not os.path.exists("plots"):
		os.makedirs("plots")	
	if args.use2016:
		hCanvas.Print("plots/"+plot.fileName+"_2016.pdf")
	elif args.use2018:
		hCanvas.Print("plots/"+plot.fileName+"_2018.pdf")
	else:	
		hCanvas.Print("plots/"+plot.fileName+"_2017.pdf")
Beispiel #11
0
        sys.exit(2)

    if vsbin:
        if tree.GetSelectedRows() >= 15:
            print("Maximum number of bins is 15")

if line or noline:
    if many:
        first = True
        color = 1
        grall = []
        vmin = 1.e+38
        vmax = -1.e+38
        cut0 = cut_cond
        data1 = data
        leg = TLegend(0.7, 0.7, 0.9, 0.9)
        for ros in range(rosmin, rosmax):
            for mod in range(modmin - 1, modmax):
                for chn in range(chanmin, chanmax + 1):
                    for adc in range(gainmin, gainmax + 1):
                        if "%d" in data:
                            data1 = data.replace(
                                "%d", str((adc - gainmin) * nval + val_n))
                        if "%d" in cut_cond:
                            cut0 = cut_cond.replace(
                                "%d", str((adc - gainmin) * nval + val_n))
                        cut1 = "(ros == %d && module == %d && channel == %d) && %s" % (
                            ros, mod, chn, cut0)
                        tree.Project("htemp", data1, cut1)
                        if tree.GetSelectedRows() > 0:
                            color = color + 1
    "D1=0 kV D2= 3 kV  E1= 1 kV E2 =3 kV",
    "D1=0 kV D2= 3 kV  E1=2  kV E2 =3 kV",
    "D1=0 kV D2= 3 kV  E1= 3 kV E2 =3 kV",
    "D1=0 kV D2= 3 kV  E1= 4 kV E2 =3 kV",
    "D1=0 kV D2= 3 kV  E1= 5 kV E2 =3 kV"
]

for j in [0, 1000, 2000, 3000, 4000, 5000]:
    timeDelay = analyseFile("../../ibsimuData/onDetector/D1_0D2_3000E1_" +
                            str(j) + "E2_3000_scanning33um.txt")
    timeDelay.SetLineWidth(5)
    listOfHistograms.append(timeDelay)

colorCounter = 1
canvas = TCanvas()
legend = TLegend(0.55, 0.55, 0.90, 0.90)
for i in range(5, -1, -1):
    print "mean", listOfHistograms[i].GetMean()
    listOfHistograms[i].GetXaxis().SetTitle("Estimated time delay [ns]")
    listOfHistograms[i].GetYaxis().SetTitle("Antiprotons per shoot")
    if i == 5:
        listOfHistograms[i].SetFillColorAlpha(colorCounter, 0.6)
        listOfHistograms[i].SetLineColor(colorCounter)
        listOfHistograms[i].Draw("hist")
        listOfHistograms[i].GetYaxis().SetRangeUser(0, 5)
        #listOfHistograms[i].Draw("hist")

    else:
        listOfHistograms[i].SetFillColorAlpha(colorCounter, 0.6)
        listOfHistograms[i].SetLineColor(colorCounter)
        listOfHistograms[i].Draw("hist same")
Beispiel #13
0
def main():  #pylint: disable=too-many-statements
    """
    main function of script
    """
    SetGlobalStyle(padleftmargin=0.18,
                   padbottommargin=0.14,
                   titleoffsety=1.6,
                   maxdigits=2,
                   optstat=0)

    n_bins = 1001
    bin_width = 0.05  # GeV
    bin_lims = [i * bin_width for i in range(0, n_bins + 1)]
    hFONLLBtoDCentral = TH1D(
        'hDfromBpred_central',
        ';#it{p}_{T} (GeV/#it{c});#frac{d#sigma}{d#it{p}_{T}} (pb GeV^{-1} #it{c})',
        n_bins, np.asarray(bin_lims, 'd'))
    hFONLLBtoDMin = TH1D(
        'hDfromBpred_min',
        ';#it{p}_{T} (GeV/#it{c});#frac{d#sigma}{d#it{p}_{T}} (pb GeV^{-1} #it{c})',
        n_bins, np.asarray(bin_lims, 'd'))
    hFONLLBtoDMax = TH1D(
        'hDfromBpred_max',
        ';#it{p}_{T} (GeV/#it{c});#frac{d#sigma}{d#it{p}_{T}} (pb GeV^{-1} #it{c})',
        n_bins, np.asarray(bin_lims, 'd'))
    hFONLLBCentral = TH1D(
        'hBpred_central',
        ';#it{p}_{T} (GeV/#it{c});#frac{d#sigma}{d#it{p}_{T}} (pb GeV^{-1} #it{c})',
        n_bins, np.asarray(bin_lims, 'd'))
    hFONLLBMin = TH1D(
        'hBpred_min',
        ';#it{p}_{T} (GeV/#it{c});#frac{d#sigma}{d#it{p}_{T}} (pb GeV^{-1} #it{c})',
        n_bins, np.asarray(bin_lims, 'd'))
    hFONLLBMax = TH1D(
        'hBpred_max',
        ';#it{p}_{T} (GeV/#it{c});#frac{d#sigma}{d#it{p}_{T}} (pb GeV^{-1} #it{c})',
        n_bins, np.asarray(bin_lims, 'd'))

    fonllBtoD_df = pd.read_csv("fonll/FONLL_DfromB_pp5_y05_toCook.txt",
                               sep=" ",
                               header=14).astype('float64')
    fonllB_df = pd.read_csv("fonll/FONLL_B_pp5_y05.txt", sep=" ",
                            header=13).astype('float64')

    for pt, cen, low, up in zip(fonllBtoD_df['pt'].to_numpy(),
                                fonllBtoD_df['central'].to_numpy(),
                                fonllBtoD_df['min'].to_numpy(),
                                fonllBtoD_df['max'].to_numpy()):
        hFONLLBtoDCentral.Fill(pt, cen)
        hFONLLBtoDMin.Fill(pt, low)
        hFONLLBtoDMax.Fill(pt, up)
    for pt, cen, low, up in zip(fonllB_df['pt'].to_numpy(),
                                fonllB_df['central'].to_numpy(),
                                fonllB_df['min'].to_numpy(),
                                fonllB_df['max'].to_numpy()):
        hFONLLBCentral.Fill(pt, cen)
        hFONLLBMin.Fill(pt, low)
        hFONLLBMax.Fill(pt, up)

    for iBin in range(hFONLLBtoDCentral.GetNbinsX()):
        hFONLLBtoDCentral.SetBinError(iBin + 1, 1.e-3)
        hFONLLBtoDMin.SetBinError(iBin + 1, 1.e-3)
        hFONLLBtoDMax.SetBinError(iBin + 1, 1.e-3)
        hFONLLBCentral.SetBinError(iBin + 1, 1.e-3)
        hFONLLBMin.SetBinError(iBin + 1, 1.e-3)
        hFONLLBMax.SetBinError(iBin + 1, 1.e-3)

    hFONLL = [hFONLLBtoDCentral, hFONLLBtoDMin, hFONLLBtoDMax]
    hBFONLL = [hFONLLBCentral, hFONLLBMin, hFONLLBMax]
    labels = ['Central', 'Min', 'Max']
    canvas = []

    for label in labels:
        canvas.append(TCanvas(f'cComp{label}', '', 2000, 1000))

    for (histo, histo_std, label, canv) in zip(hFONLL, hBFONLL, labels,
                                               canvas):
        pt_lims = np.array(histo.GetXaxis().GetXbins(), 'd')

        pt_min = list(pt_lims)[0]
        pt_max = list(pt_lims)[-1]
        histo_std = histo_std.Rebin(histo.GetNbinsX(), f'hBFONLL{label}',
                                    pt_lims)
        histo.Rebin(5)
        histo_std.Rebin(5)
        histo.Scale(1.e-6)
        histo_std.Scale(1.e-6)
        histo_ratio = histo.Clone(f'hRatioDfromBOverB{label}')
        histo_ratio.Divide(histo, histo_std)
        histo_ratio.GetYaxis().SetTitle('FONLL D from B / FONLL B')

        print(
            f'\nFONLL B {label} integral (ub): {histo_std.Integral("width"):.4e}'
        )
        print(
            f'FONLL B from D {label} integral (ub): {histo.Integral("width"):.4e}\n'
        )

        canv.Divide(2, 1)
        canv.cd(1).DrawFrame(
            pt_min, 1e-4, pt_max, 100.,
            ';#it{p}_{T} (GeV/#it{c});#frac{d#sigma}{d#it{p}_{T}} (#mub GeV^{-1} #it{c})'
        )
        leg = TLegend(0.4, 0.7, 0.8, 0.9)
        leg.SetTextSize(0.045)
        leg.SetBorderSize(0)
        leg.SetFillStyle(0)
        SetObjectStyle(histo, color=kAzure + 4, markerstyle=kFullSquare)
        SetObjectStyle(histo_std, color=kRed, markerstyle=kFullCircle)
        histo.Draw('same')
        histo_std.Draw('same')
        leg.AddEntry(histo, f'FONLL D from B {label}', 'p')
        leg.AddEntry(histo_std, f'FONLL B {label}', 'p')
        gPad.SetLogy()
        leg.Draw()

        hframe_ratio = canv.cd(2).DrawFrame(
            pt_min, 0., pt_max, 3.5,
            ';#it{p}_{T} (GeV/#it{c}); FONLL D from B / FONLL B')
        hframe_ratio.GetYaxis().SetDecimals()
        SetObjectStyle(histo_ratio, color=kAzure + 4, markerstyle=kFullSquare)
        histo_ratio.Draw('same')
        canv.Update()
        canv.SaveAs(f'CompFONLL_DfromBvsB_{label}.pdf')

    input('Press enter to exit')
Beispiel #14
0
    if i == 0:
        graphs[i].GetYaxis().SetTitleOffset(1.25)
        graphs[i].GetXaxis().SetLabelSize(fontsize)
        graphs[i].GetXaxis().SetTitleSize(fontsize)
        graphs[i].GetYaxis().SetLabelSize(fontsize)
        graphs[i].GetYaxis().SetTitleSize(fontsize)
        graphs[i].SetMarkerStyle(i+33)
        graphs[i].GetXaxis().SetTitle("Anode voltage [kV]")
        graphs[i].GetYaxis().SetTitle("Average peak height [mV]")
        graphs[i].SetTitle("Gas amplification")
        graphs[i].Draw("AP")
    else:
        graphs[i].SetMarkerStyle(i+19)
        graphs[i].Draw("P")

leg = TLegend(0.67,0.13,0.87,0.45)
leg.SetBorderSize(0)
leg.SetTextSize(fontsize)

leg.AddEntry("gr3","{} bar".format(preassures[2]/1000),"p")
leg.AddEntry("gr2","{} bar".format(preassures[1]/1000),"p")
leg.AddEntry("gr4","{} bar".format(preassures[3]/1000),"p")
leg.AddEntry("gr5","{} bar".format(preassures[4]/1000),"p")
leg.AddEntry("gr1","{} bar".format(preassures[0]/1000),"p")

leg.Draw()

c1.Draw()
c1.Print("../plots/gasamp.pdf")

f.Close()
Beispiel #15
0
  erry.append(i[2])
for i in range(len(erry) ): erry[i] = (yVals[i] * (1 - yVals[i]) / erry[i]) **(1/2.0)
g750N = TGraphErrors(9,xVals,yVals,errx,erry)
g750N.SetLineColor(ROOT.kRed+1)
g750N.SetLineWidth(3)
g750N.SetMarkerColor(ROOT.kRed+1)
g750N.SetLineStyle(2)
g750N.SetMarkerSize(1)
g750N.SetMarkerStyle(8)
g750N.SetTitle("")
g750N.GetXaxis().SetTitle("m_{a} GeV")
#g750N.GetXaxis().SetTitleSize(1.1)
g750N.GetYaxis().SetTitle("Reconstruction Efficiency")
#g750N.GetYaxis().SetTitleSize(1.1)

leg = TLegend(.3,.18,.55,.4)
leg.SetBorderSize(0)
leg.SetFillColor(0)
leg.SetFillStyle(0)
leg.SetTextFont(42)
leg.SetTextSize(0.035)
leg.SetHeader("Muon Cleaned HPS")
leg.AddEntry(g125C,"m_{h} = 125 GeV","L")
leg.AddEntry(g300C,"m_{h} = 300 GeV","L")
leg.AddEntry(g750C,"m_{h} = 750 GeV","L")

leg2 = TLegend(.6,.18,.85,.4)
leg2.SetBorderSize(0)
leg2.SetFillColor(0)
leg2.SetFillStyle(0)
leg2.SetTextFont(42)
Beispiel #16
0
def createLegends(sample, h1, h2, h3, h4):
    if sample == "data":
        leg = TLegend(0.65, 0.75, 0.92, 0.90)
    if sample == "zjets":
        leg = TLegend(0.60, 0.75, 0.90, 0.90)
        leg.SetHeader("Likelihood")
    if sample == "truth":
        leg = TLegend(0.60, 0.55, 0.90, 0.72)
        leg.SetHeader("Truth-matching")
    leg.SetFillStyle(0)
    #leg.SetBorderSize(0)
    leg.SetTextFont(62)
    leg.SetTextSize(0.03)
    leg.AddEntry(h1, "p_{T} #in [10, 60] GeV ", "l")
    leg.AddEntry(h2, "p_{T} #in [60, 90] GeV ", "l")
    leg.AddEntry(h3, "p_{T} #in [90, 130] GeV ", "l")
    leg.AddEntry(h4, "p_{T} #in [130, 1000] GeV ", "l")
    return leg
        hist_rnk = create_and_fill_rank_hist(ranks, pattern)
        plot_modifier(hist_rnk, "rank", "N", ROOT.kBlack)
        hist_rnk.Draw()
        canvas.Print("{f}/figures/hw_rank.pdf".format(f=fnames['base']))

        hists_input = create_and_fill_muon_hists(hist_parameters, in_muons,
                                                 pattern + "in")
        hists_output = create_and_fill_muon_hists(hist_parameters, out_muons,
                                                  pattern + "out")
        hists_imd = create_and_fill_muon_hists(hist_parameters,
                                               intermediate_muons,
                                               pattern + "imd")

        for var in hist_parameters:
            hw_leg = TLegend(0.4, 0.7, 0.7, 0.85)
            set_legend_style(hw_leg)
            a = hists_input[var].GetBinContent(
                hists_input[var].GetMaximumBin())
            b = hists_output[var].GetBinContent(
                hists_output[var].GetMaximumBin())
            c = max(a, b)

            plot_modifier(hists_input[var], hist_parameters[var][0], "N",
                          ROOT.kAzure - 4)
            plot_modifier(hists_output[var], hist_parameters[var][0], "N",
                          ROOT.kBlack, 20)
            plot_modifier(hists_imd[var], hist_parameters[var][0], "N",
                          ROOT.kBlack)
            hists_imd[var].SetFillStyle(0)
            hists_imd[var].SetLineStyle(2)
Beispiel #18
0
line6 = TLine(31, 1.55, 42, 1.55)
line7 = TLine(42, 1.55, 42, 2)
line8 = TLine(42, 2, 60, 2)
line9 = TLine(60, 2, 90, 2)
line10 = TLine(90, 2, 90, 0)
line11 = TLine(90, 0, 20, 0)

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

leg = TLegend(.61, .55, .65, .59)
leg.SetFillStyle(0)
leg.SetLineWidth(4)
leg.Draw()

text = TLatex(.67, .55, "MIPP 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 #19
0
                                   '/discriminantVsMu').ProjectionX().Clone()

            objHolder.append(canvas.cd(etaBinIdx + 1))
            h1.SetTitle(
                ('; Neural Network (Discriminant); Signal Counts (%s)') %
                (binname.replace('_', ',')))
            h1.SetFillColor(kAzure + 6)
            h1.SetLineColor(kAzure + 6)
            h1.Rebin(10)
            h2.SetLineColor(kBlack)
            h2.Rebin(10)
            h1.Scale(1. / h1.GetMaximum())
            h2.Scale(1. / h2.GetMaximum())
            h1.Draw()
            h2.Draw('same')
            leg1 = TLegend(0.2, 0.75, 0.5, 0.95)
            setLegend1(leg1)
            leg1.AddEntry(h1, 'MC')
            leg1.AddEntry(h2, 'Data')
            leg1.Draw()
            objHolder[-1].Update()

            path = mcBasepath + '/fakes/' + pid + '/' + ringerName + '/' + binname
            h3 = storeMC.histogram(path +
                                   '/discriminantVsMu').ProjectionX().Clone()
            path = ppBasepath + '/fakes/' + pid + '/' + ringerName + '/' + binname
            h4 = storePP.histogram(path +
                                   '/discriminantVsMu').ProjectionX().Clone()

            objHolder.append(canvas.cd(etaBinIdx + 1 + nEtaBins))
            h3.SetTitle(
Beispiel #20
0
evhistonames = ['hEvForNorm', 'hEvForNorm']
colors = [kRed + 1, kAzure + 4]
markers = [kFullSquare, kFullCircle]
legendnames = ['title1', 'title2']

SetGlobalStyle(padleftmargin=0.18,
               padtopmargin=0.05,
               padbottommargin=0.14,
               titleoffsety=1.8,
               titlesize=0.045,
               labelsize=0.04,
               maxdigits=2)

hSignal, hRatioSignal, hBackground, hRatioBkg, hSoverB, hSignif, hRatioSignif, hEv = [], [], [], [], [], [], [], []

leg = TLegend(0.5, 0.73, 0.8, 0.93)
leg.SetFillStyle(0)
leg.SetBorderSize(0)
leg.SetTextSize(0.04)

for iFile, filename in enumerate(inputfilenames):
    inputfile = TFile(f'{inputdir}/{filename}')
    hSignal.append(inputfile.Get(signalhistonames[iFile]))
    hBackground.append(inputfile.Get(bkghistonames[iFile]))
    hSignif.append(inputfile.Get(signifhistonames[iFile]))
    hSoverB.append(inputfile.Get(SoverBhistonames[iFile]))
    hEv.append(inputfile.Get(evhistonames[iFile]))
    hSignal[iFile].SetDirectory(0)
    hBackground[iFile].SetDirectory(0)
    hSoverB[iFile].SetDirectory(0)
    hSignif[iFile].SetDirectory(0)
Beispiel #21
0
def plot(path, ecms, xmin, xmax, num_charm):
    try:
        f_data = TFile(path[0])
        t_data = f_data.Get('save')
        entries_data = t_data.GetEntries()
        logging.info('data entries :'+str(entries_data))
    except:
        logging.error(path[0] + 'is invalid!')
        sys.exit()
    try:
        f_side1 = TFile(path[1])
        t_side1 = f_side1.Get('save')
        entries_side1 = t_side1.GetEntries()
        logging.info('data(side1) entries :'+str(entries_side1))
    except:
        logging.error(path[1] + ' is invalid!')
        sys.exit()
    try:
        f_side2 = TFile(path[2])
        t_side2 = f_side2.Get('save')
        entries_side2 = t_side2.GetEntries()
        logging.info('data(side2) entries :'+str(entries_side2))
    except:
        logging.error(path[2] + ' is invalid!')
        sys.exit()
    try:
        f_side3 = TFile(path[3])
        t_side3 = f_side3.Get('save')
        entries_side3 = t_side3.GetEntries()
        logging.info('data(side3) entries :'+str(entries_side3))
    except:
        logging.error(path[3] + ' is invalid!')
        sys.exit()
    try:
        f_side4 = TFile(path[4])
        t_side4 = f_side4.Get('save')
        entries_side4 = t_side4.GetEntries()
        logging.info('data(side4) entries :'+str(entries_side4))
    except:
        logging.error(path[4] + ' is invalid!')
        sys.exit()

    mbc = TCanvas('mbc', 'mbc', 800, 600)
    set_canvas_style(mbc)
    xbins = 120
    ytitle = 'Eentries'
    xtitle = 'P(OtherTrks) (GeV)'

    h_data = TH1F('data', 'data', xbins, xmin, xmax)
    set_histo_style(h_data, xtitle, ytitle, 1, -1)
    p_othertrks_fill(t_data, h_data, num_charm)
    
    h_side1 = TH1F('side1', 'side1', xbins, xmin, xmax)
    set_histo_style(h_side1, xtitle, ytitle, 3, 3004)
    p_othertrks_fill(t_side1, h_side1, num_charm)
    
    h_side2 = TH1F('side2', 'side2', xbins, xmin, xmax)
    set_histo_style(h_side2, xtitle, ytitle, 3, 3004)
    p_othertrks_fill(t_side2, h_side2, num_charm)
    
    h_side3 = TH1F('side3', 'side3', xbins, xmin, xmax)
    set_histo_style(h_side3, xtitle, ytitle, 3, 3004)
    p_othertrks_fill(t_side3, h_side3, num_charm)
    
    h_side4 = TH1F('side4', 'side4', xbins, xmin, xmax)
    set_histo_style(h_side4, xtitle, ytitle, 3, 3004)
    p_othertrks_fill(t_side4, h_side4, num_charm)
    
    h_side1.Add(h_side2)
    h_side1.Scale(0.5)
    h_side3.Add(h_side4)
    h_side3.Scale(0.25)
    h_side1.Add(h_side3, -1)
    h_data.Draw('E1')
    hs = THStack('hs', 'Stacked')
    hs.Add(h_side1)
    hs.Draw('same')
    h_data.Draw('sameE1')

    legend = TLegend(0.5, 0.6, 0.8, 0.85)
    leg_title = str(ecms) + ' MeV'
    set_legend(legend, h_data, h_side1, leg_title)
    legend.Draw()

    if not os.path.exists('./figs/'):
        os.makedirs('./figs/')
    
    mbc.SaveAs('./figs/p_othertrks_'+str(ecms)+'_'+str(num_charm)+'.pdf')

    raw_input('Enter anything to end...')
Beispiel #22
0
def compareData():
    """ Compare Frank's table with Graham's data.
    NOTES:
    fs idx 10 = 1.74 kev
    fs idx 12 = 1.84 kev
    fs idx 24 = 2.31 kev
    fs idx 28 = 2.46 kev
    linear fit gives 0.0396 ~ 0.04 bins/kev.
    that means that fLo = 1.84 - n*0.04, n = 12, *** fLo = 1.36 ***
    and fHi = 1.36 + len(fs)*0.04, len(fs)=39,   *** fHi = 2.92 ***
    """
    malbekExposure = 89.5  # kg-d

    # -- frank's table --
    col1 = [
        2.40, 3.07, 2.23, 4.34, 1.83, 2.48, 2.79, 2.23, 2.23, 1.96, 2.51, 1.95,
        1.96, 2.51, 2.79, 1.68, 2.79, 2.51, 4.75, 1.40, 2.23
    ]
    col2 = [
        5.86, 1.92, 2.40, 3.07, 2.23, 4.34, 1.84, 2.48, 2.79, 2.23, 2.23, 1.95,
        2.51, 1.96, 1.96, 2.51, 2.79, 1.68, 2.79, 2.51, 4.75
    ]
    col3 = [
        1.96, 2.51, 2.79, 1.68, 2.79, 2.51, 4.75, 1.40, 2.23, 3.07, 4.47, 3.63,
        1.96, 3.07, 2.23, 2.79, 1.12, 3.91, 1.40, 1.68, 3.07
    ]
    col4 = [
        2.79, 2.51, 4.75, 1.40, 2.23, 3.07, 4.47, 3.63, 1.95, 3.07, 2.23, 2.79,
        1.12, 3.91, 1.40, 1.68, 3.07, 1.12, 2.23, 2.23, 2.79
    ]
    col5 = [
        13.01, 10.01, 12.17, 10.49, 9.08, 12.40, 13.85, 9.74, 9.20, 10.33,
        11.44, 10.32, 7.55, 11.45, 8.38, 8.66, 9.77, 9.22, 11.17, 7.82, 12.84
    ]  # verified the sum is correct.
    axionCol = 10  # 0-indexed

    # frank's spectrum (from comparing when #'s in columns 1-4 repeat)
    fs = [
        5.86, 1.92, 2.40, 3.07, 2.23, 4.34, 1.84, 2.48, 2.79, 2.23, 2.23, 1.95,
        2.51, 1.96, 1.96, 2.51, 2.79, 1.68, 2.79, 2.51, 4.75, 1.40, 2.23, 3.07,
        4.47, 3.63, 1.96, 3.07, 2.23, 2.79, 1.12, 3.91, 1.40, 1.68, 3.07, 1.12,
        2.23, 2.23, 2.79
    ]

    # frank didn't adjust for kev/bin of 0.04 keV bins times exposure (0.04 * 89.5 = 3.58)
    fs = [val * 3.58 for val in fs]

    # set binning and endpoints, and fill a histogram
    fBins = len(fs)  # 39
    binSize = 0.04
    fLo = 1.84 - 12 * binSize  # 1.3648
    fHi = fLo + fBins * binSize  # 2.9092
    hF = TH1D("hF", "", fBins, fLo, fHi)
    for i in range(fBins):
        hF.SetBinContent(i, fs[i])
    hF.SetLineColor(ROOT.kRed)
    hF.Scale(1. / malbekExposure)
    print "Frank's data: bins %d  eLo %.3f  eHi %.3f" % (fBins, fLo, fHi)

    # -- graham's data --
    f1 = TFile("./data/malbek_data.root")
    t1 = f1.Get("malbek_wrt")

    # duplicate the frank region only
    hG1 = TH1D("hG1", "", fBins, fLo, fHi)
    t1.Project("hG1", "energy_keV", "weight")
    hG1.Scale(1. / malbekExposure)
    hG1.SetLineColor(ROOT.kGreen)

    # get histo for a larger energy region
    eLo, eHi = 1.0, 3.5
    nBins = int((eHi - eLo) / binSize + 0.5)
    hG2 = TH1D("hG2", "", nBins, eLo, eHi)
    t1.Project("hG2", "energy_keV", "weight")
    hG2.SetLineColor(ROOT.kBlue)
    hG2.GetXaxis().SetTitle("Energy (keV)")
    hG2.Scale(1. / malbekExposure)

    # -- plot all three --
    c = TCanvas("c", "c", 800, 600)
    gStyle.SetOptStat(0)

    hG2.Draw("hist")
    hG1.Draw("hist same")
    hF.Draw("hist same")

    leg = TLegend(0.5, 0.7, 0.85, 0.85)
    leg.AddEntry(hF, "frank, %.2f-%.2f, %.3f b/kev" % (fLo, fHi, binSize), "l")
    leg.AddEntry(hG1, "graham-1, %.2f-%.2f" % (fLo, fHi), "l")
    leg.AddEntry(hG2, "graham-2, %.2f-%.2f" % (eLo, eHi), "l")
    leg.Draw("same")

    c.Print("./plots/testSpec.pdf")
Beispiel #23
0
gr_pre.SetMarkerStyle(21)
gr_pre.SetLineColor(4)

gr_post = TGraphErrors(6, X, Ypost, Xerr, Ypost_err)
gr_post.SetMarkerColor(2)
gr_post.SetMarkerStyle(21)
gr_post.SetLineColor(2)

mg = TMultiGraph()
mg.Add(gr_pre, 'p')
mg.Add(gr_post, 'p')

mg.SetTitle(channel)
mg.SetTitle(channel + ';bin')

leg = TLegend(0.7, 0.7, 0.9, 0.9)
leg.SetFillColor(0)
leg.AddEntry(gr_pre, 'prefit', 'p')
leg.AddEntry(gr_post, 'postfit', 'p')

mg.Draw('a')
leg.Draw()

c1.Draw()

# In[151]:

mlfit.cd('shapes_prefit')
total_pre = gDirectory.Get('total_background')
total_pre.SetLineColor(4)
neutralLeptonPtHisto.Write()
canvas.Update()
canvas.Print(argv[1] + "_NeutralLeptonsPtHisto.png", "png")
canvas.Print(argv[1] + "_NeutralLeptonsPtHisto.svg", "svg")


# EW Boson 1 + EW Boson 2 + total distribution
ewBoson1PtHisto.SetLineColor(2)
ewBoson2PtHisto.SetLineColor(3)
ewBosonPtHisto.Draw()
ewBosonPtHisto.Write()
ewBoson1PtHisto.Draw("SAME")
ewBoson1PtHisto.Write()
ewBoson2PtHisto.Draw("SAME")
ewBoson2PtHisto.Write()
leg1 = TLegend(0.7,0.7,0.48,0.9)
leg1.SetHeader("Momentum distribution")
leg1.AddEntry(ewBosonPtHisto,"EW boson 1 + EW Boson 2","l")
leg1.AddEntry(ewBoson1PtHisto,"EW Boson 1","l")
leg1.AddEntry(ewBoson2PtHisto,"EW Boson 2","l")
leg1.Draw()
canvas.Update()
canvas.Print(argv[1] + "_EWBosonPtHistogramComparison_1.png", "png")
canvas.Print(argv[1] + "_EWBosonPtHistogramComparison_1.svg", "svg")

# Leading + sub-leading + total distribution
ewBosonLeadingPtHisto.SetLineColor(2)
ewBosonSubLeadingPtHisto.SetLineColor(3)
ewBosonPtHisto.Draw()
ewBosonPtHisto.Write()
ewBosonLeadingPtHisto.Draw("SAME")
Beispiel #25
0
h2.Sumw2()
h2.Scale(1 / h2.Integral())
h3.Sumw2()
h3.Scale(1 / h3.Integral())
h4.Sumw2()
h4.Scale(1 / h4.Integral())
h5.Sumw2()
h5.Scale(1 / h5.Integral())

a = TH1F("a", "a", 10, 0, 100)
a.Fill(1)

c = TCanvas("c1", "c1", 0, 0, 500, 500)
gStyle.SetOptStat(0)

leg = TLegend(0.15, 0.7, 0.45, 0.9)
leg.SetFillColor(0)
leg.SetFillStyle(0)
leg.SetTextSize(0.04)
leg.SetBorderSize(0)
leg.SetTextFont(22)
leg.Draw()

h1.SetLineColor(1)
h1.SetLineWidth(2)
h1.SetLineStyle(1)

h2.SetLineColor(2)
h2.SetLineWidth(2)
h2.SetLineStyle(1)
Beispiel #26
0
    def legend4Plot(plot, left = False):
        if left:
            theLeg = TLegend(0.2, 0.62, 0.55, 0.92, "", "NDC")
        else:
            theLeg = TLegend(0.60, 0.62, 0.92, 0.92, "", "NDC")
        theLeg.SetName('theLegend')

        theLeg.SetBorderSize(0)
        theLeg.SetLineColor(0)
        theLeg.SetFillColor(0)
        theLeg.SetFillStyle(0)
        theLeg.SetLineWidth(0)
        theLeg.SetLineStyle(0)
        theLeg.SetTextFont(42)
        theLeg.SetTextSize(.045)

        entryCnt = 0
        for obj in range(0, int(plot.numItems())):
            objName = plot.nameOf(obj)
            if (not plot.getInvisible(objName)):
                theObj = plot.getObject(obj)
                objTitle = theObj.GetTitle()
                if len(objTitle) < 1:
                    objTitle = objName
                dopts = plot.getDrawOptions(objName).Data()
                # print 'obj:',theObj,'title:',objTitle,'opts:',dopts,'type:',type(dopts)
                if theObj.IsA().InheritsFrom('TNamed'):
                    theLeg.AddEntry(theObj, objTitle, dopts)
                    entryCnt += 1
        theLeg.SetY1NDC(0.9 - 0.05*entryCnt - 0.005)
        theLeg.SetY1(theLeg.GetY1NDC())
        return theLeg
Beispiel #27
0
plotTitle = "Cluster Rates"

inFile1 = TFile(filename1)
inFile2 = TFile(filename2)

c = TCanvas("c", "c", 800, 600)

Histo1 = inFile1.Get(histoTitle)
Histo2 = inFile2.Get(histoTitle)

Histo3 = inFile2.Get("Energy")
Histo4 = inFile1.Get("Energy")
Histo5 = inFile2.Get("Energy Fiducial")
Histo6 = inFile1.Get("Energy Fiducial")

legend = TLegend(.68, .66, .92, .87)
legend.SetBorderSize(0)
legend.SetFillColor(0)
legend.SetFillStyle(0)
legend.SetTextFont(42)
legend.SetTextSize(0.035)
legend.AddEntry(Histo3, "L0", "LP")
legend.AddEntry(Histo4, "Nominal", "LP")

Histo1.Scale(0.1)
Histo2.Scale(0.1)

c.Print("TriggerPlots.pdf[", "Title:histoTitle")

Histo1.Draw("COLZ")
Histo1.SetTitle(plotTitle + " Nominal")
def DrawOverlap(fileVec,
                histVec,
                titleVec,
                legendtext,
                pngname,
                logstatus=[0, 0],
                xRange=[-99999, 99999, 1]):

    gStyle.SetOptTitle(0)
    gStyle.SetOptStat(0)
    gStyle.SetTitleOffset(1.1, "Y")
    gStyle.SetTitleOffset(0.9, "X")
    gStyle.SetLineWidth(3)
    gStyle.SetFrameLineWidth(3)

    i = 0

    histList_ = []
    histList = []
    histList1 = []
    maximum = []

    ## Legend
    leg = TLegend(0.4, 0.70, 0.939, 0.89)  #,NULL,"brNDC");
    leg.SetBorderSize(0)
    leg.SetNColumns(2)
    leg.SetLineColor(1)
    leg.SetLineStyle(1)
    leg.SetLineWidth(1)
    leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetTextFont(22)
    leg.SetTextSize(0.045)

    c = TCanvas("c1", "c1", 0, 0, 500, 500)
    #c.SetBottomMargin(0.15)
    #c.SetLeftMargin(0.15)
    #c.SetLogy(0)
    #c.SetLogx(0)
    c1_2 = TPad("c1_2", "newpad", 0.04, 0.13, 1, 0.994)
    c1_2.Draw()

    print("you have provided " + str(len(fileVec)) + " files and " +
          str(len(histVec)) + " histograms to make a overlapping plot")
    print "opening rootfiles"
    c.cd()
    c1_2.SetBottomMargin(0.13)
    c1_2.SetLogy(logstatus[1])
    c1_2.SetLogx(logstatus[0])

    c1_2.cd()
    ii = 0
    inputfile = {}
    print str(fileVec[(len(fileVec) - 1)])

    for ifile_ in range(len(fileVec)):
        print("opening file  " + fileVec[ifile_])
        inputfile[ifile_] = TFile(fileVec[ifile_])
        print "fetching histograms"
        for ihisto_ in range(len(histVec)):
            print("printing histo " + str(histVec[ihisto_]))
            histo = inputfile[ifile_].Get(histVec[ihisto_])
            #status_ = type(histo) is TGraphAsymmErrors
            histList.append(histo)
            # for ratio plot as they should nt be normalize
            histList1.append(histo)
            print histList[ii].Integral()
            #histList[ii].Rebin(xRange[2])
            type_obj = type(histList[ii])
            if (type_obj is TH1D) or (type_obj is TH1F) or (
                    type_obj is TH1) or (type_obj is TH1I):
                histList[ii].Rebin(5)
                histList[ii].Scale(1.0 / histList[ii].Integral())
                maximum.append(histList[ii].GetMaximum())
                maximum.sort()
            ii = ii + 1

    print histList
    for ih in range(len(histList)):
        tt = type(histList[ih])
        #        print "graph_status =" ,(tt is TGraphAsymmErrors)
        #        print "hist status =", (tt is TH1D) or (tt is TH1F)
        if ih == 0:
            if (tt is TGraphAsymmErrors) | (tt is TGraph):
                histList[ih].Draw("AL3P")
            if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I):
                histList[ih].Draw("CHIST")
        if ih > 0:
            #histList[ih].SetLineWidth(2)
            if (tt is TGraphAsymmErrors) | (tt is TGraph):
                histList[ih].Draw("L3P same")
            if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I):
                histList[ih].Draw("CHISTsame")

        if (tt is TGraphAsymmErrors) | (tt is TGraph):
            # histList[ih].SetMaximum(0.06)
            # histList[ih].SetMinimum(0.02)
            histList[ih].SetMaximum(10.2)
            histList[ih].SetMinimum(10.1)
            histList[ih].SetMarkerColor(colors[ih])
            histList[ih].SetLineColor(colors[ih])
            histList[ih].SetLineWidth(3)
            histList[ih].SetLineStyle(linestyle[ih])

            histList[ih].SetMarkerStyle(markerStyle[ih])
            histList[ih].SetMarkerSize(1)
            leg.AddEntry(histList[ih], legendtext[ih], "PL")
        if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I):
            histList[ih].SetLineStyle(linestyle[ih])
            histList[ih].SetLineColor(colors[ih])
            histList[ih].SetLineWidth(3)
            leg.AddEntry(histList[ih], legendtext[ih], "L")
        histList[ih].GetYaxis().SetTitle(titleVec[1])
        histList[ih].GetYaxis().SetTitleSize(0.045)
        histList[ih].GetYaxis().SetTitleOffset(1.1000998)
        histList[ih].GetYaxis().SetTitleFont(22)
        histList[ih].GetYaxis().SetLabelFont(22)
        histList[ih].GetYaxis().SetLabelSize(.045)
        histList[ih].GetXaxis().SetRangeUser(xRange[0], xRange[1])
        histList[ih].GetXaxis().SetLabelSize(0.0000)
        histList[ih].GetXaxis().SetTitle(titleVec[0])
        histList[ih].GetXaxis().SetLabelSize(0.052)
        histList[ih].GetXaxis().SetTitleSize(0.052)
        histList[ih].GetXaxis().SetTitleOffset(1.04)
        histList[ih].GetXaxis().SetTitleFont(22)
        histList[ih].GetXaxis().SetTickLength(0.07)
        histList[ih].GetXaxis().SetLabelFont(22)
        histList[ih].GetYaxis().SetLabelFont(22)
        # histList[ih].GetXaxis().SetNdivisions(508)
        #

        i = i + 1
    pt = TPaveText(0.0877181, 0.9, 0.9580537, 0.96, "brNDC")
    pt.SetBorderSize(0)
    pt.SetTextAlign(12)
    pt.SetFillStyle(0)
    pt.SetTextFont(22)
    pt.SetTextSize(0.046)
    text = pt.AddText(0.05, 0.5, "CMS Preliminary")
    #text = pt.AddText(0.5,0.5,"12.9 fb^{-1} (13 TeV)")
    #    text = pt.AddText(0.8,0.5," (13 TeV)")
    #   text = pt.AddText(0.65,0.5," AK8")
    pt.Draw()

    #    t2a = TPaveText(0.0877181,0.81,0.9580537,0.89,"brNDC")
    #    t2a.SetBorderSize(0)
    #    t2a.SetFillStyle(0)
    #    t2a.SetTextSize(0.040)
    #    t2a.SetTextAlign(12)
    #    t2a.SetTextFont(62)
    #    histolabel1= str(fileVec[(len(fileVec)-1)])
    #    text1 = t2a.AddText(0.06,0.5,"CMS Internal")
    #    t2a.Draw()
    leg.Draw()
    #
    #    c.cd()
    outputdirname = 'HGCAL/'
    histname = outputdirname + pngname
    c.SaveAs(histname + '.png')
    c.SaveAs(histname + '.pdf')
def drawMassRes(data, mc, output, rapidity, ptda, ptmc, trackType, funct,
                mcIsData, dataIsMC):
    style = setTDRStyle()

    pt_e = [0 for x in range(len(data))]
    pt_x = [0 for x in range(len(data))]
    for i, pt in enumerate(pt_x):
        pt_x[i] = ptbins[i] + (ptbins[i + 1] - ptbins[i]) / 2.
        pt_e[i] = (ptbins[i + 1] - ptbins[i]) / 2.
    if dataIsMC:
        (da_mean, da_meane, da_sig, da_sige,
         da_nChi2) = doFit(data, output, rapidity, "MC2", trackType, funct)
    else:
        (da_mean, da_meane, da_sig, da_sige,
         da_nChi2) = doFit(data, output, rapidity, "DATA", trackType, funct)
    if mcIsData:
        (mc_mean, mc_meane, mc_sig, mc_sige,
         mc_nChi2) = doFit(mc, output, rapidity, "DATA2", trackType, funct)
    else:
        (mc_mean, mc_meane, mc_sig, mc_sige,
         mc_nChi2) = doFit(mc, output, rapidity, "MC", trackType, funct)
    result = {}
    result["data_mean"] = da_mean
    result["data_meane"] = da_meane
    result["data_sig"] = da_sig
    result["data_sige"] = da_sige
    result["mc_mean"] = mc_mean
    result["mc_meane"] = mc_meane
    result["mc_sig"] = mc_sig
    result["mc_sige"] = mc_sige
    result["ptda"] = ptda
    result["ptmc"] = ptmc
    result["da_nChi2"] = da_nChi2
    result["mc_nChi2"] = mc_nChi2

    pklFile = open(
        output + "/MassResolutionVsPt_%s_%s.pkl" % (trackType, rapidity), "wb")
    pickle.dump(result, pklFile)
    pklFile.close()

    c2 = TCanvas("c2", "c2", 700, 700)
    c2.cd()

    # Upper plot will be in pad1
    pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0)
    pad1.SetGrid()  # Vertical grid
    pad1.SetBottomMargin(0.1)
    pad1.Draw()  # Draw the upper pad: pad1
    pad1.cd()  # pad1 becomes the current pad
    pad1.SetTicks()

    res_data = TGraphAsymmErrors()
    res_data.SetName("res_data")
    res_mc = TGraphAsymmErrors()
    res_mc.SetName("res_mc")
    ratio = TGraphErrors()
    ratio.SetName("ratio")
    #~ print len(pt_x)
    for i, pt in enumerate(pt_x):
        res_data.SetPoint(i, ptda[i], da_sig[i])
        res_data.SetPointError(i, ptda[i] - ptbins[i], ptbins[i + 1] - ptda[i],
                               da_sige[i], da_sige[i])
        res_mc.SetPoint(i, ptmc[i], mc_sig[i])
        res_mc.SetPointError(i, ptmc[i] - ptbins[i], ptbins[i + 1] - ptmc[i],
                             mc_sige[i], mc_sige[i])
        if mc_sig[i] > 0:
            ratio.SetPoint(i, pt, da_sig[i] / mc_sig[i])
            ratio.SetPointError(i, pt_e[i], (da_sig[i] / mc_sig[i]) *
                                math.sqrt((da_sige[i] / da_sig[i])**2 +
                                          (mc_sige[i] / mc_sig[i])**2))
    res_data.SetMarkerStyle(22)
    res_data.SetMarkerColor(kBlack)
    res_data.SetLineColor(kBlack)
    res_data.SetFillColor(0)
    res_data.SetTitle("Dimuon mass resolution vs pT for %s tracks" % trackType)
    res_data.GetYaxis().SetTitle("Mass resolution at Z peak [GeV]")
    res_data.GetXaxis().SetTitle("p_{T} (#mu^{#pm}) [GeV]")
    res_data.GetYaxis().SetTitleOffset(1.2)
    res_data.GetYaxis().SetRangeUser(0., 6.)
    if trackType == "Outer":
        res_data.GetYaxis().SetRangeUser(1., 20.)
    res_data.GetXaxis().SetRangeUser(ptbins[0], ptbins[len(ptda)])
    res_data.Draw("AP E0")
    res_mc.SetMarkerStyle(22)
    res_mc.SetMarkerColor(kRed)
    res_mc.SetLineColor(kRed)
    res_mc.SetFillColor(0)
    res_mc.SetTitle("Dimuon mass resolution vs pT for %s tracks" % trackType)
    res_mc.GetYaxis().SetTitle("Mass resolution at Z peak [GeV]")
    res_mc.GetXaxis().SetTitle("p_{T} (#mu^{#pm}) [GeV]")
    res_mc.GetYaxis().SetTitleOffset(1.5)
    res_mc.Draw("P E0 SAME")
    if rapidity == "BB":
        leg = TLegend(0.25, 0.6, 0.50, 0.80, "both muons |#eta| < 1.2",
                      "brNDC")
    else:
        leg = TLegend(0.25, 0.6, 0.5, 0.8, "at least one muon |#eta| > 1.2",
                      "brNDC")
    if mcIsData:
        leg.AddEntry(res_data, "DATA 2017")
        leg.AddEntry(res_mc, "DATA 2016")
    elif dataIsMC:
        leg.AddEntry(res_data, "MC 2017")
        leg.AddEntry(res_mc, "MC 2016")
    else:
        leg.AddEntry(res_data, "DATA", "p")
        leg.AddEntry(res_mc, "Simulation")

    leg.SetTextFont(42)
    leg.SetBorderSize(0)
    leg.SetTextSize(.04)
    leg.Draw("SAME")
    latex = TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)
    latex.SetNDC(True)
    latexCMS = TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.055 / 0.7)
    latexCMS.SetNDC(True)
    latexCMSExtra = TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.03 / 0.7)
    latexCMSExtra.SetNDC(True)

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

    cmsExtra = "Preliminary"
    latexCMS.DrawLatex(0.78, 0.88, "CMS")
    yLabelPos = 0.84
    latexCMSExtra.DrawLatex(0.78, yLabelPos, "%s" % (cmsExtra))
    c2.cd()  # Go back to the main canvas before defining pad2
    pad2 = TPad("pad2", "pad2", 0, 0.1, 1, 0.30)
    pad2.SetTopMargin(0)
    pad2.SetBottomMargin(0.3)
    pad2.SetGrid()
    pad2.Draw()
    pad2.cd()
    pad2.SetTicks()
    ratio.SetMarkerColor(kBlue - 4)
    ratio.SetFillColor(kBlue - 4)
    ratio.SetTitle("")
    ratio.GetYaxis().SetTitle("Data/MC")
    if mcIsData:
        ratio.GetYaxis().SetTitle("Data 2017 / Data 2016")
    elif dataIsMC:
        ratio.GetYaxis().SetTitle("MC 2017 / MC 2016")
    ratio.GetXaxis().SetTitle("p_{T} (#mu^{#pm}) [GeV]")
    ratio.GetYaxis().SetRangeUser(0.5, 1.5)
    ratio.GetXaxis().SetRangeUser(ptbins[0], ptbins[len(ptda)])
    ratio.GetYaxis().SetTitleOffset(0.50)
    ratio.GetYaxis().SetTitleSize(0.14)
    ratio.GetYaxis().SetLabelSize(0.14)
    ratio.GetYaxis().SetNdivisions(506)
    ratio.GetXaxis().SetTitleSize(0.12)
    ratio.GetXaxis().SetTitleOffset(1.2)
    ratio.GetXaxis().SetLabelSize(0.20)
    ratio.Draw("A P E2")
    pad2.Update()
    line = TLine(ptbins[0], 1, ptbins[len(ptda)], 1)

    line.SetLineColor(kBlue + 1)
    line.SetLineWidth(2)
    line.Draw()
    saveas = "/MassResolutionVsPt_%s_%s" % (trackType, rapidity)
    c2.SaveAs(output + saveas + ".png")
    c2.SaveAs(output + saveas + ".pdf")
    c2.SaveAs(output + saveas + ".root")
    c2.SaveAs(output + saveas + ".C")
def makePlot(sfHist,ofHist,selection,plot,runRange,region,cmsExtra,combination,dyHist=None,edgeShape=False,edgeShapeMC=False,differentEdgePositions=False):

	colors = createMyColors()	

	hCanvas = TCanvas("hCanvas", "Distribution", 800,800)
	
	plotPad = ROOT.TPad("plotPad","plotPad",0,0.3,1,1)
	ratioPad = ROOT.TPad("ratioPad","ratioPad",0,0.,1,0.3)
	style = setTDRStyle()
	style.SetPadTopMargin(0.07)
	ROOT.gStyle.SetOptStat(0)
	plotPad.UseCurrentStyle()
	ratioPad.UseCurrentStyle()
	plotPad.Draw()	
	ratioPad.Draw()	
	plotPad.cd()

	yMax = sfHist.GetBinContent(sfHist.GetMaximumBin())
	
	if plot.yMax == 0:
		#~ yMax = yMax*2.15
		if edgeShape or edgeShapeMC or differentEdgePositions: 
			yMax = yMax*1.75 
		else:
			yMax = yMax*1.5 
						
	else: 
		yMax = plot.yMax
					
	
	plotPad.DrawFrame(plot.firstBin,0,plot.lastBin, yMax,"; %s ; %s" %(plot.xaxis,plot.yaxis))
	
	#set overflow bin
	#~ print sfHist.GetBinContent(sfHist.GetNbinsX()), sfHist.GetBinContent(sfHist.GetNbinsX()+1)
	#~ sfHist.SetBinContent(sfHist.GetNbinsX(),sfHist.GetBinContent(sfHist.GetNbinsX())+sfHist.GetBinContent(sfHist.GetNbinsX()+1))
	#~ sfHist.SetBinError(sfHist.GetNbinsX(),(sfHist.GetBinContent(sfHist.GetNbinsX())+sfHist.GetBinContent(sfHist.GetNbinsX()+1))**0.5)
	#~ ofHist.SetBinContent(ofHist.GetNbinsX(),ofHist.GetBinContent(ofHist.GetNbinsX())+ofHist.GetBinContent(ofHist.GetNbinsX()+1))
	#~ ofHist.SetBinError(ofHist.GetNbinsX(),(ofHist.GetBinContent(ofHist.GetNbinsX())+ofHist.GetBinContent(ofHist.GetNbinsX()+1))**0.5)

	
	bkgHist = ofHist.Clone("bkgHist")
	if dyHist is not None:
		bkgHist.Add(dyHist)
		
	
	sfHist.SetMarkerStyle(20)
	sfHist.SetLineColor(ROOT.kBlack)
	bkgHist.SetLineColor(ROOT.kBlue+3)
	bkgHist.SetLineWidth(2)
	
	dyHist.SetLineColor(ROOT.kGreen+2)
	dyHist.SetFillColor(ROOT.kGreen+2)
	#~ dyHist.SetFillStyle(3002)
	
	#~ dyOnlyHist = dyHist.Clone("dyOnlyHist")
	#~ dyOnlyHist.Scale(getattr(getattr(OnlyZPredictions,bSelection).SF,region).val / getattr(getattr(zPredictions,bSelection).SF,region).val)
	#~ 
	#~ rareBGHist = dyHist.Clone("rareBGHist")
	#~ rareBGHist.Scale(getattr(getattr(OtherPredictions,bSelection).SF,region).val / getattr(getattr(zPredictions,bSelection).SF,region).val)
	#~ 
	#~ rareBGHist.SetLineColor(ROOT.kViolet+2)
	#~ rareBGHist.SetFillColor(ROOT.kViolet+2)
	
	from ROOT import THStack
	
	#~ stack = THStack()
	#~ stack.Add(rareBGHist)	
	#~ stack.Add(dyOnlyHist)
	#~ 
	bkgHistForLegend = bkgHist.Clone("bkgHistForLegend")
	bkgHistForLegend.SetLineColor(ROOT.kBlue+3)
	bkgHistForLegend.SetFillColor(ROOT.kWhite)
	bkgHistForLegend.SetLineWidth(2)
	

	
	
	
		
	latex = ROOT.TLatex()
	latex.SetTextFont(42)
	latex.SetTextAlign(31)
	latex.SetTextSize(0.055)
	latex.SetLineWidth(2)
	latex.SetNDC(True)
	latexCMS = ROOT.TLatex()
	latexCMS.SetTextFont(61)
	latexCMS.SetTextSize(0.055)
	latexCMS.SetNDC(True)
	latexCMSExtra = ROOT.TLatex()
	latexCMSExtra.SetTextFont(52)
	latexCMSExtra.SetTextSize(0.03)
	latexCMSExtra.SetNDC(True) 
		
	latex.DrawLatex(0.93, 0.942, "%s fb^{-1} (13 TeV)"%runRange.printval)
	

	latexCMS.DrawLatex(0.19,0.86,"CMS")
	if "Simulation" in cmsExtra:
		yLabelPos = 0.81	
	else:
		yLabelPos = 0.84	

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





	
	if combination == "SF":
		rSFOFErr = getattr(rSFOF,region).err
	elif combination == "EE":
		rSFOFErr = getattr(rEEOF,region).err
	elif combination == "MM":
		rSFOFErr = getattr(rMMOF,region).err
	
	errGraph, histUp, histDown = getErrHist(plot,combination,region,ofHist,dyHist,rSFOFErr)
	errGraph.SetFillColor(myColors["MyBlueOverview"])
	errGraph.SetFillStyle(3001)
	#~ errGraph.SetLineColor(myColors["MyDarkBlue"])
	#~ errGraph.SetMarkerColor(myColors["MyDarkBlue"])
	

	if edgeShape:
		
		edgeFile = ROOT.TFile("edgeShape.root","READ")
		edgeHist = ROOT.TH1F()
		edgeHist = edgeFile.Get("edgeHist300__inv")
		
		
		edgeHist.Scale(1./edgeHist.Integral())
		
		edgeHist500 = edgeFile.Get("edgeHist500__inv")
		edgeHist500.Scale(1./edgeHist500.Integral())
		
		edgeHist700 = edgeFile.Get("edgeHist700__inv")
		edgeHist700.Scale(1./edgeHist700.Integral())

		
		edgeHist.Scale(342)
		edgeHist.Add(bkgHist.Clone())
		edgeHist.SetLineColor(ROOT.kRed)		
		edgeHist.SetLineWidth(2)	
		
		
		edgeHist500.Scale(484)
		edgeHist500.Add(bkgHist.Clone())
		edgeHist500.SetLineColor(ROOT.kRed)		
		edgeHist500.SetLineWidth(2)		
		edgeHist500.SetLineStyle(ROOT.kDashed)
		
		edgeHist700.Scale(654)
		edgeHist700.Add(bkgHist.Clone())
		edgeHist700.SetLineColor(ROOT.kRed)		
		edgeHist700.SetLineStyle(ROOT.kDotted)		
		edgeHist700.SetLineWidth(2)	
		
		for i in range(1,edgeHist.GetNbinsX()+1):
			if i >= edgeHist.GetXaxis().FindBin(70.01):
				edgeHist.SetBinContent(i,0)		
				edgeHist500.SetBinContent(i,0)		
				edgeHist700.SetBinContent(i,0)		

	if edgeShapeMC:
		
		signalPath = locations.signalDataSetPath
		
		denominatorFile = TFile("../SignalScan/T6bbllsleptonDenominatorHisto.root")
		denominatorHisto = TH2F(denominatorFile.Get("massScan"))
		
		cutsWithoutSignalScaleFactors = plot.cuts
		plot.cuts = "leptonFullSimScaleFactor1*leptonFullSimScaleFactor2*leptonFastSimScaleFactor1*leptonFastSimScaleFactor2*(%s)"%plot.cuts
		
		if "Central" in selection.name:
			EETriggerEff = 0.945
			EMuTriggerEff = 0.937
			MuMuTriggerEff = 0.929
			RSFOF = 1.032
		elif "Forward" in selection.name:
			EETriggerEff = 0.943
			EMuTriggerEff = 0.938
			MuMuTriggerEff = 0.916
			RSFOF = 1.092
		else:
			EETriggerEff = 0.949
			EMuTriggerEff = 0.921811
			MuMuTriggerEff = 0.929178
			RSFOF = 1.05

		EEHistSignal450, MMHistSignal450, EMHistSignal450 = getSignalMCHistograms(signalPath,plot,runRange,"T6bbllslepton_msbottom_450_mneutralino_175")
		
		denominator = denominatorHisto.GetBinContent(denominatorHisto.GetXaxis().FindBin(450),denominatorHisto.GetYaxis().FindBin(175))		
		xsection = getattr(sbottom_masses, "m_b_450").cross_section13TeV			
		scalingLumi = runRange.lumi*xsection/denominator
		
		EEHistSignal450.Scale(EETriggerEff * scalingLumi)
		MMHistSignal450.Scale(MuMuTriggerEff * scalingLumi)
		EMHistSignal450.Scale(EMuTriggerEff * scalingLumi * RSFOF)
		
		if combination == "SF":
			edgeHist450 = EEHistSignal450.Clone()
			edgeHist450.Add(MMHistSignal450.Clone())
			edgeHist450.Add(EMHistSignal450.Clone(),-1)
		if combination == "EE":
			edgeHist450 = EEHistSignal450.Clone()
			edgeHist450.Add(EMHistSignal450.Clone(),-0.5)
		if combination == "MM":
			edgeHist450 = MMHistSignal450.Clone()
			edgeHist450.Add(EMHistSignal450.Clone(),-0.5)
			
		for i in range(0,edgeHist450.GetNbinsX()):
			if edgeHist450.GetBinContent(i) < 0:
				edgeHist450.SetBinContent(i,0.)
				
		edgeHist450.Add(bkgHist.Clone())
		edgeHist450.SetLineColor(ROOT.kRed)
		edgeHist450.SetLineWidth(2)
		
		EEHistSignal550, MMHistSignal550, EMHistSignal550 = getSignalMCHistograms(signalPath,plot,runRange,"T6bbllslepton_msbottom_550_mneutralino_175")
		
		denominator = denominatorHisto.GetBinContent(denominatorHisto.GetXaxis().FindBin(550),denominatorHisto.GetYaxis().FindBin(175))		
		xsection = getattr(sbottom_masses, "m_b_550").cross_section13TeV			
		scalingLumi = runRange.lumi*xsection/denominator
		
		EEHistSignal550.Scale(EETriggerEff * scalingLumi)
		MMHistSignal550.Scale(MuMuTriggerEff * scalingLumi)
		EMHistSignal550.Scale(EMuTriggerEff * scalingLumi * RSFOF)
		
		if combination == "SF":
			edgeHist550 = EEHistSignal550.Clone()
			edgeHist550.Add(MMHistSignal550.Clone())
			edgeHist550.Add(EMHistSignal550.Clone(),-1)
		if combination == "EE":
			edgeHist550 = EEHistSignal550.Clone()
			edgeHist550.Add(EMHistSignal550.Clone(),-0.5)
		if combination == "MM":
			edgeHist550 = MMHistSignal550.Clone()
			edgeHist550.Add(EMHistSignal550.Clone(),-0.5)
			
		for i in range(0,edgeHist550.GetNbinsX()):
			if edgeHist550.GetBinContent(i) < 0:
				edgeHist550.SetBinContent(i,0.)
				
		edgeHist550.Add(bkgHist.Clone())
		edgeHist550.SetLineColor(ROOT.kRed)
		edgeHist550.SetLineWidth(2)
		edgeHist550.SetLineStyle(ROOT.kDashed)
		
		EEHistSignal650, MMHistSignal650, EMHistSignal650 = getSignalMCHistograms(signalPath,plot,runRange,"T6bbllslepton_msbottom_650_mneutralino_175")
		
		denominator = denominatorHisto.GetBinContent(denominatorHisto.GetXaxis().FindBin(650),denominatorHisto.GetYaxis().FindBin(175))		
		xsection = getattr(sbottom_masses, "m_b_650").cross_section13TeV			
		scalingLumi = runRange.lumi*xsection/denominator
		
		EEHistSignal650.Scale(EETriggerEff * scalingLumi)
		MMHistSignal650.Scale(MuMuTriggerEff * scalingLumi)
		EMHistSignal650.Scale(EMuTriggerEff * scalingLumi * RSFOF)
		
		if combination == "SF":
			edgeHist650 = EEHistSignal650.Clone()
			edgeHist650.Add(MMHistSignal650.Clone())
			edgeHist650.Add(EMHistSignal650.Clone(),-1)
		if combination == "EE":
			edgeHist650 = EEHistSignal650.Clone()
			edgeHist650.Add(EMHistSignal650.Clone(),-0.5)
		if combination == "MM":
			edgeHist650 = MMHistSignal650.Clone()
			edgeHist650.Add(EMHistSignal650.Clone(),-0.5)
			
		for i in range(0,edgeHist650.GetNbinsX()):
			if edgeHist650.GetBinContent(i) < 0:
				edgeHist650.SetBinContent(i,0.)
				
		edgeHist650.Add(bkgHist.Clone())
		edgeHist650.SetLineColor(ROOT.kRed)
		edgeHist650.SetLineWidth(2)
		edgeHist650.SetLineStyle(ROOT.kDotted)
		
		plot.cuts = cutsWithoutSignalScaleFactors
			
	if differentEdgePositions:
		
		signalPath = locations.signalDataSetPath
		
		denominatorFile = TFile("../SignalScan/T6bbllsleptonDenominatorHisto.root")
		denominatorHisto = TH2F(denominatorFile.Get("massScan"))
		
		cutsWithoutSignalScaleFactors = plot.cuts
		plot.cuts = "leptonFullSimScaleFactor1*leptonFullSimScaleFactor2*leptonFastSimScaleFactor1*leptonFastSimScaleFactor2*(%s)"%plot.cuts
		
		if "Central" in selection.name:
			EETriggerEff = 0.945
			EMuTriggerEff = 0.937
			MuMuTriggerEff = 0.929
			RSFOF = 1.032
		elif "Forward" in selection.name:
			EETriggerEff = 0.943
			EMuTriggerEff = 0.938
			MuMuTriggerEff = 0.916
			RSFOF = 1.092
		else:
			EETriggerEff = 0.949
			EMuTriggerEff = 0.921811
			MuMuTriggerEff = 0.929178
			RSFOF = 1.05

		EEHistSignal75, MMHistSignal75, EMHistSignal75 = getSignalMCHistograms(signalPath,plot,runRange,"T6bbllslepton_msbottom_500_mneutralino_175")
		
		denominator = denominatorHisto.GetBinContent(denominatorHisto.GetXaxis().FindBin(500),denominatorHisto.GetYaxis().FindBin(175))		
		xsection = getattr(sbottom_masses, "m_b_500").cross_section13TeV			
		scalingLumi = runRange.lumi*xsection/denominator
		
		EEHistSignal75.Scale(EETriggerEff * scalingLumi)
		MMHistSignal75.Scale(MuMuTriggerEff * scalingLumi)
		EMHistSignal75.Scale(EMuTriggerEff * scalingLumi * RSFOF)
		
		if combination == "SF":
			edgeHist75 = EEHistSignal75.Clone()
			edgeHist75.Add(MMHistSignal75.Clone())
			edgeHist75.Add(EMHistSignal75.Clone(),-1)
		if combination == "EE":
			edgeHist75 = EEHistSignal75.Clone()
			edgeHist75.Add(EMHistSignal75.Clone(),-0.5)
		if combination == "MM":
			edgeHist75 = MMHistSignal75.Clone()
			edgeHist75.Add(EMHistSignal75.Clone(),-0.5)
			
		for i in range(0,edgeHist75.GetNbinsX()):
			if edgeHist75.GetBinContent(i) < 0:
				edgeHist75.SetBinContent(i,0.)
				
		edgeHist75.Add(bkgHist.Clone())
		edgeHist75.SetLineColor(ROOT.kRed)
		edgeHist75.SetLineWidth(2)
		
		EEHistSignal125, MMHistSignal125, EMHistSignal125 = getSignalMCHistograms(signalPath,plot,runRange,"T6bbllslepton_msbottom_500_mneutralino_225")
		
		denominator = denominatorHisto.GetBinContent(denominatorHisto.GetXaxis().FindBin(500),denominatorHisto.GetYaxis().FindBin(225))		
		xsection = getattr(sbottom_masses, "m_b_500").cross_section13TeV			
		scalingLumi = runRange.lumi*xsection/denominator
		
		EEHistSignal125.Scale(EETriggerEff * scalingLumi)
		MMHistSignal125.Scale(MuMuTriggerEff * scalingLumi)
		EMHistSignal125.Scale(EMuTriggerEff * scalingLumi * RSFOF)
		
		if combination == "SF":
			edgeHist125 = EEHistSignal125.Clone()
			edgeHist125.Add(MMHistSignal125.Clone())
			edgeHist125.Add(EMHistSignal125.Clone(),-1)
		if combination == "EE":
			edgeHist125 = EEHistSignal125.Clone()
			edgeHist125.Add(EMHistSignal125.Clone(),-0.5)
		if combination == "MM":
			edgeHist125 = MMHistSignal125.Clone()
			edgeHist125.Add(EMHistSignal125.Clone(),-0.5)
			
		for i in range(0,edgeHist125.GetNbinsX()):
			if edgeHist125.GetBinContent(i) < 0:
				edgeHist125.SetBinContent(i,0.)
				
		edgeHist125.Add(bkgHist.Clone())
		edgeHist125.SetLineColor(ROOT.kRed)
		edgeHist125.SetLineWidth(2)
		edgeHist125.SetLineStyle(ROOT.kDashed)
		
		EEHistSignal200, MMHistSignal200, EMHistSignal200 = getSignalMCHistograms(signalPath,plot,runRange,"T6bbllslepton_msbottom_500_mneutralino_300")
		
		denominator = denominatorHisto.GetBinContent(denominatorHisto.GetXaxis().FindBin(500),denominatorHisto.GetYaxis().FindBin(300))		
		xsection = getattr(sbottom_masses, "m_b_500").cross_section13TeV			
		scalingLumi = runRange.lumi*xsection/denominator
		
		EEHistSignal200.Scale(EETriggerEff * scalingLumi)
		MMHistSignal200.Scale(MuMuTriggerEff * scalingLumi)
		EMHistSignal200.Scale(EMuTriggerEff * scalingLumi * RSFOF)
		
		if combination == "SF":
			edgeHist200 = EEHistSignal200.Clone()
			edgeHist200.Add(MMHistSignal200.Clone())
			edgeHist200.Add(EMHistSignal200.Clone(),-1)
		if combination == "EE":
			edgeHist200 = EEHistSignal200.Clone()
			edgeHist200.Add(EMHistSignal200.Clone(),-0.5)
		if combination == "MM":
			edgeHist200 = MMHistSignal200.Clone()
			edgeHist200.Add(EMHistSignal200.Clone(),-0.5)
			
		for i in range(0,edgeHist200.GetNbinsX()):
			if edgeHist200.GetBinContent(i) < 0:
				edgeHist200.SetBinContent(i,0.)
				
		edgeHist200.Add(bkgHist.Clone())
		edgeHist200.SetLineColor(ROOT.kRed)
		edgeHist200.SetLineWidth(2)
		edgeHist200.SetLineStyle(ROOT.kDotted)
		
		plot.cuts = cutsWithoutSignalScaleFactors
				


	#~ lines = getLines(0, sfHist.GetBinContent(sfHist.GetMaximumBin())+10,xPos=[mllBins.lowMass.high,mllBins.onZ.low,mllBins.onZ.high, mllBins.highMass.low ])
	#~ for line in lines:
		#~ line.Draw()
	if edgeShape or edgeShapeMC:
		leg = TLegend(0.55, 0.4, 0.92, 0.91,"","brNDC")
	elif differentEdgePositions:
		leg = TLegend(0.55, 0.4, 0.95, 0.92,"","brNDC")
	else:
		leg = TLegend(0.6, 0.5, 0.95, 0.92,"","brNDC")
		
	leg.SetFillColor(10)
	leg.SetLineColor(10)
	leg.SetShadowColor(0)
	leg.SetBorderSize(1)
	from ROOT import TH1F,kWhite
	legendHistDing = TH1F()
	legendHistDing.SetFillColor(kWhite)
	if region == "inclusive":
		leg.AddEntry(legendHistDing,"Inclusive signal region","h")
	elif region == "central":
		leg.AddEntry(legendHistDing,"Legacy signal region","h")
	elif region == "forward":
		leg.AddEntry(legendHistDing,"Forward signal region","h")
	leg.AddEntry(sfHist,"Data","pe1")
	#~ leg.AddEntry(bkgHist, "Total background","l")
	leg.AddEntry(bkgHistForLegend, "Flavor symmetric","f")
	leg.AddEntry(dyHist,"Drell-Yan", "f")
	#~ leg.AddEntry(dyOnlyHist,"Z+jets", "f")
	#~ leg.AddEntry(rareBGHist,"Other SM", "f")
	leg.AddEntry(errGraph,"Total uncertainty", "f")	
	
	if edgeShape:
		leg.AddEntry(legendHistDing,"Scaled 8 TeV signal fit:", "h")	
		leg.AddEntry(edgeHist,"m_{#tilde{b}} = 300 GeV hypothesis", "l")	
		leg.AddEntry(edgeHist500,"m_{#tilde{b}} = 500 GeV hypothesis", "l")	
		leg.AddEntry(edgeHist700,"m_{#tilde{b}} = 700 GeV hypothesis", "l")	
	
	if edgeShapeMC:
		leg.AddEntry(legendHistDing,"Slepton signal model", "h")
		leg.AddEntry(edgeHist450,"m_{#tilde{b}} = 450 GeV, m_{#tilde{#chi}_{2}^{0}} = 175 GeV", "l")	
		leg.AddEntry(edgeHist550,"m_{#tilde{b}} = 550 GeV, m_{#tilde{#chi}_{2}^{0}} = 175 GeV", "l")	
		leg.AddEntry(edgeHist650,"m_{#tilde{b}} = 650 GeV, m_{#tilde{#chi}_{2}^{0}} = 175 GeV", "l")	
	
	if differentEdgePositions:
		leg.AddEntry(legendHistDing,"Slepton signal model, m_{#tilde{b}} = 500 GeV", "h")
		leg.AddEntry(edgeHist75,"75 GeV edge position", "l")	
		leg.AddEntry(edgeHist125,"125 GeV edge position", "l")	
		leg.AddEntry(edgeHist200,"200 GeV edge position", "l")	
	
	leg.Draw("same")
	
	errGraph.Draw("SAME02")
	
	if edgeShape:		
		edgeHist.Draw("samehist")	
		edgeHist500.Draw("samehist")	
		edgeHist700.Draw("samehist")
		
	if edgeShapeMC:
		edgeHist450.Draw("samehist")
		edgeHist550.Draw("samehist")
		edgeHist650.Draw("samehist")
		
	if differentEdgePositions:
		edgeHist75.Draw("samehist")
		edgeHist125.Draw("samehist")
		edgeHist200.Draw("samehist")
	
	
	bkgHist.Draw("samehist")	
	
	
	
	dyHist.Draw("samehist")	
	#~ stack.Draw("samehist")	
	sfHist.Draw("samepe1")






		
	plotPad.RedrawAxis()	


	ratioPad.cd()
		
	ratioGraphs =  ratios.RatioGraph(sfHist,bkgHist, xMin=plot.firstBin, xMax=plot.lastBin,title="#frac{Data}{Prediction}  ",yMin=0.0,yMax=2,ndivisions=10,color=ROOT.kBlack,adaptiveBinning=1000)
	ratioGraphs.addErrorByHistograms( "rSFOF", histUp, histDown,color= myColors["MyBlue"],fillStyle=3001)			

	ratioGraphs.draw(ROOT.gPad,True,False,True,chi2Pos=0.8)

	#~ leg2 = TLegend(0.175, 0.78, 0.475, 0.9,"","brNDC")
	#~ leg2.SetFillColor(10)
	#~ leg2.SetLineColor(10)
	#~ leg2.SetShadowColor(0)
	#~ leg2.SetBorderSize(1)
	#~ leg2.AddEntry(errGraph,"Systematic uncert.", "f")	
	#~ leg2.Draw("same")
	
	ROOT.gPad.RedrawAxis()
	plotPad.RedrawAxis()
	ratioPad.RedrawAxis()

	if edgeShape:
		hCanvas.Print("fig/mllResult_%s_%s_%s_edgeShape.pdf"%(selection.name,runRange.label,combination))	
	elif edgeShapeMC:
		hCanvas.Print("fig/mllResult_%s_%s_%s_edgeShapeMC.pdf"%(selection.name,runRange.label,combination))	
	elif differentEdgePositions:
		hCanvas.Print("fig/mllResult_%s_%s_%s_edgeShapeMC_differentEdgePositions.pdf"%(selection.name,runRange.label,combination))	
	else:
		hCanvas.Print("fig/mllResult_%s_%s_%s.pdf"%(selection.name,runRange.label,combination))	
Beispiel #31
0
def DrawBrazil(diagonal=175, doData=False, pname='limits', year=2018):
    lumi = GetLumi(year)
    import numpy as np
    # 'mstop','mlsp','sm2','sm1','central','sp1','sp2', 'data'
    d = GetDic(pname + '.p', diagonal)
    x = np.array(d['mstop'])
    e = np.array(d['exp'])
    y1max = np.array(d['s+1'])
    y2max = np.array(d['s+2'])
    y1min = np.array(d['s-1'])
    y2min = np.array(d['s-2'])
    # observed
    if (doData): o = np.array(d['obs'])
    else: o = np.array(d['exp'])

    c1 = TCanvas("c1", "CL", 10, 10, 800, 600)
    #c1.SetGrid();

    ymax = 4.5
    ymin = 0.0
    if (diagonal == 'down' or diagonal == 'Down' or diagonal == 'DOWN'):
        ymax = 3.1
        ymin = 0.30
    elif (diagonal == 'up' or diagonal == 'Up' or diagonal == 'UP'):
        ymax = 2.5
        ymin = 0.15

    #c1.DrawFrame(min(x)-2,min(d['sp2']+d['sm2'])-0.2,max(x)+2,max(d['sp2']+d['sm2'])+0.2);
    c1.DrawFrame(min(x), ymin, max(x), ymax)

    n = len(e)
    gr1min = TGraph(n, x, y1min)
    gr1max = TGraph(n, x, y1max)
    gr2min = TGraph(n, x, y2min)
    gr2max = TGraph(n, x, y2max)
    gro = TGraph(n, x, o)
    gre = TGraph(n, x, e)
    gh = TGraph(n, x, np.linspace(0.999, 1, n))
    gr1shade = TGraph(2 * n)
    gr2shade = TGraph(2 * n)

    #color1shade = 3; color2shade = 5;
    color1shade = kOrange
    color2shade = kGreen + 1
    for i in range(n):
        gr1shade.SetPoint(i, x[i], y1max[i] * scalefact)
        gr1shade.SetPoint(n + i, x[n - i - 1], y1min[n - i - 1] * scalefact)
        gr2shade.SetPoint(i, x[i], y2max[i] * scalefact)
        gr2shade.SetPoint(n + i, x[n - i - 1], y2min[n - i - 1] * scalefact)
        gre.SetPoint(i, x[i], e[i] * scalefact)
        gh.SetPoint(i, x[i], np.linspace(0.999, 1, n)[i] * scalefact)
        gro.SetPoint(i, x[i], o[i] * scalefact if doData else e[i] * scalefact)

    gr2shade.SetFillColor(color2shade)
    gr2shade.Draw("f")
    gr1shade.SetFillColor(color1shade)
    gr1shade.Draw("f")
    gh.SetLineWidth(2)
    gh.SetMarkerStyle(0)
    gh.SetLineColor(46)
    gh.SetLineStyle(2)
    gh.Draw("LP")
    gro.SetLineWidth(2)
    gro.SetMarkerStyle(20)
    gro.SetMarkerSize(0.7)
    gro.SetLineColor(1)
    if doData: gro.Draw("LP")
    gre.SetLineWidth(2)
    gre.SetMarkerStyle(0)
    gre.SetLineColor(1)
    gre.SetLineStyle(6)
    gre.Draw("LP")

    gre.SetTitle("Expected")
    gro.SetTitle("Observed")
    gr1shade.SetTitle("Expected 1#sigma")
    gr2shade.SetTitle("Expected 2#sigma")

    leg = TLegend(.1, .65, .4, .9)
    leg.AddEntry(gro)
    leg.AddEntry(gre)
    leg.AddEntry(gr1shade, '', 'f')
    leg.AddEntry(gr2shade, '', 'f')
    leg.SetFillColor(0)
    leg.Draw("same")

    gre.SetFillColor(0)
    gro.SetFillColor(0)
    gr1shade.SetLineColor(color1shade)
    gr2shade.SetLineColor(color2shade)

    tit = "m_{#tilde{t}_{1}} - m_{#tilde{#chi}_{1}^{0}} = "
    dm = "0"
    ymax = 4.1
    ymin = 0.3
    if (diagonal == 'down' or diagonal == 'Down' or diagonal == 'DOWN'):
        tit += "182.5 GeV"  #" + 7.5 GeV"
        dm = "m7p5"
        ymax = 2.2
        ymin = 0.15

    elif (diagonal == 'up' or diagonal == 'Up' or diagonal == 'UP'):
        tit += "167.5 GeV"  #" - 7.5 GeV"
        dm = "7p5"
        ymax = 3.3
        ymin = 0.30
    else:
        tit += "175 GeV"
    Title = TLatex()
    Title.SetTextSize(0.060)
    Title.DrawLatexNDC(.42, .84, tit)
    Xaxis = TLatex()
    Xaxis.SetTextFont(42)
    Xaxis.DrawLatexNDC(0.8, 0.03, "m_{#tilde{t}_{1}} (GeV)")
    Yaxis = TLatex()
    Yaxis.SetTextFont(42)
    Yaxis.SetTextAngle(90)
    Yaxis.DrawLatexNDC(0.05, 0.15, "95% CL limit on signal strength")
    textCMS = TLatex()
    textCMS.SetTextSize(0.06)
    textCMS.SetTextSizePixels(22)
    textCMS.SetTextAlign(12)
    textCMS.DrawLatexNDC(.12, .93, "CMS")
    textLumi = TLatex()
    textLumi.SetTextFont(42)
    textLumi.SetTextSize(0.06)
    textLumi.SetTextSizePixels(22)
    textLumi.DrawLatexNDC(.58, .91, "%1.1f fb^{-1} (13 TeV)" % (lumi))  #35.9

    #name = "brazil_%i"%diagonal
    name = "brazil_%s" % (pname)
    for form in ['pdf', 'png']:
        c1.Print(outputdir + name + '.%s' % form)