예제 #1
0
def makeSVMassPlots(histodict):
	ratplot = RatioPlot('SVMass')
	ratplot.normalized = True
	ratplot.ratiorange = (0.5,1.5)
	ratplot.legpos = (0.65, 0.60)
	ratplot.ratiotitle = 'Data/MC'
	ratplot.extratext = '' #Work in Progress'
	ratplot.tag = "Inclusive"
	# ratplot.tag = "e#mu channel"
	ratplot.tagpos = (0.80,0.55)
	ratplot.add(histodict[('nominal','SVMass',3)], 'N_{trk}=3 t#bar{t} MC', includeInRatio=False)
	ratplot.add(histodict[('data',   'SVMass',3)], 'N_{trk}=3 Data',        includeInRatio=True)
	ratplot.add(histodict[('nominal','SVMass',4)], 'N_{trk}=4 t#bar{t} MC', includeInRatio=False)
	ratplot.add(histodict[('data',   'SVMass',4)], 'N_{trk}=4 Data',        includeInRatio=True)
	ratplot.add(histodict[('nominal','SVMass',5)], 'N_{trk}=5 t#bar{t} MC', includeInRatio=False)
	ratplot.add(histodict[('data',   'SVMass',5)], 'N_{trk}=5 Data',        includeInRatio=True)

	ratplot.reference =     [histodict[('nominal','SVMass',3)]]
	ratplot.reference.append(histodict[('nominal','SVMass',4)])
	ratplot.reference.append(histodict[('nominal','SVMass',5)])

	ratplot.colors = [ROOT.kMagenta+1, ROOT.kMagenta+1,
	                  ROOT.kViolet+2, ROOT.kViolet+2,
	                  ROOT.kAzure+7, ROOT.kAzure+7]

	ratplot.drawoptions =  ['hist', 'PE', 'hist', 'PE', 'hist', 'PE']
	ratplot.markerstyles = [24, 24, 25, 25, 26, 26]
	ratplot.markersizes = len(ratplot.histos)*[1.4]
	ratplot.show('svmassplot',opt.outDir)
	ratplot.saveRatios('svmass_weights',opt.outDir,['SVMass_weight_3','SVMass_weight_4','SVMass_weight_5'])
예제 #2
0
def makeMassPlot(histos, outname, tag='', subtag=''):
	ratplot = RatioPlot('ratioplot')
	ratplot.normalized = False
	ratplot.ratiotitle = "Ratio wrt 172.5 GeV"
	ratplot.extratext = ''
	ratplot.tag = tag
	ratplot.subtag = subtag
	ratplot.legpos = (0.65, 0.62)
	ratplot.ratiorange = (0.7, 1.3)
	ratplot.titlex = 'm_{svl} [GeV]'
	ratplot.xlabelsize = 28
	ratplot.xtitlesize = 34
	ratplot.ylabelsize = 28
	ratplot.ytitlesize = 34
	ratplot.ytitleoffset = 1.8
	ratplot.xtitleoffset = 3
	ratplot.legendtextsize = 28
	ratplot.legendrowsize = 0.08
	ratplot.reference = [histos[172.5]]
        ratplot.titley = "Combinations / %3.1f GeV" %histos['data'].GetXaxis().GetBinWidth(1)

	####################################################
	# Construct dummy data for now
	# dummy = histos[172.5].Clone('dummy_data')
	# dummy.Reset('ICE')
	# dummy.FillRandom(histos[173.5], ROOT.gRandom.Poisson(histos[172.5].Integral()))
	# ratplot.add(dummy,'Pseudo Data (@173.5 GeV)')
	####################################################

	####################################################
	# REAL DATA:
	ratplot.add(histos['data'], 'Data')
	####################################################

	# histos[MASSESTOPLOT[0]].SetLineStyle(2)
	# histos[MASSESTOPLOT[-1]].SetLineStyle(3)


	for mass in MASSESTOPLOT:
		legentry = 'm_{t} = %5.1f GeV' % mass
		try:
			histo = histos[mass]
			ratplot.add(histo, legentry, includeInRatio=(mass != 172.5))
		except KeyError: pass

	# ratplot.colors = [ROOT.kBlack, ROOT.kAzure-4, ROOT.kAzure+1, ROOT.kAzure-6]

	# ratplot.colors = [ROOT.kBlack, ROOT.kAzure-2, ROOT.kGray, ROOT.kOrange+9]
	ratplot.colors = [ROOT.kBlack, ROOT.kSpring-8, ROOT.kGray+1, ROOT.kOrange+9]

	# ratplot.colors = [ROOT.kBlack, ROOT.kOrange-4, ROOT.kOrange-3, ROOT.kOrange+9]

	ratplot.drawoptions = ['PE', 'hist', 'hist', 'hist']
	ratplot.markerstyles = [20,1,1,1]
	ratplot.markersizes =  [1.5,1,1,1]
	ratplot.ratioydivisions = 405
	ratplot.show("massscan_paper_%s"%outname, opt.outDir)
예제 #3
0
def makeSVMassPlots(histodict):
    ratplot = RatioPlot('SVMass')
    ratplot.normalized = True
    ratplot.ratiorange = (0.5, 1.5)
    ratplot.legpos = (0.65, 0.60)
    ratplot.ratiotitle = 'Data/MC'
    ratplot.extratext = ''  #Work in Progress'
    ratplot.tag = "Inclusive"
    # ratplot.tag = "e#mu channel"
    ratplot.tagpos = (0.80, 0.55)
    ratplot.add(histodict[('nominal', 'SVMass', 3)],
                'N_{trk}=3 t#bar{t} MC',
                includeInRatio=False)
    ratplot.add(histodict[('data', 'SVMass', 3)],
                'N_{trk}=3 Data',
                includeInRatio=True)
    ratplot.add(histodict[('nominal', 'SVMass', 4)],
                'N_{trk}=4 t#bar{t} MC',
                includeInRatio=False)
    ratplot.add(histodict[('data', 'SVMass', 4)],
                'N_{trk}=4 Data',
                includeInRatio=True)
    ratplot.add(histodict[('nominal', 'SVMass', 5)],
                'N_{trk}=5 t#bar{t} MC',
                includeInRatio=False)
    ratplot.add(histodict[('data', 'SVMass', 5)],
                'N_{trk}=5 Data',
                includeInRatio=True)

    ratplot.reference = [histodict[('nominal', 'SVMass', 3)]]
    ratplot.reference.append(histodict[('nominal', 'SVMass', 4)])
    ratplot.reference.append(histodict[('nominal', 'SVMass', 5)])

    ratplot.colors = [
        ROOT.kMagenta + 1, ROOT.kMagenta + 1, ROOT.kViolet + 2,
        ROOT.kViolet + 2, ROOT.kAzure + 7, ROOT.kAzure + 7
    ]

    ratplot.drawoptions = ['hist', 'PE', 'hist', 'PE', 'hist', 'PE']
    ratplot.markerstyles = [24, 24, 25, 25, 26, 26]
    ratplot.markersizes = len(ratplot.histos) * [1.4]
    ratplot.show('svmassplot', opt.outDir)
    ratplot.saveRatios(
        'svmass_weights', opt.outDir,
        ['SVMass_weight_3', 'SVMass_weight_4', 'SVMass_weight_5'])
예제 #4
0
def main(args, options):
	os.system('mkdir -p %s'%options.outDir)
	try:
		treefiles = {} # procname -> filename
		for filename in os.listdir(args[0]):
			if not os.path.splitext(filename)[1] == '.root': continue
			procname = filename.split('_',1)[1][:-5]
			treefiles[procname] = os.path.join(args[0],filename)

	except OSError:
		print "Not a valid input directory: %s" % args[0]
		return -1

	except IndexError:
		print "Need to provide an input directory"
		return -1

	## Collect all the trees
	svltrees = {} # proc -> tree
	for proc in treefiles.keys():
		tfile = ROOT.TFile.Open(treefiles[proc], 'READ')
		if not filterUseless(treefiles[proc]): continue
		svltrees[proc] = tfile.Get(TREENAME)

	## Produce all the relevant histograms
	if not options.cached:
		masshistos = {}     # (selection tag, process) -> histo
		methistos  = {}     # (selection tag, process) -> histo
		fittertkhistos = {} # (selection tag, process) -> [h_ntk1, h_ntk2, ...]
		for tag,sel,_ in SELECTIONS:
			for proc, tree in svltrees.iteritems():
				if not filterUseless(treefiles[proc], sel): continue

				htag = ("%s_%s"%(tag, proc)).replace('.','')
				print ' ... processing %-30s %s htag=%s' % (proc, sel, htag)
				masshistos[(tag, proc)] = getHistoFromTree(tree, sel=sel,
					                               var='SVLMass',
		                                           hname="SVLMass_%s"%(htag),
		                                           titlex=MASSXAXISTITLE)

				methistos[(tag, proc)] =  getHistoFromTree(tree, sel=sel,
					                               var='MET',
		                                           hname="MET_%s"%(htag),
		                                           xmin=0,xmax=200,
		                                           titlex="Missing E_{T} [GeV]")

				fittertkhistos[(tag,proc)] = getNTrkHistos(tree, sel=sel,
									   tag=htag,
									   var='SVLMass',
									   titlex=MASSXAXISTITLE)

		cachefile = open(".svlqcdmasshistos.pck", 'w')
		pickle.dump(masshistos,     cachefile, pickle.HIGHEST_PROTOCOL)
		pickle.dump(methistos,      cachefile, pickle.HIGHEST_PROTOCOL)
		pickle.dump(fittertkhistos, cachefile, pickle.HIGHEST_PROTOCOL)
		cachefile.close()
	else:
		cachefile = open(".svlqcdmasshistos.pck", 'r')
		masshistos     = pickle.load(cachefile)
		methistos      = pickle.load(cachefile)
		fittertkhistos = pickle.load(cachefile)
		cachefile.close()


	#########################################################
	## Write out the histograms, make data/mc plots
	outputFileName = os.path.join(options.outDir,'qcd_DataMCHists.root')
	ofi = ROOT.TFile(outputFileName, 'recreate')
	ofi.cd()
	for hist in [h for h in masshistos.values() + methistos.values()]:
		hist.Write(hist.GetName())
	for hist in [h for hists in fittertkhistos.values() for h in hists]:
		hist.Write(hist.GetName())
	ofi.Write()
	ofi.Close()

	## Run the plotter to get scaled MET plots
	## Can then use those to subtract non-QCD backgrounds from data template
	## Overwrite some of the options
	options.filter = 'SVLMass,MET' ## only run SVLMass and MET plots
	# options.excludeProcesses = 'QCD'
	options.outFile = 'scaled_met_inputs.root'
	options.cutUnderOverFlow = True
	os.system('rm %s' % os.path.join(options.outDir, options.outFile))
	runPlotter(outputFileName, options)

	#########################################################
	## Build the actual templates from the single histograms
	templates = {} # selection tag -> template histo
	inputfile = openTFile(os.path.join(options.outDir, options.outFile))

	for tag,sel,_ in SELECTIONS:
		categories = ['MET', 'SVLMass']
		for x,_ in NTRKBINS:
			categories.append('SVLMass_tot_%d'%int(x))

		for category in categories:
			plotdirname = '%s_%s'%(category,tag)
			plotdir = inputfile.Get(plotdirname)
			h_bg = None
			h_data = None
			for tkey in plotdir.GetListOfKeys():
				key = tkey.GetName()
				if key.startswith('Graph_from'): continue
				if key.startswith('MC8TeV_QCD'): continue

				hist = inputfile.Get('%s/%s'%(plotdirname,key))
				if key.startswith('MC8TeV'):
					if not h_bg:
						h_bg = hist.Clone("%s_BGs" % tag)
					else:
						h_bg.Add(hist)

				if key.startswith('Data8TeV'):
					h_data = hist.Clone("%s_Data" % tag)

			## Determine a suitable output name
			histname = '%s_template'%tag
			if category == 'MET': histname = "%s_%s" % ('met',histname)
			if 'tot' in category:
				tkbin = int(category.split('_')[2])
				histname = "%s_%d" % (histname, tkbin)
			h_data_subtr = h_data.Clone(histname)

			## Now subtract the combined MC from the data
			h_data_subtr.Add(h_bg, -1)

			dicttag = tag
			if category == 'MET':
				dicttag = 'met_%s'%tag
			if '_tot_' in category:
				dicttag = '%s_%d' % (tag, tkbin)
			templates[dicttag] = h_data_subtr

	ofi = ROOT.TFile(os.path.join(options.outDir,'qcd_templates.root'),
		             'recreate')
	ofi.cd()
	for hist in templates.values(): hist.Write(hist.GetName())
	ofi.Write()
	ofi.Close()

	for key,hist in sorted(templates.iteritems()):
		print key


	#########################################################
	## Make a plot comparing the templates
	for tag,_,seltag in SELECTIONS:
		if not tag.endswith('_qcd'): continue
		templateplot = RatioPlot('qcdtemplates_%s'%tag)
		for key,hist in sorted(templates.iteritems()):
			if not tag in key: continue
			if key.startswith('met'): continue

			if key == tag:
				templateplot.add(hist, 'Inclusive')
				templateplot.reference = hist
			else:
				ntrkbin = int(key.rsplit('_',1)[1])
				templateplot.add(hist, 'N_{track} = %d'%ntrkbin)

		templateplot.tag = 'QCD templates'
		templateplot.subtag = seltag
		templateplot.tagpos    = (0.90, 0.85)
		templateplot.subtagpos = (0.90, 0.78)
		templateplot.legpos = (0.75, 0.25)
		templateplot.ratiotitle = 'Ratio wrt Inclusive'
		templateplot.extratext = '' #Work in Progress'
		templateplot.ratiorange = (0.2, 2.2)
		templateplot.colors = [ROOT.kBlack, ROOT.kBlue-8, ROOT.kAzure-2,
		                       ROOT.kCyan-3]
		templateplot.show("qcdtemplates_%s"%tag, options.outDir)
		templateplot.reset()


	return 0
예제 #5
0
def main(args, options):
    os.system('mkdir -p %s' % options.outDir)
    try:
        treefiles = {}  # procname -> filename
        for filename in os.listdir(args[0]):
            if not os.path.splitext(filename)[1] == '.root': continue
            procname = filename.split('_', 1)[1][:-5]
            treefiles[procname] = os.path.join(args[0], filename)

    except OSError:
        print "Not a valid input directory: %s" % args[0]
        return -1

    except IndexError:
        print "Need to provide an input directory"
        return -1

    ## Collect all the trees
    svltrees = {}  # proc -> tree
    for proc in treefiles.keys():
        tfile = ROOT.TFile.Open(treefiles[proc], 'READ')
        if not filterUseless(treefiles[proc]): continue
        svltrees[proc] = tfile.Get(TREENAME)

    ## Produce all the relevant histograms
    if not options.cached:
        masshistos = {}  # (selection tag, process) -> histo
        methistos = {}  # (selection tag, process) -> histo
        fittertkhistos = {
        }  # (selection tag, process) -> [h_ntk1, h_ntk2, ...]
        for tag, sel, _ in SELECTIONS:
            for proc, tree in svltrees.iteritems():
                if not filterUseless(treefiles[proc], sel): continue

                htag = ("%s_%s" % (tag, proc)).replace('.', '')
                print ' ... processing %-30s %s htag=%s' % (proc, sel, htag)
                masshistos[(tag, proc)] = getHistoFromTree(
                    tree,
                    sel=sel,
                    var='SVLMass',
                    hname="SVLMass_%s" % (htag),
                    titlex=MASSXAXISTITLE)

                methistos[(tag, proc)] = getHistoFromTree(
                    tree,
                    sel=sel,
                    var='MET',
                    hname="MET_%s" % (htag),
                    xmin=0,
                    xmax=200,
                    titlex="Missing E_{T} [GeV]")

                fittertkhistos[(tag,
                                proc)] = getNTrkHistos(tree,
                                                       sel=sel,
                                                       tag=htag,
                                                       var='SVLMass',
                                                       titlex=MASSXAXISTITLE)

        cachefile = open(".svlqcdmasshistos.pck", 'w')
        pickle.dump(masshistos, cachefile, pickle.HIGHEST_PROTOCOL)
        pickle.dump(methistos, cachefile, pickle.HIGHEST_PROTOCOL)
        pickle.dump(fittertkhistos, cachefile, pickle.HIGHEST_PROTOCOL)
        cachefile.close()
    else:
        cachefile = open(".svlqcdmasshistos.pck", 'r')
        masshistos = pickle.load(cachefile)
        methistos = pickle.load(cachefile)
        fittertkhistos = pickle.load(cachefile)
        cachefile.close()

    #########################################################
    ## Write out the histograms, make data/mc plots
    outputFileName = os.path.join(options.outDir, 'qcd_DataMCHists.root')
    ofi = ROOT.TFile(outputFileName, 'recreate')
    ofi.cd()
    for hist in [h for h in masshistos.values() + methistos.values()]:
        hist.Write(hist.GetName())
    for hist in [h for hists in fittertkhistos.values() for h in hists]:
        hist.Write(hist.GetName())
    ofi.Write()
    ofi.Close()

    ## Run the plotter to get scaled MET plots
    ## Can then use those to subtract non-QCD backgrounds from data template
    ## Overwrite some of the options
    options.filter = 'SVLMass,MET'  ## only run SVLMass and MET plots
    # options.excludeProcesses = 'QCD'
    options.outFile = 'scaled_met_inputs.root'
    options.cutUnderOverFlow = True
    os.system('rm %s' % os.path.join(options.outDir, options.outFile))
    runPlotter(outputFileName, options)

    #########################################################
    ## Build the actual templates from the single histograms
    templates = {}  # selection tag -> template histo
    inputfile = openTFile(os.path.join(options.outDir, options.outFile))

    for tag, sel, _ in SELECTIONS:
        categories = ['MET', 'SVLMass']
        for x, _ in NTRKBINS:
            categories.append('SVLMass_tot_%d' % int(x))

        for category in categories:
            plotdirname = '%s_%s' % (category, tag)
            plotdir = inputfile.Get(plotdirname)
            h_bg = None
            h_data = None
            for tkey in plotdir.GetListOfKeys():
                key = tkey.GetName()
                if key.startswith('Graph_from'): continue
                if key.startswith('MC8TeV_QCD'): continue

                hist = inputfile.Get('%s/%s' % (plotdirname, key))
                if key.startswith('MC8TeV'):
                    if not h_bg:
                        h_bg = hist.Clone("%s_BGs" % tag)
                    else:
                        h_bg.Add(hist)

                if key.startswith('Data8TeV'):
                    h_data = hist.Clone("%s_Data" % tag)

            ## Determine a suitable output name
            histname = '%s_template' % tag
            if category == 'MET': histname = "%s_%s" % ('met', histname)
            if 'tot' in category:
                tkbin = int(category.split('_')[2])
                histname = "%s_%d" % (histname, tkbin)
            h_data_subtr = h_data.Clone(histname)

            ## Now subtract the combined MC from the data
            h_data_subtr.Add(h_bg, -1)

            dicttag = tag
            if category == 'MET':
                dicttag = 'met_%s' % tag
            if '_tot_' in category:
                dicttag = '%s_%d' % (tag, tkbin)
            templates[dicttag] = h_data_subtr

    ofi = ROOT.TFile(os.path.join(options.outDir, 'qcd_templates.root'),
                     'recreate')
    ofi.cd()
    for hist in templates.values():
        hist.Write(hist.GetName())
    ofi.Write()
    ofi.Close()

    for key, hist in sorted(templates.iteritems()):
        print key

    #########################################################
    ## Make a plot comparing the templates
    for tag, _, seltag in SELECTIONS:
        if not tag.endswith('_qcd'): continue
        templateplot = RatioPlot('qcdtemplates_%s' % tag)
        for key, hist in sorted(templates.iteritems()):
            if not tag in key: continue
            if key.startswith('met'): continue

            if key == tag:
                templateplot.add(hist, 'Inclusive')
                templateplot.reference = hist
            else:
                ntrkbin = int(key.rsplit('_', 1)[1])
                templateplot.add(hist, 'N_{track} = %d' % ntrkbin)

        templateplot.tag = 'QCD templates'
        templateplot.subtag = seltag
        templateplot.tagpos = (0.90, 0.85)
        templateplot.subtagpos = (0.90, 0.78)
        templateplot.legpos = (0.75, 0.25)
        templateplot.ratiotitle = 'Ratio wrt Inclusive'
        templateplot.extratext = ''  #Work in Progress'
        templateplot.ratiorange = (0.2, 2.2)
        templateplot.colors = [
            ROOT.kBlack, ROOT.kBlue - 8, ROOT.kAzure - 2, ROOT.kCyan - 3
        ]
        templateplot.show("qcdtemplates_%s" % tag, options.outDir)
        templateplot.reset()

    return 0
def main(args, opt):
	os.system('mkdir -p %s'%opt.outDir)
	ROOT.gStyle.SetOptTitle(0)
	ROOT.gStyle.SetOptStat(0)
	ROOT.gROOT.SetBatch(1)

	# Construct histograms
	peInputFile = ROOT.TFile.Open(args[0], 'READ')
	masshistos = {}
	for mass in ALLMASSES+['data']:
		masshist = None
		masstag = mass
		if type(mass) == float:
			masstag = 'nominal_'+str(mass).replace('.','v')

		for trk,_ in NTRKBINS:
			ihist = peInputFile.Get('%s/SVLMass_inclusive_optmrank_%s_%d'%(masstag,masstag,trk))
			try:
				masshist.Add(ihist)
			except AttributeError:
				try:
					masshist = ihist.Clone(masstag)
				except ReferenceError:
					print "Histogram not found: %s/SVLMass_inclusive_optmrank_%s_%d"%(masstag,masstag,trk)
					continue
		masshistos[mass] = masshist

	ratplot = RatioPlot('ratioplot')
	ratplot.normalized = False
	ratplot.ratiotitle = "Ratio wrt 172.5 GeV"
	ratplot.tag = 'All channels combined'
	ratplot.extratext = 'Preliminary'
	ratplot.rebin = 1
	ratplot.legpos = (0.55, 0.15)
	ratplot.ratiorange = (0.5, 1.5)
	ratplot.reference = [masshistos[172.5]]

	# Construct dummy data for now
	dummy = masshistos[172.5].Clone('dummy_data')
	dummy.Reset('ICE')
	dummy.FillRandom(masshistos[173.5], ROOT.gRandom.Poisson(masshistos[172.5].Integral()))
	ratplot.add(dummy,'Pseudo Data (@173.5 GeV)')

	####################################################
	# REAL DATA:
	# ratplot.add(masshistos['data'], 'Data')
	####################################################

	for mass in MASSESTOPLOT:
		legentry = 'MC (m_{top} = %5.1f GeV)' % mass
		try:
			histo = masshistos[mass]
			ratplot.add(histo, legentry, includeInRatio=(mass != 172.5))
		except KeyError: pass

	ratplot.colors = [ROOT.kBlack, ROOT.kAzure-4, ROOT.kAzure+1, ROOT.kAzure-6]
	# ratplot.colors = [ROOT.kBlack, ROOT.kOrange-4, ROOT.kOrange-3, ROOT.kOrange+9]

	ratplot.drawoptions = ['PE', 'hist', 'hist', 'hist']
	ratplot.markerstyles = [20,1,1,1]
	ratplot.markersizes =  [1.5,1,1,1]
	ratplot.show("massscan_paper_optmrank", opt.outDir)

	return 0