Exemplo n.º 1
0
def compareFiles(plot, filenames, treename, diff):
    tree1 = readTree(filenames[0], treename)
    tree2 = readTree(filenames[1], treename)

    if diff:
        cut1, cut2 = getEventNumberDiff(tree1, tree2)
        tree1 = getTreeFriendsWithBooleanVariable(tree1, cut1)
        tree2 = getTreeFriendsWithBooleanVariable(tree2, cut2)
        h1 = createHistoFromTree(tree1, plot, "x")
        h2 = createHistoFromTree(tree2, plot, "x")

    else:

        h1 = getHisto(tree1, plot, weight="1")
        h2 = getHisto(tree2, plot, weight="1")
        mini = min(h1.GetBinLowEdge(1), h2.GetBinLowEdge(1))
        maxi = max(h2.GetBinLowEdge(h2.GetNbinsX() + 2),
                   h1.GetBinLowEdge(h1.GetNbinsX() + 2))
        h1 = getHisto(tree1, plot, weight="1", firstBin=mini, lastBin=maxi)
        h2 = getHisto(tree2, plot, weight="1", firstBin=mini, lastBin=maxi)

    h2.SetLineColor(2)
    mh = Multihisto()
    name1 = getVersion(filenames[0])
    name2 = getVersion(filenames[1])
    mh.addHisto(h1, name1, draw="hist e")
    mh.addHisto(h2, name2, draw="hist e")
    mh.Draw()
    from myRatio import Ratio
    r = Ratio("%s/%s" % (name1, name2), h1, h2)
    r.draw()

    plot = "test"
    ROOT.gPad.GetCanvas().SaveAs("compareFiles_%s.pdf" % plot)
Exemplo n.º 2
0
def drawGenComposition2Samples(treeName, sample1, sample2):

    histos = {
        "W": sample1.plot(treeName, cut="1"),
        "W (gen #gamma)": sample1.plot(treeName, cut="photons[0].isGen(0)"),
        "W (gen e)": sample1.plot(treeName, cut="photons[0].isGen(1)"),
        "W (gen had)": sample1.plot(treeName, cut="photons[0].isGen(3)"),
        "#gammaW": sample2.plot(treeName, cut="1"),
        "#gammaW (gen #gamma)": sample2.plot(treeName,
                                             cut="photons[0].isGen(0)"),
        "#gammaW (gen e)": sample2.plot(treeName, cut="photons[0].isGen(1)"),
        "#gammaW (gen had)": sample2.plot(treeName, cut="photons[0].isGen(2)"),
    }

    mh = Multihisto()
    for name, h in histos.iteritems():
        if "(gen #gamma)" in name:
            h.SetLineStyle(2)
        if "(gen e)" in name:
            h.SetLineStyle(3)
        if "(gen had)" in name:
            h.SetLineStyle(4)

        mh.addHisto(h, name)
    can = ROOT.TCanvas()
    can.cd()
    mh.Draw()
    info = PlotCaption(treeName=treeName)
    info.Draw()
    allDatasetAbbr = sample1.datasetAbbr + sample2.datasetAbbr
    plot = "met"
    SaveAs(can,
           "composition2samples_%s_%s_%s" % (treeName, plot, allDatasetAbbr))
Exemplo n.º 3
0
def drawGenComposition2Samples( treeName, sample1, sample2 ):

	histos = {
			"W": sample1.plot(treeName, cut="1"),
			"W (gen #gamma)": sample1.plot(treeName, cut="photons[0].isGen(0)"),
			"W (gen e)": sample1.plot(treeName, cut="photons[0].isGen(1)"),
			"W (gen had)": sample1.plot(treeName, cut="photons[0].isGen(3)"),
			"#gammaW": sample2.plot(treeName, cut="1"),
			"#gammaW (gen #gamma)": sample2.plot(treeName, cut="photons[0].isGen(0)"),
			"#gammaW (gen e)": sample2.plot(treeName, cut="photons[0].isGen(1)"),
			"#gammaW (gen had)": sample2.plot(treeName, cut="photons[0].isGen(2)"),
			}

	mh = Multihisto()
	for name, h in histos.iteritems():
		if "(gen #gamma)" in name:
			h.SetLineStyle(2)
		if "(gen e)" in name:
			h.SetLineStyle(3)
		if "(gen had)" in name:
			h.SetLineStyle(4)

		mh.addHisto( h, name )
	can = ROOT.TCanvas()
	can.cd()
	mh.Draw()
	info = PlotCaption(treeName=treeName)
	info.Draw()
	allDatasetAbbr = sample1.datasetAbbr+sample2.datasetAbbr
	plot = "met"
	SaveAs( can, "composition2samples_%s_%s_%s"%(treeName, plot,allDatasetAbbr) )
Exemplo n.º 4
0
def compareFiles( plot, filenames, treename, diff ):
	tree1 = readTree( filenames[0], treename )
	tree2 = readTree( filenames[1], treename )

	if diff:
		cut1, cut2 = getEventNumberDiff( tree1, tree2 )
		tree1 = getTreeFriendsWithBooleanVariable( tree1, cut1)
		tree2 = getTreeFriendsWithBooleanVariable( tree2, cut2)
		h1 = createHistoFromTree( tree1, plot, "x" )
		h2 = createHistoFromTree( tree2, plot, "x" )

	else:

		h1 = getHisto( tree1, plot, weight="1" )
		h2 = getHisto( tree2, plot, weight="1" )
		mini = min(h1.GetBinLowEdge(1), h2.GetBinLowEdge(1))
		maxi = max(h2.GetBinLowEdge(h2.GetNbinsX()+2), h1.GetBinLowEdge(h1.GetNbinsX()+2))
		h1 = getHisto( tree1, plot, weight="1", firstBin=mini, lastBin=maxi  )
		h2 = getHisto( tree2, plot, weight="1", firstBin=mini, lastBin=maxi )


	h2.SetLineColor(2)
	mh = Multihisto()
	name1 = getVersion(filenames[0])
	name2 = getVersion(filenames[1])
	mh.addHisto( h1, name1, draw="hist e" )
	mh.addHisto( h2, name2, draw="hist e" )
	mh.Draw()
	from myRatio import Ratio
	r = Ratio( "%s/%s"%(name1,name2), h1, h2 )
	r.draw()

	plot ="test"
	ROOT.gPad.GetCanvas().SaveAs( "compareFiles_%s.pdf"%plot )
Exemplo n.º 5
0
def closure( filenames, plot, treename="photonJetTree" ):
	commonCut = "[email protected]() && [email protected]()"
	#commonCut = "1"
	leptonPtCut = 15 # only larger than 15 make sense here, since this is the reprocessing cut
	commonCut = "([email protected]() || Max$(electrons.pt)<{0}) && ([email protected]() || Max$(muons.pt)<{0})".format(leptonPtCut)

	totalHist = getHists( filenames, plot, cut=commonCut, treeName=treename )
	gGenHist = getHists( filenames, plot, cut="photons[0].isGen(0) && "+commonCut, treeName=treename )
	eGenHist = getHists( filenames, plot, cut="photons[0].isGen(1) && "+commonCut, treeName=treename )
	gGenHist.SetLineColor(2)
	eGenHist.SetLineColor(3)

	gDatasetAbbrs = [getDatasetAbbr(f) for f in filenames ]
	gDatasetAbbrs = mergeDatasetAbbr( gDatasetAbbrs )

	multihisto = Multihisto()
	multihisto.leg.SetHeader( "/".join([ datasetToLatex(x) for x in gDatasetAbbrs]) )
	multihisto.addHisto( totalHist, "Simulation", draw="e0 hist" )
	multihisto.addHisto( gGenHist, "gen #gamma", toStack=True, draw="e0 hist" )
	multihisto.addHisto( eGenHist, "gen e", toStack=True, draw="e0 hist" )

	infoText = ROOT.TLatex(0.03,.96, "CMS Private Work - 8TeV #geq1#gamma,#geq2jets" )
	infoText.SetNDC()

	can = ROOT.TCanvas()
	can.cd()
	multihisto.Draw()
	infoText.Draw()
	r = Ratio( "Sim./Pred.", totalHist, multihisto.stack.GetStack().Last() )
	r.draw(0,2)
	SaveAs( can, "genMatches_%s_%s"%(getSaveNameFromDatasets(filenames), plot))

	ROOT.SetOwnership( can, False )
	del can
def split2Din1DMultihist( h2D, useYaxis, uFlow, oFlow ):
	"""Creates many TH1 out of one TH2 and put them in a Multihisto.

	h2D: TH2 (rebin appropriate if necessary )
	useYaxis: The TH2 will be splitted in different values of Y.
		If false, the X axis will be used (bool).
	uFlow: Take the underFlow into account (bool).
	oFlow: Take the overFlow into account (bool).
	"""
	mh = Multihisto()
	mh.setMinimum(1e-8)
	style = ROOT.gROOT.GetStyle("tdrStyle") # for nice color gradient

	if useYaxis:
		axis = h2D.GetYaxis()
	else:
		axis = h2D.GetXaxis()

	variable = axis.GetTitle()
	nBins = axis.GetNbins()

	binRange = range( nBins + 2 )
	if not uFlow:
		binRange = binRange[1:]
	if not oFlow:
		binRange = binRange[:-1]

	for iColor, iBin in enumerate(binRange):
		if useYaxis:
			h = h2D.ProjectionX( "_px%s"%iBin, iBin, iBin )
		else:
			h = h2D.ProjectionY( "_px%s"%iBin, iBin, iBin )
		lowEdge = axis.GetBinLowEdge( iBin )
		upEdge = axis.GetBinUpEdge( iBin )

		if iBin == 0:
			title = "       %s < %s"%( variable, upEdge )
		elif iBin != nBins+1:
			title = "%s #leq %s < %s"%( lowEdge, variable, upEdge )
		else:
			title = "%s #leq %s"%( lowEdge, variable )

		color = style.GetColorPalette( int( 1.*iColor/(len(binRange)-1)*(style.GetNumberOfColors()-1) ) )
		h.SetLineColor( color )
		h.SetMarkerColor( h.GetLineColor() )
		h.SetMarkerSize(0)
		h.GetXaxis().SetTitle( h2D.GetXaxis().GetTitle() )
		mh.addHisto( h, title,draw="e0" )

	return mh
Exemplo n.º 7
0
def drawMCStack(treeName="photonTree"):
    mh = Multihisto()
    mh.orderByIntegral = False

    datasetsToStack = [gz, tt, wjets, qcd, gjets]

    mh = fillMh(mh, datasetsToStack, treeName)

    can = ROOT.TCanvas()
    can.cd()
    mh.Draw()
    info = PlotCaption(treeName=treeName)
    info.Draw()
    allDatasetAbbr = ''.join([x.datasetAbbr for x in datasetsToStack])
    plot = "met"
    SaveAs(can, "stackedHisto_%s_%s_%s" % (treeName, plot, allDatasetAbbr))
Exemplo n.º 8
0
def drawMCStack( treeName="photonTree" ):
	mh = Multihisto()
	mh.orderByIntegral = False

	datasetsToStack = [gz,tt,wjets,qcd,gjets]

	mh = fillMh( mh, datasetsToStack, treeName )

	can = ROOT.TCanvas()
	can.cd()
	mh.Draw()
	info = PlotCaption(treeName=treeName)
	info.Draw()
	allDatasetAbbr = ''.join([x.datasetAbbr for x in datasetsToStack ])
	plot = "met"
	SaveAs( can, "stackedHisto_%s_%s_%s"%(treeName, plot,allDatasetAbbr) )
Exemplo n.º 9
0
def drawPileUpHistos(saveTex=False):

    inputHistPath = "../TreeWriter/pileUpReweighting/"

    data = readHisto(inputHistPath + "nTrueVertexData.root", "pileup")
    data.SetLineColor(1)
    data.SetMarkerColor(1)
    data.SetMarkerStyle(20)
    data.Sumw2()
    if saveTex:
        data.SetMarkerSize(.8)
    else:
        data.SetMarkerSize(1.2)

    mc = readHisto(inputHistPath + "nTrueVertexMC.root", "pileupS10")
    mc.SetLineColor(2)
    mc.SetMarkerColor(2)

    for h in [mc, data]:
        h.Scale(1. / h.Integral())
        h.SetTitle(";Number of Pile-up Events;Normalized Entries")
        if saveTex:
            h.SetLineWidth(2)
            h.SetTitleSize(0.06311227345609463, "yx")
            h.SetLabelSize(0.06311227345609463, "yx")

    muhist = Multihisto()
    muhist.addHisto(data, "Data", draw="ep")
    muhist.addHisto(mc, "Simulation", draw="hist")
    muhist.setMinimum(0)

    if saveTex:
        muhist.leg.SetTextSize(0.063112267888)
        texStyle()

    pc1 = ROOT.TLatex(0, .96, "CMS Private Work")
    pc2 = ROOT.TLatex(.76, .96, "\SI{19.8}{fb^{-1}} #sqrt{s}=\SI{8}{TeV}")

    masterPath = "~/master/documents/thesis/plots/"
    can = ROOT.TCanvas("", "", 2000, 1000)
    can.cd()
    can.SetLogy(0)
    muhist.Draw()
    for pc in [pc1, pc2]:
        pc.SetNDC()
        if saveTex:
            pc.SetTextSize(0.06311227345609463)
        pc.Draw()

    ending = 'tex' if saveTex else 'pdf'

    ROOT.gPad.SaveAs(masterPath + "puDistribution.%s" % ending)
Exemplo n.º 10
0
def drawGenComposition( treeName, sample ):
	mh = Multihisto()
	mh.addHisto( sample.plot(treeName, cut="photons[0].isGen(0)",color=2), "gen #gamma" )
	mh.addHisto( sample.plot(treeName, cut="photons[0].isGen(1)",color=3), "gen e" )
	mh.addHisto( sample.plot(treeName, cut="photons[0].isGen(2)",color=4), "gen hadron" )
	mh.addHisto( sample.plot(treeName, cut="1",color=1), "inclusive" )
	can = ROOT.TCanvas()
	can.cd()
	mh.Draw()
	info = PlotCaption(treeName=treeName)
	info.Draw()
	allDatasetAbbr = sample.datasetAbbr
	plot = "met"
	SaveAs( can, "composition_%s_%s_%s"%(treeName, plot,allDatasetAbbr) )
Exemplo n.º 11
0
def zGammaMixture(plot="met"):
    cut = "1"

    nunuTree = readTree("slimZGammaNuNu_V03.18_tree.root", "photonTree")
    zIncTree = readTree("slimZGamma_V03.18_tree.root", "photonTree")

    nBins = range(80, 500,
                  10) if plot == "photons[0].pt" else readAxisConf(plot)[2]

    h_nunu = getHisto(nunuTree,
                      plot,
                      cut + "&&photons[0].pt>=130",
                      nBins=nBins,
                      color=2)
    h_zInc = getHisto(zIncTree,
                      plot,
                      cut + "&&photons[0].pt<130",
                      nBins=nBins,
                      color=4)

    mh = Multihisto()

    mh.addHisto(h_nunu,
                "#gammaZ#rightarrow#gamma#nu#nu(p_{T}#geq130GeV)",
                draw="e",
                toStack=True)
    mh.addHisto(h_zInc, "#gammaZ(p_{T}<130GeV)", draw="e", toStack=True)
    mh.Draw()

    if plot == "photons[0].pt":
        l = ROOT.TLine(130, 0, 130, 1)
        l.Draw()

    SavePad("inclusiveAndIsrSample_%s" % plot)
Exemplo n.º 12
0
def drawClosure(filenames,
                predFilenames,
                plot,
                commonCut,
                infoText,
                additionalLabel="",
                modifyEmptyBins=True):
    infoText = ROOT.TLatex(
        0, .96,
        "CMS Private Work 19.7fb^{-1} #sqrt{s}=8TeV #geq1#gamma,#geq2jets")
    infoText.SetNDC()
    infoText.SetTextSize(0.045)

    gHist = getHists(filenames, plot, commonCut)
    fHist, sysHist = predictionHistos(predFilenames, plot, commonCut,
                                      modifyEmptyBins)
    fHist.SetMarkerSize(0)
    sysHist.SetFillStyle(3254)
    sysHist.SetFillColor(sysHist.GetLineColor())
    sysHist.SetLineColor(0)

    signalAbbrs = mergeDatasetAbbr([getDatasetAbbr(x) for x in filenames])

    muhisto = Multihisto()
    muhisto.leg.SetHeader(",".join([datasetToLatex(x) for x in signalAbbrs]))
    muhisto.addHisto(gHist, "Simulation", draw="")
    muhisto.addHisto(fHist, "Prediction", draw="hist e")
    muhisto.addHisto(sysHist, "syst. uncert", draw="e2")
    muhisto.addHisto(gHist, "", draw="e0")  ## add a second time to draw on top

    can = ROOT.TCanvas("", "", 1000, 1200)
    can.cd()

    muhisto.Draw()

    from myRatio import Ratio
    r = Ratio("Sim./Pred.", gHist, fHist, sysHist)
    r.draw(0., 2)
    infoText.Draw()
    muhisto.leg.AddEntry(r.totalUncert, "total uncert", "f")
    muhisto.leg.Draw()
    SaveAs(can,
           "qcdClosure_%s_%s" % ("".join(signalAbbrs) + additionalLabel, plot))

    # Since root is too stupid to clear the canvas before python is ending, clean
    # the canvas yourself
    ROOT.SetOwnership(can, False)
    del can
Exemplo n.º 13
0
def drawBeforeClosure( plot, gTree, foTree, cut, can, info, datasetAbbr, additionalInfo="",norm=False ):
		if plot == "met" and cut != "1":
			return

		# The first attempt to get the histogram is only to get the minimal
		# and maximal value on the x-axis, for not predefined binning
		h_gamma = getHisto( gTree, plot, cut=cut )
		h_fo = getHisto( foTree, plot, cut=cut )
		xMin, xMax = getXMinXMax( [ h_gamma, h_fo ] )

		h_gamma = getHisto( gTree, plot, cut=cut, color=1, firstBin=xMin,lastBin=xMax )
		h_fo = getHisto( foTree, plot, cut=cut, color=46, firstBin=xMin,lastBin=xMax )
		if norm:
			for h in [h_gamma,h_fo]:
				h.Scale(1./h.Integral())
				h.GetYaxis().SetTitle("Normed Entries")

		muhisto = Multihisto()
		muhisto.leg.SetHeader( datasetToLatex( datasetAbbr ) )
		muhisto.addHisto( h_gamma, "#gamma", draw="hist e0" )
		muhisto.addHisto( h_fo, "#gamma_{jet}", draw="hist e0")

		hPad = ROOT.TPad("hPad", "Histogram", 0, 0.2, 1, 1)
		hPad.cd()
		muhisto.Draw()

		ROOT.TGaxis.SetMaxDigits(4)
		ratioPad = ROOT.TPad("ratioPad", "Ratio", 0, 0, 1, 0.2)
		ratioPad.cd()
		ratioPad.SetLogy( False )
		ratioGraph = ratios.RatioGraph( h_gamma, h_fo )
		ratioGraph.draw(ROOT.gPad, yMin=None, yMax=None, adaptiveBinning=False, errors="yx")
		ratioGraph.graph.Draw("same p e0") # draw nice points
		ratioGraph.hAxis.SetYTitle( "#gamma/#gamma_{jet}")

		can.cd()
		hPad.Draw()
		ratioPad.Draw()
		info.Draw()
		SaveAs(can, "qcd_preWeight_%s_%s_%s"%(datasetAbbr+additionalInfo, plot,reweightVar) )
		ROOT.SetOwnership( hPad, False )
		ROOT.SetOwnership( ratioPad, False )
Exemplo n.º 14
0
def compareTrees( plot="photons.pt", filename="slimQCD_V02.28_tree.root" ):
	label, unit, binning = readAxisConf( "photons[0].ptJet()" )
	#binning = range(0,70,10) + binning
	#binning = range(0,1000, 30 )
	import array
	gH = ROOT.TH1F( randomName(), ";jet_{x};", len(binning)-1, array.array('d', binning) )
	fH = gH.Clone( randomName() )
	fH.SetLineColor(2)
	fH.SetMarkerColor(2)
	#cut = "!photons[0].isGen(0)"
	#cut = "1"

	gTree = readTree( filename, "photonTree" )
	fTree = readTree( filename, "photonJetTree" )

	#gH = getHisto( gTree, plot, color=1, cut=cut,firstBin=0,lastBin=1400 )
	#fH = getHisto( fTree, plot, color=2, cut=cut,firstBin=0,lastBin=1400 )

	for h, tree in [(gH, gTree), (fH, fTree)]:
		h.Sumw2()
		for event in tree:
			h.Fill( getFromEvent( event ), event.weight )


	for h in [gH, fH]:
		h.Scale( 1, "width" )

	mh = Multihisto()
	mh.addHisto( gH, "#gamma", draw="hist e" )
	mh.addHisto( fH, "#gamma_{jet}", draw="hist e" )

	can = ROOT.TCanvas()
	can.cd()
	mh.Draw()


	from myRatio import Ratio
	r = Ratio( "#gamma/#gamma_{jet}", gH, fH )
	r.draw(None,2)


	SaveAs( can, "compare_test" )
Exemplo n.º 15
0
def compareHists( filenames, tight, fcut, draw=False ):
	loose = getHistoFromFiles( "met", "photonJetTree", filenames, fcut )
	loose.SetLineColor(2)
	if loose.Integral(0,loose.FindBin(99)):
		loose.Scale( tight.Integral(0,loose.FindBin(99)) / loose.Integral(0,loose.FindBin(99)) )
	option = "uu norm" if filenames[0].startswith("PhotonHad") else "ww"
	if draw:

		c = ROOT.TCanvas()
		c.cd()
		mh = Multihisto()
		mh.addHisto( tight.Clone( randomName() ), "#gamma_{tight}", draw="hist e")
		mh.addHisto( loose, "#gamma_{loose}", draw="hist e")
		mh.Draw()
		from myRatio import Ratio
		r = Ratio( "#gamma_{tight}/#gamma_{loose}", tight, loose )
		r.draw(0,2)
		c.SaveAs("plots/findFoId_%s_twoDistributions_%s.pdf"%(getSaveNameFromDatasets(filenames),''.join([s for s in fcut if s.isdigit()])) )

	return tight.Chi2Test( loose, option )
Exemplo n.º 16
0
def compareBinnedSamples(histList1, histList2, plot="met"):

    cut = "[email protected]() && [email protected]()"
    treeName = "photonTree"

    mh = Multihisto()

    # if "ZGamma" in histList1[0]:
    # 	mh.setMinimum(0.01)

    # sum all histos in histList1
    hist1 = None
    for fileName in histList1:
        datasetAbbr1 = getDatasetAbbr(fileName)
        tree = readTree(fileName, treeName)
        h = getHisto(tree, plot, cut=cut, color=colors[datasetAbbr1])
        if hist1:
            hist1.Add(h)
        else:
            hist1 = h
    mh.addHisto(hist1, datasetToLatex(datasetAbbr1), draw="hist e")

    # stack histos in histList2
    for fileName in histList2:
        datasetAbbr = getDatasetAbbr(fileName)
        tree = readTree(fileName, treeName)
        h = getHisto(tree, plot, cut=cut, color=colors[datasetAbbr])
        mh.addHisto(h, datasetToLatex(datasetAbbr), toStack=True)

    mh.Draw()

    stack = mh.stack.GetStack().Last()
    stack.SetMarkerSize(0)
    stack.Draw("same e0")
    errorHist = mh.stack.GetStack().Last().Clone(randomName())
    errorHist.SetMarkerColor(1)
    errorHist.Draw("same e")
    if plot != "met":
        datasetAbbr1 += plot
    SavePad("compareBinned" + datasetAbbr1)
Exemplo n.º 17
0
def drawPileUpHistos( saveTex=False ):

	inputHistPath = "../TreeWriter/pileUpReweighting/"

	data = readHisto( inputHistPath + "nTrueVertexData.root", "pileup" )
	data.SetLineColor(1)
	data.SetMarkerColor(1)
	data.SetMarkerStyle(20)
	data.Sumw2()
	if saveTex:
		data.SetMarkerSize(.8)
	else:
		data.SetMarkerSize(1.2)

	mc = readHisto( inputHistPath + "nTrueVertexMC.root", "pileupS10" )
	mc.SetLineColor(2)
	mc.SetMarkerColor(2)

	for h in [mc, data ]:
		h.Scale( 1./h.Integral() )
		h.SetTitle( ";Number of Pile-up Events;Normalized Entries" )
		if saveTex:
			h.SetLineWidth(2)
			h.SetTitleSize( 0.06311227345609463, "yx" )
			h.SetLabelSize( 0.06311227345609463, "yx" )

	muhist = Multihisto()
	muhist.addHisto( data, "Data", draw="ep" )
	muhist.addHisto( mc, "Simulation", draw="hist" )
	muhist.setMinimum(0)

	if saveTex:
		muhist.leg.SetTextSize(0.063112267888)
		texStyle()


	pc1 = ROOT.TLatex(0,.96, "CMS Private Work")
	pc2 = ROOT.TLatex( .76,.96, "\SI{19.8}{fb^{-1}} #sqrt{s}=\SI{8}{TeV}")

	masterPath = "~/master/documents/thesis/plots/"
	can = ROOT.TCanvas("","",2000,1000)
	can.cd()
	can.SetLogy(0)
	muhist.Draw()
	for pc in [pc1, pc2]:
		pc.SetNDC()
		if saveTex:
			pc.SetTextSize(0.06311227345609463)
		pc.Draw()


	ending = 'tex' if saveTex else 'pdf'

	ROOT.gPad.SaveAs(masterPath+"puDistribution.%s"%ending)
Exemplo n.º 18
0
def zGammaMixture(plot="met"):
    cut = "1"

    nunuTree = readTree("slimZGammaNuNu_V03.18_tree.root", "photonTree")
    zIncTree = readTree("slimZGamma_V03.18_tree.root", "photonTree")

    nBins = range(80, 500, 10) if plot == "photons[0].pt" else readAxisConf(plot)[2]

    h_nunu = getHisto(nunuTree, plot, cut + "&&photons[0].pt>=130", nBins=nBins, color=2)
    h_zInc = getHisto(zIncTree, plot, cut + "&&photons[0].pt<130", nBins=nBins, color=4)

    mh = Multihisto()

    mh.addHisto(h_nunu, "#gammaZ#rightarrow#gamma#nu#nu(p_{T}#geq130GeV)", draw="e", toStack=True)
    mh.addHisto(h_zInc, "#gammaZ(p_{T}<130GeV)", draw="e", toStack=True)
    mh.Draw()

    if plot == "photons[0].pt":
        l = ROOT.TLine(130, 0, 130, 1)
        l.Draw()

    SavePad("inclusiveAndIsrSample_%s" % plot)
Exemplo n.º 19
0
def compareTrees( plot="photons.pt", filename="slimAllQCD_V02.28_tree.root" ):
	label, unit, binning = readAxisConf( "ht" )
	import array
	fH = ROOT.TH1F( randomName(), ";%s;"%label, len(binning)-1, array.array('d', binning) )
	fH.SetLineColor(2)
	fH.SetMarkerColor(2)
	fH.Sumw2()
	#cut = "!photons[0].isGen(0)"
	cut = "1"

	gTree = readTree( filename, "photonTree" )
	fTree = readTree( filename, "photonJetTree" )

	gH = getHisto( gTree, "ht", color=1, cut=cut,firstBin=0,lastBin=1400 )
	#fH = getHisto( fTree, plot, color=2, cut=cut,firstBin=0,lastBin=1400 )

	for event in fTree:
		fH.Fill( getFromEvent( event ) )


	for h in [gH, fH]:
		h.Scale( 1./h.Integral() )

	mh = Multihisto()
	mh.addHisto( gH, "new", draw="hist e" )
	mh.addHisto( fH, "old (recalculated)", draw="hist e" )

	can = ROOT.TCanvas()
	can.cd()
	mh.Draw()


	from myRatio import Ratio
	r = Ratio( "#gamma/#gamma_{jet}", gH, fH )
	r.draw(0,2)


	SaveAs( can, "compare_%s_norm"%plot )
Exemplo n.º 20
0
def drawTwoHists(gHist, fHist, sHist, saveName, minmax):
    for bin in range(sHist.GetNbinsX() + 2):
        sHist.SetBinError(bin, sHist.GetBinContent(bin))
        sHist.SetBinContent(bin, fHist.GetBinContent(bin))

    sHist.SetFillColor(sHist.GetLineColor())
    sHist.SetLineColor(sHist.GetLineColor())
    sHist.SetFillStyle(3254)
    sHist.SetMarkerSize(0)
    fHist.SetLineColor(2)
    sHist.SetLineColor(2)

    for h in gHist, fHist, sHist:
        from inheritRoot import H1F
        h.__class__ = H1F
        h.MergeOverflow()
        h.Scale(1., "width")

    muhisto = Multihisto()
    muhisto.addHisto(gHist, "Simulation", draw="hist e")
    muhisto.addHisto(fHist, "Prediction", draw="hist")
    muhisto.addHisto(sHist, "#sigma_{w}", draw="e2")

    can = ROOT.TCanvas(randomName(), "", 1000, 1200)
    can.cd()
    muhisto.Draw()
    text = ROOT.TLatex(.1, .965,
                       "%i #leq p_{T^{*}} < %i, %i #leq H_{T} < %i" % minmax)
    text.SetNDC()
    text.Draw()

    from myRatio import Ratio
    r = Ratio("Sim./Pred.", gHist, fHist)
    r.draw(0, 2)

    can.SaveAs(saveName + ".pdf")

    ROOT.SetOwnership(can, False)
    del can
Exemplo n.º 21
0
def split2Din1DMultihist(h2D, useYaxis, uFlow, oFlow):
    """Creates many TH1 out of one TH2 and put them in a Multihisto.

	h2D: TH2 (rebin appropriate if necessary )
	useYaxis: The TH2 will be splitted in different values of Y.
		If false, the X axis will be used (bool).
	uFlow: Take the underFlow into account (bool).
	oFlow: Take the overFlow into account (bool).
	"""
    mh = Multihisto()
    mh.setMinimum(1e-8)
    style = ROOT.gROOT.GetStyle("tdrStyle")  # for nice color gradient

    if useYaxis:
        axis = h2D.GetYaxis()
    else:
        axis = h2D.GetXaxis()

    variable = axis.GetTitle()
    nBins = axis.GetNbins()

    binRange = range(nBins + 2)
    if not uFlow:
        binRange = binRange[1:]
    if not oFlow:
        binRange = binRange[:-1]

    for iColor, iBin in enumerate(binRange):
        if useYaxis:
            h = h2D.ProjectionX("_px%s" % iBin, iBin, iBin)
        else:
            h = h2D.ProjectionY("_px%s" % iBin, iBin, iBin)
        lowEdge = axis.GetBinLowEdge(iBin)
        upEdge = axis.GetBinUpEdge(iBin)

        if iBin == 0:
            title = "       %s < %s" % (variable, upEdge)
        elif iBin != nBins + 1:
            title = "%s #leq %s < %s" % (lowEdge, variable, upEdge)
        else:
            title = "%s #leq %s" % (lowEdge, variable)

        color = style.GetColorPalette(
            int(1. * iColor / (len(binRange) - 1) *
                (style.GetNumberOfColors() - 1)))
        h.SetLineColor(color)
        h.SetMarkerColor(h.GetLineColor())
        h.SetMarkerSize(0)
        h.GetXaxis().SetTitle(h2D.GetXaxis().GetTitle())
        mh.addHisto(h, title, draw="e0")

    return mh
Exemplo n.º 22
0
def plotFakeRate(filenames, opts):
    mhisto = Multihisto()
    mhisto.legendOption = "lp"
    #mhisto.leg.SetHeader("Object matching")

    for iColor, filename in enumerate(filenames):
        mhisto.addHisto(getFakeRateHisto(filename, opts, iColor + 2),
                        getDatasetAbbr(filename, slim=False),
                        draw="")

    if opts.plot == "photons.pt":
        yuOrig = yutarosHistogramMC(1)
        mhisto.addHisto(yuOrig, "DY tag&probe", draw="")

    can = ROOT.TCanvas()
    can.cd()
    can.SetLogy(0)
    mhisto.Draw()
    saveName = "%s_%s_%s" % ("fakeRate", opts.plot, opts.savePrefix)
    can.SaveAs("plots/%s.pdf" % manipulateSaveName(saveName))
Exemplo n.º 23
0
def drawClosure( plot, gTree, foTree, cut, can, info, datasetAbbr, additionalInfo="" ):

		# The first attempt to get the histogram is only to get the minimal
		# and maximal value on the x-axis, for not predefined binning
		h_gamma = getHisto( gTree, plot,cut=cut )
		h_fo = getHisto( foTree, plot, cut=cut )
		xMin, xMax = getXMinXMax( [ h_gamma, h_fo ] )

		h_gamma = getHisto( gTree, plot, cut=cut, color=1, firstBin=xMin,lastBin=xMax )
		h_fo = getHisto( foTree, plot, cut=cut, weight="weight*w_qcd", color=46, firstBin=xMin,lastBin=xMax )
		h_fo_error = getQCDErrorHisto( foTree, plot, cut=cut, firstBin=xMin, lastBin=xMax )
		h_fo_error.SetFillColor( h_fo.GetLineColor() )
		h_fo_error.SetLineColor( h_fo_error.GetLineColor() )
		h_fo_error.SetFillStyle(3254)
		h_fo_error.SetMarkerSize(0)

		muhisto = Multihisto()
		muhisto.leg.SetHeader( datasetToLatex( datasetAbbr ) )
		muhisto.addHisto( h_gamma, "#gamma", draw="hist e0" )
		muhisto.addHisto( h_fo, "#gamma_{jet}#upointw", draw="hist e0")
		muhisto.addHisto( h_fo_error, "#sigma_{w}", draw="e2")

		hPad = ROOT.TPad("hPad", "Histogram", 0, 0.2, 1, 1)
		hPad.cd()
		muhisto.Draw()

		ratioPad = ROOT.TPad("ratioPad", "Ratio", 0, 0, 1, 0.2)
		ratioPad.cd()
		ratioPad.SetLogy( False )
		from myRatio import Ratio
		r = Ratio( "#gamma/#gamma_{pred}", h_gamma, h_fo )
		ratio, sys, one = r.draw(0,2)
		ratio.Draw("e1")
		sys.Draw("same e2")
		one.Draw()

		can.cd()
		hPad.Draw()
		ratioPad.Draw()
		info.Draw()
		SaveAs(can, "qcd_afterWeighting_%s_%s_%s"%(datasetAbbr+additionalInfo, plot,reweightVar) )
		ROOT.SetOwnership( hPad, False )
		ROOT.SetOwnership( ratioPad, False )
Exemplo n.º 24
0
def compareTrees(plot="photons.pt", filename="slimQCD_V02.28_tree.root"):
    label, unit, binning = readAxisConf("photons[0].ptJet()")
    #binning = range(0,70,10) + binning
    #binning = range(0,1000, 30 )
    import array
    gH = ROOT.TH1F(randomName(), ";jet_{x};",
                   len(binning) - 1, array.array('d', binning))
    fH = gH.Clone(randomName())
    fH.SetLineColor(2)
    fH.SetMarkerColor(2)
    #cut = "!photons[0].isGen(0)"
    #cut = "1"

    gTree = readTree(filename, "photonTree")
    fTree = readTree(filename, "photonJetTree")

    #gH = getHisto( gTree, plot, color=1, cut=cut,firstBin=0,lastBin=1400 )
    #fH = getHisto( fTree, plot, color=2, cut=cut,firstBin=0,lastBin=1400 )

    for h, tree in [(gH, gTree), (fH, fTree)]:
        h.Sumw2()
        for event in tree:
            h.Fill(getFromEvent(event), event.weight)

    for h in [gH, fH]:
        h.Scale(1, "width")

    mh = Multihisto()
    mh.addHisto(gH, "#gamma", draw="hist e")
    mh.addHisto(fH, "#gamma_{jet}", draw="hist e")

    can = ROOT.TCanvas()
    can.cd()
    mh.Draw()

    from myRatio import Ratio
    r = Ratio("#gamma/#gamma_{jet}", gH, fH)
    r.draw(None, 2)

    SaveAs(can, "compare_test")
Exemplo n.º 25
0
def plotFakeRate( filenames, opts ):
	mhisto = Multihisto()
	mhisto.legendOption = "lp"
	#mhisto.leg.SetHeader("Object matching")

	for iColor, filename in enumerate(filenames):
		mhisto.addHisto( getFakeRateHisto( filename, opts, iColor+2 ), getDatasetAbbr(filename,slim=False), draw="" )

	if opts.plot == "photons.pt":
		yuOrig = yutarosHistogramMC(1)
		mhisto.addHisto( yuOrig, "DY tag&probe", draw="")

	can = ROOT.TCanvas()
	can.cd()
	can.SetLogy(0)
	mhisto.Draw()
	saveName = "%s_%s_%s"%("fakeRate",opts.plot,opts.savePrefix)
	can.SaveAs( "plots/%s.pdf"%manipulateSaveName(saveName) )
Exemplo n.º 26
0
def drawClosure( filenames, predFilenames, plot, commonCut, infoText, additionalLabel="", modifyEmptyBins=True ):
	infoText = ROOT.TLatex(0,.96, "CMS Private Work 19.7fb^{-1} #sqrt{s}=8TeV #geq1#gamma,#geq2jets" )
	infoText.SetNDC()
	infoText.SetTextSize(0.045)

	gHist = getHists( filenames, plot, commonCut )
	fHist, sysHist = predictionHistos( predFilenames, plot, commonCut, modifyEmptyBins )
	fHist.SetMarkerSize(0)
	sysHist.SetFillStyle(3254)
	sysHist.SetFillColor( sysHist.GetLineColor() )
	sysHist.SetLineColor(0)


	signalAbbrs = mergeDatasetAbbr( [ getDatasetAbbr(x) for x in filenames ] )

	muhisto = Multihisto()
	muhisto.leg.SetHeader( ",".join( [ datasetToLatex(x) for x in signalAbbrs ] ) )
	muhisto.addHisto( gHist, "Simulation", draw="" )
	muhisto.addHisto( fHist, "Prediction", draw="hist e")
	muhisto.addHisto( sysHist, "syst. uncert", draw="e2")
	muhisto.addHisto( gHist, "", draw="e0" ) ## add a second time to draw on top

	can = ROOT.TCanvas("", "", 1000, 1200)
	can.cd()

	muhisto.Draw()

	from myRatio import Ratio
	r = Ratio( "Sim./Pred.", gHist, fHist, sysHist )
	r.draw(0.,2)
	infoText.Draw()
	muhisto.leg.AddEntry( r.totalUncert, "total uncert", "f" )
	muhisto.leg.Draw()
	SaveAs(can, "qcdClosure_%s_%s"%("".join(signalAbbrs)+additionalLabel, plot) )

	# Since root is too stupid to clear the canvas before python is ending, clean
	# the canvas yourself
	ROOT.SetOwnership( can, False )
	del can
Exemplo n.º 27
0
def drawTwoHists( gHist, fHist, sHist, saveName, minmax ):
	for bin in range( sHist.GetNbinsX()+2 ):
		sHist.SetBinError( bin, sHist.GetBinContent(bin) )
		sHist.SetBinContent( bin, fHist.GetBinContent(bin) )

	sHist.SetFillColor( sHist.GetLineColor() )
	sHist.SetLineColor( sHist.GetLineColor() )
	sHist.SetFillStyle(3254)
	sHist.SetMarkerSize(0)
	fHist.SetLineColor(2)
	sHist.SetLineColor(2)


	for h in gHist, fHist, sHist:
		from inheritRoot import H1F
		h.__class__ = H1F
		h.MergeOverflow()
		h.Scale(1., "width")

	muhisto = Multihisto()
	muhisto.addHisto( gHist, "Simulation", draw="hist e" )
	muhisto.addHisto( fHist, "Prediction", draw="hist")
	muhisto.addHisto( sHist, "#sigma_{w}", draw="e2")

	can = ROOT.TCanvas(randomName(), "", 1000, 1200)
	can.cd()
	muhisto.Draw()
	text = ROOT.TLatex(.1,.965, "%i #leq p_{T^{*}} < %i, %i #leq H_{T} < %i"%minmax)
	text.SetNDC()
	text.Draw()

	from myRatio import Ratio
	r = Ratio( "Sim./Pred.", gHist, fHist )
	r.draw(0,2)

	can.SaveAs(saveName+".pdf")

	ROOT.SetOwnership( can, False )
	del can
Exemplo n.º 28
0
def compareBinnedSamples(histList1, histList2, plot="met"):

    cut = "[email protected]() && [email protected]()"
    treeName = "photonTree"

    mh = Multihisto()

    #if "ZGamma" in histList1[0]:
    #	mh.setMinimum(0.01)

    # sum all histos in histList1
    hist1 = None
    for fileName in histList1:
        datasetAbbr1 = getDatasetAbbr(fileName)
        tree = readTree(fileName, treeName)
        h = getHisto(tree, plot, cut=cut, color=colors[datasetAbbr1])
        if hist1: hist1.Add(h)
        else: hist1 = h
    mh.addHisto(hist1, datasetToLatex(datasetAbbr1), draw="hist e")

    # stack histos in histList2
    for fileName in histList2:
        datasetAbbr = getDatasetAbbr(fileName)
        tree = readTree(fileName, treeName)
        h = getHisto(tree, plot, cut=cut, color=colors[datasetAbbr])
        mh.addHisto(h, datasetToLatex(datasetAbbr), toStack=True)

    mh.Draw()

    stack = mh.stack.GetStack().Last()
    stack.SetMarkerSize(0)
    stack.Draw("same e0")
    errorHist = mh.stack.GetStack().Last().Clone(randomName())
    errorHist.SetMarkerColor(1)
    errorHist.Draw("same e")
    if plot != "met":
        datasetAbbr1 += plot
    SavePad("compareBinned" + datasetAbbr1)
Exemplo n.º 29
0
def drawComparison( histName, mc, data ):
	hdata = getIsolationHist( data, histName )
	hdata.SetLineColor(1)


	hmc = getIsolationHist( mc, histName )
	hmc.SetLineColor(2)
	for h in hmc, hdata:
		h.SetLineWidth(2)

	hmc.Scale( hdata.Integral() / hmc.Integral() )

	mh = Multihisto()
	mh.addHisto( hdata, "Data", draw="e0" )
	mh.addHisto( hmc, "MC", draw="hist", toStack=True )
	c = ROOT.TCanvas()
	mh.Draw()

	from myRatio import Ratio
	r = Ratio( "Data/Bkg", hdata, hmc )
	r.draw(0,2)

	SavePad("isolationComparison_%s"%histName )
Exemplo n.º 30
0
def compareTrees(plot="photons.pt", filename="slimAllQCD_V02.28_tree.root"):
    label, unit, binning = readAxisConf("ht")
    import array
    fH = ROOT.TH1F(randomName(), ";%s;" % label,
                   len(binning) - 1, array.array('d', binning))
    fH.SetLineColor(2)
    fH.SetMarkerColor(2)
    fH.Sumw2()
    #cut = "!photons[0].isGen(0)"
    cut = "1"

    gTree = readTree(filename, "photonTree")
    fTree = readTree(filename, "photonJetTree")

    gH = getHisto(gTree, "ht", color=1, cut=cut, firstBin=0, lastBin=1400)
    #fH = getHisto( fTree, plot, color=2, cut=cut,firstBin=0,lastBin=1400 )

    for event in fTree:
        fH.Fill(getFromEvent(event))

    for h in [gH, fH]:
        h.Scale(1. / h.Integral())

    mh = Multihisto()
    mh.addHisto(gH, "new", draw="hist e")
    mh.addHisto(fH, "old (recalculated)", draw="hist e")

    can = ROOT.TCanvas()
    can.cd()
    mh.Draw()

    from myRatio import Ratio
    r = Ratio("#gamma/#gamma_{jet}", gH, fH)
    r.draw(0, 2)

    SaveAs(can, "compare_%s_norm" % plot)
Exemplo n.º 31
0
def compareHists(filenames, tight, fcut, draw=False):
    loose = getHistoFromFiles("met", "photonJetTree", filenames, fcut)
    loose.SetLineColor(2)
    if loose.Integral(0, loose.FindBin(99)):
        loose.Scale(
            tight.Integral(0, loose.FindBin(99)) /
            loose.Integral(0, loose.FindBin(99)))
    option = "uu norm" if filenames[0].startswith("PhotonHad") else "ww"
    if draw:

        c = ROOT.TCanvas()
        c.cd()
        mh = Multihisto()
        mh.addHisto(tight.Clone(randomName()), "#gamma_{tight}", draw="hist e")
        mh.addHisto(loose, "#gamma_{loose}", draw="hist e")
        mh.Draw()
        from myRatio import Ratio
        r = Ratio("#gamma_{tight}/#gamma_{loose}", tight, loose)
        r.draw(0, 2)
        c.SaveAs("plots/findFoId_%s_twoDistributions_%s.pdf" %
                 (getSaveNameFromDatasets(filenames), ''.join(
                     [s for s in fcut if s.isdigit()])))

    return tight.Chi2Test(loose, option)
Exemplo n.º 32
0
def drawSignalContamination(filename, xy, split):
    import array
    label, unit, binning = readAxisConf("met")
    metBinning = array.array("d", binning)

    gHisto = readHisto(filename, "gMet%s_%s" % xy).Rebin(
        len(metBinning) - 1, randomName(), metBinning)
    eHisto = readHisto(filename, "eMet%s_%s" % xy).Rebin(
        len(metBinning) - 1, randomName(), metBinning)
    fHisto = readHisto(filename, "fMet%s_%s" % xy).Rebin(
        len(metBinning) - 1, randomName(), metBinning)

    eHisto = applyFakeRateEWK(eHisto)
    eContamination = divideHistos(eHisto, gHisto)
    eContamination.SetLineColor(2)

    fContamination = divideHistos(fHisto, gHisto)
    fContamination.SetLineColor(4)

    totalContamination = divideHistos(addHistos([eHisto, fHisto]), gHisto)
    totalContamination.SetLineColor(1)
    totalContamination.SetMarkerColor(1)

    for h in [totalContamination, fContamination, eContamination]:
        h.Scale(100.)  # in %
        h.GetYaxis().SetTitleOffset(0.9)
        h.SetTitle(";%s [#text{%s}];Signal Contamination [%s]" %
                   ("#met", unit, "%"))
        h.SetLineWidth(2)
        h.SetMarkerSize(0)
        h.SetLabelSize(1. / 15.8447, "xy")
        h.SetTitleSize(1. / 15.8447, "xy")

    mh = Multihisto()
    mh.setMinimum(0)
    if split:
        mh.addHisto(totalContamination, "Total", draw="pe")
        mh.addHisto(fContamination,
                    "b_{#text{signal}}^{#text{QCD}}/s",
                    draw="hist")
        mh.addHisto(eContamination,
                    "b_{#text{signal}}^{e#rightarrow#gamma}/s",
                    draw="hist")
    else:
        mh.addHisto(totalContamination, "", draw="e0")

    can = ROOT.TCanvas()
    can.cd()
    can.SetLogy(False)
    mh.Draw()
    totalContamination.Draw("same")
    info.Draw()
    saveName = "signalContamination_%s_%s_%s_%s" % (xy +
                                                    (split, filename[0:-4]))
    SaveAs(can, saveName)
    ROOT.gPad.SaveAs("/home/knut/master/documents/thesis/plots/%stex" %
                     saveName)
    correctTiksPlot("/home/knut/master/documents/thesis/plots/%stex" %
                    saveName)
Exemplo n.º 33
0
def drawClosure(plot,
                gTree,
                foTree,
                cut,
                can,
                info,
                datasetAbbr,
                additionalInfo=""):

    # The first attempt to get the histogram is only to get the minimal
    # and maximal value on the x-axis, for not predefined binning
    h_gamma = getHisto(gTree, plot, cut=cut)
    h_fo = getHisto(foTree, plot, cut=cut)
    xMin, xMax = getXMinXMax([h_gamma, h_fo])

    h_gamma = getHisto(gTree,
                       plot,
                       cut=cut,
                       color=1,
                       firstBin=xMin,
                       lastBin=xMax)
    h_fo = getHisto(foTree,
                    plot,
                    cut=cut,
                    weight="weight*w_qcd",
                    color=46,
                    firstBin=xMin,
                    lastBin=xMax)
    h_fo_error = getQCDErrorHisto(foTree,
                                  plot,
                                  cut=cut,
                                  firstBin=xMin,
                                  lastBin=xMax)
    h_fo_error.SetFillColor(h_fo.GetLineColor())
    h_fo_error.SetLineColor(h_fo_error.GetLineColor())
    h_fo_error.SetFillStyle(3254)
    h_fo_error.SetMarkerSize(0)

    muhisto = Multihisto()
    muhisto.leg.SetHeader(datasetToLatex(datasetAbbr))
    muhisto.addHisto(h_gamma, "#gamma", draw="hist e0")
    muhisto.addHisto(h_fo, "#gamma_{jet}#upointw", draw="hist e0")
    muhisto.addHisto(h_fo_error, "#sigma_{w}", draw="e2")

    hPad = ROOT.TPad("hPad", "Histogram", 0, 0.2, 1, 1)
    hPad.cd()
    muhisto.Draw()

    ratioPad = ROOT.TPad("ratioPad", "Ratio", 0, 0, 1, 0.2)
    ratioPad.cd()
    ratioPad.SetLogy(False)
    from myRatio import Ratio
    r = Ratio("#gamma/#gamma_{pred}", h_gamma, h_fo)
    ratio, sys, one = r.draw(0, 2)
    ratio.Draw("e1")
    sys.Draw("same e2")
    one.Draw()

    can.cd()
    hPad.Draw()
    ratioPad.Draw()
    info.Draw()
    SaveAs(
        can, "qcd_afterWeighting_%s_%s_%s" %
        (datasetAbbr + additionalInfo, plot, reweightVar))
    ROOT.SetOwnership(hPad, False)
    ROOT.SetOwnership(ratioPad, False)
Exemplo n.º 34
0
def compareTrees(plot="photons.pt",
                 filenames=["slimAllQCD_V02.28_tree.root"],
                 drawRatio=False):
    cut = "1"
    #cut = plot+">110"
    #cut = "!photons[0].isGen(0)"
    #cut = "ht < 600"

    gH = getHistoFromFiles(plot, "photonTree", filenames, cut)
    fH = getHistoFromFiles(plot, "photonJetTree", filenames, cut, color=2)

    weight2D = getMixedWeigthHisto(filenames,
                                   filenames,
                                   cut,
                                   control=True,
                                   fillEmptyBins=False)
    for filename in filenames:
        fTree = readTree(filename, "photonJetTree")
        writeWeight2DToFile(filename, fTree, weight2D, "foWeightsCompare")
    fgammaHist, fgammaWeightError = qcdPredictionHistos(
        filenames, plot, cut, True)
    for bin in range(fgammaHist.GetNbinsX() + 2):
        fgammaHist.SetBinError(
            bin,
            sqrt(
                fgammaHist.GetBinError(bin)**2 +
                fgammaWeightError.GetBinContent(bin)**2))

    fH = fgammaHist

    for h in [gH, fH]:
        h.Scale(1. / h.Integral())
        h.SetMarkerSize(0)
        h.GetXaxis().SetTitleOffset(1.03)
        h.GetYaxis().SetTitleOffset(1.5)
        h.GetXaxis().SetLabelSize(0.0633790992496425)
        h.GetXaxis().SetTitleSize(0.0633790992496425)
        h.GetYaxis().SetLabelSize(0.0633790992496425)
        h.GetYaxis().SetTitleSize(0.0633790992496425)
        h.GetYaxis().SetLabelOffset(0)

        if plot == "photons[0].pt":
            h.GetXaxis().SetTitle("$p_{T}$ [GeV]")
        if plot == "photons[0].ptJet()":
            h.GetXaxis().SetTitle("$p_{T^*}$ [GeV]")

    mh = Multihisto()
    mh.leg.SetX1(0.608)
    mh.leg.SetX2(0.95)
    mh.addHisto(gH, "#gamma_{#text{tight}}", draw="hist e")
    mh.addHisto(fH, "#gamma_{#text{loose}}", draw="hist e")

    can = ROOT.TCanvas()
    #can.SetBottomMargin(0)
    #can.SetTopMargin(0)
    #can.SetRightMargin(0)
    can.SetLeftMargin(0.19)
    can.cd()
    mh.Draw()

    pc1 = ROOT.TLatex(0, .96, "CMS Private Work")
    pc2 = ROOT.TLatex(.51, .96, "\SI{19.8}{fb^{-1}} #sqrt{s}=\SI{8}{TeV}")
    for pc in [pc1, pc2]:
        pc.SetNDC()
        pc.SetTextSize(0.06311227345609463)
        pc.Draw()

    if drawRatio:
        from myRatio import Ratio
        r = Ratio("#gamma/#gamma_{jet}", gH, fH)
        r.draw()

    #can.SetFillColor(ROOT.kGreen)
    SavePad("compare2_%s_%s" % (plot, shortName(filenames)))
    ROOT.gPad.SaveAs("~/master/documents/thesis/plots/compare_%s_%s.tex" %
                     (manipulateSaveName(plot), shortName(filenames)))
    correctTiksPlot(
        "/home/knut/master/documents/thesis/plots/compare_%s_%s.tex" %
        (manipulateSaveName(plot), shortName(filenames)))
    ROOT.SetOwnership(can, False)
Exemplo n.º 35
0
def drawBeforeClosure(plot,
                      gTree,
                      foTree,
                      cut,
                      can,
                      info,
                      datasetAbbr,
                      additionalInfo="",
                      norm=False):
    if plot == "met" and cut != "1":
        return

    # The first attempt to get the histogram is only to get the minimal
    # and maximal value on the x-axis, for not predefined binning
    h_gamma = getHisto(gTree, plot, cut=cut)
    h_fo = getHisto(foTree, plot, cut=cut)
    xMin, xMax = getXMinXMax([h_gamma, h_fo])

    h_gamma = getHisto(gTree,
                       plot,
                       cut=cut,
                       color=1,
                       firstBin=xMin,
                       lastBin=xMax)
    h_fo = getHisto(foTree,
                    plot,
                    cut=cut,
                    color=46,
                    firstBin=xMin,
                    lastBin=xMax)
    if norm:
        for h in [h_gamma, h_fo]:
            h.Scale(1. / h.Integral())
            h.GetYaxis().SetTitle("Normed Entries")

    muhisto = Multihisto()
    muhisto.leg.SetHeader(datasetToLatex(datasetAbbr))
    muhisto.addHisto(h_gamma, "#gamma", draw="hist e0")
    muhisto.addHisto(h_fo, "#gamma_{jet}", draw="hist e0")

    hPad = ROOT.TPad("hPad", "Histogram", 0, 0.2, 1, 1)
    hPad.cd()
    muhisto.Draw()

    ROOT.TGaxis.SetMaxDigits(4)
    ratioPad = ROOT.TPad("ratioPad", "Ratio", 0, 0, 1, 0.2)
    ratioPad.cd()
    ratioPad.SetLogy(False)
    ratioGraph = ratios.RatioGraph(h_gamma, h_fo)
    ratioGraph.draw(ROOT.gPad,
                    yMin=None,
                    yMax=None,
                    adaptiveBinning=False,
                    errors="yx")
    ratioGraph.graph.Draw("same p e0")  # draw nice points
    ratioGraph.hAxis.SetYTitle("#gamma/#gamma_{jet}")

    can.cd()
    hPad.Draw()
    ratioPad.Draw()
    info.Draw()
    SaveAs(
        can, "qcd_preWeight_%s_%s_%s" %
        (datasetAbbr + additionalInfo, plot, reweightVar))
    ROOT.SetOwnership(hPad, False)
    ROOT.SetOwnership(ratioPad, False)
Exemplo n.º 36
0
def drawSignalContamination( filename, xy, split ):
	import array
	label, unit, binning = readAxisConf("met")
	metBinning = array.array( "d", binning )

	gHisto = readHisto( filename, "gMet%s_%s"%xy ).Rebin(len(metBinning)-1, randomName(), metBinning )
	eHisto = readHisto( filename, "eMet%s_%s"%xy ).Rebin(len(metBinning)-1, randomName(), metBinning )
	fHisto = readHisto( filename, "fMet%s_%s"%xy ).Rebin(len(metBinning)-1, randomName(), metBinning )

	eHisto = applyFakeRateEWK( eHisto )
	eContamination = divideHistos( eHisto, gHisto )
	eContamination.SetLineColor(2)

	fContamination = divideHistos( fHisto, gHisto )
	fContamination.SetLineColor(4)

	totalContamination = divideHistos( addHistos( [eHisto, fHisto] ), gHisto )
	totalContamination.SetLineColor(1)
	totalContamination.SetMarkerColor(1)

	for h in [totalContamination, fContamination, eContamination]:
		h.Scale(100.) # in %
		h.GetYaxis().SetTitleOffset( 0.9 )
		h.SetTitle(";%s [#text{%s}];Signal Contamination [%s]"%("#met",unit, "%"))
		h.SetLineWidth(2)
		h.SetMarkerSize(0)
		h.SetLabelSize(1./15.8447, "xy")
		h.SetTitleSize(1./15.8447, "xy")

	mh = Multihisto()
	mh.setMinimum(0)
	if split:
		mh.addHisto( totalContamination, "Total", draw="pe" )
		mh.addHisto( fContamination, "b_{#text{signal}}^{#text{QCD}}/s", draw="hist" )
		mh.addHisto( eContamination, "b_{#text{signal}}^{e#rightarrow#gamma}/s", draw="hist" )
	else:
		mh.addHisto( totalContamination, "", draw="e0" )

	can = ROOT.TCanvas()
	can.cd()
	can.SetLogy(False)
	mh.Draw()
	totalContamination.Draw("same")
	info.Draw()
	saveName = "signalContamination_%s_%s_%s_%s"%(xy+(split,filename[0:-4] ))
	SaveAs(can, saveName )
	ROOT.gPad.SaveAs("/home/knut/master/documents/thesis/plots/%stex"%saveName )
	correctTiksPlot( "/home/knut/master/documents/thesis/plots/%stex"%saveName )
Exemplo n.º 37
0
def compareTrees(plot="met",
                 filenames=["slimAllQCD_V02.28_tree.root"],
                 drawRatio=False):
    #cut = "@electrons.size()==0 && @muons.size()==0"
    #cut = plot+">110"
    #cut = "!photons[0].isGen(0)"
    #cut = "ht < 600"
    cut = "1"

    gH = getHistoFromFiles(plot, "photonTree", filenames, "1")
    fH = getHistoFromFiles(plot, "photonJetTree", filenames, "1", color=2)

    for h in [gH, fH]:
        #h.Scale( 1./h.Integral() )
        h.SetMarkerSize(0)
        h.GetXaxis().SetTitleOffset(1.03)
        h.GetYaxis().SetTitleOffset(1.5)
        h.GetXaxis().SetLabelSize(0.0633790992496425)
        h.GetXaxis().SetTitleSize(0.0633790992496425)
        h.GetYaxis().SetLabelSize(0.0633790992496425)
        h.GetYaxis().SetTitleSize(0.0633790992496425)
        h.GetYaxis().SetLabelOffset(0)

        if plot == "photons[0].pt":
            h.GetXaxis().SetTitle("$p_{T}$ [GeV]")
        if plot == "photons[0].ptJet()":
            h.GetXaxis().SetTitle("$p_{T^*}$ [GeV]")

    ratio = gH.Clone(randomName())
    ratio.Divide(fH)

    mh = Multihisto()
    #mh.leg.SetX1(0.608)
    #mh.leg.SetX2(0.95)
    mh.addHisto(gH, "#gamma_{#text{tight}}", draw="hist e")
    mh.addHisto(fH, "#gamma_{#text{loose}}", draw="hist e")

    can = ROOT.TCanvas()
    #can.SetBottomMargin(0)
    #can.SetTopMargin(0)
    #can.SetRightMargin(0)
    #can.SetLeftMargin(0.19)
    can.cd()
    mh.Draw()

    pc1 = ROOT.TLatex(0, .96, "CMS Private Work")
    pc2 = ROOT.TLatex(.51, .96, "\SI{19.8}{fb^{-1}} #sqrt{s}=\SI{8}{TeV}")
    for pc in [pc1, pc2]:
        pc.SetNDC()
        pc.SetTextSize(0.06311227345609463)
        pc.Draw()

    if drawRatio:
        from myRatio import Ratio
        r = Ratio("#gamma/#gamma_{jet}", gH, fH)
        r.draw()

    #can.SetFillColor(ROOT.kGreen)
    SavePad("compare2_%s_%s" % ("test", shortName(filenames)))
    #ROOT.gPad.SaveAs("~/master/documents/thesis/plots/compare_%s_%s.tex"%(manipulateSaveName(plot),shortName( filenames )) )
    ROOT.SetOwnership(can, False)
Exemplo n.º 38
0
def drawPhi( filenames ):
	t = readTree( filenames[0], "photonTree" )
	for f in filenames[1:]:
		t.Add( "%s/photonTree"%f )

	absolute = True

	label, unit, binning = readAxisConf( "photons[0].phi" )

	if absolute:
		binning = [ x for x in binning if x >= 0 ]

	import array
	gH1 = ROOT.TH1F( randomName(), ";#Delta#phi(#gamma,#slash{E}_{T});", len(binning)-1, array.array('d', binning) )
	gH2 = ROOT.TH1F( randomName(), ";#Delta#phi(#gamma,#slash{E}_{T});", len(binning)-1, array.array('d', binning) )
	gH3 = ROOT.TH1F( randomName(), ";#Delta#phi(#gamma,#slash{E}_{T});", len(binning)-1, array.array('d', binning) )
	gH2.SetLineColor(2)
	gH3.SetLineColor(3)
	for h in gH1, gH2, gH3:
		h.Sumw2()

	from math import fabs
	for e in t:

		dPhi = e.photons[0].DeltaPhi( e.metPhi )
		if absolute:
			dPhi = fabs( dPhi )

		if e.met<10:
			gH1.Fill( dPhi )
		elif e.met < 100:
			gH2.Fill( dPhi )
		else:
			gH3.Fill( dPhi )

	ft = readTree( filenames[0], "photonJetTree" )
	for f in filenames[1:]:
		ft.Add( "%s/photonJetTree"%f )

	cutStr = "photons[0].chargedIso/100<2.6 && photons[0].neutralIso/100<3.5+0.04*photons[0].pt && photons[0].photonIso/100<1.3+0.005*photons[0].pt"
	cutStr += "&& (photons[0].chargedIso>0 || photons[0].neutralIso>0 || photons[0].photonIso>0)"
	ft = ft.CopyTree( cutStr )

	fH1 = ROOT.TH1F( randomName(), ";#Delta#phi(#gamma,#slash{E}_{T});", len(binning)-1, array.array('d', binning) )
	fH2 = ROOT.TH1F( randomName(), ";#Delta#phi(#gamma,#slash{E}_{T});", len(binning)-1, array.array('d', binning) )
	fH3 = ROOT.TH1F( randomName(), ";#Delta#phi(#gamma,#slash{E}_{T});", len(binning)-1, array.array('d', binning) )
	fH2.SetLineColor(2)
	fH3.SetLineColor(3)
	for h in fH1, fH2, fH3:
		h.Sumw2()
		h.SetLineStyle(3)

	for e in ft:

		dPhi = e.photons[0].DeltaPhi( e.metPhi )
		if absolute:
			dPhi = fabs( dPhi )

		if e.met<10:
			fH1.Fill( dPhi )
		elif e.met < 100:
			fH2.Fill( dPhi )
		else:
			fH3.Fill( dPhi )


	for h in gH1, gH2, gH3, fH1, fH2, fH3:
		if h.Integral():
			h.Scale( 1./h.Integral(), "width" )

	mh = Multihisto()
	mh.addHisto( gH1, "met<10", draw="hist " )
	mh.addHisto( fH1, "met<10, loose", draw="hist " )
	mh.addHisto( gH2, "10<met<100", draw="hist " )
	mh.addHisto( fH2, "10<met<100, loose", draw="hist " )
	mh.addHisto( gH3, "100<met", draw="hist " )
	mh.addHisto( fH3, "100<met, loose", draw="hist " )


	c = ROOT.TCanvas()
	c.cd()
	mh.Draw()
	c.SaveAs("plots/deltaPhi_%s.pdf"%getSaveNameFromDatasets( filenames ))
Exemplo n.º 39
0
def inclusiveAndIsrSamples(fList1, fList2, saveAffix=""):

    cut = "[email protected]() && [email protected]()"
    treeName = "photonTree"
    plot = "met"

    if saveAffix == "pt130":
        cut += " && photons[0].pt>130"
        saveAffix = "_" + saveAffix

    mh = Multihisto()

    h1 = getHists(fList1, plot, cut)
    h1gen = getHists(fList1, plot, cut + "&&photons[0].isGen(0)")

    h2 = getHists(fList2, plot, cut)
    h2gen = getHists(fList2, plot, cut + "&&photons[0].isGen(0)")

    for h in h2, h2gen:
        h.SetLineColor(2)
    for h in h1gen, h2gen:
        h.SetLineStyle(2)

    for h in [h2, h2gen, h1, h1gen]:
        h.SetLabelSize(1.0 / 31.5562 / 0.502113, "xyz")
        h.SetTitleSize(1.0 / 31.5562 / 0.502113, "xyz")
        h.GetXaxis().SetTitleOffset(1.1)
        h.GetYaxis().SetTitleOffset(0.85)
        if plot == "met":
            h.GetXaxis().SetTitle("#met#text{ [GeV]}")

    abbr1 = shortName(fList1)
    abbr2 = shortName(fList2)

    mh = Multihisto()

    if "ZGamma" in fList1[0]:
        mh.setMaximum(10)
        mh.setMinimum(2e-4)
        mh.leg.SetFillStyle(0)

    mh.leg.SetX1(0.6)
    mh.leg.SetY1(0.6)
    mh.addHisto(h1, datasetToLatex(abbr1))
    mh.addHisto(h1gen, "#text{match to gen }#gamma")
    mh.addHisto(h2, datasetToLatex(abbr2))
    mh.addHisto(h2gen, "#text{match to gen }#gamma")

    mh.Draw()
    info.SetTextSize(1.0 / 31.5562 / 0.502113)
    info.Draw()

    if "pt130" in saveAffix:
        cutInfo = ROOT.TLatex(0.2, 0.8, "p_{T,#gamma}#geq#SI{130}{GeV}")
        cutInfo.SetNDC()
        info.SetTextSize(1.0 / 31.5562 / 0.502113)
        cutInfo.Draw()

    SavePad("inclusiveAndIsrSample_%s%s" % (abbr1, saveAffix))
    ROOT.gPad.SaveAs("/home/knut/master/documents/thesis/plots/inclusiveAndIsrSample_%s%s.tex" % (abbr1, saveAffix))
    correctTiksPlot("/home/knut/master/documents/thesis/plots/inclusiveAndIsrSample_%s%s.tex" % (abbr1, saveAffix))
Exemplo n.º 40
0
	S10scaledUsingS10 = s10.Clone( randomName() )
	S10scaledUsingS10.Divide( s10 )
	S10scaledUsingS10.Multiply( data )
	S10scaledUsingS10.SetLineStyle( 2 )

	S7scaledUsingS7 = s7.Clone( randomName() )
	S7scaledUsingS7.Divide( s7 )
	S7scaledUsingS7.Multiply( data )
	S7scaledUsingS7.SetLineStyle( 3 )

	S7scaledUsingS10 = s7.Clone( randomName() )
	S7scaledUsingS10.Divide( s10 )
	S7scaledUsingS10.Multiply( data )
	S7scaledUsingS10.SetLineStyle( 8 )

	mh = Multihisto()
	mh.setMaximum(0.07)
	mh.addHisto( data, "Data", draw="p" )
	mh.addHisto( s10, "S10 Scenario", draw="hist" )
	mh.addHisto( S10scaledUsingS10, "S10 scaled by data/S10", draw="hist")
	mh.addHisto( s7, "S7 Scenario", draw="hist")
	mh.addHisto( S7scaledUsingS7, "S7 scaled by data/S7", draw="hist")
	mh.addHisto( S7scaledUsingS10, "S7 scaled by data/S10", draw="hist")
	mh.Draw()
	mh.leg.SetX1( .65 )
	mh.leg.SetY1( .7 )
	mh.leg.SetX2( 1 )
	mh.leg.SetY2( 1 )

	ROOT.gPad.SetLogy(0)
	ROOT.gPad.SaveAs("plots/pileupScenarios.pdf")
Exemplo n.º 41
0
def finalDistributionData( plot ):

	# Sample names
	treeVersion = "31"
	wg = [ "slimWGamma_50_130_V03.%s_tree.root"%treeVersion, \
			"slimWGamma_130_inf_V03.%s_tree.root"%treeVersion ]
	tg = [ "slimTTGamma_V03.%s_tree.root"%treeVersion ]
	zgn = [ "slimZGammaNuNu_V03.%s_tree.root"%treeVersion ]
	zgll = [ "slimZGammaLL_V02.19b_tree.root" ]
	data = [ "PhotonHad%s_V03.%s_tree.root"%(x,treeVersion) for x in ["A","B","C","D" ] ]

	# additional ISR uncertainty
	ewkUncertainty = 0.11
	isrUncertaintyZ = 0.5
	isrUncertaintyW = 0.5
	isrUncertaintyT = 0.5
	isrUncertainty = 0.5


	leptonPtCut = 25 # only larger than 15 make sense here, since this is the reprocessing cut
	#commonCut = "([email protected]() || Max$(electrons.pt)<{0}) && ([email protected]() || Max$(muons.pt)<{0})".format(leptonPtCut)
	commonCut = "[email protected]() && [email protected]() && thisPt>0 && recoilChr > 0"

	# Compute the weights:
	weight2D = getMixedWeigthHisto( data, data, commonCut )
	attachWeightsToFiles( data, weight2D, "foWeights" )
	drawWeightHisto( weight2D, "Data", writeWeightFile=True )

	# Get Histograms
	dataHist = getHists( data, plot, commonCut )
	fgammaHist, fgammaWeightError = predictionHistos( data, plot, commonCut, modifyEmptyBins=False )

	egammaHist = multiDimFakeRate( data, plot, commonCut )
	egammaHistsys = setRelativeUncertainty( egammaHist.Clone(randomName()), ewkUncertainty )

	fsrZ = getHists( zgn, plot, commonCut+"&&genPhotons[0].pt>130" )
	fsrZll = getHists( zgll, plot, commonCut )
	if plot=="met":
		fsrZ2 = getHists( zgll, plot+"LL", commonCut+"&&genPhotons[0].pt<130" )
	else:
		fsrZ2 = getHists( zgll, plot, commonCut+"&&0" )
	fsrZ2.Scale( 20./(2.*3.363) )
	fsrW = getHists( wg, plot, commonCut )
	fsrT = getHists( tg, plot, commonCut )

	# apply common scale factor
	for h in fsrW, fsrT, fsrZ, fsrZ2, fsrZll:
		h.Scale(1.5)

	fsr = addHistos( [fsrT, fsrW, fsrZ, fsrZ2,fsrZll ] )
	fsr.SetLineColor(ROOT.kRed)
	fsrSys = setRelativeUncertainty( fsr, isrUncertainty )

	#signal1 = getMetHisto( "W", 900, 1720 )
	#signal2 = getMetHisto( "B", 1700, 1120 )
	signal1 = getHists( ["slimW_1700_720_375_V03.06_tree.root"], plot, commonCut )
	signal2 = getHists( ["slimW_900_1720_375_V03.06_tree.root"], plot, commonCut )
	signal3 = getHists( ["slimB_1300_1720_375_V03.06_tree.root"], plot, commonCut )
	signal4 = getHists( ["slimB_1700_1120_375_V03.06_tree.root"], plot, commonCut )
	for i, signal in enumerate([signal1, signal2, signal3, signal4]):
		signal.SetLineColor( ROOT.kGreen + i )
		signal.SetLineColor( ROOT.kBlue + i )
		#signal.SetLineStyle(5+i)


	# prettify histograms
	fgammaHist.SetLineColor(7)
	egammaHist.SetLineColor( 3 )
	fsrZ.SetLineColor( ROOT.kRed-7 )
	fsrW.SetLineColor( ROOT.kRed-9 )
	fsrT.SetLineColor( ROOT.kRed )

	mh = Multihisto()
	mh.setMinimum(0.2)
	mh.orderByIntegral = False
	mh.addHisto( fsr, "ISR", True )
	mh.addHisto( egammaHist, "e#rightarrow#gamma", True )
	mh.addHisto( fgammaHist, "Multijet", True )
	dataLegName = "Data"
	mh.addHisto( dataHist, dataLegName, draw="pe x0" )
	mh.addHisto( signal2, "Bino-like #chi_{1}^{0}", draw="hist" )
	mh.addHisto( signal1, "Wino-like #chi_{1}^{0}", draw="hist" )


	# get all SYSTEMATICAL uncertainties:
	systematicUncertHistStack = ROOT.THStack()
	systematicUncertHistStack.Add( fgammaWeightError )
	systematicUncertHistStack.Add( egammaHistsys )
	systematicUncertHistStack.Add( fsrSys )


	if plot == "met":
		writeDataCard( treeVersion, dataHist, fgammaHist, fgammaWeightError,
			egammaHist, egammaHistsys,
			fsr, fsrSys )

	# draw stuff
	luminosity = 19.7
	infoText = ROOT.TLatex(0,.96, "CMS Private Work - %sfb^{-1} #sqrt{s}=8TeV #geq1#gamma_{tight},#geq2jets"%luminosity )
	infoText.SetNDC()
	infoText.SetTextSize(.04)

	can = ROOT.TCanvas()
	mh.Draw()
	statUncert = mh.stack.GetStack().Last().Clone( randomName() )
	systUncert = systematicUncertHistStack.GetStack().Last().Clone( randomName() )
	totalUncert = statUncert.Clone( randomName() )
	for bin in range( totalUncert.GetNbinsX()+2 ):
		totalUncert.SetBinError( bin, statUncert.GetBinError(bin) |qPlus| systUncert.GetBinError(bin) )
	for h in statUncert, systUncert, totalUncert:
		h.SetMarkerSize(0)

	totalUncert.SetFillStyle(3002)
	totalUncert.SetFillColor(1)
	totalUncert.Draw("same e2")
	systUncert.SetFillStyle(3254)
	systUncert.SetFillColor(2)
	systUncert.Draw("same e2")
	statUncert.SetLineWidth(3)
	statUncert.SetLineColor(2)
	statUncert.Draw("same e x0")
	dataHist.Draw("same pe x0")

	from myRatio import Ratio
	r = Ratio( "Data / Bkg", dataHist, mh.stack.GetStack().Last(), systematicUncertHistStack.GetStack().Last() )
	r.draw(.5,1.5)

	infoText.Draw()

	SaveAs( can, "finalDistributionData_%s"%plot )
Exemplo n.º 42
0
    S10scaledUsingS10 = s10.Clone(randomName())
    S10scaledUsingS10.Divide(s10)
    S10scaledUsingS10.Multiply(data)
    S10scaledUsingS10.SetLineStyle(2)

    S7scaledUsingS7 = s7.Clone(randomName())
    S7scaledUsingS7.Divide(s7)
    S7scaledUsingS7.Multiply(data)
    S7scaledUsingS7.SetLineStyle(3)

    S7scaledUsingS10 = s7.Clone(randomName())
    S7scaledUsingS10.Divide(s10)
    S7scaledUsingS10.Multiply(data)
    S7scaledUsingS10.SetLineStyle(8)

    mh = Multihisto()
    mh.setMaximum(0.07)
    mh.addHisto(data, "Data", draw="p")
    mh.addHisto(s10, "S10 Scenario", draw="hist")
    mh.addHisto(S10scaledUsingS10, "S10 scaled by data/S10", draw="hist")
    mh.addHisto(s7, "S7 Scenario", draw="hist")
    mh.addHisto(S7scaledUsingS7, "S7 scaled by data/S7", draw="hist")
    mh.addHisto(S7scaledUsingS10, "S7 scaled by data/S10", draw="hist")
    mh.Draw()
    mh.leg.SetX1(.65)
    mh.leg.SetY1(.7)
    mh.leg.SetX2(1)
    mh.leg.SetY2(1)

    ROOT.gPad.SetLogy(0)
    ROOT.gPad.SaveAs("plots/pileupScenarios.pdf")
Exemplo n.º 43
0
def finalDistributionData(plot):

    # Sample names
    treeVersion = "31"
    wg = [ "slimWGamma_50_130_V03.%s_tree.root"%treeVersion, \
      "slimWGamma_130_inf_V03.%s_tree.root"%treeVersion ]
    tg = ["slimTTGamma_V03.%s_tree.root" % treeVersion]
    zgn = ["slimZGammaNuNu_V03.%s_tree.root" % treeVersion]
    zgll = ["slimZGammaLL_V02.19b_tree.root"]
    data = [
        "PhotonHad%s_V03.%s_tree.root" % (x, treeVersion)
        for x in ["A", "B", "C", "D"]
    ]

    # additional ISR uncertainty
    ewkUncertainty = 0.11
    isrUncertaintyZ = 0.5
    isrUncertaintyW = 0.5
    isrUncertaintyT = 0.5
    isrUncertainty = 0.5

    leptonPtCut = 25  # only larger than 15 make sense here, since this is the reprocessing cut
    #commonCut = "([email protected]() || Max$(electrons.pt)<{0}) && ([email protected]() || Max$(muons.pt)<{0})".format(leptonPtCut)
    commonCut = "[email protected]() && [email protected]() && thisPt>0 && recoilChr > 0"

    # Compute the weights:
    weight2D = getMixedWeigthHisto(data, data, commonCut)
    attachWeightsToFiles(data, weight2D, "foWeights")
    drawWeightHisto(weight2D, "Data", writeWeightFile=True)

    # Get Histograms
    dataHist = getHists(data, plot, commonCut)
    fgammaHist, fgammaWeightError = predictionHistos(data,
                                                     plot,
                                                     commonCut,
                                                     modifyEmptyBins=False)

    egammaHist = multiDimFakeRate(data, plot, commonCut)
    egammaHistsys = setRelativeUncertainty(egammaHist.Clone(randomName()),
                                           ewkUncertainty)

    fsrZ = getHists(zgn, plot, commonCut + "&&genPhotons[0].pt>130")
    fsrZll = getHists(zgll, plot, commonCut)
    if plot == "met":
        fsrZ2 = getHists(zgll, plot + "LL",
                         commonCut + "&&genPhotons[0].pt<130")
    else:
        fsrZ2 = getHists(zgll, plot, commonCut + "&&0")
    fsrZ2.Scale(20. / (2. * 3.363))
    fsrW = getHists(wg, plot, commonCut)
    fsrT = getHists(tg, plot, commonCut)

    # apply common scale factor
    for h in fsrW, fsrT, fsrZ, fsrZ2, fsrZll:
        h.Scale(1.5)

    fsr = addHistos([fsrT, fsrW, fsrZ, fsrZ2, fsrZll])
    fsr.SetLineColor(ROOT.kRed)
    fsrSys = setRelativeUncertainty(fsr, isrUncertainty)

    #signal1 = getMetHisto( "W", 900, 1720 )
    #signal2 = getMetHisto( "B", 1700, 1120 )
    signal1 = getHists(["slimW_1700_720_375_V03.06_tree.root"], plot,
                       commonCut)
    signal2 = getHists(["slimW_900_1720_375_V03.06_tree.root"], plot,
                       commonCut)
    signal3 = getHists(["slimB_1300_1720_375_V03.06_tree.root"], plot,
                       commonCut)
    signal4 = getHists(["slimB_1700_1120_375_V03.06_tree.root"], plot,
                       commonCut)
    for i, signal in enumerate([signal1, signal2, signal3, signal4]):
        signal.SetLineColor(ROOT.kGreen + i)
        signal.SetLineColor(ROOT.kBlue + i)
        #signal.SetLineStyle(5+i)

    # prettify histograms
    fgammaHist.SetLineColor(7)
    egammaHist.SetLineColor(3)
    fsrZ.SetLineColor(ROOT.kRed - 7)
    fsrW.SetLineColor(ROOT.kRed - 9)
    fsrT.SetLineColor(ROOT.kRed)

    mh = Multihisto()
    mh.setMinimum(0.2)
    mh.orderByIntegral = False
    mh.addHisto(fsr, "ISR", True)
    mh.addHisto(egammaHist, "e#rightarrow#gamma", True)
    mh.addHisto(fgammaHist, "Multijet", True)
    dataLegName = "Data"
    mh.addHisto(dataHist, dataLegName, draw="pe x0")
    mh.addHisto(signal2, "Bino-like #chi_{1}^{0}", draw="hist")
    mh.addHisto(signal1, "Wino-like #chi_{1}^{0}", draw="hist")

    # get all SYSTEMATICAL uncertainties:
    systematicUncertHistStack = ROOT.THStack()
    systematicUncertHistStack.Add(fgammaWeightError)
    systematicUncertHistStack.Add(egammaHistsys)
    systematicUncertHistStack.Add(fsrSys)

    if plot == "met":
        writeDataCard(treeVersion, dataHist, fgammaHist, fgammaWeightError,
                      egammaHist, egammaHistsys, fsr, fsrSys)

    # draw stuff
    luminosity = 19.7
    infoText = ROOT.TLatex(
        0, .96,
        "CMS Private Work - %sfb^{-1} #sqrt{s}=8TeV #geq1#gamma_{tight},#geq2jets"
        % luminosity)
    infoText.SetNDC()
    infoText.SetTextSize(.04)

    can = ROOT.TCanvas()
    mh.Draw()
    statUncert = mh.stack.GetStack().Last().Clone(randomName())
    systUncert = systematicUncertHistStack.GetStack().Last().Clone(
        randomName())
    totalUncert = statUncert.Clone(randomName())
    for bin in range(totalUncert.GetNbinsX() + 2):
        totalUncert.SetBinError(
            bin,
            statUncert.GetBinError(bin) | qPlus | systUncert.GetBinError(bin))
    for h in statUncert, systUncert, totalUncert:
        h.SetMarkerSize(0)

    totalUncert.SetFillStyle(3002)
    totalUncert.SetFillColor(1)
    totalUncert.Draw("same e2")
    systUncert.SetFillStyle(3254)
    systUncert.SetFillColor(2)
    systUncert.Draw("same e2")
    statUncert.SetLineWidth(3)
    statUncert.SetLineColor(2)
    statUncert.Draw("same e x0")
    dataHist.Draw("same pe x0")

    from myRatio import Ratio
    r = Ratio("Data / Bkg", dataHist,
              mh.stack.GetStack().Last(),
              systematicUncertHistStack.GetStack().Last())
    r.draw(.5, 1.5)

    infoText.Draw()

    SaveAs(can, "finalDistributionData_%s" % plot)
Exemplo n.º 44
0
	bkg["zll"] = { "files": ["slimZGammaLL_V02.%s_tree.root"%treeVersion], "title": "#gammaZ#rightarrow#gammall", "color": 2 }
	bkg["tt"] = { "files": ["slimTTGamma_V03.%s_tree.root"%treeVersion], "title": "#gammat#bar{t}", "color": ROOT.kBlue }
	bkg["wjets"] = { "files": ["slimWJets_250_300_V03.24_tree.root", "slimWJets_300_400_V03.24_tree.root", "slimWJets_400_inf_V03.24_tree.root" ], "title": "W", "color": ROOT.kGreen+4 }
	bkg["wgamma"] = { "files": ["slimWGamma_130_inf_V03.24_tree.root", "slimWGamma_50_130_V03.24_tree.root" ], "title": "#gammaW", "color": ROOT.kGreen-4 }
	#bkg["qcd"] = { "files": ["slimQCD_1000_inf_V03.24_tree.root", "slimQCD_250_500_V03.24_tree.root", "slimQCD_500_1000_V03.24_tree.root"], "title":"Multijet", "color": ROOT.kCyan+3 }

	nestedBkgFiles = [ bkg[a]["files"] for a in bkg.keys()]
	bkgFiles = [item for sublist in nestedBkgFiles for item in sublist]

	kFactor = getkFactor( dataFiles, bkgFiles, opts.plot, chi2Cut )

	#signal = getHists( ["slimW_1700_720_375_V03.24_tree.root" ], opts.plot, cut )
	#signal.SetLineColor( ROOT.kGreen )
	#signal.SetLineWidth(2)

	mh = Multihisto()
	mh.setMinimum(0)
	mh.addHisto( data, "Data", draw="pe" )
	for name, d in bkg.iteritems():
		histo = getHists( d["files"], opts.plot, cut )
		histo.SetLineColor( d["color"] )
		histo.Scale( kFactor )
		mh.addHisto( histo, d["title"], True )

	#mh.addHisto( signal, "Wino", False )

	#combiBkg = getCombinatoricalBkg( dataFiles, opts.plot )
	#combiBkg.SetLineWidth(2)
	#combiBkg.SetLineColor( ROOT.kBlue )
	#combiBkg.Scale( data.Integral(0, data.FindBin(70), "width") / combiBkg.Integral(0,data.FindBin(70),"width"))
	#mh.addHisto( combiBkg, "bkg", draw="hist e" )
Exemplo n.º 45
0
def zGammaCut(plot="photons[0].pt", merge=False):
    cut = "[email protected]() && [email protected]()"

    nunuTree = readTree("slimZGammaNuNu_V03.19b_tree.root", "photonTree")
    llTree = readTree("slimZGammaLL_V02.19b_tree.root", "photonTree")
    zIncTree = readTree("slimZGamma_V03.18_tree.root", "photonTree")

    nBins = range(60, 500, 10) if plot == "photons[0].pt" or plot == "genPhotons[0].pt" else readAxisConf(plot)[2]

    h_nunu = getHisto(nunuTree, plot, cut + "&&genPhotons[0].pt>130", nBins=nBins, color=2)
    h_ll = getHisto(llTree, plot, cut, nBins=nBins, color=5)
    h_zInc = getHisto(zIncTree, plot, cut, nBins=nBins)

    llTree.AddFriend("photonTreeAddVariables", llTree.GetFile().GetName())

    llPlot = "metLL" if plot == "met" else plot

    zMod = getHisto(llTree, llPlot, "genPhotons[0].pt<130", nBins=nBins, color=4)
    zMod.Scale(20.0 / (2.0 * 3.363))

    mh = Multihisto()
    mh.orderByIntegral = False
    mh.setMinimum(0.01)

    mh.addHisto(h_nunu, "#gammaZ#rightarrow#gamma#nu#nu(p_{T#gamma}^{gen}#geq130GeV)", draw="e", toStack=True)
    mh.addHisto(zMod, "ll to #slash{E}_{T}", toStack=True)
    mh.addHisto(h_ll, "#gammaZ#rightarrow#gammall", draw="e", toStack=True)
    mh.addHisto(h_zInc, "#gammaZ", draw="e")

    if merge:
        h_nunuPart = getHisto(nunuTree, plot, cut + "&&genPhotons[0].pt>=130", nBins=nBins, color=6)
        h_zIncPart = getHisto(zIncTree, plot, cut + "&&genPhotons[0].pt<130", nBins=nBins, color=6)
        merged = addHistos([h_nunuPart, h_zIncPart])
        mh.addHisto(merged, "merged", draw="e")

    mh.Draw()
    total = mh.stack.GetStack().Last().Clone(randomName())
    total.SetFillStyle(3002)
    total.SetFillColor(1)
    total.Draw("same e2")

    if plot == "photons[0].pt":
        l = ROOT.TLine(130, 0, 130, 1)
        l.Draw()

    if merge:
        plot += "_merged"
    SavePad("zGammaCut_%s" % plot)
Exemplo n.º 46
0
def drawGenComposition(treeName, sample):
    mh = Multihisto()
    mh.addHisto(sample.plot(treeName, cut="photons[0].isGen(0)", color=2),
                "gen #gamma")
    mh.addHisto(sample.plot(treeName, cut="photons[0].isGen(1)", color=3),
                "gen e")
    mh.addHisto(sample.plot(treeName, cut="photons[0].isGen(2)", color=4),
                "gen hadron")
    mh.addHisto(sample.plot(treeName, cut="1", color=1), "inclusive")
    can = ROOT.TCanvas()
    can.cd()
    mh.Draw()
    info = PlotCaption(treeName=treeName)
    info.Draw()
    allDatasetAbbr = sample.datasetAbbr
    plot = "met"
    SaveAs(can, "composition_%s_%s_%s" % (treeName, plot, allDatasetAbbr))
Exemplo n.º 47
0
def inclusiveAndIsrSamples(fList1, fList2, saveAffix=""):

    cut = "[email protected]() && [email protected]()"
    treeName = "photonTree"
    plot = "met"

    if saveAffix == "pt130":
        cut += " && photons[0].pt>130"
        saveAffix = "_" + saveAffix

    mh = Multihisto()

    h1 = getHists(fList1, plot, cut)
    h1gen = getHists(fList1, plot, cut + "&&photons[0].isGen(0)")

    h2 = getHists(fList2, plot, cut)
    h2gen = getHists(fList2, plot, cut + "&&photons[0].isGen(0)")

    for h in h2, h2gen:
        h.SetLineColor(2)
    for h in h1gen, h2gen:
        h.SetLineStyle(2)

    for h in [h2, h2gen, h1, h1gen]:
        h.SetLabelSize(1. / 31.5562 / 0.502113, "xyz")
        h.SetTitleSize(1. / 31.5562 / 0.502113, "xyz")
        h.GetXaxis().SetTitleOffset(1.1)
        h.GetYaxis().SetTitleOffset(0.85)
        if plot == "met":
            h.GetXaxis().SetTitle("#met#text{ [GeV]}")

    abbr1 = shortName(fList1)
    abbr2 = shortName(fList2)

    mh = Multihisto()

    if "ZGamma" in fList1[0]:
        mh.setMaximum(10)
        mh.setMinimum(2e-4)
        mh.leg.SetFillStyle(0)

    mh.leg.SetX1(0.6)
    mh.leg.SetY1(0.6)
    mh.addHisto(h1, datasetToLatex(abbr1))
    mh.addHisto(h1gen, "#text{match to gen }#gamma")
    mh.addHisto(h2, datasetToLatex(abbr2))
    mh.addHisto(h2gen, "#text{match to gen }#gamma")

    mh.Draw()
    info.SetTextSize(1. / 31.5562 / 0.502113)
    info.Draw()

    if "pt130" in saveAffix:
        cutInfo = ROOT.TLatex(.2, .8, "p_{T,#gamma}#geq#SI{130}{GeV}")
        cutInfo.SetNDC()
        info.SetTextSize(1. / 31.5562 / 0.502113)
        cutInfo.Draw()

    SavePad("inclusiveAndIsrSample_%s%s" % (abbr1, saveAffix))
    ROOT.gPad.SaveAs(
        "/home/knut/master/documents/thesis/plots/inclusiveAndIsrSample_%s%s.tex"
        % (abbr1, saveAffix))
    correctTiksPlot(
        "/home/knut/master/documents/thesis/plots/inclusiveAndIsrSample_%s%s.tex"
        % (abbr1, saveAffix))
Exemplo n.º 48
0
def drawStackedBackground( plot, treeName, listOfFiles, sumBinned, order=False ):

	tightCut = " photons[0].sigmaIetaIeta<0.011 && photons[0].chargedIso<0.7 && photons[0].neutralIso < 0.4+0.04*photons[0].pt && photons[0].photonIso < 0.5+0.005*photons[0].pt && photons[0].r9<0.9"
	cut = "[email protected]() && [email protected]()"
	#cut = cut +"&&" + tightCut
	cut = "std::abs(photons[0].eta)>1.4442"

	# if a data histogram is present, the mc integral will scaled to data
	mcHists = []
	dataHists = []
	for fileName in listOfFiles:
		datasetAbbr = getDatasetAbbr( fileName )
		try:
			color = colors[datasetAbbr]
		except:
			color = 1
		tree = readTree( fileName, treeName )
		histo = getHisto( tree, plot, color=color, cut=cut )
		if "PhotonHad" in fileName:
			dataHists.append( (datasetAbbr, histo ) )
		else:
			mcHists.append( ( datasetAbbr, histo ) )

	# merge datahists if there
	dataHist = addHistos( [histo for datasetAbbr, histo in dataHists] ) if dataHists else None

	scale = 1.*dataHist.Integral()/addHistos( [histo for datasetAbbr, histo in mcHists] ).Integral() if dataHists else 1
	scale = 1.

	# combine MC datasets
	if sumBinned:
		for combiAbbr, abbrList in combinedDatasets.iteritems():
			if set(abbrList).issubset( set( [ a for a, h in mcHists ] ) ):
				indices = []
				for a,b in mcHists:
					if a in abbrList:
						indices.append(mcHists.index((a,b)))
				#print "a valid combination was found"
				histosToAdd = [ h for a,h in mcHists if a in abbrList ]
				thisSum = addHistos( histosToAdd )
				mcHists = [ (a,h) for a,h in mcHists if a not in abbrList]
				mcHists.insert(min(indices),(combiAbbr,thisSum))

	mh = Multihisto()
	mh.setMinimum(0.01)
	mh.leg.SetFillStyle(0)
	mh.leg.SetNColumns(2)
	mh.orderByIntegral = order
	if dataHist:
		mh.addHisto( dataHist, "Data", draw="ep" )

	for abbr, hist in mcHists:
		hist.Scale( scale )

		mh.addHisto( hist, datasetToLatex(abbr), toStack=True, draw="hist" )

	egammaHist = True
	if egammaHist:
		egammaHist = multiDimFakeRate( [ filename for filename in listOfFiles if "PhotonHad" in filename ], plot, cut )
		egammaHist.SetLineColor(ROOT.kGreen )
		mh.addHisto( egammaHist, "e#rightarrow#gamma", toStack=True )

	#totalBG = addHistos( [ h for abbr, h in mcHists ] )
	#totalBG.SetLineColor(2)
	#mh.addHisto( totalBG, "SM Simulation", toStack=False, draw="hist" )

	# add signal histos
	#signalFiles = ["slimW_1000_1020_375_V02.44_tree.root", "slimW_1200_1120_375_V02.44_tree.root"]
	signalFiles = ["slimW_1200_1120_375_V02.44_tree.root"]
	signalFiles = ["slimW_1700_720_375_V03.22_tree.root"]
	for iColor, sf in enumerate(signalFiles):
		tree = readTree( sf, treeName )
		histo = getHisto( tree, plot, color=ROOT.kBlue+iColor, cut=cut )
		#mh.addHisto( histo, datasetToLatex(getDatasetAbbr(sf)), draw="hist" )
		mh.addHisto( histo, "Signal", draw="hist" )

	infoText = ROOT.TLatex(0,.97, "#text{CMS Private Work  }#geq1#gamma_{#text{pixel}},#geq2#text{jets}" )
	infoText.SetNDC()
	infoText.SetTextSize(0.05)

	can = ROOT.TCanvas()
	can.cd()
	mh.Draw()

	infoText.Draw()
	#if dataHist:
	#	from myRatio import Ratio
	#	den = totalBG
		#den = mh.stack.GetStack().Last().Clone( randomName() )
	#	den.SetLineColor(2)
	#	r = Ratio( "Data/Sim.", dataHist, den )
	#	r.draw(0,2)

	allDatasetAbbr = getSaveNameFromDatasets( listOfFiles )
	SaveAs( can, "stackedHisto_%s_%s_%s"%(treeName, plot,allDatasetAbbr) )
Exemplo n.º 49
0
def drawStackedBackground(plot, treeName, listOfFiles, sumBinned, order=False):

    tightCut = " photons[0].sigmaIetaIeta<0.011 && photons[0].chargedIso<0.7 && photons[0].neutralIso < 0.4+0.04*photons[0].pt && photons[0].photonIso < 0.5+0.005*photons[0].pt && photons[0].r9<0.9"
    cut = "[email protected]() && [email protected]()"
    #cut = cut +"&&" + tightCut
    cut = "std::abs(photons[0].eta)>1.4442"

    # if a data histogram is present, the mc integral will scaled to data
    mcHists = []
    dataHists = []
    for fileName in listOfFiles:
        datasetAbbr = getDatasetAbbr(fileName)
        try:
            color = colors[datasetAbbr]
        except:
            color = 1
        tree = readTree(fileName, treeName)
        histo = getHisto(tree, plot, color=color, cut=cut)
        if "PhotonHad" in fileName:
            dataHists.append((datasetAbbr, histo))
        else:
            mcHists.append((datasetAbbr, histo))

    # merge datahists if there
    dataHist = addHistos([histo for datasetAbbr, histo in dataHists
                          ]) if dataHists else None

    scale = 1. * dataHist.Integral() / addHistos(
        [histo
         for datasetAbbr, histo in mcHists]).Integral() if dataHists else 1
    scale = 1.

    # combine MC datasets
    if sumBinned:
        for combiAbbr, abbrList in combinedDatasets.iteritems():
            if set(abbrList).issubset(set([a for a, h in mcHists])):
                indices = []
                for a, b in mcHists:
                    if a in abbrList:
                        indices.append(mcHists.index((a, b)))
                #print "a valid combination was found"
                histosToAdd = [h for a, h in mcHists if a in abbrList]
                thisSum = addHistos(histosToAdd)
                mcHists = [(a, h) for a, h in mcHists if a not in abbrList]
                mcHists.insert(min(indices), (combiAbbr, thisSum))

    mh = Multihisto()
    mh.setMinimum(0.01)
    mh.leg.SetFillStyle(0)
    mh.leg.SetNColumns(2)
    mh.orderByIntegral = order
    if dataHist:
        mh.addHisto(dataHist, "Data", draw="ep")

    for abbr, hist in mcHists:
        hist.Scale(scale)

        mh.addHisto(hist, datasetToLatex(abbr), toStack=True, draw="hist")

    egammaHist = True
    if egammaHist:
        egammaHist = multiDimFakeRate(
            [filename for filename in listOfFiles if "PhotonHad" in filename],
            plot, cut)
        egammaHist.SetLineColor(ROOT.kGreen)
        mh.addHisto(egammaHist, "e#rightarrow#gamma", toStack=True)

    #totalBG = addHistos( [ h for abbr, h in mcHists ] )
    #totalBG.SetLineColor(2)
    #mh.addHisto( totalBG, "SM Simulation", toStack=False, draw="hist" )

    # add signal histos
    #signalFiles = ["slimW_1000_1020_375_V02.44_tree.root", "slimW_1200_1120_375_V02.44_tree.root"]
    signalFiles = ["slimW_1200_1120_375_V02.44_tree.root"]
    signalFiles = ["slimW_1700_720_375_V03.22_tree.root"]
    for iColor, sf in enumerate(signalFiles):
        tree = readTree(sf, treeName)
        histo = getHisto(tree, plot, color=ROOT.kBlue + iColor, cut=cut)
        #mh.addHisto( histo, datasetToLatex(getDatasetAbbr(sf)), draw="hist" )
        mh.addHisto(histo, "Signal", draw="hist")

    infoText = ROOT.TLatex(
        0, .97,
        "#text{CMS Private Work  }#geq1#gamma_{#text{pixel}},#geq2#text{jets}")
    infoText.SetNDC()
    infoText.SetTextSize(0.05)

    can = ROOT.TCanvas()
    can.cd()
    mh.Draw()

    infoText.Draw()
    #if dataHist:
    #	from myRatio import Ratio
    #	den = totalBG
    #den = mh.stack.GetStack().Last().Clone( randomName() )
    #	den.SetLineColor(2)
    #	r = Ratio( "Data/Sim.", dataHist, den )
    #	r.draw(0,2)

    allDatasetAbbr = getSaveNameFromDatasets(listOfFiles)
    SaveAs(can, "stackedHisto_%s_%s_%s" % (treeName, plot, allDatasetAbbr))
Exemplo n.º 50
0
def compareTrees( plot="photons.pt", filenames=["slimAllQCD_V02.28_tree.root"], drawRatio=False ):
	cut = "1"
	#cut = plot+">110"
	#cut = "!photons[0].isGen(0)"
	#cut = "ht < 600"

	gH = getHistoFromFiles( plot, "photonTree", filenames, cut )
	fH = getHistoFromFiles( plot, "photonJetTree", filenames, cut, color=2 )

	weight2D = getMixedWeigthHisto( filenames, filenames, cut, control=True, fillEmptyBins=False )
	for filename in filenames:
		fTree = readTree( filename, "photonJetTree" )
		writeWeight2DToFile( filename, fTree, weight2D, "foWeightsCompare" )
	fgammaHist, fgammaWeightError = qcdPredictionHistos( filenames, plot, cut, True )
	for bin in range( fgammaHist.GetNbinsX()+2 ):
		fgammaHist.SetBinError( bin, sqrt( fgammaHist.GetBinError(bin)**2 + fgammaWeightError.GetBinContent(bin)**2 ) )

	fH = fgammaHist


	for h in [gH, fH]:
		h.Scale( 1./h.Integral() )
		h.SetMarkerSize(0)
		h.GetXaxis().SetTitleOffset( 1.03 )
		h.GetYaxis().SetTitleOffset( 1.5 )
		h.GetXaxis().SetLabelSize( 0.0633790992496425 )
		h.GetXaxis().SetTitleSize( 0.0633790992496425 )
		h.GetYaxis().SetLabelSize( 0.0633790992496425 )
		h.GetYaxis().SetTitleSize( 0.0633790992496425 )
		h.GetYaxis().SetLabelOffset(0)

		if plot == "photons[0].pt":
			h.GetXaxis().SetTitle( "$p_{T}$ [GeV]" )
		if plot == "photons[0].ptJet()":
			h.GetXaxis().SetTitle( "$p_{T^*}$ [GeV]" )


	mh = Multihisto()
	mh.leg.SetX1(0.608)
	mh.leg.SetX2(0.95)
	mh.addHisto( gH, "#gamma_{#text{tight}}", draw="hist e" )
	mh.addHisto( fH, "#gamma_{#text{loose}}", draw="hist e" )

	can = ROOT.TCanvas()
	#can.SetBottomMargin(0)
	#can.SetTopMargin(0)
	#can.SetRightMargin(0)
	can.SetLeftMargin(0.19)
	can.cd()
	mh.Draw()

	pc1 = ROOT.TLatex(0,.96, "CMS Private Work")
	pc2 = ROOT.TLatex( .51,.96, "\SI{19.8}{fb^{-1}} #sqrt{s}=\SI{8}{TeV}")
	for pc in [pc1, pc2]:
		pc.SetNDC()
		pc.SetTextSize(0.06311227345609463)
		pc.Draw()


	if drawRatio:
		from myRatio import Ratio
		r = Ratio( "#gamma/#gamma_{jet}", gH, fH )
		r.draw()

	#can.SetFillColor(ROOT.kGreen)
	SavePad( "compare2_%s_%s"%(plot,shortName( filenames )) )
	ROOT.gPad.SaveAs("~/master/documents/thesis/plots/compare_%s_%s.tex"%(manipulateSaveName(plot),shortName( filenames )) )
	correctTiksPlot("/home/knut/master/documents/thesis/plots/compare_%s_%s.tex"%(manipulateSaveName(plot),shortName( filenames )) )
	ROOT.SetOwnership( can, False )
Exemplo n.º 51
0
        "#gammaW",
        "color":
        ROOT.kGreen - 4
    }
    #bkg["qcd"] = { "files": ["slimQCD_1000_inf_V03.24_tree.root", "slimQCD_250_500_V03.24_tree.root", "slimQCD_500_1000_V03.24_tree.root"], "title":"Multijet", "color": ROOT.kCyan+3 }

    nestedBkgFiles = [bkg[a]["files"] for a in bkg.keys()]
    bkgFiles = [item for sublist in nestedBkgFiles for item in sublist]

    kFactor = getkFactor(dataFiles, bkgFiles, opts.plot, chi2Cut)

    #signal = getHists( ["slimW_1700_720_375_V03.24_tree.root" ], opts.plot, cut )
    #signal.SetLineColor( ROOT.kGreen )
    #signal.SetLineWidth(2)

    mh = Multihisto()
    mh.setMinimum(0)
    mh.addHisto(data, "Data", draw="pe")
    for name, d in bkg.iteritems():
        histo = getHists(d["files"], opts.plot, cut)
        histo.SetLineColor(d["color"])
        histo.Scale(kFactor)
        mh.addHisto(histo, d["title"], True)

    #mh.addHisto( signal, "Wino", False )

    #combiBkg = getCombinatoricalBkg( dataFiles, opts.plot )
    #combiBkg.SetLineWidth(2)
    #combiBkg.SetLineColor( ROOT.kBlue )
    #combiBkg.Scale( data.Integral(0, data.FindBin(70), "width") / combiBkg.Integral(0,data.FindBin(70),"width"))
    #mh.addHisto( combiBkg, "bkg", draw="hist e" )
Exemplo n.º 52
0
def drawPhi(filenames):
    t = readTree(filenames[0], "photonTree")
    for f in filenames[1:]:
        t.Add("%s/photonTree" % f)

    absolute = True

    label, unit, binning = readAxisConf("photons[0].phi")

    if absolute:
        binning = [x for x in binning if x >= 0]

    import array
    gH1 = ROOT.TH1F(randomName(), ";#Delta#phi(#gamma,#slash{E}_{T});",
                    len(binning) - 1, array.array('d', binning))
    gH2 = ROOT.TH1F(randomName(), ";#Delta#phi(#gamma,#slash{E}_{T});",
                    len(binning) - 1, array.array('d', binning))
    gH3 = ROOT.TH1F(randomName(), ";#Delta#phi(#gamma,#slash{E}_{T});",
                    len(binning) - 1, array.array('d', binning))
    gH2.SetLineColor(2)
    gH3.SetLineColor(3)
    for h in gH1, gH2, gH3:
        h.Sumw2()

    from math import fabs
    for e in t:

        dPhi = e.photons[0].DeltaPhi(e.metPhi)
        if absolute:
            dPhi = fabs(dPhi)

        if e.met < 10:
            gH1.Fill(dPhi)
        elif e.met < 100:
            gH2.Fill(dPhi)
        else:
            gH3.Fill(dPhi)

    ft = readTree(filenames[0], "photonJetTree")
    for f in filenames[1:]:
        ft.Add("%s/photonJetTree" % f)

    cutStr = "photons[0].chargedIso/100<2.6 && photons[0].neutralIso/100<3.5+0.04*photons[0].pt && photons[0].photonIso/100<1.3+0.005*photons[0].pt"
    cutStr += "&& (photons[0].chargedIso>0 || photons[0].neutralIso>0 || photons[0].photonIso>0)"
    ft = ft.CopyTree(cutStr)

    fH1 = ROOT.TH1F(randomName(), ";#Delta#phi(#gamma,#slash{E}_{T});",
                    len(binning) - 1, array.array('d', binning))
    fH2 = ROOT.TH1F(randomName(), ";#Delta#phi(#gamma,#slash{E}_{T});",
                    len(binning) - 1, array.array('d', binning))
    fH3 = ROOT.TH1F(randomName(), ";#Delta#phi(#gamma,#slash{E}_{T});",
                    len(binning) - 1, array.array('d', binning))
    fH2.SetLineColor(2)
    fH3.SetLineColor(3)
    for h in fH1, fH2, fH3:
        h.Sumw2()
        h.SetLineStyle(3)

    for e in ft:

        dPhi = e.photons[0].DeltaPhi(e.metPhi)
        if absolute:
            dPhi = fabs(dPhi)

        if e.met < 10:
            fH1.Fill(dPhi)
        elif e.met < 100:
            fH2.Fill(dPhi)
        else:
            fH3.Fill(dPhi)

    for h in gH1, gH2, gH3, fH1, fH2, fH3:
        if h.Integral():
            h.Scale(1. / h.Integral(), "width")

    mh = Multihisto()
    mh.addHisto(gH1, "met<10", draw="hist ")
    mh.addHisto(fH1, "met<10, loose", draw="hist ")
    mh.addHisto(gH2, "10<met<100", draw="hist ")
    mh.addHisto(fH2, "10<met<100, loose", draw="hist ")
    mh.addHisto(gH3, "100<met", draw="hist ")
    mh.addHisto(fH3, "100<met, loose", draw="hist ")

    c = ROOT.TCanvas()
    c.cd()
    mh.Draw()
    c.SaveAs("plots/deltaPhi_%s.pdf" % getSaveNameFromDatasets(filenames))
Exemplo n.º 53
0
def drawStackedBackground( plot, treeName, listOfFiles, sumBinned, order=False ):

	cut = "[email protected]() && [email protected]()"

	# if a data histogram is present, the mc integral will scaled to data
	mcHists = []
	dataHists = []
	for fileName in listOfFiles:
		datasetAbbr = getDatasetAbbr( fileName )
		try:
			color = colors[datasetAbbr]
		except:
			color = 1
		tree = readTree( fileName, treeName )
		histo = getHisto( tree, plot, color=color, cut=cut )
		if "PhotonHad" in fileName:
			dataHists.append( (datasetAbbr, histo ) )
		else:
			mcHists.append( ( datasetAbbr, histo ) )

	# merge datahists if there
	dataHist = addHistos( [histo for datasetAbbr, histo in dataHists] ) if dataHists else None

	scale = 1.*dataHist.Integral()/addHistos( [histo for datasetAbbr, histo in mcHists] ).Integral() if dataHists else 1
	scale = 1.

	# combine MC datasets
	if sumBinned:
		for combiAbbr, abbrList in combinedDatasets.iteritems():
			if set(abbrList).issubset( set( [ a for a, h in mcHists ] ) ):
				#print "a valid combination was found"
				histosToAdd = [ h for a,h in mcHists if a in abbrList ]
				thisSum = addHistos( histosToAdd )
				mcHists = [ (a,h) for a,h in mcHists if a not in abbrList]+[(combiAbbr,thisSum)]


	mh = Multihisto()
	mh.setMinimum(0.01)
	mh.leg.SetX1NDC(0.5)
	mh.leg.SetY1NDC(0.5)
	mh.orderByIntegral = order
	if dataHist:
		mh.addHisto( dataHist, "Data", draw="e0" )

	for abbr, hist in mcHists:
		hist.Scale( scale )
		mh.addHisto( hist, datasetToLatex(abbr), toStack=True, draw="hist" )

	# add signal histos
	#signalFiles = ["slimW_1000_1020_375_V02.44_tree.root", "slimW_1200_1120_375_V02.44_tree.root"]
	signalFiles = ["slimW_1200_1120_375_V02.44_tree.root"]
	signalFiles = []
	for iColor, sf in enumerate(signalFiles):
		tree = readTree( sf, treeName )
		histo = getHisto( tree, plot, color=ROOT.kMagenta+iColor, cut=cut )
		mh.addHisto( histo, datasetToLatex(getDatasetAbbr(sf)), draw="hist" )

	can = ROOT.TCanvas()
	can.cd()
	mh.Draw()
	info = PlotCaption(treeName=treeName)
	info.Draw()
	if dataHist:
		from myRatio import Ratio
		den = mh.stack.GetStack().Last().Clone( randomName() )
		den.SetLineColor(2)
		r = Ratio( "Data/Sim", dataHist, den )
		r.draw(0,2)

	allDatasetAbbr = getSaveNameFromDatasets( listOfFiles )
	SaveAs( can, "stackedHisto_%s_%s_%s"%(treeName, plot,allDatasetAbbr) )
Exemplo n.º 54
0
def qcdCorrelation( filenames, plot ):
	signalCut = "met>=100"
	controlCut = "!(%s)"%signalCut
	commonCut = " && photons[0].ptJet()>100 && photons[0].ptJet()<120 "

	gControlHist = photonHisto( filenames, "photonTree", plot, controlCut+commonCut, True )
	fControlHist = photonHisto( filenames, "photonJetTree", plot, controlCut+commonCut, True )
	gSignalHist = photonHisto( filenames, "photonTree", plot, signalCut+commonCut, True )
	fSignalHist = photonHisto( filenames, "photonJetTree", plot, signalCut+commonCut, True )
	gSignalHist.SetLineColor(2)
	fSignalHist.SetLineColor(2)
	fSignalHist.SetLineStyle(2)
	fControlHist.SetLineStyle(2)

	for h in [gControlHist, fControlHist, gSignalHist, fSignalHist]:
		h.Scale( 1./h.Integral() )
		h.SetMarkerSize(0)
		pass

	mh = Multihisto()
	mh.addHisto( gControlHist, "Control #gamma", draw="hist e" )
	mh.addHisto( fControlHist, "Control #gamma_{jet}",draw="hist e" )
	mh.addHisto( gSignalHist, "Signal #gamma",draw="hist e" )
	mh.addHisto( fSignalHist, "Signal #gamma_{jet}",draw="hist e" )



	can = ROOT.TCanvas()
	can.cd()
	mh.Draw()
	info = PlotCaption()
	info.Draw()

	abbrs = mergeDatasetAbbr( [ getDatasetAbbr(x) for x in filenames ] )

	SaveAs( can, "correlation_%s_%s"%("".join(abbrs),plot ) )
Exemplo n.º 55
0
def finalDistributionMC( plot ):

	# Sample names
	treeVersion = 12
	g1 = "slimGJets_200_400_V03.%s_tree.root"%treeVersion
	g2 = "slimGJets_400_inf_V03.%s_tree.root"%treeVersion
	q1 = "slimQCD_250_500_V03.%s_tree.root"%treeVersion
	q2 = "slimQCD_500_1000_V03.%s_tree.root"%treeVersion
	q3 = "slimQCD_1000_inf_V03.%s_tree.root"%treeVersion

	tt = "slimTTJets_V03.%s_tree.root"%treeVersion
	w1 = "slimWJets_250_300_V03.%s_tree.root"%treeVersion
	w2 = "slimWJets_300_400_V03.%s_tree.root"%treeVersion
	w3 = "slimWJets_400_inf_V03.%s_tree.root"%treeVersion


	wg1 = "slimWGamma_50_130_V03.%s_tree.root"%treeVersion
	wg2 = "slimWGamma_130_inf_V03.%s_tree.root"%treeVersion
	tg = "slimTTGamma_V03.%s_tree.root"%treeVersion
	zgn = "slimZGammaNuNu_V03.%s_tree.root"%treeVersion
	data = [ g1, g2, q1, q2, q3, tt, w1, w2, w3, zgn, wg1,wg2,tg ]

	# additional ISR uncertainty
	ewkUncertainty = 0.11
	isrUncertaintyZ = 0.5
	isrUncertaintyW = 0.5
	isrUncertaintyT = 0.5
	isrUncertainty = 0.5


	leptonPtCut = 25 # only larger than 15 make sense here, since this is the reprocessing cut
	commonCut = "([email protected]() || Max$(electrons.pt)<{0}) && ([email protected]() || Max$(muons.pt)<{0})".format(leptonPtCut)
	#commonCut = "[email protected]() && [email protected]()"

	# Compute the weights:
	#weight2D = getMixedWeigthHisto( data, data, commonCut )
	#attachWeightsToFiles( data, weight2D, "foWeights" )
	#from qcdClosure import drawWeightHisto
	#drawWeightHisto( weight2D, "MC" )

	# Get Histograms
	dataHist = getHists( data, plot, commonCut )
	fgammaHist, fgammaWeightError = predictionHistos( data, plot, commonCut, modifyEmptyBins=False )

	egammaHist = multiDimFakeRate( data, plot, commonCut, isData=False )
	egammaHistsys = setRelativeUncertainty( egammaHist.Clone(randomName()), ewkUncertainty )

	fsrZ = getHists( [zgn], plot, commonCut )
	fsrZsys = setRelativeUncertainty( fsrZ, isrUncertaintyZ  )
	fsrW = getHists( [wg1,wg2], plot, commonCut )
	fsrWsys = setRelativeUncertainty( fsrW, isrUncertaintyW  )
	fsrT = getHists( [tg], plot, commonCut )
	fsrTsys = setRelativeUncertainty( fsrT, isrUncertaintyT  )
	fsr = addHistos( [fsrT, fsrW, fsrZ ] )
	fsrSys = setRelativeUncertainty( fsr, isrUncertainty )

	#signal1 = getMetHisto( "W", 900, 1720 )
	#signal2 = getMetHisto( "B", 1700, 1120 )
	signal1 = getHists( ["slimW_1700_720_375_V03.06_tree.root"], plot, commonCut )
	signal2 = getHists( ["slimW_900_1720_375_V03.06_tree.root"], plot, commonCut )
	signal3 = getHists( ["slimB_1300_1720_375_V03.06_tree.root"], plot, commonCut )
	signal4 = getHists( ["slimB_1700_1120_375_V03.06_tree.root"], plot, commonCut )
	for i, signal in enumerate([signal1, signal2, signal3, signal4]):
		signal.SetLineColor( ROOT.kGreen + i )
		signal.SetLineColor( ROOT.kBlue + i )
		#signal.SetLineStyle(5+i)

	# prettify histograms
	fgammaHist.SetLineColor(7)
	egammaHist.SetLineColor( 3 )
	fsrZ.SetLineColor( ROOT.kRed-7 )
	fsrW.SetLineColor( ROOT.kRed-9 )
	fsrT.SetLineColor( ROOT.kRed )

	mh = Multihisto()
	mh.orderByIntegral = False
	mh.addHisto( fsrT, "#gamma t#bar{t}", True )
	mh.addHisto( fsrW, "#gamma W", True )
	mh.addHisto( fsrZ, "#gamma Z", True )
	mh.addHisto( egammaHist, "e#rightarrow#gamma", True )
	mh.addHisto( fgammaHist, "Multijet", True )
	dataLegName = "Data"
	mh.addHisto( dataHist, dataLegName, draw="pe" )
	mh.addHisto( signal2, "Bino-like #chi_{1}^{0}", draw="hist" )
	mh.addHisto( signal1, "Wino-like #chi_{1}^{0}", draw="hist" )


	# get all SYSTEMATICAL uncertainties:
	systematicUncertHistStack = ROOT.THStack()
	systematicUncertHistStack.Add( fgammaWeightError )
	systematicUncertHistStack.Add( egammaHistsys )
	#systematicUncertHistStack.Add( fsrTsys )
	#systematicUncertHistStack.Add( fsrWsys )
	#systematicUncertHistStack.Add( fsrZsys )
	systematicUncertHistStack.Add( fsrSys )


	#if plot == "met":
	#	writeDataCard( treeVersion, dataHist, fgammaHist, fgammaWeightError,
	#		egammaHist, egammaHistsys,
	#		fsr, fsrSys )

	# draw stuff
	luminosity = 19.7
	infoText = ROOT.TLatex(0,.96, "CMS Private Work - %sfb^{-1} #sqrt{s}=8TeV #geq1#gamma_{tight},#geq2jets"%luminosity )
	infoText.SetNDC()
	infoText.SetTextSize(.04)

	can = ROOT.TCanvas()
	mh.Draw()
	errorBand = mh.stack.GetStack().Last().Clone( randomName() )
	sysUncert = systematicUncertHistStack.GetStack().Last()
	for bin in range(errorBand.GetNbinsX()+2):
		errorBand.SetBinError( bin, errorBand.GetBinError(bin) |qPlus| sysUncert.GetBinError(bin) )
	errorBand.SetFillStyle(3002)
	errorBand.SetMarkerSize(0)
	errorBand.SetFillColor(1)
	errorBand.Draw("e2 same")

	from myRatio import Ratio
	r = Ratio( "Data / Bkg", dataHist, mh.stack.GetStack().Last(), systematicUncertHistStack.GetStack().Last() )
	r.draw(0.5,1.5)

	infoText.Draw()

	SaveAs( can, "finalDistributionData_%s"%plot )
Exemplo n.º 56
0
def zGammaCut(plot="photons[0].pt", merge=False):
    cut = "[email protected]() && [email protected]()"

    nunuTree = readTree("slimZGammaNuNu_V03.19b_tree.root", "photonTree")
    llTree = readTree("slimZGammaLL_V02.19b_tree.root", "photonTree")
    zIncTree = readTree("slimZGamma_V03.18_tree.root", "photonTree")

    nBins = range(
        60, 500, 10
    ) if plot == "photons[0].pt" or plot == "genPhotons[0].pt" else readAxisConf(
        plot)[2]

    h_nunu = getHisto(nunuTree,
                      plot,
                      cut + "&&genPhotons[0].pt>130",
                      nBins=nBins,
                      color=2)
    h_ll = getHisto(llTree, plot, cut, nBins=nBins, color=5)
    h_zInc = getHisto(zIncTree, plot, cut, nBins=nBins)

    llTree.AddFriend("photonTreeAddVariables", llTree.GetFile().GetName())

    llPlot = "metLL" if plot == "met" else plot

    zMod = getHisto(llTree,
                    llPlot,
                    "genPhotons[0].pt<130",
                    nBins=nBins,
                    color=4)
    zMod.Scale(20. / (2. * 3.363))

    mh = Multihisto()
    mh.orderByIntegral = False
    mh.setMinimum(0.01)

    mh.addHisto(h_nunu,
                "#gammaZ#rightarrow#gamma#nu#nu(p_{T#gamma}^{gen}#geq130GeV)",
                draw="e",
                toStack=True)
    mh.addHisto(zMod, "ll to #slash{E}_{T}", toStack=True)
    mh.addHisto(h_ll, "#gammaZ#rightarrow#gammall", draw="e", toStack=True)
    mh.addHisto(h_zInc, "#gammaZ", draw="e")

    if merge:
        h_nunuPart = getHisto(nunuTree,
                              plot,
                              cut + "&&genPhotons[0].pt>=130",
                              nBins=nBins,
                              color=6)
        h_zIncPart = getHisto(zIncTree,
                              plot,
                              cut + "&&genPhotons[0].pt<130",
                              nBins=nBins,
                              color=6)
        merged = addHistos([h_nunuPart, h_zIncPart])
        mh.addHisto(merged, "merged", draw="e")

    mh.Draw()
    total = mh.stack.GetStack().Last().Clone(randomName())
    total.SetFillStyle(3002)
    total.SetFillColor(1)
    total.Draw("same e2")

    if plot == "photons[0].pt":
        l = ROOT.TLine(130, 0, 130, 1)
        l.Draw()

    if merge:
        plot += "_merged"
    SavePad("zGammaCut_%s" % plot)