def main():

    usage = 'usage: %prog [options]'
    parser = optparse.OptionParser(usage)
    parser.add_option('-i', '--inputfile', dest='inputfile' , help='Name of the input fileectory containing the histograms.' , default=None)
    parser.add_option('-b', '--batch'    , dest='batch'     , help='Use this flag to run root in batch mode.'                , action='store_true', default=False)
    parser.add_option('-v', '--verbose'  , dest='verbose'   , help='Verbose level. [default = %default]'                     , action='store', type='int', default=0)

    (opt, args) = parser.parse_args()

    if opt.inputfile is None:
        parser.error('No input file defined!')

    inputfile = opt.inputfile
    batch = opt.batch

    if batch:
        ## run ROOT in batch mode
        sys.argv.append( '-b' )
        ROOT.gROOT.SetBatch()

    sfs = {}
    i_file = mRF.openTFile(inputfile)

    channels = ['e','mu']
    print 'channels: ',channels
    levels = set([k.split('_',1)[-1] for k in mRF.GetKeyNames(i_file,'data') if 'charge' in k and not 'chargeCheck' in k and not len(k.split('_')) == 2])
    print 'levels: ',levels
    if opt.verbose==0:
        print '-----------------------------------------------------------------------------------------------------------------'
        print '                 :     W_sf    | diff data | diff MC   | diff wjets| A data (%)  | A wjets (%) | %Wjets | data/MC'
        print '-----------------------------------------------------------------------------------------------------------------'

    for chan in channels:
        for level in levels:
            sf = getNormalization(i_file,chan,chan+'_'+level, verbose=opt.verbose)
            sfs[chan+'_'+level.replace('_charge','')] = sf
        if opt.verbose==0: print '-----------------------------------------------------------------------------------------------------------------'

    # pprint(sfs)

    ## write weights to a root file
    sf_hist = TH1F('wjetssf','wjetssf',len(sfs),0,len(sfs))
    i=0
    for l in sfs:
        i+=1
        sf_hist.GetXaxis().SetBinLabel(i,l)
        sf_hist.SetBinContent(i,sfs[l][0])
        sf_hist.SetBinError(i,sfs[l][1])
    sf_out = mRF.openTFile('data/weights/top_wjetssf.root','RECREATE')
    sf_hist.Write()
    sf_out.Close()
def main():
    usage = 'usage: %prog [options]'
    parser = optparse.OptionParser(usage)
    parser.add_option('-i', '--inputfile',    dest='inputfile'   , help='Name of the input file containing the histograms.'             , default=None)
    parser.add_option('-b', '--batch',        dest='batch'       , help='Use this flag to run root in batch mode.', action='store_true' , default=False)
    parser.add_option('-q', '--qcdtemplates', dest='qcdtemplates', help='Name of the input file containing the QCD templates.'          , default=None)
    parser.add_option('-o', '--outputdir',    dest='outputdir'   , help='Name of the local output directory.'                           , default='QCDNormalization')
    (opt, args) = parser.parse_args()

    ## Handle input parameters:
    if opt.inputfile is None:
        parser.error('No input file defined!')
    inputfile = opt.inputfile

    if opt.batch:
        sys.argv.append( '-b' )
        ROOT.gROOT.SetBatch()

    i_file = mRF.openTFile(inputfile)

    channels = ['e','mu']
    print 'channels: ',channels
    # levels = set([k.split('_')[-1].replace('charge','met')   for k in mRF.GetKeyNames(i_file,'data') if 'charge' in k])
    levels = set([k.split('_',1)[-1].replace('charge','met') for k in mRF.GetKeyNames(i_file,'data') if 'charge' in k and not 'chargeCheck' in k and not len(k.split('_')) == 2])

    print 'levels: ',levels

    sfs = {}
    for chan in channels:
        # levels = [k.split('_')[1] for k in mRF.GetKeyNames(i_file,chan) if ('met' in k and not 'flow' in k)]
            for level in list(set(levels)):
                sf = getNormalization(i_file,chan,level,outputdir=opt.outputdir)
                sfs[chan+'_'+level] = sf



    pprint(sfs)
    ## write weights to a root file
    sf_hist = TH1F('qcdsf','qcdsf',len(sfs),0,len(sfs))
    i=0
    for l in sfs:
        i+=1
        sf_hist.GetXaxis().SetBinLabel(i,l)
        sf_hist.SetBinContent(i,sfs[l][0])
        sf_hist.SetBinError(i,sfs[l][1])
    sf_out = mRF.openTFile('data/weights/top_qcdsf.root','RECREATE')
    sf_hist.Write()
    sf_out.Close()
Beispiel #3
0
def getSummedShapes(path, tag, chan=''):

    ## FIXME get the following numbers from the file
    lxy_max = 5.
    lxy_bins = 50

    if chan != '':
        chan = '_' + chan

    ## prepare a summed histogram
    summed_cat = []
    ## open the corresponfing file
    tfile = mRF.openTFile(path)
    # nevents = mRF.getHist(tfile,'map_counter').Integral(0,2)

    nevents = 0.
    for i in xrange(ybin - 1):
        map_cat = mRF.getHist(tfile, 'map' + chan + '_cat' + str(i))
        # n = map_cat.Integral(0,map_cat.GetNbinsX()+1)
        n = map_cat.Integral()
        nevents += n

    checksum = 0.
    checkweight = 0.
    ## loop over categories
    for i in xrange(ybin - 1):
        summed = TH1F(tag + '_summed_lxy' + chan + '_cat' + str(i),
                      tag + '_summed_lxy' + chan + '_cat' + str(i), lxy_bins,
                      0., lxy_max).Clone()
        summed.Sumw2()
        ## get the map histo
        map_cat = mRF.getHist(tfile, 'map' + chan + '_cat' + str(i))
        map_cat.Sumw2()
        checksum += map_cat.GetEntries()
        ## get the gamma binning per category
        nbins = map_cat.GetNbinsX()

        for j in xrange(nbins):
            w = float(map_cat.GetBinContent(j + 1))
            checkweight += w
            if tag == 'templ':
                hist = mRF.getHist(tfile,
                                   tag + '_lxy_cat' + str(i) + '_bin' + str(j))
            else:
                hist = mRF.getHist(
                    tfile,
                    tag + '_lxy' + chan + '_cat' + str(i) + '_bin' + str(j))

            hist.Sumw2()
            ## scale the histogram
            integr = float(hist.Integral(0, hist.GetNbinsX() + 1))
            if integr > 0 and tag == 'templ':
                hist.Scale(w / integr)
            ## sum the histograms
            summed.Add(hist.Clone())
        summed_cat.append(summed)
    print 'checksum (map): ', checksum
    print 'checksum: ', sum([h.GetEntries() for h in summed_cat])
    print 'checkweight: ', checkweight
    return summed_cat
Beispiel #4
0
def getSummedShapes(path, tag, chan=''):

    ## FIXME get the following numbers from the file
    lxy_max = 5.
    lxy_bins = 50

    if chan != '':
        chan = '_'+chan


    ## prepare a summed histogram
    summed_cat = []
    ## open the corresponfing file
    tfile = mRF.openTFile(path)
    # nevents = mRF.getHist(tfile,'map_counter').Integral(0,2)

    nevents = 0.
    for i in xrange(ybin-1):
        map_cat = mRF.getHist(tfile,'map'+chan+'_cat'+str(i))
        # n = map_cat.Integral(0,map_cat.GetNbinsX()+1)
        n = map_cat.Integral()
        nevents+=n

    checksum = 0.
    checkweight = 0.
    ## loop over categories
    for i in xrange(ybin-1):
        summed = TH1F(tag+'_summed_lxy'+chan+'_cat'+str(i),tag+'_summed_lxy'+chan+'_cat'+str(i),lxy_bins, 0., lxy_max).Clone()
        summed.Sumw2()
        ## get the map histo
        map_cat = mRF.getHist(tfile,'map'+chan+'_cat'+str(i))
        map_cat.Sumw2()
        checksum+=map_cat.GetEntries()
        ## get the gamma binning per category
        nbins = map_cat.GetNbinsX()

        for j in xrange(nbins):
            w = float(map_cat.GetBinContent(j+1))
            checkweight+=w
            if tag=='templ':
                hist = mRF.getHist(tfile,tag+'_lxy_cat'+str(i)+'_bin'+str(j))
            else:
                hist = mRF.getHist(tfile,tag+'_lxy'+chan+'_cat'+str(i)+'_bin'+str(j))

            hist.Sumw2()
            ## scale the histogram
            integr = float(hist.Integral(0, hist.GetNbinsX()+1))
            if integr > 0 and tag=='templ':
                hist.Scale(w/integr)
            ## sum the histograms
            summed.Add(hist.Clone())
        summed_cat.append(summed)
    print 'checksum (map): ',checksum
    print 'checksum: ',sum([h.GetEntries() for h in summed_cat])
    print 'checkweight: ',checkweight
    return summed_cat
def main():

    usage = 'usage: %prog [options]'
    parser = optparse.OptionParser(usage)
    parser.add_option('-i', '--inputfile' , dest='inputfile'  , help='Name of the input file containing the histograms.' , default=None)
    parser.add_option('-o', '--outputfile', dest='outputfile' , help='Name of the output file containing the histograms.', default='lxyhist.root')
    parser.add_option('-b', '--batch'     , dest='batch'      , help='Use this flag to run root in batch mode.'          , default=False, action='store_true')

    (opt, args) = parser.parse_args()

    if opt.inputfile is None:
        parser.error('No input file defined!')
    inputfile = opt.inputfile
    outputfile = opt.outputfile
    batch = opt.batch

    if batch:
        sys.argv.append( '-b' )
        ROOT.gROOT.SetBatch()

    i_file = mRF.openTFile(inputfile)

    channels = ['e','mu']
    procs =  [k for k in mRF.GetKeyNames(i_file,'')]

    hists = {}
    for proc in procs:
        keys = [k for k in mRF.GetKeyNames(i_file,proc)]

        for key in keys:
            ## Select jetlxy or secvtxmass histograms for e and mu channels:
            try: chan, var = key.split('_', 1)
            except ValueError: continue
            if not (chan == 'e'      or chan == 'mu'):         continue
            if not (var  == 'jetlxy' or var  == 'secvtxmass'): continue

            hist = mRF.getHist(i_file, proc + '/' + key)

            if var == 'jetlxy':
                var = var.replace('jet','max')
            if var == 'secvtxmass':
                var = var.replace('secvtx','jet')

            ## Extract generated top mass
            if not 'ttbar' in proc_dict[proc]:
                mass = '0'
            else:
                try:
                    mass = proc.split('}')[-1].replace('.','')
                except IndexError:
                    mass = '1725'
            if mass == '' or 'syst' in mass:
                mass = '1725'

            name = chan+'_'+var+'_'+proc_dict[proc]+'_'+mass
            # print name
            hists[name] = hist.Clone() ## FIXME (name.replace(' ',''))

    o_file = ROOT.TFile.Open(outputfile,'recreate')
    for chan in channels:
        o_file.mkdir(chan)

    for h in hists:
        channel = h.split('_')[0]
        if channel == 'e':    o_file.cd(channel)
        elif channel == 'mu': o_file.cd(channel)
        else: continue
        hists[h].Write()
    o_file.Close()