コード例 #1
0
def prepareDYScaleFactors(filename, plotfile, inputdir, options,
	                      dytag="DY+Jets",
	                      unmergedfile="MC8TeV_TTJets_MSDecays_172v5.root"):
	"""
	Prepares a dictionary of (key, process title) -> scale factor,
	to be used in the runPlotter script to scale DY by a data-derived
	scale factor.

	A list of keys to be scaled is generated from a plotfile (for merged
	histograms), and from one file of an input directory (for unmerged ones).
	"""

	## First calculate the actual scalefactors
	DYSFs = extractFactors(filename, options=options)

	## Get a list of all keys that are to be scaled
	allkeys = []

	## Need the list of processes
	tagsToFilter = ['_ee', '_mm', '_mumu']

	## From merged plots:
	allkeys += getAllPlotsFrom(openTFile(plotfile),
		                       tagsToFilter=tagsToFilter,
		                       filterByProcsFromJSON=options.json)

	## From unmerged plots:
	allkeys += getAllPlotsFrom(openTFile(os.path.join(inputdir,
		                                              unmergedfile)),
		                       tagsToFilter=tagsToFilter)

	## Prepare dictionary of (key,tag) -> scale factor
	scaleFactors = {}

	if options.verbose > 0:
		print 'Will scale the following histograms for %s:' % dytag
	for key in allkeys:
		if '_ee' in key:
			scaleFactors[(key, dytag)] = DYSFs['ee']
			if options.verbose > 0:
				print '  %-25s: %5.3f' % (key, DYSFs['ee'])
		else:
			scaleFactors[(key, dytag)] = DYSFs['mm']
			if options.verbose > 0:
				print '  %-25s: %5.3f' % (key, DYSFs['mm'])

	return scaleFactors
コード例 #2
0
def extractFactors(inputFile, options):
	try:
		cachefile = open('.svldyscalefactors.pck','r')
		scaleFactors = pickle.load(cachefile)
		cachefile.close()
		print ('>>> Read Drell-Yan scale factors from cache '
			   '(.svldyscalefactors.pck)')
		return scaleFactors
	except IOError:
		pass

	try:
		tfile = openTFile(inputFile)
	except ReferenceError:
		print "Please provide a valid input file"

	allkeys = getAllPlotsFrom(tfile, tagsToFilter=HISTSTOPROCESS)
	scaleFactors = {}

	for histname in HISTSTOPROCESS:
		tot_data = 0
		tot_background = 0
		tot_signal = 0

		for key in allkeys:
			if not key.endswith(histname): continue
			integral = tfile.Get(key).Integral()
			if 'Data8TeV' in key:
				tot_data += integral
			elif SIGNAL in key:
				tot_signal += integral
			else:
				tot_background += integral

		channame = histname.rsplit('_',1)[1]
		if options.verbose>0:
			print 30*'-'
			print histname
			print ("Total data: %6.1f, total bg: %6.1f, total signal: %6.1f "
				        % (tot_data, tot_background, tot_signal))
		# tot_background + SF * tot_signal = tot_data
		SF = (tot_data-tot_background)/tot_signal
		if options.verbose>0:
			print " -> scale factor: %5.3f" % SF
		scaleFactors[channame] = SF
	if options.verbose>0: print 30*'-'

	cachefile = open(".svldyscalefactors.pck", 'w')
	pickle.dump(scaleFactors, cachefile, pickle.HIGHEST_PROTOCOL)
	cachefile.close()
	return scaleFactors
コード例 #3
0
def main(args, opt):
    try:
        cachefile = open(".eventyields.pck", 'r')
        yields = pickle.load(cachefile)
        cachefile.close()
        return printYields(yields)

    except EOFError:
        print "Error loading pickle file, please delete it and try again"
        return -1
    except IOError:
        pass

    try:
        tfile = openTFile(args[0])
    except ReferenceError:
        print "Please provide a valid input file"
        return -1

    ROOT.gStyle.SetOptTitle(0)
    ROOT.gStyle.SetOptStat(0)
    ROOT.gROOT.SetBatch(1)

    allkeys = getAllPlotsFrom(tfile, tagsToFilter=[opt.dist])
    channels = ['e', 'ee', 'em', 'm', 'mm']

    print 30 * '-'
    yields = {}

    for chan in channels:
        for key in allkeys:
            histname = "%s_%s" % (opt.dist, chan)
            if not key.endswith(histname): continue
            hist = tfile.Get(key)
            err = ROOT.Double(0.0)
            firstBin = opt.firstBin
            lastBin = hist.GetXaxis().GetNbins(
            ) if opt.lastBin < opt.firstBin else opt.lastBin
            integral = hist.IntegralAndError(firstBin, lastBin, err)
            err = float(err)

            proc = key.rsplit('/', 1)[1]
            proc = proc.replace('_%s' % histname, '')

            yields[(chan, proc)] = (integral, err)

    cachefile = open(".eventyields.pck", 'w')
    pickle.dump(yields, cachefile, pickle.HIGHEST_PROTOCOL)
    cachefile.close()

    return printYields(yields)
コード例 #4
0
def main(args, opt):
	try:
		cachefile = open(".eventyields.pck", 'r')
		yields = pickle.load(cachefile)
		cachefile.close()
		return printYields(yields)

	except EOFError:
		print "Error loading pickle file, please delete it and try again"
		return -1
	except IOError:
		pass

	try:
		tfile = openTFile(args[0])
	except ReferenceError:
		print "Please provide a valid input file"
		return -1

	ROOT.gStyle.SetOptTitle(0)
	ROOT.gStyle.SetOptStat(0)
	ROOT.gROOT.SetBatch(1)

	allkeys = getAllPlotsFrom(tfile, tagsToFilter=[opt.dist])
	channels = ['e', 'ee', 'em', 'm', 'mm']

	print 30*'-'
	yields = {}

	for chan in channels:
		for key in allkeys:
			histname = "%s_%s"%(opt.dist,chan)
			if not key.endswith(histname): continue
			hist = tfile.Get(key)
			err = ROOT.Double(0.0)
			firstBin=opt.firstBin
			lastBin=hist.GetXaxis().GetNbins()  if opt.lastBin<opt.firstBin else opt.lastBin
			integral = hist.IntegralAndError(firstBin,lastBin, err)
			err = float(err)

			proc = key.rsplit('/',1)[1]
			proc = proc.replace('_%s'%histname, '')

			yields[(chan,proc)] = (integral, err)

	cachefile = open(".eventyields.pck", 'w')
	pickle.dump(yields, cachefile, pickle.HIGHEST_PROTOCOL)
	cachefile.close()

	return printYields(yields)
コード例 #5
0
def extractLJNTrkWeights(inputFile=None, verbose=0):
	try:
		tfile = openTFile(inputFile)
	except ReferenceError:
		print "[extractLJNTrkWeights] Please provide a valid input file"

	allkeys = getAllPlotsFrom(tfile, tagsToFilter=HISTSTOPROCESS)

	ofile = ROOT.TFile.Open('ljntkweights.root','recreate')
	ofile.cd()

	for histname in HISTSTOPROCESS:
		tot_data, tot_mc = None, None

		for key in allkeys:
			if not key.endswith(histname): continue
			hist = tfile.Get(key)

			integral = hist.Integral()
			if 'Data8TeV' in key:
				if not tot_data:
					tot_data = hist.Clone("SVNtrk_data")
					tot_data.SetDirectory(0)
				else:
					print "WARNING: Found two data histograms"
					tot_data = hist.Clone("SVNtrk_data")
					tot_data.SetDirectory(0)

			if 'MC8TeV_TTJets_MSDecays_172v5' in key:
				if not tot_mc:
					tot_mc = hist.Clone("SVNtrk_mc")
					tot_mc.SetDirectory(0)
				else:
					tot_mc.Add(hist)

		## Normalize them
		tot_data.Scale(1.0/tot_data.Integral())
		tot_mc.Scale(1.0/tot_mc.Integral())
		ratio = tot_data.Clone("%s_weights"%histname)
		ratio.Divide(tot_mc)

		ofile.cd()
		ratio.Write(ratio.GetName())
	ofile.Write()
	ofile.Close()
	print ">>> Wrote light jet ntrk weights to ljntkweights.root"
コード例 #6
0
def extractLJNTrkWeights(inputFile=None, verbose=0):
    try:
        tfile = openTFile(inputFile)
    except ReferenceError:
        print "[extractLJNTrkWeights] Please provide a valid input file"

    allkeys = getAllPlotsFrom(tfile, tagsToFilter=HISTSTOPROCESS)

    ofile = ROOT.TFile.Open('ljntkweights.root', 'recreate')
    ofile.cd()

    for histname in HISTSTOPROCESS:
        tot_data, tot_mc = None, None

        for key in allkeys:
            if not key.endswith(histname): continue
            hist = tfile.Get(key)

            integral = hist.Integral()
            if 'Data8TeV' in key:
                if not tot_data:
                    tot_data = hist.Clone("SVNtrk_data")
                    tot_data.SetDirectory(0)
                else:
                    print "WARNING: Found two data histograms"
                    tot_data = hist.Clone("SVNtrk_data")
                    tot_data.SetDirectory(0)

            if 'MC8TeV_TTJets_MSDecays_172v5' in key:
                if not tot_mc:
                    tot_mc = hist.Clone("SVNtrk_mc")
                    tot_mc.SetDirectory(0)
                else:
                    tot_mc.Add(hist)

        ## Normalize them
        tot_data.Scale(1.0 / tot_data.Integral())
        tot_mc.Scale(1.0 / tot_mc.Integral())
        ratio = tot_data.Clone("%s_weights" % histname)
        ratio.Divide(tot_mc)

        ofile.cd()
        ratio.Write(ratio.GetName())
    ofile.Write()
    ofile.Close()
    print ">>> Wrote light jet ntrk weights to ljntkweights.root"
コード例 #7
0
ファイル: extractBcomp.py プロジェクト: pfs/TopMassSecVtx
def compareNtrk(inputFile=None, verbose=0):

	xsecweights=readXSecWeights()
	try:
		tfile = openTFile(inputFile)
	except ReferenceError:
		print "Please provide a valid input file"

	for reg in ['regA','regB','regC']:
		for ch in ['e','m','mm','em','ee']:
			histToProcess='SVNtrk_%s_optmrank' % ch
			allkeys = getAllPlotsFrom(tfile, tagsToFilter=[histToProcess])
			data=None
			mc=None
			for key in allkeys:
				if not (reg in key) : continue

				weight=1.0
				for xsecKey in xsecweights:
					procName=xsecKey.replace('MC8TeV','')+'_'
					if procName in key : weight =xsecweights[xsecKey]*LUMI
				
				if '2012' in key:
					try:
						data.Add( tfile.Get(key), weight )
					except:
						data=tfile.Get(key).Clone('data')
						data.Scale(weight)
				else:
					try:
						mc.Add( tfile.Get(key), weight )
					except:
						mc=tfile.Get(key).Clone('mc')
						mc.Scale(weight)

			varPlot = Plot('%s_%s_ntrks'%(ch,reg),False)
			varPlot.add(mc,   'expected', ROOT.kGray, False)
			varPlot.add(data, 'data',  1,         True)
			varPlot.show('~/www/tmp')
			varPlot.reset()
コード例 #8
0
def compareNtrk(inputFile=None, verbose=0):

    xsecweights = readXSecWeights()
    try:
        tfile = openTFile(inputFile)
    except ReferenceError:
        print "Please provide a valid input file"

    for reg in ['regA', 'regB', 'regC']:
        for ch in ['e', 'm', 'mm', 'em', 'ee']:
            histToProcess = 'SVNtrk_%s_optmrank' % ch
            allkeys = getAllPlotsFrom(tfile, tagsToFilter=[histToProcess])
            data = None
            mc = None
            for key in allkeys:
                if not (reg in key): continue

                weight = 1.0
                for xsecKey in xsecweights:
                    procName = xsecKey.replace('MC8TeV', '') + '_'
                    if procName in key: weight = xsecweights[xsecKey] * LUMI

                if '2012' in key:
                    try:
                        data.Add(tfile.Get(key), weight)
                    except:
                        data = tfile.Get(key).Clone('data')
                        data.Scale(weight)
                else:
                    try:
                        mc.Add(tfile.Get(key), weight)
                    except:
                        mc = tfile.Get(key).Clone('mc')
                        mc.Scale(weight)

            varPlot = Plot('%s_%s_ntrks' % (ch, reg), False)
            varPlot.add(mc, 'expected', ROOT.kGray, False)
            varPlot.add(data, 'data', 1, True)
            varPlot.show('~/www/tmp')
            varPlot.reset()
コード例 #9
0
def main():
   global INPUTS
   global TAGS
   #configuration
   usage = 'usage: %prog [options]'
   parser = optparse.OptionParser(usage)
   parser.add_option('-i', '--input' , dest='input',
                     help='input directory',
                     default=None, type='string')
   # parser.add_option('-t', '--title', dest='InputTitles',
   #                   help='titles',
   #                   default=None, type='string')
   parser.add_option('-o', '--outDir' , dest='outDir',
                     help='destination for output plots',
                     default='charmplots', type='string')
   parser.add_option('-d', '--dist' , dest='Dist',
                     help='distribution to compare',
                     default='ptfrac', type='string')
   parser.add_option('--showMean' , dest='showMean',
                     help='show mean instead of pull',
                     default=False, action='store_true')
   parser.add_option('-m', '--maxY', dest='MaxY',
                     help='max y',
                     default=0.75, type=float)
   parser.add_option('-b', '--base', dest='BaseName',
                     help='base name for root files' ,
                     default='UnfoldedDistributions', type='string')
   parser.add_option('--tag', dest='Tag', help='Add a tag label',
                     default='', type='string')
   parser.add_option('-z', dest='z', help='use Z control region inputs',
                     default=False, action='store_true')
   (opt, args) = parser.parse_args()

   if opt.z:
      print 'Using Z control region inputs'
      INPUTS = [
         ('data'       , 'Data'          ,    'Data8TeV_DoubleLepton_merged_filt23' , ROOT.kBlack),
         ('z2srblep'   , 'Z2*LEP r_{b}'     , 'MC8TeV_DY_merged_filt23_bfrag'       , ROOT.kBlack),
         ('z2srblepup' , 'Z2*LEP r_{b}+' ,    'MC8TeV_DY_merged_filt23_bfragup'     , ROOT.kMagenta),
         ('z2srblepdn' , 'Z2*LEP r_{b}-' ,    'MC8TeV_DY_merged_filt23_bfragdn'     , ROOT.kMagenta+2),
         ('z2s'        , 'Z2*' ,              'MC8TeV_DY_merged_filt23'             , ROOT.kRed+1),
         ('z2spete'    , 'Z2* Peterson'  ,    'MC8TeV_DY_merged_filt23_bfragpete'   , ROOT.kAzure+7),
         ('z2slund'    , 'Z2* Lund'      ,    'MC8TeV_DY_merged_filt23_bfraglund'   , ROOT.kBlue-7),
         #('p11frag'    , 'P11'    ,        'MC8TeV_DY_merged_filt23_bfragp11'    , ROOT.kRed-9),
         ]
      TAGS = {
         'D0':   'Z/#gamma^{*}(ll) #mu D^{0} (K^{-}#pi^{+}) + X',
         'Dpm':  'Z/#gamma^{*}(ll) D^{#pm}(K^{-}#pi^{+}#pi^{+}) + X',
         'JPsi': 'Z/#gamma^{*}(ll) J/#Psi(#mu^{+}#mu^{-}) + X',
         'Dsm':  'Z/#gamma^{*}(ll) D*^{#pm}(D^{0}(K^{-}#pi^{+})#pi^{+}) X',
         }

   #global ROOT configuration
   ROOT.gStyle.SetOptStat(0)
   ROOT.gStyle.SetOptTitle(0)
   ROOT.gStyle.SetPadTopMargin(0.05)
   ROOT.gStyle.SetPadBottomMargin(0.12)
   ROOT.gStyle.SetPadLeftMargin(0.15)
   ROOT.gStyle.SetPadRightMargin(0.05)

   print "Will store plots in", opt.outDir

   #get graphs from files
   allGr={}

   for tag,title,dirname,color in INPUTS:
      inputdir = os.path.join(opt.input,dirname)
      if 'diff' in opt.BaseName:
         inputdir = os.path.join(inputdir, 'diff')
      files = glob.glob("%s/%s_*.root"%(inputdir,opt.BaseName))
      if not files:
         print "No files found:", "%s/%s_*.root"%(inputdir,opt.BaseName)
         continue
      assert(len(files) == 1)
      inF=openTFile(files[0])
      checkKeyInFile('%s'%opt.Dist, inF, doraise=True)
      allGr[tag] = inF.Get('%s'%opt.Dist)
      inF.Close()

      #format the new plot
      allGr[tag].SetName('gr%s'%tag)
      allGr[tag].SetTitle(title)
      allGr[tag].GetYaxis().SetTitleFont(43)
      allGr[tag].GetYaxis().SetLabelFont(43)
      allGr[tag].GetYaxis().SetTitleSize(24)
      allGr[tag].GetXaxis().SetTitleSize(24)
      allGr[tag].GetXaxis().SetTitleFont(43)
      allGr[tag].GetXaxis().SetLabelFont(43)
      allGr[tag].GetXaxis().SetLabelSize(18)
      allGr[tag].GetYaxis().SetLabelSize(18)
      allGr[tag].GetXaxis().SetTitleOffset(0.9)
      allGr[tag].GetYaxis().SetTitleOffset(1.1)

      axistitles = AXISTITLES.get(opt.Dist,(opt.Dist,'Normalized'))
      allGr[tag].GetXaxis().SetTitle(axistitles[0])
      allGr[tag].GetYaxis().SetTitle(axistitles[1])

      if tag == 'data':
         allGr[tag].SetFillStyle(0)
         allGr[tag].SetFillColor(0)
         allGr[tag].SetLineColor(ROOT.kBlack)
         allGr[tag].SetLineWidth(2)
         allGr[tag].SetMarkerColor(ROOT.kBlack)
         allGr[tag].SetMarkerStyle(20)
         allGr[tag].SetMarkerSize(0.8)
      else:
         allGr[tag].SetMarkerStyle(20)
         allGr[tag].SetMarkerSize(0.8)
         allGr[tag].SetMarkerColor(color)
         allGr[tag].SetLineColor(color)
         allGr[tag].SetFillStyle(3002)
         allGr[tag].SetFillColor(color)

   # compute all the pulls or means:
   compGrs={}
   itagCtr=0
   for tag,_,_,_ in INPUTS:
      graph=allGr[tag]
      if opt.showMean:
         mu0, avg, avgErr, mu2 = computeFirstMoments(graph)
         rms = ROOT.TMath.Sqrt(mu2-avg*avg)
         if tag=='data' : continue
         compGrs[tag]=graph.Clone('compgr%s'%tag)
         compGrs[tag].Set(0)
         compGrs[tag].SetPoint(0,avg,len(compGrs))
         compGrs[tag].SetPointError(0,avgErr,avgErr,0.5,0.5)
         itagCtr+=1
      else:
         compGrs[tag]=computePullFromGraphs(graph, allGr['data'])

   ##########################################
   # PLOTTING
   canvas=ROOT.TCanvas('c','c',500,500)
   canvas.cd()
   try:
      allGr['z2srblep'].Draw('A3')
      allGr['z2srblep'].GetYaxis().SetRangeUser(0,opt.MaxY)
      allGr['data'].Draw('p')
   except KeyError:
      print "WARNING: No data or Z2*LEP rb to plot"
      pass

   CMS_lumi(canvas,2,10)
   if opt.Tag:
      tl = ROOT.TLatex()
      tl.SetNDC()
      tl.SetTextFont(43)
      tl.SetTextSize(18)
      tl.SetTextAlign(32)
      tl.DrawLatex(0.93, 0.92, TAGS[opt.Tag])

   insetPad = ROOT.TPad('inset','inset',0.55,0.55,0.95,0.85)
   if 'chfrac' in opt.Dist : insetPad = ROOT.TPad('inset','inset',0.15,0.55,0.55,0.85)
   insetPad.SetTopMargin(0.05)
   insetPad.SetLeftMargin(0.1)
   insetPad.SetRightMargin(0.4)
   insetPad.SetBottomMargin(0.2)
   insetPad.SetFillStyle(0)
   insetPad.Draw()
   insetPad.cd()
   insetPad.Clear()
   frame,dataRef=ROOT.TGraph(),None
   if opt.showMean:
      mu0, avg, avgErr, mu2 = computeFirstMoments(allGr['data'])
      rms = ROOT.TMath.Sqrt(mu2-avg*avg)
      frame.SetTitle('frame')
      frame.SetMarkerStyle(1)
      frame.SetLineColor(1)
      frame.SetPoint(0,avg-rms,-0.5)
      frame.SetPoint(1,avg-rms,len(INPUTS)+0.5)            
      frame.SetPoint(2,avg+rms,len(INPUTS)+0.5)
      frame.SetPoint(3,avg+rms,-0.5)
      frame.SetPoint(4,avg-rms,-0.5)

      dataRef=ROOT.TGraph()
      dataRef.SetTitle('dataref')
      dataRef.SetPoint(0,avg-avgErr,-0.5)
      dataRef.SetPoint(1,avg-avgErr,len(INPUTS)+0.5)
      dataRef.SetPoint(2,avg+avgErr,len(INPUTS)+0.5)
      dataRef.SetPoint(3,avg+avgErr,-0.5)
      dataRef.SetPoint(4,avg-avgErr,-0.5)

   else:
      frame.SetTitle('frame')
      frame.SetMarkerStyle(1)
      frame.SetLineColor(1)
      frame.SetPoint(0,allGr['data'].GetHistogram().GetXaxis().GetXmin(),-5.1)
      frame.SetPoint(1,allGr['data'].GetHistogram().GetXaxis().GetXmin(),5.1)
      frame.SetPoint(2,allGr['data'].GetHistogram().GetXaxis().GetXmax(),5.1)
      frame.SetPoint(3,allGr['data'].GetHistogram().GetXaxis().GetXmax(),-5.1)
      frame.SetPoint(4,allGr['data'].GetHistogram().GetXaxis().GetXmin(),-5.1)      
      
   frame.Draw('ap')
   frameXtitle,frameYtitle='','Pull'
   frame.GetYaxis().SetNdivisions(5)
   frame.GetXaxis().SetNdivisions(5)
   if opt.showMean :
      frameXtitle,frameYtitle='Average',''
      frame.GetYaxis().SetNdivisions(0)
   frame.GetYaxis().SetTitle(frameYtitle)
   frame.GetXaxis().SetTitle(frameXtitle)
   frame.GetXaxis().SetTitleSize(0.08)
   frame.GetXaxis().SetLabelSize(0.08)
   frame.GetYaxis().SetTitleOffset(0.5)
   frame.GetXaxis().SetTitleOffset(1.0)
   frame.GetYaxis().SetTitleSize(0.08)
   frame.GetYaxis().SetLabelSize(0.08)

   #inset legend
   inleg=ROOT.TLegend(0.62,0.3,0.95,0.9)
   inleg.SetBorderSize(0)
   inleg.SetFillColor(0)
   inleg.SetTextFont(42)
   inleg.SetTextSize(0.07)         
   if dataRef : 
      dataRef.Draw('l')
      inleg.AddEntry(dataRef,'data','l')
   for tag,_,_,_ in INPUTS:
      if tag=='data' : continue
      if opt.showMean:
         compGrs[tag].Draw('p')
         inleg.AddEntry(compGrs[tag],compGrs[tag].GetTitle(),'p')
      else:
         compGrs[tag].Draw('3')
         inleg.AddEntry(compGrs[tag],compGrs[tag].GetTitle(),'l')
   inleg.Draw()


   postfix='_mean' if opt.showMean else ''
   os.system('mkdir -p %s' % opt.outDir)
   for ext in ['.pdf', '.png', '.C']:
   #for ext in ['.pdf', '.png']:
      canvas.SaveAs(os.path.join(opt.outDir,'%s%s%s'%(opt.Dist,postfix,ext)))

   insetPad.Delete()
コード例 #10
0
def main():

    global INPUTS
    global TAGS

    #configuration
    usage = 'usage: %prog [options]'
    parser = optparse.OptionParser(usage)
    parser.add_option('-i',
                      '--input',
                      dest='input',
                      help='input directory',
                      default=None,
                      type='string')
    # parser.add_option('-t', '--title', dest='InputTitles',
    #                   help='titles',
    #                   default=None, type='string')
    parser.add_option('-o',
                      '--outDir',
                      dest='outDir',
                      help='destination for output plots',
                      default='charmplots',
                      type='string')
    parser.add_option('-d',
                      '--dist',
                      dest='Dist',
                      help='distribution to compare',
                      default='ptfrac',
                      type='string')
    parser.add_option('-m',
                      '--maxY',
                      dest='MaxY',
                      help='max y',
                      default=0.75,
                      type=float)
    parser.add_option('-b',
                      '--base',
                      dest='BaseName',
                      help='base name for root files',
                      default='UnfoldedDistributions',
                      type='string')
    parser.add_option('--tag',
                      dest='Tag',
                      help='Add a tag label',
                      default='',
                      type='string')
    parser.add_option('-z',
                      dest='z',
                      help='use Z control region inputs',
                      default=False,
                      action='store_true')
    (opt, args) = parser.parse_args()

    if opt.z:
        print 'Using Z control region inputs'
        INPUTS = [
            ('data', 'Data', 'Data8TeV_merged_filt23', ROOT.kBlack),
            ('z2srblep', 'Z2*LEP r_{b}', 'MC8TeV_DY_merged_filt23_bfrag',
             ROOT.kBlack),
            ('z2srblepup', 'Z2*LEP r_{b}+', 'MC8TeV_DY_merged_filt23_bfragup',
             ROOT.kMagenta),
            ('z2srblepdn', 'Z2*LEP r_{b}-', 'MC8TeV_DY_merged_filt23_bfragdn',
             ROOT.kMagenta + 2),
            ('z2s', 'Z2*', 'MC8TeV_DY_merged_filt23', ROOT.kRed + 1),
            ('z2spete', 'Z2* Peterson', 'MC8TeV_DY_merged_filt23_bfragpete',
             ROOT.kAzure + 7),
            ('z2slund', 'Z2* Lund', 'MC8TeV_DY_merged_filt23_bfraglund',
             ROOT.kBlue - 7),
            #('p11frag'    , 'P11'    ,        'MC8TeV_DY_merged_filt23_bfragp11'    , ROOT.kRed-9),
        ]
        TAGS = {
            'D0': 'Z/#gamma^{*}(ll) #mu D^{0} (K^{-}#pi^{+}) + X',
            'Dpm': 'Z/#gamma^{*}(ll) D^{#pm}(K^{-}#pi^{+}#pi^{+}) + X',
            'JPsi': 'Z/#gamma^{*}(ll) J/#Psi(#mu^{+}#mu^{-}) + X',
            'Dsm': 'Z/#gamma^{*}(ll) D*^{#pm}(D^{0}(K^{-}#pi^{+})#pi^{+}) X',
        }

    #fragmentation variations to compare
    fragToUse = [('Z2*LEP r_{b}', ['z2srblep', 'z2srblepup',
                                   'z2srblepdn'], ROOT.kBlack),
                 ('Z2*', ['z2s', 'z2s', 'z2s'], ROOT.kRed + 1),
                 ('Z2* peterson', ['z2spete', 'z2spete',
                                   'z2spete'], ROOT.kViolet + 2),
                 ('Z2* Lund', ['z2slund', 'z2slund',
                               'z2slund'], ROOT.kAzure + 7)]
    if not opt.z:
        fragToUse.append(('Herwig AUET6', ['powherw', 'powherw',
                                           'powherw'], ROOT.kMagenta + 2))
    nominalFragWgt = fragToUse[0][0]

    #global ROOT configuration
    ROOT.gStyle.SetOptStat(0)
    ROOT.gStyle.SetOptTitle(0)

    print "Will store plots in", opt.outDir

    #get graphs from files
    allGr = {}

    for tag, title, dirname, color in INPUTS:
        inputdir = os.path.join(opt.input, dirname)
        if 'diff' in opt.BaseName:
            inputdir = os.path.join(inputdir, 'diff')
        files = glob.glob("%s/%s_*.root" % (inputdir, opt.BaseName))
        if not files:
            print "No files found:", "%s/%s_*.root" % (inputdir, opt.BaseName)
            continue
        assert (len(files) == 1)
        inF = openTFile(files[0])
        checkKeyInFile('%s' % opt.Dist, inF, doraise=True)
        allGr[tag] = inF.Get('%s' % opt.Dist)
        inF.Close()

        #format the new plot
        allGr[tag].SetName('gr%s' % tag)
        allGr[tag].SetTitle(title)

        if tag == 'data':
            allGr[tag].SetFillStyle(0)
            allGr[tag].SetFillColor(0)
            allGr[tag].SetLineColor(ROOT.kBlack)
            allGr[tag].SetLineWidth(2)
            allGr[tag].SetMarkerColor(ROOT.kBlack)
            allGr[tag].SetMarkerStyle(20)
            allGr[tag].SetMarkerSize(0.8)
        else:
            allGr[tag].SetMarkerStyle(20)
            allGr[tag].SetMarkerSize(0.8)
            allGr[tag].SetMarkerColor(color)
            allGr[tag].SetLineColor(color)
            allGr[tag].SetFillStyle(3002)
            allGr[tag].SetFillColor(color)

    # compute all the pulls or means:
    compGrs = {}
    for wtitle, iwList, wcolor in fragToUse:

        compGrs[wtitle] = [0, 0, 0, 0]
        for itag in xrange(0, len(iwList)):
            tag = iwList[itag]
            mu0, avg, avgErr, mu2 = computeFirstMoments(allGr[tag])
            rms = ROOT.TMath.Sqrt(mu2 - avg * avg)
            if itag == 0:
                compGrs[wtitle][0] = avg
                compGrs[wtitle][1] = avgErr
            else:
                compGrs[wtitle][1 + itag] = avg - compGrs[wtitle][0]
    print compGrs

    ##########################################
    # PLOTTING
    canvas = ROOT.TCanvas('c', 'c', 500, 500)
    canvas.SetRightMargin(0)
    canvas.SetLeftMargin(0.)
    canvas.SetTopMargin(0)
    canvas.SetBottomMargin(0.)
    canvas.cd()
    p1 = ROOT.TPad('p1', 'p1', 0.0, 0.85, 1.0, 0.0)
    p1.SetLeftMargin(0.12)
    p1.SetBottomMargin(0.12)
    p1.SetRightMargin(0.05)
    p1.SetTopMargin(0.01)
    p1.Draw()
    canvas.cd()
    p2 = ROOT.TPad('p2', 'p2', 0.0, 0.85, 1.0, 1.0)
    p2.SetLeftMargin(0.12)
    p2.SetBottomMargin(0.01)
    p2.SetRightMargin(0.05)
    p2.SetTopMargin(0.05)
    p2.Draw()
    p1.cd()
    p1.Clear()
    try:
        allGr['z2srblep'].Draw('A3')
        allGr['z2srblep'].GetYaxis().SetRangeUser(0, opt.MaxY)
        allGr['z2srblep'].GetYaxis().SetTitleOffset(1.25)
        axistitles = AXISTITLES.get(opt.Dist, (opt.Dist, 'Normalized'))
        allGr['z2srblep'].GetXaxis().SetTitle(axistitles[0])
        allGr['z2srblep'].GetYaxis().SetTitle(axistitles[1])
        allGr['z2srblep'].GetXaxis().SetTitleOffset(1.0)
        allGr['z2srblep'].GetYaxis().SetTitleOffset(1.2)
        allGr['z2srblep'].GetYaxis().SetTitleSize(0.04)
        allGr['z2srblep'].GetXaxis().SetTitleSize(0.04)
        allGr['z2srblep'].GetYaxis().SetLabelSize(0.035)
        allGr['z2srblep'].GetXaxis().SetLabelSize(0.035)
        allGr['z2srblep'].GetXaxis().SetNdivisions(10)
        allGr['z2srblep'].GetYaxis().SetNdivisions(5)
        allGr['data'].Draw('p')
    except KeyError:
        print "WARNING: No data or Z2*LEP rb to plot"
        pass

    label = ROOT.TLatex()
    label.SetNDC()
    label.SetTextFont(42)
    label.SetTextSize(0.05)
    label.SetTextAlign(32)
    label.DrawLatex(0.25, 0.92, '#bf{CMS}')
    if opt.Tag:
        label.DrawLatex(0.92, 0.86, '#scale[0.8]{#it{%s}}' % TAGS[opt.Tag])
    label.DrawLatex(0.92, 0.92, '#scale[0.8]{19.7 fb^{-1} (8 TeV)}')

    p2.cd()
    p2.Clear()
    frame, dataRef = ROOT.TGraph(), None
    mu0, avg, avgErr, mu2 = computeFirstMoments(allGr['data'])
    rms = ROOT.TMath.Sqrt(mu2 - avg * avg)
    frame.SetTitle('frame')
    frame.SetMarkerStyle(1)
    frame.SetLineColor(1)
    frame.SetPoint(0, 0, avg - 0.5 * rms)
    frame.SetPoint(1, len(fragToUse), avg - 0.5 * rms)
    frame.SetPoint(2, len(fragToUse), avg + 0.5 * rms)
    frame.SetPoint(3, 0, avg + 0.5 * rms)
    frame.SetPoint(4, 0, avg - 0.5 * rms)

    dataRef = ROOT.TGraph()
    dataRef.SetTitle('dataref')
    dataRef.SetFillStyle(3001)
    dataRef.SetFillColor(ROOT.kGray)
    dataRef.SetLineColor(ROOT.kGray)
    dataRef.SetLineWidth(2)
    dataRef.SetPoint(0, 0, avg - avgErr)
    dataRef.SetPoint(1, len(fragToUse) + 1.0, avg - avgErr)
    dataRef.SetPoint(2, len(fragToUse) + 1.0, avg + avgErr)
    dataRef.SetPoint(3, 0, avg + avgErr)
    dataRef.SetPoint(4, 0, avg - avgErr)
    print avg, avgErr

    frame.Draw('ap')
    frame.GetXaxis().SetNdivisions(0)
    frame.GetYaxis().SetNdivisions(5)
    frameXtitle, frameYtitle = '', 'Average'
    frame.GetXaxis().SetNdivisions(0)
    frame.GetYaxis().SetTitle(frameYtitle)
    frame.GetXaxis().SetTitle(frameXtitle)
    frame.GetXaxis().SetTitleSize(0.0)
    frame.GetXaxis().SetLabelSize(0.0)
    frame.GetYaxis().SetTitleOffset(0.25)
    frame.GetXaxis().SetTitleOffset(1.8)
    frame.GetYaxis().SetTitleSize(0.2)
    frame.GetYaxis().SetLabelSize(0.2)

    #inset legend
    fraglabel = ROOT.TLatex()
    fraglabel.SetNDC()
    fraglabel.SetTextFont(42)
    fraglabel.SetTextSize(0.15)
    #fraglabel.SetTextAlign(12)
    if dataRef:
        dataRef.Draw('lf')
    grCtr = 0
    statGrs, totalGrs = {}, {}
    for wtitle, iwList, wcolor in fragToUse:
        tag = iwList[0]

        totalGrs[wtitle] = ROOT.TGraphAsymmErrors()
        totalGrs[wtitle].SetMarkerColor(wcolor)
        totalGrs[wtitle].SetLineColor(wcolor)
        totalGrs[wtitle].SetLineWidth(2)
        totalGrs[wtitle].SetMarkerStyle(20 + grCtr)
        totalGrs[wtitle].SetPoint(0, grCtr + 1, compGrs[wtitle][0])

        diff1 = ROOT.TMath.Min(compGrs[wtitle][2], compGrs[wtitle][2])
        diff2 = ROOT.TMath.Max(compGrs[wtitle][2], compGrs[wtitle][3])
        statunc = compGrs[wtitle][1]
        if diff1 * diff2 < 0:
            totalGrs[wtitle].SetPointError(
                0, 0, 0, ROOT.TMath.Sqrt(statunc**2 + diff1**2),
                ROOT.TMath.Sqrt(statunc**2 + diff2**2))
        else:
            maxDiff = ROOT.TMath.Max(ROOT.TMath.Abs(diff1),
                                     ROOT.TMath.Abs(diff2))
            totalGrs[wtitle].SetPointError(
                0, 0, 0, ROOT.TMath.Sqrt(statunc**2 + maxDiff**2),
                ROOT.TMath.Sqrt(statunc**2 + maxDiff**2))

        statGrs[wtitle] = ROOT.TGraphAsymmErrors()
        statGrs[wtitle].SetMarkerColor(wcolor)
        statGrs[wtitle].SetLineColor(wcolor)
        statGrs[wtitle].SetLineWidth(1)
        statGrs[wtitle].SetMarkerStyle(20 + grCtr)
        statGrs[wtitle].SetPoint(0, grCtr + 1, compGrs[wtitle][0])
        statGrs[wtitle].SetPointError(0, 0, 0, statunc, statunc)

        if wtitle == nominalFragWgt:
            totalGrs[wtitle].SetMarkerSize(0.5)
            statGrs[wtitle].SetMarkerSize(0.5)
            totalGrs[wtitle].Draw('p')
            statGrs[wtitle].Draw('p')
        else:
            statGrs[wtitle].Draw('pX')
        xlabel = 0.09 + 0.68 * float(grCtr + 1) / float(len(fragToUse))
        fraglabel.DrawLatex(xlabel, 0.8, '#it{%s}' % wtitle)
        grCtr += 1

    os.system('mkdir -p %s' % opt.outDir)
    for ext in ['.pdf', '.png', '.C']:
        canvas.SaveAs(os.path.join(opt.outDir, '%s%s' % (opt.Dist, ext)))
    p1.Delete()
    p2.Delete()
コード例 #11
0
def main():
   global INPUTS
   global TAGS
   #configuration
   usage = 'usage: %prog [options]'
   parser = optparse.OptionParser(usage)
   parser.add_option('-i', '--input' , dest='input',
                     help='input directory',
                     default=None, type='string')
   # parser.add_option('-t', '--title', dest='InputTitles',
   #                   help='titles',
   #                   default=None, type='string')
   parser.add_option('-o', '--outDir' , dest='outDir',
                     help='destination for output plots',
                     default='charmplots', type='string')
   parser.add_option('-d', '--dist' , dest='Dist',
                     help='distribution to compare',
                     default='ptfrac', type='string')
   parser.add_option('--pullrange' , dest='pullrange',
                     help='range of pull to plot',
                     default='-2,2', type='string')
   parser.add_option('-m', '--maxY', dest='MaxY',
                     help='max y',
                     default=0.75, type=float)
   parser.add_option('-b', '--base', dest='BaseName',
                     help='base name for root files' ,
                     default='UnfoldedDistributions', type='string')
   parser.add_option('--tag', dest='Tag', help='Add a tag label',
                     default='', type='string')
   parser.add_option('-z', dest='z', help='use Z control region inputs',
                     default=False, action='store_true')
   (opt, args) = parser.parse_args()

   if opt.z:
      print 'Using Z control region inputs'
      INPUTS = [
         ('data'       , 'Data'                , 'Data8TeV_DoubleLepton_merged_filt23' , ROOT.kBlack),
         ('z2s'        , 'Madgraph+Pythia+Z2*' , 'MC8TeV_DY_merged_filt23'             , ROOT.kBlue+3),
         ('z2srblep'   , 'MG+PY+Z2*rbLEP'      , 'MC8TeV_DY_merged_filt23_bfrag'       , ROOT.kMagenta),
         ('z2srblepup' , 'MG+PY+Z2*rbLEP hard' , 'MC8TeV_DY_merged_filt23_bfragup'     , ROOT.kMagenta+2),
         ('z2srblepdn' , 'MG+PY+Z2*rbLEP soft' , 'MC8TeV_DY_merged_filt23_bfragdn'     , ROOT.kMagenta-9),
         ('p11frag'    , 'MG+PY+P11 (frag)'    , 'MC8TeV_DY_merged_filt23_bfragp11'    , ROOT.kRed-9),
         ('z2spete'    , 'MG+PY+Z2* Peterson'  , 'MC8TeV_DY_merged_filt23_bfragpete'   , ROOT.kAzure+7),
         ('z2slund'    , 'MG+PY+Z2* Lund'      , 'MC8TeV_DY_merged_filt23_bfraglund'   , ROOT.kBlue-7)
         ]
      TAGS = {
         'D0':   'Z/#gamma^{*}(ll) #mu D^{0} (K^{-}#pi^{+}) + X',
         'Dpm':  'Z/#gamma^{*}(ll) D^{#pm}(K^{-}#pi^{+}#pi^{+}) + X',
         'JPsi': 'Z/#gamma^{*}(ll) J/#Psi(#mu^{+}#mu^{-}) + X',
         'Dsm':  'Z/#gamma^{*}(ll) D*^{#pm}(D^{0}(K^{-}#pi^{+})#pi^{+}) X',
         }

   #global ROOT configuration
   ROOT.gStyle.SetOptStat(0)
   ROOT.gStyle.SetOptTitle(0)
   ROOT.gStyle.SetPadTopMargin(0.05)
   ROOT.gStyle.SetPadBottomMargin(0.1)
   ROOT.gStyle.SetPadLeftMargin(0.15)
   ROOT.gStyle.SetPadRightMargin(0.05)

   print "Will store plots in", opt.outDir

   #get graphs from files
   allGr={}

   for tag,title,dirname,color in INPUTS:
      inputdir = os.path.join(opt.input,dirname)
      if 'diff' in opt.BaseName:
         inputdir = os.path.join(inputdir, 'diff')
      files = glob.glob("%s/%s_*.root"%(inputdir,opt.BaseName))
      if not files:
         print "No files found:", "%s/%s_*.root"%(inputdir,opt.BaseName)
         continue
      assert(len(files) == 1)
      inF=openTFile(files[0])
      checkKeyInFile('%s'%opt.Dist, inF, doraise=True)
      allGr[tag] = inF.Get('%s'%opt.Dist)
      inF.Close()

      #format the new plot
      allGr[tag].SetName('gr%s'%tag)
      allGr[tag].SetTitle(title)
      allGr[tag].GetYaxis().SetTitleFont(43)
      allGr[tag].GetYaxis().SetLabelFont(43)
      allGr[tag].GetYaxis().SetTitleSize(24)
      allGr[tag].GetXaxis().SetTitleSize(24)
      allGr[tag].GetXaxis().SetTitleFont(43)
      allGr[tag].GetXaxis().SetLabelFont(43)
      allGr[tag].GetXaxis().SetLabelSize(18)
      allGr[tag].GetYaxis().SetLabelSize(18)
      allGr[tag].GetXaxis().SetTitleOffset(0.9)
      allGr[tag].GetYaxis().SetTitleOffset(2.5)

      axistitles = AXISTITLES.get(opt.Dist,(opt.Dist,'Normalized'))
      allGr[tag].GetXaxis().SetTitle(axistitles[0])
      allGr[tag].GetYaxis().SetTitle(axistitles[1])

      if tag == 'data':
         allGr[tag].SetFillStyle(0)
         allGr[tag].SetFillColor(0)
         allGr[tag].SetLineColor(ROOT.kBlack)
         allGr[tag].SetLineWidth(2)
         allGr[tag].SetMarkerColor(ROOT.kBlack)
         allGr[tag].SetMarkerStyle(20)
         allGr[tag].SetMarkerSize(1.5)
      else:
         allGr[tag].SetMarkerStyle(20)
         allGr[tag].SetMarkerSize(1)
         allGr[tag].SetMarkerColor(color)
         allGr[tag].SetLineColor(color)
         allGr[tag].SetFillStyle(3002)
         allGr[tag].SetFillColor(color)

   # compute all the pulls:
   pullGr = {}
   for tag, graph in allGr.iteritems():
      pullGr[tag] = computePullFromGraphs(graph, allGr['data'])

   ##########################################
   # PLOTTING
   canvas=ROOT.TCanvas('c','c',800,1200)
   canvas.SetRightMargin(0)
   canvas.SetLeftMargin(0)
   canvas.SetTopMargin(0)
   canvas.SetBottomMargin(0)
   allLegs=[]
   pads=[]
   if opt.z:
      pads.append( ROOT.TPad('pad0', 'pad0', 0.0, 0.40, 1.0, 1.00) )
      pads.append( ROOT.TPad('pad1', 'pad1', 0.0, 0.40, 1.0, 0.00) )
   else:
      pads.append( ROOT.TPad('pad0', 'pad0', 0.0, 0.60, 1.0, 1.00) )
      # pads.append( ROOT.TPad('pad1', 'pad1', 0.0, 0.60, 1.0, 0.42) )
      # pads.append( ROOT.TPad('pad2', 'pad2', 0.0, 0.42, 1.0, 0.24) )
      # pads.append( ROOT.TPad('pad3', 'pad3', 0.0, 0.24, 1.0, 0.00) )

   for i in xrange(0,len(pads)):
      pads[i].SetTopMargin(0.0)
      pads[i].SetBottomMargin(0.0)
   pads[0].SetTopMargin(0.1)
   pads[-1].SetBottomMargin(0.25)
   for p in pads: p.Draw()

   canvas.cd()
   pads[0].cd()
   pads[0].Clear()
   drawngraphs = []
   try:
      allGr['z2s'].Draw('A3')
      allGr['p11'].Draw('3')
      allGr['powpyth'].Draw('3')
      allGr['powherw'].Draw('3')
      allGr['data'].Draw('p')

      # allGr['z2s'].GetYaxis().SetRangeUser(0,opt.MaxY)
      # allGr['data'].GetYaxis().SetRangeUser(0,opt.MaxY)

      drawngraphs.append(allGr['data'])
      drawngraphs.append(allGr['z2s'])

      for g in drawngraphs:
         g.GetYaxis().SetRangeUser(0,opt.MaxY)

   except KeyError:
      print "WARNING: No data or Z2* to plot"
      pass

   # Build a legend
   leg = makeLegend('main',len(drawngraphs),y2=0.85)
   for gr in drawngraphs:
      if 'data' in gr.GetName(): leg.AddEntry(gr, gr.GetTitle(), 'p')
      else:                      leg.AddEntry(gr, gr.GetTitle(), 'f')
   leg.Draw()
   drawngraphs = []

   CMS_lumi(pads[0],2,10)

   #tag
   if opt.Tag:
      tl = ROOT.TLatex()
      tl.SetNDC()
      tl.SetTextFont(43)
      tl.SetTextSize(24)
      tl.DrawLatex(0.16, 0.92, TAGS[opt.Tag])

   ## Axis ranges
   xaxisrange = (allGr['data'].GetHistogram().GetXaxis().GetXmin(),
                 allGr['data'].GetHistogram().GetXaxis().GetXmax())
   pullrange = map(float, opt.pullrange.split(','))
   haxispulls = ROOT.TH2F("haxispulls", "haxispulls",
                          1, xaxisrange[0], xaxisrange[1],
                          1, pullrange[0], pullrange[1])

   haxispulls.GetXaxis().SetLabelFont(43)
   haxispulls.GetXaxis().SetLabelSize(18)
   haxispulls.GetYaxis().SetLabelFont(43)
   haxispulls.GetYaxis().SetLabelSize(18)
   haxispulls.GetXaxis().SetTitleFont(43)
   haxispulls.GetXaxis().SetTitleSize(24)
   haxispulls.GetXaxis().SetTitleOffset(4.0)
   haxispulls.GetYaxis().SetTitleFont(43)
   haxispulls.GetYaxis().SetTitleSize(24)
   haxispulls.GetYaxis().SetTitleOffset(2.5)
   haxispulls.GetYaxis().SetTitle("Pull")
   axistitles = AXISTITLES.get(opt.Dist,(opt.Dist,'Pull'))
   haxispulls.GetXaxis().SetTitle(axistitles[0])

   ## Draw the pull pads
   line = ROOT.TLine()
   line.SetLineColor(ROOT.kGray+2)
   line.SetLineWidth(2)
   line.SetLineStyle(2)

   def drawPulls(pulls,drawOpt='L3'):
      pad.cd()
      drawngraphs = []
      for pull in pulls:
         pullGr[pull].Draw(drawOpt)
         drawngraphs.append(allGr[pull])
      leg = makeLegend('leg',len(drawngraphs))
      for gr in drawngraphs: leg.AddEntry(gr, gr.GetTitle(), 'f')
      return leg

   for n,pad in enumerate(pads[1:]):
      pad.cd()
      pad.Clear()
      # pad.SetGridy(True)
      haxispulls.Draw("axis")
      if opt.z or n==2:
         leg2 = drawPulls(['z2srblep', 'z2srblepdn', 'z2srblepup',
                           'z2spete', 'z2slund'], drawOpt='LX')
         leg2.Draw()
      elif not opt.z:
         if n==0:
            leg0 = drawPulls(['z2s','p11','p11frag'])
            leg0.Draw()
         if n==1:
            leg1 = drawPulls(['powpyth','powherw'])
            leg1.Draw()

      line.DrawLine(xaxisrange[0], 0., xaxisrange[1], 0.,)



   os.system('mkdir -p %s' % opt.outDir)
   # for ext in ['.pdf', '.png', '.C']:
   for ext in ['.pdf', '.png']:
      canvas.SaveAs(os.path.join(opt.outDir,'%s%s'%(opt.Dist,ext)))

   for pad in pads:
      pad.Delete()
コード例 #12
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
コード例 #13
0
def extractNTrkWeights(inputFile=None, verbose=0):
    try:
        cachefile = open('.svntrkweights.pck', 'r')
        ntkWeights = pickle.load(cachefile)
        cachefile.close()
        print('>>> Read SV ntrk weights from cache ' '(.svntrkweights.pck)')
        return ntkWeights
    except IOError:
        pass

    try:
        tfile = openTFile(inputFile)
    except ReferenceError:
        print "[extractNTrkWeights] Please provide a valid input file"

    allkeys = getAllPlotsFrom(tfile, tagsToFilter=HISTSTOPROCESS)

    ntkWeights = {}
    for histname in HISTSTOPROCESS:
        tot_data, tot_mc = None, None

        for key in allkeys:
            if not key.endswith(histname): continue
            hist = tfile.Get(key)

            integral = hist.Integral()
            if 'Data8TeV' in key:
                if not tot_data:
                    tot_data = hist.Clone("SVNtrk_data")
                else:
                    print "WARNING: Found two data histograms"
                    tot_data = hist.Clone("SVNtrk_data")

            else:
                if not tot_mc:
                    tot_mc = hist.Clone("SVNtrk_mc")
                else:
                    tot_mc.Add(hist)

        ratio = tot_data.Clone("ratio")
        ratio.Divide(tot_mc)

        key = 'inclusive'
        if len(histname.split('_')) > 2:
            key = histname.rsplit('_', 1)[1]

        if not key in ntkWeights:
            ntkWeights[key] = {}

        if verbose > 0:
            print '---------------------------'
            print histname
        for x in xrange(1, ratio.GetNbinsX() + 1):
            if verbose > 0:
                print("Ntrk=%1d: Ndata: %6d / Nmc: %8.1f , weight = %5.3f" %
                      (x + 1, tot_data.GetBinContent(x),
                       tot_mc.GetBinContent(x), ratio.GetBinContent(x)))
            ntkWeights[key][x + 1] = ratio.GetBinContent(x)

    cachefile = open(".svntrkweights.pck", 'w')
    pickle.dump(ntkWeights, cachefile, pickle.HIGHEST_PROTOCOL)
    cachefile.close()
    print ">>> Dumped SV ntrk weights to .svntrkweights.pck"
    return ntkWeights
コード例 #14
0
def extractNTrkWeights(inputFile=None, verbose=0):
	try:
		cachefile = open('.svntrkweights.pck','r')
		ntkWeights = pickle.load(cachefile)
		cachefile.close()
		print ('>>> Read SV ntrk weights from cache '
			   '(.svntrkweights.pck)')
		return ntkWeights
	except IOError:
		pass

	try:
		tfile = openTFile(inputFile)
	except ReferenceError:
		print "[extractNTrkWeights] Please provide a valid input file"

	allkeys = getAllPlotsFrom(tfile, tagsToFilter=HISTSTOPROCESS)

	ntkWeights = {}
	for histname in HISTSTOPROCESS:
		tot_data, tot_mc = None, None

		for key in allkeys:
			if not key.endswith(histname): continue
			hist = tfile.Get(key)

			integral = hist.Integral()
			if 'Data8TeV' in key:
				if not tot_data:
					tot_data = hist.Clone("SVNtrk_data")
				else:
					print "WARNING: Found two data histograms"
					tot_data = hist.Clone("SVNtrk_data")

			else:
				if not tot_mc:
					tot_mc = hist.Clone("SVNtrk_mc")
				else:
					tot_mc.Add(hist)

		ratio = tot_data.Clone("ratio")
		ratio.Divide(tot_mc)

		key = 'inclusive'
		if len(histname.split('_'))>2:
			key = histname.rsplit('_',1)[1]

		if not key in ntkWeights:
			ntkWeights[key] = {}

		if verbose>0:
			print '---------------------------'
			print histname
		for x in xrange(1,ratio.GetNbinsX()+1):
			if verbose>0:
				print ("Ntrk=%1d: Ndata: %6d / Nmc: %8.1f , weight = %5.3f" %
					    (x+1,
					     tot_data.GetBinContent(x),
					     tot_mc.GetBinContent(x),
					     ratio.GetBinContent(x)))
			ntkWeights[key][x+1] = ratio.GetBinContent(x)

	cachefile = open(".svntrkweights.pck", 'w')
	pickle.dump(ntkWeights, cachefile, pickle.HIGHEST_PROTOCOL)
	cachefile.close()
	print ">>> Dumped SV ntrk weights to .svntrkweights.pck"
	return ntkWeights
コード例 #15
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
コード例 #16
0
def main():

   global INPUTS
   global TAGS

   #configuration
   usage = 'usage: %prog [options]'
   parser = optparse.OptionParser(usage)
   parser.add_option('-i', '--input' , dest='input',
                     help='input directory',
                     default=None, type='string')
   # parser.add_option('-t', '--title', dest='InputTitles',
   #                   help='titles',
   #                   default=None, type='string')
   parser.add_option('-o', '--outDir' , dest='outDir',
                     help='destination for output plots',
                     default='charmplots', type='string')
   parser.add_option('-d', '--dist' , dest='Dist',
                     help='distribution to compare',
                     default='ptfrac', type='string')
   parser.add_option('-m', '--maxY', dest='MaxY',
                     help='max y',
                     default=0.75, type=float)
   parser.add_option('-b', '--base', dest='BaseName',
                     help='base name for root files' ,
                     default='UnfoldedDistributions', type='string')
   parser.add_option('--tag', dest='Tag', help='Add a tag label',
                     default='', type='string')
   parser.add_option('-z', dest='z', help='use Z control region inputs',
                     default=False, action='store_true')
   (opt, args) = parser.parse_args()

   if opt.z:
      print 'Using Z control region inputs'
      INPUTS = [
         ('data'       , 'Data'          ,    'Data8TeV_merged_filt23' , ROOT.kBlack),
         ('z2srblep'   , 'Z2*LEP r_{b}'     , 'MC8TeV_DY_merged_filt23_bfrag'       , ROOT.kBlack),
         ('z2srblepup' , 'Z2*LEP r_{b}+' ,    'MC8TeV_DY_merged_filt23_bfragup'     , ROOT.kMagenta),
         ('z2srblepdn' , 'Z2*LEP r_{b}-' ,    'MC8TeV_DY_merged_filt23_bfragdn'     , ROOT.kMagenta+2),
         ('z2s'        , 'Z2*' ,              'MC8TeV_DY_merged_filt23'             , ROOT.kRed+1),
         ('z2spete'    , 'Z2* Peterson'  ,    'MC8TeV_DY_merged_filt23_bfragpete'   , ROOT.kAzure+7),
         ('z2slund'    , 'Z2* Lund'      ,    'MC8TeV_DY_merged_filt23_bfraglund'   , ROOT.kBlue-7),
         #('p11frag'    , 'P11'    ,        'MC8TeV_DY_merged_filt23_bfragp11'    , ROOT.kRed-9),
         ]
      TAGS = {
         'D0':   'Z/#gamma^{*}(ll) #mu D^{0} (K^{-}#pi^{+}) + X',
         'Dpm':  'Z/#gamma^{*}(ll) D^{#pm}(K^{-}#pi^{+}#pi^{+}) + X',
         'JPsi': 'Z/#gamma^{*}(ll) J/#Psi(#mu^{+}#mu^{-}) + X',
         'Dsm':  'Z/#gamma^{*}(ll) D*^{#pm}(D^{0}(K^{-}#pi^{+})#pi^{+}) X',
         }

   #fragmentation variations to compare
   fragToUse=[('Z2*LEP r_{b}', ['z2srblep','z2srblepup','z2srblepdn'], ROOT.kBlack),
              ('Z2*',          ['z2s',     'z2s',       'z2s'],        ROOT.kRed+1),
              ('Z2* peterson', ['z2spete', 'z2spete',   'z2spete'],    ROOT.kViolet+2),
              ('Z2* Lund',     ['z2slund', 'z2slund',   'z2slund'],    ROOT.kAzure+7)
              ]
   if not opt.z:
      fragToUse.append( ('Herwig AUET6', ['powherw', 'powherw', 'powherw'], ROOT.kMagenta+2) )
   nominalFragWgt=fragToUse[0][0]


   #global ROOT configuration
   ROOT.gStyle.SetOptStat(0)
   ROOT.gStyle.SetOptTitle(0)

   print "Will store plots in", opt.outDir

   #get graphs from files
   allGr={}

   for tag,title,dirname,color in INPUTS:
      inputdir = os.path.join(opt.input,dirname)
      if 'diff' in opt.BaseName:
         inputdir = os.path.join(inputdir, 'diff')
      files = glob.glob("%s/%s_*.root"%(inputdir,opt.BaseName))
      if not files:
         print "No files found:", "%s/%s_*.root"%(inputdir,opt.BaseName)
         continue
      assert(len(files) == 1)
      inF=openTFile(files[0])
      checkKeyInFile('%s'%opt.Dist, inF, doraise=True)
      allGr[tag] = inF.Get('%s'%opt.Dist)
      inF.Close()

      #format the new plot
      allGr[tag].SetName('gr%s'%tag)
      allGr[tag].SetTitle(title)
   
      if tag == 'data':
         allGr[tag].SetFillStyle(0)
         allGr[tag].SetFillColor(0)
         allGr[tag].SetLineColor(ROOT.kBlack)
         allGr[tag].SetLineWidth(2)
         allGr[tag].SetMarkerColor(ROOT.kBlack)
         allGr[tag].SetMarkerStyle(20)
         allGr[tag].SetMarkerSize(0.8)
      else:
         allGr[tag].SetMarkerStyle(20)
         allGr[tag].SetMarkerSize(0.8)
         allGr[tag].SetMarkerColor(color)
         allGr[tag].SetLineColor(color)
         allGr[tag].SetFillStyle(3002)
         allGr[tag].SetFillColor(color)

   # compute all the pulls or means:
   compGrs={}
   for wtitle,iwList,wcolor in fragToUse:  

      compGrs[wtitle]=[0,0,0,0]
      for itag in xrange(0,len(iwList)):
         tag=iwList[itag]
         mu0, avg, avgErr, mu2 = computeFirstMoments(allGr[tag])
         rms = ROOT.TMath.Sqrt(mu2-avg*avg)
         if itag==0:
            compGrs[wtitle][0]=avg
            compGrs[wtitle][1]=avgErr
         else:
            compGrs[wtitle][1+itag]=avg-compGrs[wtitle][0]
   print compGrs

      
   ##########################################
   # PLOTTING
   canvas=ROOT.TCanvas('c','c',500,500)
   canvas.SetRightMargin(0)
   canvas.SetLeftMargin(0.)
   canvas.SetTopMargin(0)
   canvas.SetBottomMargin(0.)
   canvas.cd()
   p1 = ROOT.TPad('p1','p1',0.0,0.85,1.0,0.0)
   p1.SetLeftMargin(0.12)
   p1.SetBottomMargin(0.12)
   p1.SetRightMargin(0.05)
   p1.SetTopMargin(0.01)
   p1.Draw()
   canvas.cd()
   p2 = ROOT.TPad('p2','p2',0.0,0.85,1.0,1.0)
   p2.SetLeftMargin(0.12)
   p2.SetBottomMargin(0.01)
   p2.SetRightMargin(0.05)
   p2.SetTopMargin(0.05)
   p2.Draw()
   p1.cd()
   p1.Clear()
   try:
      allGr['z2srblep'].Draw('A3')
      allGr['z2srblep'].GetYaxis().SetRangeUser(0,opt.MaxY)
      allGr['z2srblep'].GetYaxis().SetTitleOffset(1.25)
      axistitles = AXISTITLES.get(opt.Dist,(opt.Dist,'Normalized'))
      allGr['z2srblep'].GetXaxis().SetTitle(axistitles[0])
      allGr['z2srblep'].GetYaxis().SetTitle(axistitles[1])
      allGr['z2srblep'].GetXaxis().SetTitleOffset(1.0)
      allGr['z2srblep'].GetYaxis().SetTitleOffset(1.2)
      allGr['z2srblep'].GetYaxis().SetTitleSize(0.04)
      allGr['z2srblep'].GetXaxis().SetTitleSize(0.04)
      allGr['z2srblep'].GetYaxis().SetLabelSize(0.035)
      allGr['z2srblep'].GetXaxis().SetLabelSize(0.035)
      allGr['z2srblep'].GetXaxis().SetNdivisions(10)
      allGr['z2srblep'].GetYaxis().SetNdivisions(5)
      allGr['data'].Draw('p')
   except KeyError:
      print "WARNING: No data or Z2*LEP rb to plot"
      pass

   label=ROOT.TLatex()
   label.SetNDC()
   label.SetTextFont(42)
   label.SetTextSize(0.05)
   label.SetTextAlign(32)
   label.DrawLatex(0.25,0.92,'#bf{CMS}')         
   if opt.Tag:
      label.DrawLatex(0.92,0.86,'#scale[0.8]{#it{%s}}'%TAGS[opt.Tag])
   label.DrawLatex(0.92,0.92,'#scale[0.8]{19.7 fb^{-1} (8 TeV)}')

   p2.cd()
   p2.Clear()
   frame,dataRef=ROOT.TGraph(),None
   mu0, avg, avgErr, mu2 = computeFirstMoments(allGr['data'])
   rms = ROOT.TMath.Sqrt(mu2-avg*avg)
   frame.SetTitle('frame')
   frame.SetMarkerStyle(1)
   frame.SetLineColor(1)
   frame.SetPoint(0,0,avg-0.5*rms)
   frame.SetPoint(1,len(fragToUse),avg-0.5*rms)
   frame.SetPoint(2,len(fragToUse),avg+0.5*rms)
   frame.SetPoint(3,0,avg+0.5*rms)
   frame.SetPoint(4,0,avg-0.5*rms)

   dataRef=ROOT.TGraph()
   dataRef.SetTitle('dataref')
   dataRef.SetFillStyle(3001)
   dataRef.SetFillColor(ROOT.kGray)
   dataRef.SetLineColor(ROOT.kGray)
   dataRef.SetLineWidth(2)
   dataRef.SetPoint(0,0,avg-avgErr)
   dataRef.SetPoint(1,len(fragToUse)+1.0,avg-avgErr)
   dataRef.SetPoint(2,len(fragToUse)+1.0,avg+avgErr)
   dataRef.SetPoint(3,0,avg+avgErr)
   dataRef.SetPoint(4,0,avg-avgErr)
   print avg,avgErr
      
   frame.Draw('ap')   
   frame.GetXaxis().SetNdivisions(0)
   frame.GetYaxis().SetNdivisions(5)
   frameXtitle,frameYtitle='','Average'
   frame.GetXaxis().SetNdivisions(0)
   frame.GetYaxis().SetTitle(frameYtitle)
   frame.GetXaxis().SetTitle(frameXtitle)
   frame.GetXaxis().SetTitleSize(0.0)
   frame.GetXaxis().SetLabelSize(0.0)
   frame.GetYaxis().SetTitleOffset(0.25)
   frame.GetXaxis().SetTitleOffset(1.8)
   frame.GetYaxis().SetTitleSize(0.2)
   frame.GetYaxis().SetLabelSize(0.2)

   #inset legend
   fraglabel=ROOT.TLatex()
   fraglabel.SetNDC()
   fraglabel.SetTextFont(42)
   fraglabel.SetTextSize(0.15)        
   #fraglabel.SetTextAlign(12)
   if dataRef : 
      dataRef.Draw('lf')
   grCtr=0
   statGrs,totalGrs={},{}
   for wtitle,iwList,wcolor in fragToUse:        
      tag=iwList[0]

      totalGrs[wtitle]=ROOT.TGraphAsymmErrors()
      totalGrs[wtitle].SetMarkerColor(wcolor)
      totalGrs[wtitle].SetLineColor(wcolor)
      totalGrs[wtitle].SetLineWidth(2)
      totalGrs[wtitle].SetMarkerStyle(20+grCtr)
      totalGrs[wtitle].SetPoint(0,grCtr+1,compGrs[wtitle][0])
 
      diff1=ROOT.TMath.Min(compGrs[wtitle][2],compGrs[wtitle][2])
      diff2=ROOT.TMath.Max(compGrs[wtitle][2],compGrs[wtitle][3])      
      statunc=compGrs[wtitle][1]      
      if diff1*diff2<0:
         totalGrs[wtitle].SetPointError(0,0,0,
                                        ROOT.TMath.Sqrt(statunc**2+diff1**2),
                                        ROOT.TMath.Sqrt(statunc**2+diff2**2))
      else:
         maxDiff=ROOT.TMath.Max(ROOT.TMath.Abs(diff1),ROOT.TMath.Abs(diff2))
         totalGrs[wtitle].SetPointError(0,0,0,
                                        ROOT.TMath.Sqrt(statunc**2+maxDiff**2),
                                        ROOT.TMath.Sqrt(statunc**2+maxDiff**2))
      
      statGrs[wtitle]=ROOT.TGraphAsymmErrors()
      statGrs[wtitle].SetMarkerColor(wcolor)
      statGrs[wtitle].SetLineColor(wcolor)
      statGrs[wtitle].SetLineWidth(1)
      statGrs[wtitle].SetMarkerStyle(20+grCtr)
      statGrs[wtitle].SetPoint(0,grCtr+1,compGrs[wtitle][0])
      statGrs[wtitle].SetPointError(0,0,0,statunc,statunc)
      
      if wtitle==nominalFragWgt : 
         totalGrs[wtitle].SetMarkerSize(0.5)
         statGrs[wtitle].SetMarkerSize(0.5)
         totalGrs[wtitle].Draw('p')          
         statGrs[wtitle].Draw('p')          
      else:
         statGrs[wtitle].Draw('pX')          
      xlabel=0.09+0.68*float(grCtr+1)/float(len(fragToUse))
      fraglabel.DrawLatex(xlabel,0.8,'#it{%s}'%wtitle)
      grCtr+=1
      
   os.system('mkdir -p %s' % opt.outDir)
   for ext in ['.pdf', '.png', '.C']:
      canvas.SaveAs(os.path.join(opt.outDir,'%s%s'%(opt.Dist,ext)))
   p1.Delete()
   p2.Delete()
コード例 #17
0
def main():

	#global ROOT configuration
	ROOT.gStyle.SetOptStat(0)
	ROOT.gStyle.SetOptTitle(0)
	ROOT.gStyle.SetOptFit(0)

	ROOT.gSystem.Load("libUserCodeTopMassSecVtx")
	ROOT.AutoLibraryLoader.enable()
	ROOT.shushRooFit()
	# see TError.h - gamma function prints lots of errors when scanning
	ROOT.gROOT.ProcessLine("gErrorIgnoreLevel=kFatal")
	ROOT.RooMsgService.instance().setSilentMode(True)

	ROOT.gStyle.SetPadTopMargin(0.05)
	ROOT.gStyle.SetPadBottomMargin(0.1)
	ROOT.gStyle.SetPadLeftMargin(0.15)
	ROOT.gStyle.SetPadRightMargin(0.05)

	ROOT.gROOT.SetBatch(True)

	#configuration
	usage = 'usage: %prog [options]'
	parser = optparse.OptionParser(usage)
	parser.add_option('-c', '--cands', dest='CandTypes',
							 help='csv list of candidates',
							 default='421',
							 type='string')
	parser.add_option('-i', '--input', dest='inputUrl' ,
							 help='csv list of files',
							 default=None,
							 type='string')
	parser.add_option('-w', '--ws', dest='wsUrl',
							 help='ws url',
							 default=None,
							 type='string')
	parser.add_option('-o', '--output', dest='output',
							 help='Where to put the output',
							 default=None,
							 type='string')
	parser.add_option('--weight', dest='weight',
							 help='Apply a weight',
							 default=None,
							 type='string')
	(opt, args) = parser.parse_args()

	###########################################
	# Differential xsec measurement: pT, eta
	if opt.wsUrl:
		if not opt.output:
			opt.output = os.path.join(
			                os.path.dirname(opt.wsUrl).strip('.root'),'diff')
		if not os.path.exists(opt.output):
			os.system('mkdir -p %s' % opt.output)

		print "Will store output in", opt.output
		wsF = openTFile(opt.wsUrl)
		if wsF == None:
			print "ERROR: workspace file not found %s"%opt.wsUrl
			return -1
		ws = wsF.Get("w")
		print "Read Workspace from  %s"%opt.wsUrl
		wsF.Close()

		outUrl=os.path.join(opt.output,
		            os.path.basename(opt.wsUrl).replace('workspace','diff'))
		outF = ROOT.TFile(outUrl,'RECREATE')
		varRanges = { "pt"  : [10,25,50,75],
					  "eta" : [0,0.9,1.5,2.5] }
		for vname,ranges in varRanges.iteritems():
			runDifferentialMeasurement(ws,vname,ranges,outF)
		outF.Close()

	###########################################
	# Create workspace and run sPlot
	else:
		if not opt.output:
			opt.output = os.path.join('unfolded',os.path.basename(
			                          opt.inputUrl).strip('.root'))
		else:
			opt.output = os.path.join(opt.output,os.path.basename(
			                          opt.inputUrl).strip('.root'))
		if opt.weight:
			wname = {
				'BFragWeight[0]': 'bfrag',
				'BFragWeight[1]': 'bfragup',
				'BFragWeight[2]': 'bfragdn',
				'BFragWeight[3]': 'bfragp11',
				'BFragWeight[4]': 'bfragpete',
				'BFragWeight[5]': 'bfraglund',
			}.get(opt.weight, opt.weight.replace('[','').replace(']',''))
			opt.output = '%s_%s'%(opt.output,wname)

		if not opt.output.endswith('/'): opt.output += '/'
		if not os.path.exists(opt.output):
			os.system('mkdir -p %s' % opt.output)

		print "Will store all output in", opt.output

		#turn csvs to arrays
		CandTypes = None
		if len(opt.CandTypes)>0:
			CandTypes=[int(val) for val in opt.CandTypes.split(',')]
		postfixForOutputs=''
		for c in CandTypes: postfixForOutputs +='_%d'%c

		inputUrl = None
		if not (opt.inputUrl is None):
			if len(opt.inputUrl)>0:
				inputUrl=opt.inputUrl.split(',')

		# Create the workspace
		wsUrl=generateWorkspace(CandTypes=CandTypes,
		                        inputUrl=inputUrl,
		                        postfixForOutputs=postfixForOutputs,
		                        options=opt)
		print "Retrieving workspace from ",wsUrl
		wsF = ROOT.TFile.Open(wsUrl)
		ws = wsF.Get("w")
		wsF.Close()

		#use the SPlot class to add SWeights to our data set
		sData = ROOT.RooStats.SPlot("sData","An SPlot from mass",
		                             ws.data('data'),ws.pdf('model'),
		                             ROOT.RooArgList(ws.var('nsig'),ws.var('nbkg'))
		)
		getattr(ws,'import')(ws.data('data'), ROOT.RooFit.Rename("dataWithSWeights"))
		data = ws.data("dataWithSWeights")

		#the weighted data for signal and background species
		sigData = ROOT.RooDataSet(data.GetName(),data.GetTitle(),data,data.get(),'','nsig_sw')
		bkgData = ROOT.RooDataSet(data.GetName(),data.GetTitle(),data,data.get(),'','nbkg_sw')

		#show the unfolded distributions and save them to a file
		outFurl = os.path.join(opt.output,'UnfoldedDistributions%s.root'%postfixForOutputs)
		outF = ROOT.TFile.Open(outFurl,'RECREATE')
		varsToUnfold = [
			['ptrel',    'p_{T,rel} [GeV]',           8],
			['pfrac',    'p / p^{Jet} [GeV]',         8],
			['ptfrac',   'p_{T} / p_{T}^{jet}',       8],
			['pzfrac',   'p_{z} / p_{z}^{jet}',       8],
			['ptchfrac', 'p_{T} / #Sigma_{ch} p_{T}', 8],
			['pzchfrac', 'p_{z} / #Sigma_{ch} p_{z}', 8],
			['dr',       '#DeltaR to jet',            8]
		]
		for var,varTitle,nBins in varsToUnfold:
			ws.var(var).SetTitle(varTitle)
			ws.var(var).setBins(nBins)
			showUnfolded(sigData=sigData,
			             bkgData=bkgData,
			             var=ws.var(var),
			             outD=opt.output,
			             outF=outF,
			             postfixForOutputs=postfixForOutputs)
		outF.Close()
		print 'Unfolded distributions can be found @ ',outFurl
コード例 #18
0
def main():

    #global ROOT configuration
    ROOT.gStyle.SetOptStat(0)
    ROOT.gStyle.SetOptTitle(0)
    ROOT.gStyle.SetOptFit(0)

    ROOT.gSystem.Load("libUserCodeTopMassSecVtx")
    ROOT.AutoLibraryLoader.enable()
    ROOT.shushRooFit()
    # see TError.h - gamma function prints lots of errors when scanning
    ROOT.gROOT.ProcessLine("gErrorIgnoreLevel=kFatal")
    ROOT.RooMsgService.instance().setSilentMode(True)

    ROOT.gStyle.SetPadTopMargin(0.05)
    ROOT.gStyle.SetPadBottomMargin(0.1)
    ROOT.gStyle.SetPadLeftMargin(0.15)
    ROOT.gStyle.SetPadRightMargin(0.05)

    ROOT.gROOT.SetBatch(True)

    #configuration
    usage = 'usage: %prog [options]'
    parser = optparse.OptionParser(usage)
    parser.add_option('-c',
                      '--cands',
                      dest='CandTypes',
                      help='csv list of candidates',
                      default='421',
                      type='string')
    parser.add_option('-i',
                      '--input',
                      dest='inputUrl',
                      help='csv list of files',
                      default=None,
                      type='string')
    parser.add_option('-w',
                      '--ws',
                      dest='wsUrl',
                      help='ws url',
                      default=None,
                      type='string')
    parser.add_option('-o',
                      '--output',
                      dest='output',
                      help='Where to put the output',
                      default=None,
                      type='string')
    parser.add_option('--weight',
                      dest='weight',
                      help='Apply a weight',
                      default=None,
                      type='string')
    (opt, args) = parser.parse_args()

    ###########################################
    # Differential xsec measurement: pT, eta
    if opt.wsUrl:
        if not opt.output:
            opt.output = os.path.join(
                os.path.dirname(opt.wsUrl).strip('.root'), 'diff')
        if not os.path.exists(opt.output):
            os.system('mkdir -p %s' % opt.output)

        print "Will store output in", opt.output
        wsF = openTFile(opt.wsUrl)
        if wsF == None:
            print "ERROR: workspace file not found %s" % opt.wsUrl
            return -1
        ws = wsF.Get("w")
        print "Read Workspace from  %s" % opt.wsUrl
        wsF.Close()

        outUrl = os.path.join(
            opt.output,
            os.path.basename(opt.wsUrl).replace('workspace', 'diff'))
        outF = ROOT.TFile(outUrl, 'RECREATE')
        varRanges = {"pt": [10, 25, 50, 75], "eta": [0, 0.9, 1.5, 2.5]}
        for vname, ranges in varRanges.iteritems():
            runDifferentialMeasurement(ws, vname, ranges, outF)
        outF.Close()

    ###########################################
    # Create workspace and run sPlot
    else:
        if not opt.output:
            opt.output = os.path.join(
                'unfolded',
                os.path.basename(opt.inputUrl).strip('.root'))
        else:
            opt.output = os.path.join(
                opt.output,
                os.path.basename(opt.inputUrl).strip('.root'))
        if opt.weight:
            wname = {
                'BFragWeight[0]': 'bfrag',
                'BFragWeight[1]': 'bfragup',
                'BFragWeight[2]': 'bfragdn',
                'BFragWeight[3]': 'bfragp11',
                'BFragWeight[4]': 'bfragpete',
                'BFragWeight[5]': 'bfraglund',
            }.get(opt.weight,
                  opt.weight.replace('[', '').replace(']', ''))
            opt.output = '%s_%s' % (opt.output, wname)

        if not opt.output.endswith('/'): opt.output += '/'
        if not os.path.exists(opt.output):
            os.system('mkdir -p %s' % opt.output)

        print "Will store all output in", opt.output

        #turn csvs to arrays
        CandTypes = None
        if len(opt.CandTypes) > 0:
            CandTypes = [int(val) for val in opt.CandTypes.split(',')]
        postfixForOutputs = ''
        for c in CandTypes:
            postfixForOutputs += '_%d' % c

        inputUrl = None
        if not (opt.inputUrl is None):
            if len(opt.inputUrl) > 0:
                inputUrl = opt.inputUrl.split(',')

        # Create the workspace
        wsUrl = generateWorkspace(CandTypes=CandTypes,
                                  inputUrl=inputUrl,
                                  postfixForOutputs=postfixForOutputs,
                                  options=opt)
        print "Retrieving workspace from ", wsUrl
        wsF = ROOT.TFile.Open(wsUrl)
        ws = wsF.Get("w")
        wsF.Close()

        #use the SPlot class to add SWeights to our data set
        sData = ROOT.RooStats.SPlot(
            "sData", "An SPlot from mass", ws.data('data'), ws.pdf('model'),
            ROOT.RooArgList(ws.var('nsig'), ws.var('nbkg')))
        getattr(ws, 'import')(ws.data('data'),
                              ROOT.RooFit.Rename("dataWithSWeights"))
        data = ws.data("dataWithSWeights")

        #the weighted data for signal and background species
        sigData = ROOT.RooDataSet(data.GetName(), data.GetTitle(), data,
                                  data.get(), '', 'nsig_sw')
        bkgData = ROOT.RooDataSet(data.GetName(), data.GetTitle(), data,
                                  data.get(), '', 'nbkg_sw')

        #show the unfolded distributions and save them to a file
        outFurl = os.path.join(
            opt.output, 'UnfoldedDistributions%s.root' % postfixForOutputs)
        outF = ROOT.TFile.Open(outFurl, 'RECREATE')
        varsToUnfold = [['ptrel', 'p_{T,rel} [GeV]', 8],
                        ['pfrac', 'p / p^{Jet} [GeV]', 8],
                        ['ptfrac', 'p_{T} / p_{T}^{jet}', 8],
                        ['pzfrac', 'p_{z} / p_{z}^{jet}', 8],
                        ['ptchfrac', 'p_{T} / #Sigma_{ch} p_{T}', 8],
                        ['pzchfrac', 'p_{z} / #Sigma_{ch} p_{z}', 8],
                        ['dr', '#DeltaR to jet', 8]]
        for var, varTitle, nBins in varsToUnfold:
            ws.var(var).SetTitle(varTitle)
            ws.var(var).setBins(nBins)
            showUnfolded(sigData=sigData,
                         bkgData=bkgData,
                         var=ws.var(var),
                         outD=opt.output,
                         outF=outF,
                         postfixForOutputs=postfixForOutputs)
        outF.Close()
        print 'Unfolded distributions can be found @ ', outFurl