Ejemplo n.º 1
0
def showRatios(ratios, outUrl):
    """shows the ratio plots"""

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

    os.system('rm %s' % outUrl)
    outDir = os.path.dirname(outUrl)

    COLOURS = [1, '#f4a582', '#bababa', '#abdda4']
    for key in ratios:
        p = Plot(key + '_ratio', com='13 TeV')
        p.doPoissonErrorBars = False
        p.ratiorange = (0.68, 1.34)
        p.spimposeWithErrors = True
        ic = 0
        for h in ratios[key]:
            p.add(h=h,
                  title=h.GetTitle(),
                  color=COLOURS[ic],
                  isData=False,
                  spImpose=True,
                  isSyst=False)
            ic += 1
        p.show(outDir=outDir,
               lumi=41400,
               noStack=False,
               saveTeX=False,
               noRatio=True)
        p.appendTo(outUrl)
        p.reset()
Ejemplo n.º 2
0
def main():

    #configuration
    usage = 'usage: %prog [options]'
    parser = optparse.OptionParser(usage)
    parser.add_option('--mcUnc',
                      dest='mcUnc',
                      help='common MC related uncertainty (e.g. lumi)',
                      default=0,
                      type=float)
    parser.add_option('--com',
                      dest='com',
                      help='center of mass energy',
                      default='13 TeV',
                      type='string')
    parser.add_option('--rawYields',
                      dest='rawYields',
                      help='do not scale by lumi, xsec, etc.',
                      default=False,
                      action='store_true')
    parser.add_option('-j',
                      '--json',
                      dest='json',
                      help='json with list of files',
                      default=None,
                      type='string')
    parser.add_option('--systJson',
                      dest='systJson',
                      help='json with list of systematics',
                      default=None,
                      type='string')
    parser.add_option('--signalJson',
                      dest='signalJson',
                      help='signal json list',
                      default=None,
                      type='string')
    parser.add_option('-i',
                      '--inDir',
                      dest='inDir',
                      help='input directory',
                      default=None,
                      type='string')
    parser.add_option('-O',
                      '--outDir',
                      dest='outDir',
                      help='output directory',
                      default=None,
                      type='string')
    parser.add_option('-o',
                      '--outName',
                      dest='outName',
                      help='name of the output file',
                      default='plotter.root',
                      type='string')
    parser.add_option('--noStack',
                      dest='noStack',
                      help='don\'t stack distributions',
                      default=False,
                      action='store_true')
    parser.add_option('--normToData',
                      dest='normToData',
                      help='normalize to data yields',
                      default=False,
                      action='store_true')
    parser.add_option('--binWid',
                      dest='binWid',
                      help='divide by bin width',
                      default=False,
                      action='store_true')
    parser.add_option('--saveLog',
                      dest='saveLog',
                      help='save log versions of the plots',
                      default=False,
                      action='store_true')
    parser.add_option('--silent',
                      dest='silent',
                      help='only dump to ROOT file',
                      default=False,
                      action='store_true')
    parser.add_option('--ratioRange',
                      dest='ratioRange',
                      help='ratio range',
                      default="0.4,1.6",
                      type='string')
    parser.add_option('--onlyData',
                      dest='onlyData',
                      help='only plots containing data',
                      default=False,
                      action='store_true')
    parser.add_option('--saveTeX',
                      dest='saveTeX',
                      help='save as tex file as well',
                      default=False,
                      action='store_true')
    parser.add_option('--rebin',
                      dest='rebin',
                      help='rebin factor',
                      default=1,
                      type=int)
    parser.add_option('-l',
                      '--lumi',
                      dest='lumi',
                      help='lumi to print out, if == 1 draw normalized',
                      default=12900,
                      type=float)
    parser.add_option(
        '--lumiSpecs',
        dest='lumiSpecs',
        help='lumi specifications for some channels [tag:lumi,tag2:lumi2,...]',
        default=None,
        type=str)
    parser.add_option('--only',
                      dest='only',
                      help='plot only these (csv)',
                      default='',
                      type='string')
    parser.add_option('--strictOnly',
                      dest='strictOnly',
                      help='strict matching for only plots',
                      default=False,
                      action='store_true')
    parser.add_option('--skip',
                      dest='skip',
                      help='skip these samples (csv)',
                      default='MC13TeV_TTJets_cflip',
                      type='string')
    parser.add_option('--rawList',
                      dest='rawList',
                      help='don\'t scale these samples',
                      default='',
                      type='string')
    parser.add_option(
        '--puNormSF',
        dest='puNormSF',
        help='Use this histogram to correct pu weight normalization',
        default=None,
        type='string')
    parser.add_option(
        '--procSF',
        dest='procSF',
        help=
        'Use this to scale a given process component e.g. "W":.wjetscalefactors.pck,"DY":dyscalefactors.pck',
        default=None,
        type='string')
    (opt, args) = parser.parse_args()

    opt.ratioRange = [float(x) for x in opt.ratioRange.split(',')]

    #read lists of samples
    samplesList = []
    jsonList = opt.json.split(',')
    for jsonPath in jsonList:
        jsonFile = open(jsonPath, 'r')
        samplesList += json.load(jsonFile,
                                 encoding='utf-8',
                                 object_pairs_hook=OrderedDict).items()
        jsonFile.close()

    #read lists of syst samples
    systSamplesList = []
    if opt.systJson:
        systJsonList = opt.systJson.split(',')
        for jsonPath in systJsonList:
            jsonFile = open(jsonPath, 'r')
            systSamplesList += json.load(jsonFile, encoding='utf-8').items()
            jsonFile.close()

    #read list of signal samples
    signalSamplesList = None
    try:
        jsonFile = open(opt.signalJson, 'r')
        signalSamplesList = json.load(jsonFile,
                                      encoding='utf-8',
                                      object_pairs_hook=OrderedDict).items()
        jsonFile.close()
    except:
        pass

    skipList = opt.skip.split(',')

    #lumi specifications per tag
    lumiSpecs = {}
    if opt.lumiSpecs:
        for spec in opt.lumiSpecs.split(','):
            tag, lumi = spec.split(':')
            lumiSpecs[tag] = float(lumi)
        print lumiSpecs

    #proc SF
    procSF = {}
    if opt.procSF:
        procList = opt.procSF.split(',')
        for newProc in procList:
            proc, cacheUrl = newProc.split(':')
            if os.path.isfile(cacheUrl):
                cache = open(cacheUrl, 'r')
                procSF[proc] = pickle.load(cache)
                cache.close()
                print 'Scale factors added for', proc
            else:
                try:
                    procSF[proc] = {'': (float(cacheUrl), 0)}
                    print 'Scale factors added for', proc
                except:
                    pass

    onlyList = opt.only.split(',')
    rawList = opt.rawList.split(',')

    #read plots
    plots = OrderedDict()

    report = ''
    for slist, isSignal, isSyst in [(samplesList, False, False),
                                    (signalSamplesList, True, False),
                                    (systSamplesList, False, True)]:
        if slist is None: continue
        for tag, sample in slist:
            print "tag: %s, sample: %s" % (tag, sample)
            if isSyst and not 't#bar{t}' in sample[3]: continue
            if tag in skipList:
                print("SKIPPED " + tag)
                continue
            skip = False
            for sl in skipList:
                if ROOT.TString(tag).Contains(sl):
                    skip = True
                    break
            if skip:
                print("SKIPPED " + tag)
                continue
            xsec = sample[0]
            isData = sample[1]
            doFlavourSplitting = sample[6]
            subProcs = [(tag, sample[3], sample[4])]
            if doFlavourSplitting:
                subProcs = []
                for flav in [(1, sample[3] + '+l'), (4, sample[3] + '+c'),
                             (5, sample[3] + '+b', sample[4])]:
                    subProcs.append(('%d_%s' % (flav[0], tag), flav[1],
                                     sample[4] + 3 * len(subProcs)))
            for sp in subProcs:
                print '%s/%s.root' % (opt.inDir, sp[0])
                fIn = ROOT.TFile.Open('%s/%s.root' % (opt.inDir, sp[0]))
                if not fIn: continue

                #fix pileup weighting normalization
                puNormSF = 1
                if opt.puNormSF and not isData:
                    puCorrH = fIn.Get(opt.puNormSF)
                    if tag not in rawList:
                        try:
                            nonWgt = puCorrH.GetBinContent(1)
                            wgt = puCorrH.GetBinContent(2)
                            if wgt > 0:
                                puNormSF = nonWgt / wgt
                                if puNormSF > 1.3 or puNormSF < 0.7:
                                    puNormSF = 1
                                    report += '%s wasn\'t be scaled as too large SF was found (probably low stats)\n' % sp[
                                        0]
                                else:
                                    report += '%s was scaled by %3.3f for pileup normalization\n' % (
                                        sp[0], puNormSF)
                        except:
                            print 'Check pu weight control histo', opt.puNormSF, 'for', sp[
                                0]

                for tkey in fIn.GetListOfKeys():
                    keyIsSyst = False
                    try:
                        key = tkey.GetName()

                        #filter plots using a selection list
                        keep = False if len(onlyList) > 0 else True
                        for pname in onlyList:
                            if opt.strictOnly and pname != key: continue
                            if not opt.strictOnly and not pname in key:
                                continue
                            keep = True
                            break
                        if not keep: continue
                        histos = []
                        obj = fIn.Get(key)
                        if obj.InheritsFrom('TH2'):
                            if key[-5:] == '_syst':
                                if sample[3] == 't#bar{t}':
                                    keyIsSyst = True
                                    key = key[:-5]
                                    for ybin in xrange(1, obj.GetNbinsY() + 1):
                                        for xbin in xrange(
                                                0,
                                                obj.GetNbinsX() + 2):
                                            if math.isnan(
                                                    obj.GetBinContent(
                                                        xbin, ybin)):
                                                obj.SetBinContent(
                                                    xbin, ybin, 0)
                                                obj.SetBinError(xbin, ybin, 0)
                                        weighthist = obj.ProjectionX(
                                            '_px' + str(ybin), ybin, ybin)
                                        weighthist.SetTitle(sp[1] +
                                                            ' weight ' +
                                                            str(ybin))
                                        weighthist.Draw()
                                        if (weighthist.Integral() > 0):
                                            histos.append(weighthist)
                                else:
                                    continue
                            else:
                                histos.append(obj)
                                histos[-1].SetTitle(sp[1])
                        else:
                            histos.append(obj)
                            histos[-1].SetTitle(sp[1])

                        for hist in histos:
                            if "vbfmva" in hist.GetName() and isData:
                                tmpBin = hist.GetXaxis().FindBin(0.2)
                                for iBin in range(tmpBin,
                                                  hist.GetXaxis().GetNbins()):
                                    hist.SetBinContent(iBin, 0.0000001)

                            if not isData and not '(data)' in sp[1]:

                                #check if a special scale factor needs to be applied
                                sfVal = 1.0
                                for procToScale in procSF:
                                    if sp[1] == procToScale:
                                        for pcat in procSF[procToScale]:
                                            if pcat not in key: continue
                                            sfVal = procSF[procToScale][pcat][
                                                0]
                                            break

                                #scale by lumi
                                lumi = opt.lumi
                                for lSpec in lumiSpecs:
                                    if not lSpec in key.split('_'): continue
                                    lumi = lumiSpecs[lSpec]
                                    break
                                if not opt.rawYields and not tag in rawList:
                                    hist.Scale(xsec * lumi * puNormSF * sfVal)

                            #rebin if needed
                            if opt.rebin > 1: hist.Rebin(opt.rebin)

                            #create new plot if needed
                            if not key in plots:
                                plots[key] = Plot(key, com=opt.com)
                                plots[key].ratiorange = opt.ratioRange

                            #add process to plot
                            plots[key].add(h=hist,
                                           title=hist.GetTitle(),
                                           color=sp[2],
                                           isData=sample[1],
                                           spImpose=isSignal,
                                           isSyst=(isSyst or keyIsSyst),
                                           doDivideByBinWidth=opt.binWid)

                    except Exception as e:
                        print e
                        pass

    #show plots
    ROOT.gStyle.SetOptTitle(0)
    ROOT.gStyle.SetOptStat(0)
    ROOT.gROOT.SetBatch(True)
    if (not opt.outDir):
        outDir = opt.inDir + '/plots/' + opt.outName.split('.root')[0]
    else:
        outDir = opt.outDir
    os.system('mkdir -p %s' % outDir)
    os.system('rm %s/%s' % (outDir, opt.outName))
    for p in plots:
        plots[p].mcUnc = opt.mcUnc
        if opt.saveLog: plots[p].savelog = True
        skipPlot = False
        if opt.onlyData and plots[p].dataH is None: skipPlot = True
        if opt.silent: skipPlot = True
        lumi = opt.lumi
        for lSpec in lumiSpecs:
            if not lSpec in p.split('_'): continue
            lumi = lumiSpecs[lSpec]
            break

        #continue
        if opt.normToData: plots[p].normToData()
        if not skipPlot:
            plots[p].show(outDir=outDir,
                          lumi=lumi,
                          noStack=opt.noStack,
                          saveTeX=opt.saveTeX)
        plots[p].appendTo('%s/../%s' % (outDir, opt.outName))
        plots[p].reset()

    print '-' * 50
    print 'Plots and summary ROOT file can be found in %s' % outDir
    if len(report): print report
    print '-' * 50
Ejemplo n.º 3
0
def showShapes(resultsDir,name,plotTitle,mass,boson,lumi,plotData=True,showPseudoData=True,showAllBkgs=True,plotpfix=''):

    """ show the shapes corresponding to a given analysis """

    colors=[ROOT.kGreen+1,ROOT.kAzure+3,ROOT.kOrange+2,ROOT.kGray,ROOT.kRed+2]
    
    shapeFiles=[os.path.join(resultsDir,f) for f in os.listdir(resultsDir) if 'shapes_' in f and '.root' in f]

    for f in shapeFiles:

        fIn=ROOT.TFile.Open(f)

        #check consistency of the file with the boson to plot
        if 'shapes_22' in f and boson=='g':
            v='g'
            channel='#gamma'
        elif 'shapes_169' in f and boson=='z': 
            v='zmm'
            channel='Z#rightarrow#mu#mu'
        elif 'shapes_121' in f and boson=='z': 
            v='zee'
            channel='Z#rightarrowee'
        else:
            continue
        

        bkgH       = fIn.Get('bkg_%s'%v)
        fidsigH    = fIn.Get('fidsig_%s_m%d'%(v,mass))
        outfidsigH = fIn.Get('outfidsig_%s_m%d'%(v,mass))
        dataH      = fIn.Get('data_obs_%s'%(v))

        if showPseudoData:
            dataH.Reset('ICE')
            nexp=bkgH.Integral()
            if fidsigH: nexp+=bkgH.Integral()
            if outfidsigH: nexp+=outfidsigH.Integral()
            for iev in range( ROOT.gRandom.Poisson( nexp ) ):
                dataH.Fill( bkgH.GetRandom() )
       
        try:
            p=Plot('%s_%s_inc%s'%(name,v,plotpfix))
            p.xtit='Missing mass [GeV]'
            p.ytit='Events'
            if fidsigH:
                p.add(fidsigH,            title='fiducial #scale[0.8]{(%d)}'%mass, color=ROOT.TColor.GetColor('#fdc086'), isData=False, spImpose=False, isSyst=False)
    
            if showAllBkgs:
                if outfidsigH:
                    p.add(outfidsigH,         title='non-fiducial',  color=ROOT.TColor.GetColor('#a6cee3'), isData=False, spImpose=False, isSyst=False)
                p.add(bkgH,               title='background',    color=ROOT.TColor.GetColor('#1f78b4'), isData=False, spImpose=False, isSyst=False)
            else:
                allBkg=bkgH.Clone('allbkg')
                if outfidsigH : 
                    allBkg.Add(outfidsigH)
                p.add(allBkg,               title='background',    color=ROOT.TColor.GetColor('#1f78b4'), isData=False, spImpose=False, isSyst=False)

            if plotData:
                dtitle='pseudo-data' if showPseudoData else 'Data'
                p.add(dataH, title=dtitle,   color=1, isData=True, spImpose=False, isSyst=False)

            if fidsigH:
                p.add(fidsigH.Clone(),    title=plotTitle+'#scale[0.8]{(%d)}'%mass, color=ROOT.TColor.GetColor('#fdc086'), isData=False, spImpose=True,  isSyst=False)

            if showAllBkgs and outfidsigH:
                p.add(outfidsigH.Clone(), title='non-fiducial',  color=ROOT.TColor.GetColor('#a6cee3'), isData=False, spImpose=True,  isSyst=False)
            
            p.ratiorange=[0.68,1.32]
            p.show('./',lumi*1000,extraText=plotTitle)

            

            #background systs
            p=Plot('%s_%s_inc_bkgunc%s'%(name,v,plotpfix))
            p.noErrorsOnRatio=True
            p.doPoissonErrorBars=False
            p.xtit='Missing mass [GeV]'
            p.ytit='Events'
            p.add(bkgH, title='background', color=1, isData=True,spImpose=False, isSyst=False)
            ic=0
            for syst,title in [('Up',            'e#mu mix'),
                               ('SingleDiffUp',  'single arm mix')]:
                h=fIn.Get('bkg_%s_bkgShape%s'%(v,syst))
                p.add(h, title=title, color=colors[ic], isData=False, spImpose=False, isSyst=False)
                ic+=1
            p.ratiorange=[0.76,1.24]                
            p.show('./',lumi,noStack=True,extraText=plotTitle)

            #signal systs
            if fidsigH:
                p=Plot('%s_%s_sigunc%s'%(name,v,plotpfix))
                #fidsigH.Scale(1./5.)
                p.doPoissonErrorBars=False
                p.noErrorsOnRatio=True
                p.xtit='Missing mass [GeV]'
                p.ytit='Events'
                p.add(fidsigH, title='signal', color=1, isData=True,spImpose=False, isSyst=False)
                ic=0
                for syst,title in [('ShapeUp',   'e#mu mix.'),
                                   ('CalibUp',   'Time dependence'),                     
                                   ('PPSEffUp',  'PPS efficiency'),
                                   ('PzModelUp', 'p_{z}(pp)')]:
                    h=fIn.Get('fidsig_%s_m%d_sig%s'%(v,mass,syst))
                    print ic,syst,title,h
                    p.add(h, title=title, color=colors[ic], isData=False, spImpose=False, isSyst=False)
                    ic+=1
                p.ratiorange=[0.5,1.46]
                p.show('./',lumi,noStack=True,extraText=plotTitle)

            #out fiducial signal systs
            if outfidsigH:
                p=Plot('%s_%s_outfidsigunc%s'%(name,v,plotpfix))
                #outfidsigH.Scale(1./5.)
                p.doPoissonErrorBars=False
                p.noErrorsOnRatio=True
                p.xtit='Missing mass [GeV]'
                p.ytit='Events'
                p.add(outfidsigH, title='out-fid. signal', color=1, isData=True,spImpose=False, isSyst=False)
                ic=0
                for syst,title in [('ShapeUp',   'e#mu mix.'),
                                   ('CalibUp',   'Time dependence'),
                                   ('PPSEffUp',  'PPS efficiency'),
                                   ('PzModelUp', 'p_{z}(pp)')]:
                    h=fIn.Get('outfidsig_%s_m%d_sig%s'%(v,mass,syst))
                    p.add(h, title=title, color=colors[ic], isData=False, spImpose=False, isSyst=False)
                    ic+=1

                p.ratiorange=[0.5,1.46]                    
                p.show('./',lumi,noStack=True,extraText=plotTitle)

        except Exception as e:
            print e
            pass

        fIn.Close()
Ejemplo n.º 4
0
    rwScenariosMassH[key] = (getDist(url,
                                     'genmass'), getDist(url, 'rwgt_genmass'))
    rwScenariosMassH[key][0].SetName('mass%d' % len(rwScenariosH))
    rwScenariosMassH[key][1].SetName('rwmass%d' % len(rwScenariosH))
    rwScenariosMassH[key][0].SetTitle('(172.5,1.32)')
    rwScenariosMassH[key][1].SetTitle('(%3.1f,%3.2f) wgt' % key)
    norig = rwScenariosMassH[key][0].Integral()
    rwScenariosMassH[key][0].Scale(1. / norig)
    rwScenariosMassH[key][1].Scale(1. / norig)

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

p = Plot('mlbwidth_closure', '13 TeV')
p.ratiorange = [0.958, 1.042]
p.savelog = True
p.doPoissonErrorBars = False
p.range = (1e-4, 0.014)
p.ytit = 'PDF'
p.add(h=simScenariosH[(172.5, 0.90)].Clone(),
      title=simScenariosH[(172.5, 0.90)].GetTitle(),
      color=1,
      isData=True,
      spImpose=False,
      isSyst=False,
      doDivideByBinWidth=True)
p.add(h=rwScenariosH[(172.5, 0.90)].Clone(),
      title=rwScenariosH[(172.5, 0.90)].GetTitle(),
      color=2,
      isData=False,
Ejemplo n.º 5
0
def showShapes(resultsDir,
               name,
               title,
               mass,
               boson,
               r95,
               sig,
               lumi,
               plotData=True,
               showPseudoData=True,
               showAllBkgs=True):
    """ show the shapes corresponding to a given analysis """

    shapeFiles = [
        os.path.join(resultsDir, f) for f in os.listdir(resultsDir)
        if 'shapes_' in f and '.root' in f
    ]
    for f in shapeFiles:

        try:
            angle = int(re.search('_a(\d+)', f).group(1))
        except:
            print 'No angle could be parsed, assuming this is an inclusive analysis'
            angle = None

        fIn = ROOT.TFile.Open(f)

        #check consistency of the file with the boson to plot
        if 'shapes_22' in f and boson == 'g':
            v = 'g'
            channel = '#gamma'
        elif 'shapes_169' in f and boson == 'z':
            v = 'zmm'
            channel = 'Z#rightarrow#mu#mu'
        elif 'shapes_121' in f and boson == 'z':
            v = 'zee'
            channel = 'Z#rightarrowee'
        else:
            continue

        for icat in range(2):

            if angle:
                bkgH = fIn.Get('bkg_%s_a%d_%d' % (v, angle, icat))
                fidsigH = fIn.Get('fidsig_%s_a%d_%d_m%d' %
                                  (v, angle, icat, mass))
                outfidsigH = fIn.Get('outfidsig_%s_a%d_%d_m%d' %
                                     (v, angle, icat, mass))
                dataH = fIn.Get('data_obs_%s_a%d_%d' % (v, angle, icat))
            else:
                bkgH = fIn.Get('bkg_%s_%d' % (v, icat))
                fidsigH = fIn.Get('fidsig_%s_%d_m%d' % (v, icat, mass))
                outfidsigH = fIn.Get('outfidsig_%s_%d_m%d' % (v, icat, mass))
                dataH = fIn.Get('data_obs_%s_%d' % (v, icat))

            print bkgH, fidsigH, outfidsigH, dataH

            try:
                fidsigH.Scale(5)
                outfidsigH.Scale(5)
            except:
                fidsigH = None
                outfidsigH = None

            if showPseudoData:
                dataH.Reset('ICE')
                nexp = bkgH.Integral()
                if fidsigH: nexp += bkgH.Integral()
                if outfidsigH: nexp += outfidsigH.Integral()
                for iev in range(ROOT.gRandom.Poisson(nexp)):
                    dataH.Fill(bkgH.GetRandom())
            try:

                #main shapes
                if angle:
                    p = Plot('%s_%s_a%d_cat%d' % (name, v, angle, icat))
                else:
                    p = Plot('%s_%s_inc_cat%d' % (name, v, icat))

                p.xtit = 'Missing mass [GeV]'
                p.ytit = 'Events'
                if fidsigH:
                    p.add(fidsigH,
                          title='#scale[0.5]{5x}' + title +
                          '#scale[0.8]{(%d)}' % mass,
                          color=ROOT.TColor.GetColor('#fdc086'),
                          isData=False,
                          spImpose=False,
                          isSyst=False)

                if showAllBkgs:
                    if outfidsigH:
                        p.add(outfidsigH,
                              title='#scale[0.5]{5x}non-fiducial',
                              color=ROOT.TColor.GetColor('#a6cee3'),
                              isData=False,
                              spImpose=False,
                              isSyst=False)
                    p.add(bkgH,
                          title='background',
                          color=ROOT.TColor.GetColor('#1f78b4'),
                          isData=False,
                          spImpose=False,
                          isSyst=False)
                else:
                    allBkg = bkgH.Clone('allbkg')
                    if outfidsigH:
                        allBkg.Add(outfidsigH)
                    p.add(allBkg,
                          title='background',
                          color=ROOT.TColor.GetColor('#1f78b4'),
                          isData=False,
                          spImpose=False,
                          isSyst=False)

                if plotData:
                    dtitle = 'pseudo-data' if showPseudoData else 'Data'
                    p.add(dataH,
                          title=dtitle,
                          color=1,
                          isData=True,
                          spImpose=False,
                          isSyst=False)
                if fidsigH:
                    p.add(fidsigH.Clone(),
                          title=title + '#scale[0.8]{(%d)}' % mass,
                          color=ROOT.TColor.GetColor('#fdc086'),
                          isData=False,
                          spImpose=True,
                          isSyst=False)

                if showAllBkgs and outfidsigH:
                    p.add(outfidsigH.Clone(),
                          title='non-fiducial',
                          color=ROOT.TColor.GetColor('#a6cee3'),
                          isData=False,
                          spImpose=True,
                          isSyst=False)
                p.ratiorange = [0.68, 1.32]

                subcatName = 'low pileup' if icat == 0 else 'high pileup'
                if angle:
                    extraText = '%s, %d#murad\\%s' % (channel, angle,
                                                      subcatName)
                else:
                    extraText = '%s, inclusive\\%s' % (channel, subcatName)
                if r95: extraText += '\\#mu_{95}(exp.)<%3.3f' % r95
                if sig: extraText += '\\S(exp.)=%3.3f' % sig
                p.show('./', lumi * 1000, extraText=extraText)

                colors = [ROOT.kGreen + 1, ROOT.kAzure + 3, ROOT.kRed + 2]

                #background systs
                if angle:
                    p = Plot('%s_%s_a%d_cat%d_bkgunc' % (name, v, angle, icat))
                else:
                    p = Plot('%s_%s_inc_cat%d_bkgunc' % (name, v, icat))
                p.noErrorsOnRatio = True
                p.doPoissonErrorBars = False
                p.xtit = 'Missing mass [GeV]'
                p.ytit = 'Events'
                p.add(bkgH,
                      title='background',
                      color=1,
                      isData=True,
                      spImpose=False,
                      isSyst=False)
                ic = 0
                for syst, title in [('Up', 'Pileup spec.'),
                                    ('SingleDiffUp', 'Single diff.')]:
                    if angle:
                        p.add(fIn.Get('bkg_%s_a%d_%d_bkgShape%s' %
                                      (v, angle, icat, syst)),
                              title=title,
                              color=colors[ic],
                              isData=False,
                              spImpose=False,
                              isSyst=False)
                    else:
                        p.add(fIn.Get('bkg_%s_inc_%d_bkgShape%s' %
                                      (v, icat, syst)),
                              title=title,
                              color=colors[ic],
                              isData=False,
                              spImpose=False,
                              isSyst=False)
                    ic += 1
                p.ratiorange = [0.76, 1.24]
                if angle:
                    extraText = '%s, %d#murad' % (channel, angle)
                else:
                    extraText = '%s, inclusive' % (channel)
                p.show('./', lumi, noStack=True, extraText=extraText)

                #signal systs
                if fidsigH:
                    if angle:
                        p = Plot('%s_%s_a%d_cat%d_sigunc' %
                                 (name, v, angle, icat))
                    else:
                        p = Plot('%s_%s_inc_cat%d_sigunc' % (name, v, icat))
                    fidsigH.Scale(1. / 5.)
                    p.doPoissonErrorBars = False
                    p.noErrorsOnRatio = True
                    p.xtit = 'Missing mass [GeV]'
                    p.ytit = 'Events'
                    p.add(fidsigH,
                          title='signal',
                          color=1,
                          isData=True,
                          spImpose=False,
                          isSyst=False)
                    ic = 0
                    for syst, title in [('ShapeUp', 'Pileup spec.'),
                                        ('CalibUp', 'Time dependence'),
                                        ('PzModelUp', 'p_{z}(pp)')]:
                        if angle:
                            p.add(fIn.Get('fidsig_%s_a%d_%d_m%d_sig%s' %
                                          (v, angle, icat, mass, syst)),
                                  title=title,
                                  color=colors[ic],
                                  isData=False,
                                  spImpose=False,
                                  isSyst=False)
                        else:
                            p.add(fIn.Get('fidsig_%s_%d_m%d_sig%s' %
                                          (v, icat, mass, syst)),
                                  title=title,
                                  color=colors[ic],
                                  isData=False,
                                  spImpose=False,
                                  isSyst=False)
                        ic += 1
                    p.ratiorange = [0.76, 1.24]
                    if angle:
                        extraText = '%s, %d#murad\\m_{X}=%d GeV' % (
                            channel, angle, mass)
                    else:
                        extraText = '%s, inclusive\\m_{X}=%d GeV' % (channel,
                                                                     mass)
                    p.show('./', lumi, noStack=True, extraText=extraText)

                #out fiducial signal systs
                if outfidsigH:
                    if angle:
                        p = Plot('%s_%s_a%d_cat%d_outfidsigunc' %
                                 (name, v, angle, icat))
                    else:
                        p = Plot('%s_%s_inc_cat%d_outfidsigunc' %
                                 (name, v, icat))
                    outfidsigH.Scale(1. / 5.)
                    p.doPoissonErrorBars = False
                    p.noErrorsOnRatio = True
                    p.xtit = 'Missing mass [GeV]'
                    p.ytit = 'Events'
                    p.add(outfidsigH,
                          title='out-fid. signal',
                          color=1,
                          isData=True,
                          spImpose=False,
                          isSyst=False)
                    ic = 0
                    for syst, title in [('ShapeUp', 'Pileup spec.'),
                                        ('CalibUp', 'Time dependence'),
                                        ('PzModelUp', 'p_{z}(pp)')]:
                        if angle:
                            p.add(fIn.Get('outfidsig_%s_a%d_%d_m%d_sig%s' %
                                          (v, angle, icat, mass, syst)),
                                  title=title,
                                  color=colors[ic],
                                  isData=False,
                                  spImpose=False,
                                  isSyst=False)
                        else:
                            p.add(fIn.Get('outfidsig_%s_%d_m%d_sig%s' %
                                          (v, icat, mass, syst)),
                                  title=title,
                                  color=colors[ic],
                                  isData=False,
                                  spImpose=False,
                                  isSyst=False)
                        ic += 1

                    p.ratiorange = [0.76, 1.24]
                    if angle:
                        extraText = '%s, %d#murad\\m_{X}=%d GeV' % (
                            channel, angle, mass)
                    else:
                        extraText = '%s, inclusive\\m_{X}=%d GeV' % (channel,
                                                                     mass)
                    p.show('./', lumi, noStack=True, extraText=extraText)

            except Exception as e:
                print e
                pass

        fIn.Close()
Ejemplo n.º 6
0
def main(args):

    parser = argparse.ArgumentParser(description='usage: %prog [options]')
    parser.add_argument(
        '-i',
        '--input',
        dest='input',
        default=
        '/eos/cms/store/cmst3/user/psilva/ExclusiveAna/final/ab05162/analysis_0p04/',
        help='input directory with the files [default: %default]')
    parser.add_argument(
        '--sig',
        dest='sig',
        default=
        '{boson}_m_X_{mass}_xangle_{xangle}_2017_preTS2_opt_v1_simu_reco.root',
        help='signal point [%default]')
    parser.add_argument('--massList',
                        dest='massList',
                        default='800,1000,1200',
                        help='signal mass list (CSV) [%default]')
    parser.add_argument(
        '--selCuts',
        dest='selCuts',
        default='bosonpt>40 && l1pt>30 && l2pt>20',
        help='preselection for Z categories [default: %default]')
    parser.add_argument('--doPerAngle',
                        dest='doPerAngle',
                        default=False,
                        help='do per crossing angle [default: %default]',
                        action='store_true')
    parser.add_argument('--lumi',
                        dest='lumi',
                        default=37500.,
                        type=float,
                        help='integrated luminosity [default: %default]')
    parser.add_argument('-o',
                        '--output',
                        dest='output',
                        default='analysis/bkg',
                        help='Output directory [default: %default]')
    opt = parser.parse_args(args)

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

    os.system('mkdir -p %s' % opt.output)

    selCuts = [(opt.selCuts, '', 'e#mu')]
    if opt.doPerAngle:
        for xangle in VALIDLHCXANGLES:
            selCuts.append((opt.selCuts + ' && xangle==%d' % xangle,
                            '_%d' % xangle, 'e#mu, %d #murad' % xangle))
    for cuts, pfix, catTitle in selCuts:

        os.system('rm %s/plotter_%s.root' % (opt.output, pfix))

        data = fillShapes(inputDir=opt.input, selCuts=cuts, proc='MuonEG')

        #sigs={}
        #for m in opt.massList.split():
        #    if not m in sigs: sigs[m]={}
        #    for xangle in VALIDLHCXANGLES:
        #        newSigs=fillShapes(inputDir=opt.input,selCuts=opt.selCuts,tag=opt.sig.format(mass=m,xangle=xangle))
        #        for dist in newSigs:
        #            if not dist in sigs[m]:
        #                sigs[m]=newSigs[dist]['data'].Clone('{0}_{1}'.format(dist,m))
        #            #FIXME scale me according to xsec
        #FIXME plot me

        for dist in data:

            pname = dist + pfix
            for c in [':', ',', '>', '=', '(', ')', '-', '<', '?']:
                pname = pname.replace(c, '')

            p = Plot(pname)
            p.doChi2 = True
            p.nominalDistForSystsName = 'background'

            #if dist=='mmiss':
            #    newBins=range(0,1000,40)+[1000,1100,1200,1500,2000]
            #    print 'Rebinning',dist,'to',newBins
            #    for k in data[dist]:
            #        data[dist][k]=rebinUnequalBinSize(data[dist][k],newBins)

            #main distributions
            #doDivideByBinWidth=True if dist=='mmiss' or dist=='(bosony>=0?mmiss:-mmiss)' else False
            #if doDivideByBinWidth:
            #    p.doPoissonErrorBars=False

            p.add(data[dist]['data'],
                  title='data',
                  color=ROOT.kBlack,
                  isData=True,
                  spImpose=False,
                  isSyst=False)  #,doDivideByBinWidth=doDivideByBinWidth)
            p.add(data[dist]['bkg'],
                  title='background',
                  color=ROOT.TColor.GetColor('#1f78b4'),
                  isData=False,
                  spImpose=False,
                  isSyst=False)  #,doDivideByBinWidth=doDivideByBinWidth)

            #background systematics
            for syst in [
                    '{0}_bkgshape_MuonEG_obsUp', '{0}_bkgshape_MuonEG_obsDown',
                    '{0}_bkgsinglediff_MuonEG_obsDown',
                    '{0}_bkgsinglediff_MuonEG_obsUp'
            ]:
                p.add(data[dist][syst.format(dist)],
                      title=syst,
                      color=ROOT.TColor.GetColor('#1f78b4'),
                      isData=False,
                      spImpose=False,
                      isSyst=True)
                #doDivideByBinWidth=doDivideByBinWidth)

            #p.ratiorange=[0.78,1.22]
            #p.ratiorange=[0.58,1.42]
            p.ratiorange = [0., 2.]
            p.show(opt.output, opt.lumi, extraText=catTitle)
            p.appendTo('%s/plotter_%s.root' % (opt.output, pfix))
            p.reset()
Ejemplo n.º 7
0
d.Draw(
    "mmiss >> hdy(50,0,3000)",
    "wgt*(mixType==1 && cat==169 && mmiss>0 && xangle==%d && bosonpt>40)" %
    xangle, "goff")
hdy = ROOT.gDirectory.Get('hdy').Clone()
hdy.SetDirectory(0)
hdy.Scale(5765.4 * lumi)
inF.Close()

#construct different scenarios
for f in [0.01, 0.1, 0.2, 0.5]:

    p = Plot('mix%d_mmiss_dysig_a%d_f%d' % (mass, xangle, f * 100),
             com='13 TeV')
    p.doPoissonErrorBars = False
    p.ratiorange = (0.6, 1.37)
    p.spimposeWithErrors = True
    p.frameMax = 1.3
    p.ratiotitle = '#frac{DY+mix.signal}{DY}'
    fhsig = hsig.Clone('sig')
    fhsig.Scale(hdy.Integral() / hsig.Integral())
    fhsig.Scale(f)

    fhsigmix = hsigmix.Clone('sigmix')
    fhsigmix.Scale(hdy.Integral() / hsigmix.Integral())
    fhsigmix.Scale(f * dilFactorSig)

    totalH = hdy.Clone('totalobs')
    totalH.Scale(1 - f)
    totalH.Add(fhsig)
    p.add(h=totalH,
    title = d.replace('mix', '')
    title = title.replace('None', 'data')
    histos.append(h.Clone('h' + title))
    histos[-1].SetTitle(title)
    histos[-1].SetDirectory(0)
    h.Reset('ICE')

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

COLOURS = [1, ROOT.kAzure + 1, ROOT.kGreen + 3, ROOT.kRed + 1]

p = Plot('mix_mmiss_siginj' + mass, com='13 TeV, 2017B')
p.doPoissonErrorBars = False
p.ratiorange = (0.58, 1.24)
p.spimposeWithErrors = True
for ic in [0, 1]:
    title = histos[ic].GetTitle()
    histos[ic].GetXaxis().SetTitle('Missing mass [GeV]')
    histos[ic].GetYaxis().SetTitle('Events')

    if ic == 0:
        p.add(h=histos[ic],
              title=title,
              color=COLOURS[ic],
              isData=True,
              spImpose=False,
              isSyst=False)
    else:
        for frac in [0.001, 0.01, 0.1]:
def main(args):

    parser = argparse.ArgumentParser(description='usage: %prog [options]')
    parser.add_argument(
        '-i',
        '--input',
        dest='input',
        default=
        '/eos/cms/store/cmst3/user/psilva/ExclusiveAna/final/ab05162/analysis_0p04/',
        help='input directory with the files [default: %default]')
    parser.add_argument(
        '--selCuts',
        dest='selCuts',
        default='bosonpt>40 && l1pt>30 && l2pt>20',
        help='preselection for Z categories [default: %default]')
    parser.add_argument('--doPerNch',
                        dest='doPerNch',
                        default=False,
                        action='store_true',
                        help='break-down per Nch [default: %default]')
    parser.add_argument('--doPerEra',
                        dest='doPerEra',
                        default=False,
                        action='store_true',
                        help='break-down per era [default: %default]')
    parser.add_argument(
        '--doPerPU',
        dest='doPerPU',
        default=False,
        action='store_true',
        help='break-down per pileup category [default: %default]')
    parser.add_argument('--doPerAngle',
                        dest='doPerAngle',
                        default=False,
                        action='store_true',
                        help='break-down per angle [default: %default]')
    parser.add_argument('--lumi',
                        dest='lumi',
                        default=37500.,
                        type=float,
                        help='integrated luminosity [default: %default]')
    parser.add_argument('-o',
                        '--output',
                        dest='output',
                        default='analysis/bkg',
                        help='Output directory [default: %default]')
    opt = parser.parse_args(args)

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

    os.system('mkdir -p %s' % opt.output)

    #do all possible combinations of these categories
    baseCats = ['protonCat==%d' % (i + 1) for i in range(4)]
    subCats = ['']
    if opt.doPerEra: subCats += ['era==%d' % int(ord(x)) for x in 'BCDEF']
    if opt.doPerPU: subCats += ['nvtx<20', 'nvtx>=20']
    if opt.doPerAngle:
        subCats += ['xangle==%d' % i for i in [120, 130, 140, 150]]
    if opt.doPerNch: subCats += ['nch<15', 'nch>=15']
    catList = list(itertools.product(baseCats, subCats))

    outF = '%s/plotter_embkg.root' % opt.output
    os.system('rm %s' % outF)

    print '[doBackgroundValidation] with %d variations to test' % len(catList)
    print '\t output will be available in', outF
    for i, cat in enumerate(catList):

        selCut = ''
        for c in cat:
            if len(c) == 0: continue
            selCut += '%s&&' % c
        selCut += opt.selCuts
        titleCut = parseTitleFromCut(selCut)
        print '\t', i, selCut

        data = fillShapes(inputDir=opt.input, selCuts=selCut, proc='MuonEG')

        for dist in data:

            pname = '%s_%d' % (dist, i)
            for c in [':', ',', '>', '=', '(', ')', '-', '<', '?']:
                pname = pname.replace(c, '')
            p = Plot(pname)
            p.doChi2 = False  #True
            p.nominalDistForSystsName = 'background'

            #if dist=='mmiss':
            #    newBins=range(0,1000,40)+[1000,1100,1200,1500,2000]
            #    print 'Rebinning',dist,'to',newBins
            #    for k in data[dist]:
            #        data[dist][k]=rebinUnequalBinSize(data[dist][k],newBins)

            p.add(data[dist]['data'],
                  title='data',
                  color=ROOT.kBlack,
                  isData=True,
                  spImpose=False,
                  isSyst=False)
            p.add(data[dist]['bkg'],
                  title='background',
                  color=ROOT.kCyan - 6,
                  isData=False,
                  spImpose=False,
                  isSyst=False)

            #background systematics
            ci = 1
            for syst in [
                    '{0}_bkgshape_MuonEG_obsUp',
                    '{0}_bkgshape_MuonEG_obsDown',
                    '{0}_bkgsinglediffUp_MuonEG_obs',
                    '{0}_bkgsinglediffDown_MuonEG_obs',
            ]:
                ci = ci + 1
                p.add(
                    data[dist][syst.format(dist)],
                    title=syst,
                    color=ROOT.kCyan - 6,  #ci
                    isData=False,
                    spImpose=False,  #True,
                    isSyst=True)  #False)

            #p.ratiorange=[0.78,1.22]
            p.ratiorange = [0.58, 1.43]
            p.show(opt.output, opt.lumi, extraText='\\'.join(titleCut))
            p.appendTo(outF)
            p.reset()